@tallyui/pos 3.18.0 → 3.19.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 (69) hide show
  1. package/dist/index.d.ts +3195 -1721
  2. package/dist/index.js +3854 -672
  3. package/package.json +6 -6
  4. package/src/customer-display/display-client.ts +341 -0
  5. package/src/customer-display/index.ts +20 -0
  6. package/src/customer-display/sale-display.ts +115 -0
  7. package/src/customer-display/snapshot-fallback.ts +138 -0
  8. package/src/customer-display/till-display-service.ts +304 -0
  9. package/src/customer-display/till-pairing.ts +177 -0
  10. package/src/customer-display/use-display-client.ts +25 -0
  11. package/src/customer-display/use-sale-display.ts +28 -0
  12. package/src/customer-display/use-till-pairing.ts +35 -0
  13. package/src/customer-display/webrtc/index.ts +5 -0
  14. package/src/customer-display/webrtc/peer-link.ts +222 -0
  15. package/src/index.ts +36 -10
  16. package/src/order/index.ts +2 -1
  17. package/src/order/order-builder.ts +104 -16
  18. package/src/order/types.ts +10 -4
  19. package/src/payment-driver/index.ts +1 -1
  20. package/src/payment-driver/registry.ts +23 -0
  21. package/src/pos-order/__fixtures__/order-create-v8.json +117 -0
  22. package/src/pos-order/command.ts +19 -4
  23. package/src/pos-order/finalize.ts +30 -2
  24. package/src/pos-order/schema.ts +16 -5
  25. package/src/pos-order/types.ts +7 -4
  26. package/src/receipt/reprint.ts +3 -10
  27. package/src/receipt/woo-gross.ts +16 -0
  28. package/src/receipt-template/index.ts +8 -0
  29. package/src/receipt-template/render-store-template.ts +51 -0
  30. package/src/receipt-template/wcpos/build.ts +320 -0
  31. package/src/receipt-template/wcpos/context.ts +29 -0
  32. package/src/receipt-template/wcpos/format.ts +153 -0
  33. package/src/receipt-template/wcpos/from-orders.ts +203 -0
  34. package/src/receipt-template/wcpos/index.ts +11 -0
  35. package/src/receipt-template/wcpos/money.ts +42 -0
  36. package/src/receipt-template/wcpos/types.ts +350 -0
  37. package/src/register/expected.ts +60 -0
  38. package/src/register/index.ts +2 -2
  39. package/src/register/use-register-session.ts +8 -4
  40. package/src/sale/discount-codes.ts +7 -2
  41. package/src/sale/index.ts +9 -2
  42. package/src/sale/order-filters-query.ts +59 -0
  43. package/src/sale/store-priced-discount-codes.ts +52 -0
  44. package/src/sale/use-sale.ts +157 -16
  45. package/src/sale/variant-match.ts +44 -0
  46. package/src/scanner/camera-scan.ts +113 -0
  47. package/src/scanner/capabilities.ts +22 -0
  48. package/src/scanner/chooser-cancel.ts +8 -0
  49. package/src/scanner/device-identity.ts +84 -0
  50. package/src/scanner/device-scanner.ts +62 -0
  51. package/src/scanner/hid-pos-decoder.ts +60 -0
  52. package/src/scanner/hid-scanner.ts +171 -0
  53. package/src/scanner/index.ts +27 -0
  54. package/src/scanner/scan-dedup.ts +48 -0
  55. package/src/scanner/scan-events.ts +75 -0
  56. package/src/scanner/scan-hub-context.tsx +124 -0
  57. package/src/scanner/scan-session.ts +4 -0
  58. package/src/scanner/scanner-profiles.ts +96 -0
  59. package/src/scanner/serial-line-decoder.ts +58 -0
  60. package/src/scanner/serial-scanner.ts +227 -0
  61. package/src/scanner/use-barcode-scanner.ts +23 -5
  62. package/src/scanner/use-camera-scan.ts +57 -0
  63. package/src/scanner/wedge-detector.ts +28 -6
  64. package/src/tax/index.ts +6 -0
  65. package/src/tax/location-rates.ts +46 -0
  66. package/src/tax/sale-tax-contexts.ts +40 -0
  67. package/src/tax/tax-context.ts +37 -0
  68. package/src/tax/tax-derivation.ts +99 -0
  69. package/src/tax/tax-provider.tsx +4 -31
@@ -0,0 +1,117 @@
1
+ {
2
+ "id": "019f6d2e-7800-7000-8000-000000000006",
3
+ "type": "order.create",
4
+ "version": 8,
5
+ "createdAt": "2026-11-11T10:00:00.000Z",
6
+ "deviceId": "device_golden",
7
+ "attempt": 1,
8
+ "payload": {
9
+ "clientOrderId": "019f6d2e-7800-7000-8000-000000000001",
10
+ "createdAt": "2026-11-11T10:00:00.000Z",
11
+ "currency": "USD",
12
+ "pricesIncludeTax": false,
13
+ "lines": [
14
+ {
15
+ "clientLineId": "019f6d2e-7800-7000-8000-000000000002",
16
+ "variantId": "1",
17
+ "title": "Item",
18
+ "quantity": 1,
19
+ "unitPriceMinor": 800
20
+ }
21
+ ],
22
+ "fees": [
23
+ {
24
+ "clientFeeId": "019f6d2e-7800-7000-8000-000000000003",
25
+ "name": "Bag",
26
+ "amountMinor": 20,
27
+ "taxStatus": "taxable",
28
+ "taxMinor": 1
29
+ }
30
+ ],
31
+ "shipping": [
32
+ {
33
+ "clientShippingId": "019f6d2e-7800-7000-8000-000000000004",
34
+ "name": "Delivery",
35
+ "methodId": "flat_rate",
36
+ "amountMinor": 300,
37
+ "taxStatus": "taxable",
38
+ "taxClass": "standard",
39
+ "taxMinor": 12
40
+ }
41
+ ],
42
+ "payments": [
43
+ {
44
+ "clientPaymentId": "019f6d2e-7800-7000-8000-000000000005",
45
+ "method": "cash",
46
+ "amountMinor": 1165,
47
+ "tenderedMinor": 1165,
48
+ "changeMinor": 0
49
+ }
50
+ ],
51
+ "subtotalMinor": 800,
52
+ "taxMinor": 45,
53
+ "totalMinor": 1165,
54
+ "display": {
55
+ "currency": "USD",
56
+ "exponent": 2,
57
+ "taxInclusive": false,
58
+ "subtotalMinor": 800,
59
+ "discountMinor": 0,
60
+ "taxMinor": 45,
61
+ "totalMinor": 1165,
62
+ "lines": [
63
+ {
64
+ "clientLineId": "019f6d2e-7800-7000-8000-000000000002",
65
+ "amountMinor": 800,
66
+ "discounts": []
67
+ }
68
+ ],
69
+ "orderDiscountMinor": 0,
70
+ "fees": [
71
+ {
72
+ "clientFeeId": "019f6d2e-7800-7000-8000-000000000003",
73
+ "amountMinor": 20
74
+ }
75
+ ],
76
+ "shipping": [
77
+ {
78
+ "clientShippingId": "019f6d2e-7800-7000-8000-000000000004",
79
+ "amountMinor": 300
80
+ }
81
+ ]
82
+ },
83
+ "taxByRate": [
84
+ {
85
+ "ratePpm": 40000,
86
+ "code": "US-NY-TAX-1",
87
+ "netMinor": 1120,
88
+ "taxMinor": 45,
89
+ "grossMinor": 1165
90
+ }
91
+ ],
92
+ "customer": {
93
+ "email": "ann@example.com",
94
+ "customerId": "42",
95
+ "billing": {
96
+ "firstName": "Ann",
97
+ "lastName": "Lee",
98
+ "address1": "1 Main St",
99
+ "city": "Albany",
100
+ "state": "NY",
101
+ "postcode": "12207",
102
+ "country": "US",
103
+ "phone": "555-0100"
104
+ },
105
+ "shipping": {
106
+ "firstName": "Ann",
107
+ "city": "Portland",
108
+ "state": "OR",
109
+ "postcode": "97201",
110
+ "country": "US"
111
+ }
112
+ },
113
+ "registerId": "register_golden",
114
+ "cashierRef": "cashier_golden",
115
+ "taxAddress": "billing"
116
+ }
117
+ }
@@ -3,7 +3,10 @@ import { MICROS_PER_MINOR, roundMicrosToMinor, taxMicros } from '../tax/exact';
3
3
  import type { PosOrder, PosOrderLine } from './types';
4
4
 
5
5
  /** The highest order.create version this till sends; pos_orders' sentVersion and downgradedFrom maxima must equal it. */
6
- export const ORDER_CREATE_MAX_VERSION = 7 as const;
6
+ export const ORDER_CREATE_MAX_VERSION = 8 as const;
7
+ /** order.create 8 (#722) tells the server which customer address the sale was taxed on (`taxAddress`) and carries the
8
+ * addresses; below it a server taxes on the store's base, so `saleTaxContexts` re-taxes by address only from here. */
9
+ export const TAX_ADDRESS_ORDER_CREATE_VERSION = 8 as const;
7
10
 
8
11
  export class UnsupportedOrderVersionError extends Error {
9
12
  readonly code = 'UNSUPPORTED_ORDER_VERSION';
@@ -88,6 +91,9 @@ function wireNote(note: string | undefined): string | undefined {
88
91
  * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
89
92
  * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
90
93
  * 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.
94
+ * A sale taxed on the customer's address (`taxAddress`, #722) needs version 8 and never downgrades: below 8 the server
95
+ * taxes on the base, so a lower cap throws UnsupportedOrderVersionError(8). At 8 it carries the note, `taxAddress` and
96
+ * the stored addresses; every other field follows the version its content makes, as at 7.
91
97
  * Orders with Any picks (#495) need version 6 too, carrying a line's `anyAttributes`, and coupons only when they have some.
92
98
  */
93
99
  export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt = 1,
@@ -98,13 +104,19 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
98
104
  if (content === 5 && cap !== undefined && cap < 5) throw new UnsupportedOrderVersionError(5, cap);
99
105
  if (content === 6 && cap !== undefined && cap < 6) throw new UnsupportedOrderVersionError(6, cap);
100
106
  if (grossMinor > 0 && cap !== undefined && cap < 2) throw new UnsupportedOrderVersionError(2, cap);
107
+ const taxAddress = order.taxAddress;
108
+ if (taxAddress && cap !== undefined && cap < TAX_ADDRESS_ORDER_CREATE_VERSION) {
109
+ throw new UnsupportedOrderVersionError(TAX_ADDRESS_ORDER_CREATE_VERSION, cap);
110
+ }
101
111
  // Version 4 only when the cap allows it (the server advertises 4, and no sentVersion holds the order lower).
102
112
  const base = (content === 3 && cap !== undefined && cap >= 4 ? 4
103
113
  : Math.min(content, cap ?? content)) as 1 | 2 | 3 | 4 | 5 | 6;
104
114
  // Version 7 (ADR-083) is 6 plus the note: only for a sale with one, with figures (3+), when the cap allows 7.
105
115
  // Every other field follows `base`, so a note changes nothing else in the payload.
106
116
  const note = wireNote(order.note);
107
- const version = (note && base >= 3 && cap !== undefined && cap >= 7 ? 7 : base) as OrderCreateEnvelope['version'];
117
+ if (taxAddress && base < 3) throw new Error(`Order ${order.id} is taxed on the customer's ${taxAddress} address but has no figures`);
118
+ const version = (taxAddress ? TAX_ADDRESS_ORDER_CREATE_VERSION
119
+ : note && base >= 3 && cap !== undefined && cap >= 7 ? 7 : base) as OrderCreateEnvelope['version'];
108
120
  const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order.pricesIncludeTax) : line.discountMinor);
109
121
  // The order's discount is the sum of its lines', on one basis, so the payload's two always agree.
110
122
  const discountMinor = lineDiscounts.reduce((sum, discount) => sum + discount, 0);
@@ -113,6 +125,8 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
113
125
  // These are the pre-#222 customerId and sessionId checks, kept byte-exact so stored orders resend older tills' bytes; don't replace with sendable.
114
126
  const customerId = typeof id === 'string' && id.length > 0 && id.length <= 64 ? id : undefined;
115
127
  const sessionId = order.sessionId ?? order.lateSessionId;
128
+ const { billing, shipping } = order.customer ?? {};
129
+ const addresses = version === 8 ? { ...(billing ? { billing: { ...billing } } : {}), ...(shipping ? { shipping: { ...shipping } } : {}) } : {};
116
130
  const { fees: _fees, shipping: _shipping, coupons: _coupons, ...storedDisplay } = { ...order.display! };
117
131
  return {
118
132
  id: order.commandId, type: 'order.create', version, createdAt: order.createdAt, deviceId, attempt,
@@ -161,12 +175,13 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
161
175
  })),
162
176
  } : {}),
163
177
  customer: base >= 3
164
- ? (email || customerId ? { ...(email ? { email } : {}), ...(customerId ? { customerId } : {}) } : null)
178
+ ? (email || customerId || version === 8 ? { ...(email ? { email } : {}), ...(customerId ? { customerId } : {}), ...addresses } : null)
165
179
  : (email ? { email } : null),
166
180
  ...(order.registerId !== undefined ? { registerId: order.registerId } : {}),
167
181
  ...(order.cashierRef !== undefined ? { cashierRef: order.cashierRef } : {}),
168
182
  ...(base >= 3 && typeof sessionId === 'string' && sessionId.length > 0 && sessionId.length <= 36 ? { sessionId } : {}),
169
- ...(version === 7 ? { note } : {}),
183
+ ...(version >= 7 && note ? { note } : {}),
184
+ ...(version === 8 ? { taxAddress } : {}),
170
185
  },
171
186
  };
172
187
  }
@@ -1,4 +1,5 @@
1
- import { minorUnitDigits, ORDER_NOTE_MAX, type ServerCapabilities, type TaxRounding } from '@tallyui/core';
1
+ import { minorUnitDigits, ORDER_NOTE_MAX, type CustomerAddress, type OrderAddress, type ServerCapabilities, type TaxRounding,
2
+ type woocommerceTax } from '@tallyui/core';
2
3
  import type { Order, SentOrder } from '../order/types';
3
4
  import { legStatus } from '../tender/payment-legs';
4
5
  import { DEFAULT_TAX_ROUNDING, taxLinesByRate } from '../tax/exact';
@@ -18,6 +19,18 @@ export interface FinalizeOptions {
18
19
  newId?: () => string;
19
20
  /** The store's `order.create` capability (ADR-062); `undefined` is treated as 1. */
20
21
  capabilities?: ServerCapabilities;
22
+ /** The address the sale's tax context matched (#722, `saleTaxContexts`). A customer's billing or shipping address
23
+ * stores `taxAddress` and the customer's addresses, sent at order.create 8; the base, or absent, stores neither. */
24
+ taxLocation?: woocommerceTax.ResolvedTaxLocation;
25
+ }
26
+
27
+ /** OrderAddress's keys: a CustomerAddress without its email (#722). */
28
+ const ORDER_ADDRESS_KEYS = ['firstName', 'lastName', 'company', 'address1', 'address2', 'city', 'state', 'postcode', 'country', 'phone'] as const;
29
+
30
+ /** A customer's address as order.create 8 carries it: the ten keys, non-empty strings only; undefined when none is. */
31
+ function orderAddress(address: CustomerAddress | undefined): OrderAddress | undefined {
32
+ const entries = ORDER_ADDRESS_KEYS.flatMap((key) => typeof address?.[key] === 'string' && address[key] ? [[key, address[key]]] : []);
33
+ return entries.length ? Object.fromEntries(entries) : undefined;
21
34
  }
22
35
 
23
36
  /** A line name in a refusal message: 60 UTF-16 units of it plus '…' at most, so a cashier-facing message stays short. */
@@ -80,6 +93,11 @@ export function freezeSentForm(order: PosOrder): PosOrder {
80
93
  return { ...payment, reference };
81
94
  });
82
95
  const customer = order.customer && { ...order.customer };
96
+ for (const kind of ['billing', 'shipping'] as const) if (customer?.[kind]) {
97
+ const address: OrderAddress = Object.fromEntries(Object.entries(customer[kind]).map(([key, value]) => [key, cutText(value, PAYLOAD_STRING_MAX)]));
98
+ changed ||= Object.entries(address).some(([key, value]) => value !== customer[kind]![key as keyof OrderAddress]);
99
+ customer[kind] = address;
100
+ }
83
101
  const localWarnings = [...(order.localWarnings ?? [])];
84
102
  for (const [field, max] of [['email', 254], ['id', 64]] as const) {
85
103
  if (customer && field in customer && !sendable(customer[field], max)) {
@@ -122,6 +140,9 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
122
140
  if (order.coupons?.length && (options.capabilities?.orderCreate ?? 1) < 6) {
123
141
  throw new Error("finalize: coupons need the store to accept order.create version 6; update the store's TallyUI plugin");
124
142
  }
143
+ if (order.couponPricesStale) {
144
+ throw new Error("finalize: the coupons' prices are out of date; price the coupons again before finalizing");
145
+ }
125
146
  if (order.lineItems.some((line) => line.anyAttributes?.length) && (options.capabilities?.orderCreate ?? 1) < 6) {
126
147
  throw new Error("finalize: picked options need the store to accept order.create version 6; update the store's TallyUI plugin");
127
148
  }
@@ -248,6 +269,10 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
248
269
  const taxRounding: TaxRounding = rounding.granularity === 'custom' ? { granularity: 'custom' }
249
270
  : rounding.granularity === 'woocommerce' ? { granularity: 'woocommerce', roundAtSubtotal: rounding.roundAtSubtotal }
250
271
  : { granularity: rounding.granularity, mode: rounding.mode };
272
+ const used = options.taxLocation?.addressUsed;
273
+ const taxAddress = used === 'billing' || used === 'shipping' ? used : undefined;
274
+ const addresses = { billing: orderAddress(order.customer?.billing), shipping: orderAddress(order.customer?.shipping) };
275
+ if (taxAddress && !addresses[taxAddress]?.country) throw new Error(`finalize: the sale was taxed on the customer's ${taxAddress} address, which it does not have`);
251
276
  const now = (options.now ?? new Date()).toISOString();
252
277
  return freezeSentForm({
253
278
  id, saleId: order.id, createdAt: now, updatedAt: now, commandId: newId(), syncStatus: 'pending',
@@ -259,8 +284,11 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
259
284
  ({ code, couponId, discountMinor, discountTaxMinor })) } : {}),
260
285
  ...(display && taxByRate ? { display, taxByRate } : {}),
261
286
  customer: order.customer ? { id: order.customer.id, name: order.customer.name,
262
- ...(order.customer.email !== undefined ? { email: order.customer.email } : {}) } : null,
287
+ ...(order.customer.email !== undefined ? { email: order.customer.email } : {}),
288
+ ...(taxAddress && addresses.billing ? { billing: addresses.billing } : {}),
289
+ ...(taxAddress && addresses.shipping ? { shipping: addresses.shipping } : {}) } : null,
263
290
  ...(order.note ? { note: order.note } : {}),
291
+ ...(taxAddress ? { taxAddress } : {}),
264
292
  ...(options.registerId !== undefined ? { registerId: options.registerId } : {}),
265
293
  ...(options.cashierRef !== undefined ? { cashierRef: options.cashierRef } : {}),
266
294
  ...(localWarnings?.length ? { localWarnings } : {}),
@@ -29,9 +29,18 @@ import type { PosOrder } from './types';
29
29
  * Its migration is the identity. It is one-way like version 8.
30
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.
31
31
  * Version 11 lets `sentVersion` and `downgradedFrom` be 7 (order.create version 7, ADR-083), and changes nothing else. Its migration is the identity. It is one-way like version 10.
32
+ * Version 12 adds the order's `taxAddress` and the customer's `billing` and `shipping` (#722), and lets `sentVersion` and
33
+ * `downgradedFrom` be 8 (order.create version 8), and changes nothing else. Its migration is the identity. It is one-way like version 11.
32
34
  */
35
+ /** A customer's address on an order taxed by it (#722, OrderAddress): ten optional strings. */
36
+ const orderAddressSchema = { type: 'object', additionalProperties: false, properties: {
37
+ firstName: { type: 'string' }, lastName: { type: 'string' }, company: { type: 'string' }, address1: { type: 'string' },
38
+ address2: { type: 'string' }, city: { type: 'string' }, state: { type: 'string' }, postcode: { type: 'string' },
39
+ country: { type: 'string' }, phone: { type: 'string' },
40
+ } } as const;
41
+
33
42
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
34
- version: 11, primaryKey: 'id', type: 'object', additionalProperties: false,
43
+ version: 12, primaryKey: 'id', type: 'object', additionalProperties: false,
35
44
  properties: {
36
45
  id: { type: 'string', maxLength: 36 },
37
46
  saleId: { type: 'string', maxLength: 36 },
@@ -96,7 +105,9 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
96
105
  amountMinor: { type: 'integer' }, tenderedMinor: { type: 'integer' }, changeMinor: { type: 'integer' }, reference: { type: 'string' },
97
106
  }, required: ['id', 'method', 'amountMinor'],
98
107
  } },
99
- customer: { type: ['object', 'null'], properties: { id: { type: 'string' }, name: { type: 'string' }, email: { type: 'string' } } },
108
+ customer: { type: ['object', 'null'], properties: { id: { type: 'string' }, name: { type: 'string' }, email: { type: 'string' },
109
+ billing: orderAddressSchema, shipping: orderAddressSchema } },
110
+ taxAddress: { type: 'string', enum: ['billing', 'shipping'] },
100
111
  serverRefs: { type: 'object', properties: {
101
112
  orderId: { type: 'string' }, displayId: { type: 'string' }, totalMinor: { type: 'integer' },
102
113
  }, required: ['orderId', 'totalMinor'] },
@@ -117,8 +128,8 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
117
128
  roundAtSubtotal: { type: 'boolean' },
118
129
  mode: { type: 'string', enum: ['half_away_from_zero', 'half_up'] },
119
130
  }, required: ['granularity'] },
120
- sentVersion: { type: 'integer', minimum: 1, maximum: 7 },
121
- downgradedFrom: { type: 'integer', minimum: 1, maximum: 7 },
131
+ sentVersion: { type: 'integer', minimum: 1, maximum: 8 },
132
+ downgradedFrom: { type: 'integer', minimum: 1, maximum: 8 },
122
133
  // The nested objects are closed too: loosening a schema later is free, tightening one costs a migration.
123
134
  display: { type: 'object', additionalProperties: false, properties: {
124
135
  currency: { type: 'string' }, exponent: { type: 'integer' }, taxInclusive: { type: 'boolean' },
@@ -182,5 +193,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
182
193
  // it means no older sale is ever re-rounded (#287).
183
194
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
184
195
  return { schema: posOrderSchema,
185
- migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity } };
196
+ migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity, 12: identity } };
186
197
  }
@@ -1,4 +1,4 @@
1
- import type { CommandError, CommandServerRefs, CommandWarning, OrderCreateLine, PaymentMethodKind, TaxRounding } from '@tallyui/core';
1
+ import type { CommandError, CommandServerRefs, CommandWarning, OrderAddress, OrderCreateLine, PaymentMethodKind, TaxRounding } from '@tallyui/core';
2
2
  import type { DisplayTotals, FeeLine, ShippingLine } from '../order/types';
3
3
 
4
4
  export type PosOrderSyncStatus = 'pending' | 'applied' | 'rejected';
@@ -74,7 +74,10 @@ export interface PosOrder {
74
74
  taxMinor: number;
75
75
  totalMinor: number;
76
76
  payments: PosOrderPayment[];
77
- customer: { id?: string; name?: string; email?: string } | null;
77
+ /** `billing` and `shipping` (#722) are frozen copies of the customer's addresses, stored only with `taxAddress`. */
78
+ customer: { id?: string; name?: string; email?: string; billing?: OrderAddress; shipping?: OrderAddress } | null;
79
+ /** The customer address the sale was taxed on (#722), sent as order.create 8's `taxAddress`; absent: the store's base. */
80
+ taxAddress?: 'billing' | 'shipping';
78
81
  /** The sale's note; sent as order.create version 7's `note` (ADR-083), cut to ORDER_NOTE_MAX when frozen. */
79
82
  note?: string;
80
83
  registerId?: string;
@@ -93,9 +96,9 @@ export interface PosOrder {
93
96
  * The order.create version every attempt under this `commandId` goes out at: the outbox records it before the first
94
97
  * send, and lowers it only on a downgrade (ADR-065 amendment). Absent means not sent yet (or requeued).
95
98
  */
96
- sentVersion?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
99
+ sentVersion?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
97
100
  /** The version first tried, before the downgrade (the order's audit). */
98
- downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
101
+ downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
99
102
  /** ADR-065: the receipt's display figures, in integer minor units of `currency` at `exponent`. */
100
103
  display?: DisplayTotals & { currency: string; exponent: number };
101
104
  /** ADR-065: tax by rate, named as `taxLinesByRate` names them (`amountMinor` is the tax). */
@@ -1,9 +1,10 @@
1
- import { minorUnitDigits, woocommerceTax, type StoreOrder } from '@tallyui/core';
1
+ import type { StoreOrder } from '@tallyui/core';
2
2
  import { noteDelivery } from '../pos-order/note-delivery';
3
3
  import type { PosOrder } from '../pos-order/types';
4
4
  import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
5
5
  import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
6
6
  import { RECEIPT_SCHEMA_VERSION } from './types';
7
+ import { wooGrossMinor } from './woo-gross';
7
8
 
8
9
  /**
9
10
  * The blocks every reprint shares with `buildReceiptData`. `fiscal.reprint_count` is this reprint's ordinal, starting
@@ -32,18 +33,10 @@ const sum = (amounts: number[]) => amounts.reduce((total, amount) => total + amo
32
33
  export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptConfig): ReceiptData {
33
34
  const { header, ...blocks } = reprintBlocks(config, order.customer);
34
35
  const { display, taxRounding: rounding } = order;
35
- const dp = minorUnitDigits(order.currency), factor = 10 ** dp;
36
- // A WooCommerce line's rounded gross (its builder `totalMinor`), as woocommerce-tax.ts lineAmounts computes it from
37
- // the 6dp net and per-rate taxes, read back from the stored micros as woocommerceTotals reads them (ADR-076).
38
- const wooGrossMinor = (line: PosOrder['lines'][number], roundAtSubtotal: boolean) => {
39
- const tax = line.taxLines.reduce((sum, row) => sum + (roundAtSubtotal ? Number(row.taxMicros) / (factor * 1e6)
40
- : woocommerceTax.roundTaxTotal(Number(row.taxMicros) / (factor * 1e6), dp, order.pricesIncludeTax)), 0);
41
- return Math.round(woocommerceTax.roundHalfUp(Number(line.netMicros) / (factor * 1e6) + tax, dp) * factor);
42
- };
43
36
  const lineTaxMicros = (line: PosOrder['lines'][number]) => line.taxLines.reduce((total, row) => total + BigInt(row.taxMicros), 0n);
44
37
  let taxSoFar = order.pricesIncludeTax ? 0n : order.lines.reduce((total, line) => line.taxInclusive === undefined ? total + lineTaxMicros(line) : total, 0n);
45
38
  const lineTotals = order.lines.map((line) => {
46
- if (rounding.granularity === 'woocommerce' && line.netMicros !== undefined) return order.pricesIncludeTax ? wooGrossMinor(line, rounding.roundAtSubtotal) : line.netMinor;
39
+ if (rounding.granularity === 'woocommerce' && line.netMicros !== undefined) return order.pricesIncludeTax ? wooGrossMinor(line, order, rounding.roundAtSubtotal) : line.netMinor;
47
40
  if (line.taxInclusive === undefined) return line.netMinor;
48
41
  const share = roundMicrosToMinor(taxSoFar + lineTaxMicros(line)) - roundMicrosToMinor(taxSoFar);
49
42
  taxSoFar += lineTaxMicros(line);
@@ -0,0 +1,16 @@
1
+ import { minorUnitDigits, woocommerceTax } from '@tallyui/core';
2
+ import type { PosOrder } from '../pos-order/types';
3
+
4
+ /**
5
+ * A stored WooCommerce line's rounded gross (its builder `totalMinor`, which PosOrder lines do not keep), as
6
+ * woocommerce-tax.ts lineAmounts computes it from the 6dp net and per-rate taxes, read back from the stored micros as
7
+ * woocommerceTotals reads them (ADR-076).
8
+ */
9
+ export function wooGrossMinor(
10
+ line: PosOrder['lines'][number], order: Pick<PosOrder, 'currency' | 'pricesIncludeTax'>, roundAtSubtotal: boolean,
11
+ ): number {
12
+ const dp = minorUnitDigits(order.currency), factor = 10 ** dp;
13
+ const tax = line.taxLines.reduce((sum, row) => sum + (roundAtSubtotal ? Number(row.taxMicros) / (factor * 1e6)
14
+ : woocommerceTax.roundTaxTotal(Number(row.taxMicros) / (factor * 1e6), dp, order.pricesIncludeTax)), 0);
15
+ return Math.round(woocommerceTax.roundHalfUp(Number(line.netMicros) / (factor * 1e6) + tax, dp) * factor);
16
+ }
@@ -13,3 +13,11 @@ export type {
13
13
  } from './template-data';
14
14
  export type { ReceiptPaper } from './default-templates';
15
15
  export type { RenderReceiptOptions } from './render-receipt';
16
+ export { wcposReceiptData, formatWcposReceiptData, formatWcposMoney, WCPOS_DEFAULT_I18N, WCPOS_TAX_ID_LABELS } from './wcpos';
17
+ export { wcposSourceFromSentOrder, wcposSourceFromPosOrder, wcposSourceFromStoreOrder, wcposReceiptContext } from './wcpos';
18
+ export { renderStoreReceiptTemplate } from './render-store-template';
19
+ export type { PrintableSale, StoreTemplateContext } from './render-store-template';
20
+ export type {
21
+ FormatWcposReceiptOptions, WcposMoneyOptions, WcposReceiptSource, WcposReceiptStore, WcposReceiptOptions,
22
+ WcposReceiptData, WcposReceiptView, WcposTaxId, WcposReceiptDate, WcposReceiptLine, WcposLineView,
23
+ } from './wcpos';
@@ -0,0 +1,51 @@
1
+ import type { ReceiptTemplate, StoreOrder } from '@tallyui/core';
2
+ import type { SentOrder } from '../order/types';
3
+ import type { PosOrder } from '../pos-order/types';
4
+ import { buildReceiptData } from '../receipt/build-receipt-data';
5
+ import { buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder } from '../receipt/reprint';
6
+ import type { ReceiptConfig } from '../receipt/types';
7
+ import { renderLogiclessTemplate, renderThermalPreview } from './render-template';
8
+ import type { RenderSanitizeOptions } from './render-template';
9
+ import { receiptTemplateData } from './template-data';
10
+ import { wcposReceiptData } from './wcpos/build';
11
+ import { wcposReceiptContext } from './wcpos/context';
12
+ import { formatWcposReceiptData } from './wcpos/format';
13
+ import { wcposSourceFromPosOrder, wcposSourceFromSentOrder, wcposSourceFromStoreOrder } from './wcpos/from-orders';
14
+ import type { WcposReceiptOptions, WcposReceiptStore } from './wcpos/types';
15
+
16
+ /** A sale a receipt prints from: the order as sent, the till's stored order, or an order read from the store. */
17
+ export type PrintableSale =
18
+ | { kind: 'sent'; order: SentOrder }
19
+ | { kind: 'pos'; order: PosOrder }
20
+ | { kind: 'store'; order: StoreOrder };
21
+
22
+ export interface StoreTemplateContext {
23
+ config: ReceiptConfig;
24
+ pricesIncludeTax: boolean;
25
+ /** Overrides merged over wcposReceiptContext's store/options (logo, locale, i18n the app knows). */
26
+ store?: Partial<WcposReceiptStore>;
27
+ options?: Partial<WcposReceiptOptions>;
28
+ sanitize?: RenderSanitizeOptions;
29
+ }
30
+
31
+ function templateData(template: ReceiptTemplate, sale: PrintableSale, context: StoreTemplateContext): object {
32
+ const { config } = context;
33
+ if (template.dataModel === 'wcpos') {
34
+ const source = sale.kind === 'sent' ? wcposSourceFromSentOrder(sale.order, config)
35
+ : sale.kind === 'pos' ? wcposSourceFromPosOrder(sale.order, config) : wcposSourceFromStoreOrder(sale.order, config);
36
+ const base = wcposReceiptContext(config, { pricesIncludeTax: context.pricesIncludeTax });
37
+ const options = { ...base.options, ...context.options };
38
+ return formatWcposReceiptData(wcposReceiptData(source, { ...base.store, ...context.store }, options));
39
+ }
40
+ const receipt = sale.kind === 'sent' ? buildReceiptData(sale.order, config)
41
+ : sale.kind === 'pos' ? buildReceiptDataFromPosOrder(sale.order, config) : buildReceiptDataFromStoreOrder(sale.order, config);
42
+ return receiptTemplateData(receipt);
43
+ }
44
+
45
+ /** Prints a store's fetched template from a sale. Throws for kind !== 'receipt'. */
46
+ export function renderStoreReceiptTemplate(template: ReceiptTemplate, sale: PrintableSale, context: StoreTemplateContext): string {
47
+ if (template.kind !== 'receipt') throw new Error('Only receipt templates print from a sale');
48
+ const data = templateData(template, sale, context);
49
+ const render = template.engine === 'thermal' ? renderThermalPreview : renderLogiclessTemplate;
50
+ return render(template.body, data, context.sanitize);
51
+ }