Replace the Suspended Carts module

Ask about this Page
Copy for AI
View as Markdown

Read suspended Carts from the InStore State module, and render a Suspended Carts page that replaces the one built into the InStore POS.

This page covers the interface that a Suspended Carts replacement module implements. For the build setup that every replacement module needs, see Build a replacement module.
A Suspended Carts replacement module reads everything it needs from the Cart module context, rather than calling the InStore backend. The Cart module context also covers suspended Carts, so no separate context exists for them. Register the module with the SuspendedCarts type.

Read suspended Cart state and operations

Import useCartModuleContext from instoreState/context/CartModuleContext to read the suspended Carts and the operations that act on them.
The POS passes no props to a SuspendedCarts replacement module, so read all state from the context. The POS serves the module at the /suspended route.
useCartModuleContext returns the following members that a Suspended Carts module uses. They are marked @public in the types that the InStore State module publishes, and are supported for use in replacement modules. To resolve those types, see Build a replacement module.
MemberTypeDescription
suspendedCartsCartModuleCart[]Suspended Carts, most recently suspended first. Empty until getSuspendedCarts runs.
checkCartParameterMethodChecks whether a configuration parameter is available for this workstation.
checkUserPermissionMethodChecks whether the signed-in user holds a given permission.
getSuspendedCartsMethodLoads the suspended Carts of a location into suspendedCarts.
getSuspendReasonListMethodReturns the selectable reasons for suspending a Cart.
suspendCartMethodSuspends a Cart and unloads it from the till.
unsuspendCartMethodLoads a suspended Cart back into the slot it was suspended from.
A suspended Cart carries a suspension object with the following fields:
FieldData typeDescription
byUserObjectUser who suspended the Cart, with id, username, and optional fullName and email.
locationKeyStringKey of the location where the Cart was suspended.
reasonStringCode of the suspend reason.
referenceStringReference that an operator uses to find the Cart again.
workstationKeyStringKey of the workstation where the Cart was suspended.

Load and refresh the list

getSuspendedCarts accepts an optional filter with the following fields:
FieldData typeDescription
locationKeyStringLocation to list. Defaults to the location configured for the workstation.
workstationKeyStringNarrows the list to one workstation. Requires locationKey.

A call without a filter lists the suspended Carts of the configured location. The context doesn't offer a tenant-wide listing.

getSuspendedCarts resolves Promise<void>. It replaces suspendedCarts, so await the call and then render from the state member rather than from a return value. Call it again to refresh the list.

Suspend a Cart

suspendCart accepts the key of the Cart and an input with the following fields:
FieldData typeDescription
reasonStringCode of the suspend reason. Take it from getSuspendReasonList.
referenceStringReference that an operator uses to find the Cart again.

The location, workstation, and user come from the session, so your module does not pass them.

cartKey selects what the till unloads. A key that belongs to the exchange Cart clears the sale and return slots too. A key that belongs to the return Cart or to the sale Cart clears only that slot. A key that matches none of them suspends the Cart and unloads nothing. On success, the Cart moves to the head of suspendedCarts.
getSuspendReasonList returns a list of { code, label } entries read from the suspendreason reference list. The list is empty when the reference list isn't configured. For more information on reference lists, see Reference lists.

Receipt printing

suspendCart prints a receipt for the suspended Cart when all of the following are true:
  • The Print_Receipt_for_Suspend_Cart parameter is true.
  • The Suspend_Cart_Receipt_Template parameter is set.
  • A printer is configured for the workstation.

Otherwise, nothing prints.

Unsuspend a Cart

unsuspendCart accepts the key of a suspended Cart and loads it into the slot it was suspended from. The slot depends on the orderType of the Cart: exchange, return, or sale for any other value. On success, the Cart leaves suspendedCarts.
unsuspendCart rejects without sending a request when that slot already holds a Cart. The context never replaces an open Cart. Offer the operator a way to finish or suspend the open Cart first.

Handle failures

getSuspendedCarts, suspendCart, and unsuspendCart reject when they fail, so wrap each call in try and catch. The operations differ in what they leave behind:
  • getSuspendedCarts rejects and leaves suspendedCarts as it was.
  • suspendCart rejects and leaves the till as it was when the request fails.
  • suspendCart also rejects when the receipt print fails or times out. The Cart stays suspended and off the till. A timeout doesn't mean that nothing printed, so the receipt might still come out.
  • unsuspendCart rejects before any request when the target slot is taken, and rejects when the request fails.
  • checkCartParameter and checkUserPermission never throw. They return false for anything they can't confirm.

The context holds no loading or error state. Track both in your own module.

Check permissions and parameters

checkUserPermission accepts a value of CartModuleUserPermission or the equivalent string:
ValuePermission
SUSPEND_CARTsuspendcart
checkCartParameter accepts a value of CartModuleParameter or the equivalent string:
ValueParameter
ALLOW_SUSPEND_CARTAllow_Suspend_Cart
PRINT_RECEIPT_FOR_SUSPEND_CARTPrint_Receipt_for_Suspend_Cart
SUSPEND_CART_RECEIPT_TEMPLATESuspend_Cart_Receipt_Template
A parameter counts as active only when its configured value is the string true. Any other value, and a parameter that isn't configured, returns false. For the way these values reach a workstation, see Administration parameters.

Render a minimal Suspended Carts page

Expose a root component that defines your routes:

src/App.tsxtsx
import React from 'react';
import { Route, Routes } from 'react-router-dom';

import { SuspendedCartsPage } from './components/SuspendedCartsPage';

const App = () => (
  <Routes>
    <Route index element={<SuspendedCartsPage />} />
  </Routes>
);

export default App;

Then read the context, load the list, and render the suspended Carts:

src/components/SuspendedCartsPage.tsxtsx
import { useConfigurationContext } from 'instoreState/configuration/context';
import { useCartModuleContext } from 'instoreState/context/CartModuleContext';
import React, { useCallback, useEffect, useState } from 'react';

export const SuspendedCartsPage = () => {
  const { navigate } = useConfigurationContext();
  const { suspendedCarts, getSuspendedCarts, unsuspendCart } =
    useCartModuleContext();
  const [busy, setBusy] = useState(true);
  const [message, setMessage] = useState('');

  const load = useCallback(async () => {
    setBusy(true);
    setMessage('');

    try {
      await getSuspendedCarts();
    } catch (error) {
      setMessage('The suspended carts could not be loaded. Try again.');
    } finally {
      setBusy(false);
    }
  }, [getSuspendedCarts]);

  useEffect(() => {
    load();
  }, [load]);

  const resume = useCallback(
    async (cartKey: string) => {
      setMessage('');

      try {
        await unsuspendCart(cartKey);
        navigate('/cart');
      } catch (error) {
        setMessage('The cart could not be resumed. Finish the open cart first.');
      }
    },
    [navigate, unsuspendCart],
  );

  return (
    <div>
      <button onClick={load}>Refresh</button>
      {busy ? <p role="status">Loading</p> : null}
      {message ? <p role="alert">{message}</p> : null}
      {suspendedCarts.map((cart) => (
        <div key={cart.key}>
          <span>{cart.suspension?.reference}</span>
          <span>{cart.suspension?.byUser.username}</span>
          <span>{cart.totals.totalPriceDinero.toFormat()}</span>
          <button onClick={() => resume(cart.key as string)}>Resume</button>
        </div>
      ))}
    </div>
  );
};

This example serves a single index route. Treat it as a starting point for the interface rather than as a complete replacement.

To suspend a Cart from your own module, pick a code from getSuspendReasonList, and pass it with a reference to suspendCart:
src/components/SuspendCartButton.tsxtsx
import {
  CartModuleParameter,
  CartModuleUserPermission,
  useCartModuleContext,
} from 'instoreState/context/CartModuleContext';
import React, { useState } from 'react';

type Props = { cartKey: string };

export const SuspendCartButton = ({ cartKey }: Props) => {
  const {
    checkCartParameter,
    checkUserPermission,
    getSuspendReasonList,
    suspendCart,
  } = useCartModuleContext();
  const [reference, setReference] = useState('');
  const [message, setMessage] = useState('');
  const reasons = getSuspendReasonList();

  const canSuspend =
    checkUserPermission(CartModuleUserPermission.SUSPEND_CART) ||
    checkCartParameter(CartModuleParameter.ALLOW_SUSPEND_CART);

  if (!canSuspend) {
    return null;
  }

  const suspend = async () => {
    try {
      await suspendCart(cartKey, {
        reason: reasons[0]?.code ?? '',
        reference,
      });
    } catch (error) {
      setMessage('The cart could not be suspended. Try again.');
    }
  };

  return (
    <div>
      <input
        aria-label="Reference"
        value={reference}
        onChange={(event) => setReference(event.target.value)}
      />
      <button onClick={suspend}>Suspend</button>
      {message ? <p role="alert">{message}</p> : null}
    </div>
  );
};
The examples use plain text for their messages. The translation keys that the POS ships for suspended Carts aren't documented on this page, so check the list of core strings before you use a key.

Suspended Carts behavior to account for

Suspended Carts arrive ready to display, so your module never handles a raw commercetools payload. Account for the following behavior:

  • Money arrives as Dinero values. Format them with .toFormat() instead of reading centAmount.
  • Totals are precomputed on cart.totals.
  • Line Item names resolve by exact match on the active locale, and fall back to an empty string. The POS applies no locale fallback chain.
  • The list is scoped to one location. It changes only when you call getSuspendedCarts, suspendCart, or unsuspendCart, so call getSuspendedCarts again to refresh it.
  • An empty suspendedCarts list is not proof that no Cart is suspended, because the list stays empty until the first getSuspendedCarts call resolves.
  • A SuspendedCarts module doesn't take a mainPath. The POS serves it at the built-in /suspended route, which is also reserved for Custom modules.
useCartModuleContext does not throw when the Cart context is out of scope. It returns an empty suspendedCarts list and operations that resolve without doing anything. A wiring issue appears as a list that stays empty instead of as a thrown error. Check the module connection first when no Carts appear.
The Cart module context covers listing, suspending, and unsuspending Carts. The built-in module also manages the suspend dialog in the POS header and the controlled Suspend and Retrieve feature, which the context does not expose as dedicated operations. A replacement module implements those surfaces itself. For the parameters that control the feature, see Administration parameters.

Next steps

Use the following resources to finish and roll out your Suspended Carts module: