Orders Module
The orders module manages the order lifecycle, cart operations, and checkout process.
Configuration Options
export interface OrderSettingsOrderPositionValidation {
order: Order;
product: Product;
quantityDiff?: number;
configuration?: { key: string; value: string }[] | null;
}
export interface OrdersSettingsOptions {
ensureUserHasCart?: boolean;
orderNumberHashFn?: (order: Order, index: number) => string;
validateOrderPosition?: (
validationParams: OrderSettingsOrderPositionValidation,
unchainedAPI: UnchainedAPI,
) => Promise<void>;
}
ensureUserHasCart: If enabled, Unchained will try to pre-generate a new cart when a user does not have one on various occasions, it's still not guaranteed that a user always has a cart. (default: false)
Order Number Creation
The orderNumberHashFn is used to generate human-readable codes that can be easily spelled out to support staff. The default generates a random alphanumeric uppercase string with length 6 using an unambiguous charset (no O, 0, 1). If the number has already been taken, the function gets iteratively called with an increasing index.
Order Position Validation
When users mutate their cart, you sometimes have cases where you want custom checks. For example you want to restrict users to only buy 4 tickets in one go despite having a stock of 100 tickets.
With validateOrderPosition you can validate cart manipulations and throw Errors that bubble through to the client.
The default validator checks if a product is active.
await startPlatform({
options: {
orders: {
orderNumberHashFn: (order, index) => `${100000 + index}`,
validateOrderPosition: async ({ order, product, quantityDiff, configuration }, context) => {
const justOneAtATime = product.tags?.includes('one-at-a-time');
const positions = await context.modules.orders.positions.findOrderPositions({
orderId: order._id,
});
const userAlreadyHasProductInPositions = positions.some((p) => p.productId === product._id);
if (justOneAtATime && userAlreadyHasProductInPositions && quantityDiff > 0) {
throw new Error('ONE_AT_A_TIME');
}
},
},
},
});
Module API
Access via modules.orders in the Unchained API context.
Queries
| Method | Arguments | Description |
|---|---|---|
cart | { userId, countryCode?, orderNumber? } | Get user's cart |
findOrder | { orderId? | orderNumber? }, options? | Find a specific order |
findOrders | { limit?, offset?, sort?, ...query } | List orders with pagination |
count | query | Count orders |
orderExists | { orderId } | Check if order exists |
isCart | order | Check if order is a cart |
Mutations
| Method | Arguments | Description |
|---|---|---|
create | { userId, countryCode, currencyCode, billingAddress?, contact?, context? } | Create order |
delete | orderId | Delete order |
setCartOwner | { orderId, userId } | Change order owner |
updateBillingAddress | orderId, billingAddress | Update billing address |
updateContact | orderId, contact, { eventPayload? }? | Update contact info; eventPayload: 'ids' keeps the contact out of ORDER_UPDATE (Personal Data) |
updateContext | orderId, context | Update order context/meta of a cart or pending order |
anonymize | orderId, { contextKeys?, clearContext? }? | Remove the personal data of an order in any status (Personal Data) |
updateStatus | orderId, { status, info? } | Update order status |
setPaymentProvider | orderId, paymentProviderId | Set payment method |
setDeliveryProvider | orderId, deliveryProviderId | Set delivery method |
acquireLock | orderId, identifier, ttl? | Acquire a distributed lock, renewed until released; ttl (default 5000 ms) bounds how long a crashed holder keeps it |
Sub-modules
modules.orders.positions — Order line items:
| Method | Arguments | Description |
|---|---|---|
findOrderPosition | { itemId } | Get single position |
findOrderPositions | { orderId } | Get all positions in order |
addProductItem | { orderId, productId, originalProductId, quantity, configuration?, quotationId?, context? } | Add product to cart |
updateProductItem | { orderPositionId, quantity, configuration } | Update line item |
delete | orderPositionId | Remove line item |
removePositions | { orderId } | Clear all positions |
anonymize | orderId, { configurationKeys? }? | Remove the configuration of the order's positions, or only the given parameters; returns the number of positions changed |
modules.orders.payments — Order payments:
| Method | Arguments | Description |
|---|---|---|
findOrderPayment | { orderPaymentId } | Get payment record |
updateStatus | orderPaymentId, { status, transactionId?, info? } | Update payment status |
markAsPaid | orderPayment, meta? | Mark an open payment as paid |
modules.orders.deliveries — Order deliveries:
| Method | Arguments | Description |
|---|---|---|
findDelivery | { orderDeliveryId } | Get delivery record |
updateStatus | orderDeliveryId, { status, info? } | Update delivery status |
markAsDelivered | orderDelivery | Mark an open delivery as delivered |
modules.orders.discounts — Order discounts:
| Method | Arguments | Description |
|---|---|---|
findOrderDiscount | { discountId } | Get discount record |
create | doc | Create discount |
delete | orderDiscountId | Remove discount |
Statistics
| Method | Arguments | Description |
|---|---|---|
statistics.countByDateField | dateField, dateRange?, options? | Count orders by date |
statistics.aggregateByDateField | dateField, dateRange?, options? | Aggregate stats by date |
statistics.getTopCustomers | orderIds, options? | Get top spending customers |
Personal Data
modules.orders.anonymize(orderId, options?) removes the personal data of an order in any status, also of confirmed and fulfilled orders (updateContext only changes carts and pending orders):
- It removes
contactandbillingAddress, and thecontextKeysyou pass (keys or dot paths oforder.context; a dot path does not reach into arrays, pass the array's key).clearContext: truereplaces the whole context with{}instead. - It stores the date of the first call in
order.anonymizedand emitsORDER_ANONYMIZEDwith{ orderId }only. It does not emitORDER_UPDATE, so subscribers that keep copies of orders (a search index, for example) listen toORDER_ANONYMIZEDto drop the removed data. - Calling it again changes and emits nothing, unless something is left to remove (for example a contact set since). Status, status log, order number, owner, positions and prices are kept.
modules.orders.positions.anonymize(orderId, { configurationKeys? }) removes the configuration of all positions of the order, or only the parameters with the given keys. It emits nothing and returns the number of positions it changed.
await modules.orders.anonymize(orderId, { contextKeys: ['attendees'] });
await modules.orders.positions.anonymize(orderId, { configurationKeys: ['attendees'] });
Neither touches copies kept elsewhere: the delivery address in the context of the order delivery (modules.orders.deliveries.updateContext), provider data in the context of the order payment, the owner's lastContact and lastBillingAddress (services.users.deleteUser removes them) and events stored before, which expire after EVENTS_TTL_SECONDS (default 2 days). Which orders may be anonymized, for example because of bookkeeping duties for paid orders, is up to the caller.
To change the contact of a placed order without storing it in an event, pass { eventPayload: 'ids' } to updateContact. ORDER_UPDATE then carries { orderId, field: 'contact', keys } (type OrderUpdateKeysEventPayload, keys are the contact keys whose value changed) instead of { order, field }. Subscribers that read payload.order load the order by payload.orderId when it is missing.
await modules.orders.updateContact(orderId, { emailAddress }, { eventPayload: 'ids' });
Events
| Event | Payload | Description |
|---|---|---|
ORDER_CREATE | { order } | Emitted when an order is created |
ORDER_UPDATE | { order, field }, or { orderId, field, keys } after updateContact(…, { eventPayload: 'ids' }) | Emitted when an order is updated |
ORDER_REMOVE | { orderId } | Emitted when an order is removed |
ORDER_ANONYMIZED | { orderId } | Emitted when anonymize removed personal data from an order |
ORDER_CHECKOUT | { order, oldStatus } | Emitted when checkout is initiated |
ORDER_CONFIRMED | { order, oldStatus } | Emitted when an order is confirmed |
ORDER_FULFILLED | { order, oldStatus } | Emitted when an order is fulfilled |
ORDER_REJECTED | { order, oldStatus } | Emitted when an order is rejected |
ORDER_ADD_PRODUCT | { orderPosition } | Emitted when a product is added to cart |
ORDER_UPDATE_CART_ITEM | { orderPosition } | Emitted when a cart item is updated |
ORDER_REMOVE_CART_ITEM | { orderPosition } | Emitted when a cart item is removed |
ORDER_EMPTY_CART | { orderId, count } | Emitted when cart is emptied |
ORDER_SET_DELIVERY_PROVIDER | { order } | Emitted when delivery provider is set |
ORDER_SET_PAYMENT_PROVIDER | { order } | Emitted when payment provider is set |
ORDER_UPDATE_DELIVERY | { orderDelivery } | Emitted when delivery is updated |
ORDER_DELIVER | { orderDelivery } | Emitted when order is delivered |
ORDER_PAY | { orderPayment } | Emitted when an order payment is marked as paid |
ORDER_UPDATE_PAYMENT | { orderPayment } | Emitted when an order payment is updated |
ORDER_CREATE_DISCOUNT | { discount } | Emitted when a discount is created |
ORDER_UPDATE_DISCOUNT | { discount } | Emitted when a discount is updated |
ORDER_REMOVE_DISCOUNT | { discount } | Emitted when a discount is removed |
More Information
For API usage and detailed documentation, see the core-orders package on GitHub.