@tallyui/pos 3.18.0 → 3.19.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 (69) hide show
  1. package/dist/index.d.ts +3195 -1721
  2. package/dist/index.js +3854 -672
  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 +19 -4
  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/tax/index.ts +6 -0
  65. package/src/tax/location-rates.ts +46 -0
  66. package/src/tax/sale-tax-contexts.ts +40 -0
  67. package/src/tax/tax-context.ts +37 -0
  68. package/src/tax/tax-derivation.ts +99 -0
  69. package/src/tax/tax-provider.tsx +4 -31
@@ -0,0 +1,203 @@
1
+ // TallyUI's three printable orders as a WcposReceiptSource. The field-by-field mapping is the #698 part B mapping;
2
+ // every figure stays in integer minor units, and nothing the order does not carry is invented.
3
+ import { paymentMethodOf, type StoreOrder } from '@tallyui/core';
4
+ import type { ChargeLine, SentOrder } from '../../order/types';
5
+ import type { PosOrder } from '../../pos-order/types';
6
+ import { buildReceiptData } from '../../receipt/build-receipt-data';
7
+ import { buildReceiptDataFromPosOrder } from '../../receipt/reprint';
8
+ import type { ReceiptConfig, ReceiptData } from '../../receipt/types';
9
+ import { wooGrossMinor } from '../../receipt/woo-gross';
10
+ import { roundMicrosToMinor, taxMicros } from '../../tax/exact';
11
+ import type { WcposItemTaxSource, WcposLineSource, WcposReceiptSource } from './types';
12
+
13
+ type Rate = { code?: string; ratePpm: number; compound?: boolean };
14
+ type MicrosRate = Rate & { taxMicros: string };
15
+ type RateKey = (rate: Rate) => string;
16
+
17
+ /**
18
+ * The key that joins a line's `taxes[].rateId` to `taxLines[].rateId`: the plain code when, in this order, every
19
+ * distinct (code, rate) pair has its own non-empty code; otherwise `JSON.stringify([code, ratePpm])` for every rate,
20
+ * which is the grouping `taxLinesByRate` uses. The WooCommerce `rateId` is not used: the rows lose it
21
+ * (`woocommerceTaxByRate` drops it), and whether a stored PosOrder line keeps it is unverified (its schema does not
22
+ * declare it).
23
+ */
24
+ function rateKeyOf(rates: Rate[]): RateKey {
25
+ const codes = new Map(rates.map((rate) => [JSON.stringify([rate.code ?? '', rate.ratePpm]), rate.code ?? '']));
26
+ const list = [...codes.values()];
27
+ const plain = list.every((code) => code !== '') && new Set(list).size === list.length;
28
+ return (rate) => (plain ? rate.code! : JSON.stringify([rate.code ?? '', rate.ratePpm]));
29
+ }
30
+
31
+ const sumTax = (rates: MicrosRate[]) => roundMicrosToMinor(rates.reduce((total, rate) => total + BigInt(rate.taxMicros), 0n));
32
+ const itemTaxes = (rates: MicrosRate[], key: RateKey): WcposItemTaxSource[] =>
33
+ rates.map((rate) => ({ rateId: key(rate), totalMinor: roundMicrosToMinor(BigInt(rate.taxMicros)) }));
34
+
35
+ /** A till line, its tax mode and WooCommerce gross already resolved by the order's adapter. */
36
+ interface TillLine {
37
+ name: string; sku: string; quantity: number; unitPriceMinor: number; regularUnitPriceMinor?: number;
38
+ taxStatus?: 'taxable' | 'none'; attributes?: Record<string, string>; netMinor: number; taxLines: MicrosRate[];
39
+ /** The price's own tax mode, and whether it differs from the order's. */
40
+ inclusive: boolean; converted: boolean;
41
+ /** Under WooCommerce (netMicros present): the rounded gross. `netMinor` is then exclusive whatever the mode. */
42
+ wooGrossMinor?: number;
43
+ /** A converted line's total in the order's mode, from TallyUI's receipt (its running tax share). */
44
+ convertedTotalMinor?: number;
45
+ /** A converted line's pre-discount amount in the order's mode: TallyUI's display amount, residue included (§2.4). */
46
+ displayAmountMinor?: number;
47
+ }
48
+
49
+ function tillLine(line: TillLine, key: RateKey): WcposLineSource {
50
+ // No pre-discount tax is stored: the subtotal's tax is the gross converted at the line's rates. The unit price is in
51
+ // its own mode even under WooCommerce, so that mode converts it. A converted line takes TallyUI's display amount, in
52
+ // the order's mode, so the subtotals add up to its receipt's rather than a cent off by the residue.
53
+ const display = line.converted && line.displayAmountMinor !== undefined;
54
+ const gross = display ? line.displayAmountMinor! : line.unitPriceMinor * line.quantity;
55
+ const grossInclusive = display ? !line.inclusive : line.inclusive;
56
+ const ratePpm = line.taxLines.reduce((total, rate) => total + rate.ratePpm, 0);
57
+ const subtotalTaxMinor = roundMicrosToMinor(taxMicros(gross, ratePpm, grossInclusive));
58
+ let totalMinor: number, totalTaxMinor: number;
59
+ if (line.wooGrossMinor !== undefined) {
60
+ // The WooCommerce lane first: its figures are an exclusive net and a rounded gross, never the line's own mode.
61
+ totalMinor = line.netMinor;
62
+ totalTaxMinor = line.wooGrossMinor - line.netMinor;
63
+ } else {
64
+ // A converted line's tax is its running share, so the lines add up to the order total as TallyUI's receipt does.
65
+ const share = line.convertedTotalMinor === undefined ? undefined
66
+ : line.inclusive ? line.netMinor - line.convertedTotalMinor : line.convertedTotalMinor - line.netMinor;
67
+ totalTaxMinor = share ?? sumTax(line.taxLines);
68
+ totalMinor = line.inclusive ? line.netMinor - totalTaxMinor : line.netMinor;
69
+ }
70
+ return {
71
+ name: line.name, sku: line.sku, quantity: line.quantity,
72
+ subtotalMinor: grossInclusive ? gross - subtotalTaxMinor : gross, subtotalTaxMinor, totalMinor, totalTaxMinor,
73
+ meta: Object.entries(line.attributes ?? {}).map(([name, value]) => ({ key: name, value })),
74
+ // The recorded prices are in the line's own mode, which build.ts reads as the sale's: kept only when they agree.
75
+ ...(!line.converted && line.regularUnitPriceMinor !== undefined ? {
76
+ recordedPrice: {
77
+ priceMinor: line.unitPriceMinor, regularPriceMinor: line.regularUnitPriceMinor,
78
+ ...(line.taxStatus ? { taxStatus: line.taxStatus } : {}),
79
+ },
80
+ } : {}),
81
+ taxes: itemTaxes(line.taxLines, key),
82
+ };
83
+ }
84
+
85
+ /** A till fee or shipping charge, in the order's mode; WooCommerce charges keep their net and rounded gross. */
86
+ function tillCharge(charge: ChargeLine, order: { pricesIncludeTax: boolean; woo: boolean }, key: RateKey) {
87
+ const tax = sumTax(charge.taxLines);
88
+ const woo = order.woo && charge.netMicros !== undefined;
89
+ return {
90
+ totalMinor: woo || !order.pricesIncludeTax ? charge.netMinor : charge.netMinor - tax,
91
+ totalTaxMinor: woo ? charge.totalMinor! - charge.netMinor : tax, taxes: itemTaxes(charge.taxLines, key),
92
+ };
93
+ }
94
+
95
+ type TillOrder = Pick<SentOrder, 'currency' | 'pricesIncludeTax' | 'taxRounding' | 'totalMinor' | 'taxMinor'> & {
96
+ fees?: ChargeLine[]; shipping?: Array<ChargeLine & { methodId?: string }>;
97
+ coupons?: Array<{ code: string; discountMinor: number; discountTaxMinor: number }>;
98
+ customer: { id?: string; name?: string; email?: string } | null;
99
+ };
100
+
101
+ /** What SentOrder and PosOrder share. The status is `completed`: a till order is paid in full when it is sent. */
102
+ function tillSource(order: TillOrder, receipt: ReceiptData, lines: TillLine[]) {
103
+ const woo = order.taxRounding?.granularity === 'woocommerce';
104
+ const charges = [...order.fees ?? [], ...order.shipping ?? []];
105
+ const rates: Rate[] = [...receipt.totals.taxLines, ...lines.flatMap((line) => line.taxLines),
106
+ ...charges.flatMap((charge) => charge.taxLines)];
107
+ const key = rateKeyOf(rates);
108
+ const context = { pricesIncludeTax: order.pricesIncludeTax, woo };
109
+ return {
110
+ status: 'completed', currency: order.currency, pricesIncludeTax: order.pricesIncludeTax,
111
+ customer: order.customer && { id: order.customer.id, firstName: order.customer.name, email: order.customer.email },
112
+ lines: lines.map((line) => tillLine(line, key)),
113
+ fees: (order.fees ?? []).map((fee) => ({ name: fee.name, ...tillCharge(fee, context, key) })),
114
+ shipping: (order.shipping ?? []).map((row) => ({
115
+ methodTitle: row.name, ...(row.methodId !== undefined ? { methodId: row.methodId } : {}), ...tillCharge(row, context, key),
116
+ })),
117
+ // Store-priced and WooCommerce coupons are listed; the line discounts already hold them, so no discountTotalMinor.
118
+ coupons: (order.coupons ?? []).map(({ code, discountMinor, discountTaxMinor }) => ({ code, discountMinor, discountTaxMinor })),
119
+ // The rows TallyUI's own receipt prints, labels included (config.taxLabels, else `Tax n%`).
120
+ taxLines: receipt.totals.taxLines.map((row) => ({
121
+ rateId: key(row), label: row.label, ...(row.code !== undefined ? { rateCode: row.code } : {}),
122
+ ratePercent: row.ratePpm / 10000,
123
+ ...(rates.some((rate) => rate.compound && key(rate) === key(row)) ? { compound: true } : {}),
124
+ taxTotalMinor: row.amountMinor, shippingTaxTotalMinor: 0,
125
+ })),
126
+ totalMinor: order.totalMinor, totalTaxMinor: order.taxMinor,
127
+ };
128
+ }
129
+
130
+ const methodTitle = (method: string) => (method === 'cash' || method === 'external' ? paymentMethodOf(method).title : method);
131
+
132
+ /** The first print of a sale, from the order as sent. */
133
+ export function wcposSourceFromSentOrder(order: SentOrder, config: ReceiptConfig): WcposReceiptSource {
134
+ const receipt = buildReceiptData(order, config);
135
+ const woo = order.taxRounding?.granularity === 'woocommerce';
136
+ const lines = order.lineItems.map((li, index): TillLine => ({
137
+ ...li, inclusive: li.taxInclusive, converted: li.priceTaxModeConverted !== undefined,
138
+ displayAmountMinor: receipt.lineItems[index]!.displayAmountMinor,
139
+ ...(woo && li.netMicros !== undefined ? { wooGrossMinor: li.totalMinor! }
140
+ : li.priceTaxModeConverted ? { convertedTotalMinor: receipt.lineItems[index]!.lineTotalMinor } : {}),
141
+ }));
142
+ return {
143
+ id: order.id, number: order.id, createdAt: order.createdAt, customerNote: order.note, ...tillSource(order, receipt, lines),
144
+ // Cash records the full tender; the change is the order's.
145
+ payments: order.payments.map((p) => ({
146
+ methodId: p.method, methodTitle: methodTitle(p.method), amountMinor: p.amountMinor,
147
+ ...(p.reference !== undefined ? { transactionId: p.reference } : {}),
148
+ })),
149
+ changeMinor: order.changeDueMinor,
150
+ };
151
+ }
152
+
153
+ /** A reprint of the till's own stored order. */
154
+ export function wcposSourceFromPosOrder(order: PosOrder, config: ReceiptConfig): WcposReceiptSource {
155
+ const receipt = buildReceiptDataFromPosOrder(order, config);
156
+ const rounding = order.taxRounding;
157
+ const lines = order.lines.map((li, index): TillLine => ({
158
+ ...li, inclusive: li.taxInclusive ?? order.pricesIncludeTax, converted: li.taxInclusive !== undefined,
159
+ displayAmountMinor: receipt.lineItems[index]!.displayAmountMinor,
160
+ ...(rounding.granularity === 'woocommerce' && li.netMicros !== undefined
161
+ ? { wooGrossMinor: wooGrossMinor(li, order, rounding.roundAtSubtotal) }
162
+ : li.taxInclusive !== undefined ? { convertedTotalMinor: receipt.lineItems[index]!.lineTotalMinor } : {}),
163
+ }));
164
+ return {
165
+ id: order.id, number: order.serverRefs?.displayId ?? order.id, createdAt: order.createdAt, customerNote: order.note ?? '',
166
+ ...tillSource(order, receipt, lines),
167
+ // A stored cash leg is net of change: the tender is what was handed over.
168
+ payments: order.payments.map((p) => ({
169
+ methodId: p.method, methodTitle: methodTitle(p.method), amountMinor: p.tenderedMinor ?? p.amountMinor,
170
+ ...(p.reference !== undefined ? { transactionId: p.reference } : {}),
171
+ ...(p.tenderedMinor !== undefined ? { tenderedMinor: p.tenderedMinor } : {}),
172
+ ...(p.changeMinor !== undefined ? { changeMinor: p.changeMinor } : {}),
173
+ })),
174
+ changeMinor: order.payments.reduce((total, p) => total + (p.changeMinor ?? 0), 0),
175
+ ...(order.registerId !== undefined ? { registerId: order.registerId } : {}),
176
+ };
177
+ }
178
+
179
+ /** A reprint of an order read from the store. Per-rate line taxes exist only when the order has one rate. */
180
+ export function wcposSourceFromStoreOrder(order: StoreOrder, _config: ReceiptConfig): WcposReceiptSource {
181
+ const key = rateKeyOf(order.taxLines);
182
+ const only = order.taxLines.length === 1 ? key(order.taxLines[0]!) : undefined;
183
+ return {
184
+ id: order.id, number: order.reference, currency: order.currency, status: order.status, createdAt: order.placedAt,
185
+ customerNote: '', pricesIncludeTax: order.pricesIncludeTax,
186
+ customer: order.customer && { id: order.customer.id, firstName: order.customer.name, email: order.customer.email },
187
+ lines: order.lines.map((li) => ({
188
+ name: li.name, sku: li.sku, quantity: li.quantity, subtotalMinor: li.subtotalMinor,
189
+ subtotalTaxMinor: li.subtotalTaxMinor, totalMinor: li.totalMinor, totalTaxMinor: li.taxMinor,
190
+ ...(only !== undefined ? { taxes: [{ rateId: only, totalMinor: li.taxMinor }] } : {}),
191
+ })),
192
+ fees: order.fees.map((fee) => ({ name: fee.name, totalMinor: fee.totalMinor, totalTaxMinor: fee.taxMinor })),
193
+ shipping: order.shipping.map((row) => ({ methodTitle: row.name, totalMinor: row.totalMinor, totalTaxMinor: row.taxMinor })),
194
+ coupons: order.coupons.map(({ code, discountMinor, discountTaxMinor }) => ({ code, discountMinor, discountTaxMinor })),
195
+ taxLines: order.taxLines.map((row) => ({
196
+ rateId: key(row), label: row.label, ...(row.code !== undefined ? { rateCode: row.code } : {}),
197
+ ratePercent: row.ratePpm / 10000, taxTotalMinor: row.amountMinor, shippingTaxTotalMinor: 0,
198
+ })),
199
+ totalMinor: order.totalMinor, totalTaxMinor: order.taxMinor,
200
+ discountTotalMinor: order.discountMinor, discountTaxMinor: order.discountTaxMinor,
201
+ payments: order.payments.map((p) => ({ methodId: p.method, methodTitle: p.title ?? p.method, amountMinor: p.amountMinor })),
202
+ };
203
+ }
@@ -0,0 +1,11 @@
1
+ export { wcposReceiptData } from './build';
2
+ export { formatWcposReceiptData, WCPOS_DEFAULT_I18N, WCPOS_TAX_ID_LABELS } from './format';
3
+ export { formatWcposMoney } from './money';
4
+ export { wcposSourceFromSentOrder, wcposSourceFromPosOrder, wcposSourceFromStoreOrder } from './from-orders';
5
+ export { wcposReceiptContext } from './context';
6
+ export type { FormatWcposReceiptOptions } from './format';
7
+ export type { WcposMoneyOptions } from './money';
8
+ export type {
9
+ WcposReceiptSource, WcposReceiptStore, WcposReceiptOptions, WcposReceiptData, WcposReceiptView, WcposTaxId,
10
+ WcposReceiptDate, WcposReceiptLine, WcposLineView,
11
+ } from './types';
@@ -0,0 +1,42 @@
1
+ // Ported from WCPOS v2 packages/printer/src/encoder/format-money.ts (wcpos/monorepo 85ecbd43f, MIT).
2
+
3
+ export interface WcposMoneyOptions {
4
+ /** `en_US` or `en-US`. Default `en-US`. */
5
+ locale?: string;
6
+ /** Fixed fraction digits; the currency's own default when absent. */
7
+ decimals?: number;
8
+ /** False for a symbol the printer cannot encode: the ISO code is printed instead. */
9
+ isSymbolEncodable?: (symbol: string) => boolean;
10
+ }
11
+
12
+ /**
13
+ * A major-unit amount as WCPOS prints it: Intl currency with the narrow symbol (`$25.00`, `25,00 €`).
14
+ * When Intl throws, it retries without the narrow symbol, then falls back to `"<CURRENCY> <value>"`
15
+ * (`INVALID 25.00`), or the bare number when there is no currency.
16
+ */
17
+ export function formatWcposMoney(value: number, currency: string, options: WcposMoneyOptions = {}): string {
18
+ const locale = (options.locale || 'en-US').replace(/_/g, '-');
19
+ const { decimals, isSymbolEncodable } = options;
20
+ const digits = decimals === undefined ? {} : { minimumFractionDigits: decimals, maximumFractionDigits: decimals };
21
+ const format = (currencyDisplay?: 'narrowSymbol'): string => {
22
+ const base = { style: 'currency' as const, currency, ...digits };
23
+ const formatter = new Intl.NumberFormat(locale, currencyDisplay ? { ...base, currencyDisplay } : base);
24
+ if (isSymbolEncodable) {
25
+ const symbol = formatter.formatToParts(value).find((part) => part.type === 'currency')?.value ?? '';
26
+ if (!isSymbolEncodable(symbol)) {
27
+ return new Intl.NumberFormat(locale, { ...base, currencyDisplay: 'code' }).format(value);
28
+ }
29
+ }
30
+ return formatter.format(value);
31
+ };
32
+ try {
33
+ return format('narrowSymbol');
34
+ } catch {
35
+ try {
36
+ return format();
37
+ } catch {
38
+ const fixed = value.toFixed(decimals ?? 2);
39
+ return currency ? `${currency} ${fixed}` : fixed;
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,350 @@
1
+ // WCPOS v2 receipt-data vocabulary (wcpos/monorepo 85ecbd43f, MIT), as typed for TallyUI.
2
+ // The canonical shape is v2's `mapReceiptData(buildReceiptData(...))`; snake_case keys are WCPOS's template tags.
3
+
4
+ /** A tax registration number (VAT ID, ABN, ...). `type` is WCPOS's id such as `eu_vat` or `de_ust_id`. */
5
+ export interface WcposTaxId { type: string; value: string; country?: string; label?: string }
6
+
7
+ /** One tax rate's share of an item, in minor units. `rateId` matches a `taxLines` entry. */
8
+ export interface WcposItemTaxSource { rateId: number | string; totalMinor: number }
9
+
10
+ /** A sale line. Amounts are integer minor units, excluding tax unless named `*TaxMinor`. */
11
+ export interface WcposLineSource {
12
+ name: string;
13
+ sku?: string;
14
+ /** Negative on a refund line. */
15
+ quantity: number;
16
+ /** Line total before discount, and its tax. */
17
+ subtotalMinor: number;
18
+ subtotalTaxMinor: number;
19
+ /** Line total after discount, and its tax. */
20
+ totalMinor: number;
21
+ totalTaxMinor: number;
22
+ /** Keys starting `_` are hidden; `displayKey`/`displayValue` win when given. */
23
+ meta?: Array<{ key: string; value: unknown; displayKey?: string; displayValue?: unknown }>;
24
+ /** The price the POS recorded per unit, in the sale's price basis (`pricesIncludeTax`). */
25
+ recordedPrice?: { priceMinor: number; regularPriceMinor: number; taxStatus?: 'taxable' | 'none' };
26
+ taxes?: WcposItemTaxSource[];
27
+ }
28
+
29
+ /**
30
+ * A platform-neutral description of a sale, in integer minor units of `currency`.
31
+ * It mirrors the WooCommerce order fields WCPOS v2 reads, without the WooCommerce wire format.
32
+ */
33
+ export interface WcposReceiptSource {
34
+ /** `Number(id)`, or 0 when that is not a number. */
35
+ id: number | string;
36
+ number: string;
37
+ currency: string;
38
+ /** WooCommerce-style status slug: `completed`, `pending`, `on-hold`, ... */
39
+ status: string;
40
+ /** ISO stamp; becomes `order.created.datetime` as given. */
41
+ createdAt: string;
42
+ customerNote: string;
43
+ paymentUrl?: string;
44
+ /** The basis the sale was rung up on. It wins over the store's setting for recorded prices. */
45
+ pricesIncludeTax: boolean;
46
+ customer: {
47
+ id?: number | string; firstName?: string; lastName?: string; email?: string; phone?: string;
48
+ taxIds?: WcposTaxId[];
49
+ } | null;
50
+ lines: WcposLineSource[];
51
+ fees: Array<{ name: string; totalMinor: number; totalTaxMinor: number; taxes?: WcposItemTaxSource[] }>;
52
+ shipping: Array<{
53
+ methodTitle: string; methodId?: string; totalMinor: number; totalTaxMinor: number; taxes?: WcposItemTaxSource[];
54
+ }>;
55
+ /** `quickDiscountPercent`: absent for a coupon, null for a fixed quick discount, else the percentage. */
56
+ coupons: Array<{ code: string; discountMinor: number; discountTaxMinor: number; quickDiscountPercent?: number | null }>;
57
+ taxLines: Array<{
58
+ rateId: number | string; label?: string; rateCode?: string; ratePercent?: number; compound?: boolean;
59
+ taxTotalMinor: number; shippingTaxTotalMinor: number;
60
+ }>;
61
+ totalMinor: number;
62
+ totalTaxMinor: number;
63
+ /** The order's own discount total (excl.) and its tax; the line sums are used when absent. */
64
+ discountTotalMinor?: number;
65
+ discountTaxMinor?: number;
66
+ payments: Array<{
67
+ methodId: string; methodTitle: string; amountMinor: number; transactionId?: string;
68
+ tenderedMinor?: number; changeMinor?: number;
69
+ }>;
70
+ changeMinor?: number;
71
+ /** The register the sale was rung up on. */
72
+ registerId?: string;
73
+ /** The fiscal sale stamp, its IANA zone and the sale counter. */
74
+ saleTime?: { at: string; tz?: string; counter?: number };
75
+ }
76
+
77
+ /** The WCPOS store settings the receipt reads. */
78
+ export interface WcposReceiptStore {
79
+ name: string;
80
+ logo?: string;
81
+ /** Address, address 2, city, "state postcode", country, in that order. */
82
+ addressParts?: string[];
83
+ phone?: string;
84
+ email?: string;
85
+ taxIds?: WcposTaxId[];
86
+ /** `wc_price_decimals`; kept only when a non-negative integer. */
87
+ priceDecimals?: number;
88
+ taxDisplayCart: 'incl' | 'excl';
89
+ /** `'single'` or `'itemized'`; anything else gives `'itemized'`. */
90
+ taxTotalDisplay?: string;
91
+ calcTaxes: boolean;
92
+ /** The store setting; feeds `presentation_hints.prices_entered_with_tax`. */
93
+ pricesIncludeTax: boolean;
94
+ /** `en_US` or `en-US`. */
95
+ locale?: string;
96
+ /** IANA zone for `order.printed` and `fiscal.sale_time`. */
97
+ timezone?: string;
98
+ /** The decimal separator for a quick-discount percentage. Default `.`. */
99
+ priceDecimalSep?: string;
100
+ receiptI18n?: Record<string, unknown>;
101
+ }
102
+
103
+ /** App context the order does not carry. */
104
+ export interface WcposReceiptOptions {
105
+ register?: { id: string; name: string };
106
+ cashier?: { id: number; name: string };
107
+ pluginVersion?: string;
108
+ appVersion?: string;
109
+ appBuild?: string;
110
+ /** How many times this receipt has printed, this print included. */
111
+ printCount?: number;
112
+ /** A translated label for a status slug. Returning the slug means "unknown". */
113
+ statusLabel?: (slug: string) => string;
114
+ /** Wins over `store.receiptI18n`. */
115
+ receiptI18n?: Record<string, unknown>;
116
+ /** Clock for `order.printed`. Default `() => new Date()`. */
117
+ now?: () => Date;
118
+ }
119
+
120
+ /** WCPOS's date block. Only the server fills every key; a local receipt sets `datetime` and leaves the rest ''. */
121
+ export interface WcposReceiptDate {
122
+ datetime: string; date: string; time: string;
123
+ datetime_short: string; datetime_long: string; datetime_full: string;
124
+ date_short: string; date_long: string; date_full: string;
125
+ date_ymd: string; date_dmy: string; date_mdy: string;
126
+ weekday_short: string; weekday_long: string;
127
+ day: string; month: string; month_short: string; month_long: string; year: string;
128
+ }
129
+
130
+ /** `x`, `x_incl` and `x_excl`: the display-side value and both bases. */
131
+ export type WcposTri<K extends string> = K | `${K}_incl` | `${K}_excl`;
132
+ type Amounts<K extends string, V = number> = { [P in WcposTri<K>]: V };
133
+
134
+ /** One tax rate on an item. `rate` is the percentage, or null when unknown. */
135
+ export interface WcposItemTax { code: string; rate: number | null; label?: string; compound?: boolean; amount: number }
136
+
137
+ /**
138
+ * A sale line, in major units. `unit_price*` is the unit before discount.
139
+ * Recorded-price and savings fields are null when unknown, never 0.
140
+ */
141
+ export interface WcposReceiptLine extends
142
+ Amounts<'unit_price'>, Amounts<'line_subtotal'>, Amounts<'discounts'>, Amounts<'line_total'>,
143
+ Amounts<'regular_price', number | null>, Amounts<'selling_price', number | null>,
144
+ Amounts<'unit_savings', number | null>, Amounts<'line_regular_total', number | null>,
145
+ Amounts<'line_selling_total', number | null>, Amounts<'line_savings', number | null> {
146
+ key: string;
147
+ name: string;
148
+ sku: string;
149
+ qty: number;
150
+ /** True when the line's discount already contains the sale saving. */
151
+ savings_in_discounts: boolean;
152
+ meta: Array<{ key: string; value: string }>;
153
+ taxes: WcposItemTax[];
154
+ /** Server payload only. */
155
+ unit_subtotal?: number; unit_subtotal_incl?: number; unit_subtotal_excl?: number;
156
+ qty_refunded?: number; total_refunded?: number;
157
+ }
158
+
159
+ /** A fee, a shipping row or a discount. Discount amounts are positive magnitudes. */
160
+ export interface WcposReceiptAdjustment extends Amounts<'total'> {
161
+ label: string;
162
+ meta?: Array<{ key: string; value: string }>;
163
+ taxes?: WcposItemTax[];
164
+ }
165
+ export interface WcposReceiptShipping extends WcposReceiptAdjustment { method_id?: string }
166
+ export interface WcposReceiptDiscount extends WcposReceiptAdjustment { code?: string; codes?: string }
167
+
168
+ export interface WcposReceiptTotals extends
169
+ Amounts<'subtotal'>, Amounts<'discount_total'>, Amounts<'total'>,
170
+ Amounts<'sale_savings_total', number | null>, Amounts<'total_saved', number | null> {
171
+ /** True when the savings are known for the display side. */
172
+ total_saved_complete: boolean;
173
+ tax_total: number;
174
+ paid_total: number;
175
+ change_total: number;
176
+ refund_total?: number;
177
+ net_total?: number;
178
+ total_qty?: number;
179
+ line_count?: number;
180
+ }
181
+
182
+ /** Section guards for the tax display. */
183
+ export interface WcposReceiptTax {
184
+ display: 'incl' | 'excl';
185
+ breakdown: 'hidden' | 'single' | 'itemized';
186
+ display_incl: boolean;
187
+ display_excl: boolean;
188
+ breakdown_hidden: boolean;
189
+ breakdown_single: boolean;
190
+ breakdown_itemized: boolean;
191
+ }
192
+
193
+ /** One row per tax rate. `taxable_amount_*` is null when no item carries the rate. */
194
+ export interface WcposTaxSummaryRow {
195
+ code: string;
196
+ rate: number | null;
197
+ label: string;
198
+ compound?: boolean;
199
+ tax_amount: number;
200
+ taxable_amount_excl: number | null;
201
+ taxable_amount_incl: number | null;
202
+ }
203
+
204
+ export interface WcposReceiptPayment {
205
+ method_id: string;
206
+ method_title: string;
207
+ amount: number;
208
+ transaction_id: string;
209
+ tendered?: number;
210
+ change?: number;
211
+ }
212
+
213
+ /** A refund line inside a refund. Amounts are positive. */
214
+ export interface WcposRefundLine {
215
+ name: string; sku?: string; qty: number; total: number; line_total?: number;
216
+ total_incl?: number; total_excl?: number; line_total_incl?: number; line_total_excl?: number;
217
+ unit_total?: number; unit_total_incl?: number; unit_total_excl?: number;
218
+ taxes?: WcposItemTax[];
219
+ }
220
+ export interface WcposRefundAdjustment {
221
+ label: string; total: number; total_incl?: number; total_excl?: number; method_id?: string; taxes?: WcposItemTax[];
222
+ }
223
+
224
+ /** A refund against the order. Never produced by `wcposReceiptData`; every amount is positive. */
225
+ export interface WcposReceiptRefund {
226
+ id: number;
227
+ amount: number;
228
+ subtotal?: number; tax_total?: number; shipping_total?: number; shipping_tax?: number;
229
+ reason?: string; refunded_by_id?: number; refunded_by_name?: string; refunded_payment?: boolean;
230
+ destination?: string; gateway_id?: string; gateway_title?: string; processing_mode?: string;
231
+ date?: WcposReceiptDate;
232
+ lines?: WcposRefundLine[];
233
+ fees?: WcposRefundAdjustment[];
234
+ shipping?: WcposRefundAdjustment[];
235
+ }
236
+
237
+ export interface WcposReceiptFiscal {
238
+ document_type: 'sale' | 'refund' | 'void' | 'cancellation';
239
+ sale_time: WcposReceiptDate | null;
240
+ sale_tz: string;
241
+ sale_counter: number | null;
242
+ received_at: WcposReceiptDate | null;
243
+ corrects: string;
244
+ is_reprint: boolean;
245
+ reprint_count: number;
246
+ is_refund_document: boolean;
247
+ immutable_id?: string;
248
+ }
249
+
250
+ export interface WcposReceiptPresentationHints {
251
+ display_tax: 'incl' | 'excl' | 'hidden' | 'itemized' | 'single';
252
+ prices_entered_with_tax: boolean;
253
+ rounding_mode: string;
254
+ /** BCP 47, `en-US`. */
255
+ locale: string;
256
+ order_barcode_type: 'qrcode' | 'code128' | 'ean13' | 'ean8' | 'upca';
257
+ }
258
+
259
+ /** WCPOS's canonical receipt data: money as numbers in major units, every always-set key present. */
260
+ export interface WcposReceiptData {
261
+ store: {
262
+ id: number; name: string; logo: string; price_decimals?: number;
263
+ address_lines: string[]; phone: string; email: string; tax_ids?: WcposTaxId[];
264
+ };
265
+ order: {
266
+ id: number; number: string; currency: string; customer_note: string;
267
+ /** The raw status slug. */
268
+ wc_status: string;
269
+ status_label: string;
270
+ needs_payment: boolean;
271
+ payment_url: string;
272
+ created_via?: string;
273
+ created: WcposReceiptDate; paid: WcposReceiptDate; completed: WcposReceiptDate; printed: WcposReceiptDate;
274
+ };
275
+ /** `{ id: 0, name: '' }` when unknown. */
276
+ cashier: { id: number; name: string };
277
+ customer: {
278
+ /** null for a guest. */
279
+ id: number | null;
280
+ name: string; first_name: string; email: string; phone: string;
281
+ tax_ids?: WcposTaxId[];
282
+ /** Server payload only; never set by `wcposReceiptData`. */
283
+ billing_address?: Record<string, string>;
284
+ shipping_address?: Record<string, string>;
285
+ };
286
+ lines: WcposReceiptLine[];
287
+ fees: WcposReceiptAdjustment[];
288
+ shipping: WcposReceiptShipping[];
289
+ discounts: WcposReceiptDiscount[];
290
+ totals: WcposReceiptTotals;
291
+ tax: WcposReceiptTax;
292
+ tax_summary: WcposTaxSummaryRow[];
293
+ /** Rows exist and the breakdown is not hidden. */
294
+ has_tax_summary: boolean;
295
+ /** Empty while the order still needs payment. */
296
+ payments: WcposReceiptPayment[];
297
+ refunds?: WcposReceiptRefund[];
298
+ fiscal: WcposReceiptFiscal;
299
+ software: { name: string; plugin_version: string; app_version: string; app_build: string };
300
+ register: { id: string; name: string };
301
+ presentation_hints: WcposReceiptPresentationHints;
302
+ /** The store's label overrides; absent when none are set. */
303
+ i18n?: Record<string, string>;
304
+ }
305
+
306
+ // The template view: the canonical data plus `*_display` money strings.
307
+ type Displays<K extends string> = { [P in K as `${P}_display`]: string };
308
+ type MaybeDisplays<K extends string> = { [P in K as `${P}_display`]?: string };
309
+
310
+ /** Savings twins are '' for 0; nullable twins are absent for null. */
311
+ export type WcposLineView = WcposReceiptLine
312
+ & Displays<WcposTri<'unit_price' | 'line_subtotal' | 'discounts' | 'line_total'>>
313
+ & MaybeDisplays<WcposTri<'regular_price' | 'selling_price' | 'unit_savings' | 'line_regular_total'
314
+ | 'line_selling_total' | 'line_savings'>>
315
+ & { taxes: WcposItemTaxView[] };
316
+ export type WcposItemTaxView = WcposItemTax & { amount_display: string };
317
+ export type WcposAdjustmentView<T extends WcposReceiptAdjustment = WcposReceiptAdjustment> = T
318
+ & Displays<WcposTri<'total'>> & { taxes?: WcposItemTaxView[] };
319
+ export type WcposTotalsView = WcposReceiptTotals
320
+ & Displays<WcposTri<'subtotal' | 'discount_total' | 'total'> | 'tax_total' | 'paid_total' | 'change_total'>
321
+ & MaybeDisplays<WcposTri<'sale_savings_total' | 'total_saved'> | 'refund_total' | 'net_total'>;
322
+ /** `taxable_amount_*_display` is '' when the amount is null. */
323
+ export type WcposTaxSummaryView = WcposTaxSummaryRow
324
+ & Displays<'tax_amount' | 'taxable_amount_excl' | 'taxable_amount_incl'>;
325
+ export type WcposPaymentView = WcposReceiptPayment & Displays<'amount'> & MaybeDisplays<'tendered' | 'change'>;
326
+ export type WcposRefundLineView = WcposRefundLine & { line_total: number }
327
+ & Displays<'total' | 'line_total'>
328
+ & MaybeDisplays<'unit_total' | 'line_total_incl' | 'line_total_excl' | 'unit_total_incl' | 'unit_total_excl'>
329
+ & { taxes?: WcposItemTaxView[] };
330
+ export type WcposRefundView = WcposReceiptRefund & Displays<'amount'>
331
+ & MaybeDisplays<'subtotal' | 'tax_total' | 'shipping_total' | 'shipping_tax'>
332
+ & {
333
+ lines?: WcposRefundLineView[];
334
+ fees?: Array<WcposRefundAdjustment & Displays<'total'>>;
335
+ shipping?: Array<WcposRefundAdjustment & Displays<'total'>>;
336
+ };
337
+
338
+ /** What a WCPOS template renders over. `i18n` is the defaults merged with the store's labels. */
339
+ export interface WcposReceiptView extends Omit<WcposReceiptData,
340
+ 'lines' | 'fees' | 'shipping' | 'discounts' | 'totals' | 'tax_summary' | 'payments' | 'refunds' | 'i18n'> {
341
+ lines: WcposLineView[];
342
+ fees: WcposAdjustmentView[];
343
+ shipping: Array<WcposAdjustmentView<WcposReceiptShipping>>;
344
+ discounts: Array<WcposAdjustmentView<WcposReceiptDiscount>>;
345
+ totals: WcposTotalsView;
346
+ tax_summary: WcposTaxSummaryView[];
347
+ payments: WcposPaymentView[];
348
+ refunds?: WcposRefundView[];
349
+ i18n: Record<string, string>;
350
+ }
@@ -81,3 +81,63 @@ export function deriveExpected({
81
81
  }
82
82
  return totals;
83
83
  }
84
+
85
+ export interface DrawerTerm { amountMinor: number; count: number }
86
+ export interface DrawerTerms {
87
+ floatMinor: number;
88
+ cashSales: DrawerTerm;
89
+ cashRefunds: DrawerTerm;
90
+ paidIn: DrawerTerm;
91
+ paidOut: DrawerTerm;
92
+ noSales: number;
93
+ /** Non-cash methods: captured rows minus applied refunds, keyed by method_id. */
94
+ otherTenders: Record<string, DrawerTerm>;
95
+ /** Cash sales − cash refunds + Σ other tenders' amounts (v2 `register-panel.tsx:216-219`). */
96
+ sessionSalesMinor: number;
97
+ /** Exactly deriveExpected's result for the same input. */
98
+ expected: Record<string, number>;
99
+ }
100
+
101
+ /**
102
+ * `deriveExpected`'s figures term by term, each with the number of rows behind it, for the
103
+ * register panel's drawer ledger (WCPOS v2 `deriveDrawerTerms`, `packages/query/src/register-session/expected.ts:210-342`).
104
+ * It applies `deriveExpected`'s filters, and `expected` is `deriveExpected`'s own result, so
105
+ * `expected.cash` is float + cash sales − cash refunds + paid in − paid out, and each other
106
+ * method's figure is its `otherTenders` amount. A refund counts once per method it touches.
107
+ */
108
+ export function deriveDrawerTerms(input: Parameters<typeof deriveExpected>[0]): DrawerTerms {
109
+ const { session, movements, ledgerRowsBySession, refunds } = input;
110
+ const term = (): DrawerTerm => ({ amountMinor: 0, count: 0 });
111
+ const add = (target: DrawerTerm, amountMinor: number) => {
112
+ target.amountMinor += amountMinor;
113
+ target.count += 1;
114
+ };
115
+ const [cashSales, cashRefunds, paidIn, paidOut] = [term(), term(), term(), term()];
116
+ const otherTenders: Record<string, DrawerTerm> = {};
117
+ let noSales = 0;
118
+ for (const row of ledgerRowsBySession) {
119
+ if (row.session_id !== session.id || row.status !== 'captured') continue;
120
+ const method = row.kind === 'cash' ? 'cash' : row.method_id;
121
+ add(method === 'cash' ? cashSales : (otherTenders[method] ??= term()), row.amountMinor);
122
+ }
123
+ const voids = new Set(movements.filter((row) => row.session_id === session.id && row.type === 'void').map((row) => row.voids));
124
+ for (const row of movements) {
125
+ if (row.session_id !== session.id || row.voided_by || voids.has(row.id)) continue;
126
+ if (row.type === 'paid_in') add(paidIn, row.amountMinor);
127
+ if (row.type === 'paid_out') add(paidOut, row.amountMinor);
128
+ if (row.type === 'no_sale') noSales += 1;
129
+ }
130
+ for (const refund of refunds ?? []) {
131
+ if (refund.status !== 'applied' || refund.sessionId !== session.id) continue;
132
+ for (const [method, amount] of refundAmounts(refund)) {
133
+ if (method === 'cash') add(cashRefunds, amount);
134
+ else add((otherTenders[method] ??= term()), -amount);
135
+ }
136
+ }
137
+ const otherMinor = Object.values(otherTenders).reduce((sum, row) => sum + row.amountMinor, 0);
138
+ return {
139
+ floatMinor: session.countedFloatMinor, cashSales, cashRefunds, paidIn, paidOut, noSales, otherTenders,
140
+ sessionSalesMinor: cashSales.amountMinor - cashRefunds.amountMinor + otherMinor,
141
+ expected: deriveExpected(input),
142
+ };
143
+ }