Source

honeywellScanner/BarcodeList.tsx

import React from 'react';
import {
  IonContent,
  IonCol,
  IonRow,
  IonButton,
  IonItem,
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar, IonToast, IonModal, IonInfiniteScrollContent, IonImg, IonLabel, IonTabButton, IonInfiniteScroll, IonIcon, IonText, IonRouterLink, IonFooter
} from '@ionic/react';
import { scan, logOut, chevronBackOutline } from "ionicons/icons";
import { connect } from "react-redux";
import { sendBarcodeListAction } from '../../redux/actions/BarcodeAction';
import { networkHelperAction } from "../../redux/actions/NetworkHelperAction";
import { Plugins, NetworkStatus } from '@capacitor/core';
import { getAllData, deleteDataFromDbById, updateDataAfterDeletion, updateScannedData,updateDataByCursor} from '../../services/indexedDb';
import './HoneywellScanner.css';
interface IProps {
  history: any
  sendBarcodeListAction: Function,
  networkHelperAction: Function,
  response: any,
  isBarcodeSuccess: boolean,
  isBarcodeErrorData: boolean,
  errorMessage: string,
  isLoadingData: boolean,
  internetConnection: boolean,
}

interface IState {
  barcodeList: any,
}
const { Network } = Plugins;

/**
 * 
 * After successfully scanning an item on the barcode scanner page and manual entry,
 * the item(s) will appear on the this page with delete option.
 * This module submit list of barcode and min to API.
 * This module support offline scanning too.
 @category Category
 */
class BarcodeList extends React.Component<IProps, IState>{

  constructor(props: IProps) {
    super(props);
  
    
    this.state = {
      barcodeList: [],
    }


    Network.addListener('networkStatusChange', (status: NetworkStatus) => {
      this.props.networkHelperAction(status.connected);
     
      if (status.connected == true) {
        this.submitBarcodes()
      }
    });
  }


  backToScan = () => {
    this.props.history.push({
      pathname: '/dashboard/scanner'
    })
  }

/**
 * This function check value stored is min or barcode from indexeddb.
 *  if its barcode and has validFlag=true then it sends data with returnId as {barcode:12344535,returnId:6576} and 
 *  That barcode's validFlag is false then send data as {barcode:5645646454}
 *  Same applies in case of minId too.
 *  JSON object looks like [{min:909845, returnId:6768},{barcode:464757757578,returnId:6767},{min:909844},{barcode:464757757577}]  and then call post API.
 *  It also checks App has internet connection or not, If internet connection is not there then It sends API call when internet is back
*/
  submitBarcodes = () => {

    if (this.props.internetConnection) {
     console.log("entered---")
      var jsonArr = [];

      for (var i = 0; i < this.state.barcodeList.length; i++) {
        if (this.state.barcodeList[i].minOrBarcode == 'barcode') {
          if (this.state.barcodeList[i].returnId == '') {
            jsonArr.push({
              barcode: this.state.barcodeList[i].barcode,
            });
          }
          else {
            jsonArr.push({
              barcode: this.state.barcodeList[i].barcode,
              returnId: this.state.barcodeList[i].returnId
            });
          }
        }
        else {
          if (this.state.barcodeList[i].returnId == '') {
            jsonArr.push({
              min: this.state.barcodeList[i].barcode,
            });
          }
          else {
            jsonArr.push({
              min: this.state.barcodeList[i].barcode,
              returnId: this.state.barcodeList[i].returnId
            });
          }
        }
      }
      let store = localStorage.getItem('Store')
      this.props.sendBarcodeListAction(jsonArr,store);
    }
    else {
       localStorage.setItem('offlineScan', 'true');
    }

  }

  /**
   * ComponentDidUpdate gets data from indexeddb and sets to State, If data's validFlag is true means its valid
   * product(From returns table) , If validFlag is false then that data is not from products returned from list.
   */
  componentDidUpdate() {
    var _this = this;

    getAllData().then(function (data) {
      _this.setState({
        barcodeList: data
      });
    }).catch(function () {
    });
    this.barcodeSendSuccess()

  }

  /**
 * This function checks if any error while sending barcode to API then it redirects to error page.
 * If barcodes successfully submitted then redirects it to success page.
 */
  barcodeSendSuccess() {
    // console.log("success or not===" + this.props.isBarcodeSuccess)
    if(this.props.isBarcodeErrorData==true)
    {
      localStorage.removeItem("offlineScan");
      this.props.history.push({
              pathname: '/dashboard/error'
          })  
         window.location.reload();
    }
    if (this.props.response.hasOwnProperty('message')) {
      localStorage.removeItem("offlineScan");

      this.props.history.push({
        pathname: '/dashboard/success'
      })
      window.location.reload();


    }

  }

   /**
   * This function is used to delete selected barcode or min and after deleting push data to indexeddb.
   * updateScannedData callback function checks deleted min/barcode has another entry in list,
   * if entry is present then need to update valid flag as well as deleted return id. 
   * If localstorage is empty then it removes whole item.
   */
 
  deleteBarcode = (value: any) => {
    var _this = this;
    deleteDataFromDbById(value.id).then(function (resp) {
      if (value.validFlag == true) {
        let prod = value.minOrBarcode == 'min' ? value.min : value.barcode
        updateDataAfterDeletion('returnId',value.returnId).then(function (dataNew) {
          var executeFlag=false;
        for(let i=0;i<_this.state.barcodeList.length;i++)
         {
           if(value.minOrBarcode=='min')
           {
             if(_this.state.barcodeList[i].min == prod && _this.state.barcodeList[i].validFlag==false)
              executeFlag=true
           }
           else
           {
               if(_this.state.barcodeList[i].barcode == prod && _this.state.barcodeList[i].validFlag==false)
                executeFlag=true
             }
         }  
         
           if(executeFlag==true)
           {       
            updateScannedData(value.minOrBarcode, prod, value.returnId).then(function (dataLatest) {             
              updateDataByCursor('returnId',value.returnId).then(function (dataNew) {
               
            }).catch(function () {
            });
            }).catch(function () {
            });
           }

        }).catch(function () {
        });
      }
    })


  }
  render() {

    return (
      <IonPage>
        <IonHeader>
          <IonToolbar className="bg-green">
            <IonIcon icon={chevronBackOutline} className="text-yellow" slot="start" size="large" onClick={this.backToScan} />
            <IonTitle className="text-yellow">Scan Product List</IonTitle>
          </IonToolbar>


        </IonHeader>

        <IonItem className="bg-grey">
          <IonLabel className="font-14">Barcode No.</IonLabel>   <IonLabel className="text-center font-14">Quantity</IonLabel>
        </IonItem>
        <IonContent>
          {this.state.barcodeList.map((value: any, index: any) => {
            return (
              <IonItem>
                <IonLabel className="font-14" key={index}>{value.barcode}</IonLabel>
                {value.validFlag == false ? (<IonLabel className="invalidProduct">Product Invalid</IonLabel>) : (<IonLabel className="validProduct">Product Valid</IonLabel>)}
                <IonLabel className="font-14 text-center">1</IonLabel>
                <IonImg src="assets/img/delete.png" onClick={() => this.deleteBarcode(value)}></IonImg>
              </IonItem>)
          })}

          <IonInfiniteScroll
            threshold="100px">
          </IonInfiniteScroll>


        </IonContent>
        <IonRow>
          <IonCol className="ion-text-center">
            <IonButton expand="block" className="bg-yellow text-green capitalize_case" disabled={this.state.barcodeList.length == 0} onClick={this.submitBarcodes}>
              Submit
            </IonButton>
          </IonCol>
        </IonRow>
      </IonPage>
    )
  }
}


const mapStateToProps = (state: any) => {
  return {
    response: state.barcodeState.response,
    isBarcodeSuccess: state.barcodeState.isBarcodeSuccess,
    isBarcodeErrorData: state.barcodeState.isBarcodeErrorData,
    isLoadingData: state.barcodeState.isLoadingData,
    internetConnection: state.uiState.internetConnection,
  };
}

const mapDispatchToProps = {
  sendBarcodeListAction,
  networkHelperAction
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BarcodeList);