@tallyui/pos 3.12.0 → 3.14.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 +1844 -359
- package/dist/index.js +4620 -2211
- package/package.json +12 -6
- package/src/app-settings/app-settings.ts +108 -0
- package/src/app-settings/index.ts +8 -0
- package/src/app-settings/use-app-settings.ts +23 -0
- package/src/cashier/can.ts +12 -0
- package/src/cashier/index.ts +2 -0
- package/src/cashier/use-cashier.ts +81 -0
- package/src/csv/csv.ts +33 -0
- package/src/csv/index.ts +2 -0
- package/src/customer-display/display-link.ts +72 -0
- package/src/customer-display/display-state.ts +30 -0
- package/src/customer-display/index.ts +13 -0
- package/src/customer-display/protocol.ts +87 -0
- package/src/customer-display/snapshot.ts +65 -0
- package/src/customer-display/transport.ts +54 -0
- package/src/customer-display/use-customer-display.ts +36 -0
- package/src/index.ts +73 -10
- package/src/order/order-builder.ts +11 -1
- package/src/order/order-drafts.ts +16 -0
- package/src/order/types.ts +6 -3
- package/src/outbox/index.ts +5 -1
- package/src/outbox/outbox-health.ts +40 -0
- package/src/outbox/register-outbox.ts +59 -6
- package/src/outbox/safe-error.ts +11 -0
- package/src/outbox/types.ts +3 -1
- package/src/outbox/use-outbox-health.ts +22 -0
- package/src/outbox/use-register-outbox.ts +6 -0
- package/src/payment-driver/index.ts +8 -0
- package/src/payment-driver/registry.ts +39 -0
- package/src/payment-driver/simulated-driver.ts +104 -0
- package/src/payment-driver/types.ts +73 -0
- package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
- package/src/pos-order/command.ts +36 -16
- package/src/pos-order/finalize.ts +7 -3
- package/src/pos-order/index.ts +1 -0
- package/src/pos-order/note-delivery.ts +13 -0
- package/src/pos-order/reopen.ts +3 -2
- package/src/pos-order/schema.ts +5 -4
- package/src/pos-order/types.ts +3 -2
- package/src/print/escpos/code-page.ts +48 -0
- package/src/print/escpos/commands.ts +53 -0
- package/src/print/escpos/encode.ts +127 -0
- package/src/print/escpos/index.ts +7 -0
- package/src/print/escpos/transport.ts +45 -0
- package/src/print/index.ts +12 -0
- package/src/print/print-queue.ts +67 -0
- package/src/print/printer-profiles.ts +71 -0
- package/src/print/system-transport.ts +101 -0
- package/src/print/types.ts +44 -0
- package/src/receipt/reprint.ts +2 -1
- package/src/receipt/types.ts +2 -0
- package/src/receipt-template/default-templates.ts +78 -0
- package/src/receipt-template/index.ts +15 -0
- package/src/receipt-template/parse-xml.ts +175 -0
- package/src/receipt-template/render-html.ts +152 -0
- package/src/receipt-template/render-receipt.ts +19 -0
- package/src/receipt-template/render-template.ts +35 -0
- package/src/receipt-template/sanitize-html.ts +146 -0
- package/src/receipt-template/template-data.ts +97 -0
- package/src/receipt-template/types.ts +49 -0
- package/src/refund/index.ts +2 -0
- package/src/refund/refundable-lines.ts +91 -0
- package/src/register/export-csv.ts +24 -35
- package/src/register/float-suggestion.ts +22 -0
- package/src/register/handover.ts +103 -0
- package/src/register/index.ts +10 -3
- package/src/register/register-adoption.ts +71 -2
- package/src/register/register-commands.ts +7 -4
- package/src/register/register-count.helpers.ts +4 -0
- package/src/register/session-store.ts +4 -1
- package/src/register/use-register-session.ts +112 -28
- package/src/reports/adapters.ts +67 -0
- package/src/reports/index.ts +5 -0
- package/src/reports/presets.ts +27 -0
- package/src/reports/sales-figures.ts +187 -0
- package/src/reports/types.ts +63 -0
- package/src/sale/in-cart.ts +18 -0
- package/src/sale/index.ts +5 -1
- package/src/sale/open-sales.ts +40 -0
- package/src/sale/use-sale.ts +72 -8
- package/src/scanner/index.ts +6 -0
- package/src/scanner/scan-session.ts +84 -0
- package/src/scanner/use-barcode-scanner.ts +61 -0
- package/src/scanner/wedge-detector.ts +137 -0
- package/src/tender/cash-rounding.ts +74 -0
- package/src/tender/index.ts +4 -0
- package/src/tender/payment-legs.ts +48 -0
package/src/sale/index.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, saleLogger } from './use-sale';
|
|
1
|
+
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, saleLogger } from './use-sale';
|
|
2
|
+
export { openSales, isPartlyPaid } from './open-sales';
|
|
3
|
+
export type { OpenSale } from './open-sales';
|
|
2
4
|
export type { SaleStage } from './use-sale';
|
|
3
5
|
export { COUPONS_UNSUPPORTED } from './discount-codes';
|
|
4
6
|
export type { SaleDiscountCodes, SaleDiscountState } from './discount-codes';
|
|
@@ -6,3 +8,5 @@ export * as woocommerceDiscountCodes from './woocommerce';
|
|
|
6
8
|
export { addEntryToCart, CartError } from './cart';
|
|
7
9
|
export { catalogueEntries, findEntryByCode, variantPriceLabel } from './catalogue';
|
|
8
10
|
export type { CatalogueEntry } from './catalogue';
|
|
11
|
+
export { cartQuantities } from './in-cart';
|
|
12
|
+
export type { CartQuantityLine } from './in-cart';
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Order, ParkedOrderSummary } from '../order';
|
|
2
|
+
|
|
3
|
+
/** One tab of the till's open sales: the current sale or a parked draft (v2 cart/tabs.tsx). */
|
|
4
|
+
export interface OpenSale {
|
|
5
|
+
id: string;
|
|
6
|
+
customerName?: string;
|
|
7
|
+
itemCount: number;
|
|
8
|
+
firstItem?: string;
|
|
9
|
+
totalMinor: number;
|
|
10
|
+
paidMinor: number;
|
|
11
|
+
balanceDueMinor: number;
|
|
12
|
+
/** The sale on the till now. */
|
|
13
|
+
current: boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** v2 cart/tab-chip.tsx: captured money and a balance still due. */
|
|
17
|
+
export function isPartlyPaid(sale: Pick<OpenSale, 'paidMinor' | 'balanceDueMinor'>): boolean {
|
|
18
|
+
return sale.paidMinor > 0 && sale.balanceDueMinor > 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The current sale (when it has lines, fees or shipping; a blank cart is no tab) and the parked drafts, in creation
|
|
23
|
+
* order: sorted by id with numeric collation, so a tab keeps its place across switches (a re-park changes
|
|
24
|
+
* `parkedAt`, never the id). A draft with the current sale's id is that sale and is skipped.
|
|
25
|
+
*/
|
|
26
|
+
export function openSales(order: Order, parked: readonly ParkedOrderSummary[]): OpenSale[] {
|
|
27
|
+
const live = order.lineItems.length > 0 || !!order.fees?.length || !!order.shipping?.length;
|
|
28
|
+
const sales: OpenSale[] = parked.filter((draft) => draft.id !== order.id).map((draft) => ({
|
|
29
|
+
id: draft.id, customerName: draft.customerName, itemCount: draft.itemCount, firstItem: draft.firstItem,
|
|
30
|
+
totalMinor: draft.totalMinor, paidMinor: draft.paidMinor ?? 0, balanceDueMinor: draft.balanceDueMinor ?? 0, current: false,
|
|
31
|
+
}));
|
|
32
|
+
if (live) {
|
|
33
|
+
sales.push({
|
|
34
|
+
id: order.id, customerName: order.customer?.name || undefined, itemCount: order.lineItems.length,
|
|
35
|
+
firstItem: order.lineItems[0]?.name, totalMinor: order.totalMinor, paidMinor: order.paidMinor,
|
|
36
|
+
balanceDueMinor: order.balanceDueMinor, current: true,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return sales.sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }));
|
|
40
|
+
}
|
package/src/sale/use-sale.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
|
2
2
|
import type { RxCollection } from 'rxdb';
|
|
3
3
|
import type { ProductTraits, ServerCapabilities, StoreSettings } from '@tallyui/core';
|
|
4
|
+
import { paymentMethodOf } from '@tallyui/core';
|
|
5
|
+
import { canVoidLeg, capturedMinor, countsTowardPaid, inMotionMinor, isInMotion } from '../tender/payment-legs';
|
|
4
6
|
import { createOrderBuilder, writeOrderDraft, restoreOrderDraft, type ChargeInput, type OrderBuilder, type CustomerSummary, type Discount, type Order, type SentOrder } from '../order';
|
|
5
7
|
import { finalizeOrder, uuidv7, type PosOrder } from '../pos-order';
|
|
6
8
|
import { MESSAGE_NAME_MAX, referenceError, referenceReason, withSentForm } from '../pos-order/finalize';
|
|
@@ -22,6 +24,14 @@ export type SaleStage = { kind: 'cart' } | { kind: 'tender'; method: 'cash' | 'e
|
|
|
22
24
|
export const DISCOUNTS_UNSUPPORTED = 'finalize: discounts are not supported by the server yet (order.create v2)';
|
|
23
25
|
/** Every sale change refuses with this while a completion is pending (see `complete()`). */
|
|
24
26
|
export const SALE_SAVING = 'This sale is being saved. Retry to finish it.';
|
|
27
|
+
export const PAYMENT_IN_MOTION = 'Finish or void the payment in progress before completing the sale';
|
|
28
|
+
/**
|
|
29
|
+
* `switchSale()` and `closeSale()` refuse a sale whose legs took money (u19). v2 keeps a partly paid order's legs on
|
|
30
|
+
* switching, but a TallyUI draft keeps no tender stage, the next `startTender` replaces every leg, and `resume`
|
|
31
|
+
* re-checks coupons: so the sale stays on the till until it is paid or its paid legs are voided.
|
|
32
|
+
*/
|
|
33
|
+
export const SALE_PARTLY_PAID = 'This sale is partly paid. Take the rest of the payment or void the paid legs first.';
|
|
34
|
+
export const SALE_IN_TENDER = 'Finish or cancel the payment before switching sales';
|
|
25
35
|
/**
|
|
26
36
|
* How often a hung save re-asks `isStored`, while the order is built and its save is still in flight
|
|
27
37
|
* and unconfirmed: an app whose tender has no New sale control while saving (the Front desk,
|
|
@@ -144,7 +154,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
144
154
|
appliedWith.current = null;
|
|
145
155
|
setBuilder(next);
|
|
146
156
|
setOrder(next.getSnapshot());
|
|
147
|
-
|
|
157
|
+
// Live at once, so a resume() in the same tick (switchSale) sees the cart before the next render.
|
|
158
|
+
stageNow.current = { kind: 'cart' };
|
|
159
|
+
setStage(stageNow.current);
|
|
148
160
|
setError(null);
|
|
149
161
|
}
|
|
150
162
|
useEffect(() => {
|
|
@@ -170,13 +182,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
170
182
|
}
|
|
171
183
|
}, []);
|
|
172
184
|
|
|
173
|
-
function addOne(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string }): string {
|
|
185
|
+
function addOne(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string; status?: 'pending' | 'authorized' | 'captured' }): string {
|
|
174
186
|
// A terminal reference finalize would refuse is dropped as it's entered, never the payment (the money is
|
|
175
187
|
// taken): the tender applies without it, with a message that doesn't block complete() and a
|
|
176
188
|
// localWarnings entry on the stored order naming the payment whose reference was dropped.
|
|
177
189
|
const reason = referenceReason(tender.reference);
|
|
178
190
|
const dropped = reason && (reason === 'nul' ? 'it contains a NUL character' : `it is over ${PAYLOAD_STRING_MAX} characters`);
|
|
179
|
-
const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor } : tender;
|
|
191
|
+
const kept = dropped ? { method: tender.method, amountMinor: tender.amountMinor, ...(tender.status !== undefined ? { status: tender.status } : {}) } : tender;
|
|
180
192
|
const builder = builderNow.current;
|
|
181
193
|
const paymentId = builder.addPayment(kept);
|
|
182
194
|
if (dropped) {
|
|
@@ -405,6 +417,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
405
417
|
applied.current.delete(normalized);
|
|
406
418
|
return null;
|
|
407
419
|
},
|
|
420
|
+
/** The sale's note, kept on the open sale (parked and resumed with it, cleared by newSale) and sent as order.create v7's note (ADR-083). */
|
|
421
|
+
setNote(note: string) { if (!locked()) builderNow.current.setNote(note); },
|
|
408
422
|
/** the picked customer reaches the server as order.create v3's customer.customerId */
|
|
409
423
|
setCustomer(customer: CustomerSummary | null) {
|
|
410
424
|
if (locked()) return;
|
|
@@ -428,16 +442,31 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
428
442
|
setStage({ kind: 'tender', method });
|
|
429
443
|
},
|
|
430
444
|
setTender,
|
|
431
|
-
/** ADR-072: external is capped at the balance due; change comes only from cash. */
|
|
432
|
-
addTender(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string }): string | null {
|
|
445
|
+
/** ADR-072: external is capped at the balance due; change comes only from cash. A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. */
|
|
446
|
+
addTender(tender: { method: 'cash' | 'external'; amountMinor: number; reference?: string; status?: 'pending' | 'authorized' | 'captured' }): string | null {
|
|
433
447
|
if (locked() || !Number.isInteger(tender.amountMinor) || tender.amountMinor <= 0) return null;
|
|
448
|
+
if (tender.method === 'cash' && tender.status !== undefined && tender.status !== 'captured') return null;
|
|
434
449
|
if (tender.method === 'external') {
|
|
435
|
-
const
|
|
450
|
+
const snapshot = builderNow.current.getSnapshot();
|
|
451
|
+
const due = snapshot.balanceDueMinor - inMotionMinor(snapshot.payments);
|
|
436
452
|
if (due <= 0) return null;
|
|
437
453
|
return addOne({ ...tender, amountMinor: Math.min(tender.amountMinor, due) });
|
|
438
454
|
}
|
|
439
455
|
return addOne(tender);
|
|
440
456
|
},
|
|
457
|
+
setTenderStatus(paymentId: string, status: 'authorized' | 'captured' | 'failed'): boolean {
|
|
458
|
+
if (locked()) return false;
|
|
459
|
+
return builderNow.current.setPaymentStatus(paymentId, status);
|
|
460
|
+
},
|
|
461
|
+
/** The leg stays in order.payments as voided and counts nothing; removeTender still removes a leg outright. */
|
|
462
|
+
voidTender(paymentId: string): boolean {
|
|
463
|
+
if (locked()) return false;
|
|
464
|
+
const payment = builderNow.current.getSnapshot().payments.find((p) => p.id === paymentId);
|
|
465
|
+
if (!payment || (payment.method !== 'cash' && payment.method !== 'external') || !canVoidLeg(payment, paymentMethodOf(payment.method))) return false;
|
|
466
|
+
builderNow.current.setPaymentStatus(paymentId, 'voided');
|
|
467
|
+
droppedReferences.current.delete(paymentId);
|
|
468
|
+
return true;
|
|
469
|
+
},
|
|
441
470
|
/** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
|
|
442
471
|
removeTender(paymentId: string): void {
|
|
443
472
|
if (locked()) return;
|
|
@@ -471,7 +500,10 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
471
500
|
confirm(null);
|
|
472
501
|
if (pending.current) return deliver(pending.current);
|
|
473
502
|
setSaving(true);
|
|
474
|
-
const
|
|
503
|
+
const snapshot = builderNow.current.getSnapshot();
|
|
504
|
+
if (snapshot.payments.some(isInMotion)) { setSaving(false); setError(PAYMENT_IN_MOTION); return; }
|
|
505
|
+
// Failed and voided legs stay on the screen's ledger but are never sent: only captured money is the sale's.
|
|
506
|
+
const current = { ...snapshot, payments: snapshot.payments.filter(countsTowardPaid) };
|
|
475
507
|
const localWarnings = current.payments.filter((payment) => droppedReferences.current.has(payment.id))
|
|
476
508
|
.map((payment) => ({ code: 'payment_reference_dropped' as const, paymentId: payment.id }));
|
|
477
509
|
let posOrder: PosOrder;
|
|
@@ -553,7 +585,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
553
585
|
if (saved.currency.toUpperCase() !== settings.currency.toUpperCase()) return 'That parked sale is in another currency';
|
|
554
586
|
const builder = restoreOrderDraft(saved, { currency: settings.currency, taxContext });
|
|
555
587
|
let n = 0;
|
|
556
|
-
|
|
588
|
+
// A draft whose legs took money keeps the prices it was paid against (u19).
|
|
589
|
+
if (opts.currentPrice && !options?.keepParkedPrices && capturedMinor(saved.payments ?? []) === 0) {
|
|
557
590
|
for (const line of builder.getSnapshot().lineItems) {
|
|
558
591
|
if (!line.variantId) continue;
|
|
559
592
|
const price = opts.currentPrice(line.variantId);
|
|
@@ -596,6 +629,37 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
|
|
|
596
629
|
if (messages.length) setError(messages.join(' '));
|
|
597
630
|
return null;
|
|
598
631
|
},
|
|
632
|
+
/**
|
|
633
|
+
* Opens the parked draft `draftId`, or an empty sale for null (New), as a tab switch (u19, v2 cart/tabs.tsx):
|
|
634
|
+
* parks the current sale first when it has lines, fees or shipping (a receipt is done and is not parked).
|
|
635
|
+
* Refused, changing nothing, while saving, for a partly paid sale (SALE_PARTLY_PAID), a payment in motion or
|
|
636
|
+
* the tender stage. Resolves to a refusal (park's, or `resume`'s for the chosen draft), or null.
|
|
637
|
+
*/
|
|
638
|
+
async switchSale(draftId: string | null): Promise<string | null> {
|
|
639
|
+
if (locked()) return SALE_SAVING;
|
|
640
|
+
if (!opts.drafts) throw new Error('useSale: switchSale() needs the drafts option');
|
|
641
|
+
const builder = builderNow.current;
|
|
642
|
+
const snapshot = builder.getSnapshot();
|
|
643
|
+
if (draftId === snapshot.id) return null;
|
|
644
|
+
if (capturedMinor(snapshot.payments) > 0 && snapshot.balanceDueMinor > 0) return SALE_PARTLY_PAID;
|
|
645
|
+
if (snapshot.payments.some(isInMotion)) return PAYMENT_IN_MOTION;
|
|
646
|
+
if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
|
|
647
|
+
if (stageNow.current.kind !== 'receipt' && (snapshot.lineItems.length || snapshot.fees?.length || snapshot.shipping?.length)) {
|
|
648
|
+
await writeOrderDraft(opts.drafts, snapshot);
|
|
649
|
+
if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
|
|
650
|
+
}
|
|
651
|
+
resetSale(null);
|
|
652
|
+
return draftId === null ? null : result.resume(draftId);
|
|
653
|
+
},
|
|
654
|
+
/** Discards the current sale (nothing is parked) and starts an empty one; refused while saving, once a leg of an unfinished sale took or holds money, or in the tender stage. */
|
|
655
|
+
closeSale(): string | null {
|
|
656
|
+
if (locked()) return SALE_SAVING;
|
|
657
|
+
const { payments } = builderNow.current.getSnapshot();
|
|
658
|
+
if (stageNow.current.kind !== 'receipt' && (capturedMinor(payments) > 0 || payments.some(isInMotion))) return SALE_PARTLY_PAID;
|
|
659
|
+
if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
|
|
660
|
+
resetSale(null);
|
|
661
|
+
return null;
|
|
662
|
+
},
|
|
599
663
|
/**
|
|
600
664
|
* Continue after a failed save whose order is confirmed stored (`canContinue`): exactly `newSale()`.
|
|
601
665
|
* The order stays pending in the outbox, which will send it; it isn't handed to `onSaleCompleted` again, and
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector } from './wedge-detector';
|
|
2
|
+
export type { WedgeSettings, WedgeState, TraceKey, WedgeReplayResult, WedgeDetectorOptions, WedgeDetector } from './wedge-detector';
|
|
3
|
+
export { DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession } from './scan-session';
|
|
4
|
+
export type { ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession } from './scan-session';
|
|
5
|
+
export { useBarcodeScanner } from './use-barcode-scanner';
|
|
6
|
+
export type { UseBarcodeScannerOptions } from './use-barcode-scanner';
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Ported from WCPOS v2 packages/scanner/src/scan-session.ts (monorepo 5ac185b0).
|
|
2
|
+
/** Suppress repeated reads within a cooldown and reject retail check-digit misreads. */
|
|
3
|
+
export const DEFAULT_COOLDOWN_MS = 1200;
|
|
4
|
+
export type ScanRejectReason = 'cooldown' | 'bad-check-digit';
|
|
5
|
+
export interface ScanOfferResult { accepted: boolean; reason?: ScanRejectReason; }
|
|
6
|
+
export interface ScanSessionOptions {
|
|
7
|
+
onAccept: (code: string, symbology?: string) => void;
|
|
8
|
+
cooldownMs?: number;
|
|
9
|
+
now?: () => number;
|
|
10
|
+
}
|
|
11
|
+
export interface ScanSession {
|
|
12
|
+
offer: (code: string, symbology?: string) => ScanOfferResult;
|
|
13
|
+
reset: () => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// UPC-E is excluded: its check digit is computed over the expanded UPC-A,
|
|
17
|
+
// so validating its printed 8 digits as EAN-8 would reject valid reads.
|
|
18
|
+
const RETAIL_SYMBOLOGIES = new Set(['ean13', 'ean8', 'upc_a', 'ean-13', 'ean-8', 'upc-a']);
|
|
19
|
+
// Decoders can expand UPC-E to UPC-A and then pad it to 13 digits too.
|
|
20
|
+
const ZERO_PADDED_SYMBOLOGIES = new Set(['ean13', 'upc_a', 'upc_e', 'ean-13', 'upc-a', 'upc-e']);
|
|
21
|
+
|
|
22
|
+
/** Report the printed UPC-A digits by dropping an implied zero from labelled
|
|
23
|
+
* EAN-13/UPC reads. Unlabelled reads and printed 8-digit UPC-E stay unchanged. */
|
|
24
|
+
export function normalizeRetailCode(code: string, symbology?: string): string {
|
|
25
|
+
if (symbology === undefined || !ZERO_PADDED_SYMBOLOGIES.has(symbology.toLowerCase())) {
|
|
26
|
+
return code;
|
|
27
|
+
}
|
|
28
|
+
return /^0\d{12}$/.test(code) ? code.slice(1) : code;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Validate EAN-13/EAN-8/UPC-A check digits; non-retail-length inputs pass. */
|
|
32
|
+
export function hasValidRetailCheckDigit(code: string): boolean {
|
|
33
|
+
if (!/^\d+$/.test(code)) return true;
|
|
34
|
+
if (code.length !== 8 && code.length !== 12 && code.length !== 13) return true;
|
|
35
|
+
const digits = code.split('').map(Number);
|
|
36
|
+
const check = digits.pop() as number;
|
|
37
|
+
// From the rightmost data digit, weights alternate 3,1,3,1…
|
|
38
|
+
let sum = 0;
|
|
39
|
+
for (let i = digits.length - 1, weight = 3; i >= 0; i -= 1, weight = weight === 3 ? 1 : 3) {
|
|
40
|
+
sum += digits[i] * weight;
|
|
41
|
+
}
|
|
42
|
+
const expected = (10 - (sum % 10)) % 10;
|
|
43
|
+
return expected === check;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The other printing of the same UPC-A: `0`+12 digits -> the 12; 12 digits -> `0`+12; anything else undefined.
|
|
47
|
+
* Ported from the UPC-A <-> EAN-13 branch of v2 barcodeMatchCandidates (sync-core/src/barcodeResolve.ts).
|
|
48
|
+
* Match the twin against barcodes only, never SKUs (v2 BARCODE_SYMBOLOGY_FIELDS excludes sku). */
|
|
49
|
+
export function retailCodeTwin(code: string): string | undefined {
|
|
50
|
+
const trimmed = code.trim();
|
|
51
|
+
if (/^0\d{12}$/.test(trimmed)) return trimmed.slice(1);
|
|
52
|
+
if (/^\d{12}$/.test(trimmed)) return `0${trimmed}`;
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function looksRetail(code: string, symbology?: string): boolean {
|
|
57
|
+
// Explicit symbology is authoritative: numeric code128/qr/upc_e must pass.
|
|
58
|
+
if (symbology) return RETAIL_SYMBOLOGIES.has(symbology.toLowerCase());
|
|
59
|
+
// Unlabelled length 8 is ambiguous between EAN-8 and UPC-E; gate only 12/13.
|
|
60
|
+
return /^\d+$/.test(code) && (code.length === 12 || code.length === 13);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function createScanSession(options: ScanSessionOptions): ScanSession {
|
|
64
|
+
const cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS;
|
|
65
|
+
const now = options.now ?? Date.now;
|
|
66
|
+
// Per-code cooldown starts at the last accepted read for trigger sources.
|
|
67
|
+
const cooldownFrom = new Map<string, number>();
|
|
68
|
+
const offer = (rawCode: string, symbology?: string): ScanOfferResult => {
|
|
69
|
+
const at = now();
|
|
70
|
+
// Normalize first so cooldown keys and downstream consumers see the same code.
|
|
71
|
+
const code = normalizeRetailCode(rawCode, symbology);
|
|
72
|
+
if (looksRetail(code, symbology) && !hasValidRetailCheckDigit(code)) {
|
|
73
|
+
return { accepted: false, reason: 'bad-check-digit' };
|
|
74
|
+
}
|
|
75
|
+
const lastAt = cooldownFrom.get(code);
|
|
76
|
+
if (lastAt !== undefined && at - lastAt < cooldownMs) {
|
|
77
|
+
return { accepted: false, reason: 'cooldown' };
|
|
78
|
+
}
|
|
79
|
+
cooldownFrom.set(code, at);
|
|
80
|
+
options.onAccept(code, symbology);
|
|
81
|
+
return { accepted: true };
|
|
82
|
+
};
|
|
83
|
+
return { offer, reset: () => { cooldownFrom.clear(); } };
|
|
84
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { useEffect, useRef } from 'react';
|
|
2
|
+
import { createWedgeDetector, DEFAULT_MIN_SCAN_CHARS, DEFAULT_WEDGE_SETTINGS } from './wedge-detector';
|
|
3
|
+
|
|
4
|
+
export interface UseBarcodeScannerOptions {
|
|
5
|
+
onScan: (code: string) => void;
|
|
6
|
+
/** Listen only while true (default true). */
|
|
7
|
+
enabled?: boolean;
|
|
8
|
+
threshold?: number;
|
|
9
|
+
prefix?: string;
|
|
10
|
+
suffix?: string;
|
|
11
|
+
minChars?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Listen for keyboard-wedge scans outside INPUT/TEXTAREA, with a minimum length gate.
|
|
15
|
+
* Ported from WCPOS v2 packages/core/src/screens/main/hooks/barcodes/use-barcode-detection.ts (monorepo 5ac185b0).
|
|
16
|
+
* @example
|
|
17
|
+
* useBarcodeScanner({ onScan: (code) => {
|
|
18
|
+
* const twin = retailCodeTwin(code);
|
|
19
|
+
* const entry = findEntryByCode(entries, code)
|
|
20
|
+
* ?? (twin ? entries.find(({ variant }) => variant.barcode === twin) : undefined);
|
|
21
|
+
* if (entry) addEntryToCart(builder, entry, traits, currency);
|
|
22
|
+
* else setSearchTerm(code); // searchProducts returns just the exact barcode/SKU matches
|
|
23
|
+
* } });
|
|
24
|
+
*/
|
|
25
|
+
export function useBarcodeScanner(options: UseBarcodeScannerOptions): void {
|
|
26
|
+
const latest = useRef(options);
|
|
27
|
+
latest.current = options;
|
|
28
|
+
const enabled = options.enabled ?? true;
|
|
29
|
+
useEffect(() => {
|
|
30
|
+
if (!enabled) return;
|
|
31
|
+
const detectorOptions = {
|
|
32
|
+
getSettings: () => ({
|
|
33
|
+
threshold: latest.current.threshold ?? DEFAULT_WEDGE_SETTINGS.threshold,
|
|
34
|
+
prefix: latest.current.prefix ?? '',
|
|
35
|
+
suffix: latest.current.suffix ?? '',
|
|
36
|
+
}),
|
|
37
|
+
onScan: (code: string) => {
|
|
38
|
+
if (code.length >= (latest.current.minChars ?? DEFAULT_MIN_SCAN_CHARS)) {
|
|
39
|
+
latest.current.onScan(code);
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
let detector = createWedgeDetector(detectorOptions);
|
|
44
|
+
const handler = (e: KeyboardEvent) => {
|
|
45
|
+
const tagName = (e.target as HTMLElement | null)?.tagName;
|
|
46
|
+
if (tagName === 'INPUT' || tagName === 'TEXTAREA') {
|
|
47
|
+
detector.dispose();
|
|
48
|
+
detector = createWedgeDetector(detectorOptions);
|
|
49
|
+
} else if (detector.handleKey(e.key)) {
|
|
50
|
+
e.preventDefault();
|
|
51
|
+
e.stopPropagation();
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
// v2 uses keydown because keyup gave lowercase.
|
|
55
|
+
window.addEventListener('keydown', handler, { capture: true });
|
|
56
|
+
return () => {
|
|
57
|
+
window.removeEventListener('keydown', handler, { capture: true });
|
|
58
|
+
detector.dispose();
|
|
59
|
+
};
|
|
60
|
+
}, [enabled]);
|
|
61
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Ported from WCPOS v2 packages/scanner/src/wedge-detector.ts (monorepo 5ac185b0).
|
|
2
|
+
/** The wedge detector distinguishes scanner bursts from typing using a folded
|
|
3
|
+
* running average of inter-key gaps. Live and replay paths share the reducer. */
|
|
4
|
+
export interface WedgeSettings {
|
|
5
|
+
/** Folded-average gap (ms) below which input latches as a scan. */
|
|
6
|
+
threshold: number;
|
|
7
|
+
/** Stripped only when it equals the first key. */
|
|
8
|
+
prefix: string;
|
|
9
|
+
/** Stripped only when it equals the last key. */
|
|
10
|
+
suffix: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** v2 store defaults: threshold 24 ms (stores.ts barcode_scanning_avg_time_input_threshold), no prefix/suffix. */
|
|
14
|
+
export const DEFAULT_WEDGE_SETTINGS: WedgeSettings = { threshold: 24, prefix: '', suffix: '' };
|
|
15
|
+
/** v2 store default barcode_scanning_min_chars. */
|
|
16
|
+
export const DEFAULT_MIN_SCAN_CHARS = 8;
|
|
17
|
+
/** End-of-scan settle: a burst is complete this long after its last key. */
|
|
18
|
+
export const WEDGE_END_OF_SCAN_MS = 150;
|
|
19
|
+
|
|
20
|
+
export interface WedgeState {
|
|
21
|
+
avg: number;
|
|
22
|
+
detecting: boolean;
|
|
23
|
+
stack: string[];
|
|
24
|
+
lastTimeMs: number | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createWedgeState(): WedgeState {
|
|
28
|
+
return { avg: 0, detecting: false, stack: [], lastTimeMs: null };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Fold one key, mutating and returning state. Kept bug-for-bug with v2:
|
|
32
|
+
* only length-1 keys advance timing; the first gap is +Infinity; the average
|
|
33
|
+
* folds as (avg + gap) / 2. Scanning latches below threshold for the burst;
|
|
34
|
+
* a slow key outside a burst resets the average and restarts the stack. */
|
|
35
|
+
export function foldWedgeKey(state: WedgeState, key: string, timeMs: number, threshold: number): WedgeState {
|
|
36
|
+
if (key.length !== 1) return state;
|
|
37
|
+
let gap = Number.POSITIVE_INFINITY;
|
|
38
|
+
if (state.lastTimeMs !== null) gap = timeMs - state.lastTimeMs;
|
|
39
|
+
state.avg = state.avg === 0 ? gap : (state.avg + gap) / 2;
|
|
40
|
+
if (state.detecting || state.avg < threshold) {
|
|
41
|
+
state.detecting = true;
|
|
42
|
+
state.stack.push(key);
|
|
43
|
+
} else {
|
|
44
|
+
state.avg = 0;
|
|
45
|
+
state.stack = [key];
|
|
46
|
+
}
|
|
47
|
+
state.lastTimeMs = timeMs;
|
|
48
|
+
return state;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Strip a configured prefix/suffix only when it equals the single key at
|
|
52
|
+
* that edge of the stack — never as a substring. */
|
|
53
|
+
export function stripBoundary(stack: string[], settings: WedgeSettings): string {
|
|
54
|
+
const inputStack = [...stack];
|
|
55
|
+
if (settings.prefix && inputStack[0] === settings.prefix) inputStack.shift();
|
|
56
|
+
if (settings.suffix && inputStack[inputStack.length - 1] === settings.suffix) inputStack.pop();
|
|
57
|
+
return inputStack.join('');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface TraceKey { key: string; timeMs: number; }
|
|
61
|
+
export interface WedgeReplayResult {
|
|
62
|
+
/** Whether the detector would latch onto this trace as a scan. */
|
|
63
|
+
detectedAsScan: boolean;
|
|
64
|
+
/** The barcode the detector would emit, with prefix/suffix stripped. */
|
|
65
|
+
code: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Replay the detector over a completed keystroke trace. */
|
|
69
|
+
export function replayWedgeDetector(keys: TraceKey[], settings: WedgeSettings): WedgeReplayResult {
|
|
70
|
+
const state = createWedgeState();
|
|
71
|
+
for (const entry of keys) foldWedgeKey(state, entry.key, entry.timeMs, settings.threshold);
|
|
72
|
+
if (!state.detecting) return { detectedAsScan: false, code: '' };
|
|
73
|
+
return { detectedAsScan: true, code: stripBoundary(state.stack, settings) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface WedgeDetectorOptions {
|
|
77
|
+
/** Read current settings per keystroke so live changes apply. */
|
|
78
|
+
getSettings: () => WedgeSettings;
|
|
79
|
+
/** A completed burst, prefix/suffix already stripped. */
|
|
80
|
+
onScan: (code: string) => void;
|
|
81
|
+
/** Injectable clock/timers so hosts and tests control time. */
|
|
82
|
+
now?: () => number;
|
|
83
|
+
setTimeout?: (fn: () => void, ms: number) => unknown;
|
|
84
|
+
clearTimeout?: (handle: unknown) => void;
|
|
85
|
+
}
|
|
86
|
+
export interface WedgeDetector {
|
|
87
|
+
/** True for a latched burst key: the host must prevent its default action. */
|
|
88
|
+
handleKey: (key: string, timeMs?: number) => boolean;
|
|
89
|
+
/** Cancel any pending end-of-scan timer on host teardown. */
|
|
90
|
+
dispose: () => void;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Stream keys through the reducer, emitting after the settle window and
|
|
94
|
+
* once the quiet period exceeds the threshold, mirroring the original hook. */
|
|
95
|
+
export function createWedgeDetector(options: WedgeDetectorOptions): WedgeDetector {
|
|
96
|
+
const now = options.now ?? Date.now;
|
|
97
|
+
const schedule = options.setTimeout ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));
|
|
98
|
+
const cancel = options.clearTimeout ?? ((handle: unknown) => clearTimeout(handle as never));
|
|
99
|
+
let state = createWedgeState();
|
|
100
|
+
let timer: unknown = null;
|
|
101
|
+
const clearTimer = () => {
|
|
102
|
+
if (timer !== null) {
|
|
103
|
+
cancel(timer);
|
|
104
|
+
timer = null;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const handleKey = (key: string, timeMs?: number) => {
|
|
108
|
+
const time = timeMs ?? now();
|
|
109
|
+
const sinceLastMs = state.lastTimeMs === null ? Number.POSITIVE_INFINITY : time - state.lastTimeMs;
|
|
110
|
+
if (key.length !== 1) {
|
|
111
|
+
// Non-printable keys never advance the burst; only its terminator is consumed.
|
|
112
|
+
return (key === 'Enter' || key === 'Tab') && state.detecting && sinceLastMs <= WEDGE_END_OF_SCAN_MS;
|
|
113
|
+
}
|
|
114
|
+
const settings = options.getSettings();
|
|
115
|
+
foldWedgeKey(state, key, time, settings.threshold);
|
|
116
|
+
if (!state.detecting) return false;
|
|
117
|
+
clearTimer();
|
|
118
|
+
function settle() {
|
|
119
|
+
timer = null;
|
|
120
|
+
const current = options.getSettings();
|
|
121
|
+
if (state.detecting && now() - (state.lastTimeMs || 0) > current.threshold) {
|
|
122
|
+
const code = stripBoundary(state.stack, current);
|
|
123
|
+
// Reset for the next burst, deliberately keeping lastTimeMs.
|
|
124
|
+
const lastTimeMs = state.lastTimeMs;
|
|
125
|
+
state = createWedgeState();
|
|
126
|
+
state.lastTimeMs = lastTimeMs;
|
|
127
|
+
options.onScan(code);
|
|
128
|
+
} else if (state.detecting) {
|
|
129
|
+
// A threshold at or above the settle window must not latch forever.
|
|
130
|
+
timer = schedule(settle, WEDGE_END_OF_SCAN_MS);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
timer = schedule(settle, WEDGE_END_OF_SCAN_MS);
|
|
134
|
+
return state.detecting && sinceLastMs <= WEDGE_END_OF_SCAN_MS;
|
|
135
|
+
};
|
|
136
|
+
return { handleKey, dispose: clearTimer };
|
|
137
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port of v2's cash rounding: packages/order-math/src/payments/rounding.ts and
|
|
3
|
+
* packages/core/src/screens/main/pos/checkout/tender/tender-figures.ts.
|
|
4
|
+
* v2's tender LEDGER: "a partial or short cash entry and every other method keep full precision".
|
|
5
|
+
* Local figures only; writing the rounding as an order line is unit 24.
|
|
6
|
+
*/
|
|
7
|
+
import type { PaymentMethodDescriptor, PaymentRounding } from '@tallyui/core';
|
|
8
|
+
import { appliedMinor, type TenderState } from './tender-state';
|
|
9
|
+
|
|
10
|
+
/** How the method rounds to its increment. */
|
|
11
|
+
export type RoundingMode = NonNullable<PaymentRounding>['mode'];
|
|
12
|
+
|
|
13
|
+
/** v2 roundToIncrement; also the identity for an increment that is not an integer. */
|
|
14
|
+
export function roundToIncrement(minor: number, incrementMinor: number, mode: RoundingMode): number {
|
|
15
|
+
if (!Number.isInteger(incrementMinor) || incrementMinor <= 1) return minor;
|
|
16
|
+
const remainder = minor % incrementMinor;
|
|
17
|
+
if (remainder === 0) return minor;
|
|
18
|
+
const down = minor - remainder;
|
|
19
|
+
if (mode === 'down') return down;
|
|
20
|
+
if (mode === 'up') return down + incrementMinor;
|
|
21
|
+
return remainder * 2 >= incrementMinor ? down + incrementMinor : down;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The balance under a manual method's rounding, with its signed difference. */
|
|
25
|
+
export function roundedDue(
|
|
26
|
+
balanceMinor: number,
|
|
27
|
+
method: PaymentMethodDescriptor | null,
|
|
28
|
+
): { dueMinor: number; roundingMinor: number } {
|
|
29
|
+
const rounding = method?.capture.mode === 'manual' ? method.defaults.rounding : null;
|
|
30
|
+
if (!rounding) return { dueMinor: balanceMinor, roundingMinor: 0 };
|
|
31
|
+
const dueMinor = roundToIncrement(balanceMinor, rounding.incrementMinor, rounding.mode);
|
|
32
|
+
return { dueMinor, roundingMinor: dueMinor - balanceMinor };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether the leg reaches the rounded due and the tendered amount covers it. */
|
|
36
|
+
export function settlesAtRoundedDue(facts: {
|
|
37
|
+
amountMinor: number;
|
|
38
|
+
tenderedMinor: number;
|
|
39
|
+
balanceMinor: number;
|
|
40
|
+
dueMinor: number;
|
|
41
|
+
}): boolean {
|
|
42
|
+
const { amountMinor, tenderedMinor, balanceMinor, dueMinor } = facts;
|
|
43
|
+
return amountMinor >= Math.min(balanceMinor, dueMinor) && tenderedMinor >= dueMinor;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Local tender figures under the method's cash rounding. */
|
|
47
|
+
export interface TenderRounding {
|
|
48
|
+
/** The balance under the method's rounding (the balance itself when none applies). */
|
|
49
|
+
roundedDueMinor: number;
|
|
50
|
+
/** `roundedDueMinor - balanceMinor` when the entry settles at the rounded due, else 0. Signed. */
|
|
51
|
+
roundingMinor: number;
|
|
52
|
+
/** The entry as the cashier sees it: an untouched prefill of the balance shows the rounded due. */
|
|
53
|
+
entryMinor: number;
|
|
54
|
+
/** What the entry applies to the order: the rounded due when rounding applies, else the capped entry. */
|
|
55
|
+
appliedMinor: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Figure the displayed entry and applied amount, rounding only a leg that settles at the due. */
|
|
59
|
+
export function tenderRounding(
|
|
60
|
+
state: Pick<TenderState, 'entryMinor' | 'entryDirty'>,
|
|
61
|
+
balanceMinor: number,
|
|
62
|
+
method: PaymentMethodDescriptor | null,
|
|
63
|
+
): TenderRounding {
|
|
64
|
+
const roundedDueMinor = roundedDue(balanceMinor, method).dueMinor;
|
|
65
|
+
const entryMinor = !state.entryDirty && state.entryMinor === balanceMinor ? roundedDueMinor : state.entryMinor;
|
|
66
|
+
const legMinor = appliedMinor(entryMinor, balanceMinor);
|
|
67
|
+
const roundingMinor = settlesAtRoundedDue({
|
|
68
|
+
amountMinor: legMinor,
|
|
69
|
+
tenderedMinor: entryMinor,
|
|
70
|
+
balanceMinor,
|
|
71
|
+
dueMinor: roundedDueMinor,
|
|
72
|
+
}) ? roundedDueMinor - balanceMinor : 0;
|
|
73
|
+
return { roundedDueMinor, roundingMinor, entryMinor, appliedMinor: roundingMinor !== 0 ? roundedDueMinor : legMinor };
|
|
74
|
+
}
|
package/src/tender/index.ts
CHANGED
|
@@ -2,3 +2,7 @@ export { tenderReducer, initTenderState, initialTenderState, appliedMinor, chang
|
|
|
2
2
|
export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg } from './tender-state';
|
|
3
3
|
export { tenderVoidSchema, tenderVoidCollection } from './tender-void';
|
|
4
4
|
export type { TenderVoid } from './tender-void';
|
|
5
|
+
export { roundedDue, tenderRounding } from './cash-rounding';
|
|
6
|
+
export type { TenderRounding } from './cash-rounding';
|
|
7
|
+
export { legStatus, countsTowardPaid, isInMotion, capturedMinor, inMotionMinor, canMoveLeg, canVoidLeg } from './payment-legs';
|
|
8
|
+
export type { PaymentLegStatus } from './payment-legs';
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** Local sale state; the order.create wire does not carry payment status yet. */
|
|
2
|
+
import type { PaymentMethodDescriptor } from '@tallyui/core';
|
|
3
|
+
|
|
4
|
+
export type PaymentLegStatus = 'pending' | 'authorized' | 'captured' | 'failed' | 'voided';
|
|
5
|
+
type Leg = { amountMinor: number; status?: PaymentLegStatus };
|
|
6
|
+
|
|
7
|
+
const moves: Record<PaymentLegStatus, readonly PaymentLegStatus[]> = {
|
|
8
|
+
pending: ['authorized', 'captured', 'failed', 'voided'],
|
|
9
|
+
authorized: ['captured', 'failed', 'voided'],
|
|
10
|
+
captured: ['voided'],
|
|
11
|
+
failed: [],
|
|
12
|
+
voided: [],
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Defaults legacy legs to captured using v2 payments/types.ts PaymentStatus. */
|
|
16
|
+
export function legStatus(leg: { status?: PaymentLegStatus }): PaymentLegStatus {
|
|
17
|
+
return leg.status ?? 'captured';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Only captured money is paid: v2 payments/derive.ts countsTowardPaid (ADR 0040 D6). */
|
|
21
|
+
export function countsTowardPaid(leg: { status?: PaymentLegStatus }): boolean {
|
|
22
|
+
return legStatus(leg) === 'captured';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Pending and authorized are in motion: v2 payments/ledger.ts isInMotionPaymentStatus. */
|
|
26
|
+
export function isInMotion(leg: { status?: PaymentLegStatus }): boolean {
|
|
27
|
+
return legStatus(leg) === 'pending' || legStatus(leg) === 'authorized';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Sums integer minor units using v2 payments/derive.ts countsTowardPaid. */
|
|
31
|
+
export function capturedMinor(legs: readonly Leg[]): number {
|
|
32
|
+
return legs.reduce((sum, leg) => sum + (countsTowardPaid(leg) ? leg.amountMinor : 0), 0);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Sums holds in integer minor units using v2 payments/ledger.ts isInMotionPaymentStatus. */
|
|
36
|
+
export function inMotionMinor(legs: readonly Leg[]): number {
|
|
37
|
+
return legs.reduce((sum, leg) => sum + (isInMotion(leg) ? leg.amountMinor : 0), 0);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Local transitions for v2 payments/ledger.ts isInMotionPaymentStatus and isFinalPaymentStatus. */
|
|
41
|
+
export function canMoveLeg(from: PaymentLegStatus, to: PaymentLegStatus): boolean {
|
|
42
|
+
return moves[from].includes(to);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Voids live legs, captured only manually: v2 payments/ledger.ts partitionVoidableRows. */
|
|
46
|
+
export function canVoidLeg(leg: { status?: PaymentLegStatus }, method: PaymentMethodDescriptor): boolean {
|
|
47
|
+
return method.capabilities.void && (isInMotion(leg) || (legStatus(leg) === 'captured' && method.capture.mode === 'manual'));
|
|
48
|
+
}
|