@tallyui/pos 3.20.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1005 -110
- package/dist/index.js +3156 -907
- package/package.json +6 -6
- package/src/app-settings/app-settings.ts +77 -0
- package/src/app-settings/index.ts +2 -0
- package/src/currency/currency-provider.tsx +5 -7
- package/src/currency/index.ts +1 -1
- package/src/customer/customer-patch.ts +70 -0
- package/src/customer-display/display-client.ts +11 -17
- package/src/customer-display/display-link.ts +10 -5
- package/src/customer-display/index.ts +3 -1
- package/src/customer-display/protocol.ts +1 -1
- package/src/customer-display/sale-display.ts +6 -8
- package/src/customer-display/snapshot-fallback.ts +14 -1
- package/src/customer-display/till-device.ts +62 -0
- package/src/customer-display/till-display-service.ts +44 -42
- package/src/customer-display/till-pairing.ts +20 -23
- package/src/customer-display/use-customer-display.ts +2 -1
- package/src/customer-display/use-till-pairing.ts +4 -4
- package/src/index.ts +37 -18
- package/src/order/allocate-order-discount.ts +5 -17
- package/src/order/apportion.ts +29 -0
- package/src/order/from-store-order.ts +115 -0
- package/src/order/index.ts +1 -0
- package/src/order/order-builder.ts +239 -52
- package/src/order/order-drafts.ts +45 -6
- package/src/order/order-manager.ts +2 -1
- package/src/order/tax-ids.ts +27 -0
- package/src/order/types.ts +59 -5
- package/src/order/woocommerce-tax.ts +9 -0
- package/src/outbox/index.ts +1 -1
- package/src/outbox/order-outbox.ts +138 -43
- package/src/outbox/register-outbox.ts +4 -3
- package/src/outbox/retry-delay.ts +8 -0
- package/src/outbox/use-order-outbox.ts +8 -2
- package/src/pos-order/__fixtures__/order-create-v10.json +97 -0
- package/src/pos-order/__fixtures__/order-create-v11.json +90 -0
- package/src/pos-order/__fixtures__/order-create-v12.json +95 -0
- package/src/pos-order/__fixtures__/order-create-v9.json +89 -0
- package/src/pos-order/attention-handled.ts +24 -0
- package/src/pos-order/command.ts +132 -12
- package/src/pos-order/extras-delivery.ts +14 -0
- package/src/pos-order/finalize.ts +138 -29
- package/src/pos-order/index.ts +7 -3
- package/src/pos-order/money-divergence.ts +19 -0
- package/src/pos-order/needs-attention.ts +9 -1
- package/src/pos-order/refund-due.ts +35 -0
- package/src/pos-order/reopen.ts +96 -12
- package/src/pos-order/schema.ts +35 -10
- package/src/pos-order/till-payments.ts +4 -0
- package/src/pos-order/types.ts +44 -5
- package/src/print/escpos/__fixtures__/thermal-every-node.xml +33 -0
- package/src/print/escpos/commands.ts +79 -0
- package/src/print/escpos/drawer.ts +25 -0
- package/src/print/escpos/encode.ts +1 -0
- package/src/print/escpos/index.ts +6 -1
- package/src/print/escpos/network-sinks.ts +130 -0
- package/src/print/escpos/render-escpos.ts +155 -0
- package/src/print/escpos/transport.ts +2 -1
- package/src/print/index.ts +5 -2
- package/src/print/resolve-printer.ts +46 -0
- package/src/print/types.ts +1 -1
- package/src/product/index.ts +2 -0
- package/src/product/terms.ts +42 -0
- package/src/product/tile-fields.ts +27 -0
- package/src/receipt/build-receipt-data.ts +12 -7
- package/src/receipt/carried-rows.ts +29 -0
- package/src/receipt/index.ts +1 -0
- package/src/receipt/reprint.ts +14 -8
- package/src/receipt/types.ts +3 -1
- package/src/receipt-template/default-templates.ts +3 -0
- package/src/receipt-template/template-data.ts +3 -0
- package/src/receipt-template/wcpos/build.ts +1 -0
- package/src/receipt-template/wcpos/format.ts +2 -2
- package/src/receipt-template/wcpos/from-orders.ts +6 -2
- package/src/receipt-template/wcpos/types.ts +5 -1
- package/src/register/closure-document.ts +42 -4
- package/src/register/closure-rows.ts +3 -2
- package/src/register/document-labels.ts +25 -0
- package/src/register/expected.ts +49 -10
- package/src/register/index.ts +5 -5
- package/src/register/money.ts +23 -0
- package/src/register/register-adoption.ts +6 -5
- package/src/register/register-commands.ts +4 -3
- package/src/register/schemas.ts +11 -3
- package/src/register/session-store.ts +44 -23
- package/src/register/settled-figures.ts +5 -19
- package/src/register/use-register-session.ts +18 -19
- package/src/reopen/index.ts +3 -0
- package/src/reopen/reopen-entry.ts +48 -0
- package/src/reopen/reopen-store-order.ts +78 -0
- package/src/reopen/send-order-reopen.ts +61 -0
- package/src/reports/adapters.ts +15 -7
- package/src/reports/sales-figures.ts +15 -1
- package/src/reports/types.ts +2 -0
- package/src/sale/cart.ts +4 -2
- package/src/sale/index.ts +1 -1
- package/src/sale/open-sales.ts +3 -0
- package/src/sale/use-sale.ts +388 -83
- package/src/sale/woocommerce/coupon-refetch.ts +1 -0
- package/src/sale/woocommerce/coupon-source.ts +4 -4
- package/src/sale/woocommerce/coupons.ts +6 -0
- package/src/sale/woocommerce/discount-codes.ts +1 -6
- package/src/scanner/analyze-trace.ts +86 -0
- package/src/scanner/device-scanner.ts +57 -0
- package/src/scanner/hid-scanner.ts +14 -41
- package/src/scanner/index.ts +2 -0
- package/src/scanner/serial-scanner.ts +15 -42
- package/src/scanner/use-barcode-scanner.ts +107 -5
- package/src/scanner/wedge-detector.ts +33 -15
- package/src/tax/exact.ts +1 -13
- package/src/tax/taxed-lines.ts +26 -0
- package/src/tender/index.ts +6 -1
- package/src/tender/split-units.ts +109 -0
- package/src/tender/tender-figures.ts +114 -0
- package/src/tender/tender-state.ts +105 -17
- package/src/currency/format-money-with.ts +0 -45
package/src/sale/use-sale.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
|
2
2
|
import type { RxCollection } from 'rxdb';
|
|
3
|
-
import type { ProductTraits, ServerCapabilities, StoreSettings, woocommerceTax } from '@tallyui/core';
|
|
4
|
-
import { paymentMethodOf } from '@tallyui/core';
|
|
3
|
+
import type { CustomerAddress, CustomerTaxId, ProductTraits, ServerCapabilities, StoreSettings, woocommerceTax } from '@tallyui/core';
|
|
4
|
+
import { ORDER_META_KEY_MAX, ORDER_META_MAX, paymentMethodOf } from '@tallyui/core';
|
|
5
5
|
import { canVoidLeg, capturedMinor, countsTowardPaid, inMotionMinor, isInMotion } from '../tender/payment-legs';
|
|
6
|
-
import {
|
|
6
|
+
import { heldUnitsByLine, unpaidUnitsByLine } from '../tender/split-units';
|
|
7
|
+
import { createOrderBuilder, writeOrderDraft, restoreOrderDraft, type ChargeInput, type ChargeLine, type LineItem, type OrderBuilder, type CustomerSummary, type Discount, type Order, type SentOrder } from '../order';
|
|
8
|
+
import { STORE_ORDER_REBUILD_REFUSALS } from '../order/from-store-order';
|
|
9
|
+
import { isLiveLeg } from '../order/order-builder';
|
|
10
|
+
import { cleanTaxIds, TAX_IDS_INVALID } from '../order/tax-ids';
|
|
7
11
|
import { finalizeOrder, uuidv7, type PosOrder } from '../pos-order';
|
|
8
|
-
import { MESSAGE_NAME_MAX, referenceError, referenceReason, withSentForm } from '../pos-order/finalize';
|
|
12
|
+
import { AFTER_CLOSE_PAYMENTS_CHANGED, afterCloseChanged, MESSAGE_NAME_MAX, referenceError, referenceReason, withSentForm } from '../pos-order/finalize';
|
|
9
13
|
import { CUSTOMER_REFUSALS, customerRefusal, cutText, PAYLOAD_STRING_MAX } from '../pos-order/command';
|
|
10
14
|
import { useTax, type SaleTaxContext, type SaleTaxLocation, type TaxContext } from '../tax';
|
|
11
15
|
import { recordRegisterFact, stampSession, type RegisterSessionCollection } from '../register';
|
|
@@ -27,19 +31,53 @@ export const SALE_SAVING = 'This sale is being saved. Retry to finish it.';
|
|
|
27
31
|
export const PAYMENT_IN_MOTION = 'Finish or void the payment in progress before completing the sale';
|
|
28
32
|
/**
|
|
29
33
|
* `switchSale()` and `closeSale()` refuse a sale whose legs took money (u19). v2 keeps a partly paid order's legs on
|
|
30
|
-
* switching, but a TallyUI draft keeps no tender stage, the next `startTender` replaces every leg
|
|
31
|
-
*
|
|
34
|
+
* switching, but a TallyUI draft keeps no tender stage, the next `startTender` replaces every unlocked leg but a kept
|
|
35
|
+
* paid draft's parked legs, and `resume` keeps a paid draft's parked coupons (ADR-077 d3, amended 2026-11-19): so the
|
|
36
|
+
* sale stays on the till until it is paid or its paid legs are voided.
|
|
32
37
|
*/
|
|
33
38
|
export const SALE_PARTLY_PAID = 'This sale is partly paid. Take the rest of the payment or void the paid legs first.';
|
|
34
39
|
export const SALE_IN_TENDER = 'Finish or cancel the payment before switching sales';
|
|
40
|
+
/**
|
|
41
|
+
* Line and total changes refuse with this while a till leg is live, as v2's resolveStage stills the cart (tally-woo 11c).
|
|
42
|
+
* "Cancel the payment" names the leg's button, `pos_checkout.cancel_payment` ("Cancel payment") in packages/components.
|
|
43
|
+
*/
|
|
44
|
+
export const SALE_HAS_PAYMENT = 'A payment was taken on this sale. Cancel the payment before changing the sale.';
|
|
45
|
+
/** On the receipt the finished sale refuses edits and re-tender with this; `add` starts the next sale instead (v2 #2861). */
|
|
46
|
+
export const SALE_FINISHED = 'This sale is finished. Start a new sale to change it.';
|
|
35
47
|
/** startTender and complete() refuse with this while the order's store-priced coupons are stale or being priced again (TallyUI#710). */
|
|
36
48
|
export const COUPONS_REPRICING = 'Coupon prices are being checked; try again in a moment';
|
|
49
|
+
/** Coupon changes refuse with this while a store-priced coupon is carried. */
|
|
50
|
+
export const COUPON_CARRIED = "The store refused this sale's coupon, so it is carried at the amount charged. Coupons can't be added or removed on this sale.";
|
|
51
|
+
/** Tender and completion refuse with this after a carried coupon's pricing basis changes. */
|
|
52
|
+
export const COUPON_CARRY_STALE = 'The sale changed after the store refused its coupon, so the amount carried for it no longer applies. Reopen the sale without the coupon to take payment.';
|
|
53
|
+
/** startTender refuses with this when the app's tenderGate rejects instead of answering. */
|
|
54
|
+
export const TENDER_GATE_FAILED = 'The checkout check failed, so the tender did not start';
|
|
55
|
+
/** 5.2 backlog F5: startTender shows this when a re-tax swapped the sale while the tender gate ran; the tender does not start. */
|
|
56
|
+
export const TENDER_SALE_CHANGED = 'The sale changed while the checkout check ran; start the payment again.';
|
|
37
57
|
/** #722: setCustomer's refusal of a customer whose address moves the sale's rates once they can no longer change (tender, receipt, money live); interim until #759 re-taxes like v2. */
|
|
38
58
|
export const CUSTOMER_RETAX_REFUSED = 'This customer would change the tax on this sale. To use them, cancel the payment and change the customer in the cart, or start a new order.';
|
|
59
|
+
/** Desk Q7.4 (19 Nov): setAddresses' refusal once the sale left the cart or money is live; the address changes only in the cart. */
|
|
60
|
+
export const ADDRESS_CHANGE_REFUSED = 'The address can only change in the cart. Cancel the payment to change it, or start a new order.';
|
|
61
|
+
/** ADR-092 6a: setTaxIds' refusal once the sale left the cart or money is live; the tax ids change only in the cart. */
|
|
62
|
+
export const TAX_IDS_CHANGE_REFUSED = 'Tax ids can only change in the cart. Cancel the payment to change them, or start a new order.';
|
|
63
|
+
export { TAX_IDS_INVALID } from '../order/tax-ids';
|
|
64
|
+
/** ADR-092 6d: setMeta's refusal once the sale left the cart or money is live; custom fields change only in the cart. */
|
|
65
|
+
export const META_CHANGE_REFUSED = 'Custom fields can only change in the cart. Cancel the payment to change them, or start a new order.';
|
|
66
|
+
/** ADR-092 6d: setMeta's refusal of an empty, too long or `_` key, or of a new key past ORDER_META_MAX. */
|
|
67
|
+
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
|
+
/** 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
|
+
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. */
|
|
71
|
+
export const RESTORE_STALE = 'This item can no longer be put back. Add it again.';
|
|
72
|
+
/** Taken by `removal()` before a remove; pass it to `restore()`. Hosts never build one. */
|
|
73
|
+
export type SaleRemoval = { readonly kind: 'line' | 'fee' | 'shipping'; readonly id: string; readonly item: LineItem | ChargeLine;
|
|
74
|
+
readonly index: number; readonly orderId: string; readonly taxContext: TaxContext; readonly epoch: number };
|
|
39
75
|
/** The sale's tax context and, with `taxContextFor`, the address it matched (#722). */
|
|
40
76
|
type SaleTax = { taxContext: TaxContext; location?: woocommerceTax.ResolvedTaxLocation };
|
|
41
77
|
// The start of the message addOne sets when a terminal reference is dropped; a later tender change keeps it.
|
|
42
78
|
const REFERENCE_DROPPED = "The terminal's payment reference couldn't be kept";
|
|
79
|
+
// A paid draft's code in `applied`, kept as parked with no `find` at resume: never passed to codes.apply; a re-price replaces it.
|
|
80
|
+
const KEPT = Symbol('kept coupon');
|
|
43
81
|
/**
|
|
44
82
|
* How often a hung save re-asks `isStored`, while the order is built and its save is still in flight
|
|
45
83
|
* and unconfirmed: an app whose tender has no New sale control while saving (the Front desk,
|
|
@@ -48,11 +86,22 @@ const REFERENCE_DROPPED = "The terminal's payment reference couldn't be kept";
|
|
|
48
86
|
*/
|
|
49
87
|
export const HUNG_SAVE_CHECK_MS = 5000;
|
|
50
88
|
|
|
89
|
+
/** Runs a builder call; an `Error` it throws becomes the refusal message to show, anything else is rethrown. */
|
|
90
|
+
function refusalOf<T>(run: () => T): T | string {
|
|
91
|
+
try { return run(); } catch (error) { if (error instanceof Error) return error.message; throw error; }
|
|
92
|
+
}
|
|
93
|
+
|
|
51
94
|
/** Call under a `TaxProvider`: its tax context and the settings' currency price every sale. */
|
|
52
95
|
export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscountsSequentially'>, opts: {
|
|
53
96
|
registerId: string; cashierRef: string; capabilities?: ServerCapabilities;
|
|
54
97
|
/** The platform's discount codes (ADR-077 amendment 3), e.g. woocommerceDiscountCodes.createDiscountCodes(source); without them, applyCoupon refuses with COUPONS_UNSUPPORTED. */
|
|
55
98
|
discountCodes?: SaleDiscountCodes<any>;
|
|
99
|
+
/**
|
|
100
|
+
* Awaited after startTender's own checks, before the tender starts (ADR-089 D11): resolves to a refusal to show,
|
|
101
|
+
* or null to start. Typically `(attempt) => host.dispatch('checkout.tender.start', attempt, sources)` from
|
|
102
|
+
* `@tallyui/extensions`. Without it startTender starts at once, as before; a rejection refuses with TENDER_GATE_FAILED.
|
|
103
|
+
*/
|
|
104
|
+
tenderGate?: (attempt: { method: 'cash' | 'external' }) => Promise<string | null>;
|
|
56
105
|
/**
|
|
57
106
|
* Put on every new sale, as v2's store setting `default_customer` (or the cashier, `default_customer_is_cashier`)
|
|
58
107
|
* is on every new cart: the first sale and each one after complete, discard, park, newSale or a switch to New,
|
|
@@ -143,6 +192,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
143
192
|
const error = saving && saleError ? saleError : configError ?? saleError;
|
|
144
193
|
// The session pinned by startTender for this tender (`undefined` inside: none); null until a tender starts.
|
|
145
194
|
const tenderSession = useRef<{ session: typeof opts.session } | null>(null);
|
|
195
|
+
const tenderGatePending = useRef(false);
|
|
146
196
|
// The ids, at the tender, of payments whose terminal references were dropped.
|
|
147
197
|
const droppedReferences = useRef<Set<string>>(new Set());
|
|
148
198
|
// The pending completion isStored confirmed stored after its save failed; `canContinue` mirrors it for
|
|
@@ -178,12 +228,29 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
178
228
|
}
|
|
179
229
|
/** locked() without its error. */
|
|
180
230
|
function busy() { return !!(inFlight.current || pending.current); }
|
|
231
|
+
/** Line and total changes' guard: SALE_SAVING while busy, SALE_FINISHED on the receipt, SALE_HAS_PAYMENT while an unlocked leg is captured or in motion; sets it as the error. */
|
|
232
|
+
function editRefusal(): string | null {
|
|
233
|
+
const refusal = busy() ? SALE_SAVING : stageNow.current.kind === 'receipt' ? SALE_FINISHED : liveLeg() ? SALE_HAS_PAYMENT : null;
|
|
234
|
+
if (refusal) setError(refusal);
|
|
235
|
+
return refusal;
|
|
236
|
+
}
|
|
237
|
+
/** An unlocked leg on the live sale is captured or in motion: its total must not move. */
|
|
238
|
+
function liveLeg() {
|
|
239
|
+
return builderNow.current.getSnapshot().payments.some(isLiveLeg);
|
|
240
|
+
}
|
|
241
|
+
function keptCodes() { return [...applied.current.values()].includes(KEPT); } // apply, remove and re-tax wait for the re-price
|
|
181
242
|
// TallyUI#710: the coupon re-price in flight (at most one), the count of coupon changes that discards its result,
|
|
182
243
|
// and the order snapshot a transient refusal or a throw stopped it on, with that reason.
|
|
183
244
|
const repricing = useRef<Promise<string | null> | null>(null);
|
|
184
245
|
const [couponsRepricing, setCouponsRepricing] = useState(false);
|
|
185
246
|
const generation = useRef(0);
|
|
247
|
+
const saleEpoch = useRef(0); // #1095: bumped by every resetSale (new sale, park, resume, switch); a removal from an older epoch is stale.
|
|
186
248
|
const stopped = useRef<{ order: Order; reason: string } | null>(null);
|
|
249
|
+
const keptCoupons = useRef<Order['coupons']>(undefined); // the draft's coupons while KEPT placeholders hold; park writes them stale
|
|
250
|
+
const keptLegIds = useRef<readonly string[]>([]); // the kept draft's parked live legs, held while KEPT placeholders hold
|
|
251
|
+
// An after-close sale's closure counted these legs, and finalize refuses any change to them: they are held like a locked leg.
|
|
252
|
+
function countedLeg(p: { id: string }) { return !!builderNow.current.getSnapshot().afterClose?.payments.some((leg) => leg.id === p.id); }
|
|
253
|
+
function heldLeg(p: Order['payments'][number]) { return !!p.locked || countedLeg(p) || (keptCodes() && isLiveLeg(p) && keptLegIds.current.includes(p.id)); }
|
|
187
254
|
/** Prices the accepted codes again, as resume() checks them, on the live builder; resolves to the error it set, or null. */
|
|
188
255
|
function reprice(): Promise<string | null> {
|
|
189
256
|
if (repricing.current) return repricing.current;
|
|
@@ -210,6 +277,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
210
277
|
asked = b.getSnapshot();
|
|
211
278
|
codes.apply(b, discountState(asked, kept));
|
|
212
279
|
applied.current = kept;
|
|
280
|
+
keptCoupons.current = undefined; keptLegIds.current = [];
|
|
213
281
|
if (!kept.size) appliedWith.current = null;
|
|
214
282
|
const message = messages.length ? messages.join(' ') : null;
|
|
215
283
|
// A refusal only a re-price could have set goes once the codes are priced.
|
|
@@ -223,6 +291,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
223
291
|
}
|
|
224
292
|
/** startTender's and complete()'s check: the live order's coupon prices are stale or being priced again. */
|
|
225
293
|
function couponsUnpriced() { return !!(builderNow.current.getSnapshot().couponPricesStale || repricing.current); }
|
|
294
|
+
function carriedCoupon() { return builderNow.current.getSnapshot().coupons?.some((coupon) => coupon.carried); }
|
|
226
295
|
// newSale()'s body (see its doc comment for the guards): `newSale()` is `resetSale()`, on the default customer.
|
|
227
296
|
function resetSale(customer: CustomerSummary | null = defaulted(), restored?: OrderBuilder, restoredTax?: SaleTax) {
|
|
228
297
|
if (inFlight.current && !pending.current) return setError(SALE_SAVING);
|
|
@@ -242,8 +311,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
242
311
|
builderNow.current = next;
|
|
243
312
|
taxNow.current = tax;
|
|
244
313
|
applied.current.clear();
|
|
314
|
+
keptCoupons.current = undefined; keptLegIds.current = [];
|
|
245
315
|
appliedWith.current = null;
|
|
246
316
|
generation.current++;
|
|
317
|
+
saleEpoch.current++;
|
|
247
318
|
setBuilder(next);
|
|
248
319
|
setOrder(next.getSnapshot());
|
|
249
320
|
// Live at once, so a resume() in the same tick (switchSale) sees the cart before the next render.
|
|
@@ -257,10 +328,19 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
257
328
|
}, [rendered]);
|
|
258
329
|
// TallyUI#710: a rendered order whose store-priced coupons went stale prices them again, one re-price at a time. Checked
|
|
259
330
|
// on every render, so it runs again when one ends (the sale may have changed meanwhile), never on a snapshot one stopped on.
|
|
331
|
+
// #1059 review: never while a leg is live, as a re-price moves the total. The coupons then stay stale, so startTender and
|
|
332
|
+
// complete() keep refusing with COUPONS_REPRICING (couponsUnpriced) and finalize's stale check stays the backstop, until
|
|
333
|
+
// the leg is voided, removed or fails; that changes the order, and this effect prices them again.
|
|
260
334
|
useEffect(() => {
|
|
261
|
-
if (order.couponPricesStale &&
|
|
262
|
-
&& stageNow.current.kind !== 'receipt' && !busy() && stopped.current?.order !== order) void reprice();
|
|
335
|
+
if (order.couponPricesStale && applied.current.size > 0 && !repricing.current
|
|
336
|
+
&& stageNow.current.kind !== 'receipt' && !busy() && !liveLeg() && stopped.current?.order !== order) void (appliedWith.current ? reprice() : dropKept());
|
|
263
337
|
});
|
|
338
|
+
function dropKept() { // kept coupons resumed with no discount codes: nothing can price them again
|
|
339
|
+
builderNow.current.setCoupons([], { kind: 'store-priced', priced: new Map(), basis: '' });
|
|
340
|
+
applied.current.clear();
|
|
341
|
+
keptCoupons.current = undefined; keptLegIds.current = [];
|
|
342
|
+
setError(COUPONS_UNSUPPORTED);
|
|
343
|
+
}
|
|
264
344
|
// New tax settings or currency wait until the sale is idle (an empty cart), then start a new sale keeping its customer:
|
|
265
345
|
// a sale in progress (lines, tender or receipt) finishes on the settings it started with (a money rule).
|
|
266
346
|
const idle = stage.kind === 'cart' && !order.lineItems.length && !order.fees?.length && !order.shipping?.length;
|
|
@@ -281,7 +361,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
281
361
|
* ones go stale and price again, as the basis has the customer). `applied`, the error and the stage are kept.
|
|
282
362
|
*/
|
|
283
363
|
function retax(customer: CustomerSummary | null, next: SaleTax) {
|
|
284
|
-
const snapshot = { ...builderNow.current.getSnapshot(), customer };
|
|
364
|
+
const snapshot = { ...builderNow.current.getSnapshot(), customer, ...(carriedCoupon() ? { couponPricesStale: true as const } : {}) };
|
|
285
365
|
const rebuilt = restoreOrderDraft(snapshot, { currency: snapshot.currency, taxContext: next.taxContext });
|
|
286
366
|
if (appliedWith.current && applied.current.size) appliedWith.current.apply(rebuilt, discountState(rebuilt.getSnapshot(), applied.current));
|
|
287
367
|
builderNow.current = rebuilt;
|
|
@@ -297,7 +377,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
297
377
|
const next = opts.taxContextFor?.(customer);
|
|
298
378
|
const { payments } = builderNow.current.getSnapshot();
|
|
299
379
|
if (!next || next.taxContext === taxNow.current.taxContext || stageNow.current.kind !== 'cart' || busy()
|
|
300
|
-
|| capturedMinor(payments) !== 0 || payments.some(isInMotion)) return false;
|
|
380
|
+
|| capturedMinor(payments) !== 0 || payments.some(isInMotion) || keptCodes()) return false;
|
|
301
381
|
retax(customer, next);
|
|
302
382
|
return true;
|
|
303
383
|
}
|
|
@@ -313,15 +393,20 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
313
393
|
}
|
|
314
394
|
}, []);
|
|
315
395
|
|
|
316
|
-
function addOne(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string; status?: 'pending' | 'authorized' | 'captured' }): string {
|
|
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 {
|
|
317
397
|
// A terminal reference finalize would refuse is dropped as it's entered, never the payment (the money is
|
|
318
398
|
// taken): the tender applies without it, with a message that doesn't block complete() and a
|
|
319
399
|
// localWarnings entry on the stored order naming the payment whose reference was dropped.
|
|
320
400
|
const reason = referenceReason(tender.reference);
|
|
321
401
|
const dropped = reason && (reason === 'nul' ? 'it contains a NUL character' : `it is over ${PAYLOAD_STRING_MAX} characters`);
|
|
322
|
-
const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor,
|
|
402
|
+
const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor,
|
|
403
|
+
...(tender.tenderedMinor !== undefined ? { tenderedMinor: tender.tenderedMinor } : {}),
|
|
404
|
+
...(tender.changeMinor !== undefined ? { changeMinor: tender.changeMinor } : {}),
|
|
405
|
+
...(tender.units !== undefined ? { units: tender.units } : {}),
|
|
406
|
+
...(tender.methodId !== undefined ? { methodId: tender.methodId } : {}), ...(tender.status !== undefined ? { status: tender.status } : {}) } : tender;
|
|
323
407
|
const builder = builderNow.current;
|
|
324
|
-
const
|
|
408
|
+
const { units, ...payment } = kept;
|
|
409
|
+
const paymentId = builder.addPayment({ ...payment, ...(units && Object.keys(units).length ? { units } : {}) });
|
|
325
410
|
if (dropped) {
|
|
326
411
|
droppedReferences.current.add(paymentId);
|
|
327
412
|
setError(`${REFERENCE_DROPPED} (${dropped}); the payment is recorded without it.`);
|
|
@@ -332,10 +417,21 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
332
417
|
return paymentId;
|
|
333
418
|
}
|
|
334
419
|
|
|
335
|
-
|
|
420
|
+
/** #1064: a customer's tax ids cleanTaxIds would refuse (a defaultCustomer, a restored draft) start no tender. */
|
|
421
|
+
function taxIdsRefusal(): string | null {
|
|
422
|
+
const taxIds = builderNow.current.getSnapshot().customer?.taxIds;
|
|
423
|
+
return taxIds && cleanTaxIds(taxIds) === null ? TAX_IDS_INVALID : null;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function setTender(tender: { method: 'cash' | 'external'; methodId?: string; amountMinor: number; reference?: string } | null) {
|
|
427
|
+
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED); // a finished sale's tender stays
|
|
336
428
|
if (locked()) return;
|
|
429
|
+
const taxIdsRefused = tender && taxIdsRefusal();
|
|
430
|
+
if (taxIdsRefused) return setError(taxIdsRefused);
|
|
431
|
+
// An after-close sale's money is what its closure counted, so the sale takes and gives none (ADR-077).
|
|
432
|
+
if (tender && builderNow.current.getSnapshot().afterClose) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
|
|
337
433
|
const builder = builderNow.current;
|
|
338
|
-
for (const payment of builder.getSnapshot().payments) builder.removePayment(payment.id);
|
|
434
|
+
for (const payment of builder.getSnapshot().payments) if (!heldLeg(payment)) builder.removePayment(payment.id);
|
|
339
435
|
droppedReferences.current.clear();
|
|
340
436
|
setError(null);
|
|
341
437
|
if (tender) addOne(tender);
|
|
@@ -393,7 +489,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
393
489
|
droppedReferences.current.clear();
|
|
394
490
|
confirm(null);
|
|
395
491
|
setSaving(false);
|
|
396
|
-
setError(null);
|
|
492
|
+
setError(null); // every error goes, SALE_HAS_PAYMENT too: it is never shown on the receipt (#1059 review)
|
|
397
493
|
stageNow.current = { kind: 'receipt', order: withSentForm(completion.order, completion.posOrder), posOrder: completion.posOrder };
|
|
398
494
|
setStage(stageNow.current);
|
|
399
495
|
}
|
|
@@ -411,6 +507,28 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
411
507
|
return inFlight.current ?? Promise.resolve();
|
|
412
508
|
}
|
|
413
509
|
|
|
510
|
+
function begin(method: 'cash' | 'external', options?: { session?: { id: string; sessions: RegisterSessionCollection } }) {
|
|
511
|
+
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED); // a tender gate that answers after complete()
|
|
512
|
+
if (locked()) return;
|
|
513
|
+
const current = builderNow.current.getSnapshot();
|
|
514
|
+
if (!current.lineItems.length) return;
|
|
515
|
+
if (couponsUnpriced()) return setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING);
|
|
516
|
+
if (afterCloseChanged(current)) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
|
|
517
|
+
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);
|
|
519
|
+
if (current.afterClose) setTender(null); // its legs are all counted
|
|
520
|
+
else if (heldMinor === 0) setTender(method === 'external' ? { method, amountMinor: current.totalMinor } : null);
|
|
521
|
+
else setTender(method === 'external' && current.totalMinor - heldMinor > 0 ? { method, amountMinor: current.totalMinor - heldMinor } : null);
|
|
522
|
+
stageNow.current = { kind: 'tender', method }; // 5.2 backlog F4: a same-tick setCustomer/setAddresses sees the tender
|
|
523
|
+
setStage(stageNow.current);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** park()'s and switchSale()'s draft write: kept codes with no figures (a stopped re-price) park their coupons stale, so the resume prices them (as main does). */
|
|
527
|
+
async function writeParked(drafts: NonNullable<typeof opts.drafts>, snapshot: Order): Promise<string | null> {
|
|
528
|
+
const stale = keptCodes() && !snapshot.coupons?.length;
|
|
529
|
+
if (stale && liveLeg()) return COUPONS_REPRICING; // a parked live leg would be re-priced on resume (as main refuses)
|
|
530
|
+
return writeOrderDraft(drafts, stale ? { ...snapshot, coupons: keptCoupons.current, couponPricesStale: true } : snapshot).then(() => null);
|
|
531
|
+
}
|
|
414
532
|
const result = {
|
|
415
533
|
order, stage, error, idle,
|
|
416
534
|
/** #722: the address the sale's customer is taxed by (WooCommerce's `tax_based_on`), for a "Tax based on" panel; undefined without `taxContextFor`. */
|
|
@@ -422,9 +540,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
422
540
|
saving,
|
|
423
541
|
/** The failed save's order is confirmed stored (see `isStored`): the UI also offers Continue (`continueSale()`). */
|
|
424
542
|
canContinue,
|
|
425
|
-
/** Adds the entry, as a new line or one more on its line; returns that line's id, or the refusal `error` now shows. */
|
|
543
|
+
/** Adds the entry, as a new line or one more on its line; returns that line's id, or the refusal `error` now shows. On the receipt it starts the next sale first (v2 #2861). */
|
|
426
544
|
add(entry: CatalogueEntry<any>, traits: ProductTraits<any>): { lineId: string } | string {
|
|
427
|
-
if (
|
|
545
|
+
if (stageNow.current.kind === 'receipt') {
|
|
546
|
+
resetSale();
|
|
547
|
+
if (stageNow.current.kind === 'receipt') return SALE_SAVING; // resetSale refused, with this as its error
|
|
548
|
+
}
|
|
549
|
+
const held = editRefusal(); if (held) return held;
|
|
428
550
|
const builder = builderNow.current;
|
|
429
551
|
try {
|
|
430
552
|
const known = new Set(builder.getSnapshot().lineItems.map((line) => line.id));
|
|
@@ -451,60 +573,54 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
451
573
|
return error.message;
|
|
452
574
|
}
|
|
453
575
|
},
|
|
454
|
-
setQuantity(lineId: string, quantity: number) { if (!
|
|
576
|
+
setQuantity(lineId: string, quantity: number) { if (!editRefusal()) builderNow.current.updateQuantity(lineId, quantity); },
|
|
455
577
|
/** v2's cart Split: a line of quantity N becomes N lines of 1. Returns the refusal to show (SPLIT_FIXED_DISCOUNT), or null. */
|
|
456
578
|
splitLine(lineId: string): string | null {
|
|
457
|
-
if (
|
|
579
|
+
const held = editRefusal(); if (held) return held;
|
|
458
580
|
try { builderNow.current.splitLine(lineId); return null; }
|
|
459
581
|
catch (error) { if (error instanceof RangeError) return error.message; throw error; }
|
|
460
582
|
},
|
|
461
583
|
/** ADR-075: adds a fee; returns its id or the builder's refusal. */
|
|
462
584
|
addFee(input: ChargeInput): { id: string } | string {
|
|
463
|
-
if (
|
|
464
|
-
|
|
465
|
-
|
|
585
|
+
const held = editRefusal(); if (held) return held;
|
|
586
|
+
const { storeLineId: _storeLineId, ...charge } = input;
|
|
587
|
+
return refusalOf(() => ({ id: builderNow.current.addFee(charge) }));
|
|
466
588
|
},
|
|
467
589
|
/** ADR-075: updates a fee; returns a refusal or null. */
|
|
468
590
|
updateFee(id: string, patch: Partial<ChargeInput>): string | null {
|
|
469
|
-
if (
|
|
470
|
-
|
|
471
|
-
catch (error) { if (error instanceof Error) return error.message; throw error; }
|
|
591
|
+
const held = editRefusal(); if (held) return held;
|
|
592
|
+
return refusalOf(() => { builderNow.current.updateFee(id, patch); return null; });
|
|
472
593
|
},
|
|
473
594
|
/** ADR-075: removes a fee; returns a refusal or null. */
|
|
474
595
|
removeFee(id: string): string | null {
|
|
475
|
-
if (
|
|
476
|
-
|
|
477
|
-
catch (error) { if (error instanceof Error) return error.message; throw error; }
|
|
596
|
+
const held = editRefusal(); if (held) return held;
|
|
597
|
+
return refusalOf(() => { builderNow.current.removeFee(id); return null; });
|
|
478
598
|
},
|
|
479
599
|
/** ADR-075: adds shipping; returns its id or the builder's refusal. */
|
|
480
600
|
addShipping(input: ChargeInput & { methodId?: string }): { id: string } | string {
|
|
481
|
-
if (
|
|
482
|
-
|
|
483
|
-
|
|
601
|
+
const held = editRefusal(); if (held) return held;
|
|
602
|
+
const { storeLineId: _storeLineId, ...charge } = input;
|
|
603
|
+
return refusalOf(() => ({ id: builderNow.current.addShipping(charge) }));
|
|
484
604
|
},
|
|
485
605
|
/** ADR-075: updates shipping; returns a refusal or null. */
|
|
486
606
|
updateShipping(id: string, patch: Partial<ChargeInput & { methodId?: string }>): string | null {
|
|
487
|
-
if (
|
|
488
|
-
|
|
489
|
-
catch (error) { if (error instanceof Error) return error.message; throw error; }
|
|
607
|
+
const held = editRefusal(); if (held) return held;
|
|
608
|
+
return refusalOf(() => { builderNow.current.updateShipping(id, patch); return null; });
|
|
490
609
|
},
|
|
491
610
|
/** ADR-075: removes shipping; returns a refusal or null. */
|
|
492
611
|
removeShipping(id: string): string | null {
|
|
493
|
-
if (
|
|
494
|
-
|
|
495
|
-
catch (error) { if (error instanceof Error) return error.message; throw error; }
|
|
612
|
+
const held = editRefusal(); if (held) return held;
|
|
613
|
+
return refusalOf(() => { builderNow.current.removeShipping(id); return null; });
|
|
496
614
|
},
|
|
497
615
|
/** ADR-075: adds a distinct custom product line; returns its id or the builder's refusal. */
|
|
498
616
|
addCustomLine(input: { name: string; priceMinor: number; quantity?: number; taxClass?: string; taxStatus?: 'taxable' | 'none'; sku?: string }): { id: string } | string {
|
|
499
|
-
if (
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
unitPrice: { amount: input.priceMinor, currency: madeWith.current.currency.toUpperCase() } }) };
|
|
503
|
-
} catch (error) { if (error instanceof Error) return error.message; throw error; }
|
|
617
|
+
const held = editRefusal(); if (held) return held;
|
|
618
|
+
return refusalOf(() => ({ id: builderNow.current.addLine({ ...input, custom: true, productId: `custom:${uuidv7()}`,
|
|
619
|
+
unitPrice: { amount: input.priceMinor, currency: madeWith.current.currency.toUpperCase() } }) }));
|
|
504
620
|
},
|
|
505
621
|
/** Sets a line's unit price in minor units of its own tax mode, recomputing discounts and tax; returns a refusal or null. */
|
|
506
622
|
setUnitPrice(lineId: string, amountMinor: number): string | null {
|
|
507
|
-
if (
|
|
623
|
+
const held = editRefusal(); if (held) return held;
|
|
508
624
|
try {
|
|
509
625
|
builderNow.current.setUnitPrice(lineId, amountMinor);
|
|
510
626
|
return null;
|
|
@@ -513,10 +629,47 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
513
629
|
throw error;
|
|
514
630
|
}
|
|
515
631
|
},
|
|
516
|
-
|
|
632
|
+
/**
|
|
633
|
+
* ADR-092 6b/6c: edits a cart line's `name`, `sku` or `regularUnitPriceMinor` (`null` removes it); the regular price is
|
|
634
|
+
* the "was" price that receipts print and order.create 6+ sends. Cart only; returns a refusal or null: editRefusal's
|
|
635
|
+
* refusals first (SALE_SAVING, SALE_FINISHED, SALE_HAS_PAYMENT), then LINE_EDIT_REFUSED for any other stage outside the cart.
|
|
636
|
+
*/
|
|
637
|
+
updateLine(lineId: string, patch: { name?: string; sku?: string; regularUnitPriceMinor?: number | null }): string | null {
|
|
638
|
+
const held = editRefusal(); if (held) return held;
|
|
639
|
+
if (stageNow.current.kind !== 'cart') return LINE_EDIT_REFUSED;
|
|
640
|
+
try {
|
|
641
|
+
builderNow.current.updateLine(lineId, patch);
|
|
642
|
+
return null;
|
|
643
|
+
} catch (error) {
|
|
644
|
+
if (error instanceof RangeError || (error instanceof Error && error.message === `Unknown line ${lineId}`)) return error.message;
|
|
645
|
+
throw error;
|
|
646
|
+
}
|
|
647
|
+
},
|
|
648
|
+
remove(lineId: string) { if (!editRefusal()) builderNow.current.removeItem(lineId); },
|
|
649
|
+
/** #1095: the line, fee or shipping line `id` as it is now, taken before a remove for `restore()`; null when it is not there. */
|
|
650
|
+
removal(kind: SaleRemoval['kind'], id: string): SaleRemoval | null {
|
|
651
|
+
const order = builderNow.current.getSnapshot();
|
|
652
|
+
const list: readonly (LineItem | ChargeLine)[] = kind === 'line' ? order.lineItems : kind === 'fee' ? order.fees ?? [] : order.shipping ?? [];
|
|
653
|
+
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: saleEpoch.current };
|
|
655
|
+
},
|
|
656
|
+
/** #1095, v2's Undo: puts a removal back at its old index (clamped), re-taxed when the sale's rates moved since; returns a refusal or null. */
|
|
657
|
+
restore(removal: SaleRemoval): string | null {
|
|
658
|
+
const held = editRefusal(); if (held) return held;
|
|
659
|
+
const order = builderNow.current.getSnapshot(), moved = removal.taxContext !== taxNow.current.taxContext;
|
|
660
|
+
if (stageNow.current.kind !== 'cart' || removal.orderId !== order.id || removal.epoch !== saleEpoch.current) return RESTORE_STALE;
|
|
661
|
+
const ids = [removal.item, ...(removal.kind === 'line' ? (removal.item as LineItem).discounts : [])].map((entry) => entry.id);
|
|
662
|
+
if ([...order.lineItems.flatMap((li) => [li, ...li.discounts]), ...order.fees ?? [], ...order.shipping ?? [], ...order.discounts, ...order.payments]
|
|
663
|
+
.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
|
+
builderNow.current.restoreItem(removal.kind, removal.item, removal.index);
|
|
667
|
+
if (moved) retax(builderNow.current.getSnapshot().customer, taxNow.current);
|
|
668
|
+
return null;
|
|
669
|
+
},
|
|
517
670
|
/** A line's discount, or the order's without a line; returns the refusal to show, or null once applied. */
|
|
518
671
|
applyDiscount(lineId: string | null, discount: Discount): string | null {
|
|
519
|
-
if (
|
|
672
|
+
const held = editRefusal(); if (held) return held;
|
|
520
673
|
if ((opts.capabilities?.orderCreate ?? 1) < 2) return DISCOUNTS_UNSUPPORTED;
|
|
521
674
|
const builder = builderNow.current;
|
|
522
675
|
const applied = (snapshot: Order) => lineId === null ? snapshot.discounts
|
|
@@ -532,23 +685,25 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
532
685
|
}
|
|
533
686
|
return null;
|
|
534
687
|
},
|
|
535
|
-
removeDiscount(id: string) { if (!
|
|
688
|
+
removeDiscount(id: string) { if (!editRefusal()) builderNow.current.removeDiscount(id); },
|
|
536
689
|
/** ADR-077: looks up, checks and applies a discount code through the platform's discount codes; resolves to the refusal to show, or null once applied. */
|
|
537
690
|
async applyCoupon(code: string): Promise<string | null> {
|
|
538
|
-
if (
|
|
691
|
+
const held = editRefusal(); if (held) return held;
|
|
692
|
+
if (carriedCoupon()) return COUPON_CARRIED;
|
|
693
|
+
if (keptCodes()) return COUPONS_REPRICING;
|
|
539
694
|
const codes = codesFor();
|
|
540
695
|
if (!codes) return COUPONS_UNSUPPORTED;
|
|
541
696
|
const builder = builderNow.current, normalized = code.trim().toLowerCase();
|
|
542
697
|
if (!normalized) return 'Enter a coupon code';
|
|
543
698
|
const result = await codes.find(normalized, discountState(builder.getSnapshot(), applied.current));
|
|
544
699
|
if ('refusal' in result) return result.refusal;
|
|
545
|
-
if (
|
|
700
|
+
const heldNow = editRefusal(); if (heldNow) return heldNow;
|
|
546
701
|
if (builderNow.current !== builder || stageNow.current.kind === 'receipt') return 'The sale changed while the coupon was being checked; apply it again';
|
|
547
702
|
const refusal = codes.check(normalized, result.found, discountState(builder.getSnapshot(), applied.current));
|
|
548
703
|
if (refusal !== null) return refusal;
|
|
549
704
|
const next = new Map([...applied.current, [normalized, result.found]]);
|
|
550
|
-
|
|
551
|
-
|
|
705
|
+
const refused = refusalOf(() => { codes.apply(builder, discountState(builder.getSnapshot(), next)); return null; });
|
|
706
|
+
if (refused !== null) return refused;
|
|
552
707
|
applied.current.set(normalized, result.found);
|
|
553
708
|
appliedWith.current = codes;
|
|
554
709
|
generation.current++;
|
|
@@ -557,7 +712,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
557
712
|
},
|
|
558
713
|
/** Removes an applied coupon; returns the refusal to show, or null once removed. */
|
|
559
714
|
removeCoupon(code: string): string | null {
|
|
560
|
-
if (
|
|
715
|
+
const held = editRefusal(); if (held) return held;
|
|
716
|
+
if (carriedCoupon()) return COUPON_CARRIED;
|
|
717
|
+
if (keptCodes()) return COUPONS_REPRICING;
|
|
561
718
|
const normalized = code.trim().toLowerCase();
|
|
562
719
|
if (!applied.current.has(normalized)) return null;
|
|
563
720
|
const remaining = new Map(applied.current); remaining.delete(normalized);
|
|
@@ -570,18 +727,26 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
570
727
|
couponsRepricing,
|
|
571
728
|
/** Prices the sale's coupons again now, as Retry after a transient refusal; resolves to the refusal or error it set, or null. */
|
|
572
729
|
async repriceCoupons(): Promise<string | null> {
|
|
573
|
-
if (
|
|
574
|
-
if (!appliedWith.current || !applied.current.size
|
|
730
|
+
const held = editRefusal(); if (held) return held; // a re-price moves the total
|
|
731
|
+
if (!appliedWith.current || !applied.current.size) return null;
|
|
575
732
|
return reprice();
|
|
576
733
|
},
|
|
577
734
|
/** The sale's note, kept on the open sale (parked and resumed with it, cleared by newSale) and sent as order.create v7's note (ADR-083). */
|
|
578
|
-
setNote(note: string) {
|
|
735
|
+
setNote(note: string) {
|
|
736
|
+
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED);
|
|
737
|
+
if (!locked()) builderNow.current.setNote(note);
|
|
738
|
+
},
|
|
579
739
|
/** the picked customer reaches the server as order.create v3's customer.customerId */
|
|
580
|
-
setCustomer(
|
|
740
|
+
setCustomer(picked: CustomerSummary | null) {
|
|
741
|
+
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED);
|
|
581
742
|
if (locked()) return;
|
|
582
743
|
// A searched customer's email or id the server would refuse never reaches the sale; the customer stays as it was.
|
|
583
|
-
const refused =
|
|
744
|
+
const refused = picked && customerRefusal(picked);
|
|
584
745
|
if (refused) return setError(refused);
|
|
746
|
+
// #1064: so do tax ids setTaxIds would refuse; the clean list is the one stored.
|
|
747
|
+
const taxIds = picked?.taxIds?.length ? cleanTaxIds(picked.taxIds) : undefined;
|
|
748
|
+
if (taxIds === null) return setError(TAX_IDS_INVALID);
|
|
749
|
+
const customer = picked && taxIds ? { ...picked, taxIds } : picked;
|
|
585
750
|
// #722: the sale's rates and its customer always agree, so a customer with other rates is refused once they are fixed.
|
|
586
751
|
if (!retaxFor(customer)) {
|
|
587
752
|
const same = opts.taxContextFor?.(customer);
|
|
@@ -590,7 +755,70 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
590
755
|
if (same) taxNow.current = same;
|
|
591
756
|
builderNow.current.setCustomer(customer);
|
|
592
757
|
}
|
|
593
|
-
setError((current) => current !== null && (CUSTOMER_REFUSALS.includes(current) || current === CUSTOMER_RETAX_REFUSED) ? null : current); // any other error stays
|
|
758
|
+
setError((current) => current !== null && (CUSTOMER_REFUSALS.includes(current) || current === CUSTOMER_RETAX_REFUSED || current === TAX_IDS_INVALID) ? null : current); // any other error stays
|
|
759
|
+
},
|
|
760
|
+
/**
|
|
761
|
+
* Replaces both addresses on the picked customer (`undefined` removes one) and re-taxes like `setCustomer`. Does
|
|
762
|
+
* nothing and returns false for a guest sale (guests come later); refuses once the sale left the cart (desk Q7.4).
|
|
763
|
+
*/
|
|
764
|
+
setAddresses(billing: CustomerAddress | undefined, shipping: CustomerAddress | undefined): boolean {
|
|
765
|
+
if (locked()) return false;
|
|
766
|
+
const { customer, payments } = builderNow.current.getSnapshot();
|
|
767
|
+
if (customer === null) return false;
|
|
768
|
+
// Q7.4: refused outside the cart or with money live, even for an address with the same rates.
|
|
769
|
+
if (stageNow.current.kind !== 'cart' || capturedMinor(payments) !== 0 || payments.some(isInMotion)) {
|
|
770
|
+
setError(ADDRESS_CHANGE_REFUSED);
|
|
771
|
+
return false;
|
|
772
|
+
}
|
|
773
|
+
const { billing: _billing, shipping: _shipping, ...rest } = customer;
|
|
774
|
+
const next: CustomerSummary = { ...rest, ...(billing !== undefined ? { billing } : {}), ...(shipping !== undefined ? { shipping } : {}) };
|
|
775
|
+
if (!retaxFor(next)) {
|
|
776
|
+
const same = opts.taxContextFor?.(next);
|
|
777
|
+
if (same && same.taxContext !== taxNow.current.taxContext) { setError(ADDRESS_CHANGE_REFUSED); return false; }
|
|
778
|
+
if (same) taxNow.current = same;
|
|
779
|
+
builderNow.current.setCustomer(next);
|
|
780
|
+
}
|
|
781
|
+
setError((current) => current === ADDRESS_CHANGE_REFUSED ? null : current); // any other error stays
|
|
782
|
+
return true;
|
|
783
|
+
},
|
|
784
|
+
/** Replaces the picked customer's tax ids on this sale (`[]` removes them). Returns false for a guest sale, as `setAddresses`
|
|
785
|
+
* does; refuses once the sale left the cart, and refuses an invalid list (ADR-092 6a). It does not re-tax, and it does
|
|
786
|
+
* not save them to the customer (the customer editor does). */
|
|
787
|
+
setTaxIds(taxIds: CustomerTaxId[]): boolean {
|
|
788
|
+
if (locked()) return false;
|
|
789
|
+
const { customer, payments } = builderNow.current.getSnapshot();
|
|
790
|
+
if (customer === null) return false;
|
|
791
|
+
if (stageNow.current.kind !== 'cart' || capturedMinor(payments) !== 0 || payments.some(isInMotion)) { setError(TAX_IDS_CHANGE_REFUSED); return false; }
|
|
792
|
+
const cleaned = cleanTaxIds(taxIds);
|
|
793
|
+
if (!cleaned) { setError(TAX_IDS_INVALID); return false; }
|
|
794
|
+
const { taxIds: _taxIds, ...rest } = customer;
|
|
795
|
+
builderNow.current.setCustomer(cleaned.length ? { ...rest, taxIds: cleaned } : rest);
|
|
796
|
+
setError((current) => current === TAX_IDS_CHANGE_REFUSED || current === TAX_IDS_INVALID ? null : current); // any other error stays
|
|
797
|
+
return true;
|
|
798
|
+
},
|
|
799
|
+
/**
|
|
800
|
+
* Sets one custom field on this sale (ADR-092 4 and 6d). It replaces the value when the key is there, and removes the
|
|
801
|
+
* field when `value` is null. It refuses once the sale has left the cart, and it refuses an invalid key. The value is
|
|
802
|
+
* cut to its bound when the order is frozen, as the note is.
|
|
803
|
+
*/
|
|
804
|
+
setMeta(key: string, value: string | null): boolean {
|
|
805
|
+
if (locked()) return false;
|
|
806
|
+
const { meta = [], payments } = builderNow.current.getSnapshot();
|
|
807
|
+
if (stageNow.current.kind !== 'cart' || capturedMinor(payments) !== 0 || payments.some(isInMotion)) {
|
|
808
|
+
setError(META_CHANGE_REFUSED);
|
|
809
|
+
return false;
|
|
810
|
+
}
|
|
811
|
+
const name = key.trim();
|
|
812
|
+
const known = meta.some((m) => m.key === name);
|
|
813
|
+
if (!name || name.length > ORDER_META_KEY_MAX || name.startsWith('_') || (value !== null && !known && meta.length >= ORDER_META_MAX)) {
|
|
814
|
+
setError(META_INVALID);
|
|
815
|
+
return false;
|
|
816
|
+
}
|
|
817
|
+
const next = value === null ? meta.filter((m) => m.key !== name)
|
|
818
|
+
: known ? meta.map((m) => m.key === name ? { key: name, value } : m) : [...meta, { key: name, value }];
|
|
819
|
+
builderNow.current.setMeta(next);
|
|
820
|
+
setError((current) => current === META_CHANGE_REFUSED || current === META_INVALID ? null : current); // any other error stays
|
|
821
|
+
return true;
|
|
594
822
|
},
|
|
595
823
|
/**
|
|
596
824
|
* Pins `options.session` for this tender when given, else the rendered `session` option. Pass the
|
|
@@ -598,19 +826,46 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
598
826
|
* opened just before (#170 race). A repeat call mid-tender keeps the first pin.
|
|
599
827
|
*/
|
|
600
828
|
startTender(method: 'cash' | 'external', options?: { session?: { id: string; sessions: RegisterSessionCollection } }) {
|
|
829
|
+
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED); // never re-tender a finished sale
|
|
830
|
+
const taxIdsRefused = taxIdsRefusal();
|
|
831
|
+
if (taxIdsRefused) return setError(taxIdsRefused);
|
|
832
|
+
if (!opts.tenderGate) return begin(method, options);
|
|
601
833
|
if (locked()) return;
|
|
602
834
|
const current = builderNow.current.getSnapshot();
|
|
603
835
|
if (!current.lineItems.length) return;
|
|
604
|
-
if (couponsUnpriced()) return setError(COUPONS_REPRICING);
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
836
|
+
if (couponsUnpriced()) return setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING);
|
|
837
|
+
if (tenderGatePending.current) return;
|
|
838
|
+
const b = builderNow.current, at = generation.current;
|
|
839
|
+
tenderGatePending.current = true;
|
|
840
|
+
void Promise.resolve().then(() => opts.tenderGate!({ method })).catch(() => TENDER_GATE_FAILED).then((refusal) => {
|
|
841
|
+
tenderGatePending.current = false;
|
|
842
|
+
if (generation.current !== at) return;
|
|
843
|
+
if (builderNow.current !== b) return setError(TENDER_SALE_CHANGED); // 5.2 backlog F5: a re-tax the gate did not judge
|
|
844
|
+
if (refusal !== null) setError(refusal);
|
|
845
|
+
else begin(method, options);
|
|
846
|
+
});
|
|
608
847
|
},
|
|
609
848
|
setTender,
|
|
610
|
-
/** 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. */
|
|
611
|
-
addTender(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string; status?: 'pending' | 'authorized' | 'captured' }): string | null {
|
|
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(tender: { method: 'cash' | 'external'; methodId?: string; amountMinor: number; tenderedMinor?: number; reference?: string; units?: Readonly<Record<string, number>>; status?: 'pending' | 'authorized' | 'captured' }): string | null {
|
|
851
|
+
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return null; }
|
|
612
852
|
if (locked() || !Number.isInteger(tender.amountMinor) || tender.amountMinor <= 0) return null;
|
|
853
|
+
if (builderNow.current.getSnapshot().afterClose) { setError(AFTER_CLOSE_PAYMENTS_CHANGED); return null; }
|
|
854
|
+
const taxIdsRefused = taxIdsRefusal();
|
|
855
|
+
if (taxIdsRefused) { setError(taxIdsRefused); return null; }
|
|
613
856
|
if (tender.method === 'cash' && tender.status !== undefined && tender.status !== 'captured') return null;
|
|
857
|
+
if (tender.units) {
|
|
858
|
+
const { lineItems, payments } = builderNow.current.getSnapshot();
|
|
859
|
+
// unpaidUnitsByLine reads only id and quantity, so totalMinor can be 0.
|
|
860
|
+
const unpaid = unpaidUnitsByLine(lineItems.map(({ id, quantity }) => ({ id, quantity, totalMinor: 0 })), heldUnitsByLine(payments));
|
|
861
|
+
if (Object.entries(tender.units).some(([id, units]) => !id || !Number.isInteger(units) || units <= 0 || !Object.hasOwn(unpaid, id) || units > unpaid[id])) return null;
|
|
862
|
+
}
|
|
863
|
+
if (tender.tenderedMinor !== undefined && (tender.method !== 'cash' || !tender.units || !Object.keys(tender.units).length
|
|
864
|
+
|| !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor < tender.amountMinor)) return null;
|
|
865
|
+
if (tender.tenderedMinor !== undefined) {
|
|
866
|
+
const snapshot = builderNow.current.getSnapshot();
|
|
867
|
+
if (tender.amountMinor > snapshot.balanceDueMinor - inMotionMinor(snapshot.payments)) return null;
|
|
868
|
+
}
|
|
614
869
|
if (tender.method === 'external') {
|
|
615
870
|
const snapshot = builderNow.current.getSnapshot();
|
|
616
871
|
const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
|
|
@@ -619,31 +874,45 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
619
874
|
return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
|
|
620
875
|
}
|
|
621
876
|
clearStaleError();
|
|
622
|
-
return addOne(tender);
|
|
877
|
+
return addOne({ ...tender, ...(tender.tenderedMinor !== undefined ? { changeMinor: tender.tenderedMinor - tender.amountMinor } : {}) });
|
|
623
878
|
},
|
|
624
879
|
setTenderStatus(paymentId: string, status: 'authorized' | 'captured' | 'failed'): boolean {
|
|
880
|
+
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return false; }
|
|
625
881
|
if (locked()) return false;
|
|
626
|
-
|
|
882
|
+
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
883
|
+
if (payment && countedLeg(payment)) { setError(AFTER_CLOSE_PAYMENTS_CHANGED); return false; }
|
|
884
|
+
const changed = builderNow.current.setPaymentStatus(paymentId, status);
|
|
885
|
+
// With no live leg left, the sale can change again: SALE_HAS_PAYMENT goes, any other error stays.
|
|
886
|
+
if (changed && status === 'failed' && !liveLeg()) setError((current) => current === SALE_HAS_PAYMENT ? null : current);
|
|
887
|
+
return changed;
|
|
627
888
|
},
|
|
628
|
-
/** The leg stays in order.payments as voided and counts nothing; removeTender still removes a leg outright. */
|
|
889
|
+
/** The leg stays in order.payments as voided and counts nothing; removeTender still removes a leg outright. Refused on the receipt. */
|
|
629
890
|
voidTender(paymentId: string): boolean {
|
|
630
|
-
if (
|
|
891
|
+
if (stageNow.current.kind === 'receipt') { setError(SALE_FINISHED); return false; } // a finished sale's legs stay
|
|
631
892
|
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
893
|
+
if (payment && countedLeg(payment)) { setError(AFTER_CLOSE_PAYMENTS_CHANGED); return false; }
|
|
894
|
+
if (payment?.locked) return false;
|
|
895
|
+
if (locked()) return false;
|
|
632
896
|
if (!payment || (payment.method !== 'cash' && payment.method !== 'external') || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
|
|
633
897
|
builderNow.current.setPaymentStatus(paymentId, 'voided');
|
|
634
898
|
droppedReferences.current.delete(paymentId);
|
|
635
899
|
clearStaleError();
|
|
636
900
|
return true;
|
|
637
901
|
},
|
|
638
|
-
/** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
|
|
902
|
+
/** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. Refused on the receipt. */
|
|
639
903
|
removeTender(paymentId: string): void {
|
|
904
|
+
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED);
|
|
905
|
+
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
906
|
+
if (payment && countedLeg(payment)) return setError(AFTER_CLOSE_PAYMENTS_CHANGED);
|
|
907
|
+
if (payment?.locked) return;
|
|
640
908
|
if (locked()) return;
|
|
641
|
-
if (!
|
|
909
|
+
if (!payment) return;
|
|
642
910
|
builderNow.current.removePayment(paymentId);
|
|
643
911
|
droppedReferences.current.delete(paymentId);
|
|
644
912
|
clearStaleError();
|
|
645
913
|
},
|
|
646
914
|
cancelTender() {
|
|
915
|
+
if (stageNow.current.kind === 'receipt') return setError(SALE_FINISHED);
|
|
647
916
|
if (locked()) return;
|
|
648
917
|
setTender(null);
|
|
649
918
|
tenderSession.current = null;
|
|
@@ -674,7 +943,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
674
943
|
setSaving(true);
|
|
675
944
|
const snapshot = builderNow.current.getSnapshot();
|
|
676
945
|
if (snapshot.payments.some(isInMotion)) { setSaving(false); setError(PAYMENT_IN_MOTION); return; }
|
|
677
|
-
if (couponsUnpriced()) { setSaving(false); setError(COUPONS_REPRICING); return; }
|
|
946
|
+
if (couponsUnpriced()) { setSaving(false); setError(carriedCoupon() ? COUPON_CARRY_STALE : COUPONS_REPRICING); return; }
|
|
678
947
|
// Failed and voided legs stay on the screen's ledger but are never sent: only captured money is the sale's.
|
|
679
948
|
const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid) };
|
|
680
949
|
const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id))
|
|
@@ -701,7 +970,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
701
970
|
// A failing sink must never lose the sale.
|
|
702
971
|
}
|
|
703
972
|
}
|
|
704
|
-
|
|
973
|
+
// An after-close successor's sale is already in a closed session's closure: it joins no session (ADR-077).
|
|
974
|
+
if (session && posOrder.countedInClosureOf === undefined) {
|
|
705
975
|
try {
|
|
706
976
|
posOrder = await stampSession(posOrder, session.id, session.sessions);
|
|
707
977
|
} catch {
|
|
@@ -742,11 +1012,37 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
742
1012
|
const builder = builderNow.current;
|
|
743
1013
|
const snapshot = builder.getSnapshot();
|
|
744
1014
|
if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return 'There is nothing to park';
|
|
745
|
-
await
|
|
1015
|
+
const refused = await writeParked(opts.drafts, snapshot); if (refused) return refused;
|
|
746
1016
|
if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
|
|
747
1017
|
resetSale();
|
|
748
1018
|
return null;
|
|
749
1019
|
},
|
|
1020
|
+
/** Whether the live sale or a parked draft holds this store order; unreadable drafts do not count. */
|
|
1021
|
+
async holdsStoreOrder(orderId: string): Promise<boolean> {
|
|
1022
|
+
if (builderNow.current.getSnapshot().storeOrder?.id === orderId) return true;
|
|
1023
|
+
if (!opts.drafts) return false;
|
|
1024
|
+
const drafts = await opts.drafts.find().exec();
|
|
1025
|
+
return drafts.some((doc) => {
|
|
1026
|
+
try {
|
|
1027
|
+
const saved: Order = JSON.parse(doc.toJSON().data);
|
|
1028
|
+
return saved.storeOrder?.id === orderId;
|
|
1029
|
+
} catch { return false; }
|
|
1030
|
+
});
|
|
1031
|
+
},
|
|
1032
|
+
/** Loads a reopened store order (from reopenStoreOrder) into an empty sale, or returns why not. */
|
|
1033
|
+
openStoreOrder(order: Order): string | null {
|
|
1034
|
+
if (locked()) return SALE_SAVING;
|
|
1035
|
+
if (!order.storeOrder) throw new Error('useSale: openStoreOrder() takes a reopened store order');
|
|
1036
|
+
const liveSnapshot = builderNow.current.getSnapshot();
|
|
1037
|
+
if (stageNow.current.kind !== 'cart' || liveSnapshot.lineItems.length || liveSnapshot.fees?.length || liveSnapshot.shipping?.length) return 'Park or clear the current sale first';
|
|
1038
|
+
if (order.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That order is in another currency';
|
|
1039
|
+
const restoredTax = contextFor(order.customer && !customerRefusal(order.customer) ? order.customer : null);
|
|
1040
|
+
const builder = restoreOrderDraft(order, { currency: settings.currency, taxContext: restoredTax.taxContext });
|
|
1041
|
+
const snapshot = builder.getSnapshot();
|
|
1042
|
+
if (snapshot.totalMinor !== order.totalMinor || snapshot.taxMinor !== order.taxMinor) return STORE_ORDER_REBUILD_REFUSALS.totals;
|
|
1043
|
+
resetSale(null, builder, restoredTax);
|
|
1044
|
+
return null;
|
|
1045
|
+
},
|
|
750
1046
|
/** Resumes a draft into an empty cart; resolves to a refusal message, or null once resumed. */
|
|
751
1047
|
async resume(draftId: string, options?: { keepParkedPrices?: boolean }): Promise<string | null> {
|
|
752
1048
|
if (locked()) return SALE_SAVING;
|
|
@@ -760,10 +1056,16 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
760
1056
|
if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That parked sale is in another currency';
|
|
761
1057
|
// Taxed for the customer the draft restores (a refused one isn't).
|
|
762
1058
|
const restoredTax = contextFor(saved.customer && !customerRefusal(saved.customer) ? saved.customer : null);
|
|
763
|
-
|
|
1059
|
+
// A draft whose legs took money keeps the tax rates it was paid against (u19); otherwise class-taxed lines re-derive.
|
|
1060
|
+
// ADR-077 d3 amended 2026-11-19: parked coupon amounts, with their prices and rates, given a display row per coupon.
|
|
1061
|
+
const carriedDraft = !!saved.coupons?.length && saved.coupons.every((coupon) => coupon.carried);
|
|
1062
|
+
const keep = !carriedDraft && !!saved.coupons?.length && saved.display.coupons?.length === saved.coupons.length && (saved.payments ?? []).some(isLiveLeg);
|
|
1063
|
+
const builder = restoreOrderDraft(saved, { currency: settings.currency, taxContext: restoredTax.taxContext,
|
|
1064
|
+
keepTaxRates: keep || capturedMinor(saved.payments ?? []) !== 0, keepCoupons: keep });
|
|
764
1065
|
let n = 0;
|
|
765
|
-
// A draft whose legs took money keeps the prices it was paid against (u19).
|
|
766
|
-
|
|
1066
|
+
// A draft whose legs took money keeps the prices it was paid against (u19), as does one kept for its coupons.
|
|
1067
|
+
// A reopened store order keeps the store's prices (ADR-090 decision 3, carryover item 22).
|
|
1068
|
+
if (opts.currentPrice && !options?.keepParkedPrices && !carriedDraft && !keep && capturedMinor(saved.payments ?? []) === 0 && !saved.storeOrder) {
|
|
767
1069
|
for (const line of builder.getSnapshot().lineItems) {
|
|
768
1070
|
if (!line.variantId) continue;
|
|
769
1071
|
const price = opts.currentPrice(line.variantId);
|
|
@@ -774,12 +1076,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
774
1076
|
}
|
|
775
1077
|
}
|
|
776
1078
|
const kept = new Map<string, unknown>(), messages: string[] = [];
|
|
777
|
-
const codes = saved.coupons?.length ? codesFor() : null;
|
|
1079
|
+
const codes = !carriedDraft && saved.coupons?.length ? codesFor() : null;
|
|
778
1080
|
if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? 'line' : 'lines'} updated to today's price.`);
|
|
779
|
-
if (saved.coupons?.length) {
|
|
1081
|
+
if (!carriedDraft && saved.coupons?.length) {
|
|
780
1082
|
const supported = codes !== null;
|
|
781
1083
|
if (supported) await codes.beforeResume?.(discountState(builder.getSnapshot(), new Map()));
|
|
782
|
-
for (const { code } of saved.coupons)
|
|
1084
|
+
if (keep) for (const { code } of saved.coupons) kept.set(code, KEPT);
|
|
1085
|
+
else for (const { code } of saved.coupons) {
|
|
783
1086
|
let reason: string | null = supported ? null : COUPONS_UNSUPPORTED;
|
|
784
1087
|
if (supported) {
|
|
785
1088
|
const result = await codes.find(code, discountState(builder.getSnapshot(), kept));
|
|
@@ -801,6 +1104,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
801
1104
|
resetSale(null, builder, restoredTax);
|
|
802
1105
|
if (builderNow.current === builder) {
|
|
803
1106
|
applied.current = kept;
|
|
1107
|
+
if (keep) { keptCoupons.current = saved.coupons; keptLegIds.current = saved.payments.filter(isLiveLeg).map((p) => p.id); }
|
|
804
1108
|
appliedWith.current = kept.size ? codes : null;
|
|
805
1109
|
generation.current++;
|
|
806
1110
|
}
|
|
@@ -819,21 +1123,22 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
819
1123
|
const builder = builderNow.current;
|
|
820
1124
|
const snapshot = builder.getSnapshot();
|
|
821
1125
|
if (draftId === snapshot.id) return null;
|
|
822
|
-
if (capturedMinor(snapshot.payments) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
|
|
1126
|
+
if (capturedMinor(snapshot.payments.filter((payment) => !payment.locked)) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
|
|
823
1127
|
if (snapshot.payments.some(isInMotion)) return PAYMENT_IN_MOTION;
|
|
824
1128
|
if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
|
|
825
1129
|
if (stageNow.current.kind !== 'receipt' && (snapshot.lineItems.length || snapshot.fees?.length || snapshot.shipping?.length)) {
|
|
826
|
-
await
|
|
1130
|
+
const refused = await writeParked(opts.drafts, snapshot); if (refused) return refused;
|
|
827
1131
|
if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
|
|
828
1132
|
}
|
|
829
1133
|
resetSale();
|
|
830
1134
|
return draftId === null ? null : result.resume(draftId);
|
|
831
1135
|
},
|
|
832
|
-
/** 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.
|
|
1136
|
+
/** 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
|
+
* A reopened sale's locked store legs do not stop it closing; the store order stays reopened, as in v2. */
|
|
833
1138
|
closeSale(): string | null {
|
|
834
1139
|
if (locked()) return SALE_SAVING;
|
|
835
1140
|
const { payments } = builderNow.current.getSnapshot();
|
|
836
|
-
if (stageNow.current.kind !== 'receipt' && (capturedMinor(payments) > 0 || payments.some(isInMotion))) return SALE_PARTLY_PAID;
|
|
1141
|
+
if (stageNow.current.kind !== 'receipt' && (capturedMinor(payments.filter((payment) => !payment.locked)) > 0 || payments.some(isInMotion))) return SALE_PARTLY_PAID;
|
|
837
1142
|
if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
|
|
838
1143
|
resetSale();
|
|
839
1144
|
return null;
|