Untitled

 avatar
unknown
javascript
a year ago
5.5 kB
2
Indexable
/** @format */

import React, { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector, useStore } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
import { Cell } from 'styled-css-grid';

import Screen from '../../components/layout/Screen';
import Button from '../../components/UI/Button';
import { clearScannedCard } from '../../store/scannedCard';
import { disableLoudSpeaker } from '../../store/loudSpeaker';
import { selectCart } from '../../store/cart';
import { selectHighContrast, toggleHighContrast } from '../../store/highContrast';
import { selectStateManager } from '../../store/stateManager';
import { clearSwipeStripData } from '../../store/swipe';
import { selectTransaction } from '../../store/transactionManager';
import { resetTicketCardVariables } from '../../store/ticketCard';
import {
  distributionService,
  accountingService,
  stateManagerService,
  loggerService as log,
} from '../../services';
import { getCurrency, getStationCloseData, responseError, setDefaultLanguage } from '../../helpers';
import IncompleteView from './views/IncompleteView';
import CompleteView from './views/CompleteView';

const DEFAULT_INACTIVITY_TRANSACTION_COMPLETE_SCREEN = 5000;

const TransactionCompleteScreen = () => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const timerRef = useRef();
  const navigate = useNavigate();
  const location = useLocation();
  const store = useStore();
  const isStationOpen = getStationCloseData() === null;
  const highContrast = useSelector(selectHighContrast);
  const cart = useSelector(selectCart);
  const stateManager = useSelector(selectStateManager);
  const transaction = useSelector(selectTransaction);
  const currentSequenceId = transaction?.sequenceId;
  const isIncomplete = location.state?.isIncomplete;

  const [isProgress, setIsProgress] = useState(true);

  const startOverHandler = async (nextScreen = '/') => {
    setDefaultLanguage();

    dispatch(clearScannedCard());
    dispatch(disableLoudSpeaker());
    dispatch(clearSwipeStripData());
    dispatch(resetTicketCardVariables());

    if (highContrast) {
      dispatch(toggleHighContrast());
    }

    if (isStationOpen) {
      if (nextScreen !== '/idle') return navigate(nextScreen);

      try {
        await stateManagerService.startIdle();
      } catch (err) {
        log.error(`[TransactionCompleteScreen] Error in startOverHandler function ${err}`);
        responseError(err, navigate);
      }
    } else {
      navigate('/station-closed');
    }
  };

  useEffect(() => {
    const fireCompleteEvents = async () => {
      try {
        const { applicationManager, distributionManager, stateManager } = store.getState();
        const params = {
          AccountingData: {
            transactionId: currentSequenceId,
            encashedAmount: applicationManager.encashAmount,
            iouTicketAmount: applicationManager.iouTicketAmount,
            changeToGiveAmount: applicationManager.changeToGive,
            changeGivenAmount: applicationManager.changeGiven,
            expectedProductQuantity: distributionManager.expectedProductQuantity,
            distributedProductQuantity: distributionManager.distributedProductQuantity,
            incident: applicationManager.incident,
            Variables: [],
            currency: getCurrency().code,
            distributedPrice: cart.amount,
          },
        };
        await distributionService.printPrejudiceTicket();
        await accountingService.transactionEnd(params);
        if (stateManager.transaction && stateManager.control) {
          await stateManagerService.stopTransaction();
        }
      } catch (err) {
        log.error(`[TransactionCompleteScreen] fireCompleteEvents error: ${err}`);
      }
    };
    fireCompleteEvents();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!stateManager.transaction) {
      setIsProgress(false);
      distributionService.updateStocks();

      timerRef.current = setTimeout(() => {
        startOverHandler('/idle');
      }, DEFAULT_INACTIVITY_TRANSACTION_COMPLETE_SCREEN);
    }
    return () => {
      timerRef.current && clearTimeout(timerRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stateManager.transaction]);

  const cellSettings = { startOver: { top: null, left: 3 } };

  return (
    <Screen
      showSettingsButton={false}
      name='transactionComplete'
      showCartButton={false}
      disableSessionTimeout={true}
    >
      {isIncomplete ? <IncompleteView /> : <CompleteView />}
      <Screen.Keyboard
        rows='70px'
        showBackButton={false}
        showCancelButton={false}
        showHelpButton={false}
      >
        <Cell top={cellSettings.startOver.top} left={cellSettings.startOver.left}>
          {isStationOpen &&
            !isProgress &&
            !stateManager.maintenanceAuthRequested &&
            !stateManager.isNeedToRebootDevice && (
              <Button name='third' onClick={startOverHandler}>
                {t('BUTTON_START_OVER')}
              </Button>
            )}
        </Cell>
      </Screen.Keyboard>
    </Screen>
  );
};

export default TransactionCompleteScreen;
Leave a Comment