diff --git a/.changeset/cart-customization-details.md b/.changeset/cart-customization-details.md new file mode 100644 index 000000000..472b47d98 --- /dev/null +++ b/.changeset/cart-customization-details.md @@ -0,0 +1,6 @@ +--- +"@godaddy/gd-commerce-server": patch +"@godaddy/gd-commerce-storefront": patch +--- + +Carry optional `details` (`productAssetUrl`, `selectedAddons`) and `metafields` through every add-to-cart call, so a shopper's product customization reaches checkout and the order instead of staying client-side only. Existing calls without these fields behave exactly as before. diff --git a/packages/commerce-server/src/lib/commerce/order-subgraph.ts b/packages/commerce-server/src/lib/commerce/order-subgraph.ts index 7eef67516..d9315cd4c 100644 --- a/packages/commerce-server/src/lib/commerce/order-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/order-subgraph.ts @@ -14,6 +14,7 @@ * - Money values are integers in the currency's smallest unit (cents for USD). */ +import { InvalidRequestError } from './errors'; import type { Money } from './gql'; export interface OrderStorefrontEndpointInput { @@ -190,6 +191,26 @@ export interface CreateDraftLineItemInput { details?: LineItemDetailsInput; } +// Distinct from `LineItemDetailsInput`: the GraphQL `AddLineItemInput.details.selectedAddons` +// field takes `{ optionId, values: [{ inputValue | optionValueId }] }` — the catalog-option +// *input* shape — not the `{ attribute, sku, values: [{ name, costAdjustment }] }` *output* +// shape a line item returns once built. +export interface AddLineItemSelectedAddonInput { + optionId: string; + values: Array<{ inputValue: string }>; +} + +export interface AddLineItemDetailsInput { + productAssetUrl?: string; + selectedAddons?: AddLineItemSelectedAddonInput[]; +} + +export interface AddLineItemMetafieldInput { + key: string; + value: string; + type: 'JSON'; +} + export interface AddLineItemBySkuIdInput { orderId: string; skuId: string; @@ -198,7 +219,8 @@ export interface AddLineItemBySkuIdInput { fulfillmentMode?: string; status?: string; type?: string; - details?: LineItemDetailsInput; + details?: AddLineItemDetailsInput; + metafields?: AddLineItemMetafieldInput[]; } export interface UpdateLineItemByIdInput { @@ -275,10 +297,178 @@ export interface EmptyCartOrderInput { currencyCode?: string; } +export const PRODUCT_ASSET_URL_MAX_LENGTH = 2048; +export const SELECTED_ADDON_VALUE_MAX_LENGTH = 500; +export const MAX_SELECTED_ADDONS = 20; +export const MAX_METAFIELDS = 10; +export const METAFIELD_VALUE_MAX_LENGTH = 2000; + +// JSON is the only metafield type the storefront's add-to-cart surface supports — no `type` +// field here, so a client can't request a different one. +export interface AddToCartMetafieldInput { + key: string; + value: string; +} + +// KNOWN LIMITATION (order-api behavior, not this file's): adding the same skuId twice produces +// two distinct line items only when at least one of the two adds includes `details.selectedAddons`. +// order-api's line-matching (`findMatchingLineItem`) looks at `selectedAddons` alone — it ignores +// `details.productAssetUrl` and `metafields` entirely. So two adds of the same skuId that differ +// only by `metafields` or `productAssetUrl`, with no `selectedAddons` on either, merge into one +// line: the quantities combine, and the second add's `details`/`metafields` silently overwrite the +// first's rather than merging with them (`buildLineItemFromSku` spreads the stored line and then +// replaces both fields wholesale). A caller that needs metafield-only or image-only customizations +// to stay on distinct lines must also include a distinguishing `selectedAddons` entry. +// Tracked as a follow-up against order-api; see `createFromSkuId.ts`'s own design-doc link. export interface AddToCartItemInput { skuId: string; name: string; quantity: number; + details?: AddLineItemDetailsInput; + metafields?: AddToCartMetafieldInput[]; +} + +// Only TEXT/NUMBER catalog options (shopper-typed `inputValue`) are supported here. A LIST +// option's pre-defined `optionValueId` is a distinct, unvalidated shape — out of scope for this +// change (see the ticket's addon-value-shape decision) — so reject it explicitly rather than +// letting it reach `order-api` unchecked or crash on a missing `inputValue`. +function assertSupportedAddonValueShape(value: unknown): string { + if ( + typeof value !== 'object' || + value === null || + typeof (value as { inputValue?: unknown }).inputValue !== 'string' + ) { + throw new InvalidRequestError( + 'selectedAddons values must use { inputValue }; LIST-option values ({ optionValueId }) are not supported', + ); + } + return (value as { inputValue: string }).inputValue; +} + +// This is the only place these shapes, length/HTTPS/count limits are enforced — `order-api`'s +// schema uses a plain `z.string()` for these fields with no such caps, and the request body +// arrives as untyped JSON, so every field read here must be shape-checked before use rather +// than trusted from a TypeScript cast. +export function assertValidCartItemInput(item: AddToCartItemInput): void { + const assetUrl = item.details?.productAssetUrl; + if (assetUrl !== undefined) { + if (typeof assetUrl !== 'string') { + throw new InvalidRequestError('productAssetUrl must be a string'); + } + if (assetUrl.length > PRODUCT_ASSET_URL_MAX_LENGTH) { + throw new InvalidRequestError( + `productAssetUrl cannot exceed ${PRODUCT_ASSET_URL_MAX_LENGTH} characters`, + ); + } + let parsed: URL; + try { + parsed = new URL(assetUrl); + } catch { + throw new InvalidRequestError('productAssetUrl must be an absolute URL'); + } + if (parsed.protocol !== 'https:') throw new InvalidRequestError('productAssetUrl must use https'); + } + const addons = item.details?.selectedAddons; + if (addons !== undefined) { + if (!Array.isArray(addons)) throw new InvalidRequestError('selectedAddons must be an array'); + if (addons.length > MAX_SELECTED_ADDONS) { + throw new InvalidRequestError(`selectedAddons cannot exceed ${MAX_SELECTED_ADDONS} entries`); + } + for (const addon of addons) { + if ( + typeof addon !== 'object' || + addon === null || + typeof addon.optionId !== 'string' || + !addon.optionId + ) { + throw new InvalidRequestError('Each selectedAddons entry must have a non-empty optionId'); + } + if (!Array.isArray(addon.values)) { + throw new InvalidRequestError('Each selectedAddons entry must have a values array'); + } + for (const value of addon.values) { + const inputValue = assertSupportedAddonValueShape(value); + if (inputValue.length > SELECTED_ADDON_VALUE_MAX_LENGTH) { + throw new InvalidRequestError( + `selectedAddons value cannot exceed ${SELECTED_ADDON_VALUE_MAX_LENGTH} characters`, + ); + } + } + } + } + const metafields = item.metafields; + if (metafields !== undefined) { + if (!Array.isArray(metafields)) throw new InvalidRequestError('metafields must be an array'); + if (metafields.length > MAX_METAFIELDS) { + throw new InvalidRequestError(`metafields cannot exceed ${MAX_METAFIELDS} entries`); + } + for (const metafield of metafields) { + if ( + typeof metafield !== 'object' || + metafield === null || + !metafield.key || + typeof metafield.key !== 'string' + ) { + throw new InvalidRequestError('Each metafield must have a non-empty string key'); + } + if (typeof metafield.value !== 'string') { + throw new InvalidRequestError('Each metafield value must be a string'); + } + if (metafield.value.length > METAFIELD_VALUE_MAX_LENGTH) { + throw new InvalidRequestError( + `metafield value cannot exceed ${METAFIELD_VALUE_MAX_LENGTH} characters`, + ); + } + } + } +} + +// The single place a cart-item request body is turned into a trusted AddToCartItemInput. Reads +// only the known top-level fields off the untyped body — any other property the client sent +// (e.g. a spread product object) is dropped here rather than riding along to order-api, which +// would otherwise reject it as an unknown field and surface as a 502 instead of this 400. +export function parseCartItemInput(body: unknown): AddToCartItemInput { + if (typeof body !== 'object' || body === null) { + throw new InvalidRequestError('Request body must be an object'); + } + const candidate = body as Partial; + if (!candidate.skuId || typeof candidate.skuId !== 'string') { + throw new InvalidRequestError('skuId must be a non-empty string'); + } + if (!candidate.name || typeof candidate.name !== 'string') { + throw new InvalidRequestError('name must be a non-empty string'); + } + if (typeof candidate.quantity !== 'number') { + throw new InvalidRequestError('quantity must be a number'); + } + // Validate before picking: every field the pick below reads has already been shape-checked + // here, so it can be destructured directly without repeating the same guards. + assertValidCartItemInput(candidate as AddToCartItemInput); + return { + skuId: candidate.skuId, + name: candidate.name, + quantity: candidate.quantity, + ...(candidate.details !== undefined + ? { + details: { + ...(candidate.details.productAssetUrl !== undefined + ? { productAssetUrl: candidate.details.productAssetUrl } + : {}), + ...(candidate.details.selectedAddons !== undefined + ? { + selectedAddons: candidate.details.selectedAddons.map((addon) => ({ + optionId: addon.optionId, + values: addon.values.map((value) => ({ inputValue: value.inputValue })), + })), + } + : {}), + }, + } + : {}), + ...(candidate.metafields !== undefined + ? { metafields: candidate.metafields.map(({ key, value }) => ({ key, value })) } + : {}), + }; } export interface CartSummaryTotals { @@ -322,6 +512,8 @@ export function buildEmptyCartOrderInput({ }; } +// Caller must have already validated `item` (e.g. via `parseCartItemInput`) — this function +// does not re-validate. export function buildAddLineItemBySkuIdInput( orderId: string, item: AddToCartItemInput, @@ -333,6 +525,16 @@ export function buildAddLineItemBySkuIdInput( quantity: item.quantity, fulfillmentMode: 'NONE', status: 'DRAFT', + ...(item.details ? { details: item.details } : {}), + ...(item.metafields + ? { + metafields: item.metafields.map(({ key, value }) => ({ + key, + value, + type: 'JSON' as const, + })), + } + : {}), }; } diff --git a/packages/commerce-server/src/lib/commerce/upstream-errors.ts b/packages/commerce-server/src/lib/commerce/upstream-errors.ts index 5d6dfe7b0..b64bf3d99 100644 --- a/packages/commerce-server/src/lib/commerce/upstream-errors.ts +++ b/packages/commerce-server/src/lib/commerce/upstream-errors.ts @@ -7,7 +7,7 @@ * upstream errors stay 502; the server log carries their codes and statuses so new rules can * be derived from real responses rather than guessed. */ -import { type CommerceError, NotFoundError, type UpstreamError } from './errors'; +import { type CommerceError, InvalidRequestError, NotFoundError, type UpstreamError } from './errors'; import { GraphQLErrorWithCodes } from './gql'; export function isCartNotFoundError(error: unknown): boolean { @@ -34,20 +34,59 @@ export function isCartNotFoundError(error: unknown): boolean { }); } +// order-api reports its own input validation (catalog option min/max, the TEXT/NUMBER +// single-value rule, a SKU with no price, etc.) with this code on addLineItemBySkuId and +// addDraftOrder. The browser can't have known the catalog-side rule in advance, so this is a +// 400, not a generic 502 — unlike a true upstream outage or an unexpected shape. +export function isBadUserInputError(error: unknown): boolean { + if (!(error instanceof GraphQLErrorWithCodes)) { + return false; + } + return error.errors.length > 0 && error.errors.every(({ code }) => code === 'BAD_USER_INPUT'); +} + interface UpstreamErrorRule { matches(error: UpstreamError): boolean; toError(error: UpstreamError): CommerceError; } -const CART_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [ - { - // A completed (paid) draft is reported the same way, so this is "no longer a usable cart". - matches: isCartNotFoundError, - toError: (error) => new NotFoundError('Cart not found', { cause: error }), - }, +const BAD_USER_INPUT_RULE: UpstreamErrorRule = { + matches: isBadUserInputError, + toError: (error) => + new InvalidRequestError('The requested change is not valid for this cart or its items.', { + cause: error, + message: error.message, + }), +}; + +const CART_NOT_FOUND_RULE: UpstreamErrorRule = { + // A completed (paid) draft is reported the same way, so this is "no longer a usable cart". + matches: isCartNotFoundError, + toError: (error) => new NotFoundError('Cart not found', { cause: error }), +}; + +const CART_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [CART_NOT_FOUND_RULE]; + +// Add-item is the only route BAD_USER_INPUT is mapped for today: it's the one order-api path +// this PR actually exercises for that code. Applying it to every classifyCartUpstreamError +// route (GET, discounts, PATCH, DELETE) would be untested scope creep — add it to +// CART_UPSTREAM_ERROR_RULES too only once those routes' BAD_USER_INPUT cases are understood. +const ADD_ITEM_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [ + CART_NOT_FOUND_RULE, + BAD_USER_INPUT_RULE, ]; /** For routes acting on an existing saved cart (`/cart/:id`); creating a cart has none to miss. */ export function classifyCartUpstreamError(error: UpstreamError): CommerceError { return CART_UPSTREAM_ERROR_RULES.find((rule) => rule.matches(error))?.toError(error) ?? error; } + +/** For `POST /cart/:id/items`: an existing cart can still go missing, and the new item can still fail validation. */ +export function classifyAddItemUpstreamError(error: UpstreamError): CommerceError { + return ADD_ITEM_UPSTREAM_ERROR_RULES.find((rule) => rule.matches(error))?.toError(error) ?? error; +} + +/** For `POST /cart`: no existing cart to report missing, but addDraftOrder/addLineItemBySkuId can still reject input. */ +export function classifyCartCreationUpstreamError(error: UpstreamError): CommerceError { + return BAD_USER_INPUT_RULE.matches(error) ? BAD_USER_INPUT_RULE.toError(error) : error; +} diff --git a/packages/commerce-server/src/router.test.ts b/packages/commerce-server/src/router.test.ts index 24773dac5..8faa296c7 100644 --- a/packages/commerce-server/src/router.test.ts +++ b/packages/commerce-server/src/router.test.ts @@ -358,6 +358,451 @@ describe('Commerce scoped routes', () => { }, ); + it('forwards details and metafields to addLineItemBySkuId when creating a cart', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addDraftOrder: { id: 'cart-1' } }) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + const details = { + productAssetUrl: 'https://cdn.example.com/design.png', + selectedAddons: [{ optionId: 'opt-1', values: [{ inputValue: 'Custom design 123' }] }], + }; + const metafields = [{ key: 'designId', value: 'design-123' }]; + await createCart( + { + headers: {}, + body: { lineItems: [{ skuId: 'sku-1', name: 'Product', quantity: 1, details, metafields }] }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[1]?.[0].variables).toEqual({ + input: expect.objectContaining({ + details, + metafields: [{ key: 'designId', value: 'design-123', type: 'JSON' }], + }), + }); + }); + + it('forwards details and metafields to addLineItemBySkuId when adding to an existing cart', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + const details = { productAssetUrl: 'https://cdn.example.com/design.png' }; + const metafields = [{ key: 'designId', value: 'design-123' }]; + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, details, metafields }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: expect.objectContaining({ + details, + metafields: [{ key: 'designId', value: 'design-123', type: 'JSON' }], + }), + }); + }); + + it('ignores a client-supplied metafield type and always sends JSON', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + metafields: [{ key: 'designId', value: 'design-123', type: 'NOT_JSON', extra: 'nope' }], + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: expect.objectContaining({ + metafields: [{ key: 'designId', value: 'design-123', type: 'JSON' }], + }), + }); + }); + + it('sends two metafield-only customizations of the same SKU as two independent mutation calls', async (): Promise => { + // This route always issues one addLineItemBySkuId call per add-item request, each carrying + // its own distinct metafields. Known limitation (order-api behavior, not this route's): when + // neither add includes `details.selectedAddons`, order-api's own line-matching merges the two + // into a single line and the second add's details/metafields overwrite the first's, rather + // than this route's two calls producing two lines. See the KNOWN LIMITATION comment on + // AddToCartItemInput in order-subgraph.ts. + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-2' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Mug', quantity: 1, metafields: [{ key: 'designId', value: 'A' }] }, + } as unknown as Request, + res as unknown as Response, + ); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Mug', quantity: 1, metafields: [{ key: 'designId', value: 'B' }] }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: expect.objectContaining({ metafields: [{ key: 'designId', value: 'A', type: 'JSON' }] }), + }); + expect(vi.mocked(gqlRequest).mock.calls[2]?.[0].variables).toEqual({ + input: expect.objectContaining({ metafields: [{ key: 'designId', value: 'B', type: 'JSON' }] }), + }); + }); + + it('drops unknown request body properties before the addLineItemBySkuId mutation', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + description: 'A product description', + price: 1200, + mediaUrl: 'https://cdn.example.com/product.png', + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: { + orderId: 'cart-1', + skuId: 'sku-1', + name: 'Product', + quantity: 1, + fulfillmentMode: 'NONE', + status: 'DRAFT', + }, + }); + }); + + it('drops unknown properties inside details and each selectedAddons value', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + details: { + productAssetUrl: 'https://cdn.example.com/design.png', + sku: 'sneaky', + unitOfMeasure: 'each', + selectedAddons: [ + { + optionId: 'opt-1', + values: [{ inputValue: 'Custom design 123', optionValueId: 'sneaky-id' }], + extra: 'sneaky', + }, + ], + }, + metafields: [{ key: 'designId', value: 'design-123', type: 'NOT_JSON', extra: 'sneaky' }], + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[0]?.[0].variables).toEqual({ + input: expect.objectContaining({ + details: { + productAssetUrl: 'https://cdn.example.com/design.png', + selectedAddons: [{ optionId: 'opt-1', values: [{ inputValue: 'Custom design 123' }] }], + }, + metafields: [{ key: 'designId', value: 'design-123', type: 'JSON' }], + }), + }); + }); + + it('drops unknown lineItem properties before creating the cart', async (): Promise => { + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addDraftOrder: { id: 'cart-1' } }) + .mockResolvedValueOnce({ addLineItemBySkuId: { id: 'item-1' } }) + .mockResolvedValueOnce({ orderById: { id: 'cart-1', lineItems: [] } }); + const res = response(); + await createCart( + { + headers: {}, + body: { + lineItems: [{ skuId: 'sku-1', name: 'Product', quantity: 1, description: 'A product description' }], + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(vi.mocked(gqlRequest).mock.calls[1]?.[0].variables).toEqual({ + input: { + orderId: 'cart-1', + skuId: 'sku-1', + name: 'Product', + quantity: 1, + fulfillmentMode: 'NONE', + status: 'DRAFT', + }, + }); + }); + + it.each([ + [{ name: 'Product', quantity: 1 }, 'missing skuId'], + [{ skuId: 'sku-1', quantity: 1 }, 'missing name'], + [{ skuId: 'sku-1', name: 'Product' }, 'missing quantity'], + [{ skuId: 'sku-1', name: 'Product', quantity: 'one' }, 'non-numeric quantity'], + ])('rejects an add-item body with %j (%s)', async (body, _description): Promise => { + const res = response(); + await addItem( + { headers: {}, params: { id: 'cart-1' }, body } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it.each([ + ['http://cdn.example.com/design.png', 'non-https productAssetUrl'], + [`https://cdn.example.com/${'a'.repeat(2049)}.png`, 'oversized productAssetUrl'], + ])('rejects an add-item with %s (%s)', async (productAssetUrl): Promise => { + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, details: { productAssetUrl } }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects an add-item with more selectedAddons than the configured maximum', async (): Promise => { + const res = response(); + const selectedAddons = Array.from({ length: 21 }, (_, index) => ({ + optionId: `opt-${index}`, + values: [{ inputValue: 'value' }], + })); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, details: { selectedAddons } }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects an add-item with a LIST-option (optionValueId) addon value', async (): Promise => { + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + details: { selectedAddons: [{ optionId: 'opt-1', values: [{ optionValueId: 'val-1' }] }] }, + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it.each([ + ['non-array selectedAddons', { selectedAddons: 'not-an-array' }], + ['selectedAddons entry missing optionId', { selectedAddons: [{ values: [{ inputValue: 'x' }] }] }], + ['selectedAddons entry with non-array values', { selectedAddons: [{ optionId: 'opt-1', values: 'x' }] }], + ['selectedAddons value that is null', { selectedAddons: [{ optionId: 'opt-1', values: [null] }] }], + ['non-string productAssetUrl', { productAssetUrl: 42 }], + ])('rejects an add-item with %s instead of a 500', async (_label, details): Promise => { + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, details }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it.each([ + ['non-array metafields', 'not-an-array'], + ['metafields entry missing key', [{ value: 'x' }]], + ['metafields entry with non-string key', [{ key: 42, value: 'x' }]], + ['metafields entry with non-string value', [{ key: 'designId', value: 42 }]], + ['metafields entry that is null', [null]], + ])('rejects an add-item with %s instead of a 500', async (_label, metafields): Promise => { + const res = response(); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, metafields }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects an add-item with more metafields than the configured maximum', async (): Promise => { + const res = response(); + const metafields = Array.from({ length: 11 }, (_, index) => ({ key: `k${index}`, value: 'v' })); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, metafields }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects an add-item with an oversized metafield value', async (): Promise => { + const res = response(); + const metafields = [{ key: 'designId', value: 'a'.repeat(2001) }]; + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1, metafields }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('rejects cart creation with an invalid customization before creating the cart', async (): Promise => { + const res = response(); + await createCart( + { + headers: {}, + body: { + lineItems: [ + { + skuId: 'sku-1', + name: 'Product', + quantity: 1, + details: { productAssetUrl: 'http://cdn.example.com/design.png' }, + }, + ], + }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(gqlRequest).not.toHaveBeenCalled(); + }); + + it('reports order-api BAD_USER_INPUT on addLineItemBySkuId as 400, not 502', async (): Promise => { + const res = response(); + vi.mocked(gqlRequest).mockRejectedValueOnce( + new GraphQLErrorWithCodes([{ code: 'BAD_USER_INPUT', message: 'SKU has no price' }]), + ); + await addItem( + { + headers: {}, + params: { id: 'cart-1' }, + body: { skuId: 'sku-1', name: 'Product', quantity: 1 }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ + error: 'The requested change is not valid for this cart or its items.', + code: 'invalid_request', + requestId: expect.any(String), + }); + }); + + it('reports order-api BAD_USER_INPUT on cart creation as 400, not 502', async (): Promise => { + const res = response(); + vi.mocked(gqlRequest) + .mockResolvedValueOnce({ addDraftOrder: { id: 'cart-1' } }) + .mockRejectedValueOnce( + new GraphQLErrorWithCodes([{ code: 'BAD_USER_INPUT', message: 'SKU has no price' }]), + ); + await createCart( + { + headers: {}, + body: { lineItems: [{ skuId: 'sku-1', name: 'Product', quantity: 1 }] }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith({ + error: 'The requested change is not valid for this cart or its items.', + code: 'invalid_request', + requestId: expect.any(String), + }); + }); + + it.each([ + ['read', readCart, 'Failed to load cart'], + ['update', updateItem, 'Failed to update line item'], + ['remove', deleteItem, 'Failed to delete line item'], + ['discount', applyDiscount, 'Failed to apply discount codes'], + ] as const)( + 'does not map order-api BAD_USER_INPUT to 400 on %s — stays a generic 502', + async (_name, handler, label): Promise => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + const res = response(); + const error = new GraphQLErrorWithCodes([{ code: 'BAD_USER_INPUT', message: 'Invalid discount code' }]); + vi.mocked(gqlRequest).mockRejectedValueOnce(error); + await handler( + { + headers: {}, + params: { id: 'cart-1', itemId: 'item-1' }, + body: { discountCodes: ['PROMO'] }, + } as unknown as Request, + res as unknown as Response, + ); + expect(res.status).toHaveBeenCalledWith(502); + expect(res.json).toHaveBeenCalledWith({ + error: label, + code: 'upstream_error', + requestId: expect.any(String), + }); + consoleError.mockRestore(); + }, + ); + const scopedRequest = { headers: {}, query: {}, diff --git a/packages/commerce-server/src/server/api/commerce/cart/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/POST.ts index 0d94b4fb1..f34758769 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/POST.ts @@ -17,7 +17,7 @@ * * Body: * currencyCode? - override the configured currency (defaults to GODADDY_CURRENCY_CODE) - * lineItems? - [{ skuId, name, quantity }] added one-by-one after create + * lineItems? - [{ skuId, name, quantity, details?, metafields? }] added one-by-one after create * * Response: { cart: CartOrder | null } * Same shape as GET /api/commerce/cart/:id and the other cart mutation @@ -28,21 +28,22 @@ import type { Request, Response } from 'express'; import { assertCommerceCartScope } from '@/lib/commerce/cart-scope'; import { commerceRoute } from '@/lib/commerce/commerce-route'; import { type CommerceConfig, readCommerceConfigForResponse } from '@/lib/commerce/config'; -import { InvalidRequestError, UpstreamError } from '@/lib/commerce/errors'; +import { UpstreamError } from '@/lib/commerce/errors'; import { gqlRequest, storefrontHeaders } from '@/lib/commerce/gql'; import { type AddCartOrderResult, type AddCartOrderVariables, type AddLineItemBySkuIdResult, type AddLineItemBySkuIdVariables, - type AddToCartItemInput, buildAddLineItemBySkuIdInput, buildEmptyCartOrderInput, type GetCartOrderResult, type GetCartOrderVariables, getCartOrderQuery, orderStorefrontEndpoint, + parseCartItemInput, } from '@/lib/commerce/order-subgraph'; +import { classifyCartCreationUpstreamError } from '@/lib/commerce/upstream-errors'; const addCartOrderMutation = ` mutation AddCartOrder($input: AddDraftOrderInput!) { @@ -62,23 +63,17 @@ const addLineItemBySkuIdMutation = ` interface CreateCartBody { currencyCode?: string; - lineItems?: AddToCartItemInput[]; + lineItems?: unknown[]; } async function createCart(req: Request, res: Response): Promise { const body = (req.body ?? {}) as CreateCartBody; - const initialItems = Array.isArray(body.lineItems) ? body.lineItems : []; + const rawItems = Array.isArray(body.lineItems) ? body.lineItems : []; - // Validate all items BEFORE creating the cart so a bad payload can't - // produce an orphaned cart (cart created, item add fails, client never - // gets the id). Mirrors the validation in POST /api/commerce/cart/:id/items. - for (const item of initialItems) { - if (!item.skuId || !item.name || typeof item.quantity !== 'number') { - throw new InvalidRequestError( - 'Each lineItem must have skuId, a non-empty name, and a numeric quantity', - ); - } - } + // Parse and validate every item BEFORE creating the cart so a bad payload can't produce an + // orphaned cart (cart created, item add fails, client never gets the id). parseCartItemInput + // also allowlists each item to its known fields, dropping anything else the client sent. + const initialItems = rawItems.map((item) => parseCartItemInput(item)); const config: CommerceConfig = readCommerceConfigForResponse(res); assertCommerceCartScope(req, config); @@ -135,4 +130,6 @@ async function createCart(req: Request, res: Response): Promise { res.status(201).json({ cart: hydrated.orderById ?? null }); } -export default commerceRoute('Failed to create cart', createCart); +export default commerceRoute('Failed to create cart', createCart, { + classifyUpstreamError: classifyCartCreationUpstreamError, +}); diff --git a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts index 0731bff9a..600ee1849 100644 --- a/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/cart/[id]/items/POST.ts @@ -5,7 +5,7 @@ * (which creates the cart via POST /api/commerce/cart); subsequent adds * for the same cart go here. * - * Body: { skuId: string, name: string, quantity: number } + * Body: { skuId: string, name: string, quantity: number, details?, metafields? } * * Response: { cart: CartOrder | null } * The underlying `addLineItemBySkuId` GraphQL mutation only returns the @@ -23,14 +23,14 @@ import { gqlRequest, storefrontHeaders } from '@/lib/commerce/gql'; import { type AddLineItemBySkuIdResult, type AddLineItemBySkuIdVariables, - type AddToCartItemInput, buildAddLineItemBySkuIdInput, type GetCartOrderResult, type GetCartOrderVariables, getCartOrderQuery, orderStorefrontEndpoint, + parseCartItemInput, } from '@/lib/commerce/order-subgraph'; -import { classifyCartUpstreamError } from '@/lib/commerce/upstream-errors'; +import { classifyAddItemUpstreamError } from '@/lib/commerce/upstream-errors'; const addLineItemBySkuIdMutation = ` mutation AddLineItemBySkuId($input: AddLineItemInput!) { @@ -46,10 +46,7 @@ async function addLineItem(req: Request, res: Response): Promise { throw new InvalidRequestError('Missing cart id'); } - const body = (req.body ?? {}) as Partial; - if (!body.skuId || !body.name || typeof body.quantity !== 'number') { - throw new InvalidRequestError('Missing required fields: skuId, name, quantity'); - } + const item = parseCartItemInput(req.body); const config: CommerceConfig = readCommerceConfigForResponse(res); assertCommerceCartScope(req, config); @@ -63,13 +60,7 @@ async function addLineItem(req: Request, res: Response): Promise { await gqlRequest({ endpoint, query: addLineItemBySkuIdMutation, - variables: { - input: buildAddLineItemBySkuIdInput(cartId, { - skuId: body.skuId, - name: body.name, - quantity: body.quantity, - }), - }, + variables: { input: buildAddLineItemBySkuIdInput(cartId, item) }, headers, }); @@ -84,5 +75,5 @@ async function addLineItem(req: Request, res: Response): Promise { } export default commerceRoute('Failed to add line item', addLineItem, { - classifyUpstreamError: classifyCartUpstreamError, + classifyUpstreamError: classifyAddItemUpstreamError, }); diff --git a/packages/commerce-storefront/docs/server-api.md b/packages/commerce-storefront/docs/server-api.md index d02cab5ab..74223fb05 100644 --- a/packages/commerce-storefront/docs/server-api.md +++ b/packages/commerce-storefront/docs/server-api.md @@ -22,8 +22,8 @@ Server implementations can use GoDaddy Commerce APIs or their existing integrati | `GET /products/:id` | URI-encoded product ID | `{ skuGroup: SKUGroup \| null }` | | `GET /products/:id?attributeValues=blue&attributeValues=large` | Repeated selected attribute **names**, not IDs | `{ skuGroup: SKUGroup \| null }` with matching SKU connection | | `GET /cart/:id` | URI-encoded cart ID | `{ cart: CartOrder \| null }` | -| `POST /cart` | `{ lineItems: [{ skuId, name, quantity }] }` | `{ cart: CartOrder }` | -| `POST /cart/:id/items` | `{ skuId, name, quantity }` | `{ cart: CartOrder }` | +| `POST /cart` | `{ lineItems: [{ skuId, name, quantity, details?, metafields? }] }` | `{ cart: CartOrder }` | +| `POST /cart/:id/items` | `{ skuId, name, quantity, details?, metafields? }` | `{ cart: CartOrder }` | | `PATCH /cart/:id/items/:itemId` | `{ quantity }` | `{ cart: CartOrder }` | | `DELETE /cart/:id/items/:itemId` | No body | `{ cart: CartOrder }` | | `POST /cart/:id/discounts` | `{ discountCodes: string[] }` | `{ cart: CartOrder }` | @@ -96,7 +96,18 @@ A cart is a draft order. Return its `id`, complete `lineItems`, and authoritativ } ``` -Optional totals include `shippingTotal`, `taxTotal`, and `discountTotal`. Optional line details include `productAssetUrl` and `selectedOptions: [{ attribute, values: string[] }]`. The drawer shows supplied totals; it does not calculate authoritative prices from catalog values. A missing total disables checkout. +Optional totals include `shippingTotal`, `taxTotal`, and `discountTotal`. Optional line details include `productAssetUrl`, `selectedOptions: [{ attribute, values: string[] }]`, and `selectedAddons: [{ attribute, values: [{ name, costAdjustment? }] }]`. The drawer shows supplied totals; it does not calculate authoritative prices from catalog values. A missing total disables checkout. + +`metafields` on an add-item request are accepted and stored on the order, but are not returned on cart reads — the browser never sees any line item's metafields, whether written by this storefront, the merchant, or another app. Anything a shopper should see echoed back (a customization, a selected option) belongs in `details`, not `metafields`. + +### Customization fields on add-item requests + +`POST /cart` and `POST /cart/:id/items` accept an optional `details` and `metafields` alongside `skuId`, `name`, and `quantity`: + +- `details.productAssetUrl` must be an absolute `https://` URL (max 2048 characters), meant for the shopper's own design or customization preview. It replaces the catalog image for this line item only — the cart, the merchant's order view, emails, and fulfillment/packing views — the catalog itself and its own SKU media are unchanged. +- `details.selectedAddons` is `[{ optionId, values: [{ inputValue }] }]` — only the shopper-typed TEXT/NUMBER catalog-option shape. A pre-defined LIST-option value (`{ optionValueId }`) is not supported by this contract and is rejected. Up to 20 addon entries per item; each `inputValue` up to 500 characters. +- `metafields` is `[{ key, value }]`, up to 10 entries per item, each value up to 2000 characters. The server always sends `type: "JSON"` to the upstream order system regardless of any `type` the client supplies. +- **Known limitation:** two add-item calls for the same `skuId` reliably produce two distinct cart lines only when at least one of them includes `details.selectedAddons`. If neither call includes `selectedAddons` — for example, two calls that differ only by `metafields` or `productAssetUrl` — they merge into a single line, and the second call's customization silently replaces the first's. ## Checkout boundary diff --git a/packages/commerce-storefront/src/cart-model.ts b/packages/commerce-storefront/src/cart-model.ts index d93d855f8..c73ec2556 100644 --- a/packages/commerce-storefront/src/cart-model.ts +++ b/packages/commerce-storefront/src/cart-model.ts @@ -129,10 +129,24 @@ export interface CartOrder { tags?: string[] | null; } +export interface AddToCartSelectedAddonInput { + optionId: string; + values: Array<{ inputValue: string }>; +} + +// JSON is the only metafield type the server accepts here — no `type` field, so there is +// nothing for a caller to get wrong. +export interface AddToCartMetafieldInput { + key: string; + value: string; +} + export interface AddToCartItemInput { skuId: string; name: string; quantity: number; + details?: { productAssetUrl?: string; selectedAddons?: AddToCartSelectedAddonInput[] }; + metafields?: AddToCartMetafieldInput[]; } export interface CartSummaryTotals { diff --git a/packages/commerce-storefront/src/cart-parts.test.tsx b/packages/commerce-storefront/src/cart-parts.test.tsx index 4217e4213..6459ac617 100644 --- a/packages/commerce-storefront/src/cart-parts.test.tsx +++ b/packages/commerce-storefront/src/cart-parts.test.tsx @@ -561,6 +561,210 @@ describe('composable cart', () => { expect(added).toHaveBeenCalledWith({ name: 'Product 2', quantity: 1, isSample: true }); }); + it('forwards details and metafields from a custom addItem call to the cart POST body', async () => { + const fetchMock = mockStore(); + function CustomAdd(): ReactElement { + const { addItem } = useCommerce(); + return ( + + ); + } + render(app()); + await userEvent.click(screen.getByRole('button', { name: 'Add customized' })); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + const itemsCall = fetchMock.mock.calls.find(([input]) => String(input).includes('/items')); + const body = JSON.parse(String(itemsCall?.[1]?.body)); + expect(body).toEqual({ + skuId: 'sku-mug', + name: 'Mug', + quantity: 1, + details: { + productAssetUrl: 'https://cdn.test/design.png', + selectedAddons: [{ optionId: 'opt-1', values: [{ inputValue: 'Custom design 123' }] }], + }, + metafields: [{ key: 'designId', value: 'design-123' }], + }); + }); + + it('drops extra properties from a spread object passed to addItem', async () => { + const fetchMock = mockStore(); + function CustomAdd(): ReactElement { + const { addItem } = useCommerce(); + const product = { + id: 'sku-mug', + description: 'A mug', + price: 1200, + mediaUrl: 'https://cdn.test/mug.png', + }; + return ( + + ); + } + render(app()); + await userEvent.click(screen.getByRole('button', { name: 'Add from product card' })); + await waitFor(() => expect(fetchMock).toHaveBeenCalled()); + const itemsCall = fetchMock.mock.calls.find(([input]) => String(input).includes('/items')); + const body = JSON.parse(String(itemsCall?.[1]?.body)); + expect(body).toEqual({ skuId: 'sku-mug', name: 'Mug', quantity: 1 }); + }); + + it('surfaces selectedAddons in useCart() options alongside selectedOptions', async () => { + localStorage.setItem(storageKey, 'cart-1'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input), 'https://host.test'); + if (url.pathname.endsWith('/config')) return response({ cartScope: 's', currencyCode: 'USD' }); + return response({ + cart: { + id: 'cart-1', + lineItems: [ + { + id: 'line-1', + name: 'Mug', + quantity: 1, + details: { + selectedAddons: [{ attribute: 'Design', values: [{ name: 'Custom design 123' }] }], + }, + totals: { subTotal: { value: 1200, currencyCode: 'USD' } }, + }, + ], + totals: { + subTotal: { value: 1200, currencyCode: 'USD' }, + total: { value: 1200, currencyCode: 'USD' }, + }, + }, + }); + }), + ); + function Options(): ReactElement { + const { items } = useCart(); + return {JSON.stringify(items[0]?.options ?? [])}; + } + render(app()); + await waitFor(() => + expect(screen.getByTestId('options')).toHaveTextContent( + JSON.stringify([{ attribute: 'Design', values: ['Custom design 123'] }]), + ), + ); + }); + + it('includes a priced addon surcharge and drops a nameless addon value', async () => { + localStorage.setItem(storageKey, 'cart-1'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input), 'https://host.test'); + if (url.pathname.endsWith('/config')) return response({ cartScope: 's', currencyCode: 'USD' }); + return response({ + cart: { + id: 'cart-1', + lineItems: [ + { + id: 'line-1', + name: 'Mug', + quantity: 1, + details: { + selectedAddons: [ + { + attribute: 'Engraving', + values: [ + { name: 'Custom design 123', costAdjustment: { value: 500, currencyCode: 'USD' } }, + { name: null }, + ], + }, + ], + }, + totals: { subTotal: { value: 1700, currencyCode: 'USD' } }, + }, + ], + totals: { + subTotal: { value: 1700, currencyCode: 'USD' }, + total: { value: 1700, currencyCode: 'USD' }, + }, + }, + }); + }), + ); + function Options(): ReactElement { + const { items } = useCart(); + return {JSON.stringify(items[0]?.options ?? [])}; + } + render(app()); + await waitFor(() => + expect(screen.getByTestId('options')).toHaveTextContent( + JSON.stringify([{ attribute: 'Engraving', values: ['Custom design 123 (+$5.00)'] }]), + ), + ); + }); + + it('shows a negative addon surcharge with a minus sign, not a double negative', async () => { + localStorage.setItem(storageKey, 'cart-1'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input), 'https://host.test'); + if (url.pathname.endsWith('/config')) return response({ cartScope: 's', currencyCode: 'USD' }); + return response({ + cart: { + id: 'cart-1', + lineItems: [ + { + id: 'line-1', + name: 'Mug', + quantity: 1, + details: { + selectedAddons: [ + { + attribute: 'Size', + values: [{ name: 'Small', costAdjustment: { value: -200, currencyCode: 'USD' } }], + }, + ], + }, + totals: { subTotal: { value: 1000, currencyCode: 'USD' } }, + }, + ], + totals: { + subTotal: { value: 1000, currencyCode: 'USD' }, + total: { value: 1000, currencyCode: 'USD' }, + }, + }, + }); + }), + ); + function Options(): ReactElement { + const { items } = useCart(); + return {JSON.stringify(items[0]?.options ?? [])}; + } + render(app()); + await waitFor(() => + expect(screen.getByTestId('options')).toHaveTextContent( + JSON.stringify([{ attribute: 'Size', values: ['Small (-$2.00)'] }]), + ), + ); + }); + it('renders the packaged drawer from CommerceStorefront with dividers between lines', async () => { mockStore(); render( diff --git a/packages/commerce-storefront/src/cart-state.ts b/packages/commerce-storefront/src/cart-state.ts index 90b90b8c8..7fbecdb0d 100644 --- a/packages/commerce-storefront/src/cart-state.ts +++ b/packages/commerce-storefront/src/cart-state.ts @@ -1,7 +1,29 @@ import { useMemo } from 'react'; -import { useCommerce } from './commerce-provider'; +import { useCommerce, useMessage } from './commerce-provider'; import { type SampleProduct, sampleCurrency, useSampleCart } from './sample-cart'; +// A dedicated formatter cache for signed addon-cost adjustments, separate from `api.ts`'s +// `money()` cache: `signDisplay` is only needed here, not for the much hotter plain-price path +// `money()`/`useMoney()` serve everywhere else, so it isn't worth widening that shared cache's +// key or public signature for this one case. Capped the same way, for the same reason: a page +// uses a few pairs, but a long-running server rendering many locales/currencies should not grow +// this map unbounded. +const signedCurrencyFormats = new Map(); +const maxSignedCurrencyFormats: number = 64; +function formatSignedCost(value: number, currency: string, locale: string): string { + const key = `${locale}|${currency}`; + let format = signedCurrencyFormats.get(key); + if (!format) { + format = new Intl.NumberFormat(locale, { style: 'currency', currency, signDisplay: 'exceptZero' }); + // Maps keep insertion order, so the first key is the oldest. + if (signedCurrencyFormats.size >= maxSignedCurrencyFormats) + signedCurrencyFormats.delete(signedCurrencyFormats.keys().next().value ?? ''); + signedCurrencyFormats.set(key, format); + } + const scale = 10 ** (format.resolvedOptions().maximumFractionDigits ?? 2); + return format.format(value / scale); +} + /** One cart line, for custom cart parts. */ export interface CartItemState { /** Empty when the server returned a line without an ID. Such a line cannot be changed or removed. */ @@ -31,7 +53,8 @@ export interface CartState { /** Read the cart from anywhere inside `CommerceProvider`, for example to build a custom cart button. */ export function useCart(): CartState { - const { cart, config, connection, hydrating } = useCommerce(); + const { cart, config, connection, hydrating, locale } = useCommerce(); + const text = useMessage(); const sample = useSampleCart(); const isSample: boolean = connection === 'unbound'; const sampleItems = sample.items; @@ -59,24 +82,41 @@ export function useCart(): CartState { const lines = cart?.lineItems ?? []; const subtotal = cart?.totals?.subTotal?.value; return { - items: lines.map((item) => ({ - id: item.id ?? '', - name: item.name ?? '', - quantity: item.quantity ?? 0, - imageUrl: item.details?.productAssetUrl || null, - options: (item.details?.selectedOptions ?? []).map((option) => ({ - attribute: option.attribute ?? '', - values: option.values ?? [], - })), - subtotal: typeof item.totals?.subTotal?.value === 'number' ? item.totals.subTotal.value : null, - currency: item.totals?.subTotal?.currencyCode ?? currency, - sample: null, - })), + items: lines.map((item) => { + const itemCurrency = item.totals?.subTotal?.currencyCode ?? currency; + return { + id: item.id ?? '', + name: item.name ?? '', + quantity: item.quantity ?? 0, + imageUrl: item.details?.productAssetUrl || null, + options: [ + ...(item.details?.selectedOptions ?? []).map((option) => ({ + attribute: option.attribute ?? '', + values: option.values ?? [], + })), + ...(item.details?.selectedAddons ?? []).map((addon) => ({ + attribute: addon.attribute ?? '', + // A value without a name has nothing to show; skip it rather than render a blank entry. + values: (addon.values ?? []) + .filter((value) => !!value.name) + .map((value) => { + const cost = value.costAdjustment; + if (typeof cost?.value !== 'number' || cost.value === 0) return value.name as string; + const amount = formatSignedCost(cost.value, cost.currencyCode ?? itemCurrency, locale); + return text('addonValueWithCost', { name: value.name as string, amount }); + }), + })), + ], + subtotal: typeof item.totals?.subTotal?.value === 'number' ? item.totals.subTotal.value : null, + currency: itemCurrency, + sample: null, + }; + }), itemCount: lines.reduce((total, item) => total + (item.quantity ?? 0), 0), subtotal: typeof subtotal === 'number' ? subtotal : null, currency: cart?.totals?.subTotal?.currencyCode ?? currency, isSample, loading: hydrating, }; - }, [cart, config.currencyCode, hydrating, isSample, sampleItems]); + }, [cart, config.currencyCode, hydrating, isSample, locale, sampleItems, text]); } diff --git a/packages/commerce-storefront/src/commerce-provider.tsx b/packages/commerce-storefront/src/commerce-provider.tsx index 3c8db018b..81fc8d40e 100644 --- a/packages/commerce-storefront/src/commerce-provider.tsx +++ b/packages/commerce-storefront/src/commerce-provider.tsx @@ -691,11 +691,17 @@ function BoundCommerceProvider({ headers.set('X-Commerce-Scope', config.cartScope); return checkedFetch(input, { ...init, headers }); }; - const result: CartResponse = await addToCart( - id.current, - { skuId: item.skuId, name: item.name, quantity: item.quantity }, - fetchCart, - ); + // Pick only the supported fields: a caller spreading a larger object (e.g. + // addItem({ ...product, skuId, name, quantity })) must not forward the rest of it — + // order-api rejects unknown fields, which would otherwise surface as a 502. + const payload: AddToCartItemInput = { + skuId: item.skuId, + name: item.name, + quantity: item.quantity, + ...(item.details ? { details: item.details } : {}), + ...(item.metafields ? { metafields: item.metafields } : {}), + }; + const result: CartResponse = await addToCart(id.current, payload, fetchCart); if (!result.cart?.id || !result.cart.lineItems?.length) throw new StorefrontError('addReturnedNoCart'); if (!isActive()) return; commit(result.cart); diff --git a/packages/commerce-storefront/src/locales/fr-fr.ts b/packages/commerce-storefront/src/locales/fr-fr.ts index e992fa5e1..049856ebf 100644 --- a/packages/commerce-storefront/src/locales/fr-fr.ts +++ b/packages/commerce-storefront/src/locales/fr-fr.ts @@ -76,6 +76,7 @@ export const frFR: StorefrontMessages = { quantityPrefix: `Quantité${colon} `, remove: 'Retirer', itemOption: `{attribute}${colon} {values}`, + addonValueWithCost: '{name} ({amount})', cartEmpty: 'Votre panier est vide', cartEmptyHint: 'Ajoutez un article qui vous plaît et il apparaîtra ici.', sampleCartEmptyHint: "Ajoutez un produit d'exemple pour essayer le panier.", diff --git a/packages/commerce-storefront/src/messages.test.tsx b/packages/commerce-storefront/src/messages.test.tsx index 728c04afb..405482e9e 100644 --- a/packages/commerce-storefront/src/messages.test.tsx +++ b/packages/commerce-storefront/src/messages.test.tsx @@ -130,7 +130,8 @@ describe('formatMessage', () => { const keys = Object.keys(enUS) as StorefrontMessageKey[]; expect(Object.keys(frFR).sort()).toEqual(keys.sort()); for (const key of keys) { - if (key === 'skuOptionLabel') continue; + // Pure interpolation templates with no localizable wording — identical in every language. + if (key === 'skuOptionLabel' || key === 'addonValueWithCost') continue; expect.soft(frFR[key], key).not.toEqual(enUS[key]); } }); diff --git a/packages/commerce-storefront/src/messages.ts b/packages/commerce-storefront/src/messages.ts index 22e8cb7c8..31098b03d 100644 --- a/packages/commerce-storefront/src/messages.ts +++ b/packages/commerce-storefront/src/messages.ts @@ -65,6 +65,7 @@ const englishText = { quantityPrefix: 'Quantity: ', remove: 'Remove', itemOption: '{attribute}: {values}', + addonValueWithCost: '{name} ({amount})', cartEmpty: 'Your cart is empty', cartEmptyHint: 'Add something you love and it will show up here.', sampleCartEmptyHint: 'Add a sample product to try the cart.',