@tallyui/pos 3.18.0 → 3.20.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 (70) hide show
  1. package/dist/index.d.ts +3202 -1721
  2. package/dist/index.js +3871 -677
  3. package/package.json +6 -6
  4. package/src/customer-display/display-client.ts +341 -0
  5. package/src/customer-display/index.ts +20 -0
  6. package/src/customer-display/sale-display.ts +115 -0
  7. package/src/customer-display/snapshot-fallback.ts +138 -0
  8. package/src/customer-display/till-display-service.ts +304 -0
  9. package/src/customer-display/till-pairing.ts +177 -0
  10. package/src/customer-display/use-display-client.ts +25 -0
  11. package/src/customer-display/use-sale-display.ts +28 -0
  12. package/src/customer-display/use-till-pairing.ts +35 -0
  13. package/src/customer-display/webrtc/index.ts +5 -0
  14. package/src/customer-display/webrtc/peer-link.ts +222 -0
  15. package/src/index.ts +36 -10
  16. package/src/order/index.ts +2 -1
  17. package/src/order/order-builder.ts +104 -16
  18. package/src/order/types.ts +10 -4
  19. package/src/payment-driver/index.ts +1 -1
  20. package/src/payment-driver/registry.ts +23 -0
  21. package/src/pos-order/__fixtures__/order-create-v8.json +117 -0
  22. package/src/pos-order/command.ts +27 -9
  23. package/src/pos-order/finalize.ts +30 -2
  24. package/src/pos-order/schema.ts +16 -5
  25. package/src/pos-order/types.ts +7 -4
  26. package/src/receipt/reprint.ts +3 -10
  27. package/src/receipt/woo-gross.ts +16 -0
  28. package/src/receipt-template/index.ts +8 -0
  29. package/src/receipt-template/render-store-template.ts +51 -0
  30. package/src/receipt-template/wcpos/build.ts +320 -0
  31. package/src/receipt-template/wcpos/context.ts +29 -0
  32. package/src/receipt-template/wcpos/format.ts +153 -0
  33. package/src/receipt-template/wcpos/from-orders.ts +203 -0
  34. package/src/receipt-template/wcpos/index.ts +11 -0
  35. package/src/receipt-template/wcpos/money.ts +42 -0
  36. package/src/receipt-template/wcpos/types.ts +350 -0
  37. package/src/register/expected.ts +60 -0
  38. package/src/register/index.ts +2 -2
  39. package/src/register/use-register-session.ts +8 -4
  40. package/src/sale/discount-codes.ts +7 -2
  41. package/src/sale/index.ts +9 -2
  42. package/src/sale/order-filters-query.ts +59 -0
  43. package/src/sale/store-priced-discount-codes.ts +52 -0
  44. package/src/sale/use-sale.ts +157 -16
  45. package/src/sale/variant-match.ts +44 -0
  46. package/src/scanner/camera-scan.ts +113 -0
  47. package/src/scanner/capabilities.ts +22 -0
  48. package/src/scanner/chooser-cancel.ts +8 -0
  49. package/src/scanner/device-identity.ts +84 -0
  50. package/src/scanner/device-scanner.ts +62 -0
  51. package/src/scanner/hid-pos-decoder.ts +60 -0
  52. package/src/scanner/hid-scanner.ts +171 -0
  53. package/src/scanner/index.ts +27 -0
  54. package/src/scanner/scan-dedup.ts +48 -0
  55. package/src/scanner/scan-events.ts +75 -0
  56. package/src/scanner/scan-hub-context.tsx +124 -0
  57. package/src/scanner/scan-session.ts +4 -0
  58. package/src/scanner/scanner-profiles.ts +96 -0
  59. package/src/scanner/serial-line-decoder.ts +58 -0
  60. package/src/scanner/serial-scanner.ts +227 -0
  61. package/src/scanner/use-barcode-scanner.ts +23 -5
  62. package/src/scanner/use-camera-scan.ts +57 -0
  63. package/src/scanner/wedge-detector.ts +28 -6
  64. package/src/store-settings/use-store-settings.ts +23 -5
  65. package/src/tax/index.ts +6 -0
  66. package/src/tax/location-rates.ts +46 -0
  67. package/src/tax/sale-tax-contexts.ts +40 -0
  68. package/src/tax/tax-context.ts +37 -0
  69. package/src/tax/tax-derivation.ts +99 -0
  70. package/src/tax/tax-provider.tsx +4 -31
@@ -0,0 +1,320 @@
1
+ // Ported from WCPOS v2 build-receipt-data.ts and the canonical branch of map-receipt-data.ts
2
+ // (wcpos/monorepo 85ecbd43f, MIT). One function gives what v2's mapReceiptData(buildReceiptData(...)) gives,
3
+ // from minor units instead of a WooCommerce order, with the gap fixes marked "Gap §5.x".
4
+ import { minorUnitDigits } from '@tallyui/core';
5
+ import type {
6
+ WcposItemTax, WcposItemTaxSource, WcposLineSource, WcposReceiptData, WcposReceiptDate, WcposReceiptLine,
7
+ WcposReceiptOptions, WcposReceiptSource, WcposReceiptStore, WcposTaxId, WcposTaxSummaryRow, WcposTri,
8
+ } from './types';
9
+
10
+ /** v2's isCompletingStatus list: an order in one of these needs no payment, as WC_Order::needs_payment(). */
11
+ const COMPLETING_STATUSES = ['completed', 'processing', 'refunded'];
12
+
13
+ const DATE_KEYS: ReadonlyArray<keyof WcposReceiptDate> = [
14
+ 'datetime', 'date', 'time', 'datetime_short', 'datetime_long', 'datetime_full', 'date_short', 'date_long',
15
+ 'date_full', 'date_ymd', 'date_dmy', 'date_mdy', 'weekday_short', 'weekday_long', 'day', 'month',
16
+ 'month_short', 'month_long', 'year',
17
+ ];
18
+
19
+ const STAMP_FORMAT: Intl.DateTimeFormatOptions = {
20
+ year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', hour12: true,
21
+ };
22
+
23
+ type Pair = { incl: number | null; excl: number | null };
24
+ type Side = 'incl' | 'excl';
25
+
26
+ /** A date block with only `datetime` set, as a locally built receipt has it. */
27
+ function dateBlock(datetime = ''): WcposReceiptDate {
28
+ const block = {} as WcposReceiptDate;
29
+ for (const key of DATE_KEYS) block[key] = '';
30
+ block.datetime = datetime;
31
+ return block;
32
+ }
33
+
34
+ /** `Sep 11, 2026, 10:30 AM`, in `timeZone` when given. Throws a RangeError for a bad zone or date. */
35
+ function stamp(date: Date, timeZone?: string): string {
36
+ return new Intl.DateTimeFormat('en-US', timeZone ? { ...STAMP_FORMAT, timeZone } : STAMP_FORMAT).format(date);
37
+ }
38
+
39
+ function printedStamp(now: Date, timeZone?: string): string {
40
+ try {
41
+ return stamp(now, timeZone);
42
+ } catch (error) {
43
+ if (!(error instanceof RangeError)) throw error;
44
+ return stamp(now);
45
+ }
46
+ }
47
+
48
+ function saleTime(at: string | undefined, timeZone: string | undefined): WcposReceiptDate | null {
49
+ if (!at) return null;
50
+ try {
51
+ return dateBlock(stamp(new Date(at), timeZone));
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ function capitalizeStatus(slug: string): string {
58
+ return slug.split('-').map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ');
59
+ }
60
+
61
+ function metaText(value: unknown): string {
62
+ if (typeof value === 'string') return value;
63
+ if (value === null || value === undefined) return '';
64
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
65
+ }
66
+
67
+ /** Keeps entries with a non-empty type and value; omits the key when none are left. */
68
+ function taxIdsKey(list: WcposTaxId[] | undefined): { tax_ids?: WcposTaxId[] } {
69
+ const kept = (list ?? []).filter((id) => id.type && id.value).map((id) => ({
70
+ type: id.type, value: id.value,
71
+ ...(id.country ? { country: id.country } : {}), ...(id.label ? { label: id.label } : {}),
72
+ }));
73
+ return kept.length > 0 ? { tax_ids: kept } : {};
74
+ }
75
+
76
+ /**
77
+ * A recorded per-unit price, put on both bases. The recorded value is on the sale's basis; the other basis
78
+ * uses the line subtotal's own tax ratio, and is null when that ratio has a zero denominator.
79
+ */
80
+ function convertRecorded(
81
+ value: number, taxStatus: string | undefined, inclBasis: boolean, subExcl: number, subIncl: number,
82
+ ): Pair {
83
+ if (taxStatus === 'none' || value === 0) return { incl: value, excl: value };
84
+ if (inclBasis) return { incl: value, excl: subIncl === 0 ? null : Math.round((value * subExcl) / subIncl) };
85
+ return { incl: subExcl === 0 ? null : Math.round((value * subIncl) / subExcl), excl: value };
86
+ }
87
+
88
+ function savings(regular: number | null, selling: number | null): number | null {
89
+ return regular === null || selling === null ? null : Math.max(0, regular - selling);
90
+ }
91
+
92
+ const sum = (values: number[]): number => values.reduce((total, value) => total + value, 0);
93
+ const sumKnown = (values: Array<number | null>): number | null =>
94
+ values.some((value) => value === null) ? null : sum(values as number[]);
95
+
96
+ interface LineCalc {
97
+ line: WcposReceiptLine;
98
+ qty: number;
99
+ sub: { incl: number; excl: number };
100
+ discount: { incl: number; excl: number };
101
+ lineSavings: Pair;
102
+ savingsInDiscounts: boolean;
103
+ }
104
+
105
+ /** WCPOS's canonical receipt data for a sale. Pure: the clock comes from `options.now`. */
106
+ export function wcposReceiptData(
107
+ source: WcposReceiptSource, store: WcposReceiptStore, options: WcposReceiptOptions = {},
108
+ ): WcposReceiptData {
109
+ const factor = 10 ** minorUnitDigits(source.currency);
110
+ const major = (minor: number): number => Math.round(minor) / factor;
111
+ const majorOrNull = (minor: number | null): number | null => (minor === null ? null : major(minor));
112
+ const side: Side = store.taxDisplayCart === 'incl' ? 'incl' : 'excl';
113
+ const tri = <K extends string, V extends number | null>(key: K, incl: V, excl: V) =>
114
+ ({ [key]: side === 'incl' ? incl : excl, [`${key}_incl`]: incl, [`${key}_excl`]: excl }) as
115
+ { [P in WcposTri<K>]: V };
116
+ const triMinor = <K extends string>(key: K, pair: Pair) =>
117
+ tri(key, majorOrNull(pair.incl), majorOrNull(pair.excl));
118
+ const taxLines = new Map(source.taxLines.map((tax) => [String(tax.rateId), tax]));
119
+ const taxLabel = (tax: WcposReceiptSource['taxLines'][number]) => tax.label || tax.rateCode || 'Tax';
120
+ const ratePercent = (value: number | undefined) => (value !== undefined && value > 0 ? value : null);
121
+
122
+ // Gap §5.4: v2's build emits no line taxes; the canonical data carries the line's own rate split.
123
+ const itemTaxes = (taxes: WcposItemTaxSource[] | undefined): WcposItemTax[] =>
124
+ (taxes ?? []).map((tax) => {
125
+ const code = String(tax.rateId);
126
+ const line = taxLines.get(code);
127
+ return {
128
+ code, rate: ratePercent(line?.ratePercent),
129
+ ...(line ? { label: taxLabel(line), compound: !!line.compound } : {}), amount: major(tax.totalMinor),
130
+ };
131
+ }).filter((tax) => tax.code !== '' || tax.amount !== 0);
132
+
133
+ const buildLine = (item: WcposLineSource, index: number): LineCalc => {
134
+ const qty = item.quantity;
135
+ const sub = { incl: item.subtotalMinor + item.subtotalTaxMinor, excl: item.subtotalMinor };
136
+ const total = { incl: item.totalMinor + item.totalTaxMinor, excl: item.totalMinor };
137
+ // Gap §5.2: the unit price is the unit before discount, as v2's build computes it (its schema says after).
138
+ const unit = { incl: qty > 0 ? Math.round(sub.incl / qty) : 0, excl: qty > 0 ? Math.round(sub.excl / qty) : 0 };
139
+ const recorded = item.recordedPrice && Number.isFinite(item.recordedPrice.priceMinor)
140
+ && Number.isFinite(item.recordedPrice.regularPriceMinor) ? item.recordedPrice : undefined;
141
+ // The sale's own basis wins over the store setting: a reprint uses the basis the sale was rung up on.
142
+ const inclBasis = source.pricesIncludeTax;
143
+ const convert = (value: number) => convertRecorded(value, recorded?.taxStatus, inclBasis, sub.excl, sub.incl);
144
+ const selling: Pair = recorded ? convert(recorded.priceMinor) : unit;
145
+ const regular: Pair = recorded ? convert(recorded.regularPriceMinor) : { incl: null, excl: null };
146
+ const unitSavings = { incl: savings(regular.incl, selling.incl), excl: savings(regular.excl, selling.excl) };
147
+ const times = (pair: Pair): Pair => ({
148
+ incl: pair.incl === null ? null : pair.incl * qty, excl: pair.excl === null ? null : pair.excl * qty,
149
+ });
150
+ const lineSavings = times(unitSavings);
151
+ // The discount already holds the sale saving when the unit subtotal sits nearer the regular price than the
152
+ // recorded price, both distances rounded to the minor unit.
153
+ const basisUnit = qty === 0 ? null : (inclBasis ? sub.incl : sub.excl) / qty;
154
+ const savingsInDiscounts = !!recorded && basisUnit !== null
155
+ && Math.round(Math.abs(basisUnit - recorded.regularPriceMinor)) < Math.round(Math.abs(basisUnit - recorded.priceMinor));
156
+ const discount = { incl: sub.incl - total.incl, excl: sub.excl - total.excl };
157
+ const sku = item.sku ?? '';
158
+ const meta = (item.meta ?? []).filter((entry) => !entry.key.startsWith('_')).map((entry) => ({
159
+ key: entry.displayKey || entry.key, value: metaText(entry.displayValue ?? entry.value),
160
+ })).filter((entry) => entry.key !== '' && entry.value !== '');
161
+ return {
162
+ qty, sub, discount, lineSavings, savingsInDiscounts,
163
+ line: {
164
+ key: sku || `line-${index}-${item.name.slice(0, 20)}`, name: item.name, sku, qty,
165
+ ...triMinor('unit_price', unit) as { [P in WcposTri<'unit_price'>]: number },
166
+ ...triMinor('line_subtotal', sub) as { [P in WcposTri<'line_subtotal'>]: number },
167
+ ...triMinor('discounts', discount) as { [P in WcposTri<'discounts'>]: number },
168
+ ...triMinor('line_total', total) as { [P in WcposTri<'line_total'>]: number },
169
+ ...triMinor('regular_price', regular), ...triMinor('selling_price', selling),
170
+ ...triMinor('unit_savings', unitSavings), ...triMinor('line_regular_total', times(regular)),
171
+ ...triMinor('line_selling_total', times(selling)), ...triMinor('line_savings', lineSavings),
172
+ savings_in_discounts: savingsInDiscounts, meta, taxes: itemTaxes(item.taxes),
173
+ },
174
+ };
175
+ };
176
+ const calcs = source.lines.map(buildLine);
177
+
178
+ const adjustment = (label: string, totalMinor: number, taxMinor: number) => ({
179
+ label, ...tri('total', major(totalMinor + taxMinor), major(totalMinor)),
180
+ });
181
+ const fees = source.fees.map((fee) => adjustment(fee.name, fee.totalMinor, fee.totalTaxMinor));
182
+ // v2's build uses the method id only as the label fallback and does not emit `method_id`.
183
+ const shipping = source.shipping.map((row) =>
184
+ adjustment(row.methodTitle || row.methodId || '', row.totalMinor, row.totalTaxMinor));
185
+ const sep = store.priceDecimalSep ?? '.';
186
+ const discounts = source.coupons.map((coupon) => {
187
+ const percent = coupon.quickDiscountPercent;
188
+ const label = percent === undefined ? coupon.code
189
+ : percent === null ? 'Discount' : `Discount (${String(percent).replace('.', sep)}%)`;
190
+ return adjustment(label, coupon.discountMinor, coupon.discountTaxMinor);
191
+ });
192
+
193
+ const lineSum = (pick: (calc: LineCalc) => number) => sum(calcs.map(pick));
194
+ const discountTotal = {
195
+ excl: source.discountTotalMinor ?? lineSum((calc) => calc.discount.excl),
196
+ incl: source.discountTotalMinor !== undefined && source.discountTaxMinor !== undefined
197
+ ? source.discountTotalMinor + source.discountTaxMinor : lineSum((calc) => calc.discount.incl),
198
+ };
199
+ const saleSavings: Pair = {
200
+ incl: sumKnown(calcs.map((calc) => calc.lineSavings.incl)),
201
+ excl: sumKnown(calcs.map((calc) => calc.lineSavings.excl)),
202
+ };
203
+ const notInDiscounts = calcs.filter((calc) => !calc.savingsInDiscounts);
204
+ const totalSaved: Pair = {
205
+ incl: saleSavings.incl === null ? null : discountTotal.incl + sum(notInDiscounts.map((c) => c.lineSavings.incl ?? 0)),
206
+ excl: saleSavings.excl === null ? null : discountTotal.excl + sum(notInDiscounts.map((c) => c.lineSavings.excl ?? 0)),
207
+ };
208
+
209
+ const needsPayment = !COMPLETING_STATUSES.includes(source.status) && source.totalMinor > 0;
210
+ // Gap §5.4: one row per tender TallyUI recorded, instead of v2's one row from the order's method.
211
+ const payments = needsPayment ? [] : source.payments.map((payment) => ({
212
+ method_id: payment.methodId, method_title: payment.methodTitle, amount: major(payment.amountMinor),
213
+ transaction_id: payment.transactionId ?? '',
214
+ ...(payment.tenderedMinor !== undefined ? { tendered: major(payment.tenderedMinor) } : {}),
215
+ ...(payment.changeMinor !== undefined ? { change: major(payment.changeMinor) } : {}),
216
+ }));
217
+
218
+ const taxable = (code: string): number | null => {
219
+ let base: number | null = null;
220
+ for (const item of [...source.lines, ...source.fees, ...source.shipping]) {
221
+ if (item.taxes?.some((tax) => String(tax.rateId) === code)) base = (base ?? 0) + item.totalMinor;
222
+ }
223
+ return base;
224
+ };
225
+ const taxSummary: WcposTaxSummaryRow[] = source.taxLines.map((tax) => {
226
+ const code = String(tax.rateId);
227
+ const amount = tax.taxTotalMinor + tax.shippingTaxTotalMinor;
228
+ const base = taxable(code);
229
+ return {
230
+ code, rate: ratePercent(tax.ratePercent), label: taxLabel(tax), compound: !!tax.compound,
231
+ tax_amount: major(amount),
232
+ taxable_amount_excl: base === null ? null : major(base),
233
+ taxable_amount_incl: base === null ? null : major(base + amount),
234
+ };
235
+ });
236
+ const breakdown = !store.calcTaxes ? 'hidden' : store.taxTotalDisplay === 'single' ? 'single' : 'itemized';
237
+
238
+ const label = options.statusLabel?.(source.status);
239
+ const customer = source.customer ?? {};
240
+ const customerId = Number(customer.id);
241
+ const orderId = Number(source.id);
242
+ const decimals = store.priceDecimals;
243
+ const register = options.register;
244
+ const printCount = options.printCount ?? 0;
245
+ const i18n = Object.fromEntries(Object.entries(options.receiptI18n ?? store.receiptI18n ?? {})
246
+ .filter((entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1].trim() !== ''));
247
+ const totalIncl = major(source.totalMinor);
248
+
249
+ return {
250
+ store: {
251
+ id: 0, name: store.name ?? '', logo: store.logo ?? '',
252
+ // Gap §5.5: v2's map can let an invalid `wc_price_decimals` through; only a non-negative integer is kept.
253
+ ...(decimals !== undefined && Number.isInteger(decimals) && decimals >= 0 ? { price_decimals: decimals } : {}),
254
+ address_lines: (store.addressParts ?? []).flatMap((part) => part.split(','))
255
+ .map((part) => part.trim()).filter((part) => part !== ''),
256
+ phone: store.phone ?? '', email: store.email ?? '', ...taxIdsKey(store.taxIds),
257
+ },
258
+ order: {
259
+ id: Number.isFinite(orderId) ? orderId : 0, number: source.number || String(source.id),
260
+ currency: source.currency ?? '', customer_note: source.customerNote ?? '',
261
+ wc_status: source.status, status_label: label && label !== source.status ? label : capitalizeStatus(source.status),
262
+ needs_payment: needsPayment, payment_url: source.paymentUrl ?? '',
263
+ created: dateBlock(source.createdAt), paid: dateBlock(), completed: dateBlock(),
264
+ printed: dateBlock(printedStamp((options.now ?? (() => new Date()))(), store.timezone)),
265
+ },
266
+ // Gap §5.4: v2's build has no cashier; TallyUI passes the one it knows.
267
+ cashier: options.cashier ?? { id: 0, name: '' },
268
+ // Gap §5.3: no billing or shipping address keys, since the source carries none.
269
+ customer: {
270
+ id: customerId > 0 ? customerId : null,
271
+ name: [customer.firstName, customer.lastName].filter((part) => part).join(' '),
272
+ first_name: customer.firstName ?? '', email: customer.email ?? '', phone: customer.phone ?? '',
273
+ // Gap §5.1: every type is kept, as for store tax IDs; v2's map drops types missing from its list.
274
+ ...taxIdsKey(customer.taxIds),
275
+ },
276
+ lines: calcs.map((calc) => calc.line),
277
+ fees, shipping, discounts,
278
+ totals: {
279
+ ...triMinor('subtotal', { incl: lineSum((c) => c.sub.incl), excl: lineSum((c) => c.sub.excl) }) as
280
+ { [P in WcposTri<'subtotal'>]: number },
281
+ ...triMinor('discount_total', discountTotal) as { [P in WcposTri<'discount_total'>]: number },
282
+ ...triMinor('sale_savings_total', saleSavings), ...triMinor('total_saved', totalSaved),
283
+ total_saved_complete: (side === 'incl' ? totalSaved.incl : totalSaved.excl) !== null,
284
+ tax_total: major(source.totalTaxMinor),
285
+ ...tri('total', totalIncl, major(source.totalMinor - source.totalTaxMinor)),
286
+ // Gap §5.4: the tendered sum and the change TallyUI recorded, where v2 defaults to the total and 0.
287
+ paid_total: payments.length > 0 ? major(sum(source.payments.map((payment) => payment.amountMinor))) : totalIncl,
288
+ change_total: major(source.changeMinor ?? 0),
289
+ total_qty: lineSum((calc) => calc.qty), line_count: calcs.length,
290
+ },
291
+ tax: {
292
+ display: side, breakdown, display_incl: side === 'incl', display_excl: side === 'excl',
293
+ breakdown_hidden: breakdown === 'hidden', breakdown_single: breakdown === 'single',
294
+ breakdown_itemized: breakdown === 'itemized',
295
+ },
296
+ tax_summary: taxSummary,
297
+ has_tax_summary: taxSummary.length > 0 && breakdown !== 'hidden',
298
+ payments,
299
+ fiscal: {
300
+ document_type: 'sale', sale_time: saleTime(source.saleTime?.at, source.saleTime?.tz || store.timezone),
301
+ sale_tz: source.saleTime?.tz ?? '', sale_counter: source.saleTime?.counter ?? null,
302
+ received_at: null, corrects: '', is_reprint: printCount > 1, reprint_count: Math.max(0, printCount - 1),
303
+ is_refund_document: false,
304
+ },
305
+ software: {
306
+ name: 'WCPOS', plugin_version: options.pluginVersion ?? '', app_version: options.appVersion ?? '',
307
+ app_build: options.appBuild ?? '',
308
+ },
309
+ register: {
310
+ id: source.registerId ?? register?.id ?? '',
311
+ // A receipt from another till does not borrow this till's name.
312
+ name: register && (source.registerId === undefined || source.registerId === register.id) ? register.name : '',
313
+ },
314
+ presentation_hints: {
315
+ display_tax: side, prices_entered_with_tax: store.pricesIncludeTax, rounding_mode: 'round',
316
+ locale: (store.locale || 'en-US').replace(/_/g, '-'), order_barcode_type: 'code128',
317
+ },
318
+ ...(Object.keys(i18n).length > 0 ? { i18n } : {}),
319
+ };
320
+ }
@@ -0,0 +1,29 @@
1
+ import type { ReceiptConfig } from '../../receipt/types';
2
+ import type { WcposReceiptOptions, WcposReceiptStore } from './types';
3
+
4
+ /** The WCPOS store settings and app context today's `ReceiptConfig` and the store's tax mode can fill (#698 mapping §3). */
5
+ export function wcposReceiptContext(
6
+ config: ReceiptConfig, tax: { pricesIncludeTax: boolean }, now?: () => Date,
7
+ ): { store: WcposReceiptStore; options: WcposReceiptOptions } {
8
+ const addressParts = (config.storeAddress ?? '').split('\n').filter((part) => part.trim() !== '');
9
+ const store: WcposReceiptStore = {
10
+ name: config.storeName,
11
+ ...(addressParts.length ? { addressParts } : {}),
12
+ // Stand-in (§3 store): the display mode follows the price mode, as TallyUI's own receipt prints.
13
+ taxDisplayCart: tax.pricesIncludeTax ? 'incl' : 'excl',
14
+ // Stand-in (§3 store): a TallyUI till always calculates tax.
15
+ calcTaxes: true,
16
+ pricesIncludeTax: tax.pricesIncludeTax,
17
+ };
18
+ const { software } = config;
19
+ const options: WcposReceiptOptions = {
20
+ ...(config.register && config.registerName ? { register: { id: config.register, name: config.registerName } } : {}),
21
+ // Stand-in (§3 options): TallyUI keeps the cashier's name only, so the WCPOS user id is 0.
22
+ ...(config.cashier ? { cashier: { id: 0, name: config.cashier } } : {}),
23
+ pluginVersion: software?.plugin_version, appVersion: software?.app_version, appBuild: software?.app_build,
24
+ // `fiscal.reprint_count` is the n-th reprint, so this print is the (n + 1)-th.
25
+ printCount: (config.fiscal?.reprint_count ?? 0) + 1,
26
+ ...(now ? { now } : {}),
27
+ };
28
+ return { store, options };
29
+ }
@@ -0,0 +1,153 @@
1
+ // Ported from WCPOS v2 packages/printer/src/encoder/format-receipt-data.ts (wcpos/monorepo 85ecbd43f, MIT).
2
+ import { formatWcposMoney } from './money';
3
+ import type {
4
+ WcposAdjustmentView, WcposItemTax, WcposItemTaxView, WcposReceiptAdjustment, WcposReceiptData, WcposReceiptView,
5
+ WcposRefundAdjustment, WcposRefundLine, WcposTaxId,
6
+ } from './types';
7
+
8
+ /** The labels every WCPOS template can rely on; a store's non-blank labels override them. */
9
+ export const WCPOS_DEFAULT_I18N: Readonly<Record<string, string>> = {
10
+ copy: 'COPY', corrects: 'Corrects', refunded_to: 'Refunded to', reprint: 'Reprint', register: 'Register',
11
+ sale_time: 'Sale time', document_refund: 'Refund', document_void: 'Void', document_cancellation: 'Cancellation',
12
+ software: 'Software', order: 'Order', date: 'Date', cashier: 'Cashier', customer: 'Customer',
13
+ store_tax_id_label_other: 'Tax ID', customer_tax_id_label_other: 'Tax ID',
14
+ subtotal: 'Subtotal', total_saved: 'Total saved', total: 'Total', tax: 'Tax', tax_summary: 'Tax Summary',
15
+ included_tax: 'Tax included', total_tax: 'Total Tax', tax_amount_short: 'Tax', taxable_excl_short: 'Taxable excl.',
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!',
18
+ };
19
+
20
+ /** The built-in label per WCPOS tax-ID type. */
21
+ export const WCPOS_TAX_ID_LABELS: Readonly<Record<string, string>> = {
22
+ eu_vat: 'VAT ID', gb_vat: 'VAT No.', sa_vat: 'VAT No.', au_abn: 'ABN', br_cpf: 'CPF', br_cnpj: 'CNPJ',
23
+ in_gst: 'GSTIN', it_cf: 'Codice Fiscale', it_piva: 'P.IVA', es_nif: 'NIF', ar_cuit: 'CUIT',
24
+ ca_gst_hst: 'GST/HST No.', us_ein: 'EIN', de_ust_id: 'USt-IdNr.', de_steuernummer: 'Steuernummer',
25
+ de_hrb: 'HRB', nl_kvk: 'KVK', fr_siret: 'SIRET', fr_siren: 'SIREN', gb_company: 'Company No.', ch_uid: 'UID',
26
+ };
27
+
28
+ export interface FormatWcposReceiptOptions {
29
+ /** False for a currency symbol the printer's code page cannot encode: the ISO code is printed instead. */
30
+ isSymbolEncodable?: (symbol: string) => boolean;
31
+ }
32
+
33
+ const tri = (key: string): string[] => [key, `${key}_incl`, `${key}_excl`];
34
+ const own = (record: Readonly<Record<string, string>>, key: string): string | undefined =>
35
+ Object.hasOwn(record, key) ? record[key] : undefined;
36
+ const definedOnly = (values: Record<string, number | undefined>): Record<string, number> =>
37
+ Object.fromEntries(Object.entries(values).filter((entry): entry is [string, number] => entry[1] !== undefined));
38
+
39
+ /** `<key>_display` for each key whose value is a number; null and absent keys get no twin. */
40
+ function displays(source: object, keys: string[], format: (value: number) => string): Record<string, string> {
41
+ const out: Record<string, string> = {};
42
+ for (const key of keys) {
43
+ const value = (source as Record<string, unknown>)[key];
44
+ if (typeof value === 'number') out[`${key}_display`] = format(value);
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /**
50
+ * The template view of canonical WCPOS receipt data: the input unchanged, plus `*_display` money strings,
51
+ * filled tax-ID labels and `i18n` merged over WCPOS_DEFAULT_I18N. The input is not mutated.
52
+ */
53
+ export function formatWcposReceiptData(data: WcposReceiptData, options: FormatWcposReceiptOptions = {}): WcposReceiptView {
54
+ const hints = data.presentation_hints;
55
+ const side = hints.display_tax === 'incl' || hints.display_tax === 'excl' ? hints.display_tax
56
+ : hints.prices_entered_with_tax === false ? 'excl' : 'incl';
57
+ const moneyOptions = {
58
+ locale: hints.locale, decimals: data.store.price_decimals, isSymbolEncodable: options.isSymbolEncodable,
59
+ };
60
+ const money = (value: number) => formatWcposMoney(value, data.order.currency, moneyOptions);
61
+ // Savings are zero-falsy, so `{{#unit_savings_display}}` hides a zero saving.
62
+ const saving = (value: number) => (value === 0 ? '' : money(value));
63
+ const bySide = (incl: number | undefined, bare: number | undefined, excl: number | undefined) =>
64
+ side === 'excl' ? excl ?? bare ?? incl : incl ?? bare ?? excl;
65
+
66
+ const i18n: Record<string, string> = { ...WCPOS_DEFAULT_I18N };
67
+ for (const [key, value] of Object.entries(data.i18n ?? {})) {
68
+ if (typeof value === 'string' && value.trim() !== '') i18n[key] = value;
69
+ }
70
+ const taxIdLabel = (scope: 'store' | 'customer', id: WcposTaxId): string =>
71
+ (id.label && id.label.trim() !== '' ? id.label : undefined)
72
+ ?? own(i18n, `${scope}_tax_id_label_${id.type}`) ?? own(WCPOS_TAX_ID_LABELS, id.type)
73
+ ?? own(i18n, `${scope}_tax_id_label_other`) ?? 'Tax ID';
74
+ const labelled = (scope: 'store' | 'customer', ids: WcposTaxId[] | undefined) =>
75
+ ids ? { tax_ids: ids.map((id) => ({ ...id, label: taxIdLabel(scope, id) })) } : {};
76
+
77
+ const taxView = (tax: WcposItemTax): WcposItemTaxView => ({ ...tax, amount_display: money(tax.amount) });
78
+ const taxesKey = (taxes: WcposItemTax[] | undefined) => (taxes ? { taxes: taxes.map(taxView) } : {});
79
+ const adjustment = <T extends WcposReceiptAdjustment>({ taxes, ...row }: T) =>
80
+ ({ ...row, ...displays(row, tri('total'), money), ...taxesKey(taxes) }) as WcposAdjustmentView<T>;
81
+ const refundAdjustment = ({ taxes, ...row }: WcposRefundAdjustment) => ({
82
+ ...row, total_display: money(bySide(row.total_incl, row.total, row.total_excl) ?? row.total), ...taxesKey(taxes),
83
+ });
84
+ const refundLine = ({ taxes, ...line }: WcposRefundLine) => {
85
+ const perUnit = (value: number | undefined) => (value === undefined || line.qty === 0 ? undefined : value / line.qty);
86
+ const totals = {
87
+ line_total: line.line_total ?? line.total,
88
+ line_total_incl: line.line_total_incl ?? line.total_incl ?? line.total,
89
+ line_total_excl: line.line_total_excl ?? line.total_excl,
90
+ };
91
+ const units = {
92
+ unit_total: line.unit_total ?? perUnit(totals.line_total),
93
+ unit_total_incl: line.unit_total_incl ?? perUnit(totals.line_total_incl),
94
+ unit_total_excl: line.unit_total_excl ?? perUnit(totals.line_total_excl),
95
+ };
96
+ const view = { ...line, ...definedOnly(totals), ...definedOnly(units), line_total: totals.line_total };
97
+ const unit = bySide(units.unit_total_incl, units.unit_total, units.unit_total_excl);
98
+ return {
99
+ ...view, ...displays(view, ['line_total_incl', 'line_total_excl', 'unit_total_incl', 'unit_total_excl'], money),
100
+ total_display: money(bySide(line.total_incl, line.total, line.total_excl) ?? line.total),
101
+ line_total_display: money(bySide(totals.line_total_incl, totals.line_total, totals.line_total_excl) ?? line.total),
102
+ ...(unit === undefined ? {} : { unit_total_display: money(unit) }),
103
+ ...taxesKey(taxes),
104
+ };
105
+ };
106
+
107
+ const { totals, refunds, ...rest } = data;
108
+ return {
109
+ ...rest,
110
+ store: { ...data.store, ...labelled('store', data.store.tax_ids) },
111
+ customer: { ...data.customer, ...labelled('customer', data.customer.tax_ids) },
112
+ lines: data.lines.map((line) => ({
113
+ ...line,
114
+ ...displays(line, [
115
+ ...tri('unit_price'), ...tri('line_subtotal'), ...tri('discounts'), ...tri('line_total'), ...tri('regular_price'),
116
+ ...tri('selling_price'), ...tri('line_regular_total'), ...tri('line_selling_total'),
117
+ ], money),
118
+ ...displays(line, [...tri('unit_savings'), ...tri('line_savings')], saving),
119
+ taxes: line.taxes.map(taxView),
120
+ })) as WcposReceiptView['lines'],
121
+ fees: data.fees.map(adjustment),
122
+ shipping: data.shipping.map(adjustment),
123
+ discounts: data.discounts.map(adjustment),
124
+ totals: {
125
+ ...totals,
126
+ ...displays(totals, [
127
+ ...tri('subtotal'), ...tri('discount_total'), ...tri('total'), 'tax_total', 'paid_total', 'change_total',
128
+ 'refund_total', 'net_total',
129
+ ], money),
130
+ ...displays(totals, [...tri('sale_savings_total'), ...tri('total_saved')], saving),
131
+ } as WcposReceiptView['totals'],
132
+ tax_summary: data.tax_summary.map((row) => ({
133
+ ...row,
134
+ tax_amount_display: money(row.tax_amount),
135
+ taxable_amount_excl_display: row.taxable_amount_excl === null ? '' : money(row.taxable_amount_excl),
136
+ taxable_amount_incl_display: row.taxable_amount_incl === null ? '' : money(row.taxable_amount_incl),
137
+ })),
138
+ payments: data.payments.map((payment) => ({
139
+ ...payment, amount_display: money(payment.amount), ...displays(payment, ['tendered', 'change'], money),
140
+ })),
141
+ ...(refunds ? {
142
+ refunds: refunds.map(({ lines, fees, shipping, ...refund }) => ({
143
+ ...refund,
144
+ amount_display: money(refund.amount),
145
+ ...displays(refund, ['subtotal', 'tax_total', 'shipping_total', 'shipping_tax'], money),
146
+ ...(lines ? { lines: lines.map(refundLine) } : {}),
147
+ ...(fees ? { fees: fees.map(refundAdjustment) } : {}),
148
+ ...(shipping ? { shipping: shipping.map(refundAdjustment) } : {}),
149
+ })),
150
+ } : {}),
151
+ i18n,
152
+ };
153
+ }