@tallyui/pos 3.20.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/index.d.ts +1005 -110
  2. package/dist/index.js +3156 -907
  3. package/package.json +6 -6
  4. package/src/app-settings/app-settings.ts +77 -0
  5. package/src/app-settings/index.ts +2 -0
  6. package/src/currency/currency-provider.tsx +5 -7
  7. package/src/currency/index.ts +1 -1
  8. package/src/customer/customer-patch.ts +70 -0
  9. package/src/customer-display/display-client.ts +11 -17
  10. package/src/customer-display/display-link.ts +10 -5
  11. package/src/customer-display/index.ts +3 -1
  12. package/src/customer-display/protocol.ts +1 -1
  13. package/src/customer-display/sale-display.ts +6 -8
  14. package/src/customer-display/snapshot-fallback.ts +14 -1
  15. package/src/customer-display/till-device.ts +62 -0
  16. package/src/customer-display/till-display-service.ts +44 -42
  17. package/src/customer-display/till-pairing.ts +20 -23
  18. package/src/customer-display/use-customer-display.ts +2 -1
  19. package/src/customer-display/use-till-pairing.ts +4 -4
  20. package/src/index.ts +37 -18
  21. package/src/order/allocate-order-discount.ts +5 -17
  22. package/src/order/apportion.ts +29 -0
  23. package/src/order/from-store-order.ts +115 -0
  24. package/src/order/index.ts +1 -0
  25. package/src/order/order-builder.ts +239 -52
  26. package/src/order/order-drafts.ts +45 -6
  27. package/src/order/order-manager.ts +2 -1
  28. package/src/order/tax-ids.ts +27 -0
  29. package/src/order/types.ts +59 -5
  30. package/src/order/woocommerce-tax.ts +9 -0
  31. package/src/outbox/index.ts +1 -1
  32. package/src/outbox/order-outbox.ts +138 -43
  33. package/src/outbox/register-outbox.ts +4 -3
  34. package/src/outbox/retry-delay.ts +8 -0
  35. package/src/outbox/use-order-outbox.ts +8 -2
  36. package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
  37. package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
  38. package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
  39. package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
  40. package/src/pos-order/attention-handled.ts +24 -0
  41. package/src/pos-order/command.ts +132 -12
  42. package/src/pos-order/extras-delivery.ts +14 -0
  43. package/src/pos-order/finalize.ts +138 -29
  44. package/src/pos-order/index.ts +7 -3
  45. package/src/pos-order/money-divergence.ts +19 -0
  46. package/src/pos-order/needs-attention.ts +9 -1
  47. package/src/pos-order/refund-due.ts +35 -0
  48. package/src/pos-order/reopen.ts +96 -12
  49. package/src/pos-order/schema.ts +35 -10
  50. package/src/pos-order/till-payments.ts +4 -0
  51. package/src/pos-order/types.ts +44 -5
  52. package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
  53. package/src/print/escpos/commands.ts +79 -0
  54. package/src/print/escpos/drawer.ts +25 -0
  55. package/src/print/escpos/encode.ts +1 -0
  56. package/src/print/escpos/index.ts +6 -1
  57. package/src/print/escpos/network-sinks.ts +130 -0
  58. package/src/print/escpos/render-escpos.ts +155 -0
  59. package/src/print/escpos/transport.ts +2 -1
  60. package/src/print/index.ts +5 -2
  61. package/src/print/resolve-printer.ts +46 -0
  62. package/src/print/types.ts +1 -1
  63. package/src/product/index.ts +2 -0
  64. package/src/product/terms.ts +42 -0
  65. package/src/product/tile-fields.ts +27 -0
  66. package/src/receipt/build-receipt-data.ts +12 -7
  67. package/src/receipt/carried-rows.ts +29 -0
  68. package/src/receipt/index.ts +1 -0
  69. package/src/receipt/reprint.ts +14 -8
  70. package/src/receipt/types.ts +3 -1
  71. package/src/receipt-template/default-templates.ts +3 -0
  72. package/src/receipt-template/template-data.ts +3 -0
  73. package/src/receipt-template/wcpos/build.ts +1 -0
  74. package/src/receipt-template/wcpos/format.ts +2 -2
  75. package/src/receipt-template/wcpos/from-orders.ts +6 -2
  76. package/src/receipt-template/wcpos/types.ts +5 -1
  77. package/src/register/closure-document.ts +42 -4
  78. package/src/register/closure-rows.ts +3 -2
  79. package/src/register/document-labels.ts +25 -0
  80. package/src/register/expected.ts +49 -10
  81. package/src/register/index.ts +5 -5
  82. package/src/register/money.ts +23 -0
  83. package/src/register/register-adoption.ts +6 -5
  84. package/src/register/register-commands.ts +4 -3
  85. package/src/register/schemas.ts +11 -3
  86. package/src/register/session-store.ts +44 -23
  87. package/src/register/settled-figures.ts +5 -19
  88. package/src/register/use-register-session.ts +18 -19
  89. package/src/reopen/index.ts +3 -0
  90. package/src/reopen/reopen-entry.ts +48 -0
  91. package/src/reopen/reopen-store-order.ts +78 -0
  92. package/src/reopen/send-order-reopen.ts +61 -0
  93. package/src/reports/adapters.ts +15 -7
  94. package/src/reports/sales-figures.ts +15 -1
  95. package/src/reports/types.ts +2 -0
  96. package/src/sale/cart.ts +4 -2
  97. package/src/sale/index.ts +1 -1
  98. package/src/sale/open-sales.ts +3 -0
  99. package/src/sale/use-sale.ts +388 -83
  100. package/src/sale/woocommerce/coupon-refetch.ts +1 -0
  101. package/src/sale/woocommerce/coupon-source.ts +4 -4
  102. package/src/sale/woocommerce/coupons.ts +6 -0
  103. package/src/sale/woocommerce/discount-codes.ts +1 -6
  104. package/src/scanner/analyze-trace.ts +86 -0
  105. package/src/scanner/device-scanner.ts +57 -0
  106. package/src/scanner/hid-scanner.ts +14 -41
  107. package/src/scanner/index.ts +2 -0
  108. package/src/scanner/serial-scanner.ts +15 -42
  109. package/src/scanner/use-barcode-scanner.ts +107 -5
  110. package/src/scanner/wedge-detector.ts +33 -15
  111. package/src/tax/exact.ts +1 -13
  112. package/src/tax/taxed-lines.ts +26 -0
  113. package/src/tender/index.ts +6 -1
  114. package/src/tender/split-units.ts +109 -0
  115. package/src/tender/tender-figures.ts +114 -0
  116. package/src/tender/tender-state.ts +105 -17
  117. package/src/currency/format-money-with.ts +0 -45
@@ -0,0 +1,155 @@
1
+ // After WCPOS v2 `receipt-renderer/src/render-escpos.ts` (monorepo main dfed181d1). Text is wrapped and aligned with
2
+ // spaces here, `ESC a` only wraps codes; row cells wrap (v2 truncates). Images are skipped; no `ESC 3` or `ESC !`.
3
+ import { parseXml } from '../../receipt-template/parse-xml';
4
+ import { renderReceiptTemplate } from '../../receipt-template/render-template';
5
+ import type { BarcodeNode, ColNode, DrawerConnector, QrcodeNode, ReceiptNode, ThermalNode } from '../../receipt-template/types';
6
+ import { foldText, resolveCodePage } from './code-page';
7
+ import { escpos, type EscPosBuilder } from './commands';
8
+ import { wrapText } from './encode';
9
+
10
+ export interface RenderEscposOptions {
11
+ /** Characters per line at 1× width. Default: the template's `paperWidth`. */ columns?: number;
12
+ /** A code page name for `resolveCodePage`. Default cp437. */ codePage?: string;
13
+ /** Pulse the drawer when the template has no `<drawer>` node (v2 rule). Default false. */ openDrawer?: boolean;
14
+ /** For `openDrawer` and for a `<drawer>` with no connector. Default 'pin2'. */ drawerConnector?: DrawerConnector;
15
+ }
16
+ interface Style { bold: boolean; underline: boolean; invert: boolean; width: number; height: number }
17
+ type Align = 'left' | 'center' | 'right';
18
+ const PLAIN: Style = { bold: false, underline: false, invert: false, width: 1, height: 1 };
19
+ /** v2 `collectTrailingControls`: the run of these ending the body follows the auto pulse and the style reset. */
20
+ const TRAILING = new Set<ThermalNode['type']>(['cut', 'feed', 'drawer']);
21
+ const BREAK = /\r\n|\r|\n/;
22
+ const leading = (text: string) => text.length - text.replace(/^ +/, '').length;
23
+
24
+ /** Print a parsed thermal template as ESC/POS bytes: `ESC @`, the code page, the body, then its trailing controls. */
25
+ export function renderEscpos(ast: ReceiptNode, options: RenderEscposOptions = {}): Uint8Array {
26
+ const page = resolveCodePage(options.codePage);
27
+ const columns = options.columns ?? ast.paperWidth;
28
+ const connector = options.drawerConnector ?? 'pin2';
29
+ const out = escpos(page).init().codePage();
30
+ let [style, printed] = [PLAIN, PLAIN];
31
+ let align: Align = 'left';
32
+ let line: { text: string; style: Style }[] = [];
33
+ // Lazy: only what changed since the last style sent.
34
+ const sync = (next: Style) => {
35
+ if (next.width !== printed.width || next.height !== printed.height) out.size(next.width, next.height);
36
+ if (next.bold !== printed.bold) out.bold(next.bold);
37
+ if (next.underline !== printed.underline) out.underline(next.underline);
38
+ if (next.invert !== printed.invert) out.invert(next.invert);
39
+ printed = next;
40
+ };
41
+ // One physical line: v2 `alignedPadding` as spaces, then each character in its own style, then LF.
42
+ const emit = (text: string, styles: Style[], mode: Align, scale: number) => {
43
+ const room = columns - text.length * scale;
44
+ const pad = Math.floor((mode === 'center' ? Math.floor(room / 2) : mode === 'right' ? room : 0) / scale);
45
+ if (text && pad > 0) { sync({ ...styles[0], underline: false, invert: false }); out.text(' '.repeat(pad)); }
46
+ Array.from(text).forEach((char, i) => { sync(styles[i]); out.text(char); });
47
+ out.text('\n');
48
+ };
49
+ // Ends the pending line (any line when forced). The indent repeats on wrapped lines, and a cursor maps each
50
+ // output character back to its source character's style (`wrapText` only drops spaces).
51
+ const endLine = (force: boolean) => {
52
+ if (!force && !line.length) return;
53
+ const text = line.map((run) => run.text).join('');
54
+ const styles = line.flatMap((run) => Array.from(run.text, () => run.style));
55
+ const scale = Math.max(1, ...line.map((run) => run.style.width));
56
+ const indent = leading(text);
57
+ line = [];
58
+ let cursor = indent;
59
+ for (const part of wrapText(text.slice(indent), Math.max(1, Math.floor(columns / scale) - indent))) {
60
+ const partStyles = Array.from(part, (char) => { while (text[cursor] !== char) cursor++; return styles[cursor++]; });
61
+ emit(' '.repeat(indent) + part, [...styles.slice(0, indent), ...partStyles], align, scale);
62
+ }
63
+ };
64
+ const row = (cols: ColNode[]) => {
65
+ const widths = rowWidths(cols, Math.floor(columns / style.width));
66
+ const cells = cols.map((col, i) => {
67
+ const text = foldText(extractText(col.children).split(BREAK).join(' '), page);
68
+ const indent = col.align === 'left' ? Math.min(leading(text), widths[i] - 1) : 0;
69
+ return wrapText(text.slice(leading(text)), widths[i] - indent).map((cell) =>
70
+ col.align === 'left' ? (' '.repeat(indent) + cell).padEnd(widths[i]) : cell.padStart(widths[i]));
71
+ });
72
+ const height = Math.max(0, ...cells.map((cell) => cell.length));
73
+ for (let r = 0; r < height; r++) {
74
+ sync(style);
75
+ out.text(cells.map((cell, i) => cell[r - height + cell.length] ?? ' '.repeat(widths[i])).join('') + '\n');
76
+ }
77
+ };
78
+ // Validated on a scratch builder first (13a throws before pushing), so a rejected value leaves no `ESC a`.
79
+ const code = (node: BarcodeNode | QrcodeNode) => {
80
+ if (!node.value) return;
81
+ const sym = node.type === 'qrcode' ? 'qrcode' : node.barcodeType.trim().toLowerCase();
82
+ const print = (to: EscPosBuilder) => node.type === 'qrcode' ? to.qrcode(node.value, { size: node.size })
83
+ : to.barcode(node.value, sym as 'code128' | 'ean13', { height: node.height, hri: 'below' });
84
+ let native = sym === 'qrcode' || sym === 'code128' || sym === 'ean13';
85
+ try { if (native) print(escpos(page)); } catch (error) {
86
+ if (!(error instanceof RangeError)) throw error;
87
+ native = false;
88
+ }
89
+ if (native) { print(out.align(align)).align('left'); return; }
90
+ emit(foldText(node.value, page), Array.from(node.value, () => style), 'center', style.width);
91
+ };
92
+ // Nested style and align nodes restore the context they found; an align ends its pending line inside.
93
+ const within = (children: ThermalNode[], nextStyle: Style, nextAlign: Align, ends = false) => {
94
+ const saved = [style, align] as const;
95
+ [style, align] = [nextStyle, nextAlign];
96
+ children.forEach(walk);
97
+ if (ends) endLine(false);
98
+ [style, align] = saved;
99
+ };
100
+ const walk = (node: ThermalNode): void => {
101
+ switch (node.type) {
102
+ case 'raw-text': return node.value.split(BREAK).forEach((part, i) => {
103
+ if (i > 0) endLine(true);
104
+ if (part) line.push({ text: foldText(part, page), style });
105
+ });
106
+ case 'text': node.children.forEach(walk); return endLine(true);
107
+ case 'image': return;
108
+ case 'receipt': case 'col': return node.children.forEach(walk);
109
+ case 'size': return within(node.children, { ...style, width: node.width, height: node.height }, align);
110
+ case 'bold': case 'underline': case 'invert': return within(node.children, { ...style, [node.type]: true }, align);
111
+ case 'align': endLine(false); return within(node.children, style, node.mode, true);
112
+ }
113
+ endLine(false);
114
+ switch (node.type) {
115
+ case 'row': return row(node.children);
116
+ case 'barcode': case 'qrcode': return code(node);
117
+ case 'feed': out.text('\n'.repeat(node.lines)); return;
118
+ case 'cut': out.cut(node.cutType); return;
119
+ case 'drawer': out.pulse(node.connector ?? connector); return;
120
+ case 'line':
121
+ sync(style);
122
+ out.text((node.style === 'dotted' ? '. '.repeat(Math.ceil(columns / 2)).slice(0, columns)
123
+ : (node.style === 'double' ? '═' : '-').repeat(columns)) + '\n');
124
+ }
125
+ };
126
+ const body = ast.children;
127
+ let end = body.length;
128
+ while (end > 0 && TRAILING.has(body[end - 1].type)) end--;
129
+ body.slice(0, end).forEach(walk);
130
+ endLine(false);
131
+ if (options.openDrawer && !hasDrawer(body)) out.pulse(connector);
132
+ sync(PLAIN);
133
+ body.slice(end).forEach(walk);
134
+ return out.bytes();
135
+ }
136
+
137
+ /** WCPOS v2's `encodeThermalTemplate`: Mustache (`renderReceiptTemplate`), then `parseXml`, then `renderEscpos`. */
138
+ export function encodeThermalTemplate(template: string, data: object, options?: RenderEscposOptions): Uint8Array {
139
+ return renderEscpos(parseXml(renderReceiptTemplate(template, data)), options);
140
+ }
141
+
142
+ /** v2 `resolveThermalRowWidths`: the last `*` column takes the remainder; every `*` column is at least 1. */
143
+ function rowWidths(cols: ColNode[], columns: number): number[] {
144
+ const fixed = cols.reduce((sum, col) => sum + (col.width === '*' ? 0 : col.width), 0);
145
+ const stars = cols.filter((col) => col.width === '*').length;
146
+ const remaining = Math.max(0, columns - fixed);
147
+ const star = stars ? Math.floor(remaining / stars) : 0;
148
+ let k = 0;
149
+ return cols.map((col) => col.width !== '*' ? col.width : Math.max(1, star + (++k === stars ? remaining - star * stars : 0)));
150
+ }
151
+ /** v2 `extractText`: raw text as is, a node with children recursed, anything else empty. */
152
+ const extractText = (nodes: ThermalNode[]): string =>
153
+ nodes.map((node) => node.type === 'raw-text' ? node.value : 'children' in node ? extractText(node.children) : '').join('');
154
+ const hasDrawer = (nodes: ThermalNode[]): boolean =>
155
+ nodes.some((node) => node.type === 'drawer' || ('children' in node && hasDrawer(node.children)));
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * A `PrintTransport` that writes ESC/POS bytes to a sink the app supplies (WebUSB, WebSerial, a TCP socket,
3
- * Bluetooth). It holds no device code; ADR-084 decision 2 keeps vendor SDKs out of the MIT packages. Run it
3
+ * Bluetooth); the pos package ships the Epson ePOS and Star WebPRNT web sinks (`networkSinkFor`). It holds no
4
+ * device code; ADR-084 decision 2 keeps vendor SDKs out of the MIT packages. Run it
4
5
  * through `createPrintQueue`, like the system transport, so one printer prints one job at a time.
5
6
  */
6
7
  import type { ReceiptTemplateOptions } from '../../receipt-template/template-data';
@@ -6,7 +6,10 @@ export {
6
6
  PRINTER_PROFILES_COLLECTION, printerProfileSchema, printerProfileCollection, addPrinterProfileCollection,
7
7
  } from './printer-profiles';
8
8
  export type { PrinterProfile, PrinterProfileCollection } from './printer-profiles';
9
+ export { resolvePrinter, templateColumns } from './resolve-printer';
10
+ export type { ResolvePrinterOptions } from './resolve-printer';
9
11
  export { createSystemPrintTransport, SYSTEM_PRINT_TIMING } from './system-transport';
10
12
  export type { SystemPrintTransportOptions } from './system-transport';
11
- export { escpos, encodeEscPos, createEscPosTransport, ESCPOS_CODE_PAGES } from './escpos';
12
- export type { EscPosBuilder, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions } from './escpos';
13
+ export { escpos, encodeEscPos, createEscPosTransport, ESCPOS_CODE_PAGES, renderEscpos, encodeThermalTemplate } from './escpos';
14
+ export { createEpsonEposSink, createStarWebPrntSink, networkSinkFor, canOpenDrawer, openDrawerJob } from './escpos';
15
+ export type { EscPosBuilder, EscPosBarcodeOptions, EscPosQrOptions, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions, NetworkSinkOptions, RenderEscposOptions } from './escpos';
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Which printer prints a template: the cashier's pick for this print, else the device's per-template override,
3
+ * else the first match by paper (the default printer first). Ported from WCPOS v2
4
+ * `packages/printer/src/resolve-printer.ts` (monorepo main). A thermal template matches a non-dialog printer whose
5
+ * columns fit its paper (58mm -> 32; 80mm or unset -> 42 or 48); an html template matches the print dialog.
6
+ */
7
+ import type { ReceiptTemplate } from '@tallyui/core';
8
+ import type { PrinterProfile } from './printer-profiles';
9
+
10
+ export interface ResolvePrinterOptions {
11
+ template: Pick<ReceiptTemplate, 'id' | 'engine' | 'paper'>;
12
+ profiles: readonly PrinterProfile[];
13
+ /** Template id -> printer profile id, set on this device. A missing or deleted profile falls through to auto. */
14
+ overrides?: Readonly<Record<string, string>>;
15
+ /** The cashier's pick at print time. A pick that names no profile resolves to null, as in v2. */
16
+ manualPrinterId?: string;
17
+ }
18
+
19
+ /** `PrinterProfile.columns` when absent. */
20
+ const DEFAULT_COLUMNS = 42;
21
+
22
+ /** The column counts a thermal template's paper fits: 58mm -> [32]; 80mm or unset -> [42, 48]. */
23
+ export function templateColumns(paper: ReceiptTemplate['paper']): readonly number[] {
24
+ return paper === '58mm' ? [32] : [42, 48];
25
+ }
26
+
27
+ export function resolvePrinter(options: ResolvePrinterOptions): PrinterProfile | null {
28
+ const { template, profiles, overrides, manualPrinterId } = options;
29
+
30
+ if (manualPrinterId) return profiles.find((p) => p.id === manualPrinterId) ?? null;
31
+
32
+ const overrideId = overrides?.[template.id];
33
+ const override = overrideId ? profiles.find((p) => p.id === overrideId) : undefined;
34
+ if (override) return override;
35
+
36
+ let candidates: readonly PrinterProfile[];
37
+ if (template.engine === 'thermal') {
38
+ const columns = templateColumns(template.paper);
39
+ candidates = profiles.filter(
40
+ (p) => p.connectionType !== 'system' && columns.includes(p.columns ?? DEFAULT_COLUMNS),
41
+ );
42
+ } else {
43
+ candidates = profiles.filter((p) => p.connectionType === 'system');
44
+ }
45
+ return candidates.find((p) => p.isDefault === true) ?? candidates[0] ?? null;
46
+ }
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import type { ReceiptData } from '../receipt/types';
7
7
 
8
- export type PrintJobKind = 'receipt' | 'report' | 'test';
8
+ export type PrintJobKind = 'receipt' | 'report' | 'test' | 'drawer';
9
9
 
10
10
  export interface PrintJob {
11
11
  id: string;
@@ -1,5 +1,7 @@
1
1
  export { searchProducts } from './search-products';
2
2
  export { productCategories, listCategories, inCategory } from './categories';
3
+ export { productTerms, listTermGroups, hasTerm, type ProductTermGroup } from './terms';
4
+ export { TILE_FIELDS, DEFAULT_TILE_FIELDS, normalizeTileFields, type TileField, type TileFields } from './tile-fields';
3
5
  export { catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE, type CatalogueView, type CatalogueGridColumns, type CatalogueViewState, type CatalogueViewAction } from './catalogue-view-state';
4
6
  export { sortProducts, productSortValue, PRODUCT_SORT_FIELDS, type ProductSort, type ProductSortValue } from './sort-products';
5
7
  export { withStockOverlay, getProductStock, stockOverlay$, stockOverlayAsOf$ } from './stock';
@@ -0,0 +1,42 @@
1
+ import type { ProductTerm, ProductTraits } from '@tallyui/core';
2
+
3
+ /** One term group across a set of products, e.g. Brand with its terms. */
4
+ export interface ProductTermGroup {
5
+ id: string;
6
+ name: string;
7
+ terms: { id: string; name: string }[];
8
+ }
9
+
10
+ /** By name (natural, case-insensitive), ties by id: the same order as `listCategories`. */
11
+ function byName(a: { id: string; name: string }, b: { id: string; name: string }): number {
12
+ return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' })
13
+ || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
14
+ }
15
+
16
+ /** The product's terms: `getTerms`, else none. */
17
+ export function productTerms<Doc>(doc: Doc, traits: ProductTraits<Doc>): ProductTerm[] {
18
+ return traits.getTerms?.(doc) ?? [];
19
+ }
20
+
21
+ /** Every term group across `docs`, once per group id and each term once per id (the first name seen wins), groups and terms sorted by name. */
22
+ export function listTermGroups<Doc>(docs: readonly Doc[], traits: ProductTraits<Doc>): ProductTermGroup[] {
23
+ const groups = new Map<string, { id: string; name: string; terms: Map<string, { id: string; name: string }> }>();
24
+ for (const doc of docs) {
25
+ for (const term of productTerms(doc, traits)) {
26
+ let group = groups.get(term.group);
27
+ if (!group) {
28
+ group = { id: term.group, name: term.groupName, terms: new Map() };
29
+ groups.set(term.group, group);
30
+ }
31
+ if (!group.terms.has(term.id)) group.terms.set(term.id, { id: term.id, name: term.name });
32
+ }
33
+ }
34
+ return [...groups.values()]
35
+ .map(({ id, name, terms }) => ({ id, name, terms: [...terms.values()].sort(byName) }))
36
+ .sort(byName);
37
+ }
38
+
39
+ /** Whether `doc` carries the term with this id in this group. */
40
+ export function hasTerm<Doc>(doc: Doc, group: string, termId: string, traits: ProductTraits<Doc>): boolean {
41
+ return productTerms(doc, traits).some((term) => term.group === group && term.id === termId);
42
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Which words a catalogue grid tile shows (vendurepos gap 9.9). Device-local, kept in app_settings as
3
+ * `catalogue.tileFields`. v2 provenance: WCPOS monorepo `core/src/screens/main/pos/products/ui-settings-form.tsx`
4
+ * (`gridFields`, nine switches). TallyUI's keys are camelCase; v2's tax and cost_of_goods_sold are not here yet.
5
+ */
6
+ export const TILE_FIELDS = ['name', 'price', 'onSale', 'categories', 'sku', 'barcode', 'stock'] as const;
7
+ export type TileField = (typeof TILE_FIELDS)[number];
8
+ export type TileFields = Readonly<Record<TileField, boolean>>;
9
+
10
+ /** Today's tile: name, price with its on-sale strike, and the stock status. Desk 19 Nov (Q6): the default stays today's. */
11
+ export const DEFAULT_TILE_FIELDS: TileFields = Object.freeze({
12
+ name: true, price: true, onSale: true, categories: false, sku: false, barcode: false, stock: true,
13
+ });
14
+
15
+ /**
16
+ * Each field takes the value's own boolean, else its default, so a value stored before a field was added keeps its
17
+ * switches. Unknown keys are dropped; a non-object (including an array) gives `undefined`.
18
+ */
19
+ export function normalizeTileFields(value: unknown): TileFields | undefined {
20
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;
21
+ const fields = {} as Record<TileField, boolean>;
22
+ for (const field of TILE_FIELDS) {
23
+ const own = Object.hasOwn(value, field) ? (value as Record<string, unknown>)[field] : undefined;
24
+ fields[field] = typeof own === 'boolean' ? own : DEFAULT_TILE_FIELDS[field];
25
+ }
26
+ return fields;
27
+ }
@@ -1,15 +1,15 @@
1
1
  import type { Discount, SentOrder } from '../order/types';
2
+ import { lockedRefundDueMinor } from '../pos-order/refund-due';
2
3
  import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
4
+ import { taxedLinesFor } from '../tax/taxed-lines';
5
+ import { carriedRows } from './carried-rows';
3
6
  import type { ReceiptConfig, ReceiptData } from './types';
4
7
  import { RECEIPT_SCHEMA_VERSION } from './types';
5
8
 
6
9
  export function buildReceiptData(order: SentOrder, config: ReceiptConfig): ReceiptData {
7
10
  // Drops the shared helper's `netMinor` (the Z report's own use): the receipt's tax summary
8
11
  // never showed it, and an exact-shape test elsewhere in this package pins that.
9
- const taxedLines = [...order.lineItems.map((line) => order.taxRounding?.granularity === 'woocommerce' && line.netMicros !== undefined
10
- ? { ...line, taxInclusive: order.pricesIncludeTax } : line), ...[...(order.fees ?? []), ...(order.shipping ?? [])].map((charge) => ({
11
- ...charge, taxInclusive: order.pricesIncludeTax,
12
- }))];
12
+ const taxedLines = taxedLinesFor(order.lineItems, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
13
13
  const taxLines = taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding).map(
14
14
  ({ label, code, ratePpm, amountMinor }) => ({ label, code, ratePpm, amountMinor }),
15
15
  );
@@ -28,6 +28,7 @@ export function buildReceiptData(order: SentOrder, config: ReceiptConfig): Recei
28
28
  });
29
29
  const label = (d: Discount) => d.label ?? d.couponCode ?? `${d.type} discount`;
30
30
  const customer = order.customer?.name || order.customer?.email;
31
+ const refundDueMinor = lockedRefundDueMinor(order);
31
32
 
32
33
  return {
33
34
  schemaVersion: RECEIPT_SCHEMA_VERSION,
@@ -57,7 +58,9 @@ export function buildReceiptData(order: SentOrder, config: ReceiptConfig): Recei
57
58
  // Line plus allocated order discounts, in the line's own mode; lineTotalMinor is already after it (ADR-062).
58
59
  ...(li.discountMinor > 0 ? { discountMinor: li.discountMinor } : {}),
59
60
  displayAmountMinor: order.display.lines[index].amountMinor,
60
- displayDiscounts: order.display.lines[index].discounts.map((row, i) => ({ label: label(li.discounts[i]), amountMinor: row.amountMinor })),
61
+ displayDiscounts: [...order.display.lines[index].discounts.map((row, i) => ({ label: label(li.discounts[i]), amountMinor: row.amountMinor })),
62
+ ...carriedRows(order.coupons, li.id, (id) => order.lineItems.find((line) => line.id === id)?.taxInclusive ?? order.display.taxInclusive,
63
+ order.display.taxInclusive, order.display.coupons)],
61
64
  })),
62
65
  discounts: order.discounts.map((d) => ({
63
66
  label: label(d),
@@ -76,10 +79,12 @@ export function buildReceiptData(order: SentOrder, config: ReceiptConfig): Recei
76
79
  },
77
80
  payments: order.payments.map((p) => ({
78
81
  method: p.method,
79
- amountMinor: p.amountMinor,
82
+ amountMinor: p.tenderedMinor ?? p.amountMinor,
83
+ ...(p.changeMinor !== undefined ? { changeMinor: p.changeMinor } : {}),
80
84
  reference: p.reference,
81
85
  })),
82
- changeDueMinor: order.changeDueMinor,
86
+ changeDueMinor: order.changeDueMinor - refundDueMinor + order.payments.reduce((sum, p) => sum + (p.changeMinor ?? 0), 0),
87
+ ...(refundDueMinor > 0 ? { refundDueMinor } : {}),
83
88
  footer: {
84
89
  note: order.note || undefined,
85
90
  barcode: order.id,
@@ -0,0 +1,29 @@
1
+ /** A carried coupon's receipt label: derived from `carried`, never stored (Front desk, 2026-11-21). */
2
+ export const carriedCouponLabel = (code: string) => `coupon ${code} not accepted at send`;
3
+
4
+ /** Whether a receipt row is a carried coupon's derived label (carriedCouponLabel). */
5
+ export const isCarriedCouponLabel = (label: string) => label.startsWith('coupon ') && label.endsWith(' not accepted at send');
6
+
7
+ /**
8
+ * One display row per carried coupon, in coupon order, that priced this line. The coupon's display row is its shares'
9
+ * total, and the stored `amountMinor` is in each line's own mode, so it is used only when every share stores it and every
10
+ * line of the coupon is in the display mode; otherwise the row is the coupon's share in the display mode on every line.
11
+ * When the coupon's display row is known (`displayRows`, aligned with `coupons`), its last listed line takes what its other
12
+ * rows leave of it, so the rows add up to it even when order-rounded tax puts the shares a cent off; never below 0.
13
+ */
14
+ export function carriedRows(coupons: ReadonlyArray<{ code: string; carried?: true; lines?: ReadonlyArray<{ lineId: string; discountMinor: number; discountTaxMinor: number; amountMinor?: number }> }> | undefined,
15
+ lineId: string, inclusiveOf: (lineId: string) => boolean, displayInclusive: boolean,
16
+ displayRows: ReadonlyArray<{ code: string; amountMinor: number }> | undefined): Array<{ label: string; amountMinor: number }> {
17
+ return (coupons ?? []).flatMap((coupon, k) => {
18
+ if (!coupon.carried || !coupon.lines?.some((entry) => entry.lineId === lineId)) return [];
19
+ const shares = coupon.lines;
20
+ const stored = shares.every((share) => share.amountMinor !== undefined && inclusiveOf(share.lineId) === displayInclusive);
21
+ const amounts = shares.map((share) => stored ? share.amountMinor!
22
+ : displayInclusive ? share.discountMinor + share.discountTaxMinor : share.discountMinor);
23
+ const row = displayRows?.[k];
24
+ const last = row && row.code === coupon.code ? row.amountMinor - amounts.slice(0, -1).reduce((sum, amount) => sum + amount, 0) : -1;
25
+ if (last >= 0) amounts[amounts.length - 1] = last;
26
+ const amountMinor = amounts[shares.findIndex((entry) => entry.lineId === lineId)]!;
27
+ return amountMinor !== 0 ? [{ label: carriedCouponLabel(coupon.code), amountMinor }] : [];
28
+ });
29
+ }
@@ -1,4 +1,5 @@
1
1
  export { buildReceiptData } from './build-receipt-data';
2
2
  export { buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder } from './reprint';
3
3
  export { RECEIPT_SCHEMA_VERSION } from './types';
4
+ export { isCarriedCouponLabel } from './carried-rows';
4
5
  export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, ReceiptRegister, ReceiptFiscal } from './types';
@@ -1,7 +1,10 @@
1
1
  import type { StoreOrder } from '@tallyui/core';
2
2
  import { noteDelivery } from '../pos-order/note-delivery';
3
+ import { refundDueOf } from '../pos-order/refund-due';
3
4
  import type { PosOrder } from '../pos-order/types';
4
5
  import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
6
+ import { recordedTaxByRate, taxedLinesFor } from '../tax/taxed-lines';
7
+ import { carriedRows } from './carried-rows';
5
8
  import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
6
9
  import { RECEIPT_SCHEMA_VERSION } from './types';
7
10
  import { wooGrossMinor } from './woo-gross';
@@ -33,6 +36,7 @@ const sum = (amounts: number[]) => amounts.reduce((total, amount) => total + amo
33
36
  export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptConfig): ReceiptData {
34
37
  const { header, ...blocks } = reprintBlocks(config, order.customer);
35
38
  const { display, taxRounding: rounding } = order;
39
+ const refundDueMinor = refundDueOf(order);
36
40
  const lineTaxMicros = (line: PosOrder['lines'][number]) => line.taxLines.reduce((total, row) => total + BigInt(row.taxMicros), 0n);
37
41
  let taxSoFar = order.pricesIncludeTax ? 0n : order.lines.reduce((total, line) => line.taxInclusive === undefined ? total + lineTaxMicros(line) : total, 0n);
38
42
  const lineTotals = order.lines.map((line) => {
@@ -45,9 +49,12 @@ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCon
45
49
  const lineItems = order.lines.map((line, index): ReceiptLineItem => {
46
50
  const displayLine = display?.lines.find((row) => row.lineId === line.id);
47
51
  const displayAmountMinor = display ? displayLine?.amountMinor ?? 0 : line.taxInclusive !== undefined ? lineTotals[index]! + line.discountMinor : line.unitPriceMinor * line.quantity;
48
- const displayDiscounts = display
52
+ const displayDiscounts = [...display
49
53
  ? (displayLine?.discounts ?? []).map((d) => ({ label: d.label ?? 'Discount', amountMinor: d.amountMinor }))
50
- : line.discountMinor > 0 ? [{ label: 'Discount', amountMinor: line.discountMinor }] : [];
54
+ : line.discountMinor > 0 ? [{ label: 'Discount', amountMinor: line.discountMinor }] : [],
55
+ ...carriedRows(order.coupons, line.id, (id) => { const other = order.lines.find((row) => row.id === id);
56
+ return other ? other.taxInclusive ?? order.pricesIncludeTax : display ? display.taxInclusive : order.pricesIncludeTax; },
57
+ display ? display.taxInclusive : order.pricesIncludeTax, display?.coupons)];
51
58
  return {
52
59
  name: line.name,
53
60
  ...(line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
@@ -60,12 +67,10 @@ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCon
60
67
  displayDiscounts,
61
68
  };
62
69
  });
63
- // Without taxByRate (finalized below order.create v3), the rows are computed as buildReceiptData computes them. A line's
64
- // taxInclusive is stored only when it differs from the order's mode; WooCommerce lines take the order's, as there.
65
- const taxedLines = [...order.lines.map((line) => ({ ...line, taxInclusive: order.taxRounding.granularity === 'woocommerce'
66
- && line.netMicros !== undefined ? order.pricesIncludeTax : line.taxInclusive ?? order.pricesIncludeTax })),
67
- ...[...(order.fees ?? []), ...(order.shipping ?? [])].map((charge) => ({ ...charge, taxInclusive: order.pricesIncludeTax }))];
68
- const taxLines = order.taxByRate ? order.taxByRate.map((row) => ({
70
+ // Use a stored split unless recordedTaxByRate refuses it; otherwise compute it as buildReceiptData does.
71
+ const taxedLines = taxedLinesFor(order.lines, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
72
+ const recorded = recordedTaxByRate(order);
73
+ const taxLines = recorded ? recorded.map((row) => ({
69
74
  label: config.taxLabels?.[row.ratePpm] ?? row.label ?? `Tax ${row.ratePpm / 10000}%`, code: row.code, ratePpm: row.ratePpm, amountMinor: row.amountMinor,
70
75
  })) : taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding)
71
76
  .map(({ label, code, ratePpm, amountMinor }) => ({ label, code, ratePpm, amountMinor }));
@@ -93,6 +98,7 @@ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCon
93
98
  },
94
99
  payments: order.payments.map((p) => ({ method: p.method, amountMinor: p.tenderedMinor ?? p.amountMinor, reference: p.reference })),
95
100
  changeDueMinor: sum(order.payments.map((p) => p.changeMinor ?? 0)),
101
+ ...(refundDueMinor > 0 ? { refundDueMinor } : {}),
96
102
  footer: { note: order.note || undefined, ...(noteDelivery(order) === 'not_sent' ? { noteNotSent: true as const } : {}), barcode: order.id },
97
103
  currency: order.currency,
98
104
  };
@@ -54,8 +54,10 @@ export interface ReceiptData {
54
54
  taxMinor: number; // order.display.taxMinor
55
55
  totalMinor: number; // order.display.totalMinor
56
56
  };
57
- payments: { method: string; amountMinor: number; reference?: string }[];
57
+ payments: { method: string; amountMinor: number; changeMinor?: number; reference?: string }[];
58
58
  changeDueMinor: number;
59
+ /** What the store owes back on a reopened sale (ADR-090); present only when above 0. Never part of changeDueMinor. */
60
+ refundDueMinor?: number;
59
61
  footer: {
60
62
  note?: string;
61
63
  /** ADR-083 condition 2: set only on a reprint of a till order whose note was not sent to the store. */
@@ -63,6 +63,9 @@ function receiptTemplate(columns: number, labelWidth: number, amountWidth: numbe
63
63
  {{#change}}
64
64
  <row><col width="*">Change</col><col width="${amountWidth}" align="right">{{change}}</col></row>
65
65
  {{/change}}
66
+ {{#refundDue}}
67
+ <row><col width="*">Refund due</col><col width="${amountWidth}" align="right">{{refundDue}}</col></row>
68
+ {{/refundDue}}
66
69
  {{#note}}
67
70
  <feed lines="1" />
68
71
  <text>{{note}}</text>
@@ -29,6 +29,8 @@ export interface ReceiptTemplateData {
29
29
  total: string;
30
30
  payments: { method: string; amount: string; reference: string }[];
31
31
  change: string;
32
+ /** What the store owes back on a reopened sale (ADR-090); present only when above 0. Never shown as change. */
33
+ refundDue?: string;
32
34
  note: string;
33
35
  qrPayload: string;
34
36
  }
@@ -91,6 +93,7 @@ export function receiptTemplateData(receipt: ReceiptData, options: ReceiptTempla
91
93
  method: paymentLabel(payment.method), amount: money(payment.amountMinor), reference: payment.reference ?? '',
92
94
  })),
93
95
  change: receipt.changeDueMinor > 0 ? money(receipt.changeDueMinor) : '',
96
+ ...(receipt.refundDueMinor && receipt.refundDueMinor > 0 ? { refundDue: money(receipt.refundDueMinor) } : {}),
94
97
  note: receipt.footer.note ?? '',
95
98
  qrPayload: fiscal.qr_payload,
96
99
  };
@@ -286,6 +286,7 @@ export function wcposReceiptData(
286
286
  // Gap §5.4: the tendered sum and the change TallyUI recorded, where v2 defaults to the total and 0.
287
287
  paid_total: payments.length > 0 ? major(sum(source.payments.map((payment) => payment.amountMinor))) : totalIncl,
288
288
  change_total: major(source.changeMinor ?? 0),
289
+ ...(source.refundDueMinor && source.refundDueMinor > 0 ? { refund_due_total: major(source.refundDueMinor) } : {}),
289
290
  total_qty: lineSum((calc) => calc.qty), line_count: calcs.length,
290
291
  },
291
292
  tax: {
@@ -14,7 +14,7 @@ export const WCPOS_DEFAULT_I18N: Readonly<Record<string, string>> = {
14
14
  subtotal: 'Subtotal', total_saved: 'Total saved', total: 'Total', tax: 'Tax', tax_summary: 'Tax Summary',
15
15
  included_tax: 'Tax included', total_tax: 'Total Tax', tax_amount_short: 'Tax', taxable_excl_short: 'Taxable excl.',
16
16
  taxable_incl_short: 'Taxable incl.', total_refunded: 'Total Refunded', refunded: 'Refunded', net_total: 'Net Total',
17
- tendered: 'Tendered', change: 'Change', thank_you: 'Thank you', thank_you_purchase: 'Thank you for your purchase!',
17
+ tendered: 'Tendered', change: 'Change', refund_due: 'Refund due', thank_you: 'Thank you', thank_you_purchase: 'Thank you for your purchase!',
18
18
  };
19
19
 
20
20
  /** The built-in label per WCPOS tax-ID type. */
@@ -125,7 +125,7 @@ export function formatWcposReceiptData(data: WcposReceiptData, options: FormatWc
125
125
  ...totals,
126
126
  ...displays(totals, [
127
127
  ...tri('subtotal'), ...tri('discount_total'), ...tri('total'), 'tax_total', 'paid_total', 'change_total',
128
- 'refund_total', 'net_total',
128
+ 'refund_due_total', 'refund_total', 'net_total',
129
129
  ], money),
130
130
  ...displays(totals, [...tri('sale_savings_total'), ...tri('total_saved')], saving),
131
131
  } as WcposReceiptView['totals'],
@@ -143,10 +143,13 @@ export function wcposSourceFromSentOrder(order: SentOrder, config: ReceiptConfig
143
143
  id: order.id, number: order.id, createdAt: order.createdAt, customerNote: order.note, ...tillSource(order, receipt, lines),
144
144
  // Cash records the full tender; the change is the order's.
145
145
  payments: order.payments.map((p) => ({
146
- methodId: p.method, methodTitle: methodTitle(p.method), amountMinor: p.amountMinor,
146
+ methodId: p.method, methodTitle: methodTitle(p.method), amountMinor: p.tenderedMinor ?? p.amountMinor,
147
147
  ...(p.reference !== undefined ? { transactionId: p.reference } : {}),
148
+ ...(p.tenderedMinor !== undefined ? { tenderedMinor: p.tenderedMinor } : {}),
149
+ ...(p.changeMinor !== undefined ? { changeMinor: p.changeMinor } : {}),
148
150
  })),
149
- changeMinor: order.changeDueMinor,
151
+ changeMinor: receipt.changeDueMinor,
152
+ ...(receipt.refundDueMinor ? { refundDueMinor: receipt.refundDueMinor } : {}),
150
153
  };
151
154
  }
152
155
 
@@ -172,6 +175,7 @@ export function wcposSourceFromPosOrder(order: PosOrder, config: ReceiptConfig):
172
175
  ...(p.changeMinor !== undefined ? { changeMinor: p.changeMinor } : {}),
173
176
  })),
174
177
  changeMinor: order.payments.reduce((total, p) => total + (p.changeMinor ?? 0), 0),
178
+ ...(receipt.refundDueMinor ? { refundDueMinor: receipt.refundDueMinor } : {}),
175
179
  ...(order.registerId !== undefined ? { registerId: order.registerId } : {}),
176
180
  };
177
181
  }
@@ -68,6 +68,8 @@ export interface WcposReceiptSource {
68
68
  tenderedMinor?: number; changeMinor?: number;
69
69
  }>;
70
70
  changeMinor?: number;
71
+ /** What the store owes back on a reopened sale (ADR-090); present only when above 0. Never part of changeMinor. */
72
+ refundDueMinor?: number;
71
73
  /** The register the sale was rung up on. */
72
74
  registerId?: string;
73
75
  /** The fiscal sale stamp, its IANA zone and the sale counter. */
@@ -173,6 +175,8 @@ export interface WcposReceiptTotals extends
173
175
  tax_total: number;
174
176
  paid_total: number;
175
177
  change_total: number;
178
+ /** v2's `refund_due`: what the store owes back on a reopened sale (ADR-090); absent when none. Not `refund_total`. */
179
+ refund_due_total?: number;
176
180
  refund_total?: number;
177
181
  net_total?: number;
178
182
  total_qty?: number;
@@ -318,7 +322,7 @@ export type WcposAdjustmentView<T extends WcposReceiptAdjustment = WcposReceiptA
318
322
  & Displays<WcposTri<'total'>> & { taxes?: WcposItemTaxView[] };
319
323
  export type WcposTotalsView = WcposReceiptTotals
320
324
  & Displays<WcposTri<'subtotal' | 'discount_total' | 'total'> | 'tax_total' | 'paid_total' | 'change_total'>
321
- & MaybeDisplays<WcposTri<'sale_savings_total' | 'total_saved'> | 'refund_total' | 'net_total'>;
325
+ & MaybeDisplays<WcposTri<'sale_savings_total' | 'total_saved'> | 'refund_due_total' | 'refund_total' | 'net_total'>;
322
326
  /** `taxable_amount_*_display` is '' when the amount is null. */
323
327
  export type WcposTaxSummaryView = WcposTaxSummaryRow
324
328
  & Displays<'tax_amount' | 'taxable_amount_excl' | 'taxable_amount_incl'>;