@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,67 @@
1
+ import type { StoreOrder } from '@tallyui/core';
2
+ import type { PosOrder } from '../pos-order/types';
3
+ import type { PosRefund } from '../refund/pos-refund';
4
+ import { roundMicrosToMinor, taxLinesByRate } from '../tax/exact';
5
+ import type { LineJoin, ReportLine, ReportOrder, ReportRefund } from './types';
6
+
7
+ function joinedLine(line: { productId?: string; variantId?: string; quantity: number }, join?: LineJoin): Pick<ReportLine, 'costMinor' | 'category'> {
8
+ const answer = join?.({
9
+ ...(line.productId !== undefined ? { productId: line.productId } : {}),
10
+ ...(line.variantId !== undefined ? { variantId: line.variantId } : {}),
11
+ });
12
+ return {
13
+ ...(typeof answer?.unitCostMinor === 'number' && Number.isFinite(answer.unitCostMinor)
14
+ ? { costMinor: Math.round(answer.unitCostMinor * line.quantity) } : {}),
15
+ ...(answer?.category ? { category: answer.category } : {}),
16
+ };
17
+ }
18
+
19
+ export function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin): ReportOrder {
20
+ const taxedLines = [...order.lines.map((line) => ({ ...line, taxInclusive: order.taxRounding.granularity === 'woocommerce'
21
+ && line.netMicros !== undefined ? order.pricesIncludeTax : line.taxInclusive ?? order.pricesIncludeTax })),
22
+ ...[...(order.fees ?? []), ...(order.shipping ?? [])].map((charge) => ({ ...charge, taxInclusive: order.pricesIncludeTax }))];
23
+ const taxes = order.taxByRate ?? taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding);
24
+ return {
25
+ id: order.id, at: order.createdAt, totalMinor: order.totalMinor, taxMinor: order.taxMinor,
26
+ discountMinor: order.discountMinor, needsPayment: false, refunds: [],
27
+ lines: order.lines.map((line) => {
28
+ const taxMinor = roundMicrosToMinor(line.taxLines.reduce((sum, tax) => sum + BigInt(tax.taxMicros), 0n));
29
+ return {
30
+ key: line.variantId || line.productId || line.name, name: line.name, quantity: line.quantity,
31
+ netMinor: order.taxRounding.granularity === 'woocommerce' && line.netMicros !== undefined
32
+ ? line.netMinor
33
+ : (line.taxInclusive ?? order.pricesIncludeTax) ? line.netMinor - taxMinor : line.netMinor,
34
+ taxMinor, ...joinedLine(line, join),
35
+ };
36
+ }),
37
+ payments: order.payments.map(({ method, amountMinor }) => ({ method, amountMinor })),
38
+ taxes: taxes.map((row) => ({
39
+ ratePpm: row.ratePpm, ...(row.code !== undefined ? { code: row.code } : {}),
40
+ label: row.label ?? `Tax ${row.ratePpm / 10000}%`, taxMinor: row.amountMinor, netMinor: row.netMinor,
41
+ })),
42
+ };
43
+ }
44
+
45
+ export function reportOrderFromStoreOrder(order: StoreOrder, join?: LineJoin): ReportOrder {
46
+ return {
47
+ id: order.id, at: order.placedAt, totalMinor: order.totalMinor, taxMinor: order.taxMinor, discountMinor: order.discountMinor,
48
+ lines: order.lines.map((line) => ({
49
+ key: line.variantId || line.productId || line.name, name: line.name, quantity: line.quantity,
50
+ netMinor: line.totalMinor, taxMinor: line.taxMinor, ...joinedLine(line, join),
51
+ })),
52
+ payments: order.payments.map(({ method, title, amountMinor }) => ({ method, ...(title !== undefined ? { label: title } : {}), amountMinor })),
53
+ taxes: order.taxLines.map(({ ratePpm, code, label, amountMinor }) => ({
54
+ ratePpm, ...(code !== undefined ? { code } : {}), label, taxMinor: amountMinor, netMinor: null,
55
+ })),
56
+ refunds: order.refunds.map(({ id, amountMinor }) => ({ id, amountMinor })),
57
+ };
58
+ }
59
+
60
+ export function reportRefundFromPosRefund(refund: PosRefund): ReportRefund | undefined {
61
+ if (refund.status !== 'applied') return undefined;
62
+ return {
63
+ id: refund.id, orderId: refund.orderId, at: refund.envelope.payload.createdAt || refund.createdAt,
64
+ amountMinor: refund.result && Number.isSafeInteger(refund.result.totalMinor)
65
+ ? refund.result.totalMinor : refund.envelope.payload.totalMinor,
66
+ };
67
+ }
@@ -0,0 +1,5 @@
1
+ export { salesFigures, marginOf, comparisonRange, daysOf, inRange } from './sales-figures';
2
+ export { presetRange, DATE_PRESETS, type DatePreset } from './presets';
3
+ export { reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund } from './adapters';
4
+ export type { StoreDay, DayRange, ReportCategory, ReportLine, ReportPayment, ReportTax, ReportOrder, ReportRefund, LineJoin } from './types';
5
+ export type { Margin, SalesTotals, PaymentRow, GroupRow, TaxRow, DayPoint, SalesFiguresInput, SalesFigures } from './sales-figures';
@@ -0,0 +1,27 @@
1
+ import { businessDayOf } from '../register/session-store';
2
+ import type { DayRange, StoreDay } from './types';
3
+
4
+ export type DatePreset = 'today' | 'yesterday' | 'thisWeek' | 'lastWeek' | 'thisMonth' | 'lastMonth';
5
+ export const DATE_PRESETS: readonly DatePreset[] = ['today', 'yesterday', 'thisWeek', 'lastWeek', 'thisMonth', 'lastMonth'];
6
+
7
+ const DAY_MS = 86_400_000;
8
+ const iso = (at: number): StoreDay => new Date(at).toISOString().slice(0, 10);
9
+
10
+ /**
11
+ * The preset's store days at `now` in `timezone` (IANA or 'device'). Weeks start Monday;
12
+ * this week and this month end today, as WCPOS v2's date button clamps a preset to today.
13
+ */
14
+ export function presetRange(preset: DatePreset, now: Date, timezone: string): DayRange {
15
+ const today = businessDayOf(now.toISOString(), timezone);
16
+ const [year, month, day] = today.split('-').map(Number);
17
+ const at = Date.UTC(year, month - 1, day);
18
+ const monday = at - ((new Date(at).getUTCDay() + 6) % 7) * DAY_MS;
19
+ switch (preset) {
20
+ case 'today': return { from: today, to: today };
21
+ case 'yesterday': return { from: iso(at - DAY_MS), to: iso(at - DAY_MS) };
22
+ case 'thisWeek': return { from: iso(monday), to: today };
23
+ case 'lastWeek': return { from: iso(monday - 7 * DAY_MS), to: iso(monday - DAY_MS) };
24
+ case 'thisMonth': return { from: iso(Date.UTC(year, month - 1, 1)), to: today };
25
+ case 'lastMonth': return { from: iso(Date.UTC(year, month - 2, 1)), to: iso(Date.UTC(year, month - 1, 0)) };
26
+ }
27
+ }
@@ -0,0 +1,173 @@
1
+ import { businessDayOf } from '../register/session-store';
2
+ import type { DayRange, ReportLine, ReportOrder, ReportRefund, StoreDay } from './types';
3
+
4
+ export interface Margin {
5
+ costedNetMinor: number;
6
+ costMinor: number;
7
+ profitMinor: number;
8
+ marginPct: number | null;
9
+ missingLines: number;
10
+ missingQuantity: number;
11
+ }
12
+ export interface SalesTotals {
13
+ grossMinor: number; netMinor: number; taxMinor: number; discountMinor: number;
14
+ refundsMinor: number; embeddedRefundsMinor: number;
15
+ orderCount: number; averageMinor: number; items: number;
16
+ margin: Margin;
17
+ }
18
+ export interface PaymentRow { method: string; label: string; amountMinor: number; orders: number }
19
+ export interface GroupRow { key: string; name: string; quantity: number; netMinor: number; margin: Margin }
20
+ export interface TaxRow { key: string; ratePpm: number; code?: string; label: string; taxMinor: number; netMinor: number | null }
21
+ export interface DayPoint { day: StoreDay; grossMinor: number; orderCount: number; refundsMinor: number }
22
+ export interface SalesFiguresInput {
23
+ orders: readonly ReportOrder[];
24
+ refunds?: readonly ReportRefund[];
25
+ range: DayRange;
26
+ compare?: DayRange;
27
+ /** IANA zone of the store, or 'device'. */
28
+ timezone: string;
29
+ }
30
+ export interface SalesFigures {
31
+ range: DayRange;
32
+ totals: SalesTotals;
33
+ payments: { rows: PaymentRow[]; takenMinor: number };
34
+ products: GroupRow[];
35
+ categories: GroupRow[];
36
+ taxes: TaxRow[];
37
+ refunds: { count: number; amountMinor: number; orders: number };
38
+ series: DayPoint[];
39
+ comparison?: { range: DayRange; totals: SalesTotals; series: DayPoint[] };
40
+ }
41
+
42
+ export function inRange(at: string, range: DayRange, timezone: string): boolean {
43
+ const day = businessDayOf(at, timezone);
44
+ return range.from <= day && day <= range.to;
45
+ }
46
+
47
+ export function daysOf(range: DayRange): StoreDay[] {
48
+ const [year, month, day] = range.from.split('-').map(Number);
49
+ const days: StoreDay[] = [];
50
+ for (let at = Date.UTC(year, month - 1, day); ; at += 86_400_000) {
51
+ const next = new Date(at).toISOString().slice(0, 10);
52
+ if (next > range.to) return days;
53
+ days.push(next);
54
+ }
55
+ }
56
+
57
+ export function comparisonRange(range: DayRange, mode: 'previous' | 'week'): DayRange {
58
+ const [year, month, day] = range.from.split('-').map(Number);
59
+ const from = Date.UTC(year, month - 1, day);
60
+ const [toYear, toMonth, toDay] = range.to.split('-').map(Number);
61
+ const to = Date.UTC(toYear, toMonth - 1, toDay);
62
+ if (mode === 'previous' && day === 1 && to === Date.UTC(year, month, 0)) {
63
+ return {
64
+ from: new Date(Date.UTC(year, month - 2, 1)).toISOString().slice(0, 10),
65
+ to: new Date(Date.UTC(year, month - 1, 0)).toISOString().slice(0, 10),
66
+ };
67
+ }
68
+ const shift = (mode === 'week' ? 7 : daysOf(range).length) * 86_400_000;
69
+ return { from: new Date(from - shift).toISOString().slice(0, 10), to: new Date(to - shift).toISOString().slice(0, 10) };
70
+ }
71
+
72
+ export function marginOf(lines: readonly ReportLine[]): Margin {
73
+ const margin: Margin = { costedNetMinor: 0, costMinor: 0, profitMinor: 0, marginPct: null, missingLines: 0, missingQuantity: 0 };
74
+ let costed = false;
75
+ for (const line of lines) {
76
+ if (typeof line.costMinor === 'number' && Number.isFinite(line.costMinor)) {
77
+ costed = true;
78
+ margin.costMinor += line.costMinor;
79
+ margin.costedNetMinor += line.netMinor;
80
+ } else {
81
+ margin.missingLines += 1;
82
+ margin.missingQuantity += Number.isFinite(line.quantity) ? Math.abs(line.quantity) : 0;
83
+ }
84
+ }
85
+ margin.profitMinor = margin.costedNetMinor - margin.costMinor;
86
+ margin.marginPct = costed && margin.costedNetMinor !== 0 ? margin.profitMinor / margin.costedNetMinor : null;
87
+ return margin;
88
+ }
89
+
90
+ function periodFigures(input: SalesFiguresInput, range: DayRange) {
91
+ const orders = input.orders.filter((order) => inRange(order.at, range, input.timezone));
92
+ const refunds = (input.refunds ?? []).filter((refund) => inRange(refund.at, range, input.timezone));
93
+ const lines = orders.flatMap((order) => order.lines);
94
+ const totals: SalesTotals = {
95
+ grossMinor: 0, netMinor: 0, taxMinor: 0, discountMinor: 0, refundsMinor: 0, embeddedRefundsMinor: 0,
96
+ orderCount: orders.length, averageMinor: 0,
97
+ items: lines.reduce((sum, line) => sum + (Number.isFinite(line.quantity) ? line.quantity : 0), 0),
98
+ margin: marginOf(lines),
99
+ };
100
+ const series: DayPoint[] = daysOf(range).map((day) => ({ day, grossMinor: 0, orderCount: 0, refundsMinor: 0 }));
101
+ const byDay = new Map(series.map((point) => [point.day, point]));
102
+ for (const order of orders) {
103
+ totals.grossMinor += order.totalMinor;
104
+ totals.taxMinor += order.taxMinor;
105
+ totals.discountMinor += order.discountMinor;
106
+ totals.embeddedRefundsMinor += order.refunds.reduce((sum, refund) => sum + Math.abs(refund.amountMinor), 0);
107
+ const point = byDay.get(businessDayOf(order.at, input.timezone))!;
108
+ point.grossMinor += order.totalMinor;
109
+ point.orderCount += 1;
110
+ }
111
+ for (const refund of refunds) {
112
+ totals.refundsMinor += Math.abs(refund.amountMinor);
113
+ byDay.get(businessDayOf(refund.at, input.timezone))!.refundsMinor += Math.abs(refund.amountMinor);
114
+ }
115
+ totals.netMinor = totals.grossMinor - totals.taxMinor;
116
+ totals.averageMinor = orders.length ? Math.round(totals.grossMinor / orders.length) : 0;
117
+ return { orders, refunds, totals, series };
118
+ }
119
+
120
+ export function salesFigures(input: SalesFiguresInput): SalesFigures {
121
+ const { orders, refunds, totals, series } = periodFigures(input, input.range);
122
+ const payments = new Map<string, PaymentRow>();
123
+ const products = new Map<string, { name: string; lines: ReportLine[] }>();
124
+ const categories = new Map<string, { name: string; lines: ReportLine[] }>();
125
+ const taxes = new Map<string, TaxRow>();
126
+ for (const order of orders) {
127
+ const contributions = [...order.payments];
128
+ const remainder = order.totalMinor - order.payments.reduce((sum, payment) => sum + payment.amountMinor, 0);
129
+ if (remainder > 0) contributions.push({ method: order.needsPayment ? 'unpaid' : 'unknown', amountMinor: remainder });
130
+ const methods = new Set<string>();
131
+ for (const payment of contributions) {
132
+ const row = payments.get(payment.method) ?? { method: payment.method, label: '', amountMinor: 0, orders: 0 };
133
+ row.amountMinor += payment.amountMinor;
134
+ if (!row.label && payment.label) row.label = payment.label;
135
+ if (!methods.has(payment.method)) row.orders += 1;
136
+ methods.add(payment.method);
137
+ payments.set(payment.method, row);
138
+ }
139
+ for (const line of order.lines) {
140
+ const product = products.get(line.key) ?? { name: line.name, lines: [] };
141
+ product.lines.push(line);
142
+ products.set(line.key, product);
143
+ const key = line.category?.id ?? '';
144
+ const category = categories.get(key) ?? { name: line.category?.name ?? '', lines: [] };
145
+ category.lines.push(line);
146
+ categories.set(key, category);
147
+ }
148
+ for (const tax of order.taxes) {
149
+ const key = JSON.stringify([tax.ratePpm, tax.code ?? tax.label]);
150
+ const row = taxes.get(key) ?? { ...tax, key, taxMinor: 0, netMinor: 0 };
151
+ row.taxMinor += tax.taxMinor;
152
+ row.netMinor = row.netMinor === null || tax.netMinor === null ? null : row.netMinor + tax.netMinor;
153
+ taxes.set(key, row);
154
+ }
155
+ }
156
+ const groups = [products, categories].map((group) => Array.from(group, ([key, { name, lines }]): GroupRow => ({
157
+ key, name, quantity: lines.reduce((sum, line) => sum + (Number.isFinite(line.quantity) ? line.quantity : 0), 0),
158
+ netMinor: lines.reduce((sum, line) => sum + line.netMinor, 0), margin: marginOf(lines),
159
+ })).sort((a, b) => b.netMinor - a.netMinor || b.quantity - a.quantity || a.name.localeCompare(b.name)));
160
+ const rows = [...payments.values()].sort((a, b) => b.amountMinor - a.amountMinor || a.method.localeCompare(b.method));
161
+ const result: SalesFigures = {
162
+ range: input.range, totals,
163
+ payments: { rows, takenMinor: rows.reduce((sum, row) => sum + (row.method === 'unpaid' ? 0 : row.amountMinor), 0) },
164
+ products: groups[0], categories: groups[1], taxes: [...taxes.values()].sort((a, b) => b.taxMinor - a.taxMinor),
165
+ refunds: { count: refunds.length, amountMinor: totals.refundsMinor, orders: new Set(refunds.map((refund) => refund.orderId)).size },
166
+ series,
167
+ };
168
+ if (input.compare) {
169
+ const comparison = periodFigures(input, input.compare);
170
+ result.comparison = { range: input.compare, totals: comparison.totals, series: comparison.series };
171
+ }
172
+ return result;
173
+ }
@@ -0,0 +1,63 @@
1
+ /** A store day, `yyyy-MM-dd` in the store's timezone. */
2
+ export type StoreDay = string;
3
+ /** Inclusive range of store days. */
4
+ export interface DayRange { from: StoreDay; to: StoreDay }
5
+
6
+ export interface ReportCategory { id: string; name: string }
7
+
8
+ export interface ReportLine {
9
+ /** Grouping identity: variant, else product, else name. */
10
+ key: string;
11
+ name: string;
12
+ quantity: number;
13
+ /** After discounts, excluding tax. */
14
+ netMinor: number;
15
+ taxMinor: number;
16
+ /** Cost of goods for the whole line (quantity × unit cost). Absent or null means the cost is missing, never 0. */
17
+ costMinor?: number | null;
18
+ /** The line's first category, when the caller joined one. */
19
+ category?: ReportCategory;
20
+ }
21
+
22
+ export interface ReportPayment { method: string; label?: string; amountMinor: number }
23
+
24
+ export interface ReportTax {
25
+ ratePpm: number;
26
+ code?: string;
27
+ label: string;
28
+ taxMinor: number;
29
+ /** The net this rate taxed; null when the source does not carry it. */
30
+ netMinor: number | null;
31
+ }
32
+
33
+ /** An order as the reports read it. Money in integer minor units. */
34
+ export interface ReportOrder {
35
+ id: string;
36
+ /** ISO 8601 UTC instant the sale was made. */
37
+ at: string;
38
+ /** Gross, including tax. */
39
+ totalMinor: number;
40
+ taxMinor: number;
41
+ discountMinor: number;
42
+ /** True when the order still owes money: its unpaid remainder is `unpaid`, not `unknown`. */
43
+ needsPayment?: boolean;
44
+ lines: ReportLine[];
45
+ payments: ReportPayment[];
46
+ taxes: ReportTax[];
47
+ /** Refunds embedded on the order, undated (a store order's own list). Positive. */
48
+ refunds: Array<{ id: string; amountMinor: number }>;
49
+ }
50
+
51
+ /** A refund dated by when it was made, counted on that store day. */
52
+ export interface ReportRefund {
53
+ id: string;
54
+ orderId: string;
55
+ /** ISO 8601 UTC instant the refund was made. */
56
+ at: string;
57
+ /** Positive. */
58
+ amountMinor: number;
59
+ }
60
+
61
+ /** The caller's product directory: a line's unit cost and first category. */
62
+ export type LineJoin = (line: { productId?: string; variantId?: string }) =>
63
+ { unitCostMinor?: number | null; category?: ReportCategory } | undefined;
package/src/sale/cart.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { resolvePrice, type ProductTraits } from '@tallyui/core';
2
2
  import type { OrderBuilder } from '../order';
3
- import { regularUnitPriceMinor } from '../order/order-builder';
3
+ import { regularUnitPriceMinor, samePicks } from '../order/order-builder';
4
4
  import type { CatalogueEntry } from './catalogue';
5
5
 
6
6
  export class CartError extends Error {}
@@ -8,7 +8,18 @@ export class CartError extends Error {}
8
8
  export function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry<Doc>,
9
9
  traits: ProductTraits<Doc>, currency: string): string {
10
10
  const { product, variant } = entry;
11
- const existing = builder.getSnapshot().lineItems.find((line) => line.variantId === variant.id);
11
+ const picks = entry.picks ?? {};
12
+ const groups = Object.keys(picks).length ? traits.getVariantOptions?.(product) ?? [] : [];
13
+ // Only a local group (no id) the variant leaves as "Any" can be picked, and only with one of its values (#495).
14
+ const position = (name: string) => groups.findIndex((group) => group.id === undefined && group.name === name);
15
+ for (const [name, value] of Object.entries(picks)) {
16
+ const group = groups[position(name)];
17
+ if (!group || Object.keys(variant.options ?? {}).includes(name)) throw new CartError(`${name} is not an option to choose for this item`);
18
+ if (typeof value !== 'string' || !value || !group.values.includes(value)) throw new CartError(`${value} is not a choice for ${name}`);
19
+ }
20
+ const anyAttributes = Object.keys(picks).sort((a, b) => position(a) - position(b));
21
+ const attributes = { ...variant.options, ...Object.fromEntries(anyAttributes.map((name) => [name, picks[name]])) };
22
+ const existing = builder.getSnapshot().lineItems.find((line) => line.variantId === variant.id && samePicks(line, { anyAttributes, attributes }));
12
23
  if (existing) {
13
24
  builder.updateQuantity(existing.id, existing.quantity + 1);
14
25
  return existing.id;
@@ -19,7 +30,8 @@ export function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry
19
30
  const unitPrice = resolved.current, regularPrice = regularUnitPriceMinor(resolved);
20
31
  return builder.addLine({
21
32
  productId: traits.getId(product), variantId: variant.id, name,
22
- ...(variant.options && Object.keys(variant.options).length ? { attributes: variant.options } : {}),
33
+ ...(Object.keys(attributes).length ? { attributes } : {}),
34
+ ...(anyAttributes.length ? { anyAttributes } : {}),
23
35
  sku: variant.sku ?? '', imageUrl: traits.getImageUrl?.(product), unitPrice,
24
36
  ...(regularPrice !== undefined ? { regularUnitPriceMinor: regularPrice } : {}),
25
37
  taxClass: traits.getTaxClass?.(product, variant.id),
@@ -1,7 +1,11 @@
1
1
  import { findVariantByCode, formatMoney, resolvePrice } from '@tallyui/core';
2
2
  import type { ProductTraits, TraitContext, VariantSummary } from '@tallyui/core';
3
3
 
4
- export type CatalogueEntry<Doc> = { product: Doc; variant: VariantSummary };
4
+ export type CatalogueEntry<Doc> = {
5
+ product: Doc; variant: VariantSummary;
6
+ /** The cashier's value for each of the variant's local "Any" option groups, group name to value (#495). */
7
+ picks?: Record<string, string>;
8
+ };
5
9
 
6
10
  /** Variants in product/variant order, passing context through; without getVariants,
7
11
  * simple products use their own traits and products with variants contribute no entries. */
package/src/sale/index.ts CHANGED
@@ -1,4 +1,6 @@
1
- export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, saleLogger } from './use-sale';
1
+ export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, saleLogger } from './use-sale';
2
+ export { openSales, isPartlyPaid } from './open-sales';
3
+ export type { OpenSale } from './open-sales';
2
4
  export type { SaleStage } from './use-sale';
3
5
  export { COUPONS_UNSUPPORTED } from './discount-codes';
4
6
  export type { SaleDiscountCodes, SaleDiscountState } from './discount-codes';
@@ -0,0 +1,40 @@
1
+ import type { Order, ParkedOrderSummary } from '../order';
2
+
3
+ /** One tab of the till's open sales: the current sale or a parked draft (v2 cart/tabs.tsx). */
4
+ export interface OpenSale {
5
+ id: string;
6
+ customerName?: string;
7
+ itemCount: number;
8
+ firstItem?: string;
9
+ totalMinor: number;
10
+ paidMinor: number;
11
+ balanceDueMinor: number;
12
+ /** The sale on the till now. */
13
+ current: boolean;
14
+ }
15
+
16
+ /** v2 cart/tab-chip.tsx: captured money and a balance still due. */
17
+ export function isPartlyPaid(sale: Pick<OpenSale, 'paidMinor' | 'balanceDueMinor'>): boolean {
18
+ return sale.paidMinor > 0 && sale.balanceDueMinor > 0;
19
+ }
20
+
21
+ /**
22
+ * The current sale (when it has lines, fees or shipping; a blank cart is no tab) and the parked drafts, in creation
23
+ * order: sorted by id with numeric collation, so a tab keeps its place across switches (a re-park changes
24
+ * `parkedAt`, never the id). A draft with the current sale's id is that sale and is skipped.
25
+ */
26
+ export function openSales(order: Order, parked: readonly ParkedOrderSummary[]): OpenSale[] {
27
+ const live = order.lineItems.length > 0 || !!order.fees?.length || !!order.shipping?.length;
28
+ const sales: OpenSale[] = parked.filter((draft) => draft.id !== order.id).map((draft) => ({
29
+ id: draft.id, customerName: draft.customerName, itemCount: draft.itemCount, firstItem: draft.firstItem,
30
+ totalMinor: draft.totalMinor, paidMinor: draft.paidMinor ?? 0, balanceDueMinor: draft.balanceDueMinor ?? 0, current: false,
31
+ }));
32
+ if (live) {
33
+ sales.push({
34
+ id: order.id, customerName: order.customer?.name || undefined, itemCount: order.lineItems.length,
35
+ firstItem: order.lineItems[0]?.name, totalMinor: order.totalMinor, paidMinor: order.paidMinor,
36
+ balanceDueMinor: order.balanceDueMinor, current: true,
37
+ });
38
+ }
39
+ return sales.sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }));
40
+ }
@@ -1,6 +1,8 @@
1
1
  import { useEffect, useLayoutEffect, useRef, useState } from 'react';
2
2
  import type { RxCollection } from 'rxdb';
3
3
  import type { ProductTraits, ServerCapabilities, StoreSettings } from '@tallyui/core';
4
+ import { paymentMethodOf } from '@tallyui/core';
5
+ import { canVoidLeg, capturedMinor, countsTowardPaid, inMotionMinor, isInMotion } from '../tender/payment-legs';
4
6
  import { createOrderBuilder, writeOrderDraft, restoreOrderDraft, type ChargeInput, type OrderBuilder, type CustomerSummary, type Discount, type Order, type SentOrder } from '../order';
5
7
  import { finalizeOrder, uuidv7, type PosOrder } from '../pos-order';
6
8
  import { MESSAGE_NAME_MAX, referenceError, referenceReason, withSentForm } from '../pos-order/finalize';
@@ -22,6 +24,14 @@ export type SaleStage = { kind: 'cart' } | { kind: 'tender'; method: 'cash' | 'e
22
24
  export const DISCOUNTS_UNSUPPORTED = 'finalize: discounts are not supported by the server yet (order.create v2)';
23
25
  /** Every sale change refuses with this while a completion is pending (see `complete()`). */
24
26
  export const SALE_SAVING = 'This sale is being saved. Retry to finish it.';
27
+ export const PAYMENT_IN_MOTION = 'Finish or void the payment in progress before completing the sale';
28
+ /**
29
+ * `switchSale()` and `closeSale()` refuse a sale whose legs took money (u19). v2 keeps a partly paid order's legs on
30
+ * switching, but a TallyUI draft keeps no tender stage, the next `startTender` replaces every leg, and `resume`
31
+ * re-checks coupons: so the sale stays on the till until it is paid or its paid legs are voided.
32
+ */
33
+ export const SALE_PARTLY_PAID = 'This sale is partly paid. Take the rest of the payment or void the paid legs first.';
34
+ export const SALE_IN_TENDER = 'Finish or cancel the payment before switching sales';
25
35
  /**
26
36
  * How often a hung save re-asks `isStored`, while the order is built and its save is still in flight
27
37
  * and unconfirmed: an app whose tender has no New sale control while saving (the Front desk,
@@ -144,7 +154,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
144
154
  appliedWith.current = null;
145
155
  setBuilder(next);
146
156
  setOrder(next.getSnapshot());
147
- setStage({ kind: 'cart' });
157
+ // Live at once, so a resume() in the same tick (switchSale) sees the cart before the next render.
158
+ stageNow.current = { kind: 'cart' };
159
+ setStage(stageNow.current);
148
160
  setError(null);
149
161
  }
150
162
  useEffect(() => {
@@ -170,13 +182,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
170
182
  }
171
183
  }, []);
172
184
 
173
- function addOne(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string }): string {
185
+ function addOne(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string; status?: 'pending' | 'authorized' | 'captured' }): string {
174
186
  // A terminal reference finalize would refuse is dropped as it's entered, never the payment (the money is
175
187
  // taken): the tender applies without it, with a message that doesn't block complete() and a
176
188
  // localWarnings entry on the stored order naming the payment whose reference was dropped.
177
189
  const reason = referenceReason(tender.reference);
178
190
  const dropped = reason && (reason === 'nul' ? 'it contains a NUL character' : `it is over ${PAYLOAD_STRING_MAX} characters`);
179
- const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor } : tender;
191
+ const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor, ...(tender.status !== undefined ? { status: tender.status } : {}) } : tender;
180
192
  const builder = builderNow.current;
181
193
  const paymentId = builder.addPayment(kept);
182
194
  if (dropped) {
@@ -405,6 +417,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
405
417
  applied.current.delete(normalized);
406
418
  return null;
407
419
  },
420
+ /** The sale's note, kept on the open sale (parked and resumed with it, cleared by newSale) and sent as order.create v7's note (ADR-083). */
421
+ setNote(note: string) { if (!locked()) builderNow.current.setNote(note); },
408
422
  /** the picked customer reaches the server as order.create v3's customer.customerId */
409
423
  setCustomer(customer: CustomerSummary | null) {
410
424
  if (locked()) return;
@@ -428,16 +442,31 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
428
442
  setStage({ kind: 'tender', method });
429
443
  },
430
444
  setTender,
431
- /** ADR-072: external is capped at the balance due; change comes only from cash. */
432
- addTender(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string }): string | null {
445
+ /** ADR-072: external is capped at the balance due; change comes only from cash. A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. */
446
+ addTender(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string; status?: 'pending' | 'authorized' | 'captured' }): string | null {
433
447
  if (locked() || !Number.isInteger(tender.amountMinor) || tender.amountMinor <= 0) return null;
448
+ if (tender.method === 'cash' && tender.status !== undefined && tender.status !== 'captured') return null;
434
449
  if (tender.method === 'external') {
435
- const due = builderNow.current.getSnapshot().balanceDueMinor;
450
+ const snapshot = builderNow.current.getSnapshot();
451
+ const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
436
452
  if (due <= 0) return null;
437
453
  return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
438
454
  }
439
455
  return addOne(tender);
440
456
  },
457
+ setTenderStatus(paymentId: string, status: 'authorized' | 'captured' | 'failed'): boolean {
458
+ if (locked()) return false;
459
+ return builderNow.current.setPaymentStatus(paymentId, status);
460
+ },
461
+ /** The leg stays in order.payments as voided and counts nothing; removeTender still removes a leg outright. */
462
+ voidTender(paymentId: string): boolean {
463
+ if (locked()) return false;
464
+ const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
465
+ if (!payment || (payment.method !== 'cash' && payment.method !== 'external') || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
466
+ builderNow.current.setPaymentStatus(paymentId, 'voided');
467
+ droppedReferences.current.delete(paymentId);
468
+ return true;
469
+ },
441
470
  /** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
442
471
  removeTender(paymentId: string): void {
443
472
  if (locked()) return;
@@ -471,7 +500,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
471
500
  confirm(null);
472
501
  if (pending.current) return deliver(pending.current);
473
502
  setSaving(true);
474
- const current = builderNow.current.getSnapshot();
503
+ const snapshot = builderNow.current.getSnapshot();
504
+ if (snapshot.payments.some(isInMotion)) { setSaving(false); setError(PAYMENT_IN_MOTION); return; }
505
+ // Failed and voided legs stay on the screen's ledger but are never sent: only captured money is the sale's.
506
+ const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid) };
475
507
  const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id))
476
508
  .map((payment) => ({ code: 'payment_reference_dropped' as const, paymentId: payment.id }));
477
509
  let posOrder: PosOrder;
@@ -553,7 +585,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
553
585
  if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That parked sale is in another currency';
554
586
  const builder = restoreOrderDraft(saved, { currency: settings.currency, taxContext });
555
587
  let n = 0;
556
- if (opts.currentPrice && !options?.keepParkedPrices) {
588
+ // A draft whose legs took money keeps the prices it was paid against (u19).
589
+ if (opts.currentPrice && !options?.keepParkedPrices && capturedMinor(saved.payments ?? []) === 0) {
557
590
  for (const line of builder.getSnapshot().lineItems) {
558
591
  if (!line.variantId) continue;
559
592
  const price = opts.currentPrice(line.variantId);
@@ -596,6 +629,37 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
596
629
  if (messages.length) setError(messages.join(' '));
597
630
  return null;
598
631
  },
632
+ /**
633
+ * Opens the parked draft `draftId`, or an empty sale for null (New), as a tab switch (u19, v2 cart/tabs.tsx):
634
+ * parks the current sale first when it has lines, fees or shipping (a receipt is done and is not parked).
635
+ * Refused, changing nothing, while saving, for a partly paid sale (SALE_PARTLY_PAID), a payment in motion or
636
+ * the tender stage. Resolves to a refusal (park's, or `resume`'s for the chosen draft), or null.
637
+ */
638
+ async switchSale(draftId: string | null): Promise<string | null> {
639
+ if (locked()) return SALE_SAVING;
640
+ if (!opts.drafts) throw new Error('useSale: switchSale() needs the drafts option');
641
+ const builder = builderNow.current;
642
+ const snapshot = builder.getSnapshot();
643
+ if (draftId === snapshot.id) return null;
644
+ if (capturedMinor(snapshot.payments) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
645
+ if (snapshot.payments.some(isInMotion)) return PAYMENT_IN_MOTION;
646
+ if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
647
+ if (stageNow.current.kind !== 'receipt' && (snapshot.lineItems.length || snapshot.fees?.length || snapshot.shipping?.length)) {
648
+ await writeOrderDraft(opts.drafts, snapshot);
649
+ if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
650
+ }
651
+ resetSale(null);
652
+ return draftId === null ? null : result.resume(draftId);
653
+ },
654
+ /** Discards the current sale (nothing is parked) and starts an empty one; refused while saving, once a leg of an unfinished sale took or holds money, or in the tender stage. */
655
+ closeSale(): string | null {
656
+ if (locked()) return SALE_SAVING;
657
+ const { payments } = builderNow.current.getSnapshot();
658
+ if (stageNow.current.kind !== 'receipt' && (capturedMinor(payments) > 0 || payments.some(isInMotion))) return SALE_PARTLY_PAID;
659
+ if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
660
+ resetSale(null);
661
+ return null;
662
+ },
599
663
  /**
600
664
  * Continue after a failed save whose order is confirmed stored (`canContinue`): exactly `newSale()`.
601
665
  * The order stays pending in the outbox, which will send it; it isn't handed to `onSaleCompleted` again, and
@@ -0,0 +1,6 @@
1
+ export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector } from './wedge-detector';
2
+ export type { WedgeSettings, WedgeState, TraceKey, WedgeReplayResult, WedgeDetectorOptions, WedgeDetector } from './wedge-detector';
3
+ export { DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession } from './scan-session';
4
+ export type { ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession } from './scan-session';
5
+ export { useBarcodeScanner } from './use-barcode-scanner';
6
+ export type { UseBarcodeScannerOptions } from './use-barcode-scanner';