@tallyui/pos 3.12.0 → 3.14.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 (89) hide show
  1. package/dist/index.d.ts +1844 -359
  2. package/dist/index.js +4620 -2211
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +108 -0
  5. package/src/app-settings/index.ts +8 -0
  6. package/src/app-settings/use-app-settings.ts +23 -0
  7. package/src/cashier/can.ts +12 -0
  8. package/src/cashier/index.ts +2 -0
  9. package/src/cashier/use-cashier.ts +81 -0
  10. package/src/csv/csv.ts +33 -0
  11. package/src/csv/index.ts +2 -0
  12. package/src/customer-display/display-link.ts +72 -0
  13. package/src/customer-display/display-state.ts +30 -0
  14. package/src/customer-display/index.ts +13 -0
  15. package/src/customer-display/protocol.ts +87 -0
  16. package/src/customer-display/snapshot.ts +65 -0
  17. package/src/customer-display/transport.ts +54 -0
  18. package/src/customer-display/use-customer-display.ts +36 -0
  19. package/src/index.ts +73 -10
  20. package/src/order/order-builder.ts +11 -1
  21. package/src/order/order-drafts.ts +16 -0
  22. package/src/order/types.ts +6 -3
  23. package/src/outbox/index.ts +5 -1
  24. package/src/outbox/outbox-health.ts +40 -0
  25. package/src/outbox/register-outbox.ts +59 -6
  26. package/src/outbox/safe-error.ts +11 -0
  27. package/src/outbox/types.ts +3 -1
  28. package/src/outbox/use-outbox-health.ts +22 -0
  29. package/src/outbox/use-register-outbox.ts +6 -0
  30. package/src/payment-driver/index.ts +8 -0
  31. package/src/payment-driver/registry.ts +39 -0
  32. package/src/payment-driver/simulated-driver.ts +104 -0
  33. package/src/payment-driver/types.ts +73 -0
  34. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  35. package/src/pos-order/command.ts +36 -16
  36. package/src/pos-order/finalize.ts +7 -3
  37. package/src/pos-order/index.ts +1 -0
  38. package/src/pos-order/note-delivery.ts +13 -0
  39. package/src/pos-order/reopen.ts +3 -2
  40. package/src/pos-order/schema.ts +5 -4
  41. package/src/pos-order/types.ts +3 -2
  42. package/src/print/escpos/code-page.ts +48 -0
  43. package/src/print/escpos/commands.ts +53 -0
  44. package/src/print/escpos/encode.ts +127 -0
  45. package/src/print/escpos/index.ts +7 -0
  46. package/src/print/escpos/transport.ts +45 -0
  47. package/src/print/index.ts +12 -0
  48. package/src/print/print-queue.ts +67 -0
  49. package/src/print/printer-profiles.ts +71 -0
  50. package/src/print/system-transport.ts +101 -0
  51. package/src/print/types.ts +44 -0
  52. package/src/receipt/reprint.ts +2 -1
  53. package/src/receipt/types.ts +2 -0
  54. package/src/receipt-template/default-templates.ts +78 -0
  55. package/src/receipt-template/index.ts +15 -0
  56. package/src/receipt-template/parse-xml.ts +175 -0
  57. package/src/receipt-template/render-html.ts +152 -0
  58. package/src/receipt-template/render-receipt.ts +19 -0
  59. package/src/receipt-template/render-template.ts +35 -0
  60. package/src/receipt-template/sanitize-html.ts +146 -0
  61. package/src/receipt-template/template-data.ts +97 -0
  62. package/src/receipt-template/types.ts +49 -0
  63. package/src/refund/index.ts +2 -0
  64. package/src/refund/refundable-lines.ts +91 -0
  65. package/src/register/export-csv.ts +24 -35
  66. package/src/register/float-suggestion.ts +22 -0
  67. package/src/register/handover.ts +103 -0
  68. package/src/register/index.ts +10 -3
  69. package/src/register/register-adoption.ts +71 -2
  70. package/src/register/register-commands.ts +7 -4
  71. package/src/register/register-count.helpers.ts +4 -0
  72. package/src/register/session-store.ts +4 -1
  73. package/src/register/use-register-session.ts +112 -28
  74. package/src/reports/adapters.ts +67 -0
  75. package/src/reports/index.ts +5 -0
  76. package/src/reports/presets.ts +27 -0
  77. package/src/reports/sales-figures.ts +187 -0
  78. package/src/reports/types.ts +63 -0
  79. package/src/sale/in-cart.ts +18 -0
  80. package/src/sale/index.ts +5 -1
  81. package/src/sale/open-sales.ts +40 -0
  82. package/src/sale/use-sale.ts +72 -8
  83. package/src/scanner/index.ts +6 -0
  84. package/src/scanner/scan-session.ts +84 -0
  85. package/src/scanner/use-barcode-scanner.ts +61 -0
  86. package/src/scanner/wedge-detector.ts +137 -0
  87. package/src/tender/cash-rounding.ts +74 -0
  88. package/src/tender/index.ts +4 -0
  89. package/src/tender/payment-legs.ts +48 -0
@@ -0,0 +1,104 @@
1
+ // Ported from WCPOS v2 packages/core/src/services/payment-drivers/simulated-driver.ts (monorepo 5ac185b0).
2
+ import type { CollectResult, DriverAvailability, DriverStatus, PaymentDriver, ReaderInfo } from './types';
3
+
4
+ export const SIMULATED_PROVIDER = 'simulated';
5
+ export const SIMULATED_TIMING = { connectMs: 300, decisionMs: 500, readWindowMs: 1500 } as const;
6
+ export type SimulatedReaderId = 'sim-approve' | 'sim-decline' | 'sim-cancel' | 'sim-timeout' | 'sim-tip' | 'sim-tap';
7
+ export interface SimulatedDriverOptions {
8
+ /** Override any of the delays in SIMULATED_TIMING. */
9
+ timing?: Partial<{ connectMs: number; decisionMs: number; readWindowMs: number }>;
10
+ /** Timer functions; default to globalThis.setTimeout / clearTimeout. */
11
+ timers?: {
12
+ setTimeout: (fn: () => void, ms: number) => unknown;
13
+ clearTimeout: (handle: unknown) => void;
14
+ };
15
+ /** What `availability()` returns; default `{ available: true }`. */
16
+ availability?: DriverAvailability;
17
+ }
18
+
19
+ export function createSimulatedDriver(options: SimulatedDriverOptions = {}): PaymentDriver {
20
+ const timing = { ...SIMULATED_TIMING, ...options.timing };
21
+ const timers = options.timers ?? {
22
+ setTimeout: (fn: () => void, ms: number) => globalThis.setTimeout(fn, ms),
23
+ clearTimeout: (handle: unknown) => globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>),
24
+ };
25
+ const ids: SimulatedReaderId[] = ['sim-approve', 'sim-decline', 'sim-cancel', 'sim-timeout', 'sim-tip', 'sim-tap'];
26
+ const readers: ReaderInfo[] = ids.map((id) => ({
27
+ id,
28
+ label: `Simulated ${id.slice(4)}`,
29
+ model: 'Simulated reader',
30
+ battery: 82,
31
+ transport: id === 'sim-tap' ? 'tap_to_pay' : 'bluetooth',
32
+ }));
33
+ let status: DriverStatus = { connection: 'disconnected', reader: null };
34
+ const listeners = new Set<(status: DriverStatus) => void>();
35
+ let cancelCollection: (() => void) | undefined;
36
+ const publish = (next: DriverStatus) => {
37
+ status = next;
38
+ listeners.forEach((listener) => listener(status));
39
+ };
40
+ return {
41
+ provider: SIMULATED_PROVIDER,
42
+ capabilities: { discovery: 'harness', cancel: 'app', refund: false },
43
+ availability: () => options.availability ?? { available: true },
44
+ async discoverReaders(transport) {
45
+ return readers.filter((reader) => reader.transport === transport);
46
+ },
47
+ async connect(reader) {
48
+ publish({ connection: 'connecting', reader });
49
+ await new Promise<void>((resolve) => { timers.setTimeout(resolve, timing.connectMs); });
50
+ publish({ connection: 'connected', reader });
51
+ },
52
+ async disconnect() {
53
+ cancelCollection?.();
54
+ publish({ connection: 'disconnected', reader: null });
55
+ },
56
+ status$: {
57
+ get: () => status,
58
+ subscribe(listener) {
59
+ listeners.add(listener);
60
+ return () => { listeners.delete(listener); };
61
+ },
62
+ },
63
+ collect(input) {
64
+ const reader = status.reader;
65
+ if (status.connection !== 'connected' || !reader) return Promise.reject(new Error('No reader connected'));
66
+ if (cancelCollection) return Promise.reject(new Error('Reader is in use'));
67
+ return new Promise<CollectResult>((resolve) => {
68
+ const pending: { timer?: unknown } = {};
69
+ const base = {
70
+ providerRefs: { reference: 'sim_' + input.legId },
71
+ receipt: { brand: 'visa', last4: '4242' },
72
+ amountMinor: input.amountMinor,
73
+ transport: input.transport,
74
+ };
75
+ const finish = (result: CollectResult) => {
76
+ if (pending.timer !== undefined) timers.clearTimeout(pending.timer);
77
+ cancelCollection = undefined;
78
+ resolve(result);
79
+ };
80
+ cancelCollection = () => finish({ ...base, outcome: 'cancelled' });
81
+ const result: CollectResult = { ...base, outcome: 'captured' };
82
+ switch (reader.id) {
83
+ case 'sim-cancel':
84
+ return;
85
+ case 'sim-decline':
86
+ result.outcome = 'declined';
87
+ result.failureReason = 'card_declined';
88
+ break;
89
+ case 'sim-timeout':
90
+ result.outcome = 'cancelled';
91
+ result.failureReason = 'timed_out';
92
+ break;
93
+ case 'sim-tip':
94
+ result.amountMinor = input.amountMinor + (input.tipEligibleMinor === null ? 0 : Math.round(input.tipEligibleMinor / 10));
95
+ break;
96
+ }
97
+ pending.timer = timers.setTimeout(() => finish(result), reader.id === 'sim-timeout' ? timing.readWindowMs : timing.decisionMs);
98
+ });
99
+ },
100
+ async cancel() {
101
+ cancelCollection?.();
102
+ },
103
+ };
104
+ }
@@ -0,0 +1,73 @@
1
+ // Ported from WCPOS v2 packages/core/src/services/payment-drivers/types.ts (monorepo 5ac185b0).
2
+ import type { PaymentMethodDescriptor } from '@tallyui/core';
3
+ import type { PaymentTransport } from '../tender/tender-state';
4
+
5
+ export interface DriverCapabilities {
6
+ /** `harness`: the till lists readers and connects; `sdk_ui`: the vendor SDK shows its own picker. */
7
+ discovery: 'harness' | 'sdk_ui';
8
+ /** `app`: the till can cancel a collection; `on_device`: only the reader can. */
9
+ cancel: 'app' | 'on_device';
10
+ refund: boolean;
11
+ }
12
+ export interface ReaderInfo {
13
+ id: string;
14
+ label: string;
15
+ model?: string;
16
+ serial?: string;
17
+ battery?: number | null;
18
+ transport: PaymentTransport;
19
+ }
20
+ export interface DriverStatus {
21
+ connection: 'disconnected' | 'discovering' | 'connecting' | 'updating' | 'connected';
22
+ reader: ReaderInfo | null;
23
+ progress?: number | null;
24
+ pairingCode?: string | null;
25
+ message?: string | null;
26
+ }
27
+ export type DriverAvailability =
28
+ | { available: true }
29
+ | { available: false; reason: 'web' | 'permission' | 'bluetooth_off' | 'not_logged_in' | 'unsupported' };
30
+ export interface CollectInput {
31
+ /** The payment leg's id; a driver may use it to make its provider reference. */
32
+ legId: string;
33
+ /** The leg's amount in minor units of `currency`. */
34
+ amountMinor: number;
35
+ /** ISO 4217 code. */
36
+ currency: string;
37
+ method: PaymentMethodDescriptor;
38
+ transport: PaymentTransport;
39
+ /** Provider data from the server (credentials, an intent), or null. */
40
+ handoff: Record<string, unknown> | null;
41
+ /** The amount a tip may be taken on, in minor units; null when the leg takes no tip. */
42
+ tipEligibleMinor: number | null;
43
+ }
44
+ export type CollectOutcome = 'captured' | 'authorized' | 'declined' | 'cancelled';
45
+ export interface CollectResult {
46
+ outcome: CollectOutcome;
47
+ /** The provider's own references for the payment (opaque to the till). */
48
+ providerRefs: Record<string, unknown>;
49
+ /** Card details to print (brand, last four and so on). */
50
+ receipt: Record<string, unknown>;
51
+ /** What the reader charged in minor units, tip included; null when the driver cannot say. */
52
+ amountMinor: number | null;
53
+ transport: PaymentTransport;
54
+ /** Why a leg was declined or cancelled; `'timed_out'` when the reader's own collect window ran out. */
55
+ failureReason?: string | null;
56
+ }
57
+ export interface DriverStatusSource {
58
+ subscribe(listener: (status: DriverStatus) => void): () => void;
59
+ get(): DriverStatus;
60
+ }
61
+ export interface PaymentDriver {
62
+ /** Matches a payment method's `capture.provider`. */
63
+ readonly provider: string;
64
+ readonly capabilities: DriverCapabilities;
65
+ availability(): DriverAvailability;
66
+ /** Scan for readers; `until` names a reader id the caller waits for, so a driver may stop early. */
67
+ discoverReaders?(transport: PaymentTransport, options?: { until?: string }): Promise<ReaderInfo[]>;
68
+ connect?(reader: ReaderInfo, handoff: Record<string, unknown> | null): Promise<void>;
69
+ disconnect?(): Promise<void>;
70
+ collect(input: CollectInput): Promise<CollectResult>;
71
+ cancel?(): Promise<void>;
72
+ status$: DriverStatusSource;
73
+ }
@@ -0,0 +1,97 @@
1
+ {
2
+ "id": "019f6d2e-7800-7000-8000-000000000005",
3
+ "type": "order.create",
4
+ "version": 7,
5
+ "createdAt": "2026-10-07T10:00:00.000Z",
6
+ "deviceId": "device_golden",
7
+ "attempt": 1,
8
+ "payload": {
9
+ "clientOrderId": "019f6d2e-7800-7000-8000-000000000001",
10
+ "createdAt": "2026-10-07T10:00:00.000Z",
11
+ "currency": "GBP",
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
+ "regularUnitPriceMinor": 1000,
21
+ "attributes": {
22
+ "Size": "L",
23
+ "Colour": "Red"
24
+ }
25
+ },
26
+ {
27
+ "clientLineId": "019f6d2e-7800-7000-8000-000000000003",
28
+ "variantId": "2",
29
+ "title": "Item 2",
30
+ "quantity": 1,
31
+ "unitPriceMinor": 500,
32
+ "regularUnitPriceMinor": 500
33
+ }
34
+ ],
35
+ "coupons": [
36
+ {
37
+ "code": "ten",
38
+ "couponId": "303",
39
+ "discountMinor": 130,
40
+ "discountTaxMinor": 26
41
+ }
42
+ ],
43
+ "payments": [
44
+ {
45
+ "clientPaymentId": "019f6d2e-7800-7000-8000-000000000004",
46
+ "method": "cash",
47
+ "amountMinor": 1404,
48
+ "tenderedMinor": 1404,
49
+ "changeMinor": 0
50
+ }
51
+ ],
52
+ "subtotalMinor": 1170,
53
+ "taxMinor": 234,
54
+ "totalMinor": 1404,
55
+ "display": {
56
+ "currency": "GBP",
57
+ "exponent": 2,
58
+ "taxInclusive": false,
59
+ "subtotalMinor": 1300,
60
+ "discountMinor": 130,
61
+ "taxMinor": 234,
62
+ "totalMinor": 1404,
63
+ "lines": [
64
+ {
65
+ "clientLineId": "019f6d2e-7800-7000-8000-000000000002",
66
+ "amountMinor": 800,
67
+ "discounts": []
68
+ },
69
+ {
70
+ "clientLineId": "019f6d2e-7800-7000-8000-000000000003",
71
+ "amountMinor": 500,
72
+ "discounts": []
73
+ }
74
+ ],
75
+ "orderDiscountMinor": 0,
76
+ "coupons": [
77
+ {
78
+ "code": "ten",
79
+ "amountMinor": 130
80
+ }
81
+ ]
82
+ },
83
+ "taxByRate": [
84
+ {
85
+ "ratePpm": 200000,
86
+ "code": "VAT",
87
+ "netMinor": 1170,
88
+ "taxMinor": 234,
89
+ "grossMinor": 1404
90
+ }
91
+ ],
92
+ "customer": null,
93
+ "registerId": "register_golden",
94
+ "cashierRef": "cashier_golden",
95
+ "note": "Gift wrap, please"
96
+ }
97
+ }
@@ -3,7 +3,7 @@ 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 = 6 as const;
6
+ export const ORDER_CREATE_MAX_VERSION = 7 as const;
7
7
 
8
8
  export class UnsupportedOrderVersionError extends Error {
9
9
  readonly code = 'UNSUPPORTED_ORDER_VERSION';
@@ -66,6 +66,20 @@ export function contentVersion(order: Pick<PosOrder, 'display' | 'taxByRate' | '
66
66
  return order.display && order.taxByRate ? 3 : order.lines.reduce((sum, line) => sum + line.discountMinor, 0) > 0 ? 2 : 1;
67
67
  }
68
68
 
69
+ const LEGACY_REFUSAL_PREFIX = 'Refused by the store: ';
70
+
71
+ /**
72
+ * The note as it goes on the wire. ADR-083 condition 1: `payload.note` never carries the refusal prefix that
73
+ * @tallyui/pos 3.12.0's `reopenRefusedOrder` wrote into a reopened draft's note (`Refused by the store: <message>`,
74
+ * then `\n` and the cashier's note, or the prefix alone), so a draft parked by 3.12.0 drops that first line here.
75
+ * A note that is only that line is no note. The phrase anywhere else in a cashier's note is kept.
76
+ */
77
+ function wireNote(note: string | undefined): string | undefined {
78
+ if (!note?.startsWith(LEGACY_REFUSAL_PREFIX)) return note || undefined;
79
+ const newline = note.indexOf('\n');
80
+ return newline === -1 ? undefined : note.slice(newline + 1) || undefined;
81
+ }
82
+
69
83
  /**
70
84
  * Builds the ADR-038 order.create envelope for a PosOrder. It sends the stored order unchanged, so every resend of
71
85
  * an order is byte-identical, and an order stored by an older till goes out exactly as that till sent it:
@@ -73,6 +87,7 @@ export function contentVersion(order: Pick<PosOrder, 'display' | 'taxByRate' | '
73
87
  * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
74
88
  * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
75
89
  * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
90
+ * 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.
76
91
  * Orders with Any picks (#495) need version 6 too, carrying a line's `anyAttributes`, and coupons only when they have some.
77
92
  */
78
93
  export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt = 1,
@@ -84,9 +99,13 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
84
99
  if (content === 6 && cap !== undefined && cap < 6) throw new UnsupportedOrderVersionError(6, cap);
85
100
  if (grossMinor > 0 && cap !== undefined && cap < 2) throw new UnsupportedOrderVersionError(2, cap);
86
101
  // Version 4 only when the cap allows it (the server advertises 4, and no sentVersion holds the order lower).
87
- const version = (content === 3 && cap !== undefined && cap >= 4 ? 4
88
- : Math.min(content, cap ?? content)) as OrderCreateEnvelope['version'];
89
- const lineDiscounts = order.lines.map((line) => version >= 4 ? netDiscountMinor(line, order.pricesIncludeTax) : line.discountMinor);
102
+ const base = (content === 3 && cap !== undefined && cap >= 4 ? 4
103
+ : Math.min(content, cap ?? content)) as 1 | 2 | 3 | 4 | 5 | 6;
104
+ // Version 7 (ADR-083) is 6 plus the note: only for a sale with one, with figures (3+), when the cap allows 7.
105
+ // Every other field follows `base`, so a note changes nothing else in the payload.
106
+ const note = wireNote(order.note);
107
+ const version = (note && base >= 3 && cap !== undefined && cap >= 7 ? 7 : base) as OrderCreateEnvelope['version'];
108
+ const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order.pricesIncludeTax) : line.discountMinor);
90
109
  // The order's discount is the sum of its lines', on one basis, so the payload's two always agree.
91
110
  const discountMinor = lineDiscounts.reduce((sum, discount) => sum + discount, 0);
92
111
  const email = order.customer?.email;
@@ -104,20 +123,20 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
104
123
  quantity: line.quantity, unitPriceMinor: line.unitPriceMinor,
105
124
  ...(line.taxInclusive !== undefined ? { taxInclusive: line.taxInclusive } : {}),
106
125
  ...(lineDiscounts[i] > 0 ? { discountMinor: lineDiscounts[i] } : {}),
107
- ...(version === 6 && line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
108
- ...(version === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
109
- ...(version === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
126
+ ...(base === 6 && line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
127
+ ...(base === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
128
+ ...(base === 6 && line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
110
129
  })),
111
- ...(version >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
130
+ ...(base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
112
131
  clientFeeId: fee.id, name: fee.name, amountMinor: fee.amountMinor, taxStatus: fee.taxStatus,
113
132
  ...(fee.taxClass !== undefined ? { taxClass: fee.taxClass } : {}), taxMinor: roundMicrosToMinor(BigInt(fee.taxMicros)),
114
133
  })) } : {}),
115
- ...(version >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
134
+ ...(base >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
116
135
  clientShippingId: charge.id, name: charge.name, ...(charge.methodId !== undefined ? { methodId: charge.methodId } : {}),
117
136
  amountMinor: charge.amountMinor, taxStatus: charge.taxStatus,
118
137
  ...(charge.taxClass !== undefined ? { taxClass: charge.taxClass } : {}), taxMinor: roundMicrosToMinor(BigInt(charge.taxMicros)),
119
138
  })) } : {}),
120
- ...(version === 6 && order.coupons?.length ? { coupons: order.coupons.map(({ code, couponId, discountMinor, discountTaxMinor }) => ({
139
+ ...(base === 6 && order.coupons?.length ? { coupons: order.coupons.map(({ code, couponId, discountMinor, discountTaxMinor }) => ({
121
140
  code, couponId, discountMinor, discountTaxMinor,
122
141
  })) } : {}),
123
142
  payments: order.payments.map((payment) => ({
@@ -129,24 +148,25 @@ export function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt
129
148
  subtotalMinor: order.subtotalMinor,
130
149
  ...(discountMinor > 0 ? { discountMinor } : {}),
131
150
  taxMinor: order.taxMinor, totalMinor: order.totalMinor,
132
- ...(version >= 3 ? {
151
+ ...(base >= 3 ? {
133
152
  display: { ...storedDisplay, lines: order.display!.lines.map(({ lineId, amountMinor, discounts }) => ({
134
153
  clientLineId: lineId, amountMinor, discounts,
135
154
  })),
136
- ...(version >= 5 && order.display!.fees ? { fees: order.display!.fees.map(({ id, amountMinor }) => ({ clientFeeId: id, amountMinor })) } : {}),
137
- ...(version >= 5 && order.display!.shipping ? { shipping: order.display!.shipping.map(({ id, amountMinor }) => ({ clientShippingId: id, amountMinor })) } : {}),
138
- ...(version === 6 && order.coupons?.length && order.display!.coupons ? { coupons: order.display!.coupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}),
155
+ ...(base >= 5 && order.display!.fees ? { fees: order.display!.fees.map(({ id, amountMinor }) => ({ clientFeeId: id, amountMinor })) } : {}),
156
+ ...(base >= 5 && order.display!.shipping ? { shipping: order.display!.shipping.map(({ id, amountMinor }) => ({ clientShippingId: id, amountMinor })) } : {}),
157
+ ...(base === 6 && order.coupons?.length && order.display!.coupons ? { coupons: order.display!.coupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}),
139
158
  },
140
159
  taxByRate: order.taxByRate!.map(({ ratePpm, code, netMinor, amountMinor, grossMinor }) => ({
141
160
  ratePpm, ...(code !== undefined ? { code } : {}), netMinor, taxMinor: amountMinor, grossMinor,
142
161
  })),
143
162
  } : {}),
144
- customer: version >= 3
163
+ customer: base >= 3
145
164
  ? (email || customerId ? { ...(email ? { email } : {}), ...(customerId ? { customerId } : {}) } : null)
146
165
  : (email ? { email } : null),
147
166
  ...(order.registerId !== undefined ? { registerId: order.registerId } : {}),
148
167
  ...(order.cashierRef !== undefined ? { cashierRef: order.cashierRef } : {}),
149
- ...(version >= 3 && typeof sessionId === 'string' && sessionId.length > 0 && sessionId.length <= 36 ? { sessionId } : {}),
168
+ ...(base >= 3 && typeof sessionId === 'string' && sessionId.length > 0 && sessionId.length <= 36 ? { sessionId } : {}),
169
+ ...(version === 7 ? { note } : {}),
150
170
  },
151
171
  };
152
172
  }
@@ -1,5 +1,6 @@
1
- import { minorUnitDigits, type ServerCapabilities, type TaxRounding } from '@tallyui/core';
1
+ import { minorUnitDigits, ORDER_NOTE_MAX, type ServerCapabilities, type TaxRounding } from '@tallyui/core';
2
2
  import type { Order, SentOrder } from '../order/types';
3
+ import { legStatus } from '../tender/payment-legs';
3
4
  import { DEFAULT_TAX_ROUNDING, taxLinesByRate } from '../tax/exact';
4
5
  import { outboxLogger } from '../outbox/logger';
5
6
  import { cutText, PAYLOAD_STRING_MAX, sendable } from './command';
@@ -27,7 +28,7 @@ export function withSentForm(order: Order, posOrder: PosOrder): SentOrder {
27
28
  const customer: SentOrder['customer'] = order.customer && { ...order.customer };
28
29
  if (customer && posOrder.customer?.email === undefined) delete customer.email;
29
30
  if (customer && posOrder.customer?.id === undefined) delete customer.id;
30
- return { ...order, customer,
31
+ return { ...order, customer, note: posOrder.note ?? order.note,
31
32
  lineItems: order.lineItems.map((line, i) => ({ ...line, name: posOrder.lines[i].name })),
32
33
  ...(order.fees ? { fees: order.fees.map((fee, i) => ({ ...fee, name: posOrder.fees![i].name })) } : {}),
33
34
  ...(order.shipping ? { shipping: order.shipping.map((charge, i) => ({ ...charge, name: posOrder.shipping![i].name })) } : {}),
@@ -44,6 +45,8 @@ export function withSentForm(order: Order, posOrder: PosOrder): SentOrder {
44
45
  /** Bounds apply when the sent form is frozen; the outbox freezes older tills' stored orders before their first send. */
45
46
  export function freezeSentForm(order: PosOrder): PosOrder {
46
47
  let changed = false;
48
+ const note = order.note === undefined ? undefined : cutText(order.note, ORDER_NOTE_MAX);
49
+ changed ||= note !== order.note;
47
50
  const lines = order.lines.map((line) => {
48
51
  const name = cutText(line.name, PAYLOAD_STRING_MAX);
49
52
  changed ||= name !== line.name;
@@ -84,7 +87,7 @@ export function freezeSentForm(order: PosOrder): PosOrder {
84
87
  if (!localWarnings.some((warning) => warning.code === 'customer_omitted' && warning.field === field)) localWarnings.push({ code: 'customer_omitted', field });
85
88
  }
86
89
  }
87
- return changed ? { ...order, lines, payments, customer, ...(charges.fees ? { fees: charges.fees } : {}),
90
+ return changed ? { ...order, lines, payments, customer, ...(note !== undefined ? { note } : {}), ...(charges.fees ? { fees: charges.fees } : {}),
88
91
  ...(charges.shipping ? { shipping: charges.shipping } : {}), ...(display ? { display } : {}), ...(localWarnings.length ? { localWarnings } : {}) } : order;
89
92
  }
90
93
 
@@ -142,6 +145,7 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
142
145
  if (payment.method !== 'cash' && payment.method !== 'external') {
143
146
  throw new Error(`finalize: unsupported payment method ${payment.method}`);
144
147
  }
148
+ if (legStatus(payment) !== 'captured') throw new Error(`finalize: the ${payment.method} payment is ${legStatus(payment)}, not captured`);
145
149
  }
146
150
  if (order.paidMinor < order.totalMinor) throw new Error('finalize: underpaid');
147
151
  let change = order.paidMinor - order.totalMinor;
@@ -9,4 +9,5 @@ export { getDeviceId } from './device-id';
9
9
  export { needsAttention } from './needs-attention';
10
10
  export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './reopen';
11
11
  export { isReopened, replacedOrderIds } from './reopened';
12
+ export { noteDelivery, type NoteDelivery } from './note-delivery';
12
13
  export { sameSale, OrderContentMismatchError } from './same-sale';
@@ -0,0 +1,13 @@
1
+ import type { PosOrder } from './types';
2
+
3
+ export type NoteDelivery = 'none' | 'pending' | 'sent' | 'not_sent';
4
+
5
+ /**
6
+ * ADR-083 condition 2: a note goes only at order.create 7, and the outbox stores the version every attempt goes out at
7
+ * (`sentVersion`, lowered on a downgrade), so a sale whose stored version is below 7 went without its note.
8
+ */
9
+ export function noteDelivery(order: Pick<PosOrder, 'note' | 'sentVersion'>): NoteDelivery {
10
+ if (!order.note) return 'none';
11
+ if (order.sentVersion === undefined) return 'pending';
12
+ return order.sentVersion >= 7 ? 'sent' : 'not_sent';
13
+ }
@@ -81,8 +81,9 @@ export async function reopenRefusedOrder(orderId: string, deps: {
81
81
  builder.setCustomer({ id: order.customer.id, name: order.customer.name,
82
82
  ...(order.customer.email !== undefined ? { email: order.customer.email } : {}) });
83
83
  }
84
- const prefix = `Refused by the store: ${order.error!.message}`;
85
- builder.setNote(prefix + (order.note ? '\n' + order.note : ''));
84
+ // ADR-083 condition 1: the note holds only the cashier's own note, since order.create 7 sends it. The refusal stays
85
+ // on this refused row (`error`), the till's record of it; the draft's id is this row's id.
86
+ if (order.note) builder.setNote(order.note);
86
87
  await writeOrderDraft(deps.drafts, builder.getSnapshot());
87
88
  }
88
89
  const document = await deps.orders.findOne(orderId).exec();
@@ -28,9 +28,10 @@ import type { PosOrder } from './types';
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
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
+ * 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.
31
32
  */
32
33
  export const posOrderSchema: RxJsonSchema<PosOrder> = {
33
- version: 10, primaryKey: 'id', type: 'object', additionalProperties: false,
34
+ version: 11, primaryKey: 'id', type: 'object', additionalProperties: false,
34
35
  properties: {
35
36
  id: { type: 'string', maxLength: 36 },
36
37
  saleId: { type: 'string', maxLength: 36 },
@@ -116,8 +117,8 @@ export const posOrderSchema: RxJsonSchema<PosOrder> = {
116
117
  roundAtSubtotal: { type: 'boolean' },
117
118
  mode: { type: 'string', enum: ['half_away_from_zero', 'half_up'] },
118
119
  }, required: ['granularity'] },
119
- sentVersion: { type: 'integer', minimum: 1, maximum: 6 },
120
- downgradedFrom: { type: 'integer', minimum: 1, maximum: 6 },
120
+ sentVersion: { type: 'integer', minimum: 1, maximum: 7 },
121
+ downgradedFrom: { type: 'integer', minimum: 1, maximum: 7 },
121
122
  // The nested objects are closed too: loosening a schema later is free, tightening one costs a migration.
122
123
  display: { type: 'object', additionalProperties: false, properties: {
123
124
  currency: { type: 'string' }, exponent: { type: 'integer' }, taxInclusive: { type: 'boolean' },
@@ -181,5 +182,5 @@ export function posOrderCollection(): { schema: RxJsonSchema<PosOrder>; migratio
181
182
  // it means no older sale is ever re-rounded (#287).
182
183
  const recordRounding = (doc: PosOrder) => { doc.taxRounding ??= { ...DEFAULT_TAX_ROUNDING }; return doc; };
183
184
  return { schema: posOrderSchema,
184
- migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity } };
185
+ migrationStrategies: { 1: identity, 2: identity, 3: identity, 4: identity, 5: recordSent, 6: recordRounding, 7: identity, 8: identity, 9: identity, 10: identity, 11: identity } };
185
186
  }
@@ -75,6 +75,7 @@ export interface PosOrder {
75
75
  totalMinor: number;
76
76
  payments: PosOrderPayment[];
77
77
  customer: { id?: string; name?: string; email?: string } | null;
78
+ /** The sale's note; sent as order.create version 7's `note` (ADR-083), cut to ORDER_NOTE_MAX when frozen. */
78
79
  note?: string;
79
80
  registerId?: string;
80
81
  /**
@@ -92,9 +93,9 @@ export interface PosOrder {
92
93
  * The order.create version every attempt under this `commandId` goes out at: the outbox records it before the first
93
94
  * send, and lowers it only on a downgrade (ADR-065 amendment). Absent means not sent yet (or requeued).
94
95
  */
95
- sentVersion?: 1 | 2 | 3 | 4 | 5 | 6;
96
+ sentVersion?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
96
97
  /** The version first tried, before the downgrade (the order's audit). */
97
- downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6;
98
+ downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
98
99
  /** ADR-065: the receipt's display figures, in integer minor units of `currency` at `exponent`. */
99
100
  display?: DisplayTotals & { currency: string; exponent: number };
100
101
  /** ADR-065: tax by rate, named as `taxLinesByRate` names them (`amountMinor` is the tax). */
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Character tables for ESC/POS text. WCPOS v2 (monorepo main) leaves the code page to
3
+ * `@point-of-sale/receipt-printer-encoder`; here two fixed tables cover Latin receipts without a dependency.
4
+ * `high` holds the characters for bytes 0x80-0xFF; `id` is the `ESC t n` table number.
5
+ */
6
+ export const ESCPOS_CODE_PAGES = {
7
+ cp437: {
8
+ id: 0,
9
+ high: 'ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀'
10
+ + 'αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00A0',
11
+ },
12
+ // PC850 with the euro sign at 0xD5.
13
+ cp858: {
14
+ id: 19,
15
+ high: 'ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤'
16
+ + 'ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´\u00AD±‗¾¶§÷¸°¨·¹³²■\u00A0',
17
+ },
18
+ } as const;
19
+
20
+ export type EscPosCodePageName = keyof typeof ESCPOS_CODE_PAGES;
21
+ export interface EscPosCodePage { id: number; high: string }
22
+
23
+ /** The named page; cp437 (ESC/POS table 0, the usual default) when the name is absent or unknown. */
24
+ export function resolveCodePage(name?: string): EscPosCodePage {
25
+ return ESCPOS_CODE_PAGES[name as EscPosCodePageName] ?? ESCPOS_CODE_PAGES.cp437;
26
+ }
27
+
28
+ const PRINTABLE_ASCII = /^[\x20-\x7E]$/;
29
+
30
+ /**
31
+ * Text the page can print, one character for one, so `length` is the columns it takes. v2's
32
+ * `normalizeThermalText` first (dashes and the minus sign to `-`, curly quotes to ASCII, no-break and thin
33
+ * spaces to a space); then a character the page has stays; `×` becomes `x`; an accented letter outside the
34
+ * page loses its accent (`ź` → `z`); anything else prints as `?`.
35
+ */
36
+ export function foldText(text: string, page: EscPosCodePage): string {
37
+ const normalized = text
38
+ .replace(/[\u2010-\u2014\u2212]/g, '-')
39
+ .replace(/[\u2018\u2019]/g, "'")
40
+ .replace(/[\u201C\u201D]/g, '"')
41
+ .replace(/[\u00A0\u202F\u2009\u2007]/g, ' ');
42
+ return Array.from(normalized, (char) => {
43
+ if (char === '\n' || PRINTABLE_ASCII.test(char) || page.high.includes(char)) return char;
44
+ if (char === '\u00D7') return 'x';
45
+ const base = char.normalize('NFD').replace(/[\u0300-\u036F]/g, '');
46
+ return PRINTABLE_ASCII.test(base) ? base : '?';
47
+ }).join('');
48
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * A small ESC/POS command builder. The command bytes follow WCPOS v2 (monorepo main): `escpos-text.ts`
3
+ * opens every job with `ESC @` then `ESC M 0` (Font A, so the profile's column count holds whatever the
4
+ * printer's memory switch says; v2 gotcha N39), and `render-escpos.ts` `writeCut` cuts with `GS V 0x41|0x42 0`
5
+ * (feed to the cutter, then cut). Text goes through `foldText`, so no multibyte UTF-8 ever reaches the printer.
6
+ */
7
+ import type { DrawerConnector } from '../../receipt-template/types';
8
+ import { foldText, resolveCodePage, type EscPosCodePage } from './code-page';
9
+
10
+ const ESC = 0x1b;
11
+ const GS = 0x1d;
12
+
13
+ export interface EscPosBuilder {
14
+ /** `ESC @` (reset), then `ESC M 0` (Font A). */
15
+ init(): EscPosBuilder;
16
+ /** `ESC t n`: select the builder's code page. */
17
+ codePage(): EscPosBuilder;
18
+ align(mode: 'left' | 'center' | 'right'): EscPosBuilder;
19
+ bold(on: boolean): EscPosBuilder;
20
+ /** `GS ! n`: character width and height multipliers, 1-8 each. */
21
+ size(width: number, height: number): EscPosBuilder;
22
+ /** Folded to the code page, one byte per character; `\n` is LF. */
23
+ text(value: string): EscPosBuilder;
24
+ /** `ESC d n`: print and feed n lines. */
25
+ feed(lines: number): EscPosBuilder;
26
+ cut(type?: 'full' | 'partial'): EscPosBuilder;
27
+ /** `ESC p m 25 250`: a drawer kick, on 50 ms and off 500 ms; m 0 for pin 2, 1 for pin 5. */
28
+ pulse(connector?: DrawerConnector): EscPosBuilder;
29
+ bytes(): Uint8Array;
30
+ }
31
+
32
+ export function escpos(page: EscPosCodePage = resolveCodePage()): EscPosBuilder {
33
+ const out: number[] = [];
34
+ const clamp = (n: number) => Math.min(8, Math.max(1, Math.round(n))) - 1;
35
+ const builder: EscPosBuilder = {
36
+ init: () => push(ESC, 0x40, ESC, 0x4d, 0),
37
+ codePage: () => push(ESC, 0x74, page.id),
38
+ align: (mode) => push(ESC, 0x61, mode === 'left' ? 0 : mode === 'center' ? 1 : 2),
39
+ bold: (on) => push(ESC, 0x45, on ? 1 : 0),
40
+ size: (width, height) => push(GS, 0x21, (clamp(width) << 4) | clamp(height)),
41
+ text: (value) => push(...Array.from(foldText(value, page), (char) =>
42
+ char.charCodeAt(0) < 0x80 ? char.charCodeAt(0) : 0x80 + page.high.indexOf(char))),
43
+ feed: (lines) => push(ESC, 0x64, Math.min(255, Math.max(0, lines))),
44
+ cut: (type = 'partial') => push(GS, 0x56, type === 'full' ? 0x41 : 0x42, 0),
45
+ pulse: (connector = 'pin2') => push(ESC, 0x70, connector === 'pin5' ? 1 : 0, 25, 250),
46
+ bytes: () => Uint8Array.from(out),
47
+ };
48
+ function push(...bytes: number[]): EscPosBuilder {
49
+ for (const byte of bytes) out.push(byte);
50
+ return builder;
51
+ }
52
+ return builder;
53
+ }