@tallyui/pos 3.11.0 → 3.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "3.11.0",
3
+ "version": "3.12.0",
4
4
  "type": "module",
5
5
  "description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
6
6
  "main": "./dist/index.js",
@@ -28,20 +28,20 @@
28
28
  "directory": "packages/pos"
29
29
  },
30
30
  "peerDependencies": {
31
- "@tallyui/core": "^3.11.0",
31
+ "@tallyui/core": "^3.12.0",
32
32
  "react": ">=18",
33
33
  "rxdb": "~17.5.0",
34
34
  "rxjs": ">=7"
35
35
  },
36
36
  "devDependencies": {
37
- "@tallyui/core": "3.11.0",
37
+ "@tallyui/core": "3.12.0",
38
38
  "@types/react": ">=18",
39
39
  "react": "^19.2.4",
40
40
  "rxdb": "17.5.0",
41
41
  "rxjs": "7.8.2",
42
- "@tallyui/connector-medusa": "3.11.0",
43
- "@tallyui/connector-woocommerce": "3.11.0",
44
- "@tallyui/database": "3.11.0"
42
+ "@tallyui/connector-medusa": "3.12.0",
43
+ "@tallyui/connector-woocommerce": "3.12.0",
44
+ "@tallyui/database": "3.12.0"
45
45
  },
46
46
  "scripts": {
47
47
  "build": "tsup",
package/src/index.ts CHANGED
@@ -52,7 +52,7 @@ export type {
52
52
  } from './order';
53
53
 
54
54
  // Receipt
55
- export { buildReceiptData, RECEIPT_SCHEMA_VERSION } from './receipt';
55
+ export { buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, RECEIPT_SCHEMA_VERSION } from './receipt';
56
56
  export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, ReceiptRegister, ReceiptFiscal } from './receipt';
57
57
 
58
58
  // Product
@@ -62,6 +62,12 @@ export function assertDisplayResidue(residue: number, convertedLines: number, co
62
62
  if (Math.abs(residue) > bound) throw new Error(`Display residue ${residue} exceeds its bound of ${bound} (ADR-063)`);
63
63
  }
64
64
 
65
+ /** Whether two lines carry the same "Any" picks (#495): the same names in the same order with equal values; none matches none. */
66
+ export function samePicks(a: Pick<LineItem, 'anyAttributes' | 'attributes'>, b: Pick<LineItem, 'anyAttributes' | 'attributes'>): boolean {
67
+ const names = a.anyAttributes ?? [], other = b.anyAttributes ?? [];
68
+ return names.length === other.length && names.every((name, i) => name === other[i] && a.attributes?.[name] === b.attributes?.[name]);
69
+ }
70
+
65
71
  /** The regular unit price to store with a catalogue line (ADR-077 d3): the base price when on sale, else the price charged. */
66
72
  export function regularUnitPriceMinor(resolved: ResolvedPrice): number | undefined {
67
73
  return resolved.was === undefined ? resolved.current.amount : resolved.was.taxInclusive === resolved.current.taxInclusive ? resolved.was.amount : undefined;
@@ -379,7 +385,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
379
385
  const existing = lineItems.find(
380
386
  (li) => !input.custom && !li.custom && li.productId === productId && li.variantId === variantId && li.taxInclusive === taxInclusive
381
387
  && (!woo || li.taxClass === input.taxClass && (li.taxStatus === 'none') === (input.taxStatus === 'none'))
382
- && li.regularUnitPriceMinor === input.regularUnitPriceMinor
388
+ && li.regularUnitPriceMinor === input.regularUnitPriceMinor && samePicks(li, input)
383
389
  && li.unitPriceMinor === unitPrice.amount && li.taxLines.length === taxRates.length
384
390
  && li.taxLines.every((tax, index) => tax.code === taxRates[index].code && tax.ratePpm === taxRates[index].ratePpm),
385
391
  );
@@ -402,6 +408,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
402
408
  variantId,
403
409
  name: input.name,
404
410
  ...(input.attributes && Object.keys(input.attributes).length ? { attributes: { ...input.attributes } } : {}),
411
+ ...(input.anyAttributes?.length ? { anyAttributes: [...input.anyAttributes] } : {}),
405
412
  sku: input.sku ?? '',
406
413
  imageUrl: input.imageUrl,
407
414
  unitPriceMinor: unitPrice.amount,
@@ -71,6 +71,7 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
71
71
  variantId: line.variantId,
72
72
  name: line.name,
73
73
  ...(line.attributes !== undefined ? { attributes: line.attributes } : {}),
74
+ ...(line.anyAttributes !== undefined ? { anyAttributes: line.anyAttributes } : {}),
74
75
  sku: line.sku,
75
76
  imageUrl: line.imageUrl,
76
77
  unitPrice: { amount: line.unitPriceMinor, currency, taxInclusive: line.taxInclusive },
@@ -77,6 +77,8 @@ export interface LineItem {
77
77
  name: string;
78
78
  /** The variant's chosen options, name to value (#495). */
79
79
  attributes?: Record<string, string>;
80
+ /** The names in attributes the cashier picked for the variant's "Any" option groups (#495); absent when none. */
81
+ anyAttributes?: string[];
80
82
  sku: string;
81
83
  imageUrl?: string;
82
84
  unitPriceMinor: number; // as sold, integer
@@ -162,6 +164,8 @@ export interface AddLineInput {
162
164
  name: string;
163
165
  /** The variant's chosen options, name to value (#495). */
164
166
  attributes?: Record<string, string>;
167
+ /** The names in attributes the cashier picked for the variant's "Any" option groups (#495); absent when none. */
168
+ anyAttributes?: string[];
165
169
  sku?: string;
166
170
  imageUrl?: string;
167
171
  unitPrice: Money & { taxInclusive?: boolean }; // currency must equal the order currency; taxInclusive wins over the order's pricesIncludeTax
@@ -58,10 +58,10 @@ function netDiscountMinor(line: PosOrderLine, pricesIncludeTax: boolean): number
58
58
 
59
59
  /**
60
60
  * The order.create version an order's stored content makes: 3 with ADR-065's figures, else 2 when its lines are
61
- * discounted (ADR-062), else 1; fees, shipping or custom lines need 5; coupons need 6. Also used by pos_orders v5's migration.
61
+ * discounted (ADR-062), else 1; fees, shipping or custom lines need 5; coupons or a line's Any picks (#495) need 6. Also used by pos_orders v5's migration.
62
62
  */
63
63
  export function contentVersion(order: Pick<PosOrder, 'display' | 'taxByRate' | 'lines' | 'fees' | 'shipping' | 'coupons'>): 1 | 2 | 3 | 5 | 6 {
64
- if (order.coupons?.length) return 6;
64
+ if (order.coupons?.length || order.lines.some((line) => line.anyAttributes?.length)) return 6;
65
65
  if (order.fees?.length || order.shipping?.length || order.lines.some((line) => line.custom)) return 5;
66
66
  return order.display && order.taxByRate ? 3 : order.lines.reduce((sum, line) => sum + line.discountMinor, 0) > 0 ? 2 : 1;
67
67
  }
@@ -73,6 +73,7 @@ export function contentVersion(order: Pick<PosOrder, 'display' | 'taxByRate' | '
73
73
  * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
74
74
  * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
75
75
  * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
76
+ * Orders with Any picks (#495) need version 6 too, carrying a line's `anyAttributes`, and coupons only when they have some.
76
77
  */
77
78
  export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt = 1,
78
79
  options?: { maxVersion?: number }): OrderCreateEnvelope {
@@ -105,6 +106,7 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
105
106
  ...(lineDiscounts[i] > 0 ? { discountMinor: lineDiscounts[i] } : {}),
106
107
  ...(version === 6 && line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
107
108
  ...(version === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
109
+ ...(version === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
108
110
  })),
109
111
  ...(version >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
110
112
  clientFeeId: fee.id, name: fee.name, amountMinor: fee.amountMinor, taxStatus: fee.taxStatus,
@@ -115,7 +117,7 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
115
117
  amountMinor: charge.amountMinor, taxStatus: charge.taxStatus,
116
118
  ...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}), taxMinor: roundMicrosToMinor(BigInt(charge.taxMicros)),
117
119
  })) } : {}),
118
- ...(version === 6 ? { coupons: order.coupons!.map(({ code, couponId, discountMinor, discountTaxMinor }) => ({
120
+ ...(version === 6 && order.coupons?.length ? { coupons: order.coupons.map(({ code, couponId, discountMinor, discountTaxMinor }) => ({
119
121
  code, couponId, discountMinor, discountTaxMinor,
120
122
  })) } : {}),
121
123
  payments: order.payments.map((payment) => ({
@@ -133,7 +135,7 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
133
135
  })),
134
136
  ...(version >= 5 && order.display!.fees ? { fees: order.display!.fees.map(({ id, amountMinor }) => ({ clientFeeId: id, amountMinor })) } : {}),
135
137
  ...(version >= 5 && order.display!.shipping ? { shipping: order.display!.shipping.map(({ id, amountMinor }) => ({ clientShippingId: id, amountMinor })) } : {}),
136
- ...(version === 6 && order.display!.coupons ? { coupons: order.display!.coupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}),
138
+ ...(version === 6 && order.coupons?.length && order.display!.coupons ? { coupons: order.display!.coupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}),
137
139
  },
138
140
  taxByRate: order.taxByRate!.map(({ ratePpm, code, netMinor, amountMinor, grossMinor }) => ({
139
141
  ratePpm, ...(code !== undefined ? { code } : {}), netMinor, taxMinor: amountMinor, grossMinor,
@@ -119,6 +119,9 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
119
119
  if (order.coupons?.length && (options.capabilities?.orderCreate ?? 1) < 6) {
120
120
  throw new Error("finalize: coupons need the store to accept order.create version 6; update the store's TallyUI plugin");
121
121
  }
122
+ if (order.lineItems.some((line) => line.anyAttributes?.length) && (options.capabilities?.orderCreate ?? 1) < 6) {
123
+ throw new Error("finalize: picked options need the store to accept order.create version 6; update the store's TallyUI plugin");
124
+ }
122
125
  if (!order.lineItems.length) throw new Error('finalize: no lines');
123
126
  // Defence in depth: the builder already clamps every discount to >= 0, so this should never fire.
124
127
  if (order.discountMinor < 0
@@ -169,6 +172,7 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
169
172
  ...(line.taxStatus !== undefined ? { taxStatus: line.taxStatus } : {}),
170
173
  name: line.name, sku: line.sku, quantity: line.quantity, unitPriceMinor: line.unitPriceMinor,
171
174
  ...(line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
175
+ ...(line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
172
176
  ...(line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
173
177
  discountMinor: line.discountMinor, netMinor: line.netMinor,
174
178
  ...(order.taxRounding?.granularity === 'woocommerce' ? { netMicros: line.netMicros } : {}),
@@ -45,6 +45,7 @@ export async function reopenRefusedOrder(orderId: string, deps: {
45
45
  unitPrice: { amount: line.unitPriceMinor, currency: order.currency, taxInclusive: line.taxInclusive },
46
46
  ...(line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
47
47
  ...(line.attributes !== undefined ? { attributes: line.attributes } : {}),
48
+ ...(line.anyAttributes !== undefined ? { anyAttributes: line.anyAttributes } : {}),
48
49
  quantity: line.quantity,
49
50
  taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm })),
50
51
  ...(line.custom ? { custom: true, taxClass: line.custom.taxClass, taxStatus: line.custom.taxStatus }
@@ -27,9 +27,10 @@ import type { PosOrder } from './types';
27
27
  * and `regularUnitPriceMinor` (ADR-077 d2), and `reopenedAt`: when a refused order was reopened as a parked sale (ADR-077 d4b), and lets `sentVersion` and `downgradedFrom` be 6 (order.create version 6, ADR-077 d4), and changes nothing else.
28
28
  * `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them only at version 6.
29
29
  * Its migration is the identity. It is one-way like version 8.
30
+ * Version 10 adds a line's `anyAttributes` (#495 c/d) and changes nothing else. Its migration is the identity. It is one-way like version 9.
30
31
  */
31
32
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
32
- version: 9, primaryKey: 'id', type: 'object', additionalProperties: false,
33
+ version: 10, primaryKey: 'id', type: 'object', additionalProperties: false,
33
34
  properties: {
34
35
  id: { type: 'string', maxLength: 36 },
35
36
  saleId: { type: 'string', maxLength: 36 },
@@ -58,6 +59,7 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
58
59
  }, required: ['name', 'taxStatus'] },
59
60
  unitPriceMinor: { type: 'integer' }, discountMinor: { type: 'integer' }, netMinor: { type: 'integer' },
60
61
  attributes: { type: 'object', additionalProperties: { type: 'string' } },
62
+ anyAttributes: { type: 'array', items: { type: 'string', minLength: 1, maxLength: 255 } },
61
63
  regularUnitPriceMinor: { type: 'integer' },
62
64
  netMicros: { type: 'string', pattern: '^-?[0-9]{1,24}$', maxLength: 25 },
63
65
  taxLines: { type: 'array', items: {
@@ -179,5 +181,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
179
181
  // it means no older sale is ever re-rounded (#287).
180
182
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
181
183
  return { schema: posOrderSchema,
182
- migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity } };
184
+ migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity } };
183
185
  }
@@ -35,6 +35,8 @@ export interface PosOrderLine {
35
35
  unitPriceMinor: number;
36
36
  /** The chosen variation attributes, name to value (pos_orders v9, #495). */
37
37
  attributes?: Record<string, string>;
38
+ /** The names in attributes the cashier picked for the variant's "Any" option groups (#495); absent when none. */
39
+ anyAttributes?: string[];
38
40
  /** The catalogue's regular unit price, in the line's own tax mode like `unitPriceMinor` (pos_orders v9, ADR-077 d2). */
39
41
  regularUnitPriceMinor?: number;
40
42
  /** Line discounts plus the allocated order-discount share, in the line's own tax mode (ADR-062). */
@@ -1,3 +1,4 @@
1
1
  export { buildReceiptData } from './build-receipt-data';
2
+ export { buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder } from './reprint';
2
3
  export { RECEIPT_SCHEMA_VERSION } from './types';
3
4
  export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, ReceiptRegister, ReceiptFiscal } from './types';
@@ -0,0 +1,148 @@
1
+ import { minorUnitDigits, woocommerceTax, type StoreOrder } from '@tallyui/core';
2
+ import type { PosOrder } from '../pos-order/types';
3
+ import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
4
+ import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
5
+ import { RECEIPT_SCHEMA_VERSION } from './types';
6
+
7
+ /**
8
+ * The blocks every reprint shares with `buildReceiptData`. `fiscal.reprint_count` is this reprint's ordinal, starting
9
+ * at 1: the app passes `fiscal: { reprint_count: n }` for its n-th reprint.
10
+ */
11
+ function reprintBlocks(config: ReceiptConfig, customer: { name?: string; email?: string } | null) {
12
+ const name = customer?.name || customer?.email;
13
+ return {
14
+ schemaVersion: RECEIPT_SCHEMA_VERSION,
15
+ software: { name: 'WCPOS', plugin_version: '', app_version: '', app_build: '', platform: '', ...config.software },
16
+ register: { id: config.register ?? '', name: config.registerName ?? '' },
17
+ fiscal: { document_type: 'sale' as const, is_reprint: true, reprint_count: 1, qr_payload: '', ...config.fiscal },
18
+ header: {
19
+ storeName: config.storeName, storeAddress: config.storeAddress, cashier: config.cashier,
20
+ ...(name ? { customer: name } : {}), register: config.register,
21
+ },
22
+ };
23
+ }
24
+
25
+ const sum = (amounts: number[]) => amounts.reduce((total, amount) => total + amount, 0);
26
+
27
+ /**
28
+ * Receipt data for reprinting the till's own stored order (ADR-081). A stored order keeps no discount labels: the order discount
29
+ * is one row, `Order discount`, in the display mode when lines were converted. Without `display`, a converted line's discount is in its own mode.
30
+ */
31
+ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptConfig): ReceiptData {
32
+ const { header, ...blocks } = reprintBlocks(config, order.customer);
33
+ const { display, taxRounding: rounding } = order;
34
+ const dp = minorUnitDigits(order.currency), factor = 10 ** dp;
35
+ // A WooCommerce line's rounded gross (its builder `totalMinor`), as woocommerce-tax.ts lineAmounts computes it from
36
+ // the 6dp net and per-rate taxes, read back from the stored micros as woocommerceTotals reads them (ADR-076).
37
+ const wooGrossMinor = (line: PosOrder['lines'][number], roundAtSubtotal: boolean) => {
38
+ const tax = line.taxLines.reduce((sum, row) => sum + (roundAtSubtotal ? Number(row.taxMicros) / (factor * 1e6)
39
+ : woocommerceTax.roundTaxTotal(Number(row.taxMicros) / (factor * 1e6), dp, order.pricesIncludeTax)), 0);
40
+ return Math.round(woocommerceTax.roundHalfUp(Number(line.netMicros) / (factor * 1e6) + tax, dp) * factor);
41
+ };
42
+ const lineTaxMicros = (line: PosOrder['lines'][number]) => line.taxLines.reduce((total, row) => total + BigInt(row.taxMicros), 0n);
43
+ let taxSoFar = order.pricesIncludeTax ? 0n : order.lines.reduce((total, line) => line.taxInclusive === undefined ? total + lineTaxMicros(line) : total, 0n);
44
+ const lineTotals = order.lines.map((line) => {
45
+ if (rounding.granularity === 'woocommerce' && line.netMicros !== undefined) return order.pricesIncludeTax ? wooGrossMinor(line, rounding.roundAtSubtotal) : line.netMinor;
46
+ if (line.taxInclusive === undefined) return line.netMinor;
47
+ const share = roundMicrosToMinor(taxSoFar + lineTaxMicros(line)) - roundMicrosToMinor(taxSoFar);
48
+ taxSoFar += lineTaxMicros(line);
49
+ return line.taxInclusive ? line.netMinor - share : line.netMinor + share;
50
+ });
51
+ const lineItems = order.lines.map((line, index): ReceiptLineItem => {
52
+ const displayLine = display?.lines.find((row) => row.lineId === line.id);
53
+ const displayAmountMinor = display ? displayLine?.amountMinor ?? 0 : line.taxInclusive !== undefined ? lineTotals[index]! + line.discountMinor : line.unitPriceMinor * line.quantity;
54
+ const displayDiscounts = display
55
+ ? (displayLine?.discounts ?? []).map((d) => ({ label: d.label ?? 'Discount', amountMinor: d.amountMinor }))
56
+ : line.discountMinor > 0 ? [{ label: 'Discount', amountMinor: line.discountMinor }] : [];
57
+ return {
58
+ name: line.name,
59
+ ...(line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
60
+ sku: line.sku,
61
+ quantity: line.quantity,
62
+ unitPriceMinor: line.unitPriceMinor,
63
+ lineTotalMinor: lineTotals[index]!,
64
+ ...(line.discountMinor > 0 ? { discountMinor: line.discountMinor } : {}),
65
+ displayAmountMinor,
66
+ displayDiscounts,
67
+ };
68
+ });
69
+ // Without taxByRate (finalized below order.create v3), the rows are computed as buildReceiptData computes them. A line's
70
+ // taxInclusive is stored only when it differs from the order's mode; WooCommerce lines take the order's, as there.
71
+ const taxedLines = [...order.lines.map((line) => ({ ...line, taxInclusive: order.taxRounding.granularity === 'woocommerce'
72
+ && line.netMicros !== undefined ? order.pricesIncludeTax : line.taxInclusive ?? order.pricesIncludeTax })),
73
+ ...[...(order.fees ?? []), ...(order.shipping ?? [])].map((charge) => ({ ...charge, taxInclusive: order.pricesIncludeTax }))];
74
+ const taxLines = order.taxByRate ? order.taxByRate.map((row) => ({
75
+ label: config.taxLabels?.[row.ratePpm] ?? row.label ?? `Tax ${row.ratePpm / 10000}%`, code: row.code, ratePpm: row.ratePpm, amountMinor: row.amountMinor,
76
+ })) : taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding)
77
+ .map(({ label, code, ratePpm, amountMinor }) => ({ label, code, ratePpm, amountMinor }));
78
+ const charges = (rows: Array<{ name: string; amountMinor: number }> | undefined) =>
79
+ (rows ?? []).map(({ name, amountMinor }) => ({ name, amountMinor }));
80
+
81
+ return {
82
+ ...blocks,
83
+ header: { ...header, orderNumber: order.serverRefs?.displayId ?? order.id, date: order.createdAt },
84
+ lineItems,
85
+ discounts: display && display.orderDiscountMinor > 0 ? [{ label: 'Order discount', amountMinor: display.orderDiscountMinor }] : [],
86
+ fees: charges(display ? display.fees : order.fees),
87
+ shipping: charges(display ? display.shipping : order.shipping),
88
+ orderDiscountMinor: display ? display.orderDiscountMinor : 0,
89
+ totals: display
90
+ ? {
91
+ taxInclusive: display.taxInclusive, subtotalMinor: display.subtotalMinor, discountMinor: display.discountMinor,
92
+ taxLines, taxMinor: display.taxMinor, totalMinor: display.totalMinor,
93
+ }
94
+ : {
95
+ taxInclusive: order.pricesIncludeTax,
96
+ subtotalMinor: sum(lineItems.map((line) => line.displayAmountMinor)),
97
+ discountMinor: sum(order.lines.map((line) => line.discountMinor)),
98
+ taxLines, taxMinor: order.taxMinor, totalMinor: order.totalMinor,
99
+ },
100
+ payments: order.payments.map((p) => ({ method: p.method, amountMinor: p.tenderedMinor ?? p.amountMinor, reference: p.reference })),
101
+ changeDueMinor: sum(order.payments.map((p) => p.changeMinor ?? 0)),
102
+ footer: { note: order.note || undefined, barcode: order.id },
103
+ currency: order.currency,
104
+ };
105
+ }
106
+
107
+ /** Receipt data for reprinting an order read from the store with `getOrders`/`listOrders` (ADR-081). */
108
+ export function buildReceiptDataFromStoreOrder(order: StoreOrder, config: ReceiptConfig): ReceiptData {
109
+ const { header, ...blocks } = reprintBlocks(config, order.customer);
110
+ const gross = (net: number, tax: number) => order.pricesIncludeTax ? net + tax : net;
111
+ const lineItems = order.lines.map((line): ReceiptLineItem => {
112
+ const displayAmountMinor = gross(line.subtotalMinor, line.subtotalTaxMinor);
113
+ const lineTotalMinor = gross(line.totalMinor, line.taxMinor);
114
+ const discount = displayAmountMinor - lineTotalMinor;
115
+ return {
116
+ name: line.name,
117
+ sku: line.sku ?? '',
118
+ quantity: line.quantity,
119
+ unitPriceMinor: line.quantity === 0 ? 0 : Math.round(displayAmountMinor / line.quantity),
120
+ lineTotalMinor,
121
+ ...(discount > 0 ? { discountMinor: discount } : {}),
122
+ displayAmountMinor,
123
+ displayDiscounts: discount > 0 ? [{ label: 'Discount', amountMinor: discount }] : [],
124
+ };
125
+ });
126
+ const charges = (rows: StoreOrder['fees']) => rows.map(({ name, totalMinor, taxMinor }) => ({ name, amountMinor: gross(totalMinor, taxMinor) }));
127
+
128
+ return {
129
+ ...blocks,
130
+ header: { ...header, orderNumber: order.reference, date: order.placedAt },
131
+ lineItems,
132
+ discounts: order.coupons.map(({ code, discountMinor, discountTaxMinor }) => ({ label: code, amountMinor: gross(discountMinor, discountTaxMinor) })),
133
+ fees: charges(order.fees),
134
+ shipping: charges(order.shipping),
135
+ orderDiscountMinor: 0,
136
+ totals: {
137
+ taxInclusive: order.pricesIncludeTax,
138
+ subtotalMinor: sum(lineItems.map((line) => line.displayAmountMinor)),
139
+ discountMinor: sum(lineItems.map((line) => line.discountMinor ?? 0)),
140
+ taxLines: order.taxLines.map(({ label, code, ratePpm, amountMinor }) => ({ label, ...(code !== undefined ? { code } : {}), ratePpm, amountMinor })),
141
+ taxMinor: order.taxMinor, totalMinor: order.totalMinor,
142
+ },
143
+ payments: order.payments.map((p) => ({ method: p.kind ?? p.title ?? p.method, amountMinor: p.amountMinor })),
144
+ changeDueMinor: 0,
145
+ footer: { barcode: order.reference },
146
+ currency: order.currency,
147
+ };
148
+ }
package/src/sale/cart.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { resolvePrice, type ProductTraits } from '@tallyui/core';
2
2
  import type { OrderBuilder } from '../order';
3
- import { regularUnitPriceMinor } from '../order/order-builder';
3
+ import { regularUnitPriceMinor, samePicks } from '../order/order-builder';
4
4
  import type { CatalogueEntry } from './catalogue';
5
5
 
6
6
  export class CartError extends Error {}
@@ -8,7 +8,18 @@ export class CartError extends Error {}
8
8
  export function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry<Doc>,
9
9
  traits: ProductTraits<Doc>, currency: string): string {
10
10
  const { product, variant } = entry;
11
- const existing = builder.getSnapshot().lineItems.find((line) => line.variantId === variant.id);
11
+ const picks = entry.picks ?? {};
12
+ const groups = Object.keys(picks).length ? traits.getVariantOptions?.(product) ?? [] : [];
13
+ // Only a local group (no id) the variant leaves as "Any" can be picked, and only with one of its values (#495).
14
+ const position = (name: string) => groups.findIndex((group) => group.id === undefined && group.name === name);
15
+ for (const [name, value] of Object.entries(picks)) {
16
+ const group = groups[position(name)];
17
+ if (!group || Object.keys(variant.options ?? {}).includes(name)) throw new CartError(`${name} is not an option to choose for this item`);
18
+ if (typeof value !== 'string' || !value || !group.values.includes(value)) throw new CartError(`${value} is not a choice for ${name}`);
19
+ }
20
+ const anyAttributes = Object.keys(picks).sort((a, b) => position(a) - position(b));
21
+ const attributes = { ...variant.options, ...Object.fromEntries(anyAttributes.map((name) => [name, picks[name]])) };
22
+ const existing = builder.getSnapshot().lineItems.find((line) => line.variantId === variant.id && samePicks(line, { anyAttributes, attributes }));
12
23
  if (existing) {
13
24
  builder.updateQuantity(existing.id, existing.quantity + 1);
14
25
  return existing.id;
@@ -19,7 +30,8 @@ export function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry
19
30
  const unitPrice = resolved.current, regularPrice = regularUnitPriceMinor(resolved);
20
31
  return builder.addLine({
21
32
  productId: traits.getId(product), variantId: variant.id, name,
22
- ...(variant.options && Object.keys(variant.options).length ? { attributes: variant.options } : {}),
33
+ ...(Object.keys(attributes).length ? { attributes } : {}),
34
+ ...(anyAttributes.length ? { anyAttributes } : {}),
23
35
  sku: variant.sku ?? '', imageUrl: traits.getImageUrl?.(product), unitPrice,
24
36
  ...(regularPrice !== undefined ? { regularUnitPriceMinor: regularPrice } : {}),
25
37
  taxClass: traits.getTaxClass?.(product, variant.id),
@@ -1,7 +1,11 @@
1
1
  import { findVariantByCode, formatMoney, resolvePrice } from '@tallyui/core';
2
2
  import type { ProductTraits, TraitContext, VariantSummary } from '@tallyui/core';
3
3
 
4
- export type CatalogueEntry<Doc> = { product: Doc; variant: VariantSummary };
4
+ export type CatalogueEntry<Doc> = {
5
+ product: Doc; variant: VariantSummary;
6
+ /** The cashier's value for each of the variant's local "Any" option groups, group name to value (#495). */
7
+ picks?: Record<string, string>;
8
+ };
5
9
 
6
10
  /** Variants in product/variant order, passing context through; without getVariants,
7
11
  * simple products use their own traits and products with variants contribute no entries. */