@tallyui/pos 4.1.0 → 5.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 +584 -161
- package/dist/index.js +1908 -1077
- package/package.json +7 -6
- package/src/index.ts +17 -10
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +65 -21
- package/src/order/order-drafts.ts +78 -24
- package/src/order/taken-at.ts +5 -0
- package/src/order/types.ts +11 -2
- package/src/order/woocommerce-tax.ts +9 -12
- package/src/outbox/http-transport.ts +16 -1
- package/src/outbox/index.ts +2 -1
- package/src/outbox/needs-admin-reason.ts +10 -0
- package/src/outbox/order-outbox.ts +14 -5
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-order-outbox.ts +7 -3
- package/src/pos-order/command.ts +3 -0
- package/src/pos-order/finalize.ts +11 -0
- package/src/pos-order/reopen.ts +11 -2
- package/src/pos-order/schema.ts +7 -2
- package/src/pos-order/types.ts +7 -1
- package/src/print/escpos/bluetooth-sink.ts +114 -0
- package/src/print/escpos/index.ts +4 -0
- package/src/print/escpos/transport.ts +3 -2
- package/src/print/escpos/usb-sink.ts +84 -0
- package/src/print/index.ts +2 -2
- package/src/receipt/build-receipt-data.ts +8 -1
- package/src/receipt/reprint.ts +2 -0
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/template-data.ts +1 -1
- package/src/receipt-template/wcpos/from-orders.ts +5 -1
- package/src/refund/index.ts +1 -0
- package/src/refund/needs-admin-line.ts +6 -0
- package/src/refund/refundable-lines.ts +2 -91
- package/src/refund/send-order-refund.ts +6 -1
- package/src/refund/submit-order-refund.ts +33 -1
- package/src/register/closing.ts +15 -0
- package/src/register/closure-document.ts +13 -5
- package/src/register/closure-figures.ts +83 -0
- package/src/register/document-labels.ts +5 -3
- package/src/register/expected.ts +30 -9
- package/src/register/index.ts +3 -1
- package/src/register/register-adoption.ts +42 -4
- package/src/register/register-document.ts +17 -0
- package/src/register/session-store.ts +48 -12
- package/src/register/use-register-session.ts +53 -20
- package/src/reports/adapters.ts +5 -1
- package/src/reports/index.ts +1 -1
- package/src/reports/sales-figures.ts +33 -6
- package/src/reports/types.ts +3 -1
- package/src/sale/index.ts +1 -1
- package/src/sale/use-sale.ts +321 -135
- package/src/store-orders/index.ts +5 -0
- package/src/store-orders/sales-range-query.ts +18 -0
- package/src/store-orders/use-store-orders-in-range.ts +127 -0
- package/src/store-orders/use-store-refunds-in-range.ts +179 -0
- package/src/tax/exact.ts +2 -10
- package/src/tax/index.ts +1 -0
- package/src/tender/cash-rounding.ts +49 -6
- package/src/tender/index.ts +1 -1
- package/src/tender/payment-legs.ts +5 -0
- package/src/tender/tender-figures.ts +3 -1
- package/src/outbox/types.test-d.ts +0 -27
package/src/sale/use-sale.ts
CHANGED
|
@@ -1,18 +1,22 @@
|
|
|
1
1
|
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
|
2
2
|
import type { RxCollection } from 'rxdb';
|
|
3
|
-
import type { CustomerAddress, CustomerTaxId, ProductTraits, ServerCapabilities, StoreSettings, woocommerceTax } from '@tallyui/core';
|
|
3
|
+
import type { CustomerAddress, CustomerTaxId, PaymentRounding, ProductTraits, ServerCapabilities, StoreSettings, woocommerceTax } from '@tallyui/core';
|
|
4
4
|
import { ORDER_META_KEY_MAX, ORDER_META_MAX, paymentMethodOf } from '@tallyui/core';
|
|
5
|
-
import { canVoidLeg, capturedMinor, countsTowardPaid, inMotionMinor, isInMotion } from '../tender/payment-legs';
|
|
5
|
+
import { canVoidLeg, capturedMinor, countsTowardPaid, inMotionMinor, isInMotion, legStatus, takenLeg } from '../tender/payment-legs';
|
|
6
6
|
import { heldUnitsByLine, unpaidUnitsByLine } from '../tender/split-units';
|
|
7
7
|
import { createOrderBuilder, writeOrderDraft, restoreOrderDraft, type ChargeInput, type ChargeLine, type LineItem, type OrderBuilder, type CustomerSummary, type Discount, type Order, type SentOrder } from '../order';
|
|
8
8
|
import { STORE_ORDER_REBUILD_REFUSALS } from '../order/from-store-order';
|
|
9
9
|
import { isLiveLeg } from '../order/order-builder';
|
|
10
|
+
import { sessionTakenLegs } from '../order/order-drafts';
|
|
11
|
+
import type { CashRounding, Payment } from '../order/types';
|
|
10
12
|
import { cleanTaxIds, TAX_IDS_INVALID } from '../order/tax-ids';
|
|
11
13
|
import { finalizeOrder, uuidv7, type PosOrder } from '../pos-order';
|
|
12
14
|
import { AFTER_CLOSE_PAYMENTS_CHANGED, afterCloseChanged, MESSAGE_NAME_MAX, referenceError, referenceReason, withSentForm } from '../pos-order/finalize';
|
|
13
15
|
import { CUSTOMER_REFUSALS, customerRefusal, cutText, PAYLOAD_STRING_MAX } from '../pos-order/command';
|
|
16
|
+
import { cashVoidRefusal, nearestPayableCash, remainderEntriesMinor, roundedPickTarget, roundedRemainder, settlesAtRoundedDue } from '../tender/cash-rounding';
|
|
14
17
|
import { useTax, type SaleTaxContext, type SaleTaxLocation, type TaxContext } from '../tax';
|
|
15
18
|
import { recordRegisterFact, stampSession, type RegisterSessionCollection } from '../register';
|
|
19
|
+
import { isRegisterClosing } from '../register/closing';
|
|
16
20
|
import { createLogger } from '../logging';
|
|
17
21
|
import type { CatalogueEntry } from './catalogue';
|
|
18
22
|
import { addEntryToCart, CartError } from './cart';
|
|
@@ -28,20 +32,39 @@ export type SaleStage = { kind: 'cart' } | { kind: 'tender'; method: 'cash' | 'e
|
|
|
28
32
|
export const DISCOUNTS_UNSUPPORTED = 'finalize: discounts are not supported by the server yet (order.create v2)';
|
|
29
33
|
/** Every sale change refuses with this while a completion is pending (see `complete()`). */
|
|
30
34
|
export const SALE_SAVING = 'This sale is being saved. Retry to finish it.';
|
|
35
|
+
/** `complete`, `park` and `resume` refuse with this while a close for the sale's register is in flight (#1275). */
|
|
36
|
+
export const REGISTER_CLOSING = 'The register is closing. Wait for the close to finish, then try again.';
|
|
31
37
|
export const PAYMENT_IN_MOTION = 'Finish or void the payment in progress before completing the sale';
|
|
32
38
|
/**
|
|
33
39
|
* `switchSale()` and `closeSale()` refuse a sale whose legs took money (u19). v2 keeps a partly paid order's legs on
|
|
34
|
-
* switching, but a TallyUI draft keeps no tender stage
|
|
35
|
-
*
|
|
40
|
+
* switching, but a TallyUI draft keeps no tender stage; `startTender` keeps taken legs and legs in motion (ADR-072 d3,
|
|
41
|
+
* amended 2026-11-22 and 2026-11-23), and `resume` keeps a paid draft's parked coupons (ADR-077 d3, amended 2026-11-19): so the
|
|
36
42
|
* sale stays on the till until it is paid or its paid legs are voided.
|
|
37
43
|
*/
|
|
38
44
|
export const SALE_PARTLY_PAID = 'This sale is partly paid. Take the rest of the payment or void the paid legs first.';
|
|
45
|
+
/** newSale refuses with this while an unlocked payment leg is pending or authorized. */
|
|
46
|
+
export const SALE_CARD_IN_PROGRESS = 'A card payment is still in progress. Finish or cancel it before starting a new sale.';
|
|
39
47
|
export const SALE_IN_TENDER = 'Finish or cancel the payment before switching sales';
|
|
40
48
|
/**
|
|
41
49
|
* Line and total changes refuse with this while a till leg is live, as v2's resolveStage stills the cart (tally-woo 11c).
|
|
42
50
|
* "Cancel the payment" names the leg's button, `pos_checkout.cancel_payment` ("Cancel payment") in packages/components.
|
|
43
51
|
*/
|
|
44
52
|
export const SALE_HAS_PAYMENT = 'A payment was taken on this sale. Cancel the payment before changing the sale.';
|
|
53
|
+
/** removeTender refuses a taken leg with this: it is voided, never removed (ADR-072 d3, amended 2026-11-22). */
|
|
54
|
+
export const PAYMENT_TAKEN = 'This payment was taken. Void it instead of removing it.';
|
|
55
|
+
/** A cash addTender refuses with this when the balance less the legs in motion leaves nothing due (row 500). */
|
|
56
|
+
export const NOTHING_DUE = 'Nothing is left to pay: the payments on this sale already cover the total.';
|
|
57
|
+
/** ADR-094: a cash due that rounds to nothing is entered against the last leg counting toward paid; with none, there is nothing to round against. */
|
|
58
|
+
export const NOTHING_TO_ROUND_AGAINST = 'This sale rounds to nothing in cash: take it by another method.';
|
|
59
|
+
export const CASH_NOT_PAYABLE = 'Cash cannot pay that amount: take a whole number of the smallest cash step.';
|
|
60
|
+
export const CASH_WAITS_FOR_PAYMENT = 'Cash cannot pay that amount while another payment is in progress: finish that payment first.';
|
|
61
|
+
// order-payload-shape.ts accepts at most 16 cashRoundings entries; one stays free for the leg that settles the sale.
|
|
62
|
+
export const CASH_PICK_ENTRIES_MAX = 15;
|
|
63
|
+
export const CASH_PICK_LIMIT = 'Too many rounded cash payments on this sale: take the rest as one payment.';
|
|
64
|
+
// order-payload-shape.ts accepts at most 16 entries, so a non-pick cash leg may not add a 17th.
|
|
65
|
+
export const CASH_SETTLE_LIMIT = 'Too many rounded cash payments on this sale: take the rest by another method.';
|
|
66
|
+
/** voidTender's refusal for cashVoidRefusal's 'later_cash_rounding' (ADR-094 item 6); the components translate it as pos_checkout.void_later_cash_first. */
|
|
67
|
+
export const VOID_LATER_CASH_FIRST = 'Void the later cash payment first.';
|
|
45
68
|
/** On the receipt the finished sale refuses edits and re-tender with this; `add` starts the next sale instead (v2 #2861). */
|
|
46
69
|
export const SALE_FINISHED = 'This sale is finished. Start a new sale to change it.';
|
|
47
70
|
/** startTender and complete() refuse with this while the order's store-priced coupons are stale or being priced again (TallyUI#710). */
|
|
@@ -67,7 +90,7 @@ export const META_CHANGE_REFUSED = 'Custom fields can only change in the cart. C
|
|
|
67
90
|
export const META_INVALID = 'A custom field needs a name of at most 255 characters that does not start with "_", and a sale takes at most 50.';
|
|
68
91
|
/** ADR-092 6b: updateLine's refusal once the sale left the cart; a line's name, SKU and regular price change only in the cart. */
|
|
69
92
|
export const LINE_EDIT_REFUSED = 'A line can only be edited in the cart. Cancel the payment to edit it, or start a new order.';
|
|
70
|
-
/** #1095: restore()'s refusal of a removal whose sale moved on (reset, parked, finished) or that is already back. */
|
|
93
|
+
/** #1095: restore()'s refusal of a removal whose sale moved on (reset, parked, resumed, finished), whose customer changed or whose sale was re-taxed since, or that is already back. */
|
|
71
94
|
export const RESTORE_STALE = 'This item can no longer be put back. Add it again.';
|
|
72
95
|
/** Taken by `removal()` before a remove; pass it to `restore()`. Hosts never build one. */
|
|
73
96
|
export type SaleRemoval = { readonly kind: 'line' | 'fee' | 'shipping'; readonly id: string; readonly item: LineItem | ChargeLine;
|
|
@@ -85,6 +108,11 @@ const KEPT = Symbol('kept coupon');
|
|
|
85
108
|
* `useSale`'s `hungSaveCheckMs` overrides this; that option is tests only.
|
|
86
109
|
*/
|
|
87
110
|
export const HUNG_SAVE_CHECK_MS = 5000;
|
|
111
|
+
/**
|
|
112
|
+
* An `onSaleCompleted` call unsettled after this long is treated as failed, so the sale offers Retry;
|
|
113
|
+
* the register can be closed once the retry succeeds (Front desk, 2026-11-23).
|
|
114
|
+
*/
|
|
115
|
+
export const SAVE_TIMEOUT_MS = 60_000;
|
|
88
116
|
|
|
89
117
|
/** Runs a builder call; an `Error` it throws becomes the refusal message to show, anything else is rethrown. */
|
|
90
118
|
function refusalOf<T>(run: () => T): T | string {
|
|
@@ -135,6 +163,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
135
163
|
isStored?: (posOrder: PosOrder) => Promise<boolean>;
|
|
136
164
|
/** Tests only: overrides HUNG_SAVE_CHECK_MS, so a test can shrink the hung-save poll's interval. */
|
|
137
165
|
hungSaveCheckMs?: number;
|
|
166
|
+
/** Tests only: overrides SAVE_TIMEOUT_MS, so a test can shrink the save's time bound. */
|
|
167
|
+
saveTimeoutMs?: number;
|
|
138
168
|
/**
|
|
139
169
|
* #722: the tax context for a customer's address (`saleTaxContexts(settings)`, memoized). Each new sale is taxed for its
|
|
140
170
|
* customer, and `setCustomer` re-taxes a cart whose new customer moves the matched rates; tender and receipt keep theirs.
|
|
@@ -158,6 +188,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
158
188
|
}
|
|
159
189
|
const defaultKey = opts.defaultCustomer ? JSON.stringify([opts.defaultCustomer.id, opts.defaultCustomer.name, opts.defaultCustomer.email]) : '';
|
|
160
190
|
const defaultSeen = useRef(defaultKey);
|
|
191
|
+
const resetRefused = useRef(false); // the idle reset was refused for a held taken payment; its error is set once, not on every render (row 516)
|
|
161
192
|
const [rendered, setBuilder] = useState(() => {
|
|
162
193
|
const customer = defaulted();
|
|
163
194
|
taxNow.current = contextFor(customer);
|
|
@@ -218,6 +249,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
218
249
|
}
|
|
219
250
|
// The complete() call in flight, and the stage as of the last render or receipt, both read synchronously.
|
|
220
251
|
const inFlight = useRef<Promise<void> | null>(null);
|
|
252
|
+
// park() and resume() calls in flight, which the register reads as `saving` (#1275).
|
|
253
|
+
const moving = useRef(0);
|
|
221
254
|
const stageNow = useRef(stage);
|
|
222
255
|
stageNow.current = stage;
|
|
223
256
|
/** True, with SALE_SAVING shown, from complete()'s entry (inFlight) through a pending retry: the sale can't change. */
|
|
@@ -244,13 +277,23 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
244
277
|
const repricing = useRef<Promise<string | null> | null>(null);
|
|
245
278
|
const [couponsRepricing, setCouponsRepricing] = useState(false);
|
|
246
279
|
const generation = useRef(0);
|
|
247
|
-
|
|
280
|
+
// #1095: a removal from an older epoch is stale; bumped by every resetSale (new sale, park, resume, switch, receipt exit)
|
|
281
|
+
// and every accepted customer change (setCustomer, setAddresses, setTaxIds).
|
|
282
|
+
const removalEpoch = useRef(0);
|
|
248
283
|
const stopped = useRef<{ order: Order; reason: string } | null>(null);
|
|
249
284
|
const keptCoupons = useRef<Order['coupons']>(undefined); // the draft's coupons while KEPT placeholders hold; park writes them stale
|
|
250
285
|
const keptLegIds = useRef<readonly string[]>([]); // the kept draft's parked live legs, held while KEPT placeholders hold
|
|
286
|
+
const resumedLegIds = useRef<readonly string[]>([]); // a resumed draft's parked live legs, held until the sale resets (ADR-072 d3, amended 2026-11-22; row 328 F3)
|
|
287
|
+
// a resumed draft's captured legs with no takenAt (parked before 4.2): taken, with no stamp invented (row 517)
|
|
288
|
+
const resumedTakenIds = useRef<readonly string[]>([]);
|
|
251
289
|
// An after-close sale's closure counted these legs, and finalize refuses any change to them: they are held like a locked leg.
|
|
252
290
|
function countedLeg(p: { id: string }) { return !!builderNow.current.getSnapshot().afterClose?.payments.some((leg) => leg.id === p.id); }
|
|
253
|
-
|
|
291
|
+
// BUG 2: a leg in motion is held too, so Back and a repeat startTender never drop a card the terminal may still capture.
|
|
292
|
+
function heldLeg(p: Order['payments'][number]) { return !!p.locked || !!p.reopened || countedLeg(p) || (keptCodes() && isLiveLeg(p) && keptLegIds.current.includes(p.id))
|
|
293
|
+
|| (isLiveLeg(p) && resumedLegIds.current.includes(p.id)) || taken(p) || isInMotion(p); }
|
|
294
|
+
function taken(p: Order['payments'][number]) { return takenLeg(p) || resumedTakenIds.current.includes(p.id); }
|
|
295
|
+
/** The live sale holds a captured taken payment (row 517's `taken`): newSale, openStoreOrder, resume and the empty-sale resets refuse it with SALE_PARTLY_PAID (row 516). */
|
|
296
|
+
function holdsTakenPayment() { return builderNow.current.getSnapshot().payments.some((p) => !p.locked && legStatus(p) === 'captured' && taken(p)); }
|
|
254
297
|
/** Prices the accepted codes again, as resume() checks them, on the live builder; resolves to the error it set, or null. */
|
|
255
298
|
function reprice(): Promise<string | null> {
|
|
256
299
|
if (repricing.current) return repricing.current;
|
|
@@ -292,7 +335,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
292
335
|
/** startTender's and complete()'s check: the live order's coupon prices are stale or being priced again. */
|
|
293
336
|
function couponsUnpriced() { return !!(builderNow.current.getSnapshot().couponPricesStale || repricing.current); }
|
|
294
337
|
function carriedCoupon() { return builderNow.current.getSnapshot().coupons?.some((coupon) => coupon.carried); }
|
|
295
|
-
// newSale()'s body (see its doc comment for the guards): `newSale()` is `resetSale()
|
|
338
|
+
// newSale()'s body (see its doc comment for the guards): `newSale()` is `resetSale()` after newSale's guard, on the default customer.
|
|
296
339
|
function resetSale(customer: CustomerSummary | null = defaulted(), restored?: OrderBuilder, restoredTax?: SaleTax) {
|
|
297
340
|
if (inFlight.current && !pending.current) return setError(SALE_SAVING);
|
|
298
341
|
if (pending.current && confirmed.current !== pending.current) {
|
|
@@ -311,10 +354,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
311
354
|
builderNow.current = next;
|
|
312
355
|
taxNow.current = tax;
|
|
313
356
|
applied.current.clear();
|
|
314
|
-
keptCoupons.current = undefined; keptLegIds.current = [];
|
|
357
|
+
keptCoupons.current = undefined; keptLegIds.current = []; resumedLegIds.current = []; resumedTakenIds.current = [];
|
|
315
358
|
appliedWith.current = null;
|
|
316
359
|
generation.current++;
|
|
317
|
-
|
|
360
|
+
removalEpoch.current++;
|
|
318
361
|
setBuilder(next);
|
|
319
362
|
setOrder(next.getSnapshot());
|
|
320
363
|
// Live at once, so a resume() in the same tick (switchSale) sees the cart before the next render.
|
|
@@ -342,18 +385,22 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
342
385
|
setError(COUPONS_UNSUPPORTED);
|
|
343
386
|
}
|
|
344
387
|
// New tax settings or currency wait until the sale is idle (an empty cart), then start a new sale keeping its customer:
|
|
345
|
-
// a sale in progress (lines, tender or receipt) finishes on the settings it started with (a money rule)
|
|
388
|
+
// a sale in progress (lines, tender or receipt) finishes on the settings it started with (a money rule), and an empty
|
|
389
|
+
// sale holding a taken payment waits too, refused with SALE_PARTLY_PAID (row 516).
|
|
346
390
|
const idle = stage.kind === 'cart' && !order.lineItems.length && !order.fees?.length && !order.shipping?.length;
|
|
347
391
|
// A layout effect, on live idleness (#301): it runs inside the settings' commit, before any tap can be handled, and
|
|
348
392
|
// the rendered `idle` would miss a line added since this render (it would then be dropped with the old builder).
|
|
349
393
|
// A new default customer starts a new sale on it at once when idle, as v2 seeds its new cart again; never held pending.
|
|
394
|
+
function refuseIdleReset() { if (!resetRefused.current) setError(SALE_PARTLY_PAID); resetRefused.current = true; }
|
|
350
395
|
useLayoutEffect(() => {
|
|
351
396
|
const live = builderNow.current.getSnapshot();
|
|
352
397
|
const liveIdle = stageNow.current.kind === 'cart' && !live.lineItems.length && !live.fees?.length && !live.shipping?.length && !inFlight.current && !pending.current;
|
|
353
398
|
const newDefault = defaultSeen.current !== defaultKey;
|
|
354
399
|
defaultSeen.current = defaultKey;
|
|
355
|
-
|
|
356
|
-
|| madeWith.current.taxContextFor !== opts.taxContextFor)
|
|
400
|
+
const due = liveIdle && (newDefault || madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency
|
|
401
|
+
|| madeWith.current.taxContextFor !== opts.taxContextFor);
|
|
402
|
+
if (due && holdsTakenPayment()) refuseIdleReset();
|
|
403
|
+
else { resetRefused.current = false; if (due) resetSale(newDefault ? undefined : live.customer ?? null); }
|
|
357
404
|
});
|
|
358
405
|
/**
|
|
359
406
|
* #722: the cart rebuilt on `next`, its customer's context, as resume() restores a draft: the order id, lines, discounts,
|
|
@@ -393,20 +440,26 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
393
440
|
}
|
|
394
441
|
}, []);
|
|
395
442
|
|
|
396
|
-
function addOne(tender: { method: 'cash' | 'external'; methodId?: string; amountMinor: number; tenderedMinor?: number; changeMinor?: number; reference?: string; units?: Readonly<Record<string, number>>; status?: 'pending' | 'authorized' | 'captured' }): string {
|
|
443
|
+
function addOne(tender: { method: 'cash' | 'external'; methodId?: string; amountMinor: number; tenderedMinor?: number; changeMinor?: number; reference?: string; units?: Readonly<Record<string, number>>; status?: 'pending' | 'authorized' | 'captured' }, stamp: boolean, rounding?: { minor: number }): string {
|
|
397
444
|
// A terminal reference finalize would refuse is dropped as it's entered, never the payment (the money is
|
|
398
445
|
// taken): the tender applies without it, with a message that doesn't block complete() and a
|
|
399
446
|
// localWarnings entry on the stored order naming the payment whose reference was dropped.
|
|
400
447
|
const reason = referenceReason(tender.reference);
|
|
401
448
|
const dropped = reason && (reason === 'nul' ? 'it contains a NUL character' : `it is over ${PAYLOAD_STRING_MAX} characters`);
|
|
402
|
-
|
|
449
|
+
// addTender stamps a leg that enters captured; setTender's pre-filled leg waits for complete(), a pending one for capture.
|
|
450
|
+
// Stamped here, never in addPayment, which the restore paths call too.
|
|
451
|
+
// S3: a leg entering captured is also stamped with its tender's session; a pending or authorized one gets its session
|
|
452
|
+
// at capture (setTenderStatus), which may be in a later session. No session, no stamp.
|
|
453
|
+
const captured = stamp && legStatus({ status: tender.status }) === 'captured', sessionId = captured ? legSessionId() : undefined;
|
|
454
|
+
const takenAt = { ...(captured ? { takenAt: new Date().toISOString() } : {}), ...(sessionId !== undefined ? { sessionId } : {}) };
|
|
455
|
+
const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor, ...takenAt,
|
|
403
456
|
...(tender.tenderedMinor !== undefined ? { tenderedMinor: tender.tenderedMinor } : {}),
|
|
404
457
|
...(tender.changeMinor !== undefined ? { changeMinor: tender.changeMinor } : {}),
|
|
405
458
|
...(tender.units !== undefined ? { units: tender.units } : {}),
|
|
406
|
-
...(tender.methodId !== undefined ? { methodId: tender.methodId } : {}), ...(tender.status !== undefined ? { status: tender.status } : {}) } : tender;
|
|
459
|
+
...(tender.methodId !== undefined ? { methodId: tender.methodId } : {}), ...(tender.status !== undefined ? { status: tender.status } : {}) } : { ...tender, ...takenAt };
|
|
407
460
|
const builder = builderNow.current;
|
|
408
461
|
const { units, ...payment } = kept;
|
|
409
|
-
const paymentId = builder.addPayment({ ...payment, ...(units && Object.keys(units).length ? { units } : {}) });
|
|
462
|
+
const paymentId = builder.addPayment({ ...payment, ...(units && Object.keys(units).length ? { units } : {}) }, rounding);
|
|
410
463
|
if (dropped) {
|
|
411
464
|
droppedReferences.current.add(paymentId);
|
|
412
465
|
setError(`${REFERENCE_DROPPED} (${dropped}); the payment is recorded without it.`);
|
|
@@ -431,10 +484,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
431
484
|
// An after-close sale's money is what its closure counted, so the sale takes and gives none (ADR-077).
|
|
432
485
|
if (tender && builderNow.current.getSnapshot().afterClose) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
|
|
433
486
|
const builder = builderNow.current;
|
|
434
|
-
for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) builder.removePayment(payment.id);
|
|
435
|
-
droppedReferences.current.clear();
|
|
487
|
+
for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) { builder.removePayment(payment.id); droppedReferences.current.delete(payment.id); }
|
|
436
488
|
setError(null);
|
|
437
|
-
if (tender) addOne(tender);
|
|
489
|
+
if (tender) addOne(tender, false);
|
|
438
490
|
}
|
|
439
491
|
|
|
440
492
|
/** addTender, voidTender and removeTender changed the tenders: a stale error goes, a dropped-reference message stays. */
|
|
@@ -466,8 +518,20 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
466
518
|
else if (hungSaveTimer.current === timer) clearHungSaveTimer();
|
|
467
519
|
}, opts.hungSaveCheckMs ?? HUNG_SAVE_CHECK_MS) : null;
|
|
468
520
|
hungSaveTimer.current = timer;
|
|
521
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
522
|
+
let timedOut = false;
|
|
469
523
|
try {
|
|
470
|
-
await
|
|
524
|
+
await Promise.race([
|
|
525
|
+
Promise.resolve(opts.onSaleCompleted?.(completion.posOrder)).then(() => {
|
|
526
|
+
if (timedOut && pending.current === completion && inFlight.current === null) finish();
|
|
527
|
+
}, (error) => {
|
|
528
|
+
if (timedOut && confirmed.current !== completion) saleLogger.error('onSaleCompleted failed', { orderId: completion.posOrder.id, error: error instanceof Error ? error.message : String(error) });
|
|
529
|
+
throw error;
|
|
530
|
+
}),
|
|
531
|
+
new Promise<never>((_resolve, reject) => {
|
|
532
|
+
timeout = setTimeout(() => { timedOut = true; reject(new Error('the save took too long')); }, opts.saveTimeoutMs ?? SAVE_TIMEOUT_MS);
|
|
533
|
+
}),
|
|
534
|
+
]);
|
|
471
535
|
} catch (error) {
|
|
472
536
|
if (hungSaveTimer.current === timer) clearHungSaveTimer();
|
|
473
537
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -482,16 +546,19 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
482
546
|
checkStored(completion);
|
|
483
547
|
}
|
|
484
548
|
return;
|
|
549
|
+
} finally { clearTimeout(timeout); }
|
|
550
|
+
finish();
|
|
551
|
+
function finish() {
|
|
552
|
+
if (hungSaveTimer.current === timer) clearHungSaveTimer();
|
|
553
|
+
if (pending.current !== completion) return;
|
|
554
|
+
pending.current = null;
|
|
555
|
+
droppedReferences.current.clear();
|
|
556
|
+
confirm(null);
|
|
557
|
+
setSaving(false);
|
|
558
|
+
setError(null); // every error goes, SALE_HAS_PAYMENT too: it is never shown on the receipt (#1059 review)
|
|
559
|
+
stageNow.current = { kind: 'receipt', order: withSentForm(completion.order, completion.posOrder), posOrder: completion.posOrder };
|
|
560
|
+
setStage(stageNow.current);
|
|
485
561
|
}
|
|
486
|
-
if (hungSaveTimer.current === timer) clearHungSaveTimer();
|
|
487
|
-
if (pending.current !== completion) return;
|
|
488
|
-
pending.current = null;
|
|
489
|
-
droppedReferences.current.clear();
|
|
490
|
-
confirm(null);
|
|
491
|
-
setSaving(false);
|
|
492
|
-
setError(null); // every error goes, SALE_HAS_PAYMENT too: it is never shown on the receipt (#1059 review)
|
|
493
|
-
stageNow.current = { kind: 'receipt', order: withSentForm(completion.order, completion.posOrder), posOrder: completion.posOrder };
|
|
494
|
-
setStage(stageNow.current);
|
|
495
562
|
}
|
|
496
563
|
|
|
497
564
|
/**
|
|
@@ -507,6 +574,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
507
574
|
return inFlight.current ?? Promise.resolve();
|
|
508
575
|
}
|
|
509
576
|
|
|
577
|
+
/** The session this tender is pinned to, as complete() stamps the order (S3). */
|
|
578
|
+
const legSessionId = () => (tenderSession.current?.session ?? opts.session)?.id;
|
|
579
|
+
|
|
510
580
|
function begin(method: 'cash' | 'external', options?: { session?: { id: string; sessions: RegisterSessionCollection } }) {
|
|
511
581
|
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED); // a tender gate that answers after complete()
|
|
512
582
|
if (locked()) return;
|
|
@@ -515,7 +585,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
515
585
|
if (couponsUnpriced()) return setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING);
|
|
516
586
|
if (afterCloseChanged(current)) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
|
|
517
587
|
tenderSession.current ??= { session: options?.session ?? opts.session }; // a repeat call mid-tender keeps the pin
|
|
518
|
-
const heldMinor = current.payments.reduce((sum, payment) => sum + (heldLeg(payment) ? payment.amountMinor : 0), 0);
|
|
588
|
+
const heldMinor = current.payments.reduce((sum, payment) => sum + (heldLeg(payment) && legStatus(payment) !== 'voided' ? payment.amountMinor : 0), 0);
|
|
519
589
|
if (current.afterClose) setTender(null); // its legs are all counted
|
|
520
590
|
else if (heldMinor === 0) setTender(method === 'external' ? { method, amountMinor: current.totalMinor } : null);
|
|
521
591
|
else setTender(method === 'external' && current.totalMinor - heldMinor > 0 ? { method, amountMinor: current.totalMinor - heldMinor } : null);
|
|
@@ -651,20 +721,18 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
651
721
|
const order = builderNow.current.getSnapshot();
|
|
652
722
|
const list: readonly (LineItem | ChargeLine)[] = kind === 'line' ? order.lineItems : kind === 'fee' ? order.fees ?? [] : order.shipping ?? [];
|
|
653
723
|
const index = list.findIndex((item) => item.id === id);
|
|
654
|
-
return index < 0 ? null : { kind, id, item: list[index], index, orderId: order.id, taxContext: taxNow.current.taxContext, epoch:
|
|
724
|
+
return index < 0 ? null : { kind, id, item: list[index], index, orderId: order.id, taxContext: taxNow.current.taxContext, epoch: removalEpoch.current };
|
|
655
725
|
},
|
|
656
|
-
/** #1095, v2's Undo: puts a removal back at its old index (clamped), re-
|
|
726
|
+
/** #1095, v2's Undo: puts a removal back at its old index (clamped); returns a refusal or null. Any customer change, a re-tax, a reset (park, resume, new sale) or the receipt voids it (RESTORE_STALE). */
|
|
657
727
|
restore(removal: SaleRemoval): string | null {
|
|
658
728
|
const held = editRefusal(); if (held) return held;
|
|
659
|
-
const order = builderNow.current.getSnapshot()
|
|
660
|
-
if (stageNow.current.kind !== 'cart' || removal.orderId !== order.id || removal.epoch !==
|
|
729
|
+
const order = builderNow.current.getSnapshot();
|
|
730
|
+
if (stageNow.current.kind !== 'cart' || removal.orderId !== order.id || removal.epoch !== removalEpoch.current
|
|
731
|
+
|| removal.taxContext !== taxNow.current.taxContext) return RESTORE_STALE;
|
|
661
732
|
const ids = [removal.item, ...(removal.kind === 'line' ? (removal.item as LineItem).discounts : [])].map((entry) => entry.id);
|
|
662
733
|
if ([...order.lineItems.flatMap((li) => [li, ...li.discounts]), ...order.fees ?? [], ...order.shipping ?? [], ...order.discounts, ...order.payments]
|
|
663
734
|
.some((entry) => ids.includes(entry.id))) return RESTORE_STALE; // already back
|
|
664
|
-
// A re-tax runs only as retaxFor allows it (stage and busy are refused above).
|
|
665
|
-
if (moved && (capturedMinor(order.payments) !== 0 || order.payments.some(isInMotion) || keptCodes())) return RESTORE_STALE;
|
|
666
735
|
builderNow.current.restoreItem(removal.kind, removal.item, removal.index);
|
|
667
|
-
if (moved) retax(builderNow.current.getSnapshot().customer, taxNow.current);
|
|
668
736
|
return null;
|
|
669
737
|
},
|
|
670
738
|
/** A line's discount, or the order's without a line; returns the refusal to show, or null once applied. */
|
|
@@ -755,6 +823,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
755
823
|
if (same) taxNow.current = same;
|
|
756
824
|
builderNow.current.setCustomer(customer);
|
|
757
825
|
}
|
|
826
|
+
removalEpoch.current++;
|
|
758
827
|
setError((current) => current !== null && (CUSTOMER_REFUSALS.includes(current) || current === CUSTOMER_RETAX_REFUSED || current === TAX_IDS_INVALID) ? null : current); // any other error stays
|
|
759
828
|
},
|
|
760
829
|
/**
|
|
@@ -778,6 +847,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
778
847
|
if (same) taxNow.current = same;
|
|
779
848
|
builderNow.current.setCustomer(next);
|
|
780
849
|
}
|
|
850
|
+
removalEpoch.current++;
|
|
781
851
|
setError((current) => current === ADDRESS_CHANGE_REFUSED ? null : current); // any other error stays
|
|
782
852
|
return true;
|
|
783
853
|
},
|
|
@@ -793,6 +863,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
793
863
|
if (!cleaned) { setError(TAX_IDS_INVALID); return false; }
|
|
794
864
|
const { taxIds: _taxIds, ...rest } = customer;
|
|
795
865
|
builderNow.current.setCustomer(cleaned.length ? { ...rest, taxIds: cleaned } : rest);
|
|
866
|
+
removalEpoch.current++;
|
|
796
867
|
setError((current) => current === TAX_IDS_CHANGE_REFUSED || current === TAX_IDS_INVALID ? null : current); // any other error stays
|
|
797
868
|
return true;
|
|
798
869
|
},
|
|
@@ -846,10 +917,19 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
846
917
|
});
|
|
847
918
|
},
|
|
848
919
|
setTender,
|
|
849
|
-
/** 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. Units are checked against the units legs hold (`heldUnitsByLine`), but a leg's amount is not tied to its units' money here; the pane enforces that (#1133). */
|
|
850
|
-
addTender(
|
|
920
|
+
/** ADR-072: external is capped at the balance due; change comes only from cash. A cash leg records the amount applied, the amount handed over (`tenderedMinor`) and the change (`changeMinor`). A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. Units are checked against the units legs hold (`heldUnitsByLine`), but a leg's amount is not tied to its units' money here; the pane enforces that (#1133). A cash part pick rounds its own target on a cashRounding store (ADR-094). */
|
|
921
|
+
addTender(input: { method: 'cash' | 'external'; methodId?: string; amountMinor: number; tenderedMinor?: number; reference?: string; units?: Readonly<Record<string, number>>; status?: 'pending' | 'authorized' | 'captured'; rounding?: PaymentRounding }): string | null {
|
|
922
|
+
const { rounding, ...tender } = input;
|
|
851
923
|
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return null; }
|
|
852
|
-
if (
|
|
924
|
+
if (rounding && tender.method !== 'cash') return null;
|
|
925
|
+
// ADR-094: a cash leg is rounded only against a store whose connector declares cashRounding; otherwise, BASE's leg.
|
|
926
|
+
// A leg in motion means this cash leg does not settle the sale, so nothing rounds: BASE's row 500 leg, but the leg it records must still be a whole number of cash steps (refused with CASH_WAITS_FOR_PAYMENT otherwise).
|
|
927
|
+
const rule = rounding && tender.tenderedMinor === undefined && opts.capabilities?.cashRounding === true
|
|
928
|
+
&& inMotionMinor(builderNow.current.getSnapshot().payments) === 0 ? rounding : null;
|
|
929
|
+
// ADR-094 (cash picks): a cash part pick rounds its own target and carries its own entry.
|
|
930
|
+
const pickRule = rounding && tender.method === 'cash' && opts.capabilities?.cashRounding === true
|
|
931
|
+
&& inMotionMinor(builderNow.current.getSnapshot().payments) === 0 ? rounding : null;
|
|
932
|
+
if (locked() || !Number.isInteger(tender.amountMinor) || tender.amountMinor < 0 || (tender.amountMinor === 0 && !rule)) return null;
|
|
853
933
|
if (builderNow.current.getSnapshot().afterClose) { setError(AFTER_CLOSE_PAYMENTS_CHANGED); return null; }
|
|
854
934
|
const taxIdsRefused = taxIdsRefusal();
|
|
855
935
|
if (taxIdsRefused) { setError(taxIdsRefused); return null; }
|
|
@@ -860,33 +940,75 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
860
940
|
const unpaid = unpaidUnitsByLine(lineItems.map(({ id, quantity }) => ({ id, quantity, totalMinor: 0 })), heldUnitsByLine(payments));
|
|
861
941
|
if (Object.entries(tender.units).some(([id, units]) => !id || !Number.isInteger(units) || units <= 0 || !Object.hasOwn(unpaid, id) || units > unpaid[id])) return null;
|
|
862
942
|
}
|
|
943
|
+
const pickMinor = pickRule && tender.tenderedMinor !== undefined ? roundedPickTarget(tender.amountMinor, pickRule) : tender.amountMinor;
|
|
944
|
+
if (tender.tenderedMinor !== undefined && pickMinor === 0) return null;
|
|
863
945
|
if (tender.tenderedMinor !== undefined && (tender.method !== 'cash' || !tender.units || !Object.keys(tender.units).length
|
|
864
|
-
|| !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor <
|
|
946
|
+
|| !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor < pickMinor)) return null;
|
|
865
947
|
if (tender.tenderedMinor !== undefined) {
|
|
866
948
|
const snapshot = builderNow.current.getSnapshot();
|
|
867
949
|
if (tender.amountMinor > snapshot.balanceDueMinor - inMotionMinor(snapshot.payments)) return null;
|
|
950
|
+
if (pickMinor !== tender.amountMinor && (snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX) { setError(CASH_PICK_LIMIT); return null; }
|
|
951
|
+
if (rounding && opts.capabilities?.cashRounding === true && tender.method === 'cash' && inMotionMinor(snapshot.payments) > 0
|
|
952
|
+
&& nearestPayableCash(tender.amountMinor, rounding.incrementMinor) !== null) { setError(CASH_WAITS_FOR_PAYMENT); return null; }
|
|
868
953
|
}
|
|
869
954
|
if (tender.method === 'external') {
|
|
870
955
|
const snapshot = builderNow.current.getSnapshot();
|
|
871
956
|
const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
|
|
872
957
|
if (due <= 0) return null;
|
|
873
958
|
clearStaleError(); // before addOne, which sets its own message for a dropped reference
|
|
874
|
-
return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
|
|
959
|
+
return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) }, true);
|
|
960
|
+
}
|
|
961
|
+
if (tender.tenderedMinor === undefined) {
|
|
962
|
+
const snapshot = builderNow.current.getSnapshot();
|
|
963
|
+
const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
|
|
964
|
+
if (due <= 0) { setError(NOTHING_DUE); return null; }
|
|
965
|
+
const entries = remainderEntriesMinor(snapshot);
|
|
966
|
+
const dueMinor = rule ? roundedRemainder(due, entries, rule) : due;
|
|
967
|
+
if (rule && settlesAtRoundedDue({ amountMinor: Math.min(tender.amountMinor, due), tenderedMinor: tender.amountMinor, balanceMinor: due, dueMinor })) {
|
|
968
|
+
const against = snapshot.payments.filter(countsTowardPaid).at(-1);
|
|
969
|
+
const roundings = snapshot.cashRoundings ?? [];
|
|
970
|
+
// The 16-entry cap: a settle that adds an entry (a rounded leg, or a write-off onto a leg with none) is refused at 16.
|
|
971
|
+
if (roundings.length >= CASH_PICK_ENTRIES_MAX + 1 && (dueMinor > 0 ? dueMinor !== due
|
|
972
|
+
: against !== undefined && !roundings.some((entry) => entry.paymentId === against.id))) { setError(CASH_SETTLE_LIMIT); return null; }
|
|
973
|
+
clearStaleError();
|
|
974
|
+
if (dueMinor > 0) {
|
|
975
|
+
return addOne({ ...tender, amountMinor: dueMinor, tenderedMinor: tender.amountMinor, changeMinor: tender.amountMinor - dueMinor }, true, { minor: dueMinor - due });
|
|
976
|
+
}
|
|
977
|
+
// A remainder that rounds to zero closes the sale: no leg, its entry goes on the last leg counting toward paid.
|
|
978
|
+
if (!against) { setError(NOTHING_TO_ROUND_AGAINST); return null; }
|
|
979
|
+
builderNow.current.addCashRounding({ paymentId: against.id, minor: -due });
|
|
980
|
+
return against.id;
|
|
981
|
+
}
|
|
982
|
+
if (tender.amountMinor === 0) return null; // only the zero-remainder settle takes nothing
|
|
983
|
+
if (rule && nearestPayableCash(tender.amountMinor, rule.incrementMinor)) { setError(CASH_NOT_PAYABLE); return null; }
|
|
984
|
+
const amountMinor = Math.min(tender.amountMinor, due);
|
|
985
|
+
if (rounding && tender.tenderedMinor === undefined && opts.capabilities?.cashRounding === true
|
|
986
|
+
&& inMotionMinor(snapshot.payments) > 0 && nearestPayableCash(amountMinor, rounding.incrementMinor) !== null) {
|
|
987
|
+
setError(CASH_WAITS_FOR_PAYMENT); return null;
|
|
988
|
+
}
|
|
989
|
+
clearStaleError();
|
|
990
|
+
return addOne({ ...tender, amountMinor, tenderedMinor: tender.amountMinor, changeMinor: tender.amountMinor - amountMinor }, true);
|
|
875
991
|
}
|
|
876
992
|
clearStaleError();
|
|
877
|
-
return addOne({ ...tender,
|
|
993
|
+
return addOne({ ...tender, amountMinor: pickMinor, changeMinor: tender.tenderedMinor - pickMinor }, true,
|
|
994
|
+
pickMinor !== tender.amountMinor ? { minor: pickMinor - tender.amountMinor } : undefined);
|
|
878
995
|
},
|
|
879
996
|
setTenderStatus(paymentId: string, status: 'authorized' | 'captured' | 'failed'): boolean {
|
|
880
997
|
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return false; }
|
|
881
998
|
if (locked()) return false;
|
|
882
999
|
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
883
1000
|
if (payment && countedLeg(payment)) { setError(AFTER_CLOSE_PAYMENTS_CHANGED); return false; }
|
|
884
|
-
|
|
1001
|
+
// S3: a capture stamps the capturing tender's session on a leg that has none yet.
|
|
1002
|
+
const changed = status === 'captured'
|
|
1003
|
+
? builderNow.current.setPaymentStatus(paymentId, status, new Date().toISOString(), legSessionId())
|
|
1004
|
+
: builderNow.current.setPaymentStatus(paymentId, status);
|
|
885
1005
|
// With no live leg left, the sale can change again: SALE_HAS_PAYMENT goes, any other error stays.
|
|
886
1006
|
if (changed && status === 'failed' && !liveLeg()) setError((current) => current === SALE_HAS_PAYMENT ? null : current);
|
|
1007
|
+
// A leg moved, so the due changed: a stale NOTHING_DUE goes (row 502).
|
|
1008
|
+
if (changed) setError((current) => current === NOTHING_DUE ? null : current);
|
|
887
1009
|
return changed;
|
|
888
1010
|
},
|
|
889
|
-
/** The leg stays in order.payments as voided and counts nothing; removeTender
|
|
1011
|
+
/** The leg stays in order.payments as voided and counts nothing; removeTender removes only a leg that took no money. Refused on the receipt. */
|
|
890
1012
|
voidTender(paymentId: string): boolean {
|
|
891
1013
|
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return false; } // a finished sale's legs stay
|
|
892
1014
|
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
@@ -894,6 +1016,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
894
1016
|
if (payment?.locked) return false;
|
|
895
1017
|
if (locked()) return false;
|
|
896
1018
|
if (!payment || (payment.method !== 'cash' && payment.method !== 'external') || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
|
|
1019
|
+
if (cashVoidRefusal(builderNow.current.getSnapshot(), paymentId)) { setError(VOID_LATER_CASH_FIRST); return false; }
|
|
897
1020
|
builderNow.current.setPaymentStatus(paymentId, 'voided');
|
|
898
1021
|
droppedReferences.current.delete(paymentId);
|
|
899
1022
|
clearStaleError();
|
|
@@ -907,10 +1030,16 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
907
1030
|
if (payment?.locked) return;
|
|
908
1031
|
if (locked()) return;
|
|
909
1032
|
if (!payment) return;
|
|
1033
|
+
if (taken(payment)) return setError(PAYMENT_TAKEN);
|
|
910
1034
|
builderNow.current.removePayment(paymentId);
|
|
911
1035
|
droppedReferences.current.delete(paymentId);
|
|
912
1036
|
clearStaleError();
|
|
913
1037
|
},
|
|
1038
|
+
/** True when setTender keeps this payment; false for one it replaces and for an id not among the payments. Changes nothing. */
|
|
1039
|
+
tenderHeld(paymentId: string): boolean {
|
|
1040
|
+
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
1041
|
+
return !!payment && heldLeg(payment);
|
|
1042
|
+
},
|
|
914
1043
|
cancelTender() {
|
|
915
1044
|
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED);
|
|
916
1045
|
if (locked()) return;
|
|
@@ -935,8 +1064,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
935
1064
|
* another is in flight returns that call's promise, and a call on the receipt does nothing. While
|
|
936
1065
|
* `cashierRef` or `registerId` is out of bounds (shown as `error`), a call does nothing either,
|
|
937
1066
|
* unless it's the Retry of a pending completion, which was built with the options as they were.
|
|
1067
|
+
* Refused with `REGISTER_CLOSING`, changing nothing, while a close for this register is in flight (#1275).
|
|
938
1068
|
*/
|
|
939
|
-
complete: () => configError && !pending.current && !inFlight.current ? Promise.resolve()
|
|
1069
|
+
complete: () => configError && !pending.current && !inFlight.current ? Promise.resolve()
|
|
1070
|
+
: isRegisterClosing(opts.registerId) ? (setError(REGISTER_CLOSING), Promise.resolve()) : once(async () => {
|
|
940
1071
|
attempts.current++;
|
|
941
1072
|
confirm(null);
|
|
942
1073
|
if (pending.current) return deliver(pending.current);
|
|
@@ -945,7 +1076,12 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
945
1076
|
if (snapshot.payments.some(isInMotion)) { setSaving(false); setError(PAYMENT_IN_MOTION); return; }
|
|
946
1077
|
if (couponsUnpriced()) { setSaving(false); setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING); return; }
|
|
947
1078
|
// Failed and voided legs stay on the screen's ledger but are never sent: only captured money is the sale's.
|
|
948
|
-
|
|
1079
|
+
// A leg with no takenAt yet (setTender's pre-filled one) was taken now; store, reopened and resumed pre-4.2 legs keep what they have.
|
|
1080
|
+
// Only this copy is stamped, never the builder, so a retry (pending.current) keeps this attempt's instant.
|
|
1081
|
+
const completedAt = new Date().toISOString(), sessionId = legSessionId();
|
|
1082
|
+
const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid)
|
|
1083
|
+
.map((payment) => payment.takenAt === undefined && !payment.locked && !payment.reopened && !resumedTakenIds.current.includes(payment.id)
|
|
1084
|
+
? { ...payment, takenAt: completedAt, ...(sessionId !== undefined && payment.sessionId === undefined ? { sessionId } : {}) } : payment) };
|
|
949
1085
|
const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id))
|
|
950
1086
|
.map((payment) => ({ code: 'payment_reference_dropped' as const, paymentId: payment.id }));
|
|
951
1087
|
let posOrder: PosOrder;
|
|
@@ -1001,21 +1137,53 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
1001
1137
|
* save still in flight carries on in the background, a throw logged at error) and starts the new
|
|
1002
1138
|
* sale outright — from the receipt, or an idle cart, there's nothing pending to abandon. Abandoning
|
|
1003
1139
|
* clears the screen, never the record (the Front desk, 2026-09-25). `newSale()` never deletes,
|
|
1004
|
-
* updates or requeues `pos_orders` itself.
|
|
1140
|
+
* updates or requeues `pos_orders` itself. An unfinished sale that still holds a taken payment is refused
|
|
1141
|
+
* with SALE_PARTLY_PAID, changing nothing, as `closeSale` refuses it; the receipt and a confirmed stored
|
|
1142
|
+
* pending completion are unchanged.
|
|
1143
|
+
* An unfinished sale with an unlocked leg in motion refuses with SALE_CARD_IN_PROGRESS, changing nothing.
|
|
1144
|
+
*/
|
|
1145
|
+
newSale() {
|
|
1146
|
+
if (stageNow.current.kind !== 'receipt' && !inFlight.current && !pending.current && builderNow.current.getSnapshot().payments.some((p) => !p.locked && isInMotion(p))) return setError(SALE_CARD_IN_PROGRESS);
|
|
1147
|
+
if (stageNow.current.kind !== 'receipt' && !inFlight.current && !pending.current && holdsTakenPayment()) return setError(SALE_PARTLY_PAID);
|
|
1148
|
+
resetSale();
|
|
1149
|
+
},
|
|
1150
|
+
/**
|
|
1151
|
+
* S3: the live sale's legs its session counts now and no stored order counts yet, for `useRegisterSession`'s
|
|
1152
|
+
* `liveSale`: captured till legs stamped with a session, not reopened and not counted by an after-close sale's closure
|
|
1153
|
+
* (`sessionTakenLegs`, the rule a parked draft's legs follow). `[]` on the receipt, whose stored order counts them.
|
|
1154
|
+
* `cashRoundings` are the sale's cash rounding entries on those legs, copied, counted on the Z with them (#1281).
|
|
1155
|
+
* `saving` is true while a completion is in flight or pending, including after a failed save, and while a
|
|
1156
|
+
* `park()` or `resume()` is in flight.
|
|
1157
|
+
*/
|
|
1158
|
+
registerView(): { takenLegs: Payment[]; saving: boolean; cashRoundings: CashRounding[] } {
|
|
1159
|
+
const snapshot = builderNow.current.getSnapshot();
|
|
1160
|
+
const takenLegs = stageNow.current.kind === 'receipt' ? [] : sessionTakenLegs(snapshot.payments, countedLeg);
|
|
1161
|
+
const taken = new Set(takenLegs.map((leg) => leg.id));
|
|
1162
|
+
return {
|
|
1163
|
+
takenLegs,
|
|
1164
|
+
saving: inFlight.current !== null || pending.current !== null || moving.current > 0,
|
|
1165
|
+
cashRoundings: (snapshot.cashRoundings ?? []).filter((entry) => taken.has(entry.paymentId)).map((entry) => ({ ...entry })),
|
|
1166
|
+
};
|
|
1167
|
+
},
|
|
1168
|
+
/**
|
|
1169
|
+
* Parks the cart in `drafts`; resolves to a refusal message, or null once parked.
|
|
1170
|
+
* Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
|
|
1005
1171
|
*/
|
|
1006
|
-
newSale() { resetSale(); },
|
|
1007
|
-
/** Parks the cart in `drafts`; resolves to a refusal message, or null once parked. */
|
|
1008
1172
|
async park(): Promise<string | null> {
|
|
1009
1173
|
if (locked()) return SALE_SAVING;
|
|
1010
|
-
if (
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1174
|
+
if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
|
|
1175
|
+
moving.current++;
|
|
1176
|
+
try {
|
|
1177
|
+
if (!opts.drafts) throw new Error('useSale: park() needs the drafts option');
|
|
1178
|
+
if (stageNow.current.kind !== 'cart') return 'Finish or cancel the payment before parking the sale';
|
|
1179
|
+
const builder = builderNow.current;
|
|
1180
|
+
const snapshot = builder.getSnapshot();
|
|
1181
|
+
if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return 'There is nothing to park';
|
|
1182
|
+
const refused = await writeParked(opts.drafts, snapshot); if (refused) return refused;
|
|
1183
|
+
if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
|
|
1184
|
+
resetSale();
|
|
1185
|
+
return null;
|
|
1186
|
+
} finally { moving.current--; }
|
|
1019
1187
|
},
|
|
1020
1188
|
/** Whether the live sale or a parked draft holds this store order; unreadable drafts do not count. */
|
|
1021
1189
|
async holdsStoreOrder(orderId: string): Promise<boolean> {
|
|
@@ -1029,12 +1197,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
1029
1197
|
} catch { return false; }
|
|
1030
1198
|
});
|
|
1031
1199
|
},
|
|
1032
|
-
/** Loads a reopened store order (from reopenStoreOrder) into an empty sale, or returns why not. */
|
|
1200
|
+
/** Loads a reopened store order (from reopenStoreOrder) into an empty sale, or returns why not; refused with SALE_PARTLY_PAID while the live sale holds a taken payment. */
|
|
1033
1201
|
openStoreOrder(order: Order): string | null {
|
|
1034
1202
|
if (locked()) return SALE_SAVING;
|
|
1035
1203
|
if (!order.storeOrder) throw new Error('useSale: openStoreOrder() takes a reopened store order');
|
|
1036
1204
|
const liveSnapshot = builderNow.current.getSnapshot();
|
|
1037
1205
|
if (stageNow.current.kind !== 'cart' || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return 'Park or clear the current sale first';
|
|
1206
|
+
if (holdsTakenPayment()) return SALE_PARTLY_PAID;
|
|
1038
1207
|
if (order.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That order is in another currency';
|
|
1039
1208
|
const restoredTax = contextFor(order.customer && !customerRefusal(order.customer) ? order.customer : null);
|
|
1040
1209
|
const builder = restoreOrderDraft(order, { currency: settings.currency, taxContext: restoredTax.taxContext });
|
|
@@ -1043,95 +1212,112 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
1043
1212
|
resetSale(null, builder, restoredTax);
|
|
1044
1213
|
return null;
|
|
1045
1214
|
},
|
|
1046
|
-
/**
|
|
1215
|
+
/**
|
|
1216
|
+
* Resumes a draft into an empty cart; resolves to a refusal message, or null once resumed; refused with SALE_PARTLY_PAID while the live sale holds a taken payment.
|
|
1217
|
+
* Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
|
|
1218
|
+
*/
|
|
1047
1219
|
async resume(draftId: string, options?: { keepParkedPrices?: boolean }): Promise<string | null> {
|
|
1048
1220
|
if (locked()) return SALE_SAVING;
|
|
1049
|
-
if (
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1221
|
+
if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
|
|
1222
|
+
moving.current++;
|
|
1223
|
+
try {
|
|
1224
|
+
if (!opts.drafts) throw new Error('useSale: resume() needs the drafts option');
|
|
1225
|
+
const live = builderNow.current;
|
|
1226
|
+
const liveSnapshot = live.getSnapshot();
|
|
1227
|
+
if (stageNow.current.kind !== 'cart' || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return 'Park or clear the current sale first';
|
|
1228
|
+
if (holdsTakenPayment()) return SALE_PARTLY_PAID;
|
|
1229
|
+
const doc = await opts.drafts.findOne(draftId).exec();
|
|
1230
|
+
if (!doc) return 'That parked sale is no longer there';
|
|
1231
|
+
const saved: Order = JSON.parse(doc.toJSON().data);
|
|
1232
|
+
if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That parked sale is in another currency';
|
|
1233
|
+
// Taxed for the customer the draft restores (a refused one isn't).
|
|
1234
|
+
const restoredTax = contextFor(saved.customer && !customerRefusal(saved.customer) ? saved.customer : null);
|
|
1235
|
+
// A draft whose legs took money keeps the tax rates it was paid against (u19); otherwise class-taxed lines re-derive.
|
|
1236
|
+
// ADR-077 d3 amended 2026-11-19: parked coupon amounts, with their prices and rates, given a display row per coupon.
|
|
1237
|
+
const carriedDraft = !!saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried);
|
|
1238
|
+
const keep = !carriedDraft && !!saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length && (saved.payments ?? []).some(isLiveLeg);
|
|
1239
|
+
const builder = restoreOrderDraft(saved, { currency: settings.currency, taxContext: restoredTax.taxContext,
|
|
1240
|
+
keepTaxRates: keep || capturedMinor(saved.payments ?? []) !== 0, keepCoupons: keep });
|
|
1241
|
+
let n = 0;
|
|
1242
|
+
// A draft whose legs took money keeps the prices it was paid against (u19), as does one kept for its coupons.
|
|
1243
|
+
// A reopened store order keeps the store's prices (ADR-090 decision 3, carryover item 22).
|
|
1244
|
+
if (opts.currentPrice && !options?.keepParkedPrices && !carriedDraft && !keep && capturedMinor(saved.payments ?? []) === 0 && !saved.storeOrder) {
|
|
1245
|
+
for (const line of builder.getSnapshot().lineItems) {
|
|
1246
|
+
if (!line.variantId) continue;
|
|
1247
|
+
const price = opts.currentPrice(line.variantId);
|
|
1248
|
+
if (price !== undefined && Number.isInteger(price) && price >= 0 && price !== line.unitPriceMinor) {
|
|
1249
|
+
builder.setUnitPrice(line.id, price);
|
|
1250
|
+
n++;
|
|
1251
|
+
}
|
|
1075
1252
|
}
|
|
1076
1253
|
}
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1254
|
+
const kept = new Map<string, unknown>(), messages: string[] = [];
|
|
1255
|
+
const codes = !carriedDraft && saved.coupons?.length ? codesFor() : null;
|
|
1256
|
+
if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? 'line' : 'lines'} updated to today's price.`);
|
|
1257
|
+
if (!carriedDraft && saved.coupons?.length) {
|
|
1258
|
+
const supported = codes !== null;
|
|
1259
|
+
if (supported) await codes.beforeResume?.(discountState(builder.getSnapshot(), new Map()));
|
|
1260
|
+
if (keep) for (const { code } of saved.coupons) kept.set(code, KEPT);
|
|
1261
|
+
else for (const { code } of saved.coupons) {
|
|
1262
|
+
let reason: string | null = supported ? null : COUPONS_UNSUPPORTED;
|
|
1263
|
+
if (supported) {
|
|
1264
|
+
const result = await codes.find(code, discountState(builder.getSnapshot(), kept));
|
|
1265
|
+
if ('refusal' in result) reason = result.refusal;
|
|
1266
|
+
else {
|
|
1267
|
+
reason = codes.check(code, result.found, discountState(builder.getSnapshot(), kept));
|
|
1268
|
+
if (reason === null) try { codes.apply(builder, discountState(builder.getSnapshot(), new Map([...kept, [code, result.found]]))); kept.set(code, result.found); }
|
|
1269
|
+
catch (error) { if (error instanceof Error) reason = error.message; else throw error; }
|
|
1270
|
+
}
|
|
1094
1271
|
}
|
|
1272
|
+
if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
|
|
1095
1273
|
}
|
|
1096
|
-
if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
|
|
1097
1274
|
}
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1275
|
+
await doc.remove();
|
|
1276
|
+
if (builderNow.current !== live || live.getSnapshot() !== liveSnapshot) {
|
|
1277
|
+
await writeOrderDraft(opts.drafts, saved);
|
|
1278
|
+
return 'The sale changed while it was being resumed; resume it again';
|
|
1279
|
+
}
|
|
1280
|
+
resetSale(null, builder, restoredTax);
|
|
1281
|
+
if (builderNow.current === builder) {
|
|
1282
|
+
applied.current = kept;
|
|
1283
|
+
resumedLegIds.current = (saved.payments ?? []).filter(isLiveLeg).map((p) => p.id);
|
|
1284
|
+
// A pre-4.2 leg voided before the park carries no takenAt and holds no money the till still has: it is dropped (desk, 23 Nov).
|
|
1285
|
+
resumedTakenIds.current = builder.getSnapshot().payments.filter((p) => !p.locked && legStatus(p) === 'captured' && p.takenAt === undefined).map((p) => p.id);
|
|
1286
|
+
if (keep) { keptCoupons.current = saved.coupons; keptLegIds.current = saved.payments.filter(isLiveLeg).map((p) => p.id); }
|
|
1287
|
+
appliedWith.current = kept.size ? codes : null;
|
|
1288
|
+
generation.current++;
|
|
1289
|
+
}
|
|
1290
|
+
if (messages.length) setError(messages.join(' '));
|
|
1291
|
+
return null;
|
|
1292
|
+
} finally { moving.current--; }
|
|
1113
1293
|
},
|
|
1114
1294
|
/**
|
|
1115
1295
|
* Opens the parked draft `draftId`, or an empty sale for null (New), as a tab switch (u19, v2 cart/tabs.tsx):
|
|
1116
1296
|
* parks the current sale first when it has lines, fees or shipping (a receipt is done and is not parked).
|
|
1117
|
-
* Refused, changing nothing, while saving, for a partly paid sale (SALE_PARTLY_PAID), a payment in motion or
|
|
1297
|
+
* Refused, changing nothing, while saving, for a partly paid sale or an empty sale holding a taken payment (SALE_PARTLY_PAID), a payment in motion or
|
|
1118
1298
|
* the tender stage. Resolves to a refusal (park's, or `resume`'s for the chosen draft), or null.
|
|
1299
|
+
* Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
|
|
1119
1300
|
*/
|
|
1120
1301
|
async switchSale(draftId: string | null): Promise<string | null> {
|
|
1121
1302
|
if (locked()) return SALE_SAVING;
|
|
1122
|
-
if (
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
if (
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1303
|
+
if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
|
|
1304
|
+
moving.current++;
|
|
1305
|
+
try {
|
|
1306
|
+
if (!opts.drafts) throw new Error('useSale: switchSale() needs the drafts option');
|
|
1307
|
+
const builder = builderNow.current;
|
|
1308
|
+
const snapshot = builder.getSnapshot();
|
|
1309
|
+
if (draftId === snapshot.id) return null;
|
|
1310
|
+
if (capturedMinor(snapshot.payments.filter((payment) => !payment.locked)) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
|
|
1311
|
+
if (snapshot.payments.some(isInMotion)) return PAYMENT_IN_MOTION;
|
|
1312
|
+
if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
|
|
1313
|
+
if (stageNow.current.kind !== 'receipt' && !snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length && holdsTakenPayment()) return SALE_PARTLY_PAID;
|
|
1314
|
+
if (stageNow.current.kind !== 'receipt' && (snapshot.lineItems.length || snapshot.fees?.length || snapshot.shipping?.length)) {
|
|
1315
|
+
const refused = await writeParked(opts.drafts, snapshot); if (refused) return refused;
|
|
1316
|
+
if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
|
|
1317
|
+
}
|
|
1318
|
+
resetSale();
|
|
1319
|
+
return draftId === null ? null : await result.resume(draftId);
|
|
1320
|
+
} finally { moving.current--; }
|
|
1135
1321
|
},
|
|
1136
1322
|
/** 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.
|
|
1137
1323
|
* A reopened sale's locked store legs do not stop it closing; the store order stays reopened, as in v2. */
|