# Replace the Suspended Carts module

**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](/instore/customization/pos-module-development.md).

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](/instore/customization/pos-module-development.md#resolve-types).

| Member | Type | Description |
| --- | --- | --- |
| `suspendedCarts` | `CartModuleCart[]` | Suspended Carts, most recently suspended first. Empty until `getSuspendedCarts` runs. |
| `checkCartParameter` | Method | Checks whether a configuration parameter is available for this workstation. |
| `checkUserPermission` | Method | Checks whether the signed-in user holds a given permission. |
| `getSuspendedCarts` | Method | Loads the suspended Carts of a location into `suspendedCarts`. |
| `getSuspendReasonList` | Method | Returns the selectable reasons for suspending a Cart. |
| `suspendCart` | Method | Suspends a Cart and unloads it from the till. |
| `unsuspendCart` | Method | Loads a suspended Cart back into the slot it was suspended from. |

A suspended Cart carries a `suspension` object with the following fields:

| Field | Data type | Description |
| --- | --- | --- |
| `byUser` | Object | User who suspended the Cart, with `id`, `username`, and optional `fullName` and `email`. |
| `locationKey` | String | Key of the location where the Cart was suspended. |
| `reason` | String | Code of the suspend reason. |
| `reference` | String | Reference that an operator uses to find the Cart again. |
| `workstationKey` | String | Key of the workstation where the Cart was suspended. |

### Load and refresh the list

`getSuspendedCarts` accepts an optional filter with the following fields:

| Field | Data type | Description |
| --- | --- | --- |
| `locationKey` | String | Location to list. Defaults to the location configured for the workstation. |
| `workstationKey` | String | Narrows 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:

| Field | Data type | Description |
| --- | --- | --- |
| `reason` | String | Code of the suspend reason. Take it from `getSuspendReasonList`. |
| `reference` | String | Reference 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](/instore/use-the-instore-center/reference-lists.md).

#### 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:

| Value | Permission |
| --- | --- |
| `SUSPEND_CART` | `suspendcart` |

`checkCartParameter` accepts a value of `CartModuleParameter` or the equivalent string:

| Value | Parameter |
| --- | --- |
| `ALLOW_SUSPEND_CART` | `Allow_Suspend_Cart` |
| `PRINT_RECEIPT_FOR_SUSPEND_CART` | `Print_Receipt_for_Suspend_Cart` |
| `SUSPEND_CART_RECEIPT_TEMPLATE` | `Suspend_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](/instore/customization/administration-parameters.md).

## Render a minimal Suspended Carts page

Expose a root component that defines your routes:

```tsx title="src/App.tsx"
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:

```tsx title="src/components/SuspendedCartsPage.tsx"
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`:

```tsx title="src/components/SuspendCartButton.tsx"
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](/instore/customization/list-of-core-strings.md) 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.

> **Warning:** `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](/instore/customization/administration-parameters.md).

## Next steps

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

- [Build a replacement module](/instore/customization/pos-module-development.md) to configure Module Federation, resolve types, and read shared POS state.
- [Replace InStore POS UI modules](/instore/customization/pos-ui-modules.md) to register the module and assign it to a location or a workstation.
- [Implement the Cart module](/instore/customization/pos-cart-module.md) to read Cart state and render a replacement Cart.
- [Implement the Catalog module](/instore/customization/pos-catalog-module.md) to read catalog state and render replacement catalog browsing and search.
- [Implement the Customer module](/instore/customization/pos-customer-module.md) to read Customer state and render a replacement Customer lookup or header control.
- [Run InStore POS API requests](/instore/customization/pos-api-access.md) to set the API host, Project, and tenant, and to get an access token.

## Related pages

- [Area overview page with navigation](/instore.md)
- [Previous page: Replace Search Transaction](/instore/customization/pos-search-transaction-module.md)
- [Search documentation and API specs](/search.md)