Skip to main content

Cart Module Guide

The Cart module manages shopping carts for customers, handling everything from adding items to completing checkout and placing orders.

Shopping Cart

Create and manage customer shopping carts

Line Items

Add, update, and remove products from carts

Checkout Flow

Handle shipping, payment, and order creation

Promotions

Apply discounts and promotional codes

Overview

A cart is a virtual shopping bag that customers use to collect items before purchase. The Cart module provides:
  • Creating and managing shopping carts
  • Adding, updating, and removing line items
  • Managing shipping and billing addresses
  • Applying promotions and calculating discounts
  • Tax line calculations
  • Payment collection integration
  • Completing the cart to create an order

Database Schema

Cart Table

The cart table stores the main cart entity:
id
string
required
Primary key with cart prefix (e.g., cart_01H...)
region_id
string
Associated region for pricing and tax calculations
customer_id
string
Customer reference (null for guest carts)
sales_channel_id
string
Sales channel context for the cart
email
string
Customer email address
currency_code
string
required
Currency for pricing (e.g., “USD”)
completed_at
datetime
When the cart was completed (order placed)
shipping_address_id
string
Foreign key to shipping address
billing_address_id
string
Foreign key to billing address

Line Item Table

The cart_line_item table stores products in the cart:
id
string
required
Primary key with cali prefix
cart_id
string
required
Foreign key to parent cart
title
string
required
Product title (denormalized)
quantity
integer
required
Quantity in cart
variant_id
string
Product variant reference
product_id
string
Product reference
unit_price
number
required
Price per unit in the cart’s currency
is_tax_inclusive
boolean
Whether the unit price includes tax
is_discountable
boolean
Whether promotions can be applied
requires_shipping
boolean
Whether the item needs shipping
Product information is denormalized onto line items to preserve order history even if products change later.

Relationships

Cart
├── items (LineItem[])
│   ├── adjustments (LineItemAdjustment[])
│   └── tax_lines (LineItemTaxLine[])
├── shipping_methods (ShippingMethod[])
│   ├── adjustments (ShippingMethodAdjustment[])
│   └── tax_lines (ShippingMethodTaxLine[])
├── shipping_address (Address)
├── billing_address (Address)
└── credit_lines (CreditLine[])

Core Workflows

The Cart module uses workflows for all major operations. Workflows ensure data consistency, emit events, and support compensation on failures.

Create Cart Workflow

The createCartWorkflow creates a new cart with optional initial items:
1

Validate inputs

Find or create the sales channel, region, and customer.
2

Get variant pricing

Retrieve prices for items being added, applying any custom pricing rules.
3

Confirm inventory

Verify sufficient stock is available for all items.
4

Create the cart

Create the cart record with line items.
5

Calculate taxes

Apply tax lines based on region and shipping address.
6

Apply promotions

Process any promotion codes provided.
7

Create payment collection

Initialize the payment collection for checkout.
Example Usage
const { result } = await createCartWorkflow(container).run({
  input: {
    region_id: "reg_123",
    items: [
      { variant_id: "var_456", quantity: 2 }
    ],
    customer_id: "cus_789",
    promo_codes: ["SUMMER20"]
  }
})

Add to Cart Workflow

The addToCartWorkflow adds items to an existing cart:
1

Acquire lock

Prevent concurrent modifications to the same cart.
2

Validate cart

Ensure the cart exists and is not completed.
3

Get pricing

Retrieve prices for the variants being added.
4

Confirm inventory

Verify stock availability for the quantities requested.
5

Create or update items

If the variant already exists in cart, update quantity. Otherwise, create a new line item.
6

Refresh cart

Recalculate totals, taxes, and promotions.
7

Release lock

Allow other operations on the cart.
The workflow uses locking to prevent race conditions when multiple requests try to modify the same cart simultaneously.

Complete Cart Workflow

The completeCartWorkflow converts a cart into an order:
1

Validate cart

Ensure payment is authorized and shipping is configured.
2

Create order

Transform cart data into an order record.
3

Reserve inventory

Decrement available stock for ordered items.
4

Register promotion usage

Track that promotions were used for reporting.
5

Link order to cart

Create the order-cart relationship.
6

Authorize payment

Complete payment authorization with the provider.
7

Emit order.placed event

Trigger downstream workflows (notifications, fulfillment, etc.).
Once a cart is completed, it cannot be modified. The completed_at timestamp indicates the cart has been converted to an order.

Calculated Totals

Request total fields when you need them. The module calculates these on-demand:
FieldDescription
totalGrand total including all taxes and shipping
subtotalItems total before tax and discounts
tax_totalTotal tax amount
discount_totalTotal discount amount
shipping_totalShipping cost with tax
item_totalItems subtotal with tax
item_subtotalItems subtotal without tax
Requesting Totals
const cart = await cartService.retrieveCart("cart_123", {
  select: ["total", "subtotal", "tax_total", "discount_total"],
  relations: ["items", "shipping_methods"]
})
When you request total fields, the module automatically includes required relations for calculations.

Integration with Other Modules

Product Module

Line items reference products and variants:
{
  variant_id: "var_123",
  product_id: "prod_456",
  // Product data is denormalized for history
  product_title: "Organic Apples",
  variant_sku: "APPL-ORG-1LB"
}

Payment Module

Carts have a payment collection for checkout:
  • Payment collection is created automatically on cart creation
  • Customers select a payment provider and authorize payment
  • Payment is finalized during cart completion

Promotion Module

Promotions are applied through adjustments:
  • Line item adjustments for product discounts
  • Shipping method adjustments for shipping discounts
  • Promotion usage is tracked when cart is completed

Tax Module

Tax lines are calculated based on:
  • Region tax rates
  • Shipping address
  • Product tax classes

Inventory Module

Inventory is managed at two points:
  1. Add to Cart - Confirm inventory is available
  2. Complete Cart - Reserve inventory for the order

Order Module

When a cart is completed:
  1. Order is created from cart data
  2. Link is established between order and cart
  3. Cart is marked as completed
The order_cart link module creates a relationship between orders and carts:
Order → order_cart → Cart
This allows you to:
  • Query the original cart from an order
  • Find which order was created from a cart
  • Maintain audit trail for order history

Complete Checkout Example

import { createCartWorkflow, addToCartWorkflow, completeCartWorkflow } from "@switchyard/core-flows"

// 1. Create cart with initial items
const { result: cart } = await createCartWorkflow(container).run({
  input: {
    region_id: "reg_123",
    items: [{ variant_id: "var_456", quantity: 1 }]
  }
})

// 2. Add shipping address
await updateCartWorkflow(container).run({
  input: {
    id: cart.id,
    shipping_address: {
      first_name: "John",
      last_name: "Doe",
      address_1: "123 Main St",
      city: "New York",
      postal_code: "10001",
      country_code: "us"
    }
  }
})

// 3. Add shipping method
await addShippingMethodToCartWorkflow(container).run({
  input: {
    cart_id: cart.id,
    options: [{ id: "so_123" }]
  }
})

// 4. Initialize and authorize payment
// (implementation depends on payment provider)

// 5. Complete cart to create order
const { result: order } = await completeCartWorkflow(container).run({
  input: { id: cart.id }
})

console.log("Order created:", order.id)

Best Practices

Always use the provided workflows instead of direct service calls. Workflows handle locking, event emission, and compensation on failures.
Total calculations require loading additional relations. Only include total fields when displaying to users.
The cart workflows use locking to prevent race conditions. If you build custom operations, implement similar locking.
Always verify a cart is not completed before attempting modifications. Completed carts cannot be changed.
Line items store product info to preserve order history. Don’t rely on product lookups for historical data.