@tallyui/pos 3.12.0 → 3.13.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 (79) hide show
  1. package/dist/index.d.ts +1545 -300
  2. package/dist/index.js +4259 -2218
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +93 -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-state.ts +30 -0
  13. package/src/customer-display/index.ts +8 -0
  14. package/src/customer-display/protocol.ts +87 -0
  15. package/src/customer-display/snapshot.ts +65 -0
  16. package/src/index.ts +67 -10
  17. package/src/order/order-builder.ts +11 -1
  18. package/src/order/order-drafts.ts +16 -0
  19. package/src/order/types.ts +6 -3
  20. package/src/outbox/index.ts +5 -1
  21. package/src/outbox/outbox-health.ts +40 -0
  22. package/src/outbox/register-outbox.ts +59 -6
  23. package/src/outbox/safe-error.ts +11 -0
  24. package/src/outbox/types.ts +3 -1
  25. package/src/outbox/use-outbox-health.ts +22 -0
  26. package/src/outbox/use-register-outbox.ts +6 -0
  27. package/src/payment-driver/index.ts +8 -0
  28. package/src/payment-driver/registry.ts +39 -0
  29. package/src/payment-driver/simulated-driver.ts +104 -0
  30. package/src/payment-driver/types.ts +73 -0
  31. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  32. package/src/pos-order/command.ts +36 -16
  33. package/src/pos-order/finalize.ts +7 -3
  34. package/src/pos-order/index.ts +1 -0
  35. package/src/pos-order/note-delivery.ts +13 -0
  36. package/src/pos-order/reopen.ts +3 -2
  37. package/src/pos-order/schema.ts +5 -4
  38. package/src/pos-order/types.ts +3 -2
  39. package/src/print/index.ts +10 -0
  40. package/src/print/print-queue.ts +67 -0
  41. package/src/print/printer-profiles.ts +71 -0
  42. package/src/print/system-transport.ts +101 -0
  43. package/src/print/types.ts +40 -0
  44. package/src/receipt/reprint.ts +2 -1
  45. package/src/receipt/types.ts +2 -0
  46. package/src/receipt-template/default-templates.ts +78 -0
  47. package/src/receipt-template/index.ts +15 -0
  48. package/src/receipt-template/parse-xml.ts +175 -0
  49. package/src/receipt-template/render-html.ts +152 -0
  50. package/src/receipt-template/render-receipt.ts +19 -0
  51. package/src/receipt-template/render-template.ts +35 -0
  52. package/src/receipt-template/sanitize-html.ts +146 -0
  53. package/src/receipt-template/template-data.ts +97 -0
  54. package/src/receipt-template/types.ts +49 -0
  55. package/src/refund/index.ts +2 -0
  56. package/src/refund/refundable-lines.ts +91 -0
  57. package/src/register/export-csv.ts +24 -35
  58. package/src/register/float-suggestion.ts +22 -0
  59. package/src/register/index.ts +8 -3
  60. package/src/register/register-adoption.ts +71 -2
  61. package/src/register/register-commands.ts +7 -4
  62. package/src/register/register-count.helpers.ts +4 -0
  63. package/src/register/session-store.ts +4 -1
  64. package/src/register/use-register-session.ts +112 -28
  65. package/src/reports/adapters.ts +67 -0
  66. package/src/reports/index.ts +5 -0
  67. package/src/reports/presets.ts +27 -0
  68. package/src/reports/sales-figures.ts +173 -0
  69. package/src/reports/types.ts +63 -0
  70. package/src/sale/index.ts +3 -1
  71. package/src/sale/open-sales.ts +40 -0
  72. package/src/sale/use-sale.ts +72 -8
  73. package/src/scanner/index.ts +6 -0
  74. package/src/scanner/scan-session.ts +84 -0
  75. package/src/scanner/use-barcode-scanner.ts +61 -0
  76. package/src/scanner/wedge-detector.ts +137 -0
  77. package/src/tender/cash-rounding.ts +74 -0
  78. package/src/tender/index.ts +4 -0
  79. package/src/tender/payment-legs.ts +48 -0
@@ -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,10 @@
1
+ export { PrintError, toPrintError } from './types';
2
+ export type { PrintJob, PrintJobKind, PrintErrorCode, PrintTransport } from './types';
3
+ export { createPrintQueue, SYSTEM_PRINTER_ID } from './print-queue';
4
+ export type { PrintQueue, PrintQueueOptions, PrintQueueState } from './print-queue';
5
+ export {
6
+ PRINTER_PROFILES_COLLECTION, printerProfileSchema, printerProfileCollection, addPrinterProfileCollection,
7
+ } from './printer-profiles';
8
+ export type { PrinterProfile, PrinterProfileCollection } from './printer-profiles';
9
+ export { createSystemPrintTransport, SYSTEM_PRINT_TIMING } from './system-transport';
10
+ export type { SystemPrintTransportOptions } from './system-transport';
@@ -0,0 +1,67 @@
1
+ /**
2
+ * One serial queue per printer id. Ported from WCPOS v2 `packages/printer/src/printer-service.ts` (monorepo
3
+ * main), which keeps a `PQueue({ concurrency: 1 })` per profile because one shared queue let a stalled printer
4
+ * stall the till (its gotcha N44). Here a promise chain per printer id does the same without p-queue.
5
+ */
6
+ import { toPrintError, type PrintJob, type PrintTransport } from './types';
7
+
8
+ /** v2's queue id for the OS print dialog, which is one shared resource on the device. */
9
+ export const SYSTEM_PRINTER_ID = 'system';
10
+
11
+ export interface PrintQueueState {
12
+ printerId: string;
13
+ /** The id of the job printing now, or null. */
14
+ running: string | null;
15
+ /** Ids of the jobs waiting, in the order they will print. */
16
+ queued: string[];
17
+ }
18
+
19
+ export interface PrintQueueOptions {
20
+ transportFor: (printerId: string) => PrintTransport | Promise<PrintTransport>;
21
+ }
22
+
23
+ export interface PrintQueue {
24
+ /** Resolves when this job has printed; rejects with a `PrintError`. A failure never holds up the next job. */
25
+ print(printerId: string, job: PrintJob): Promise<void>;
26
+ state(printerId: string): PrintQueueState;
27
+ subscribe(listener: (state: PrintQueueState) => void): () => void;
28
+ }
29
+
30
+ export function createPrintQueue({ transportFor }: PrintQueueOptions): PrintQueue {
31
+ const tails = new Map<string, Promise<void>>();
32
+ const states = new Map<string, PrintQueueState>();
33
+ const listeners = new Set<(state: PrintQueueState) => void>();
34
+
35
+ const state = (printerId: string): PrintQueueState => states.get(printerId) ?? { printerId, running: null, queued: [] };
36
+ const update = (printerId: string, change: (current: PrintQueueState) => PrintQueueState) => {
37
+ const next = change(state(printerId));
38
+ states.set(printerId, next);
39
+ for (const listener of listeners) listener(next);
40
+ };
41
+
42
+ const run = async (printerId: string, job: PrintJob) => {
43
+ // Jobs start in enqueue order, so the starting job is the head of `queued`.
44
+ update(printerId, ({ queued }) => ({ printerId, running: job.id, queued: queued.slice(1) }));
45
+ try {
46
+ await (await transportFor(printerId)).print(job);
47
+ } catch (error) {
48
+ throw toPrintError(error);
49
+ } finally {
50
+ update(printerId, (current) => ({ ...current, running: null }));
51
+ }
52
+ };
53
+
54
+ return {
55
+ print(printerId, job) {
56
+ update(printerId, (current) => ({ ...current, queued: [...current.queued, job.id] }));
57
+ const result = (tails.get(printerId) ?? Promise.resolve()).then(() => run(printerId, job));
58
+ tails.set(printerId, result.catch(() => undefined));
59
+ return result;
60
+ },
61
+ state: (printerId) => ({ ...state(printerId) }),
62
+ subscribe(listener) {
63
+ listeners.add(listener);
64
+ return () => { listeners.delete(listener); };
65
+ },
66
+ };
67
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Printers set up on this device. Local only, never replicated; the app adds the collection as
3
+ * `printer_profiles`. Ported from WCPOS v2 `packages/database/src/collections/schemas/printer-profiles.ts`
4
+ * (monorepo main, version 0, device-local). Left out: v2's cloud fields (`cloudPrinterId`, `cloudProvider`,
5
+ * `connectionType: 'cloud'`; vendor services stay out of the MIT packages, ADR-084 decision 2), its vendor-SDK and
6
+ * encoder-library hints (`nativeInterfaceType`, `printerModel`), `emitEscPrintMode` and `fullReceiptRaster`.
7
+ * v2's schema defaults are kept as comments, not schema `default`s; a reader treats a missing field as its default.
8
+ */
9
+ import type { RxCollection, RxDatabase, RxJsonSchema } from 'rxdb';
10
+
11
+ export const PRINTER_PROFILES_COLLECTION = 'printer_profiles';
12
+
13
+ export interface PrinterProfile {
14
+ id: string;
15
+ /** User-assigned, e.g. "Front counter". */
16
+ name: string;
17
+ connectionType: 'system' | 'network' | 'bluetooth' | 'usb';
18
+ /** Default `generic`. */
19
+ vendor?: 'epson' | 'star' | 'generic';
20
+ /** IP address, Bluetooth address or USB path. */
21
+ address?: string;
22
+ /** Default 9100. */
23
+ port?: number;
24
+ /** Default `esc-pos`. */
25
+ language?: 'esc-pos' | 'star-prnt' | 'star-line';
26
+ /** Characters per line: 32 for 58 mm, 42 or 48 for 80 mm. Default 42. */
27
+ columns?: number;
28
+ /** The encoder's code page name, e.g. `cp437`; absent lets the encoder choose. */
29
+ codePage?: string;
30
+ /** Default true. */
31
+ autoCut?: boolean;
32
+ /** Default false. */
33
+ autoOpenDrawer?: boolean;
34
+ /** Default `pin2` (drawer 1). */
35
+ drawerConnector?: 'pin2' | 'pin5';
36
+ isDefault?: boolean;
37
+ /** A platform printer (the print dialog) that cannot be deleted. */
38
+ isBuiltIn?: boolean;
39
+ }
40
+
41
+ export const printerProfileSchema: RxJsonSchema<PrinterProfile> = {
42
+ title: 'Printer profiles', version: 0, primaryKey: 'id', type: 'object', additionalProperties: false,
43
+ properties: {
44
+ id: { type: 'string', maxLength: 36 },
45
+ name: { type: 'string' },
46
+ connectionType: { type: 'string', enum: ['system', 'network', 'bluetooth', 'usb'] },
47
+ vendor: { type: 'string', enum: ['epson', 'star', 'generic'] },
48
+ address: { type: 'string' },
49
+ port: { type: 'integer' },
50
+ language: { type: 'string', enum: ['esc-pos', 'star-prnt', 'star-line'] },
51
+ columns: { type: 'integer' },
52
+ codePage: { type: 'string' },
53
+ autoCut: { type: 'boolean' },
54
+ autoOpenDrawer: { type: 'boolean' },
55
+ drawerConnector: { type: 'string', enum: ['pin2', 'pin5'] },
56
+ isDefault: { type: 'boolean' },
57
+ isBuiltIn: { type: 'boolean' },
58
+ },
59
+ required: ['id', 'name', 'connectionType'],
60
+ };
61
+
62
+ export function printerProfileCollection(): { readonly schema: RxJsonSchema<PrinterProfile> } {
63
+ return { schema: printerProfileSchema } as const;
64
+ }
65
+
66
+ export type PrinterProfileCollection = RxCollection<PrinterProfile>;
67
+
68
+ export async function addPrinterProfileCollection(db: RxDatabase): Promise<PrinterProfileCollection> {
69
+ const added = await db.addCollections({ [PRINTER_PROFILES_COLLECTION]: printerProfileCollection() });
70
+ return added[PRINTER_PROFILES_COLLECTION] as PrinterProfileCollection;
71
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Prints rendered HTML through the platform print dialog. Ported from WCPOS v2 (monorepo main)
3
+ * `packages/printer/src/transport/system-print-adapter.web.ts` (hidden iframe, `print()`, `afterprint`) and
4
+ * `system-print-adapter.ts` (native, `expo-print`). On native the app injects `printHtml` (for example
5
+ * `(html) => Print.printAsync({ html })`), so this package takes no native dependency.
6
+ */
7
+ import { PrintError, type PrintJob, type PrintTransport } from './types';
8
+
9
+ /** v2's waits: let the frame render, give images 5 s, and settle after 60 s if `afterprint` never fires. */
10
+ export const SYSTEM_PRINT_TIMING = { renderDelayMs: 500, imageTimeoutMs: 5_000, afterPrintTimeoutMs: 60_000, removeDelayMs: 1_000 };
11
+ type SystemPrintTiming = typeof SYSTEM_PRINT_TIMING;
12
+
13
+ const FRAME_ID = 'tallyui-print-frame';
14
+
15
+ export interface SystemPrintTransportOptions {
16
+ /** Native: prints HTML through the OS dialog. When given, the iframe path is not used. */
17
+ printHtml?: (html: string) => Promise<void>;
18
+ /** Web: the document to print from; defaults to `globalThis.document`. */
19
+ document?: Document;
20
+ timing?: Partial<SystemPrintTiming>;
21
+ }
22
+
23
+ function imagesSettled(doc: Document, timeoutMs: number): Promise<void> {
24
+ const pending = Array.from(doc.images).filter((image) => !image.complete);
25
+ if (pending.length === 0) return Promise.resolve();
26
+ let timer: ReturnType<typeof setTimeout> | undefined;
27
+ return Promise.race([
28
+ Promise.all(pending.map((image) => new Promise<void>((resolve) => {
29
+ image.addEventListener('load', () => resolve(), { once: true });
30
+ image.addEventListener('error', () => resolve(), { once: true });
31
+ }))).then(() => undefined),
32
+ new Promise<void>((resolve) => { timer = setTimeout(resolve, timeoutMs); }),
33
+ ]).finally(() => clearTimeout(timer));
34
+ }
35
+
36
+ function printInFrame(doc: Document, html: string, timing: SystemPrintTiming): Promise<void> {
37
+ return new Promise<void>((resolve, reject) => {
38
+ doc.getElementById(FRAME_ID)?.remove();
39
+ const iframe = doc.createElement('iframe');
40
+ iframe.id = FRAME_ID;
41
+ Object.assign(iframe.style, { position: 'absolute', top: '-10000px', left: '-10000px', width: '0', height: '0' });
42
+ doc.body.appendChild(iframe);
43
+ const frameDoc = iframe.contentDocument;
44
+ const win = iframe.contentWindow;
45
+ if (!frameDoc || !win) {
46
+ iframe.remove();
47
+ reject(new PrintError('unavailable', 'The print frame has no document'));
48
+ return;
49
+ }
50
+ frameDoc.open();
51
+ frameDoc.write(html);
52
+ frameDoc.close();
53
+
54
+ setTimeout(() => {
55
+ void imagesSettled(frameDoc, timing.imageTimeoutMs).then(() => {
56
+ let settled = false;
57
+ const settle = (error?: unknown) => {
58
+ if (settled) return;
59
+ settled = true;
60
+ clearTimeout(fallback);
61
+ win.removeEventListener('afterprint', onAfterPrint);
62
+ // Removed later so the browser can finish spooling; the captured ref never removes a newer job's frame.
63
+ setTimeout(() => iframe.remove(), timing.removeDelayMs);
64
+ if (error === undefined) resolve();
65
+ else reject(new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error }));
66
+ };
67
+ const onAfterPrint = () => settle();
68
+ const fallback = setTimeout(onAfterPrint, timing.afterPrintTimeoutMs);
69
+ win.addEventListener('afterprint', onAfterPrint, { once: true });
70
+ try {
71
+ win.focus();
72
+ win.print();
73
+ } catch (error) {
74
+ settle(error);
75
+ }
76
+ });
77
+ }, timing.renderDelayMs);
78
+ });
79
+ }
80
+
81
+ export function createSystemPrintTransport(options: SystemPrintTransportOptions = {}): PrintTransport {
82
+ const timing = { ...SYSTEM_PRINT_TIMING, ...options.timing };
83
+ const { printHtml } = options;
84
+ return {
85
+ name: printHtml ? 'system-print-native' : 'system-print-web',
86
+ async print(job: PrintJob) {
87
+ if (job.html === undefined) throw new PrintError('unsupported', `The system dialog prints HTML; job ${job.id} has none`);
88
+ if (printHtml) {
89
+ try {
90
+ await printHtml(job.html);
91
+ } catch (error) {
92
+ throw new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error });
93
+ }
94
+ return;
95
+ }
96
+ const doc = options.document ?? globalThis.document;
97
+ if (!doc?.body) throw new PrintError('unavailable', 'No document to print from');
98
+ await printInFrame(doc, job.html, timing);
99
+ },
100
+ };
101
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The printing seam. Ported from WCPOS v2 `packages/printer/src/types.ts` (monorepo main): v2's
3
+ * `PrinterTransport` has `printRaw(bytes)` and `printHtml(html)`; here one `print(job)` takes a job that
4
+ * carries HTML, bytes or both, and each transport prints what it can.
5
+ */
6
+ export type PrintJobKind = 'receipt' | 'report' | 'test';
7
+
8
+ export interface PrintJob {
9
+ id: string;
10
+ kind: PrintJobKind;
11
+ /** Rendered HTML, for the system dialog (see `renderReceiptHtml`). */
12
+ html?: string;
13
+ /** Pre-encoded printer bytes (ESC/POS and the like), for a raw transport. */
14
+ bytes?: Uint8Array;
15
+ }
16
+
17
+ /** `unsupported`: this transport cannot print the job; `unavailable`: the platform has no way to print; `failed`: the print went wrong. */
18
+ export type PrintErrorCode = 'unsupported' | 'unavailable' | 'failed';
19
+
20
+ export class PrintError extends Error {
21
+ readonly code: PrintErrorCode;
22
+ constructor(code: PrintErrorCode, message: string, options?: { cause?: unknown }) {
23
+ super(message, options);
24
+ this.code = code;
25
+ this.name = 'PrintError';
26
+ }
27
+ }
28
+
29
+ export function toPrintError(error: unknown): PrintError {
30
+ if (error instanceof PrintError) return error;
31
+ return new PrintError('failed', error instanceof Error ? error.message : String(error), { cause: error });
32
+ }
33
+
34
+ export interface PrintTransport {
35
+ /** For logs, e.g. `system-print-web`. */
36
+ readonly name: string;
37
+ /** Resolves once the job is handed to the printer or dialog; rejects with a `PrintError`. */
38
+ print(job: PrintJob): Promise<void>;
39
+ disconnect?(): Promise<void>;
40
+ }
@@ -1,4 +1,5 @@
1
1
  import { minorUnitDigits, woocommerceTax, type StoreOrder } from '@tallyui/core';
2
+ import { noteDelivery } from '../pos-order/note-delivery';
2
3
  import type { PosOrder } from '../pos-order/types';
3
4
  import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
4
5
  import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
@@ -99,7 +100,7 @@ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCon
99
100
  },
100
101
  payments: order.payments.map((p) => ({ method: p.method, amountMinor: p.tenderedMinor ?? p.amountMinor, reference: p.reference })),
101
102
  changeDueMinor: sum(order.payments.map((p) => p.changeMinor ?? 0)),
102
- footer: { note: order.note || undefined, barcode: order.id },
103
+ footer: { note: order.note || undefined, ...(noteDelivery(order) === 'not_sent' ? { noteNotSent: true as const } : {}), barcode: order.id },
103
104
  currency: order.currency,
104
105
  };
105
106
  }