@tallyui/pos 4.2.0 → 5.1.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 +620 -166
- package/dist/index.js +1970 -1091
- package/package.json +7 -6
- package/src/index.ts +15 -12
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +64 -22
- package/src/order/order-drafts.ts +77 -25
- package/src/order/types.ts +9 -2
- package/src/order/woocommerce-tax.ts +9 -12
- package/src/outbox/http-transport.ts +16 -1
- package/src/outbox/index.ts +3 -1
- package/src/outbox/needs-admin-reason.ts +10 -0
- package/src/outbox/order-outbox.ts +27 -11
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/store-settlement.ts +136 -0
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-order-outbox.ts +54 -4
- package/src/pos-order/attention-handled.ts +2 -0
- package/src/pos-order/command.ts +31 -9
- package/src/pos-order/finalize.ts +9 -0
- package/src/pos-order/index.ts +3 -1
- package/src/pos-order/needs-attention.ts +8 -3
- package/src/pos-order/reopen.ts +9 -2
- package/src/pos-order/schema.ts +20 -2
- package/src/pos-order/store-order-left.ts +21 -0
- package/src/pos-order/store-settlement.ts +51 -0
- package/src/pos-order/types.ts +27 -1
- 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 +320 -134
- package/src/store-orders/index.ts +3 -0
- package/src/store-orders/sales-range-query.ts +18 -0
- package/src/store-orders/use-store-refunds-in-range.ts +179 -0
- package/src/tax/exact.ts +2 -10
- package/src/tender/cash-rounding.ts +57 -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/print/escpos/sinks.test-d.ts +0 -77
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, legStatus } 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, writeOffLeg } 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,7 +440,7 @@ 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' }, stamp: boolean): 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.
|
|
@@ -401,7 +448,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
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.
|
|
403
450
|
// Stamped here, never in addPayment, which the restore paths call too.
|
|
404
|
-
|
|
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 } : {}) };
|
|
405
455
|
const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor, ...takenAt,
|
|
406
456
|
...(tender.tenderedMinor !== undefined ? { tenderedMinor: tender.tenderedMinor } : {}),
|
|
407
457
|
...(tender.changeMinor !== undefined ? { changeMinor: tender.changeMinor } : {}),
|
|
@@ -409,7 +459,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
409
459
|
...(tender.methodId !== undefined ? { methodId: tender.methodId } : {}), ...(tender.status !== undefined ? { status: tender.status } : {}) } : { ...tender, ...takenAt };
|
|
410
460
|
const builder = builderNow.current;
|
|
411
461
|
const { units, ...payment } = kept;
|
|
412
|
-
const paymentId = builder.addPayment({ ...payment, ...(units && Object.keys(units).length ? { units } : {}) });
|
|
462
|
+
const paymentId = builder.addPayment({ ...payment, ...(units && Object.keys(units).length ? { units } : {}) }, rounding);
|
|
413
463
|
if (dropped) {
|
|
414
464
|
droppedReferences.current.add(paymentId);
|
|
415
465
|
setError(`${REFERENCE_DROPPED} (${dropped}); the payment is recorded without it.`);
|
|
@@ -434,8 +484,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
434
484
|
// An after-close sale's money is what its closure counted, so the sale takes and gives none (ADR-077).
|
|
435
485
|
if (tender && builderNow.current.getSnapshot().afterClose) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
|
|
436
486
|
const builder = builderNow.current;
|
|
437
|
-
for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) builder.removePayment(payment.id);
|
|
438
|
-
droppedReferences.current.clear();
|
|
487
|
+
for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) { builder.removePayment(payment.id); droppedReferences.current.delete(payment.id); }
|
|
439
488
|
setError(null);
|
|
440
489
|
if (tender) addOne(tender, false);
|
|
441
490
|
}
|
|
@@ -469,8 +518,20 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
469
518
|
else if (hungSaveTimer.current === timer) clearHungSaveTimer();
|
|
470
519
|
}, opts.hungSaveCheckMs ?? HUNG_SAVE_CHECK_MS) : null;
|
|
471
520
|
hungSaveTimer.current = timer;
|
|
521
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
522
|
+
let timedOut = false;
|
|
472
523
|
try {
|
|
473
|
-
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
|
+
]);
|
|
474
535
|
} catch (error) {
|
|
475
536
|
if (hungSaveTimer.current === timer) clearHungSaveTimer();
|
|
476
537
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -485,16 +546,19 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
485
546
|
checkStored(completion);
|
|
486
547
|
}
|
|
487
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);
|
|
488
561
|
}
|
|
489
|
-
if (hungSaveTimer.current === timer) clearHungSaveTimer();
|
|
490
|
-
if (pending.current !== completion) return;
|
|
491
|
-
pending.current = null;
|
|
492
|
-
droppedReferences.current.clear();
|
|
493
|
-
confirm(null);
|
|
494
|
-
setSaving(false);
|
|
495
|
-
setError(null); // every error goes, SALE_HAS_PAYMENT too: it is never shown on the receipt (#1059 review)
|
|
496
|
-
stageNow.current = { kind: 'receipt', order: withSentForm(completion.order, completion.posOrder), posOrder: completion.posOrder };
|
|
497
|
-
setStage(stageNow.current);
|
|
498
562
|
}
|
|
499
563
|
|
|
500
564
|
/**
|
|
@@ -510,6 +574,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
510
574
|
return inFlight.current ?? Promise.resolve();
|
|
511
575
|
}
|
|
512
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
|
+
|
|
513
580
|
function begin(method: 'cash' | 'external', options?: { session?: { id: string; sessions: RegisterSessionCollection } }) {
|
|
514
581
|
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED); // a tender gate that answers after complete()
|
|
515
582
|
if (locked()) return;
|
|
@@ -518,7 +585,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
518
585
|
if (couponsUnpriced()) return setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING);
|
|
519
586
|
if (afterCloseChanged(current)) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
|
|
520
587
|
tenderSession.current ??= { session: options?.session ?? opts.session }; // a repeat call mid-tender keeps the pin
|
|
521
|
-
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);
|
|
522
589
|
if (current.afterClose) setTender(null); // its legs are all counted
|
|
523
590
|
else if (heldMinor === 0) setTender(method === 'external' ? { method, amountMinor: current.totalMinor } : null);
|
|
524
591
|
else setTender(method === 'external' && current.totalMinor - heldMinor > 0 ? { method, amountMinor: current.totalMinor - heldMinor } : null);
|
|
@@ -654,20 +721,18 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
654
721
|
const order = builderNow.current.getSnapshot();
|
|
655
722
|
const list: readonly (LineItem | ChargeLine)[] = kind === 'line' ? order.lineItems : kind === 'fee' ? order.fees ?? [] : order.shipping ?? [];
|
|
656
723
|
const index = list.findIndex((item) => item.id === id);
|
|
657
|
-
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 };
|
|
658
725
|
},
|
|
659
|
-
/** #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). */
|
|
660
727
|
restore(removal: SaleRemoval): string | null {
|
|
661
728
|
const held = editRefusal(); if (held) return held;
|
|
662
|
-
const order = builderNow.current.getSnapshot()
|
|
663
|
-
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;
|
|
664
732
|
const ids = [removal.item, ...(removal.kind === 'line' ? (removal.item as LineItem).discounts : [])].map((entry) => entry.id);
|
|
665
733
|
if ([...order.lineItems.flatMap((li) => [li, ...li.discounts]), ...order.fees ?? [], ...order.shipping ?? [], ...order.discounts, ...order.payments]
|
|
666
734
|
.some((entry) => ids.includes(entry.id))) return RESTORE_STALE; // already back
|
|
667
|
-
// A re-tax runs only as retaxFor allows it (stage and busy are refused above).
|
|
668
|
-
if (moved && (capturedMinor(order.payments) !== 0 || order.payments.some(isInMotion) || keptCodes())) return RESTORE_STALE;
|
|
669
735
|
builderNow.current.restoreItem(removal.kind, removal.item, removal.index);
|
|
670
|
-
if (moved) retax(builderNow.current.getSnapshot().customer, taxNow.current);
|
|
671
736
|
return null;
|
|
672
737
|
},
|
|
673
738
|
/** A line's discount, or the order's without a line; returns the refusal to show, or null once applied. */
|
|
@@ -758,6 +823,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
758
823
|
if (same) taxNow.current = same;
|
|
759
824
|
builderNow.current.setCustomer(customer);
|
|
760
825
|
}
|
|
826
|
+
removalEpoch.current++;
|
|
761
827
|
setError((current) => current !== null && (CUSTOMER_REFUSALS.includes(current) || current === CUSTOMER_RETAX_REFUSED || current === TAX_IDS_INVALID) ? null : current); // any other error stays
|
|
762
828
|
},
|
|
763
829
|
/**
|
|
@@ -781,6 +847,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
781
847
|
if (same) taxNow.current = same;
|
|
782
848
|
builderNow.current.setCustomer(next);
|
|
783
849
|
}
|
|
850
|
+
removalEpoch.current++;
|
|
784
851
|
setError((current) => current === ADDRESS_CHANGE_REFUSED ? null : current); // any other error stays
|
|
785
852
|
return true;
|
|
786
853
|
},
|
|
@@ -796,6 +863,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
796
863
|
if (!cleaned) { setError(TAX_IDS_INVALID); return false; }
|
|
797
864
|
const { taxIds: _taxIds, ...rest } = customer;
|
|
798
865
|
builderNow.current.setCustomer(cleaned.length ? { ...rest, taxIds: cleaned } : rest);
|
|
866
|
+
removalEpoch.current++;
|
|
799
867
|
setError((current) => current === TAX_IDS_CHANGE_REFUSED || current === TAX_IDS_INVALID ? null : current); // any other error stays
|
|
800
868
|
return true;
|
|
801
869
|
},
|
|
@@ -849,10 +917,19 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
849
917
|
});
|
|
850
918
|
},
|
|
851
919
|
setTender,
|
|
852
|
-
/** 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). */
|
|
853
|
-
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 target less the live entries on a cashRounding store, and one that reaches the whole-settle due is taken as that settle (ADR-094 item 7). */
|
|
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;
|
|
854
923
|
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return null; }
|
|
855
|
-
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 item 7 (carry): a cash part pick rounds its target less the sale's live entries, and carries amount less target.
|
|
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;
|
|
856
933
|
if (builderNow.current.getSnapshot().afterClose) { setError(AFTER_CLOSE_PAYMENTS_CHANGED); return null; }
|
|
857
934
|
const taxIdsRefused = taxIdsRefusal();
|
|
858
935
|
if (taxIdsRefused) { setError(taxIdsRefused); return null; }
|
|
@@ -863,11 +940,23 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
863
940
|
const unpaid = unpaidUnitsByLine(lineItems.map(({ id, quantity }) => ({ id, quantity, totalMinor: 0 })), heldUnitsByLine(payments));
|
|
864
941
|
if (Object.entries(tender.units).some(([id, units]) => !id || !Number.isInteger(units) || units <= 0 || !Object.hasOwn(unpaid, id) || units > unpaid[id])) return null;
|
|
865
942
|
}
|
|
943
|
+
const pickMinor = pickRule && tender.tenderedMinor !== undefined ? roundedPickTarget(tender.amountMinor, pickRule, remainderEntriesMinor(builderNow.current.getSnapshot())) : tender.amountMinor;
|
|
944
|
+
if (tender.tenderedMinor !== undefined && pickMinor === 0) return null;
|
|
866
945
|
if (tender.tenderedMinor !== undefined && (tender.method !== 'cash' || !tender.units || !Object.keys(tender.units).length
|
|
867
|
-
|| !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor <
|
|
946
|
+
|| !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor < pickMinor)) return null;
|
|
868
947
|
if (tender.tenderedMinor !== undefined) {
|
|
869
948
|
const snapshot = builderNow.current.getSnapshot();
|
|
870
949
|
if (tender.amountMinor > snapshot.balanceDueMinor - inMotionMinor(snapshot.payments)) return null;
|
|
950
|
+
// ADR-094 item 7 (promotion): a carried pick that reaches the whole-settle due is that settle, keeping its units; entry due - balance.
|
|
951
|
+
const due = snapshot.balanceDueMinor;
|
|
952
|
+
if (pickRule && pickMinor === roundedRemainder(due, remainderEntriesMinor(snapshot), pickRule)) {
|
|
953
|
+
if ((snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX + 1 && pickMinor !== due) { setError(CASH_SETTLE_LIMIT); return null; }
|
|
954
|
+
clearStaleError();
|
|
955
|
+
return addOne({ ...tender, amountMinor: pickMinor, changeMinor: tender.tenderedMinor - pickMinor }, true, pickMinor !== due ? { minor: pickMinor - due } : undefined);
|
|
956
|
+
}
|
|
957
|
+
if (pickMinor !== tender.amountMinor && (snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX) { setError(CASH_PICK_LIMIT); return null; }
|
|
958
|
+
if (rounding && opts.capabilities?.cashRounding === true && tender.method === 'cash' && inMotionMinor(snapshot.payments) > 0
|
|
959
|
+
&& nearestPayableCash(tender.amountMinor, rounding.incrementMinor) !== null) { setError(CASH_WAITS_FOR_PAYMENT); return null; }
|
|
871
960
|
}
|
|
872
961
|
if (tender.method === 'external') {
|
|
873
962
|
const snapshot = builderNow.current.getSnapshot();
|
|
@@ -876,20 +965,57 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
876
965
|
clearStaleError(); // before addOne, which sets its own message for a dropped reference
|
|
877
966
|
return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) }, true);
|
|
878
967
|
}
|
|
968
|
+
if (tender.tenderedMinor === undefined) {
|
|
969
|
+
const snapshot = builderNow.current.getSnapshot();
|
|
970
|
+
const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
|
|
971
|
+
if (due <= 0) { setError(NOTHING_DUE); return null; }
|
|
972
|
+
const entries = remainderEntriesMinor(snapshot);
|
|
973
|
+
const dueMinor = rule ? roundedRemainder(due, entries, rule) : due;
|
|
974
|
+
if (rule && settlesAtRoundedDue({ amountMinor: Math.min(tender.amountMinor, due), tenderedMinor: tender.amountMinor, balanceMinor: due, dueMinor })) {
|
|
975
|
+
const against = writeOffLeg(snapshot);
|
|
976
|
+
const roundings = snapshot.cashRoundings ?? [];
|
|
977
|
+
// 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.
|
|
978
|
+
if (roundings.length >= CASH_PICK_ENTRIES_MAX + 1 && (dueMinor > 0 ? dueMinor !== due
|
|
979
|
+
: against !== undefined && !roundings.some((entry) => entry.paymentId === against.id))) { setError(CASH_SETTLE_LIMIT); return null; }
|
|
980
|
+
clearStaleError();
|
|
981
|
+
if (dueMinor > 0) {
|
|
982
|
+
return addOne({ ...tender, amountMinor: dueMinor, tenderedMinor: tender.amountMinor, changeMinor: tender.amountMinor - dueMinor }, true, { minor: dueMinor - due });
|
|
983
|
+
}
|
|
984
|
+
// A remainder that rounds to zero closes the sale: no leg, its entry goes on writeOffLeg (ADR-094 item 1, #1365).
|
|
985
|
+
if (!against) { setError(NOTHING_TO_ROUND_AGAINST); return null; }
|
|
986
|
+
builderNow.current.addCashRounding({ paymentId: against.id, minor: -due });
|
|
987
|
+
return against.id;
|
|
988
|
+
}
|
|
989
|
+
if (tender.amountMinor === 0) return null; // only the zero-remainder settle takes nothing
|
|
990
|
+
if (rule && nearestPayableCash(tender.amountMinor, rule.incrementMinor)) { setError(CASH_NOT_PAYABLE); return null; }
|
|
991
|
+
const amountMinor = Math.min(tender.amountMinor, due);
|
|
992
|
+
if (rounding && tender.tenderedMinor === undefined && opts.capabilities?.cashRounding === true
|
|
993
|
+
&& inMotionMinor(snapshot.payments) > 0 && nearestPayableCash(amountMinor, rounding.incrementMinor) !== null) {
|
|
994
|
+
setError(CASH_WAITS_FOR_PAYMENT); return null;
|
|
995
|
+
}
|
|
996
|
+
clearStaleError();
|
|
997
|
+
return addOne({ ...tender, amountMinor, tenderedMinor: tender.amountMinor, changeMinor: tender.amountMinor - amountMinor }, true);
|
|
998
|
+
}
|
|
879
999
|
clearStaleError();
|
|
880
|
-
return addOne({ ...tender,
|
|
1000
|
+
return addOne({ ...tender, amountMinor: pickMinor, changeMinor: tender.tenderedMinor - pickMinor }, true,
|
|
1001
|
+
pickMinor !== tender.amountMinor ? { minor: pickMinor - tender.amountMinor } : undefined);
|
|
881
1002
|
},
|
|
882
1003
|
setTenderStatus(paymentId: string, status: 'authorized' | 'captured' | 'failed'): boolean {
|
|
883
1004
|
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return false; }
|
|
884
1005
|
if (locked()) return false;
|
|
885
1006
|
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
886
1007
|
if (payment && countedLeg(payment)) { setError(AFTER_CLOSE_PAYMENTS_CHANGED); return false; }
|
|
887
|
-
|
|
1008
|
+
// S3: a capture stamps the capturing tender's session on a leg that has none yet.
|
|
1009
|
+
const changed = status === 'captured'
|
|
1010
|
+
? builderNow.current.setPaymentStatus(paymentId, status, new Date().toISOString(), legSessionId())
|
|
1011
|
+
: builderNow.current.setPaymentStatus(paymentId, status);
|
|
888
1012
|
// With no live leg left, the sale can change again: SALE_HAS_PAYMENT goes, any other error stays.
|
|
889
1013
|
if (changed && status === 'failed' && !liveLeg()) setError((current) => current === SALE_HAS_PAYMENT ? null : current);
|
|
1014
|
+
// A leg moved, so the due changed: a stale NOTHING_DUE goes (row 502).
|
|
1015
|
+
if (changed) setError((current) => current === NOTHING_DUE ? null : current);
|
|
890
1016
|
return changed;
|
|
891
1017
|
},
|
|
892
|
-
/** The leg stays in order.payments as voided and counts nothing; removeTender
|
|
1018
|
+
/** The leg stays in order.payments as voided and counts nothing; removeTender removes only a leg that took no money. Refused on the receipt. */
|
|
893
1019
|
voidTender(paymentId: string): boolean {
|
|
894
1020
|
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return false; } // a finished sale's legs stay
|
|
895
1021
|
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
@@ -897,6 +1023,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
897
1023
|
if (payment?.locked) return false;
|
|
898
1024
|
if (locked()) return false;
|
|
899
1025
|
if (!payment || (payment.method !== 'cash' && payment.method !== 'external') || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
|
|
1026
|
+
if (cashVoidRefusal(builderNow.current.getSnapshot(), paymentId)) { setError(VOID_LATER_CASH_FIRST); return false; }
|
|
900
1027
|
builderNow.current.setPaymentStatus(paymentId, 'voided');
|
|
901
1028
|
droppedReferences.current.delete(paymentId);
|
|
902
1029
|
clearStaleError();
|
|
@@ -910,10 +1037,16 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
910
1037
|
if (payment?.locked) return;
|
|
911
1038
|
if (locked()) return;
|
|
912
1039
|
if (!payment) return;
|
|
1040
|
+
if (taken(payment)) return setError(PAYMENT_TAKEN);
|
|
913
1041
|
builderNow.current.removePayment(paymentId);
|
|
914
1042
|
droppedReferences.current.delete(paymentId);
|
|
915
1043
|
clearStaleError();
|
|
916
1044
|
},
|
|
1045
|
+
/** True when setTender keeps this payment; false for one it replaces and for an id not among the payments. Changes nothing. */
|
|
1046
|
+
tenderHeld(paymentId: string): boolean {
|
|
1047
|
+
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
1048
|
+
return !!payment && heldLeg(payment);
|
|
1049
|
+
},
|
|
917
1050
|
cancelTender() {
|
|
918
1051
|
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED);
|
|
919
1052
|
if (locked()) return;
|
|
@@ -938,8 +1071,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
938
1071
|
* another is in flight returns that call's promise, and a call on the receipt does nothing. While
|
|
939
1072
|
* `cashierRef` or `registerId` is out of bounds (shown as `error`), a call does nothing either,
|
|
940
1073
|
* unless it's the Retry of a pending completion, which was built with the options as they were.
|
|
1074
|
+
* Refused with `REGISTER_CLOSING`, changing nothing, while a close for this register is in flight (#1275).
|
|
941
1075
|
*/
|
|
942
|
-
complete: () => configError && !pending.current && !inFlight.current ? Promise.resolve()
|
|
1076
|
+
complete: () => configError && !pending.current && !inFlight.current ? Promise.resolve()
|
|
1077
|
+
: isRegisterClosing(opts.registerId) ? (setError(REGISTER_CLOSING), Promise.resolve()) : once(async () => {
|
|
943
1078
|
attempts.current++;
|
|
944
1079
|
confirm(null);
|
|
945
1080
|
if (pending.current) return deliver(pending.current);
|
|
@@ -948,11 +1083,12 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
948
1083
|
if (snapshot.payments.some(isInMotion)) { setSaving(false); setError(PAYMENT_IN_MOTION); return; }
|
|
949
1084
|
if (couponsUnpriced()) { setSaving(false); setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING); return; }
|
|
950
1085
|
// Failed and voided legs stay on the screen's ledger but are never sent: only captured money is the sale's.
|
|
951
|
-
// A leg with no takenAt yet (setTender's pre-filled one) was taken now; store and
|
|
1086
|
+
// 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.
|
|
952
1087
|
// Only this copy is stamped, never the builder, so a retry (pending.current) keeps this attempt's instant.
|
|
953
|
-
const completedAt = new Date().toISOString();
|
|
1088
|
+
const completedAt = new Date().toISOString(), sessionId = legSessionId();
|
|
954
1089
|
const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid)
|
|
955
|
-
.map((payment) => payment.takenAt === undefined && !payment.locked && !payment.reopened
|
|
1090
|
+
.map((payment) => payment.takenAt === undefined && !payment.locked && !payment.reopened && !resumedTakenIds.current.includes(payment.id)
|
|
1091
|
+
? { ...payment, takenAt: completedAt, ...(sessionId !== undefined && payment.sessionId === undefined ? { sessionId } : {}) } : payment) };
|
|
956
1092
|
const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id))
|
|
957
1093
|
.map((payment) => ({ code: 'payment_reference_dropped' as const, paymentId: payment.id }));
|
|
958
1094
|
let posOrder: PosOrder;
|
|
@@ -1008,21 +1144,53 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
1008
1144
|
* save still in flight carries on in the background, a throw logged at error) and starts the new
|
|
1009
1145
|
* sale outright — from the receipt, or an idle cart, there's nothing pending to abandon. Abandoning
|
|
1010
1146
|
* clears the screen, never the record (the Front desk, 2026-09-25). `newSale()` never deletes,
|
|
1011
|
-
* updates or requeues `pos_orders` itself.
|
|
1147
|
+
* updates or requeues `pos_orders` itself. An unfinished sale that still holds a taken payment is refused
|
|
1148
|
+
* with SALE_PARTLY_PAID, changing nothing, as `closeSale` refuses it; the receipt and a confirmed stored
|
|
1149
|
+
* pending completion are unchanged.
|
|
1150
|
+
* An unfinished sale with an unlocked leg in motion refuses with SALE_CARD_IN_PROGRESS, changing nothing.
|
|
1151
|
+
*/
|
|
1152
|
+
newSale() {
|
|
1153
|
+
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);
|
|
1154
|
+
if (stageNow.current.kind !== 'receipt' && !inFlight.current && !pending.current && holdsTakenPayment()) return setError(SALE_PARTLY_PAID);
|
|
1155
|
+
resetSale();
|
|
1156
|
+
},
|
|
1157
|
+
/**
|
|
1158
|
+
* S3: the live sale's legs its session counts now and no stored order counts yet, for `useRegisterSession`'s
|
|
1159
|
+
* `liveSale`: captured till legs stamped with a session, not reopened and not counted by an after-close sale's closure
|
|
1160
|
+
* (`sessionTakenLegs`, the rule a parked draft's legs follow). `[]` on the receipt, whose stored order counts them.
|
|
1161
|
+
* `cashRoundings` are the sale's cash rounding entries on those legs, copied, counted on the Z with them (#1281).
|
|
1162
|
+
* `saving` is true while a completion is in flight or pending, including after a failed save, and while a
|
|
1163
|
+
* `park()` or `resume()` is in flight.
|
|
1164
|
+
*/
|
|
1165
|
+
registerView(): { takenLegs: Payment[]; saving: boolean; cashRoundings: CashRounding[] } {
|
|
1166
|
+
const snapshot = builderNow.current.getSnapshot();
|
|
1167
|
+
const takenLegs = stageNow.current.kind === 'receipt' ? [] : sessionTakenLegs(snapshot.payments, countedLeg);
|
|
1168
|
+
const taken = new Set(takenLegs.map((leg) => leg.id));
|
|
1169
|
+
return {
|
|
1170
|
+
takenLegs,
|
|
1171
|
+
saving: inFlight.current !== null || pending.current !== null || moving.current > 0,
|
|
1172
|
+
cashRoundings: (snapshot.cashRoundings ?? []).filter((entry) => taken.has(entry.paymentId)).map((entry) => ({ ...entry })),
|
|
1173
|
+
};
|
|
1174
|
+
},
|
|
1175
|
+
/**
|
|
1176
|
+
* Parks the cart in `drafts`; resolves to a refusal message, or null once parked.
|
|
1177
|
+
* Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
|
|
1012
1178
|
*/
|
|
1013
|
-
newSale() { resetSale(); },
|
|
1014
|
-
/** Parks the cart in `drafts`; resolves to a refusal message, or null once parked. */
|
|
1015
1179
|
async park(): Promise<string | null> {
|
|
1016
1180
|
if (locked()) return SALE_SAVING;
|
|
1017
|
-
if (
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1181
|
+
if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
|
|
1182
|
+
moving.current++;
|
|
1183
|
+
try {
|
|
1184
|
+
if (!opts.drafts) throw new Error('useSale: park() needs the drafts option');
|
|
1185
|
+
if (stageNow.current.kind !== 'cart') return 'Finish or cancel the payment before parking the sale';
|
|
1186
|
+
const builder = builderNow.current;
|
|
1187
|
+
const snapshot = builder.getSnapshot();
|
|
1188
|
+
if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return 'There is nothing to park';
|
|
1189
|
+
const refused = await writeParked(opts.drafts, snapshot); if (refused) return refused;
|
|
1190
|
+
if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
|
|
1191
|
+
resetSale();
|
|
1192
|
+
return null;
|
|
1193
|
+
} finally { moving.current--; }
|
|
1026
1194
|
},
|
|
1027
1195
|
/** Whether the live sale or a parked draft holds this store order; unreadable drafts do not count. */
|
|
1028
1196
|
async holdsStoreOrder(orderId: string): Promise<boolean> {
|
|
@@ -1036,12 +1204,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
1036
1204
|
} catch { return false; }
|
|
1037
1205
|
});
|
|
1038
1206
|
},
|
|
1039
|
-
/** Loads a reopened store order (from reopenStoreOrder) into an empty sale, or returns why not. */
|
|
1207
|
+
/** 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. */
|
|
1040
1208
|
openStoreOrder(order: Order): string | null {
|
|
1041
1209
|
if (locked()) return SALE_SAVING;
|
|
1042
1210
|
if (!order.storeOrder) throw new Error('useSale: openStoreOrder() takes a reopened store order');
|
|
1043
1211
|
const liveSnapshot = builderNow.current.getSnapshot();
|
|
1044
1212
|
if (stageNow.current.kind !== 'cart' || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return 'Park or clear the current sale first';
|
|
1213
|
+
if (holdsTakenPayment()) return SALE_PARTLY_PAID;
|
|
1045
1214
|
if (order.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That order is in another currency';
|
|
1046
1215
|
const restoredTax = contextFor(order.customer && !customerRefusal(order.customer) ? order.customer : null);
|
|
1047
1216
|
const builder = restoreOrderDraft(order, { currency: settings.currency, taxContext: restoredTax.taxContext });
|
|
@@ -1050,95 +1219,112 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
1050
1219
|
resetSale(null, builder, restoredTax);
|
|
1051
1220
|
return null;
|
|
1052
1221
|
},
|
|
1053
|
-
/**
|
|
1222
|
+
/**
|
|
1223
|
+
* 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.
|
|
1224
|
+
* Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
|
|
1225
|
+
*/
|
|
1054
1226
|
async resume(draftId: string, options?: { keepParkedPrices?: boolean }): Promise<string | null> {
|
|
1055
1227
|
if (locked()) return SALE_SAVING;
|
|
1056
|
-
if (
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1228
|
+
if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
|
|
1229
|
+
moving.current++;
|
|
1230
|
+
try {
|
|
1231
|
+
if (!opts.drafts) throw new Error('useSale: resume() needs the drafts option');
|
|
1232
|
+
const live = builderNow.current;
|
|
1233
|
+
const liveSnapshot = live.getSnapshot();
|
|
1234
|
+
if (stageNow.current.kind !== 'cart' || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return 'Park or clear the current sale first';
|
|
1235
|
+
if (holdsTakenPayment()) return SALE_PARTLY_PAID;
|
|
1236
|
+
const doc = await opts.drafts.findOne(draftId).exec();
|
|
1237
|
+
if (!doc) return 'That parked sale is no longer there';
|
|
1238
|
+
const saved: Order = JSON.parse(doc.toJSON().data);
|
|
1239
|
+
if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That parked sale is in another currency';
|
|
1240
|
+
// Taxed for the customer the draft restores (a refused one isn't).
|
|
1241
|
+
const restoredTax = contextFor(saved.customer && !customerRefusal(saved.customer) ? saved.customer : null);
|
|
1242
|
+
// A draft whose legs took money keeps the tax rates it was paid against (u19); otherwise class-taxed lines re-derive.
|
|
1243
|
+
// ADR-077 d3 amended 2026-11-19: parked coupon amounts, with their prices and rates, given a display row per coupon.
|
|
1244
|
+
const carriedDraft = !!saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried);
|
|
1245
|
+
const keep = !carriedDraft && !!saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length && (saved.payments ?? []).some(isLiveLeg);
|
|
1246
|
+
const builder = restoreOrderDraft(saved, { currency: settings.currency, taxContext: restoredTax.taxContext,
|
|
1247
|
+
keepTaxRates: keep || capturedMinor(saved.payments ?? []) !== 0, keepCoupons: keep });
|
|
1248
|
+
let n = 0;
|
|
1249
|
+
// A draft whose legs took money keeps the prices it was paid against (u19), as does one kept for its coupons.
|
|
1250
|
+
// A reopened store order keeps the store's prices (ADR-090 decision 3, carryover item 22).
|
|
1251
|
+
if (opts.currentPrice && !options?.keepParkedPrices && !carriedDraft && !keep && capturedMinor(saved.payments ?? []) === 0 && !saved.storeOrder) {
|
|
1252
|
+
for (const line of builder.getSnapshot().lineItems) {
|
|
1253
|
+
if (!line.variantId) continue;
|
|
1254
|
+
const price = opts.currentPrice(line.variantId);
|
|
1255
|
+
if (price !== undefined && Number.isInteger(price) && price >= 0 && price !== line.unitPriceMinor) {
|
|
1256
|
+
builder.setUnitPrice(line.id, price);
|
|
1257
|
+
n++;
|
|
1258
|
+
}
|
|
1082
1259
|
}
|
|
1083
1260
|
}
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1261
|
+
const kept = new Map<string, unknown>(), messages: string[] = [];
|
|
1262
|
+
const codes = !carriedDraft && saved.coupons?.length ? codesFor() : null;
|
|
1263
|
+
if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? 'line' : 'lines'} updated to today's price.`);
|
|
1264
|
+
if (!carriedDraft && saved.coupons?.length) {
|
|
1265
|
+
const supported = codes !== null;
|
|
1266
|
+
if (supported) await codes.beforeResume?.(discountState(builder.getSnapshot(), new Map()));
|
|
1267
|
+
if (keep) for (const { code } of saved.coupons) kept.set(code, KEPT);
|
|
1268
|
+
else for (const { code } of saved.coupons) {
|
|
1269
|
+
let reason: string | null = supported ? null : COUPONS_UNSUPPORTED;
|
|
1270
|
+
if (supported) {
|
|
1271
|
+
const result = await codes.find(code, discountState(builder.getSnapshot(), kept));
|
|
1272
|
+
if ('refusal' in result) reason = result.refusal;
|
|
1273
|
+
else {
|
|
1274
|
+
reason = codes.check(code, result.found, discountState(builder.getSnapshot(), kept));
|
|
1275
|
+
if (reason === null) try { codes.apply(builder, discountState(builder.getSnapshot(), new Map([...kept, [code, result.found]]))); kept.set(code, result.found); }
|
|
1276
|
+
catch (error) { if (error instanceof Error) reason = error.message; else throw error; }
|
|
1277
|
+
}
|
|
1101
1278
|
}
|
|
1279
|
+
if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
|
|
1102
1280
|
}
|
|
1103
|
-
if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
|
|
1104
1281
|
}
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1282
|
+
await doc.remove();
|
|
1283
|
+
if (builderNow.current !== live || live.getSnapshot() !== liveSnapshot) {
|
|
1284
|
+
await writeOrderDraft(opts.drafts, saved);
|
|
1285
|
+
return 'The sale changed while it was being resumed; resume it again';
|
|
1286
|
+
}
|
|
1287
|
+
resetSale(null, builder, restoredTax);
|
|
1288
|
+
if (builderNow.current === builder) {
|
|
1289
|
+
applied.current = kept;
|
|
1290
|
+
resumedLegIds.current = (saved.payments ?? []).filter(isLiveLeg).map((p) => p.id);
|
|
1291
|
+
// 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).
|
|
1292
|
+
resumedTakenIds.current = builder.getSnapshot().payments.filter((p) => !p.locked && legStatus(p) === 'captured' && p.takenAt === undefined).map((p) => p.id);
|
|
1293
|
+
if (keep) { keptCoupons.current = saved.coupons; keptLegIds.current = saved.payments.filter(isLiveLeg).map((p) => p.id); }
|
|
1294
|
+
appliedWith.current = kept.size ? codes : null;
|
|
1295
|
+
generation.current++;
|
|
1296
|
+
}
|
|
1297
|
+
if (messages.length) setError(messages.join(' '));
|
|
1298
|
+
return null;
|
|
1299
|
+
} finally { moving.current--; }
|
|
1120
1300
|
},
|
|
1121
1301
|
/**
|
|
1122
1302
|
* Opens the parked draft `draftId`, or an empty sale for null (New), as a tab switch (u19, v2 cart/tabs.tsx):
|
|
1123
1303
|
* parks the current sale first when it has lines, fees or shipping (a receipt is done and is not parked).
|
|
1124
|
-
* Refused, changing nothing, while saving, for a partly paid sale (SALE_PARTLY_PAID), a payment in motion or
|
|
1304
|
+
* 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
|
|
1125
1305
|
* the tender stage. Resolves to a refusal (park's, or `resume`'s for the chosen draft), or null.
|
|
1306
|
+
* Refused with `REGISTER_CLOSING` while a close for this register is in flight (#1275).
|
|
1126
1307
|
*/
|
|
1127
1308
|
async switchSale(draftId: string | null): Promise<string | null> {
|
|
1128
1309
|
if (locked()) return SALE_SAVING;
|
|
1129
|
-
if (
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
if (
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1310
|
+
if (isRegisterClosing(opts.registerId)) return REGISTER_CLOSING;
|
|
1311
|
+
moving.current++;
|
|
1312
|
+
try {
|
|
1313
|
+
if (!opts.drafts) throw new Error('useSale: switchSale() needs the drafts option');
|
|
1314
|
+
const builder = builderNow.current;
|
|
1315
|
+
const snapshot = builder.getSnapshot();
|
|
1316
|
+
if (draftId === snapshot.id) return null;
|
|
1317
|
+
if (capturedMinor(snapshot.payments.filter((payment) => !payment.locked)) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
|
|
1318
|
+
if (snapshot.payments.some(isInMotion)) return PAYMENT_IN_MOTION;
|
|
1319
|
+
if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
|
|
1320
|
+
if (stageNow.current.kind !== 'receipt' && !snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length && holdsTakenPayment()) return SALE_PARTLY_PAID;
|
|
1321
|
+
if (stageNow.current.kind !== 'receipt' && (snapshot.lineItems.length || snapshot.fees?.length || snapshot.shipping?.length)) {
|
|
1322
|
+
const refused = await writeParked(opts.drafts, snapshot); if (refused) return refused;
|
|
1323
|
+
if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
|
|
1324
|
+
}
|
|
1325
|
+
resetSale();
|
|
1326
|
+
return draftId === null ? null : await result.resume(draftId);
|
|
1327
|
+
} finally { moving.current--; }
|
|
1142
1328
|
},
|
|
1143
1329
|
/** 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.
|
|
1144
1330
|
* A reopened sale's locked store legs do not stop it closing; the store order stays reopened, as in v2. */
|