Generated by XState Viz: https://xstate.js.org/viz

Home   »   Generated by XState Viz: https://xstate.js.org/viz

const State = {
  Error: 'Error',
  InboundPackage: 'InboundPackage',
  ScanPackage: 'ScanPackage',
  ScanSpace: 'ScanSpace',
}

const Event = {
  BarcodeDetected: 'BARCODE_DETECTED',
  Reset: 'RESET',
}

const initialContext = {
  destination: [],
  errorType: '',
  packageBarcode: '',
  scannerEnabled: true,
};

const dismissTimeout = 10000;
const packageErrors = ['scanned-space-instead-of-package', 'package-not-found'];

function xdInboundRequest(barcode, fail = false) {
  console.log({barcode});
  return fail
    ? Promise.reject(new Error("package-not-found"))
    : Promise.resolve(["a1", "b2"]);
}

const fetchMachine = Machine(
  {
    id: 'xd-inbound-v2',
    context: initialContext,
    initial: State.ScanPackage,
    on: {
      [Event.Reset]: {
        target: State.ScanPackage,
        actions: ['resetContext']
      },
    },
    states: {
      [State.ScanPackage]: {
        entry: 'enableScanner',
        on: {
          [Event.BarcodeDetected]: {
            target: State.InboundPackage,
            actions: ['assignPackageBarcode'],
          },
        },
      },
      [State.InboundPackage]: {
        entry: 'disableScanner',
        invoke: {
          id: 'receive-package',
          src: "receivePackage",
          onDone: {
            target: State.ScanSpace,
            actions: ['assignDestination']
          },
          onError: {
            target: State.Error,
            actions: ['assignErrorType']
          }
        },
        exit: 'enableScanner',
      },
      [State.ScanSpace]: {},
      [State.Error]: {
        after: {
          [dismissTimeout]: [
            { target: State.ScanPackage, cond: 'shouldScanPackageAgain' },
            
          ],
        },
        exit: 'clearErrorType'
      },
    },
  },
  {
    actions: {
      assignDestination: assign({ destination: (_, event) => event.data }),
      assignErrorType: assign({ errorType: (_, event) => event.data }),
      assignPackageBarcode: assign({
        packageBarcode: (_, event) => 'barcode' in event && event.barcode,
      }),
      clearErrorType: assign({ errorType: '' }),
      disableScanner: assign({ scannerEnabled: false }),
      enableScanner: assign({ scannerEnabled: true }),
      resetContext: assign(initialContext)
    },
    guards: {
      shouldScanPackageAgain: (context) => packageErrors.includes(context.errorType),
    },
    services: {
      receivePackage: (context) => xdInboundRequest(context.barcode)
    }
  },
);

Leave a Reply

Your email address will not be published. Required fields are marked *