@tallyui/pos 3.20.1 → 4.0.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.
Files changed (117) hide show
  1. package/dist/index.d.ts +1005 -110
  2. package/dist/index.js +3156 -907
  3. package/package.json +6 -6
  4. package/src/app-settings/app-settings.ts +77 -0
  5. package/src/app-settings/index.ts +2 -0
  6. package/src/currency/currency-provider.tsx +5 -7
  7. package/src/currency/index.ts +1 -1
  8. package/src/customer/customer-patch.ts +70 -0
  9. package/src/customer-display/display-client.ts +11 -17
  10. package/src/customer-display/display-link.ts +10 -5
  11. package/src/customer-display/index.ts +3 -1
  12. package/src/customer-display/protocol.ts +1 -1
  13. package/src/customer-display/sale-display.ts +6 -8
  14. package/src/customer-display/snapshot-fallback.ts +14 -1
  15. package/src/customer-display/till-device.ts +62 -0
  16. package/src/customer-display/till-display-service.ts +44 -42
  17. package/src/customer-display/till-pairing.ts +20 -23
  18. package/src/customer-display/use-customer-display.ts +2 -1
  19. package/src/customer-display/use-till-pairing.ts +4 -4
  20. package/src/index.ts +37 -18
  21. package/src/order/allocate-order-discount.ts +5 -17
  22. package/src/order/apportion.ts +29 -0
  23. package/src/order/from-store-order.ts +115 -0
  24. package/src/order/index.ts +1 -0
  25. package/src/order/order-builder.ts +239 -52
  26. package/src/order/order-drafts.ts +45 -6
  27. package/src/order/order-manager.ts +2 -1
  28. package/src/order/tax-ids.ts +27 -0
  29. package/src/order/types.ts +59 -5
  30. package/src/order/woocommerce-tax.ts +9 -0
  31. package/src/outbox/index.ts +1 -1
  32. package/src/outbox/order-outbox.ts +138 -43
  33. package/src/outbox/register-outbox.ts +4 -3
  34. package/src/outbox/retry-delay.ts +8 -0
  35. package/src/outbox/use-order-outbox.ts +8 -2
  36. package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
  37. package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
  38. package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
  39. package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
  40. package/src/pos-order/attention-handled.ts +24 -0
  41. package/src/pos-order/command.ts +132 -12
  42. package/src/pos-order/extras-delivery.ts +14 -0
  43. package/src/pos-order/finalize.ts +138 -29
  44. package/src/pos-order/index.ts +7 -3
  45. package/src/pos-order/money-divergence.ts +19 -0
  46. package/src/pos-order/needs-attention.ts +9 -1
  47. package/src/pos-order/refund-due.ts +35 -0
  48. package/src/pos-order/reopen.ts +96 -12
  49. package/src/pos-order/schema.ts +35 -10
  50. package/src/pos-order/till-payments.ts +4 -0
  51. package/src/pos-order/types.ts +44 -5
  52. package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
  53. package/src/print/escpos/commands.ts +79 -0
  54. package/src/print/escpos/drawer.ts +25 -0
  55. package/src/print/escpos/encode.ts +1 -0
  56. package/src/print/escpos/index.ts +6 -1
  57. package/src/print/escpos/network-sinks.ts +130 -0
  58. package/src/print/escpos/render-escpos.ts +155 -0
  59. package/src/print/escpos/transport.ts +2 -1
  60. package/src/print/index.ts +5 -2
  61. package/src/print/resolve-printer.ts +46 -0
  62. package/src/print/types.ts +1 -1
  63. package/src/product/index.ts +2 -0
  64. package/src/product/terms.ts +42 -0
  65. package/src/product/tile-fields.ts +27 -0
  66. package/src/receipt/build-receipt-data.ts +12 -7
  67. package/src/receipt/carried-rows.ts +29 -0
  68. package/src/receipt/index.ts +1 -0
  69. package/src/receipt/reprint.ts +14 -8
  70. package/src/receipt/types.ts +3 -1
  71. package/src/receipt-template/default-templates.ts +3 -0
  72. package/src/receipt-template/template-data.ts +3 -0
  73. package/src/receipt-template/wcpos/build.ts +1 -0
  74. package/src/receipt-template/wcpos/format.ts +2 -2
  75. package/src/receipt-template/wcpos/from-orders.ts +6 -2
  76. package/src/receipt-template/wcpos/types.ts +5 -1
  77. package/src/register/closure-document.ts +42 -4
  78. package/src/register/closure-rows.ts +3 -2
  79. package/src/register/document-labels.ts +25 -0
  80. package/src/register/expected.ts +49 -10
  81. package/src/register/index.ts +5 -5
  82. package/src/register/money.ts +23 -0
  83. package/src/register/register-adoption.ts +6 -5
  84. package/src/register/register-commands.ts +4 -3
  85. package/src/register/schemas.ts +11 -3
  86. package/src/register/session-store.ts +44 -23
  87. package/src/register/settled-figures.ts +5 -19
  88. package/src/register/use-register-session.ts +18 -19
  89. package/src/reopen/index.ts +3 -0
  90. package/src/reopen/reopen-entry.ts +48 -0
  91. package/src/reopen/reopen-store-order.ts +78 -0
  92. package/src/reopen/send-order-reopen.ts +61 -0
  93. package/src/reports/adapters.ts +15 -7
  94. package/src/reports/sales-figures.ts +15 -1
  95. package/src/reports/types.ts +2 -0
  96. package/src/sale/cart.ts +4 -2
  97. package/src/sale/index.ts +1 -1
  98. package/src/sale/open-sales.ts +3 -0
  99. package/src/sale/use-sale.ts +388 -83
  100. package/src/sale/woocommerce/coupon-refetch.ts +1 -0
  101. package/src/sale/woocommerce/coupon-source.ts +4 -4
  102. package/src/sale/woocommerce/coupons.ts +6 -0
  103. package/src/sale/woocommerce/discount-codes.ts +1 -6
  104. package/src/scanner/analyze-trace.ts +86 -0
  105. package/src/scanner/device-scanner.ts +57 -0
  106. package/src/scanner/hid-scanner.ts +14 -41
  107. package/src/scanner/index.ts +2 -0
  108. package/src/scanner/serial-scanner.ts +15 -42
  109. package/src/scanner/use-barcode-scanner.ts +107 -5
  110. package/src/scanner/wedge-detector.ts +33 -15
  111. package/src/tax/exact.ts +1 -13
  112. package/src/tax/taxed-lines.ts +26 -0
  113. package/src/tender/index.ts +6 -1
  114. package/src/tender/split-units.ts +109 -0
  115. package/src/tender/tender-figures.ts +114 -0
  116. package/src/tender/tender-state.ts +105 -17
  117. package/src/currency/format-money-with.ts +0 -45
@@ -0,0 +1,95 @@
1
+ {
2
+ "id": "019f8f66-7800-7000-8000-000000000004",
3
+ "type": "order.create",
4
+ "version": 12,
5
+ "createdAt": "2026-11-19T10:00:00.000Z",
6
+ "deviceId": "device_golden",
7
+ "attempt": 1,
8
+ "payload": {
9
+ "clientOrderId": "019f8f66-7800-7000-8000-000000000001",
10
+ "createdAt": "2026-11-19T10:00:00.000Z",
11
+ "currency": "EUR",
12
+ "pricesIncludeTax": true,
13
+ "lines": [
14
+ {
15
+ "clientLineId": "019f8f66-7800-7000-8000-000000000002",
16
+ "variantId": "p",
17
+ "title": "Coffee",
18
+ "sku": "COF-1-EDIT",
19
+ "quantity": 1,
20
+ "unitPriceMinor": 1190
21
+ }
22
+ ],
23
+ "payments": [
24
+ {
25
+ "clientPaymentId": "019f8f66-7800-7000-8000-000000000003",
26
+ "method": "cash",
27
+ "amountMinor": 1190,
28
+ "tenderedMinor": 1190,
29
+ "changeMinor": 0
30
+ }
31
+ ],
32
+ "subtotalMinor": 1000,
33
+ "taxMinor": 190,
34
+ "totalMinor": 1190,
35
+ "display": {
36
+ "currency": "EUR",
37
+ "exponent": 2,
38
+ "taxInclusive": true,
39
+ "subtotalMinor": 1190,
40
+ "discountMinor": 0,
41
+ "taxMinor": 190,
42
+ "totalMinor": 1190,
43
+ "lines": [
44
+ {
45
+ "clientLineId": "019f8f66-7800-7000-8000-000000000002",
46
+ "amountMinor": 1190,
47
+ "discounts": []
48
+ }
49
+ ],
50
+ "orderDiscountMinor": 0
51
+ },
52
+ "taxByRate": [
53
+ {
54
+ "ratePpm": 190000,
55
+ "netMinor": 1000,
56
+ "taxMinor": 190,
57
+ "grossMinor": 1190
58
+ }
59
+ ],
60
+ "customer": {
61
+ "email": "ann@example.com",
62
+ "customerId": "42",
63
+ "billing": {
64
+ "firstName": "Ann",
65
+ "lastName": "Lee",
66
+ "address1": "1 State St",
67
+ "city": "Albany",
68
+ "state": "NY",
69
+ "postcode": "12207",
70
+ "country": "US"
71
+ },
72
+ "taxIds": [
73
+ {
74
+ "type": "eu_vat",
75
+ "value": "DE123456789",
76
+ "country": "DE"
77
+ },
78
+ {
79
+ "type": "us_ein",
80
+ "value": "12-3456789"
81
+ }
82
+ ]
83
+ },
84
+ "meta": [
85
+ {
86
+ "key": "po_number",
87
+ "value": "PO-1"
88
+ },
89
+ {
90
+ "key": "gift_message",
91
+ "value": ""
92
+ }
93
+ ]
94
+ }
95
+ }
@@ -0,0 +1,89 @@
1
+ {
2
+ "id": "019f6d2e-7800-7000-8000-000000000004",
3
+ "type": "order.create",
4
+ "version": 9,
5
+ "createdAt": "2026-11-12T10:00:00.000Z",
6
+ "deviceId": "device_golden",
7
+ "attempt": 1,
8
+ "payload": {
9
+ "clientOrderId": "019f6d2e-7800-7000-8000-000000000001",
10
+ "createdAt": "2026-11-12T10:00:00.000Z",
11
+ "currency": "EUR",
12
+ "pricesIncludeTax": true,
13
+ "lines": [
14
+ {
15
+ "clientLineId": "019f6d2e-7800-7000-8000-000000000002",
16
+ "variantId": "p",
17
+ "title": "p",
18
+ "quantity": 1,
19
+ "unitPriceMinor": 1190,
20
+ "discountMinor": 100
21
+ }
22
+ ],
23
+ "coupons": [
24
+ {
25
+ "code": "c",
26
+ "couponId": "promo_1",
27
+ "discountMinor": 84,
28
+ "discountTaxMinor": 16,
29
+ "lines": [
30
+ {
31
+ "clientLineId": "019f6d2e-7800-7000-8000-000000000002",
32
+ "discountMinor": 84,
33
+ "discountTaxMinor": 16
34
+ }
35
+ ]
36
+ }
37
+ ],
38
+ "payments": [
39
+ {
40
+ "clientPaymentId": "019f6d2e-7800-7000-8000-000000000003",
41
+ "method": "cash",
42
+ "amountMinor": 971,
43
+ "tenderedMinor": 971,
44
+ "changeMinor": 0
45
+ }
46
+ ],
47
+ "subtotalMinor": 816,
48
+ "discountMinor": 100,
49
+ "taxMinor": 155,
50
+ "totalMinor": 971,
51
+ "display": {
52
+ "currency": "EUR",
53
+ "exponent": 2,
54
+ "taxInclusive": true,
55
+ "subtotalMinor": 1190,
56
+ "discountMinor": 219,
57
+ "taxMinor": 155,
58
+ "totalMinor": 971,
59
+ "lines": [
60
+ {
61
+ "clientLineId": "019f6d2e-7800-7000-8000-000000000002",
62
+ "amountMinor": 1190,
63
+ "discounts": [
64
+ {
65
+ "discountId": "discount_line",
66
+ "amountMinor": 119
67
+ }
68
+ ]
69
+ }
70
+ ],
71
+ "orderDiscountMinor": 0,
72
+ "coupons": [
73
+ {
74
+ "code": "c",
75
+ "amountMinor": 100
76
+ }
77
+ ]
78
+ },
79
+ "taxByRate": [
80
+ {
81
+ "ratePpm": 190000,
82
+ "netMinor": 816,
83
+ "taxMinor": 155,
84
+ "grossMinor": 971
85
+ }
86
+ ],
87
+ "customer": null
88
+ }
89
+ }
@@ -0,0 +1,24 @@
1
+ import type { RxCollection } from 'rxdb';
2
+ import type { PosOrder } from './types';
3
+
4
+ /**
5
+ * Marks the order `orderId` handled for its current `commandId`, so `needsAttention` leaves it out until a requeue
6
+ * mints a new one (ADR-092 6f, tally-woo 03). Resolves to true when the order is stamped (or already was, for this
7
+ * commandId); false, with nothing changed, when the id is unknown or the order is pending (still the outbox's to settle).
8
+ */
9
+ export async function markAttentionHandled(orders: RxCollection<PosOrder>, orderId: string, now?: () => Date): Promise<boolean> {
10
+ const doc = await orders.findOne(orderId).exec();
11
+ if (!doc) return false;
12
+ let stamped = false;
13
+ // pos_orders is till-local, never pulled from a store, so this write breaks no replication rule (ADR-092 6f).
14
+ // Decide on the stored state, as discard() does: a requeue that won the race leaves its pending order unstamped.
15
+ await doc.incrementalModify((data) => {
16
+ // The modifier runs again on a write conflict, so it decides on each run.
17
+ stamped = data.syncStatus !== 'pending';
18
+ if (!stamped || data.attentionHandledFor === data.commandId) return data;
19
+ data.attentionHandledFor = data.commandId;
20
+ data.updatedAt = (now?.() ?? new Date()).toISOString();
21
+ return data;
22
+ });
23
+ return stamped;
24
+ }
@@ -1,9 +1,17 @@
1
- import type { OrderCreateEnvelope } from '@tallyui/core';
1
+ import { ORDER_META_KEY_MAX, ORDER_META_MAX, ORDER_NOTE_MAX, ORDER_TAX_ID_TYPE_MAX, ORDER_TAX_ID_VALUE_MAX, ORDER_TAX_IDS_MAX } from '@tallyui/core';
2
+ import type { OrderCreateEnvelope, OrderCreateMeta, OrderCreatePayload, OrderCreateTaxId, OrderUpdateEnvelope, OrderUpdatePayload } from '@tallyui/core';
2
3
  import { MICROS_PER_MINOR, roundMicrosToMinor, taxMicros } from '../tax/exact';
4
+ import { woocommerceChargeTaxMinor } from '../order/woocommerce-tax';
3
5
  import type { PosOrder, PosOrderLine } from './types';
4
6
 
5
7
  /** The highest order.create version this till sends; pos_orders' sentVersion and downgradedFrom maxima must equal it. */
6
- export const ORDER_CREATE_MAX_VERSION = 8 as const;
8
+ export const ORDER_CREATE_MAX_VERSION = 12 as const;
9
+ /** order.create 10 (ruling A, 2026-11-18) is 9 plus each payment's `methodId`, the payment method's own id on the platform. */
10
+ export const PAYMENT_METHOD_ID_ORDER_CREATE_VERSION = 10 as const;
11
+ /** order.create 11 (ADR-086 d2, amended 2026-11-19) is 10 plus the customer's addresses on a sale not taxed by address, as informational fields. */
12
+ export const UNTAXED_ADDRESS_ORDER_CREATE_VERSION = 11 as const;
13
+ /** order.create 12 (ADR-092) is 11 plus the customer's tax ids, a catalogue line's edited SKU and order meta, as informational fields. */
14
+ export const INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION = 12 as const;
7
15
  /** order.create 8 (#722) tells the server which customer address the sale was taxed on (`taxAddress`) and carries the
8
16
  * addresses; below it a server taxes on the store's base, so `saleTaxContexts` re-taxes by address only from here. */
9
17
  export const TAX_ADDRESS_ORDER_CREATE_VERSION = 8 as const;
@@ -22,6 +30,12 @@ export class UnsupportedOrderVersionError extends Error {
22
30
  */
23
31
  export const PAYLOAD_STRING_MAX = 255;
24
32
 
33
+ /** A store revision's bound (ADR-090): an opaque token, e.g. WooCommerce's 71-character `sha256:` + 64 hex. One number for core's order.reopen and order.update shapes, the rebuild and pos_orders. */
34
+ export const REVISION_MAX = 128;
35
+
36
+ /** order.update's lowest order.create version (ADR-090, desk Q1 2026-11-17): fees and shipping travel from 5, so an update never drops the store's. */
37
+ const ORDER_UPDATE_MIN_CREATE_VERSION = 5;
38
+
25
39
  /** A non-empty string of at most `max` UTF-16 units with no NUL: what order.create's shape check accepts. */
26
40
  export const sendable = (value: unknown, max: number): value is string =>
27
41
  typeof value === 'string' && value.length > 0 && value.length <= max && !value.includes('\u0000');
@@ -46,6 +60,25 @@ export function cutText(text: string, max: number): string {
46
60
  return `${clean.slice(0, high >= 0xd800 && high <= 0xdbff ? max - 2 : max - 1)}…`;
47
61
  }
48
62
 
63
+ // What order.create 12's shape check accepts (order-payload-shape.ts); a bad entry is dropped, not sent, so one bad extra never holds the sale (desk, F1054-1).
64
+ export function sendableTaxIds(taxIds: readonly OrderCreateTaxId[] | undefined): OrderCreateTaxId[] {
65
+ return (taxIds ?? []).flatMap(({ type, value, country }) => {
66
+ const id = { type: cutText(type, ORDER_TAX_ID_TYPE_MAX), value: cutText(value, ORDER_TAX_ID_VALUE_MAX) };
67
+ const code = country?.toUpperCase();
68
+ return id.type && id.value ? [{ ...id, ...(code !== undefined && /^[A-Z]{2}$/.test(code) ? { country: code } : {}) }] : [];
69
+ }).slice(0, ORDER_TAX_IDS_MAX);
70
+ }
71
+ export function sendableMeta(meta: readonly OrderCreateMeta[] | undefined): OrderCreateMeta[] {
72
+ const kept = new Set<string>();
73
+ return (meta ?? []).flatMap((entry) => {
74
+ const key = cutText(entry.key, ORDER_META_KEY_MAX);
75
+ if (!key || key.startsWith('_') || kept.has(key)) return [];
76
+ kept.add(key);
77
+ return [{ key, value: cutText(entry.value, ORDER_NOTE_MAX) }];
78
+ }).slice(0, ORDER_META_MAX);
79
+ }
80
+ export const editedSku = (line: PosOrderLine) => !line.custom && line.catalogueSku !== undefined && line.sku !== '' && line.sku !== line.catalogueSku;
81
+
49
82
  /**
50
83
  * Version 4 (#286): a line's discount made tax-exclusive. An exclusive line's is unchanged; an inclusive line's
51
84
  * gross discount D on its amount A becomes `net(A) − net(A − D)`, exact in millionths, rounded half away from zero.
@@ -67,7 +100,8 @@ function netDiscountMinor(line: PosOrderLine, pricesIncludeTax: boolean, woocomm
67
100
  * 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.
68
101
  */
69
102
  export function contentVersion(order: Pick<PosOrder, 'display' | 'taxByRate' | 'lines' | 'fees' | 'shipping' | 'coupons'>): 1 | 2 | 3 | 5 | 6 {
70
- if (order.coupons?.length || order.lines.some((line) => line.anyAttributes?.length)) return 6;
103
+ const redeemable = order.coupons?.filter((coupon) => !coupon.carried);
104
+ if (redeemable?.length || order.lines.some((line) => line.anyAttributes?.length)) return 6;
71
105
  if (order.fees?.length || order.shipping?.length || order.lines.some((line) => line.custom)) return 5;
72
106
  return order.display && order.taxByRate ? 3 : order.lines.reduce((sum, line) => sum + line.discountMinor, 0) > 0 ? 2 : 1;
73
107
  }
@@ -93,17 +127,30 @@ function wireNote(note: string | undefined): string | undefined {
93
127
  * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
94
128
  * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
95
129
  * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
130
+ * A carried coupon (`carried`) is never sent as a coupon; its line shares go in the line discounts and its display row in `display.orderDiscountMinor`, and it needs version 4.
96
131
  * A sale with a note goes as version 7 when capped at 7 or more and it has figures; otherwise the note is not sent.
97
132
  * A sale taxed on the customer's address (`taxAddress`, #722) needs version 8 and never downgrades: below 8 the server
98
133
  * taxes on the base, so a lower cap throws UnsupportedOrderVersionError(8). At 8 it carries the note, `taxAddress` and
99
134
  * the stored addresses; every other field follows the version its content makes, as at 7.
135
+ * Version 9 sends every coupon's stored line shares when the cap allows it, keeping notes and any tax address.
136
+ * Version 10 is 9 plus each payment's `methodId`: only at a cap of 10 or more, for an order with figures (4+) whose coupons all have lines and a leg with an id.
137
+ * Version 11 is 10 plus the customer's addresses on a sale with no `taxAddress`: only at a cap of 11 or more, for an order with figures (4+) whose coupons all have lines; otherwise they are dropped.
138
+ * Version 12 is 11 plus the customer's tax ids (without `label`), order meta and a catalogue line's edited `sku` (ADR-092): only at a cap of 12 or more, for an order with figures (4+) whose coupons all have lines; otherwise they are dropped.
100
139
  * Orders with Any picks (#495) need version 6 too, carrying a line's `anyAttributes`, and coupons only when they have some.
140
+ * A reopened sale (`storeOrderId`) throws: it goes as `order.update` (`toOrderUpdateEnvelope`).
101
141
  */
102
142
  export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt = 1,
103
143
  options?: { maxVersion?: number }): OrderCreateEnvelope {
144
+ if (order.storeOrderId !== undefined) throw new Error(`Order ${order.id} reopened store order ${order.storeOrderId}: it is sent as order.update, never order.create (ADR-090)`);
145
+ return createEnvelope(order, deviceId, attempt, options);
146
+ }
147
+
148
+ function createEnvelope(order: PosOrder, deviceId: string, attempt: number, options?: { maxVersion?: number }, floor?: 5): OrderCreateEnvelope {
149
+ const redeemable = (order.coupons ?? []).filter((coupon) => !coupon.carried), carried = (order.coupons ?? []).filter((coupon) => coupon.carried);
104
150
  const grossMinor = order.lines.reduce((sum, line) => sum + line.discountMinor, 0);
105
151
  const content = contentVersion(order);
106
152
  const cap = options?.maxVersion === undefined ? order.sentVersion : Math.min(options.maxVersion, order.sentVersion ?? options.maxVersion);
153
+ if (floor !== undefined && cap !== undefined && cap < floor) throw new UnsupportedOrderVersionError(floor, cap);
107
154
  if (content === 5 && cap !== undefined && cap < 5) throw new UnsupportedOrderVersionError(5, cap);
108
155
  if (content === 6 && cap !== undefined && cap < 6) throw new UnsupportedOrderVersionError(6, cap);
109
156
  if (grossMinor > 0 && cap !== undefined && cap < 2) throw new UnsupportedOrderVersionError(2, cap);
@@ -112,15 +159,36 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
112
159
  throw new UnsupportedOrderVersionError(TAX_ADDRESS_ORDER_CREATE_VERSION, cap);
113
160
  }
114
161
  // Version 4 only when the cap allows it (the server advertises 4, and no sentVersion holds the order lower).
115
- const base = (content === 3 && cap !== undefined && cap >= 4 ? 4
162
+ const base = Math.max(floor ?? 1, content === 3 && cap !== undefined && cap >= 4 ? 4
116
163
  : Math.min(content, cap ?? content)) as 1 | 2 | 3 | 4 | 5 | 6;
164
+ if (carried.length && base < 4) throw new UnsupportedOrderVersionError(4, cap ?? base);
117
165
  // Version 7 (ADR-083) is 6 plus the note: only for a sale with one, with figures (3+), when the cap allows 7.
118
166
  // Every other field follows `base`, so a note changes nothing else in the payload.
119
167
  const note = wireNote(order.note);
120
168
  if (taxAddress && base < 3) throw new Error(`Order ${order.id} is taxed on the customer's ${taxAddress} address but has no figures`);
121
- const version = (taxAddress ? TAX_ADDRESS_ORDER_CREATE_VERSION
169
+ const couponLines = !!redeemable.length && redeemable.every((coupon) => coupon.lines !== undefined);
170
+ // Version 10 is 9 plus each payment's methodId: only when the cap allows 10, the payload has figures (net discounts, 4+),
171
+ // every coupon carries its lines (10 sends them as 9 does), and a leg has an id. Otherwise the version is today's and no id is sent.
172
+ const methodIds = cap !== undefined && cap >= PAYMENT_METHOD_ID_ORDER_CREATE_VERSION && base >= 4
173
+ && (!redeemable.length || couponLines) && order.payments.some((payment) => payment.methodId !== undefined);
174
+ // Version 11 is 10 plus the customer's addresses on a sale not taxed by address (ADR-086 d2, amended 2026-11-19):
175
+ // only when the cap allows 11 and the payload meets 10's own requirements; otherwise the addresses are dropped and the bytes are today's.
176
+ const untaxedAddresses = !taxAddress && !!(order.customer?.billing || order.customer?.shipping)
177
+ && cap !== undefined && cap >= UNTAXED_ADDRESS_ORDER_CREATE_VERSION && base >= 4 && (!redeemable.length || couponLines);
178
+ // Version 12 is 11 plus tax ids, meta and a catalogue line's edited SKU (ADR-092), on the same terms; otherwise none of them is sent.
179
+ const sentTaxIds = sendableTaxIds(order.customer?.taxIds), sentMeta = sendableMeta(order.meta);
180
+ const extras = !!(sentTaxIds.length || sentMeta.length || order.lines.some(editedSku))
181
+ && cap !== undefined && cap >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && base >= 4 && (!redeemable.length || couponLines);
182
+ const version = (extras ? 12 : untaxedAddresses ? 11 : methodIds ? 10 : couponLines && base === 6 && cap !== undefined && cap >= 9 ? 9 : taxAddress ? TAX_ADDRESS_ORDER_CREATE_VERSION
122
183
  : note && base >= 3 && cap !== undefined && cap >= 7 ? 7 : base) as OrderCreateEnvelope['version'];
184
+ const withTaxAddress = version === 8 || (version >= 9 && taxAddress !== undefined);
185
+ const withAddresses = withTaxAddress || version >= UNTAXED_ADDRESS_ORDER_CREATE_VERSION;
186
+ const taxIds = version >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && sentTaxIds.length ? { taxIds: sentTaxIds } : undefined;
123
187
  const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order.pricesIncludeTax, order.taxRounding?.granularity === 'woocommerce') : line.discountMinor);
188
+ for (const coupon of carried) {
189
+ if (!coupon.lines) throw new Error(`Order ${order.id}: a carried coupon has no line shares`);
190
+ for (const [i, line] of order.lines.entries()) lineDiscounts[i] += coupon.lines.find(({ lineId }) => lineId === line.id)?.discountMinor ?? 0;
191
+ }
124
192
  // The order's discount is the sum of its lines', on one basis, so the payload's two always agree.
125
193
  const discountMinor = lineDiscounts.reduce((sum, discount) => sum + discount, 0);
126
194
  const email = order.customer?.email;
@@ -129,14 +197,16 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
129
197
  const customerId = typeof id === 'string' && id.length > 0 && id.length <= 64 ? id : undefined;
130
198
  const sessionId = order.sessionId ?? order.lateSessionId;
131
199
  const { billing, shipping } = order.customer ?? {};
132
- const addresses = version === 8 ? { ...(billing ? { billing: { ...billing } } : {}), ...(shipping ? { shipping: { ...shipping } } : {}) } : {};
200
+ const addresses = withAddresses ? { ...(billing ? { billing: { ...billing } } : {}), ...(shipping ? { shipping: { ...shipping } } : {}) } : {};
133
201
  const { fees: _fees, shipping: _shipping, coupons: _coupons, ...storedDisplay } = { ...order.display! };
202
+ const displayCoupons = carried.length ? _coupons?.filter(({ code }) => redeemable.some((coupon) => coupon.code === code)) : _coupons;
134
203
  return {
135
204
  id: order.commandId, type: 'order.create', version, createdAt: order.createdAt, deviceId, attempt,
136
205
  payload: {
137
206
  clientOrderId: order.id, createdAt: order.createdAt, currency: order.currency, pricesIncludeTax: order.pricesIncludeTax,
138
207
  lines: order.lines.map((line, i) => ({
139
208
  clientLineId: line.id, ...(line.custom ? { custom: { ...line.custom } } : { variantId: line.variantId ?? line.productId }), title: line.name,
209
+ ...(version >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && editedSku(line) ? { sku: line.sku } : {}),
140
210
  quantity: line.quantity, unitPriceMinor: line.unitPriceMinor,
141
211
  ...(line.taxInclusive !== undefined ? { taxInclusive: line.taxInclusive } : {}),
142
212
  ...(lineDiscounts[i] > 0 ? { discountMinor: lineDiscounts[i] } : {}),
@@ -146,21 +216,32 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
146
216
  })),
147
217
  ...(base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
148
218
  clientFeeId: fee.id, name: fee.name, amountMinor: fee.amountMinor, taxStatus: fee.taxStatus,
149
- ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}), taxMinor: roundMicrosToMinor(BigInt(fee.taxMicros)),
219
+ ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}),
220
+ // #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
221
+ taxMinor: order.taxRounding?.granularity === 'woocommerce'
222
+ ? woocommerceChargeTaxMinor(fee, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax)
223
+ : roundMicrosToMinor(BigInt(fee.taxMicros)),
150
224
  })) } : {}),
151
225
  ...(base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
152
226
  clientShippingId: charge.id, name: charge.name, ...(charge.methodId !== undefined ? { methodId: charge.methodId } : {}),
153
227
  amountMinor: charge.amountMinor, taxStatus: charge.taxStatus,
154
- ...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}), taxMinor: roundMicrosToMinor(BigInt(charge.taxMicros)),
228
+ ...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}),
229
+ // #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
230
+ taxMinor: order.taxRounding?.granularity === 'woocommerce'
231
+ ? woocommerceChargeTaxMinor(charge, order.taxRounding.roundAtSubtotal, order.pricesIncludeTax)
232
+ : roundMicrosToMinor(BigInt(charge.taxMicros)),
155
233
  })) } : {}),
156
- ...(base === 6 && order.coupons?.length ? { coupons: order.coupons.map(({ code, couponId, discountMinor, discountTaxMinor }) => ({
234
+ ...(base === 6 && redeemable.length ? { coupons: redeemable.map(({ code, couponId, discountMinor, discountTaxMinor, lines }) => ({
157
235
  code, couponId, discountMinor, discountTaxMinor,
236
+ ...(version >= 9 ? { lines: lines!.map(({ lineId, discountMinor, discountTaxMinor }) =>
237
+ ({ clientLineId: lineId, discountMinor, discountTaxMinor })) } : {}),
158
238
  })) } : {}),
159
239
  payments: order.payments.map((payment) => ({
160
240
  clientPaymentId: payment.id, method: payment.method, amountMinor: payment.amountMinor,
161
241
  ...(payment.tenderedMinor !== undefined ? { tenderedMinor: payment.tenderedMinor } : {}),
162
242
  ...(payment.changeMinor !== undefined ? { changeMinor: payment.changeMinor } : {}),
163
243
  ...(payment.reference !== undefined ? { reference: payment.reference } : {}),
244
+ ...(version >= PAYMENT_METHOD_ID_ORDER_CREATE_VERSION && payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
164
245
  })),
165
246
  subtotalMinor: order.subtotalMinor,
166
247
  ...(discountMinor > 0 ? { discountMinor } : {}),
@@ -169,22 +250,61 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
169
250
  display: { ...storedDisplay, lines: order.display!.lines.map(({ lineId, amountMinor, discounts }) => ({
170
251
  clientLineId: lineId, amountMinor, discounts,
171
252
  })),
253
+ ...(carried.length ? { orderDiscountMinor: order.display!.orderDiscountMinor + (_coupons ?? [])
254
+ .reduce((sum, row) => sum + (carried.some((coupon) => coupon.code === row.code) ? row.amountMinor : 0), 0) } : {}),
172
255
  ...(base >= 5 && order.display!.fees ? { fees: order.display!.fees.map(({ id, amountMinor }) => ({ clientFeeId: id, amountMinor })) } : {}),
173
256
  ...(base >= 5 && order.display!.shipping ? { shipping: order.display!.shipping.map(({ id, amountMinor }) => ({ clientShippingId: id, amountMinor })) } : {}),
174
- ...(base === 6 && order.coupons?.length && order.display!.coupons ? { coupons: order.display!.coupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}),
257
+ ...(base === 6 && redeemable.length && displayCoupons && (!carried.length || displayCoupons.length) ? { coupons: displayCoupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}),
175
258
  },
176
259
  taxByRate: order.taxByRate!.map(({ ratePpm, code, netMinor, amountMinor, grossMinor }) => ({
177
260
  ratePpm, ...(code !== undefined ? { code } : {}), netMinor, taxMinor: amountMinor, grossMinor,
178
261
  })),
179
262
  } : {}),
180
263
  customer: base >= 3
181
- ? (email || customerId || version === 8 ? { ...(email ? { email } : {}), ...(customerId ? { customerId } : {}), ...addresses } : null)
264
+ ? (email || customerId || withAddresses || taxIds ? { ...(email ? { email } : {}), ...(customerId ? { customerId } : {}), ...addresses, ...taxIds } : null)
182
265
  : (email ? { email } : null),
183
266
  ...(order.registerId !== undefined ? { registerId: order.registerId } : {}),
184
267
  ...(order.cashierRef !== undefined ? { cashierRef: order.cashierRef } : {}),
185
268
  ...(base >= 3 && typeof sessionId === 'string' && sessionId.length > 0 && sessionId.length <= 36 ? { sessionId } : {}),
186
269
  ...(version >= 7 && note ? { note } : {}),
187
- ...(version === 8 ? { taxAddress } : {}),
270
+ ...(withTaxAddress ? { taxAddress } : {}),
271
+ ...(version >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && sentMeta.length ? { meta: sentMeta } : {}),
188
272
  },
189
273
  };
190
274
  }
275
+
276
+ /** Gate 8 (ADR-090): each kept item's store id goes on the update item with the same client id, never by position. */
277
+ export function pairStoreIds(payload: OrderCreatePayload, order: PosOrder): Pick<OrderUpdatePayload, 'lines' | 'payments' | 'fees' | 'shipping'> {
278
+ const lines = new Map<string, string | undefined>(order.lines.map((line) => [line.id, line.storeLineId]));
279
+ const fees = new Map<string, string | undefined>((order.fees ?? []).map((fee) => [fee.id, fee.storeLineId]));
280
+ const shipping = new Map<string, string | undefined>((order.shipping ?? []).map((charge) => [charge.id, charge.storeLineId]));
281
+ const payments = new Map<string, string | undefined>(order.payments.map((payment) => [payment.id, payment.storePaymentId]));
282
+ return {
283
+ lines: payload.lines.map((line) => {
284
+ const id = lines.get(line.clientLineId); return id !== undefined ? { ...line, storeLineId: id } : line;
285
+ }),
286
+ payments: payload.payments.map((payment) => {
287
+ const id = payments.get(payment.clientPaymentId); return id !== undefined ? { ...payment, paymentId: id } : payment;
288
+ }),
289
+ ...(payload.fees ? { fees: payload.fees.map((fee) => {
290
+ const id = fees.get(fee.clientFeeId); return id !== undefined ? { ...fee, storeLineId: id } : fee;
291
+ }) } : {}),
292
+ ...(payload.shipping ? { shipping: payload.shipping.map((charge) => {
293
+ const id = shipping.get(charge.clientShippingId); return id !== undefined ? { ...charge, storeLineId: id } : charge;
294
+ }) } : {}),
295
+ };
296
+ }
297
+
298
+ /** Builds at order.create version 5 or more (a store's cap below 5 throws UnsupportedOrderVersionError(5, cap)).
299
+ * Refuses a row without baseRevision or figures, and pairs store ids by client id. */
300
+ export function toOrderUpdateEnvelope(order: PosOrder, deviceId: string, attempt = 1, options?: { maxVersion?: number }): OrderUpdateEnvelope {
301
+ if (order.storeOrderId === undefined) throw new Error(`Order ${order.id} has no storeOrderId: it is sent as order.create`);
302
+ if (order.baseRevision === undefined) throw new Error(`Order ${order.id} reopened store order ${order.storeOrderId} without its base revision: order.update needs it (ADR-090)`);
303
+ if (!order.display || !order.taxByRate) throw new Error(`Order ${order.id} has no figures: order.update goes at order.create version 5 or more, which needs them (ADR-090)`);
304
+ const create = createEnvelope(order, deviceId, attempt, options, ORDER_UPDATE_MIN_CREATE_VERSION);
305
+ return { id: create.id, type: 'order.update', version: 1, createdAt: create.createdAt,
306
+ deviceId: create.deviceId, attempt: create.attempt, payload: { ...create.payload, orderId: order.storeOrderId,
307
+ baseRevision: order.baseRevision, createVersion: create.version,
308
+ ...pairStoreIds(create.payload, order),
309
+ } };
310
+ }
@@ -0,0 +1,14 @@
1
+ import { editedSku, sendableMeta, sendableTaxIds } from './command';
2
+ import type { PosOrder } from './types';
3
+
4
+ export interface ExtrasNotSent { taxIds: boolean; meta: boolean; skuLineIds: string[] }
5
+
6
+ /** ADR-092 condition 1: which of a sale's tax ids, meta and edited SKUs went below order.create 12, so the store never got them. */
7
+ export function extrasNotSent(order: Pick<PosOrder, 'customer' | 'meta' | 'lines' | 'sentVersion'>): ExtrasNotSent {
8
+ if (order.sentVersion === undefined || order.sentVersion >= 12) return { taxIds: false, meta: false, skuLineIds: [] };
9
+ return {
10
+ taxIds: sendableTaxIds(order.customer?.taxIds).length > 0,
11
+ meta: sendableMeta(order.meta).length > 0,
12
+ skuLineIds: order.lines.filter(editedSku).map((line) => line.id),
13
+ };
14
+ }