@tallyui/pos 3.11.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 (82) hide show
  1. package/dist/index.d.ts +1621 -358
  2. package/dist/index.js +6515 -4314
  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 +68 -11
  17. package/src/order/order-builder.ts +19 -2
  18. package/src/order/order-drafts.ts +17 -0
  19. package/src/order/types.ts +10 -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 +39 -17
  33. package/src/pos-order/finalize.ts +11 -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 +4 -2
  37. package/src/pos-order/schema.ts +7 -4
  38. package/src/pos-order/types.ts +5 -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/index.ts +1 -0
  45. package/src/receipt/reprint.ts +149 -0
  46. package/src/receipt/types.ts +2 -0
  47. package/src/receipt-template/default-templates.ts +78 -0
  48. package/src/receipt-template/index.ts +15 -0
  49. package/src/receipt-template/parse-xml.ts +175 -0
  50. package/src/receipt-template/render-html.ts +152 -0
  51. package/src/receipt-template/render-receipt.ts +19 -0
  52. package/src/receipt-template/render-template.ts +35 -0
  53. package/src/receipt-template/sanitize-html.ts +146 -0
  54. package/src/receipt-template/template-data.ts +97 -0
  55. package/src/receipt-template/types.ts +49 -0
  56. package/src/refund/index.ts +2 -0
  57. package/src/refund/refundable-lines.ts +91 -0
  58. package/src/register/export-csv.ts +24 -35
  59. package/src/register/float-suggestion.ts +22 -0
  60. package/src/register/index.ts +8 -3
  61. package/src/register/register-adoption.ts +71 -2
  62. package/src/register/register-commands.ts +7 -4
  63. package/src/register/register-count.helpers.ts +4 -0
  64. package/src/register/session-store.ts +4 -1
  65. package/src/register/use-register-session.ts +112 -28
  66. package/src/reports/adapters.ts +67 -0
  67. package/src/reports/index.ts +5 -0
  68. package/src/reports/presets.ts +27 -0
  69. package/src/reports/sales-figures.ts +173 -0
  70. package/src/reports/types.ts +63 -0
  71. package/src/sale/cart.ts +15 -3
  72. package/src/sale/catalogue.ts +5 -1
  73. package/src/sale/index.ts +3 -1
  74. package/src/sale/open-sales.ts +40 -0
  75. package/src/sale/use-sale.ts +72 -8
  76. package/src/scanner/index.ts +6 -0
  77. package/src/scanner/scan-session.ts +84 -0
  78. package/src/scanner/use-barcode-scanner.ts +61 -0
  79. package/src/scanner/wedge-detector.ts +137 -0
  80. package/src/tender/cash-rounding.ts +74 -0
  81. package/src/tender/index.ts +4 -0
  82. package/src/tender/payment-legs.ts +48 -0
@@ -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,3 +1,4 @@
1
1
  export { buildReceiptData } from './build-receipt-data';
2
+ export { buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder } from './reprint';
2
3
  export { RECEIPT_SCHEMA_VERSION } from './types';
3
4
  export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, ReceiptRegister, ReceiptFiscal } from './types';
@@ -0,0 +1,149 @@
1
+ import { minorUnitDigits, woocommerceTax, type StoreOrder } from '@tallyui/core';
2
+ import { noteDelivery } from '../pos-order/note-delivery';
3
+ import type { PosOrder } from '../pos-order/types';
4
+ import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
5
+ import type { ReceiptConfig, ReceiptData, ReceiptLineItem } from './types';
6
+ import { RECEIPT_SCHEMA_VERSION } from './types';
7
+
8
+ /**
9
+ * The blocks every reprint shares with `buildReceiptData`. `fiscal.reprint_count` is this reprint's ordinal, starting
10
+ * at 1: the app passes `fiscal: { reprint_count: n }` for its n-th reprint.
11
+ */
12
+ function reprintBlocks(config: ReceiptConfig, customer: { name?: string; email?: string } | null) {
13
+ const name = customer?.name || customer?.email;
14
+ return {
15
+ schemaVersion: RECEIPT_SCHEMA_VERSION,
16
+ software: { name: 'WCPOS', plugin_version: '', app_version: '', app_build: '', platform: '', ...config.software },
17
+ register: { id: config.register ?? '', name: config.registerName ?? '' },
18
+ fiscal: { document_type: 'sale' as const, is_reprint: true, reprint_count: 1, qr_payload: '', ...config.fiscal },
19
+ header: {
20
+ storeName: config.storeName, storeAddress: config.storeAddress, cashier: config.cashier,
21
+ ...(name ? { customer: name } : {}), register: config.register,
22
+ },
23
+ };
24
+ }
25
+
26
+ const sum = (amounts: number[]) => amounts.reduce((total, amount) => total + amount, 0);
27
+
28
+ /**
29
+ * Receipt data for reprinting the till's own stored order (ADR-081). A stored order keeps no discount labels: the order discount
30
+ * is one row, `Order discount`, in the display mode when lines were converted. Without `display`, a converted line's discount is in its own mode.
31
+ */
32
+ export function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptConfig): ReceiptData {
33
+ const { header, ...blocks } = reprintBlocks(config, order.customer);
34
+ const { display, taxRounding: rounding } = order;
35
+ const dp = minorUnitDigits(order.currency), factor = 10 ** dp;
36
+ // A WooCommerce line's rounded gross (its builder `totalMinor`), as woocommerce-tax.ts lineAmounts computes it from
37
+ // the 6dp net and per-rate taxes, read back from the stored micros as woocommerceTotals reads them (ADR-076).
38
+ const wooGrossMinor = (line: PosOrder['lines'][number], roundAtSubtotal: boolean) => {
39
+ const tax = line.taxLines.reduce((sum, row) => sum + (roundAtSubtotal ? Number(row.taxMicros) / (factor * 1e6)
40
+ : woocommerceTax.roundTaxTotal(Number(row.taxMicros) / (factor * 1e6), dp, order.pricesIncludeTax)), 0);
41
+ return Math.round(woocommerceTax.roundHalfUp(Number(line.netMicros) / (factor * 1e6) + tax, dp) * factor);
42
+ };
43
+ const lineTaxMicros = (line: PosOrder['lines'][number]) => line.taxLines.reduce((total, row) => total + BigInt(row.taxMicros), 0n);
44
+ let taxSoFar = order.pricesIncludeTax ? 0n : order.lines.reduce((total, line) => line.taxInclusive === undefined ? total + lineTaxMicros(line) : total, 0n);
45
+ const lineTotals = order.lines.map((line) => {
46
+ if (rounding.granularity === 'woocommerce' && line.netMicros !== undefined) return order.pricesIncludeTax ? wooGrossMinor(line, rounding.roundAtSubtotal) : line.netMinor;
47
+ if (line.taxInclusive === undefined) return line.netMinor;
48
+ const share = roundMicrosToMinor(taxSoFar + lineTaxMicros(line)) - roundMicrosToMinor(taxSoFar);
49
+ taxSoFar += lineTaxMicros(line);
50
+ return line.taxInclusive ? line.netMinor - share : line.netMinor + share;
51
+ });
52
+ const lineItems = order.lines.map((line, index): ReceiptLineItem => {
53
+ const displayLine = display?.lines.find((row) => row.lineId === line.id);
54
+ const displayAmountMinor = display ? displayLine?.amountMinor ?? 0 : line.taxInclusive !== undefined ? lineTotals[index]! + line.discountMinor : line.unitPriceMinor * line.quantity;
55
+ const displayDiscounts = display
56
+ ? (displayLine?.discounts ?? []).map((d) => ({ label: d.label ?? 'Discount', amountMinor: d.amountMinor }))
57
+ : line.discountMinor > 0 ? [{ label: 'Discount', amountMinor: line.discountMinor }] : [];
58
+ return {
59
+ name: line.name,
60
+ ...(line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
61
+ sku: line.sku,
62
+ quantity: line.quantity,
63
+ unitPriceMinor: line.unitPriceMinor,
64
+ lineTotalMinor: lineTotals[index]!,
65
+ ...(line.discountMinor > 0 ? { discountMinor: line.discountMinor } : {}),
66
+ displayAmountMinor,
67
+ displayDiscounts,
68
+ };
69
+ });
70
+ // Without taxByRate (finalized below order.create v3), the rows are computed as buildReceiptData computes them. A line's
71
+ // taxInclusive is stored only when it differs from the order's mode; WooCommerce lines take the order's, as there.
72
+ const taxedLines = [...order.lines.map((line) => ({ ...line, taxInclusive: order.taxRounding.granularity === 'woocommerce'
73
+ && line.netMicros !== undefined ? order.pricesIncludeTax : line.taxInclusive ?? order.pricesIncludeTax })),
74
+ ...[...(order.fees ?? []), ...(order.shipping ?? [])].map((charge) => ({ ...charge, taxInclusive: order.pricesIncludeTax }))];
75
+ const taxLines = order.taxByRate ? order.taxByRate.map((row) => ({
76
+ label: config.taxLabels?.[row.ratePpm] ?? row.label ?? `Tax ${row.ratePpm / 10000}%`, code: row.code, ratePpm: row.ratePpm, amountMinor: row.amountMinor,
77
+ })) : taxLinesByRate(taxedLines, order.taxMinor, config.taxLabels, order.taxRounding)
78
+ .map(({ label, code, ratePpm, amountMinor }) => ({ label, code, ratePpm, amountMinor }));
79
+ const charges = (rows: Array<{ name: string; amountMinor: number }> | undefined) =>
80
+ (rows ?? []).map(({ name, amountMinor }) => ({ name, amountMinor }));
81
+
82
+ return {
83
+ ...blocks,
84
+ header: { ...header, orderNumber: order.serverRefs?.displayId ?? order.id, date: order.createdAt },
85
+ lineItems,
86
+ discounts: display && display.orderDiscountMinor > 0 ? [{ label: 'Order discount', amountMinor: display.orderDiscountMinor }] : [],
87
+ fees: charges(display ? display.fees : order.fees),
88
+ shipping: charges(display ? display.shipping : order.shipping),
89
+ orderDiscountMinor: display ? display.orderDiscountMinor : 0,
90
+ totals: display
91
+ ? {
92
+ taxInclusive: display.taxInclusive, subtotalMinor: display.subtotalMinor, discountMinor: display.discountMinor,
93
+ taxLines, taxMinor: display.taxMinor, totalMinor: display.totalMinor,
94
+ }
95
+ : {
96
+ taxInclusive: order.pricesIncludeTax,
97
+ subtotalMinor: sum(lineItems.map((line) => line.displayAmountMinor)),
98
+ discountMinor: sum(order.lines.map((line) => line.discountMinor)),
99
+ taxLines, taxMinor: order.taxMinor, totalMinor: order.totalMinor,
100
+ },
101
+ payments: order.payments.map((p) => ({ method: p.method, amountMinor: p.tenderedMinor ?? p.amountMinor, reference: p.reference })),
102
+ changeDueMinor: sum(order.payments.map((p) => p.changeMinor ?? 0)),
103
+ footer: { note: order.note || undefined, ...(noteDelivery(order) === 'not_sent' ? { noteNotSent: true as const } : {}), barcode: order.id },
104
+ currency: order.currency,
105
+ };
106
+ }
107
+
108
+ /** Receipt data for reprinting an order read from the store with `getOrders`/`listOrders` (ADR-081). */
109
+ export function buildReceiptDataFromStoreOrder(order: StoreOrder, config: ReceiptConfig): ReceiptData {
110
+ const { header, ...blocks } = reprintBlocks(config, order.customer);
111
+ const gross = (net: number, tax: number) => order.pricesIncludeTax ? net + tax : net;
112
+ const lineItems = order.lines.map((line): ReceiptLineItem => {
113
+ const displayAmountMinor = gross(line.subtotalMinor, line.subtotalTaxMinor);
114
+ const lineTotalMinor = gross(line.totalMinor, line.taxMinor);
115
+ const discount = displayAmountMinor - lineTotalMinor;
116
+ return {
117
+ name: line.name,
118
+ sku: line.sku ?? '',
119
+ quantity: line.quantity,
120
+ unitPriceMinor: line.quantity === 0 ? 0 : Math.round(displayAmountMinor / line.quantity),
121
+ lineTotalMinor,
122
+ ...(discount > 0 ? { discountMinor: discount } : {}),
123
+ displayAmountMinor,
124
+ displayDiscounts: discount > 0 ? [{ label: 'Discount', amountMinor: discount }] : [],
125
+ };
126
+ });
127
+ const charges = (rows: StoreOrder['fees']) => rows.map(({ name, totalMinor, taxMinor }) => ({ name, amountMinor: gross(totalMinor, taxMinor) }));
128
+
129
+ return {
130
+ ...blocks,
131
+ header: { ...header, orderNumber: order.reference, date: order.placedAt },
132
+ lineItems,
133
+ discounts: order.coupons.map(({ code, discountMinor, discountTaxMinor }) => ({ label: code, amountMinor: gross(discountMinor, discountTaxMinor) })),
134
+ fees: charges(order.fees),
135
+ shipping: charges(order.shipping),
136
+ orderDiscountMinor: 0,
137
+ totals: {
138
+ taxInclusive: order.pricesIncludeTax,
139
+ subtotalMinor: sum(lineItems.map((line) => line.displayAmountMinor)),
140
+ discountMinor: sum(lineItems.map((line) => line.discountMinor ?? 0)),
141
+ taxLines: order.taxLines.map(({ label, code, ratePpm, amountMinor }) => ({ label, ...(code !== undefined ? { code } : {}), ratePpm, amountMinor })),
142
+ taxMinor: order.taxMinor, totalMinor: order.totalMinor,
143
+ },
144
+ payments: order.payments.map((p) => ({ method: p.kind ?? p.title ?? p.method, amountMinor: p.amountMinor })),
145
+ changeDueMinor: 0,
146
+ footer: { barcode: order.reference },
147
+ currency: order.currency,
148
+ };
149
+ }
@@ -58,6 +58,8 @@ export interface ReceiptData {
58
58
  changeDueMinor: number;
59
59
  footer: {
60
60
  note?: string;
61
+ /** ADR-083 condition 2: set only on a reprint of a till order whose note was not sent to the store. */
62
+ noteNotSent?: true;
61
63
  barcode?: string;
62
64
  };
63
65
  currency: string;
@@ -0,0 +1,78 @@
1
+ export type ReceiptPaper = '58mm' | '80mm';
2
+ /** Characters per line (v2 encode-receipt.ts:18). */
3
+ export const PAPER_COLUMNS: Record<ReceiptPaper, number> = { '58mm': 32, '80mm': 48 };
4
+ export const DEFAULT_RECEIPT_TEMPLATES: Record<ReceiptPaper, string> = {
5
+ '58mm': receiptTemplate(32, 10, 12),
6
+ '80mm': receiptTemplate(48, 12, 14),
7
+ };
8
+
9
+ function receiptTemplate(columns: number, labelWidth: number, amountWidth: number): string {
10
+ return `<receipt paper-width="${columns}">
11
+ <align mode="center">
12
+ <bold><text>{{store.name}}</text></bold>
13
+ {{#store.addressLines}}
14
+ <text>{{line}}</text>
15
+ {{/store.addressLines}}
16
+ </align>
17
+ <line />
18
+ <align mode="center"><bold><text>{{document.title}}</text></bold></align>
19
+ {{#document.isReprint}}
20
+ <align mode="center"><text>Copy {{document.reprintCount}}</text></align>
21
+ {{/document.isReprint}}
22
+ <row><col width="${labelWidth}">Order</col><col width="*" align="right">{{order.number}}</col></row>
23
+ <row><col width="${labelWidth}">Date</col><col width="*" align="right">{{order.date}}</col></row>
24
+ {{#cashier}}
25
+ <row><col width="${labelWidth}">Cashier</col><col width="*" align="right">{{cashier}}</col></row>
26
+ {{/cashier}}
27
+ {{#register}}
28
+ <row><col width="${labelWidth}">Register</col><col width="*" align="right">{{register}}</col></row>
29
+ {{/register}}
30
+ {{#customer}}
31
+ <row><col width="${labelWidth}">Customer</col><col width="*" align="right">{{customer}}</col></row>
32
+ {{/customer}}
33
+ <line style="dashed" />
34
+ {{#lines}}
35
+ <text>{{name}}</text>
36
+ {{#options}}
37
+ <text> {{text}}</text>
38
+ {{/options}}
39
+ <row><col width="*"> {{detail}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
40
+ {{#discounts}}
41
+ <row><col width="*"> {{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
42
+ {{/discounts}}
43
+ {{/lines}}
44
+ <line style="dashed" />
45
+ <row><col width="*">Subtotal</col><col width="${amountWidth}" align="right">{{subtotal}}</col></row>
46
+ {{#lineDiscount}}
47
+ <row><col width="*">Line discounts</col><col width="${amountWidth}" align="right">{{lineDiscount}}</col></row>
48
+ {{/lineDiscount}}
49
+ {{#orderDiscount}}
50
+ <row><col width="*">Order discount</col><col width="${amountWidth}" align="right">{{orderDiscount}}</col></row>
51
+ {{/orderDiscount}}
52
+ {{#charges}}
53
+ <row><col width="*">{{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
54
+ {{/charges}}
55
+ {{#taxes}}
56
+ <row><col width="*">{{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
57
+ {{/taxes}}
58
+ <bold><row><col width="*">Total</col><col width="${amountWidth}" align="right">{{total}}</col></row></bold>
59
+ <line />
60
+ {{#payments}}
61
+ <row><col width="*">{{method}}{{#reference}} {{reference}}{{/reference}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
62
+ {{/payments}}
63
+ {{#change}}
64
+ <row><col width="*">Change</col><col width="${amountWidth}" align="right">{{change}}</col></row>
65
+ {{/change}}
66
+ {{#note}}
67
+ <feed lines="1" />
68
+ <text>{{note}}</text>
69
+ {{/note}}
70
+ <feed lines="1" />
71
+ <align mode="center"><text>Thank you</text></align>
72
+ {{#qrPayload}}
73
+ <align mode="center"><qrcode size="4">{{qrPayload}}</qrcode></align>
74
+ {{/qrPayload}}
75
+ <feed lines="3" />
76
+ <cut />
77
+ </receipt>`;
78
+ }
@@ -0,0 +1,15 @@
1
+ export { parseXml } from './parse-xml';
2
+ export { renderHtml } from './render-html';
3
+ export { sanitizeHtml } from './sanitize-html';
4
+ export { renderReceiptTemplate, renderLogiclessTemplate, renderThermalPreview } from './render-template';
5
+ export { receiptTemplateData } from './template-data';
6
+ export { DEFAULT_RECEIPT_TEMPLATES, PAPER_COLUMNS } from './default-templates';
7
+ export { renderReceiptHtml } from './render-receipt';
8
+ export type { ThermalNode, ReceiptNode } from './types';
9
+ export type { SanitizeHtmlOptions } from './sanitize-html';
10
+ export type { RenderSanitizeOptions } from './render-template';
11
+ export type {
12
+ ReceiptTemplateRow, ReceiptTemplateLine, ReceiptTemplateData, ReceiptTemplateOptions,
13
+ } from './template-data';
14
+ export type { ReceiptPaper } from './default-templates';
15
+ export type { RenderReceiptOptions } from './render-receipt';
@@ -0,0 +1,175 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/parse-xml.ts (monorepo main 5ac185b0, MIT).
2
+ // Native DOMParser, else @xmldom/xmldom (React Native).
3
+ import { DOMParser as XmlDOMParser } from '@xmldom/xmldom';
4
+ import type { ColNode, DrawerConnector, ReceiptNode, RowNode, ThermalNode } from './types';
5
+
6
+ /** Parse a thermal XML template string into an AST using the native DOMParser or xmldom. */
7
+ export function parseXml(xml: string): ReceiptNode {
8
+ const doc = parseXmlDocument(xml);
9
+ const errorNode = doc.getElementsByTagName('parsererror')[0];
10
+ if (errorNode) throw new Error(`XML parse error: ${errorNode.textContent}`);
11
+ const root = doc.documentElement;
12
+ if (root.tagName !== 'receipt') {
13
+ throw new Error(`Expected <receipt> root element, got <${root.tagName}>`);
14
+ }
15
+ return { type: 'receipt', paperWidth: intAttr(root, 'paper-width', 48), children: parseChildren(root) };
16
+ }
17
+
18
+ function parseChildren(parent: Element): ThermalNode[] {
19
+ const nodes: ThermalNode[] = [];
20
+ for (const child of Array.from(parent.childNodes)) {
21
+ if (child.nodeType === 3 /* TEXT_NODE */) {
22
+ const text = child.textContent ?? '';
23
+ // Skip indentation, but preserve non-empty text so spaces around inline elements survive.
24
+ if (/\S/.test(text)) nodes.push({ type: 'raw-text', value: text });
25
+ continue;
26
+ }
27
+ if (child.nodeType !== 1 /* ELEMENT_NODE */) continue;
28
+ const el = child as Element;
29
+ const tag = el.tagName.toLowerCase();
30
+ switch (tag) {
31
+ case 'text':
32
+ nodes.push({ type: 'text', children: parseChildren(el) });
33
+ break;
34
+ case 'bold':
35
+ nodes.push({ type: 'bold', children: parseChildren(el) });
36
+ break;
37
+ case 'underline':
38
+ nodes.push({ type: 'underline', children: parseChildren(el) });
39
+ break;
40
+ case 'invert':
41
+ nodes.push({ type: 'invert', children: parseChildren(el) });
42
+ break;
43
+ case 'size': {
44
+ const w = intAttr(el, 'width', 1);
45
+ nodes.push({ type: 'size', width: w, height: intAttr(el, 'height', w), children: parseChildren(el) });
46
+ break;
47
+ }
48
+ case 'align': {
49
+ const modeAttr = el.getAttribute('mode');
50
+ const validModes = ['left', 'center', 'right'] as const;
51
+ const mode = validModes.includes(modeAttr as (typeof validModes)[number])
52
+ ? (modeAttr as 'left' | 'center' | 'right') : 'left';
53
+ nodes.push({ type: 'align', mode, children: parseChildren(el) });
54
+ break;
55
+ }
56
+ case 'row':
57
+ nodes.push({ type: 'row', children: parseRowChildren(el) } as RowNode);
58
+ break;
59
+ case 'col':
60
+ break;
61
+ case 'line': {
62
+ const styleAttr = el.getAttribute('style');
63
+ const validStyles = ['single', 'double', 'dashed', 'dotted'] as const;
64
+ nodes.push({
65
+ type: 'line',
66
+ style: validStyles.includes(styleAttr as (typeof validStyles)[number])
67
+ ? (styleAttr as (typeof validStyles)[number]) : 'single',
68
+ });
69
+ break;
70
+ }
71
+ case 'barcode':
72
+ if (isQrBarcodeType(el.getAttribute('type') ?? 'code128')) {
73
+ nodes.push({
74
+ type: 'qrcode', size: heightToQrSize(intAttr(el, 'height', 40)), value: (el.textContent ?? '').trim(),
75
+ });
76
+ } else {
77
+ nodes.push({
78
+ type: 'barcode', barcodeType: el.getAttribute('type') ?? 'code128',
79
+ height: intAttr(el, 'height', 40), value: (el.textContent ?? '').trim(),
80
+ });
81
+ }
82
+ break;
83
+ case 'qrcode':
84
+ nodes.push({ type: 'qrcode', size: intAttr(el, 'size', 4), value: (el.textContent ?? '').trim() });
85
+ break;
86
+ case 'image':
87
+ nodes.push({ type: 'image', src: el.getAttribute('src') ?? '', width: intAttr(el, 'width', 200) });
88
+ break;
89
+ case 'cut': {
90
+ const cutAttr = el.getAttribute('type');
91
+ const validCuts = ['full', 'partial'] as const;
92
+ nodes.push({
93
+ type: 'cut',
94
+ cutType: validCuts.includes(cutAttr as (typeof validCuts)[number])
95
+ ? (cutAttr as 'full' | 'partial') : 'partial',
96
+ });
97
+ break;
98
+ }
99
+ case 'feed':
100
+ nodes.push({ type: 'feed', lines: intAttr(el, 'lines', 1) });
101
+ break;
102
+ case 'drawer':
103
+ nodes.push({ type: 'drawer', ...(drawerConnectorAttr(el) ? { connector: drawerConnectorAttr(el) } : {}) });
104
+ break;
105
+ default:
106
+ nodes.push(...parseChildren(el));
107
+ }
108
+ }
109
+ return nodes;
110
+ }
111
+
112
+ function drawerConnectorAttr(el: Element): DrawerConnector | undefined {
113
+ const connector = el.getAttribute('connector')?.trim();
114
+ return connector === 'pin2' || connector === 'pin5' ? connector : undefined;
115
+ }
116
+
117
+ function isQrBarcodeType(type: string): boolean {
118
+ return type.trim().toLowerCase() === 'qrcode' || type.trim().toLowerCase() === 'qr';
119
+ }
120
+
121
+ function heightToQrSize(height: number): number {
122
+ return Number.isFinite(height) && height > 0 ? Math.max(2, Math.min(10, Math.round(height / 10))) : 4;
123
+ }
124
+
125
+ function parseRowChildren(row: Element): ColNode[] {
126
+ const cols: ColNode[] = [];
127
+ for (const child of Array.from(row.childNodes)) {
128
+ if (child.nodeType !== 1 /* ELEMENT_NODE */) continue;
129
+ const el = child as Element;
130
+ if (el.tagName.toLowerCase() === 'col') {
131
+ const rawWidth = el.getAttribute('width');
132
+ const width: number | '*' = rawWidth === '*' ? '*' : intAttr(el, 'width', 12);
133
+ cols.push({
134
+ type: 'col', width,
135
+ align: (['left', 'right'] as const).includes(el.getAttribute('align') as 'left' | 'right')
136
+ ? (el.getAttribute('align') as 'left' | 'right') : 'left',
137
+ children: parseChildren(el),
138
+ });
139
+ }
140
+ }
141
+ return cols;
142
+ }
143
+
144
+ function parseXmlDocument(xml: string): Document {
145
+ if (typeof DOMParser !== 'undefined') {
146
+ return new DOMParser().parseFromString(xml, 'text/xml');
147
+ }
148
+
149
+ const errors: string[] = [];
150
+ let doc: Document | undefined;
151
+ try {
152
+ doc = new XmlDOMParser({
153
+ onError: (_level: string, message: unknown) => errors.push(String(message)),
154
+ } as unknown as ConstructorParameters<typeof XmlDOMParser>[0]).parseFromString(
155
+ xml,
156
+ 'text/xml'
157
+ ) as unknown as Document;
158
+ } catch (error) {
159
+ errors.push(error instanceof Error ? error.message : String(error));
160
+ }
161
+
162
+ if (errors.length > 0 || !doc) {
163
+ throw new Error(`XML parse error: ${errors.join('; ') || 'invalid document'}`);
164
+ }
165
+
166
+ return doc;
167
+ }
168
+
169
+ function intAttr(el: Element, name: string, fallback: number): number {
170
+ const raw = el.getAttribute(name)?.trim();
171
+ if (raw == null) return fallback;
172
+ if (!/^[1-9]\d*$/.test(raw)) return fallback;
173
+ const n = Number(raw);
174
+ return Number.isSafeInteger(n) ? n : fallback;
175
+ }