@tallyui/pos 3.20.1 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1005 -110
- package/dist/index.js +3156 -907
- package/package.json +6 -6
- package/src/app-settings/app-settings.ts +77 -0
- package/src/app-settings/index.ts +2 -0
- package/src/currency/currency-provider.tsx +5 -7
- package/src/currency/index.ts +1 -1
- package/src/customer/customer-patch.ts +70 -0
- package/src/customer-display/display-client.ts +11 -17
- package/src/customer-display/display-link.ts +10 -5
- package/src/customer-display/index.ts +3 -1
- package/src/customer-display/protocol.ts +1 -1
- package/src/customer-display/sale-display.ts +6 -8
- package/src/customer-display/snapshot-fallback.ts +14 -1
- package/src/customer-display/till-device.ts +62 -0
- package/src/customer-display/till-display-service.ts +44 -42
- package/src/customer-display/till-pairing.ts +20 -23
- package/src/customer-display/use-customer-display.ts +2 -1
- package/src/customer-display/use-till-pairing.ts +4 -4
- package/src/index.ts +37 -18
- package/src/order/allocate-order-discount.ts +5 -17
- package/src/order/apportion.ts +29 -0
- package/src/order/from-store-order.ts +115 -0
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +239 -52
- package/src/order/order-drafts.ts +45 -6
- package/src/order/order-manager.ts +2 -1
- package/src/order/tax-ids.ts +27 -0
- package/src/order/types.ts +59 -5
- package/src/order/woocommerce-tax.ts +9 -0
- package/src/outbox/index.ts +1 -1
- package/src/outbox/order-outbox.ts +138 -43
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/retry-delay.ts +8 -0
- package/src/outbox/use-order-outbox.ts +8 -2
- package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
- package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
- package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
- package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
- package/src/pos-order/attention-handled.ts +24 -0
- package/src/pos-order/command.ts +132 -12
- package/src/pos-order/extras-delivery.ts +14 -0
- package/src/pos-order/finalize.ts +138 -29
- package/src/pos-order/index.ts +7 -3
- package/src/pos-order/money-divergence.ts +19 -0
- package/src/pos-order/needs-attention.ts +9 -1
- package/src/pos-order/refund-due.ts +35 -0
- package/src/pos-order/reopen.ts +96 -12
- package/src/pos-order/schema.ts +35 -10
- package/src/pos-order/till-payments.ts +4 -0
- package/src/pos-order/types.ts +44 -5
- package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
- package/src/print/escpos/commands.ts +79 -0
- package/src/print/escpos/drawer.ts +25 -0
- package/src/print/escpos/encode.ts +1 -0
- package/src/print/escpos/index.ts +6 -1
- package/src/print/escpos/network-sinks.ts +130 -0
- package/src/print/escpos/render-escpos.ts +155 -0
- package/src/print/escpos/transport.ts +2 -1
- package/src/print/index.ts +5 -2
- package/src/print/resolve-printer.ts +46 -0
- package/src/print/types.ts +1 -1
- package/src/product/index.ts +2 -0
- package/src/product/terms.ts +42 -0
- package/src/product/tile-fields.ts +27 -0
- package/src/receipt/build-receipt-data.ts +12 -7
- package/src/receipt/carried-rows.ts +29 -0
- package/src/receipt/index.ts +1 -0
- package/src/receipt/reprint.ts +14 -8
- package/src/receipt/types.ts +3 -1
- package/src/receipt-template/default-templates.ts +3 -0
- package/src/receipt-template/template-data.ts +3 -0
- package/src/receipt-template/wcpos/build.ts +1 -0
- package/src/receipt-template/wcpos/format.ts +2 -2
- package/src/receipt-template/wcpos/from-orders.ts +6 -2
- package/src/receipt-template/wcpos/types.ts +5 -1
- package/src/register/closure-document.ts +42 -4
- package/src/register/closure-rows.ts +3 -2
- package/src/register/document-labels.ts +25 -0
- package/src/register/expected.ts +49 -10
- package/src/register/index.ts +5 -5
- package/src/register/money.ts +23 -0
- package/src/register/register-adoption.ts +6 -5
- package/src/register/register-commands.ts +4 -3
- package/src/register/schemas.ts +11 -3
- package/src/register/session-store.ts +44 -23
- package/src/register/settled-figures.ts +5 -19
- package/src/register/use-register-session.ts +18 -19
- package/src/reopen/index.ts +3 -0
- package/src/reopen/reopen-entry.ts +48 -0
- package/src/reopen/reopen-store-order.ts +78 -0
- package/src/reopen/send-order-reopen.ts +61 -0
- package/src/reports/adapters.ts +15 -7
- package/src/reports/sales-figures.ts +15 -1
- package/src/reports/types.ts +2 -0
- package/src/sale/cart.ts +4 -2
- package/src/sale/index.ts +1 -1
- package/src/sale/open-sales.ts +3 -0
- package/src/sale/use-sale.ts +388 -83
- package/src/sale/woocommerce/coupon-refetch.ts +1 -0
- package/src/sale/woocommerce/coupon-source.ts +4 -4
- package/src/sale/woocommerce/coupons.ts +6 -0
- package/src/sale/woocommerce/discount-codes.ts +1 -6
- package/src/scanner/analyze-trace.ts +86 -0
- package/src/scanner/device-scanner.ts +57 -0
- package/src/scanner/hid-scanner.ts +14 -41
- package/src/scanner/index.ts +2 -0
- package/src/scanner/serial-scanner.ts +15 -42
- package/src/scanner/use-barcode-scanner.ts +107 -5
- package/src/scanner/wedge-detector.ts +33 -15
- package/src/tax/exact.ts +1 -13
- package/src/tax/taxed-lines.ts +26 -0
- package/src/tender/index.ts +6 -1
- package/src/tender/split-units.ts +109 -0
- package/src/tender/tender-figures.ts +114 -0
- package/src/tender/tender-state.ts +105 -17
- package/src/currency/format-money-with.ts +0 -45
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { minorUnitDigits, ORDER_NOTE_MAX, type CustomerAddress, type OrderAddress, type ServerCapabilities, type TaxRounding,
|
|
1
|
+
import { minorUnitDigits, ORDER_LINE_SKU_MAX, ORDER_META_KEY_MAX, ORDER_NOTE_MAX, ORDER_TAX_ID_TYPE_MAX, ORDER_TAX_ID_VALUE_MAX, type CustomerAddress, type OrderAddress, type ServerCapabilities, type TaxRounding,
|
|
2
2
|
type woocommerceTax } from '@tallyui/core';
|
|
3
|
-
import
|
|
3
|
+
import { chargeOrderModeMinor } from '../order/order-builder';
|
|
4
|
+
import { cleanTaxIds, TAX_IDS_INVALID } from '../order/tax-ids';
|
|
5
|
+
import type { ChargeLine, Order, SentOrder } from '../order/types';
|
|
4
6
|
import { legStatus } from '../tender/payment-legs';
|
|
5
7
|
import { DEFAULT_TAX_ROUNDING, taxLinesByRate } from '../tax/exact';
|
|
8
|
+
import { taxedLinesFor } from '../tax/taxed-lines';
|
|
6
9
|
import { outboxLogger } from '../outbox/logger';
|
|
7
|
-
import { cutText, PAYLOAD_STRING_MAX, sendable } from './command';
|
|
10
|
+
import { cutText, PAYLOAD_STRING_MAX, REVISION_MAX, sendable } from './command';
|
|
8
11
|
import type { PosOrder, PosOrderLocalWarning, PosOrderPayment } from './types';
|
|
9
12
|
import { uuidv7 } from './uuidv7';
|
|
10
13
|
|
|
@@ -19,8 +22,9 @@ export interface FinalizeOptions {
|
|
|
19
22
|
newId?: () => string;
|
|
20
23
|
/** The store's `order.create` capability (ADR-062); `undefined` is treated as 1. */
|
|
21
24
|
capabilities?: ServerCapabilities;
|
|
22
|
-
/** The address the sale's tax context matched (#722, `saleTaxContexts`). A customer's billing or shipping address
|
|
23
|
-
*
|
|
25
|
+
/** The address the sale's tax context matched (#722, `saleTaxContexts`). A customer's billing or shipping address stores
|
|
26
|
+
* `taxAddress`; the base, or absent, stores none. The customer's non-empty addresses are stored on every order, sent at
|
|
27
|
+
* order.create 8 with `taxAddress` and at 11 without it (ADR-086 d2, amended 2026-11-19). */
|
|
24
28
|
taxLocation?: woocommerceTax.ResolvedTaxLocation;
|
|
25
29
|
}
|
|
26
30
|
|
|
@@ -33,9 +37,30 @@ function orderAddress(address: CustomerAddress | undefined): OrderAddress | unde
|
|
|
33
37
|
return entries.length ? Object.fromEntries(entries) : undefined;
|
|
34
38
|
}
|
|
35
39
|
|
|
40
|
+
// Front desk 2026-11-21 (Q-B1): an after-close sale keeps the payments its closed session's closure counted.
|
|
41
|
+
export const AFTER_CLOSE_PAYMENTS_CHANGED = 'This sale was counted in a closed register. Its payments must stay as that closure counted them.';
|
|
42
|
+
|
|
43
|
+
type TaxedRow = { taxLines: ReadonlyArray<{ code?: string; ratePpm: number; taxMicros: string }> };
|
|
44
|
+
type Charge = Pick<ChargeLine, 'totalMinor' | 'taxLines'>;
|
|
45
|
+
/** The same tax lines, by index: code, rate and tax. */
|
|
46
|
+
export const sameTaxes = (a: TaxedRow, b: TaxedRow) => a.taxLines.length === b.taxLines.length
|
|
47
|
+
&& a.taxLines.every((tax, i) => tax.code === b.taxLines[i].code && tax.ratePpm === b.taxLines[i].ratePpm && tax.taxMicros === b.taxLines[i].taxMicros);
|
|
48
|
+
/** The same fee or shipping lines, by index: total and tax lines. */
|
|
49
|
+
export const sameCharges = (a: readonly Charge[] = [], b: readonly Charge[] = []) => a.length === b.length
|
|
50
|
+
&& a.every((charge, i) => charge.totalMinor === b[i].totalMinor && sameTaxes(charge, b[i]));
|
|
51
|
+
|
|
36
52
|
/** A line name in a refusal message: 60 UTF-16 units of it plus '…' at most, so a cashier-facing message stays short. */
|
|
37
53
|
export const MESSAGE_NAME_MAX = 61;
|
|
38
54
|
|
|
55
|
+
/** A charge as stored and sent: in the order's mode, without the cashier's own mode (vendurepos gap 2.10).
|
|
56
|
+
* A converted generic charge keeps its display row, so the payload equals the display (core fiscal-figures.ts). */
|
|
57
|
+
function storedCharge<C extends ChargeLine>(charge: C, pricesIncludeTax: boolean, displayMinor: number | undefined): C {
|
|
58
|
+
if (charge.amountIncludesTax === undefined && charge.percent === undefined) return charge;
|
|
59
|
+
const { amountIncludesTax: _mode, percent: _percent, ...rest } = charge;
|
|
60
|
+
const amountMinor = charge.totalMinor === undefined && displayMinor !== undefined ? displayMinor : chargeOrderModeMinor(charge, pricesIncludeTax);
|
|
61
|
+
return { ...rest, amountMinor, ...(charge.totalMinor === undefined ? { netMinor: amountMinor } : {}) } as C;
|
|
62
|
+
}
|
|
63
|
+
|
|
39
64
|
/** The receipt shows the order as it was stored and sent (Front desk, 2026-09-29). */
|
|
40
65
|
export function withSentForm(order: Order, posOrder: PosOrder): SentOrder {
|
|
41
66
|
const customer: SentOrder['customer'] = order.customer && { ...order.customer };
|
|
@@ -43,8 +68,9 @@ export function withSentForm(order: Order, posOrder: PosOrder): SentOrder {
|
|
|
43
68
|
if (customer && posOrder.customer?.id === undefined) delete customer.id;
|
|
44
69
|
return { ...order, customer, note: posOrder.note ?? order.note,
|
|
45
70
|
lineItems: order.lineItems.map((line, i) => ({ ...line, name: posOrder.lines[i].name })),
|
|
46
|
-
...(order.fees ? { fees: order.fees.map((fee, i) => ({ ...fee, name: posOrder.fees![i].name })) } : {}),
|
|
47
|
-
...(order.shipping ? { shipping: order.shipping.map((charge, i) => ({ ...charge,
|
|
71
|
+
...(order.fees ? { fees: order.fees.map((fee, i) => ({ ...storedCharge(fee, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor), name: posOrder.fees![i].name })) } : {}),
|
|
72
|
+
...(order.shipping ? { shipping: order.shipping.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor),
|
|
73
|
+
name: posOrder.shipping![i].name })) } : {}),
|
|
48
74
|
display: posOrder.display ? { ...order.display,
|
|
49
75
|
...(order.display.fees ? { fees: order.display.fees.map((row, i) => ({ ...row, name: posOrder.display!.fees![i].name })) } : {}),
|
|
50
76
|
...(order.display.shipping ? { shipping: order.display.shipping.map((row, i) => ({ ...row, name: posOrder.display!.shipping![i].name })) } : {}),
|
|
@@ -62,10 +88,12 @@ export function freezeSentForm(order: PosOrder): PosOrder {
|
|
|
62
88
|
changed ||= note !== order.note;
|
|
63
89
|
const lines = order.lines.map((line) => {
|
|
64
90
|
const name = cutText(line.name, PAYLOAD_STRING_MAX);
|
|
65
|
-
|
|
91
|
+
const sku = cutText(line.sku, ORDER_LINE_SKU_MAX);
|
|
92
|
+
const catalogueSku = line.catalogueSku === undefined ? undefined : cutText(line.catalogueSku, ORDER_LINE_SKU_MAX);
|
|
93
|
+
changed ||= name !== line.name || sku !== line.sku || catalogueSku !== line.catalogueSku;
|
|
66
94
|
const custom = line.custom && { ...line.custom, name: cutText(line.custom.name, PAYLOAD_STRING_MAX) };
|
|
67
95
|
changed ||= custom !== undefined && custom.name !== line.custom!.name;
|
|
68
|
-
return { ...line, name, ...(custom ? { custom } : {}) };
|
|
96
|
+
return { ...line, name, sku, ...(catalogueSku !== undefined ? { catalogueSku } : {}), ...(custom ? { custom } : {}) };
|
|
69
97
|
});
|
|
70
98
|
const charges = { fees: order.fees, shipping: order.shipping };
|
|
71
99
|
for (const field of ['fees', 'shipping'] as const) if (charges[field]) charges[field] = charges[field]!.map((charge) => {
|
|
@@ -98,6 +126,18 @@ export function freezeSentForm(order: PosOrder): PosOrder {
|
|
|
98
126
|
changed ||= Object.entries(address).some(([key, value]) => value !== customer[kind]![key as keyof OrderAddress]);
|
|
99
127
|
customer[kind] = address;
|
|
100
128
|
}
|
|
129
|
+
// Version 12 (ADR-092): tax ids and meta are cut to their bounds like the other text.
|
|
130
|
+
if (customer?.taxIds) customer.taxIds = customer.taxIds.map((taxId) => {
|
|
131
|
+
const cut = { ...taxId, type: cutText(taxId.type, ORDER_TAX_ID_TYPE_MAX), value: cutText(taxId.value, ORDER_TAX_ID_VALUE_MAX),
|
|
132
|
+
...(taxId.label !== undefined ? { label: cutText(taxId.label, PAYLOAD_STRING_MAX) } : {}) };
|
|
133
|
+
changed ||= cut.type !== taxId.type || cut.value !== taxId.value || cut.label !== taxId.label;
|
|
134
|
+
return cut;
|
|
135
|
+
});
|
|
136
|
+
const meta = order.meta?.map((entry) => {
|
|
137
|
+
const cut = { key: cutText(entry.key, ORDER_META_KEY_MAX), value: cutText(entry.value, ORDER_NOTE_MAX) };
|
|
138
|
+
changed ||= cut.key !== entry.key || cut.value !== entry.value;
|
|
139
|
+
return cut;
|
|
140
|
+
});
|
|
101
141
|
const localWarnings = [...(order.localWarnings ?? [])];
|
|
102
142
|
for (const [field, max] of [['email', 254], ['id', 64]] as const) {
|
|
103
143
|
if (customer && field in customer && !sendable(customer[field], max)) {
|
|
@@ -106,7 +146,7 @@ export function freezeSentForm(order: PosOrder): PosOrder {
|
|
|
106
146
|
}
|
|
107
147
|
}
|
|
108
148
|
return changed ? { ...order, lines, payments, customer, ...(note !== undefined ? { note } : {}), ...(charges.fees ? { fees: charges.fees } : {}),
|
|
109
|
-
...(charges.shipping ? { shipping: charges.shipping } : {}), ...(display ? { display } : {}), ...(localWarnings.length ? { localWarnings } : {}) } : order;
|
|
149
|
+
...(charges.shipping ? { shipping: charges.shipping } : {}), ...(display ? { display } : {}), ...(meta ? { meta } : {}), ...(localWarnings.length ? { localWarnings } : {}) } : order;
|
|
110
150
|
}
|
|
111
151
|
|
|
112
152
|
/**
|
|
@@ -127,19 +167,41 @@ export function referenceReason(value: string | undefined): 'long' | 'nul' | nul
|
|
|
127
167
|
return value.includes('\u0000') ? 'nul' : null;
|
|
128
168
|
}
|
|
129
169
|
|
|
170
|
+
/**
|
|
171
|
+
* True when an after-close order (one carrying `afterClose`) no longer matches what its closure counted; false without
|
|
172
|
+
* `afterClose`. It finalizes with the legs, fees, shipping and tax the closure counted, at the legs' sum, so it gives
|
|
173
|
+
* no change (a removed fee or shipping line would), and no new leg of the same amount finalizes uncounted.
|
|
174
|
+
*/
|
|
175
|
+
export function afterCloseChanged(order: Order): boolean {
|
|
176
|
+
const { afterClose } = order;
|
|
177
|
+
return !!afterClose && (order.payments.length !== afterClose.payments.length || order.payments.some((payment, i) =>
|
|
178
|
+
payment.id !== afterClose.payments[i].id
|
|
179
|
+
|| payment.method !== afterClose.payments[i].method || payment.amountMinor !== afterClose.payments[i].amountMinor)
|
|
180
|
+
|| order.totalMinor !== afterClose.payments.reduce((sum, payment) => sum + payment.amountMinor, 0)
|
|
181
|
+
|| order.taxMinor !== afterClose.taxMinor || !sameCharges(order.fees, afterClose.fees) || !sameCharges(order.shipping, afterClose.shipping));
|
|
182
|
+
}
|
|
183
|
+
|
|
130
184
|
/**
|
|
131
185
|
* Turns a fully paid builder Order into a pending PosOrder without mutating it. The PosOrder holds the sent form,
|
|
132
186
|
* frozen: line names and v3 discount labels are cut to PAYLOAD_STRING_MAX with NUL stripped (`cutText`), and a
|
|
133
187
|
* customer email or id the shape check would refuse is left out, so `toOrderCreateEnvelope` sends it unchanged.
|
|
134
188
|
*/
|
|
135
189
|
export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosOrder {
|
|
190
|
+
const { afterClose } = order;
|
|
191
|
+
if (afterCloseChanged(order)) throw new Error(AFTER_CLOSE_PAYMENTS_CHANGED);
|
|
192
|
+
// An after-close sale keeps its original register; the till finalizing it now is not where it was taken.
|
|
193
|
+
const registerId = afterClose ? afterClose.registerId : options.registerId;
|
|
136
194
|
if ((order.fees?.length || order.shipping?.length || order.lineItems.some((line) => line.custom))
|
|
137
195
|
&& (options.capabilities?.orderCreate ?? 1) < 5) {
|
|
138
196
|
throw new Error("finalize: fees, shipping and custom lines need the store to accept order.create version 5; update the store's TallyUI plugin");
|
|
139
197
|
}
|
|
140
|
-
if (order.
|
|
198
|
+
if (order.storeOrder && (options.capabilities?.orderCreate ?? 1) < 5) throw new Error("finalize: a reopened store order needs the store to accept order.create version 5; update the store's TallyUI plugin");
|
|
199
|
+
if (order.coupons?.some((coupon) => !coupon.carried) && (options.capabilities?.orderCreate ?? 1) < 6) {
|
|
141
200
|
throw new Error("finalize: coupons need the store to accept order.create version 6; update the store's TallyUI plugin");
|
|
142
201
|
}
|
|
202
|
+
if (order.coupons?.some((coupon) => coupon.carried) && (options.capabilities?.orderCreate ?? 1) < 4) {
|
|
203
|
+
throw new Error("finalize: a carried coupon needs the store to accept order.create version 4; update the store's TallyUI plugin");
|
|
204
|
+
}
|
|
143
205
|
if (order.couponPricesStale) {
|
|
144
206
|
throw new Error("finalize: the coupons' prices are out of date; price the coupons again before finalizing");
|
|
145
207
|
}
|
|
@@ -168,14 +230,41 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
168
230
|
}
|
|
169
231
|
if (legStatus(payment) !== 'captured') throw new Error(`finalize: the ${payment.method} payment is ${legStatus(payment)}, not captured`);
|
|
170
232
|
}
|
|
233
|
+
// A reopened sale's store ids (ADR-090 D7c5), checked before any id is minted: a dropped or bent id makes the store
|
|
234
|
+
// take a kept line or a captured payment as new. Gate 1 is core's id rule, gate 3 its uniqueness rule.
|
|
235
|
+
const reopened = order.storeOrder !== undefined;
|
|
236
|
+
const storeLineIds = [...order.lineItems, ...(order.fees ?? []), ...(order.shipping ?? [])]
|
|
237
|
+
.flatMap((item) => item.storeLineId !== undefined ? [item.storeLineId] : []);
|
|
238
|
+
const storePaymentIds = order.payments.flatMap((payment) => payment.storePaymentId !== undefined ? [payment.storePaymentId] : []);
|
|
239
|
+
if (!reopened && (storeLineIds.length || storePaymentIds.length || order.payments.some((payment) => payment.locked))) {
|
|
240
|
+
throw new Error('finalize: a store id on a sale that reopened no store order');
|
|
241
|
+
}
|
|
242
|
+
if (order.storeOrder && (![order.storeOrder.id, ...storeLineIds, ...storePaymentIds].every((value) => sendable(value, 64))
|
|
243
|
+
|| !sendable(order.storeOrder.revision, REVISION_MAX))) {
|
|
244
|
+
throw new Error('finalize: the reopened order carries a store id the store would refuse');
|
|
245
|
+
}
|
|
246
|
+
if (reopened && (new Set(storeLineIds).size !== storeLineIds.length || new Set(storePaymentIds).size !== storePaymentIds.length)) {
|
|
247
|
+
throw new Error('finalize: the reopened order carries a store id twice');
|
|
248
|
+
}
|
|
249
|
+
if (order.payments.some((payment) => (payment.storePaymentId !== undefined) !== (payment.locked === true)
|
|
250
|
+
|| (payment.locked && payment.method !== 'external'))) {
|
|
251
|
+
throw new Error('finalize: a payment the store already holds must be locked, external and carry its store id');
|
|
252
|
+
}
|
|
253
|
+
// Desk Q6: once the store's own legs cover the new total, the sale completes as refund-due and takes nothing here.
|
|
254
|
+
const lockedMinor = order.payments.reduce((sum, p) => sum + (p.locked ? p.amountMinor : 0), 0);
|
|
255
|
+
const heldByStore = reopened && lockedMinor >= order.totalMinor;
|
|
256
|
+
if (heldByStore && order.payments.some((p) => !p.locked)) {
|
|
257
|
+
throw new Error('finalize: the store already holds the new total; remove the payments taken here');
|
|
258
|
+
}
|
|
259
|
+
const refundDue = heldByStore ? lockedMinor - order.totalMinor : 0;
|
|
171
260
|
if (order.paidMinor < order.totalMinor) throw new Error('finalize: underpaid');
|
|
172
|
-
let change = order.paidMinor - order.totalMinor;
|
|
173
|
-
const cash = order.payments.reduce((sum, p) => sum + (p.method === 'cash' ? p.amountMinor : 0), 0);
|
|
261
|
+
let change = heldByStore ? 0 : order.paidMinor - order.totalMinor;
|
|
262
|
+
const cash = order.payments.reduce((sum, p) => sum + (p.method === 'cash' && !p.locked && p.tenderedMinor === undefined ? p.amountMinor : 0), 0);
|
|
174
263
|
if (change > cash) throw new Error('finalize: change exceeds cash');
|
|
175
264
|
// Refused before any id is minted, so such a value never reaches the stored order or the outbox.
|
|
176
265
|
// v3 also sends each line discount's id and each tax code (as taxByRate's codes); an id is never clamped.
|
|
177
266
|
const v3 = (options.capabilities?.orderCreate ?? 1) >= 3;
|
|
178
|
-
const references: Array<[string, string | undefined]> = [['registerId',
|
|
267
|
+
const references: Array<[string, string | undefined]> = [['registerId', registerId], ['cashierRef', options.cashierRef],
|
|
179
268
|
...order.lineItems.flatMap((line, i): Array<[string, string | undefined]> => {
|
|
180
269
|
const name = `"${cutText(line.name, MESSAGE_NAME_MAX)}"`;
|
|
181
270
|
return [line.variantId !== undefined ? [`${name}: the variant id`, line.variantId] : [`${name}: the product id`, line.productId],
|
|
@@ -190,12 +279,13 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
190
279
|
const newId = options.newId ?? uuidv7;
|
|
191
280
|
const id = newId();
|
|
192
281
|
const lines: PosOrder['lines'] = order.lineItems.map((line) => ({
|
|
193
|
-
id: newId(), productId: line.productId,
|
|
282
|
+
id: newId(), ...(line.storeLineId !== undefined ? { storeLineId: line.storeLineId } : {}), productId: line.productId,
|
|
194
283
|
...(line.variantId !== undefined ? { variantId: line.variantId } : {}),
|
|
195
284
|
...(line.custom ? { custom: { name: line.name, ...(line.sku ? { sku: line.sku } : {}),
|
|
196
285
|
...(line.taxClass !== undefined ? { taxClass: line.taxClass } : {}), taxStatus: line.taxStatus ?? 'taxable' } } : {}),
|
|
197
286
|
...(line.taxStatus !== undefined ? { taxStatus: line.taxStatus } : {}),
|
|
198
|
-
name: line.name, sku: line.sku,
|
|
287
|
+
name: line.name, sku: line.sku, ...(line.catalogueSku !== undefined && !line.custom ? { catalogueSku: line.catalogueSku } : {}),
|
|
288
|
+
quantity: line.quantity, unitPriceMinor: line.unitPriceMinor,
|
|
199
289
|
...(line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}),
|
|
200
290
|
...(line.anyAttributes?.length ? { anyAttributes: [...line.anyAttributes] } : {}),
|
|
201
291
|
...(line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
|
|
@@ -204,10 +294,15 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
204
294
|
taxLines: line.taxLines.map((tax) => ({ ...tax })),
|
|
205
295
|
...(line.priceTaxModeConverted ? { taxInclusive: line.taxInclusive } : {}),
|
|
206
296
|
}));
|
|
207
|
-
const fees = order.fees?.map((charge) => ({ ...charge, id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
|
|
208
|
-
const shipping = order.shipping?.map((charge) => ({ ...charge, id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
|
|
297
|
+
const fees = order.fees?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.fees?.[i]?.amountMinor), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
|
|
298
|
+
const shipping = order.shipping?.map((charge, i) => ({ ...storedCharge(charge, order.pricesIncludeTax, order.display.shipping?.[i]?.amountMinor), id: newId(), taxLines: charge.taxLines.map((tax) => ({ ...tax })) }));
|
|
209
299
|
const payments: PosOrderPayment[] = order.payments.map((payment) => ({
|
|
210
|
-
id: newId(),
|
|
300
|
+
id: newId(), ...(payment.storePaymentId !== undefined ? { storePaymentId: payment.storePaymentId } : {}),
|
|
301
|
+
method: payment.method as PosOrderPayment['method'],
|
|
302
|
+
...(payment.methodId !== undefined && sendable(payment.methodId, 64) ? { methodId: payment.methodId } : {}),
|
|
303
|
+
amountMinor: payment.amountMinor,
|
|
304
|
+
...(payment.tenderedMinor !== undefined ? { tenderedMinor: payment.tenderedMinor } : {}),
|
|
305
|
+
...(payment.changeMinor !== undefined ? { changeMinor: payment.changeMinor } : {}),
|
|
211
306
|
...(payment.reference !== undefined ? { reference: payment.reference } : {}),
|
|
212
307
|
}));
|
|
213
308
|
// A warning naming a payment the order no longer has is dropped and logged, never thrown: this runs at sale completion.
|
|
@@ -224,13 +319,14 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
224
319
|
});
|
|
225
320
|
for (let i = payments.length - 1; i >= 0; i--) {
|
|
226
321
|
const payment = payments[i];
|
|
227
|
-
if (payment.method !== 'cash') continue;
|
|
322
|
+
if (payment.method !== 'cash' || order.payments[i].tenderedMinor !== undefined) continue;
|
|
228
323
|
payment.tenderedMinor = payment.amountMinor;
|
|
229
324
|
payment.changeMinor = Math.min(change, payment.tenderedMinor);
|
|
230
325
|
payment.amountMinor -= payment.changeMinor;
|
|
231
326
|
change -= payment.changeMinor;
|
|
232
327
|
}
|
|
233
|
-
|
|
328
|
+
// A reopened sale's refund due is the locked legs beyond the new total (desk Q4); a till sale's is 0.
|
|
329
|
+
if (payments.reduce((sum, p) => sum + p.amountMinor, 0) - refundDue !== order.totalMinor) {
|
|
234
330
|
throw new Error('finalize: payments do not reconcile');
|
|
235
331
|
}
|
|
236
332
|
let display: PosOrder['display'];
|
|
@@ -250,8 +346,7 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
250
346
|
})),
|
|
251
347
|
})),
|
|
252
348
|
};
|
|
253
|
-
const taxedLines =
|
|
254
|
-
.map((charge) => ({ ...charge, taxInclusive: order.pricesIncludeTax }))];
|
|
349
|
+
const taxedLines = taxedLinesFor(order.lineItems, [...(order.fees ?? []), ...(order.shipping ?? [])], order.pricesIncludeTax, order.taxRounding);
|
|
255
350
|
taxByRate = taxLinesByRate(taxedLines, order.taxMinor, undefined, order.taxRounding).map(({ ratePpm, code, netMinor, amountMinor }) => ({
|
|
256
351
|
ratePpm, ...(code !== undefined ? { code } : {}), netMinor, amountMinor, grossMinor: netMinor + amountMinor,
|
|
257
352
|
}));
|
|
@@ -273,23 +368,37 @@ export function finalizeOrder(order: Order, options: FinalizeOptions = {}): PosO
|
|
|
273
368
|
const taxAddress = used === 'billing' || used === 'shipping' ? used : undefined;
|
|
274
369
|
const addresses = { billing: orderAddress(order.customer?.billing), shipping: orderAddress(order.customer?.shipping) };
|
|
275
370
|
if (taxAddress && !addresses[taxAddress]?.country) throw new Error(`finalize: the sale was taxed on the customer's ${taxAddress} address, which it does not have`);
|
|
371
|
+
// #1064: the backstop for a list no setter checked; the stored list is always a clean copy.
|
|
372
|
+
const taxIds = order.customer?.taxIds && cleanTaxIds(order.customer.taxIds);
|
|
373
|
+
if (taxIds === null) throw new Error(TAX_IDS_INVALID);
|
|
276
374
|
const now = (options.now ?? new Date()).toISOString();
|
|
277
375
|
return freezeSentForm({
|
|
278
|
-
id, saleId: order.id, createdAt: now, updatedAt: now, commandId: newId(), syncStatus: 'pending',
|
|
376
|
+
id, saleId: order.id, createdAt: afterClose?.createdAt ?? now, updatedAt: now, commandId: newId(), syncStatus: 'pending',
|
|
279
377
|
currency: order.currency, pricesIncludeTax: order.pricesIncludeTax, lines, payments,
|
|
280
378
|
...(fees?.length ? { fees } : {}), ...(shipping?.length ? { shipping } : {}),
|
|
281
379
|
subtotalMinor: order.subtotalMinor, discountMinor: order.discountMinor,
|
|
282
380
|
taxMinor: order.taxMinor, totalMinor: order.totalMinor, taxRounding,
|
|
283
|
-
...(order.
|
|
284
|
-
|
|
381
|
+
...(order.storeOrder ? { storeOrderId: order.storeOrder.id, baseRevision: order.storeOrder.revision, refundDueMinor: refundDue } : {}),
|
|
382
|
+
...(order.coupons?.length ? { coupons: order.coupons.map((coupon) => ({
|
|
383
|
+
code: coupon.code, couponId: coupon.couponId, discountMinor: coupon.discountMinor, discountTaxMinor: coupon.discountTaxMinor,
|
|
384
|
+
...(coupon.carried ? { carried: true as const } : {}),
|
|
385
|
+
...(coupon.lines !== undefined ? { lines: coupon.lines.map(({ lineId, discountMinor, discountTaxMinor, amountMinor }) => {
|
|
386
|
+
const index = order.lineItems.findIndex((line) => line.id === lineId);
|
|
387
|
+
if (index === -1) throw new Error("finalize: a coupon's line share names no line on the order");
|
|
388
|
+
return { lineId: lines[index].id, discountMinor, discountTaxMinor, ...(amountMinor !== undefined ? { amountMinor } : {}) };
|
|
389
|
+
}) } : {}),
|
|
390
|
+
})) } : {}),
|
|
285
391
|
...(display && taxByRate ? { display, taxByRate } : {}),
|
|
286
392
|
customer: order.customer ? { id: order.customer.id, name: order.customer.name,
|
|
287
393
|
...(order.customer.email !== undefined ? { email: order.customer.email } : {}),
|
|
288
|
-
...(
|
|
289
|
-
...(
|
|
394
|
+
...(addresses.billing ? { billing: addresses.billing } : {}),
|
|
395
|
+
...(addresses.shipping ? { shipping: addresses.shipping } : {}),
|
|
396
|
+
...(taxIds?.length ? { taxIds } : {}) } : null,
|
|
290
397
|
...(order.note ? { note: order.note } : {}),
|
|
398
|
+
...(order.meta?.length ? { meta: order.meta.map((m) => ({ ...m })) } : {}),
|
|
291
399
|
...(taxAddress ? { taxAddress } : {}),
|
|
292
|
-
...(
|
|
400
|
+
...(registerId !== undefined ? { registerId } : {}),
|
|
401
|
+
...(afterClose ? { countedInClosureOf: afterClose.sessionId } : {}),
|
|
293
402
|
...(options.cashierRef !== undefined ? { cashierRef: options.cashierRef } : {}),
|
|
294
403
|
...(localWarnings?.length ? { localWarnings } : {}),
|
|
295
404
|
});
|
package/src/pos-order/index.ts
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder } from './types';
|
|
2
2
|
export { uuidv7 } from './uuidv7';
|
|
3
|
-
export { finalizeOrder } from './finalize';
|
|
3
|
+
export { AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder } from './finalize';
|
|
4
4
|
export type { FinalizeOptions } from './finalize';
|
|
5
|
-
export { toOrderCreateEnvelope, UnsupportedOrderVersionError } from './command';
|
|
5
|
+
export { toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError } from './command';
|
|
6
6
|
export { posOrderSchema, posOrderCollection } from './schema';
|
|
7
7
|
export { addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger } from './open';
|
|
8
8
|
export { getDeviceId } from './device-id';
|
|
9
|
-
export { needsAttention } from './needs-attention';
|
|
9
|
+
export { needsAttention, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE } from './needs-attention';
|
|
10
|
+
export { markAttentionHandled } from './attention-handled';
|
|
11
|
+
export { moneyDivergence, type MoneyDivergence } from './money-divergence';
|
|
10
12
|
export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './reopen';
|
|
11
13
|
export { isReopened, replacedOrderIds } from './reopened';
|
|
12
14
|
export { noteDelivery, type NoteDelivery } from './note-delivery';
|
|
15
|
+
export { extrasNotSent, type ExtrasNotSent } from './extras-delivery';
|
|
13
16
|
export { sameSale, OrderContentMismatchError } from './same-sale';
|
|
17
|
+
export { refundDueOf } from './refund-due';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { knownWarnings } from '@tallyui/core';
|
|
2
|
+
import type { PosOrder } from './types';
|
|
3
|
+
|
|
4
|
+
/** What the store computed differently on a sale, for a cashier's notice: the order figures (`figures_mismatch`) and
|
|
5
|
+
* the lines (`line_figures_mismatch`, distinct `lineId`s in first-seen order). null when neither warning is known. */
|
|
6
|
+
export interface MoneyDivergence { orderFields: string[]; lineIds: string[] }
|
|
7
|
+
|
|
8
|
+
export function moneyDivergence(order: Pick<PosOrder, 'warnings'>): MoneyDivergence | null {
|
|
9
|
+
const orderFields: string[] = [];
|
|
10
|
+
const lineIds: string[] = [];
|
|
11
|
+
for (const warning of knownWarnings(order.warnings)) {
|
|
12
|
+
if (warning.code === 'figures_mismatch') {
|
|
13
|
+
for (const { field } of warning.fields) if (!orderFields.includes(field)) orderFields.push(field);
|
|
14
|
+
} else if (warning.code === 'line_figures_mismatch') {
|
|
15
|
+
for (const { lineId } of warning.lines) if (!lineIds.includes(lineId)) lineIds.push(lineId);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return orderFields.length === 0 && lineIds.length === 0 ? null : { orderFields, lineIds };
|
|
19
|
+
}
|
|
@@ -2,6 +2,10 @@ import { knownWarnings } from '@tallyui/core';
|
|
|
2
2
|
import { replacedOrderIds } from './reopened';
|
|
3
3
|
import type { PosOrder } from './types';
|
|
4
4
|
|
|
5
|
+
/** The `error.code` the outbox puts on a pending reopened sale whose `order.update` it cannot build (ADR-090 W4b). The row stays pending: unsent. */
|
|
6
|
+
export const UPDATE_UNSENDABLE = 'update_unsendable';
|
|
7
|
+
export const UPDATE_UNSENDABLE_MESSAGE = "The store can't accept this change yet. Ask the owner to update the POS plugin, then press Retry.";
|
|
8
|
+
|
|
5
9
|
/**
|
|
6
10
|
* The orders a cashier must look at: rejected, applied with a known warning, taken after their
|
|
7
11
|
* session closed (`lateSessionId`) or with local warnings (whatever the sync status), or pending with a `commandId` in
|
|
@@ -9,13 +13,17 @@ import type { PosOrder } from './types';
|
|
|
9
13
|
* A warning code this till version doesn't know is not shown here (`knownWarnings`). Never changes `orders`.
|
|
10
14
|
* `register_session_unknown` is not shown, because the store counts the order once its session arrives (ADR-078).
|
|
11
15
|
* A refused order is left out once its finalized successor is in `orders`.
|
|
16
|
+
* Pending updates marked `UPDATE_UNSENDABLE` are shown until a person acts.
|
|
17
|
+
* An order a cashier marked handled (`markAttentionHandled`) is left out while its `commandId` is the one it was marked
|
|
18
|
+
* for; a requeue mints a new `commandId`, so a fresh refusal shows again (ADR-092 6f).
|
|
12
19
|
*/
|
|
13
20
|
export function needsAttention(orders: PosOrder[], options: { stuckCommandIds?: readonly string[] } = {}): PosOrder[] {
|
|
14
21
|
const replaced = replacedOrderIds(orders);
|
|
15
22
|
return orders.filter((order) => order.syncStatus === 'rejected'
|
|
23
|
+
|| (order.syncStatus === 'pending' && order.error?.code === UPDATE_UNSENDABLE)
|
|
16
24
|
|| (order.localWarnings?.length ?? 0) > 0
|
|
17
25
|
|| (order.syncStatus === 'applied' && knownWarnings(order.warnings).some((warning) => warning.code !== 'register_session_unknown')) || order.lateSessionId !== undefined
|
|
18
26
|
|| (order.syncStatus === 'pending' && options.stuckCommandIds?.includes(order.commandId) === true))
|
|
19
|
-
.filter((order) => !replaced.has(order.id))
|
|
27
|
+
.filter((order) => !replaced.has(order.id) && !(order.attentionHandledFor !== undefined && order.attentionHandledFor === order.commandId))
|
|
20
28
|
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
21
29
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Payment } from '../order/types';
|
|
2
|
+
import { countsTowardPaid } from '../tender/payment-legs';
|
|
3
|
+
import type { PosOrder } from './types';
|
|
4
|
+
|
|
5
|
+
const sum = (amounts: number[]) => amounts.reduce((total, amount) => total + amount, 0);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* What the store owes back on a stored sale (ADR-090, desk Q4 2026-11-17): the stored `refundDueMinor`, which
|
|
9
|
+
* `finalizeOrder` writes on every reopened sale (0 when nothing is due); a till sale and a row stored before v15 have
|
|
10
|
+
* none, and for those `sum(payments) − total`, never below 0, gives 0 because a till sale's cash leg is capped at the balance.
|
|
11
|
+
*/
|
|
12
|
+
export function refundDueOf(order: Pick<PosOrder, 'refundDueMinor' | 'payments' | 'totalMinor'>): number {
|
|
13
|
+
return order.refundDueMinor ?? Math.max(0, sum(order.payments.map((payment) => payment.amountMinor)) - order.totalMinor);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The same figure for a sale still in the builder: the locked legs (the store's own, ADR-090) beyond the new total.
|
|
18
|
+
* Unlocked legs never count, so a cashier's cash overpayment stays change.
|
|
19
|
+
*/
|
|
20
|
+
export function lockedRefundDueMinor(order: { payments: readonly Pick<Payment, 'locked' | 'amountMinor'>[]; totalMinor: number }): number {
|
|
21
|
+
return Math.max(0, sum(order.payments.filter((payment) => payment.locked).map((payment) => payment.amountMinor)) - order.totalMinor);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The till legs a reopened sale may not keep (ADR-090 gate 36c): once the store's locked legs cover the total, every
|
|
26
|
+
* unlocked payment is refused. Mirrors finalizeOrder's desk Q6 check (finalize.ts:193-197), so the pane can name and
|
|
27
|
+
* remove them before Complete instead of after it throws. It judges only captured legs, the ones useSale's complete
|
|
28
|
+
* passes to finalizeOrder (use-sale.ts:713), so a voided or failed till leg is never named.
|
|
29
|
+
*/
|
|
30
|
+
export function tillLegsTheStoreRefuses(order: { storeOrder?: unknown; totalMinor: number; payments: readonly Pick<Payment, 'id' | 'locked' | 'amountMinor' | 'status'>[] }): string[] {
|
|
31
|
+
if (order.storeOrder === undefined) return [];
|
|
32
|
+
const captured = order.payments.filter(countsTowardPaid);
|
|
33
|
+
const lockedMinor = sum(captured.filter((payment) => payment.locked).map((payment) => payment.amountMinor));
|
|
34
|
+
return lockedMinor >= order.totalMinor ? captured.filter((payment) => !payment.locked).map((payment) => payment.id) : [];
|
|
35
|
+
}
|
package/src/pos-order/reopen.ts
CHANGED
|
@@ -1,21 +1,40 @@
|
|
|
1
|
+
import type { ServerCapabilities } from '@tallyui/core';
|
|
1
2
|
import type { RxCollection } from 'rxdb';
|
|
2
|
-
import { createOrderBuilder } from '../order/order-builder';
|
|
3
|
+
import { couponPricingBasis, createOrderBuilder, type StorePricedCoupon } from '../order/order-builder';
|
|
3
4
|
import { writeOrderDraft } from '../order/order-drafts';
|
|
4
|
-
import {
|
|
5
|
+
import type { Order } from '../order/types';
|
|
6
|
+
import { readSession, type ClosureCollection, type RegisterSessionCollection } from '../register/session-store';
|
|
5
7
|
import { readFresh } from '../rxdb';
|
|
6
8
|
import type { TaxContext } from '../tax/types';
|
|
7
9
|
import { customerRefusal } from './command';
|
|
10
|
+
import { sameCharges, sameTaxes } from './finalize';
|
|
8
11
|
import type { PosOrder } from './types';
|
|
9
12
|
|
|
10
13
|
export const REOPENABLE_CODES: readonly string[] = ['coupon_invalid', 'total_mismatch'];
|
|
11
|
-
export type ReopenRefusal = 'not_found' | 'not_rejected' | 'code_not_reopenable' | 'already_replaced' | 'session_closed'
|
|
14
|
+
export type ReopenRefusal = 'not_found' | 'store_order' | 'not_rejected' | 'code_not_reopenable' | 'already_replaced' | 'session_closed'
|
|
15
|
+
| 'coupon_carry_inexact' | 'carried_draft_exists';
|
|
12
16
|
export class ReopenRefusedOrderError extends Error {
|
|
13
|
-
constructor(readonly orderId: string, readonly reason: ReopenRefusal) {
|
|
17
|
+
constructor(readonly orderId: string, readonly reason: ReopenRefusal, readonly toCollectMinor?: number) {
|
|
14
18
|
super(`Cannot reopen order ${orderId}: ${reason}`);
|
|
15
19
|
this.name = 'ReopenRefusedOrderError';
|
|
16
20
|
}
|
|
17
21
|
}
|
|
18
22
|
|
|
23
|
+
/** The carried draft has the stored order's figures exactly: every line, fee and shipping line, its total and its tax. */
|
|
24
|
+
function sameFigures(draft: Order, order: PosOrder): boolean {
|
|
25
|
+
return draft.couponPricesStale !== true && draft.lineItems.length === order.lines.length
|
|
26
|
+
&& draft.lineItems.every((line, i) => line.netMinor === order.lines[i].netMinor
|
|
27
|
+
&& (order.lines[i].netMicros === undefined || line.netMicros === order.lines[i].netMicros) && sameTaxes(line, order.lines[i]))
|
|
28
|
+
&& sameCharges(draft.fees, order.fees) && sameCharges(draft.shipping, order.shipping)
|
|
29
|
+
&& draft.totalMinor === order.totalMinor && draft.taxMinor === order.taxMinor;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Reopens a refused sale as a draft; a coupon sale reopens with its coupons carried at the amounts the store charged.
|
|
34
|
+
* When that carry is not exact it refuses `coupon_carry_inexact`, with `toCollectMinor` the amount still to collect without them.
|
|
35
|
+
* `{ withoutCoupons: true }` is the explicit drop: the sale reopens without its coupons and the cashier collects the difference.
|
|
36
|
+
* It refuses `carried_draft_exists` when the parked draft already carries a coupon, rather than return that draft.
|
|
37
|
+
*/
|
|
19
38
|
export async function reopenRefusedOrder(orderId: string, deps: {
|
|
20
39
|
orders: RxCollection<PosOrder>;
|
|
21
40
|
drafts: RxCollection;
|
|
@@ -24,24 +43,50 @@ export async function reopenRefusedOrder(orderId: string, deps: {
|
|
|
24
43
|
/** The product's tax class from the catalogue (ProductTraits.getTaxClass); undefined falls back to 'standard'. */
|
|
25
44
|
taxClassOf?: (productId: string, variantId?: string) => string | undefined;
|
|
26
45
|
now?: () => Date;
|
|
27
|
-
|
|
46
|
+
/** The store's capabilities: a coupon carry needs `orderCreate` 4 or more; absent counts as 1, as in finalize. */
|
|
47
|
+
capabilities?: ServerCapabilities;
|
|
48
|
+
/** The frozen closures: a carried sale whose closed session's closure lists it reopens after close (ADR-077, Front desk 2026-11-21). */
|
|
49
|
+
closures?: ClosureCollection;
|
|
50
|
+
}, options?: { withoutCoupons?: true }): Promise<string> {
|
|
28
51
|
const [order] = await readFresh(deps.orders, { selector: { id: orderId } });
|
|
29
52
|
if (!order) throw new ReopenRefusedOrderError(orderId, 'not_found');
|
|
53
|
+
// A reopened store order returns as order.update; a redo would send order.create without its store ids (ADR-090 gate 6).
|
|
54
|
+
if (order.storeOrderId !== undefined) throw new ReopenRefusedOrderError(orderId, 'store_order');
|
|
30
55
|
if (order.syncStatus !== 'rejected') throw new ReopenRefusedOrderError(orderId, 'not_rejected');
|
|
31
56
|
if (!REOPENABLE_CODES.includes(order.error?.code ?? '')) throw new ReopenRefusedOrderError(orderId, 'code_not_reopenable');
|
|
32
57
|
const successors = await readFresh(deps.orders, { selector: { saleId: orderId } });
|
|
33
58
|
if (successors.some((successor) => successor.id !== orderId)) throw new ReopenRefusedOrderError(orderId, 'already_replaced');
|
|
59
|
+
// A successor already counted in a frozen closure: a manager settles it in Needs attention (ADR-077).
|
|
60
|
+
if (order.countedInClosureOf !== undefined) throw new ReopenRefusedOrderError(orderId, 'session_closed');
|
|
61
|
+
let afterClose: Order['afterClose'];
|
|
34
62
|
if (order.sessionId) {
|
|
35
63
|
const session = await readSession(deps.sessions, order.sessionId);
|
|
36
|
-
|
|
64
|
+
// Its closure counted this sale's money: only the exact carry may re-send it, outside every session.
|
|
65
|
+
const counted = session?.status === 'closed' && !!order.coupons?.length && !options?.withoutCoupons && deps.closures
|
|
66
|
+
&& !!(await deps.closures.storageInstance.findDocumentsById([session.id], false))[0]?.order_ids.includes(order.id);
|
|
67
|
+
if (counted) {
|
|
68
|
+
afterClose = { sessionId: order.sessionId, createdAt: order.createdAt, ...(order.registerId !== undefined ? { registerId: order.registerId } : {}),
|
|
69
|
+
payments: order.payments.map(({ id, method, amountMinor }) => ({ id, method, amountMinor })), taxMinor: order.taxMinor,
|
|
70
|
+
fees: (order.fees ?? []).map(({ totalMinor, taxLines }) => ({ totalMinor, taxLines })),
|
|
71
|
+
shipping: (order.shipping ?? []).map(({ totalMinor, taxLines }) => ({ totalMinor, taxLines })) };
|
|
72
|
+
} else if (!session || session.status !== 'open') throw new ReopenRefusedOrderError(orderId, 'session_closed');
|
|
37
73
|
}
|
|
38
|
-
|
|
39
|
-
|
|
74
|
+
const existing = await deps.drafts.findOne(orderId).exec();
|
|
75
|
+
const parked = existing && (afterClose || options?.withoutCoupons) ? JSON.parse(String(existing.data)) as Order : undefined;
|
|
76
|
+
// Parked while the session was open, its money is in the closed closure: reopen refuses it after close (resume is not gated).
|
|
77
|
+
if (afterClose && parked && !parked.afterClose) throw new ReopenRefusedOrderError(orderId, 'session_closed');
|
|
78
|
+
if (parked && options?.withoutCoupons && parked.coupons?.some((coupon) => coupon.carried)) {
|
|
79
|
+
throw new ReopenRefusedOrderError(orderId, 'carried_draft_exists');
|
|
80
|
+
}
|
|
81
|
+
if (!existing) {
|
|
82
|
+
const builder = createOrderBuilder({ currency: order.currency, taxContext: deps.taxContext, id: order.id, ...(afterClose ? { afterClose } : {}) });
|
|
40
83
|
const converted = order.lines.some((line) => line.taxInclusive !== undefined && line.taxInclusive !== order.pricesIncludeTax);
|
|
41
84
|
const display = order.display && !converted ? order.display : undefined;
|
|
85
|
+
const carry = !!order.coupons?.length && !options?.withoutCoupons;
|
|
86
|
+
const lineIds: string[] = [];
|
|
42
87
|
for (const [i, line] of order.lines.entries()) {
|
|
43
88
|
const lineId = builder.addLine({
|
|
44
|
-
productId: line.productId, variantId: line.variantId, name: line.name, sku: line.sku,
|
|
89
|
+
productId: line.productId, variantId: line.variantId, name: line.name, sku: (line.custom ? undefined : line.catalogueSku) ?? line.sku,
|
|
45
90
|
unitPrice: { amount: line.unitPriceMinor, currency: order.currency, taxInclusive: line.taxInclusive },
|
|
46
91
|
...(line.regularUnitPriceMinor !== undefined ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {}),
|
|
47
92
|
...(line.attributes !== undefined ? { attributes: line.attributes } : {}),
|
|
@@ -50,7 +95,12 @@ export async function reopenRefusedOrder(orderId: string, deps: {
|
|
|
50
95
|
taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm })),
|
|
51
96
|
...(line.custom ? { custom: true, taxClass: line.custom.taxClass, taxStatus: line.custom.taxStatus }
|
|
52
97
|
: { taxClass: deps.taxClassOf?.(line.productId, line.variantId) ?? 'standard', taxStatus: line.taxStatus }),
|
|
98
|
+
// Stored lines stay distinct for a coupon sale, so the carry maps by index and the drop is the rebuild it previews.
|
|
99
|
+
...(order.coupons?.length ? { separate: true as const } : {}),
|
|
53
100
|
});
|
|
101
|
+
lineIds.push(lineId);
|
|
102
|
+
// A catalogue line comes back with its catalogue SKU, then its edit, as restoreOrderDraft does (ADR-092 6b).
|
|
103
|
+
if (line.catalogueSku !== undefined && !line.custom) builder.updateLine(lineId, { sku: line.sku });
|
|
54
104
|
if (display) {
|
|
55
105
|
for (const row of display.lines[i].discounts) builder.applyLineDiscount(lineId, {
|
|
56
106
|
type: 'fixed', value: row.amountMinor, ...(row.label !== undefined ? { label: row.label } : {}),
|
|
@@ -74,17 +124,51 @@ export async function reopenRefusedOrder(orderId: string, deps: {
|
|
|
74
124
|
...(shipping.methodId !== undefined ? { methodId: shipping.methodId } : {}),
|
|
75
125
|
});
|
|
76
126
|
for (const payment of order.payments) builder.addPayment({
|
|
77
|
-
|
|
127
|
+
// After close each leg keeps the refused order's id, so finalize knows it for the leg that closure counted.
|
|
128
|
+
...(afterClose ? { id: payment.id } : {}), method: payment.method, amountMinor: payment.amountMinor,
|
|
78
129
|
...(payment.reference !== undefined ? { reference: payment.reference } : {}),
|
|
130
|
+
...(payment.methodId !== undefined ? { methodId: payment.methodId } : {}),
|
|
79
131
|
});
|
|
80
132
|
if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
|
|
81
133
|
builder.setCustomer({ id: order.customer.id, name: order.customer.name,
|
|
82
|
-
...(order.customer.email !== undefined ? { email: order.customer.email } : {})
|
|
134
|
+
...(order.customer.email !== undefined ? { email: order.customer.email } : {}),
|
|
135
|
+
...(order.customer.billing !== undefined ? { billing: order.customer.billing } : {}),
|
|
136
|
+
...(order.customer.shipping !== undefined ? { shipping: order.customer.shipping } : {}),
|
|
137
|
+
...(order.customer.taxIds?.length ? { taxIds: order.customer.taxIds.map((taxId) => ({ ...taxId })) } : {}) });
|
|
83
138
|
}
|
|
84
139
|
// ADR-083 condition 1: the note holds only the cashier's own note, since order.create 7 sends it. The refusal stays
|
|
85
140
|
// on this refused row (`error`), the till's record of it; the draft's id is this row's id.
|
|
86
141
|
if (order.note) builder.setNote(order.note);
|
|
87
|
-
|
|
142
|
+
const dropped = builder.getSnapshot();
|
|
143
|
+
if (carry) {
|
|
144
|
+
const coupons = order.coupons!;
|
|
145
|
+
const toCollectMinor = Math.max(0, dropped.totalMinor - order.payments.reduce((sum, payment) => sum + payment.amountMinor, 0));
|
|
146
|
+
// After close no drop is offered: an inexact carry stays refused for a manager (Front desk, 2026-11-21).
|
|
147
|
+
const inexact = () => afterClose ? new ReopenRefusedOrderError(orderId, 'session_closed')
|
|
148
|
+
: new ReopenRefusedOrderError(orderId, 'coupon_carry_inexact', toCollectMinor);
|
|
149
|
+
const index = new Map(order.lines.map((line, i) => [line.id, i]));
|
|
150
|
+
if ((deps.capabilities?.orderCreate ?? 1) < 4 || coupons.some((coupon) => !coupon.lines
|
|
151
|
+
|| coupon.lines.some(({ lineId }) => !index.has(lineId)))) throw inexact();
|
|
152
|
+
// Shares split ex-tax and tax separately, so on an inclusive line their sum can be a unit off the price; a line one
|
|
153
|
+
// coupon priced holds the exact total, else the shares in the line's own mode serve. The equality guard proves it.
|
|
154
|
+
const exact = (i: number) => {
|
|
155
|
+
const line = order.lines[i], total = line.unitPriceMinor * line.quantity - line.discountMinor - line.netMinor;
|
|
156
|
+
return coupons.filter((coupon) => coupon.lines!.some(({ lineId }) => lineId === line.id)).length === 1
|
|
157
|
+
&& order.taxRounding?.granularity !== 'woocommerce' && total >= 0 ? total : undefined;
|
|
158
|
+
};
|
|
159
|
+
const priced = new Map<string, StorePricedCoupon>(coupons.map((coupon) => [coupon.code, { couponId: coupon.couponId,
|
|
160
|
+
lines: coupon.lines!.map((share) => {
|
|
161
|
+
const i = index.get(share.lineId)!, inclusive = order.lines[i].taxInclusive ?? order.pricesIncludeTax;
|
|
162
|
+
return { lineId: lineIds[i],
|
|
163
|
+
amountMinor: share.amountMinor ?? exact(i) ?? share.discountMinor + (inclusive ? share.discountTaxMinor : 0) };
|
|
164
|
+
}) }]));
|
|
165
|
+
builder.setCoupons(coupons.map((coupon) => coupon.code), { kind: 'store-priced', carried: true, priced, basis: couponPricingBasis(dropped) });
|
|
166
|
+
const carried = builder.getSnapshot();
|
|
167
|
+
if (!sameFigures(carried, order)) throw inexact();
|
|
168
|
+
await writeOrderDraft(deps.drafts, carried);
|
|
169
|
+
} else {
|
|
170
|
+
await writeOrderDraft(deps.drafts, dropped);
|
|
171
|
+
}
|
|
88
172
|
}
|
|
89
173
|
const document = await deps.orders.findOne(orderId).exec();
|
|
90
174
|
await document!.incrementalModify((data) => {
|