@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
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
|
+
import { displayReducer, initialDisplayState, type DisplayState } from './display-state';
|
|
3
|
+
import { makeEnvelope, type DisplayTemplate } from './protocol';
|
|
4
|
+
import type { DisplayTransport } from './transport';
|
|
5
|
+
|
|
6
|
+
export const DISPLAY_TEMPLATE: DisplayTemplate = { id: 'default', version: 1 };
|
|
7
|
+
/** The hello is re-sent until a config answers it, so a till opened after the display still finds it. */
|
|
8
|
+
export const HELLO_RETRY_MS = 2000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The customer display's side: says `display.hello`, then shows what the till sends. As v2's display page
|
|
12
|
+
* (Pro packages/display/src/session.ts), nothing is applied before the `display.config` that answers this hello.
|
|
13
|
+
*/
|
|
14
|
+
export function useCustomerDisplay(transport: DisplayTransport | null): DisplayState {
|
|
15
|
+
const [state, setState] = useState(initialDisplayState);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
if (!transport) return;
|
|
18
|
+
const hello = makeEnvelope('display.hello', { template: DISPLAY_TEMPLATE });
|
|
19
|
+
let configured = false;
|
|
20
|
+
const retry = setInterval(() => transport.send(hello), HELLO_RETRY_MS);
|
|
21
|
+
const unsubscribe = transport.onMessage((envelope) => {
|
|
22
|
+
if (!configured) {
|
|
23
|
+
if (envelope.action !== 'display.config' || envelope.id !== hello.id) return;
|
|
24
|
+
configured = true;
|
|
25
|
+
clearInterval(retry);
|
|
26
|
+
}
|
|
27
|
+
setState((previous) => displayReducer(previous, envelope));
|
|
28
|
+
});
|
|
29
|
+
transport.send(hello);
|
|
30
|
+
return () => {
|
|
31
|
+
clearInterval(retry);
|
|
32
|
+
unsubscribe();
|
|
33
|
+
};
|
|
34
|
+
}, [transport]);
|
|
35
|
+
return state;
|
|
36
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
export { createLogger, consoleSink, callbackSink } from './logging';
|
|
3
3
|
export type { Logger, LogSink, LogEntry, LogLevel } from './logging';
|
|
4
4
|
|
|
5
|
+
// CSV
|
|
6
|
+
export { csvCell, csvFromCells, toCsv } from './csv';
|
|
7
|
+
export type { CsvColumn } from './csv';
|
|
8
|
+
|
|
5
9
|
// Currency
|
|
6
10
|
export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './currency';
|
|
7
11
|
export type { CurrencyProviderProps } from './currency';
|
|
@@ -17,6 +21,19 @@ export type { TaxRateMap, TaxContext } from './tax';
|
|
|
17
21
|
export { resolveStoreSettings, useStoreSettings, withPricingContext, taxProviderProps } from './store-settings';
|
|
18
22
|
export type { StoreSettingsResolution, ResolveStoreSettingsOptions, StoreSettingsState } from './store-settings';
|
|
19
23
|
|
|
24
|
+
// Cashier permissions (v2 parity A12)
|
|
25
|
+
export { can, useCashier } from './cashier';
|
|
26
|
+
export type { CashierState } from './cashier';
|
|
27
|
+
|
|
28
|
+
// App settings
|
|
29
|
+
export {
|
|
30
|
+
UI_SCALES, UI_THEMES, APP_SETTING_DEFINITIONS, DEFAULT_APP_SETTINGS, appSettingSchema,
|
|
31
|
+
appSettingCollection, resolveAppSettings, readAppSettings, appSettings$, writeAppSetting, useAppSettings,
|
|
32
|
+
} from './app-settings';
|
|
33
|
+
export type {
|
|
34
|
+
UiScale, UiTheme, AppSettings, AppSettingKey, AppSettingDefinition, AppSettingDoc, AppSettingCollection,
|
|
35
|
+
} from './app-settings';
|
|
36
|
+
|
|
20
37
|
// RxDB reads past the query cache, and live lists that can't leave it stale (RxDB 16.21.1 bug 4)
|
|
21
38
|
export { readFresh, countFresh, watchFresh } from './rxdb';
|
|
22
39
|
|
|
@@ -55,34 +72,71 @@ export type {
|
|
|
55
72
|
export { buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, RECEIPT_SCHEMA_VERSION } from './receipt';
|
|
56
73
|
export type { ReceiptData, ReceiptLineItem, ReceiptConfig, ReceiptSoftware, ReceiptRegister, ReceiptFiscal } from './receipt';
|
|
57
74
|
|
|
75
|
+
// Receipt templates
|
|
76
|
+
export { parseXml, renderHtml, sanitizeHtml, renderReceiptTemplate, renderLogiclessTemplate, renderThermalPreview, receiptTemplateData, DEFAULT_RECEIPT_TEMPLATES, PAPER_COLUMNS, renderReceiptHtml } from './receipt-template';
|
|
77
|
+
export type { ThermalNode, ReceiptNode, SanitizeHtmlOptions, RenderSanitizeOptions, ReceiptTemplateRow, ReceiptTemplateLine, ReceiptTemplateData, ReceiptTemplateOptions, ReceiptPaper, RenderReceiptOptions } from './receipt-template';
|
|
78
|
+
|
|
79
|
+
// Customer display
|
|
80
|
+
export { DISPLAY_PROTOCOL_VERSION, DISPLAY_ACTIONS, makeEnvelope, displayCart, decode as decodeDisplayMessage, encode as encodeDisplayMessage, messageBytes, MAX_MESSAGE_BYTES, displayReducer, initialDisplayState } from './customer-display';
|
|
81
|
+
export type { PaymentPhase, DisplayTemplate, DisplayCart, DisplayPayment, DisplayConfig, DisplayPayloads, DisplayAction, DisplayEnvelope, DecodeRefusal, DecodeResult, DisplayView, DisplayState } from './customer-display';
|
|
82
|
+
export { DISPLAY_CHANNEL, createBroadcastDisplayTransport, createDisplayLink, useCustomerDisplay, DISPLAY_TEMPLATE, HELLO_RETRY_MS } from './customer-display';
|
|
83
|
+
export type { DisplayTransport, BroadcastChannelLike, DisplayLink, DisplayClock } from './customer-display';
|
|
84
|
+
|
|
58
85
|
// Product
|
|
59
86
|
export { searchProducts, sortProducts, productSortValue, PRODUCT_SORT_FIELDS, type ProductSort, type ProductSortValue, catalogueViewReducer, normalizeCatalogueViewState, resolveGridColumns, DEFAULT_CATALOGUE_VIEW_STATE, type CatalogueView, type CatalogueGridColumns, type CatalogueViewState, type CatalogueViewAction, withStockOverlay, getProductStock, stockOverlay$, stockOverlayAsOf$, productCategories, listCategories, inCategory } from './product';
|
|
60
87
|
|
|
88
|
+
// Scanner
|
|
89
|
+
export { DEFAULT_WEDGE_SETTINGS, DEFAULT_MIN_SCAN_CHARS, WEDGE_END_OF_SCAN_MS, createWedgeState, foldWedgeKey, stripBoundary, replayWedgeDetector, createWedgeDetector, DEFAULT_COOLDOWN_MS, normalizeRetailCode, hasValidRetailCheckDigit, retailCodeTwin, createScanSession, useBarcodeScanner } from './scanner';
|
|
90
|
+
export type { WedgeSettings, WedgeState, TraceKey, WedgeReplayResult, WedgeDetectorOptions, WedgeDetector, ScanRejectReason, ScanOfferResult, ScanSessionOptions, ScanSession, UseBarcodeScannerOptions } from './scanner';
|
|
91
|
+
|
|
92
|
+
// Payment drivers
|
|
93
|
+
export { createPaymentDriverRegistry, driverForMethod, createSimulatedDriver, SIMULATED_PROVIDER, SIMULATED_TIMING } from './payment-driver';
|
|
94
|
+
export type {
|
|
95
|
+
DriverCapabilities, ReaderInfo, DriverStatus, DriverAvailability, CollectInput,
|
|
96
|
+
CollectOutcome, CollectResult, DriverStatusSource, PaymentDriver, PaymentDriverRegistry,
|
|
97
|
+
SimulatedReaderId, SimulatedDriverOptions,
|
|
98
|
+
} from './payment-driver';
|
|
99
|
+
|
|
100
|
+
// Printing
|
|
101
|
+
export {
|
|
102
|
+
PrintError, toPrintError, createPrintQueue, SYSTEM_PRINTER_ID, PRINTER_PROFILES_COLLECTION, printerProfileSchema,
|
|
103
|
+
printerProfileCollection, addPrinterProfileCollection, createSystemPrintTransport, SYSTEM_PRINT_TIMING,
|
|
104
|
+
escpos, encodeEscPos, createEscPosTransport, ESCPOS_CODE_PAGES,
|
|
105
|
+
} from './print';
|
|
106
|
+
export type {
|
|
107
|
+
PrintJob, PrintJobKind, PrintErrorCode, PrintTransport, PrintQueue, PrintQueueOptions, PrintQueueState,
|
|
108
|
+
PrinterProfile, PrinterProfileCollection, SystemPrintTransportOptions,
|
|
109
|
+
EscPosBuilder, EncodeEscPosOptions, EscPosSink, EscPosTransportOptions,
|
|
110
|
+
} from './print';
|
|
111
|
+
|
|
61
112
|
// Sale
|
|
62
|
-
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED } from './sale';
|
|
63
|
-
export type { SaleStage, CatalogueEntry, SaleDiscountCodes, SaleDiscountState } from './sale';
|
|
113
|
+
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_IN_TENDER, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED, cartQuantities } from './sale';
|
|
114
|
+
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, CartQuantityLine } from './sale';
|
|
64
115
|
|
|
65
116
|
export { uuidv7, finalizeOrder, toOrderCreateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
|
|
66
117
|
export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
|
|
118
|
+
export { noteDelivery, type NoteDelivery } from './pos-order';
|
|
67
119
|
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions } from './pos-order';
|
|
68
120
|
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, useOrderOutbox, outboxLogger } from './outbox';
|
|
69
|
-
export { createRegisterOutbox, useRegisterOutbox } from './outbox';
|
|
121
|
+
export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
|
|
70
122
|
export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
|
|
123
|
+
export type { OutboxCounts, OutboxHealth, UseOutboxHealthOptions, UseOutboxHealthResult } from './outbox';
|
|
71
124
|
export { createBackendNotFound } from './outbox/backend-not-found';
|
|
72
125
|
export type { BackendNotFound } from './outbox/backend-not-found';
|
|
73
126
|
export type { HttpTransportOptions, OrderOutboxOptions, OrderOutbox, TransportOutcome, CommandTransport, OrderTransportContext, OutboxState, UseOrderOutboxOptions, UseOrderOutboxResult } from './outbox';
|
|
74
|
-
export { sendOrderRefund, type OrderRefundOutcome, posRefundSchema, posRefundCollection, submitOrderRefund, RefundAnswerPendingError, type PosRefund, type PosRefundStatus, type PosRefundCollection } from './refund';
|
|
75
|
-
export {
|
|
76
|
-
export
|
|
127
|
+
export { sendOrderRefund, type OrderRefundOutcome, posRefundSchema, posRefundCollection, submitOrderRefund, RefundAnswerPendingError, type PosRefund, type PosRefundStatus, type PosRefundCollection, refundableLines, priceRefund } from './refund';
|
|
128
|
+
export type { RefundableOrderLine, EarlierRefund, RefundableLine, PricedRefundLine, PricedRefund } from './refund';
|
|
129
|
+
export { tenderReducer, initTenderState, initialTenderState, appliedMinor, changeMinor, quickTenderedAmounts, evenSplitShareMinor, activePlan, planLegs, MAX_TENDER_MINOR, tenderVoidSchema, tenderVoidCollection, legStatus, countsTowardPaid, isInMotion, capturedMinor, inMotionMinor, canMoveLeg, canVoidLeg } from './tender';
|
|
130
|
+
export type { PaymentTransport, TenderView, TenderLineId, TenderPlan, SplitTab, TenderState, TenderKey, TenderAction, PlanLeg, TenderVoid, PaymentLegStatus } from './tender';
|
|
77
131
|
|
|
78
132
|
// Register
|
|
79
|
-
export { normalizeAmount, isServerDecimal, movementFieldError, deriveExpected, parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, denominationTotal, varianceText, denominations } from './register';
|
|
133
|
+
export { normalizeAmount, isServerDecimal, movementFieldError, deriveExpected, parseMinor, validAmount, countVariance, overThreshold, closeNeedsApproval, closureVariance, denominationTotal, varianceText, denominations } from './register';
|
|
80
134
|
export type { MovementType, LedgerRow, Movement } from './register';
|
|
81
135
|
export { registerSessionSchema, registerSessionCollection, cashMovementSchema, closureSchema } from './register';
|
|
82
136
|
export { addRegisterSessionCollection, RegisterSessionOpenClosedError, registerSessionsLogger, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS } from './register';
|
|
83
137
|
export type { RegisterSession, CashMovement, Closure } from './register';
|
|
84
|
-
export { registerCommandSchema, registerCommandCollection, registerCommandsLogger, sessionOpenCommand, sessionTransitionCommand, movementCommand, closureCommand, reconcileRegisterCommands, adoptRegisterResults, takeOverSession, abandonSession } from './register';
|
|
85
|
-
export type { RegisterCommand, RegisterCommandCollection } from './register';
|
|
138
|
+
export { registerCommandSchema, registerCommandCollection, registerCommandsLogger, sessionOpenCommand, sessionTransitionCommand, movementCommand, closureCommand, reconcileRegisterCommands, adoptRegisterResults, takeOverSession, abandonSession, isLiveAtStore, closureApprovalStatus, reapproveClosure, RegisterReapproveError } from './register';
|
|
139
|
+
export type { RegisterCommand, RegisterCommandCollection, ClosureApprovalStatus } from './register';
|
|
86
140
|
export { mintUuid, readRegister, ensureRegister, observeRegister$, getBoundRegisterId, readBoundRegister, bindRegister, unbindRegister, nextSaleCounter, mintClosureNumber, advancePerpetual, RegisterIdInvalidError } from './register';
|
|
87
141
|
export type { RegisterHost, RegisterCounters, RegisterBucket, RegisterStore, RegisterDocument } from './register';
|
|
88
142
|
export { RegisterSessionRequiredError, RegisterSessionClosedError, RegisterNeedsUpgradeError, RegisterSessionConflictError, RegisterTakeOverError, isKnownSessionStatus, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, openSessionSelector, requireOpenSession, stampSession, openSession, startCounting, backToSelling, closeSession, recordMovement, voidMovement, writeClosure } from './register';
|
|
@@ -90,4 +144,13 @@ export type { RegisterSessionCollection, CashMovementCollection, ClosureCollecti
|
|
|
90
144
|
export { deriveSettled, exportCsv, labelKeys, clampClosureScope, selectClosureRows } from './register';
|
|
91
145
|
export type { Correction, RecordedFigures, ClosureScope } from './register';
|
|
92
146
|
export { minorToDecimal, formatClosureDate, buildClosureDocument, buildXReportDocument, TAX_ROUNDING_MIXED_NOTE, registerFactsLogger, recordRegisterFact, type ClosureContext, type Actor, type RegisterFact } from './register';
|
|
93
|
-
export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type UseRegisterSessionOptions } from './register';
|
|
147
|
+
export { useRegisterSession, RegisterTenderInProgressError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type ApprovalNeeded, type UseRegisterSessionOptions } from './register';
|
|
148
|
+
export { roundedDue, tenderRounding } from './tender';
|
|
149
|
+
export type { TenderRounding } from './tender';
|
|
150
|
+
export { suggestFloat, type FloatSuggestion } from './register';
|
|
151
|
+
export { switchWarnings, handoverSlip } from './register';
|
|
152
|
+
export type { SwitchKind, SwitchWarning, SwitchWarningInput, SwitchWarnings, HandoverSlipInput, HandoverSlipData } from './register';
|
|
153
|
+
|
|
154
|
+
// Reports
|
|
155
|
+
export { salesFigures, marginOf, comparisonRange, daysOf, inRange, presetRange, DATE_PRESETS, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund } from './reports';
|
|
156
|
+
export type { StoreDay, DayRange, ReportCategory, ReportLine, ReportPayment, ReportTax, ReportOrder, ReportRefund, LineJoin, Margin, SalesTotals, PaymentRow, GroupRow, TaxRow, DayPoint, SalesFiguresInput, SalesFigures, DatePreset } from './reports';
|
|
@@ -3,6 +3,7 @@ import { resolvePrice, woocommerceTax, type woocommerceCoupons, type ProductTrai
|
|
|
3
3
|
import type { TaxContext } from '../tax/types';
|
|
4
4
|
import { taxMicros, roundMicrosToMinor, roundedTaxByRate } from '../tax/exact';
|
|
5
5
|
import { taxLogger } from '../tax/tax-provider';
|
|
6
|
+
import { capturedMinor, canMoveLeg, legStatus, type PaymentLegStatus } from '../tender/payment-legs';
|
|
6
7
|
import { allocateOrderDiscount } from './allocate-order-discount';
|
|
7
8
|
import { woocommerceLine, woocommerceTotals, woocommerceCouponReplay } from './woocommerce-tax';
|
|
8
9
|
import type {
|
|
@@ -105,6 +106,7 @@ export interface OrderBuilder {
|
|
|
105
106
|
applyOrderDiscount(discount: Discount): void;
|
|
106
107
|
removeDiscount(discountId: string): void;
|
|
107
108
|
addPayment(payment: Omit<Payment, 'id'>): string;
|
|
109
|
+
setPaymentStatus(paymentId: string, status: PaymentLegStatus): boolean;
|
|
108
110
|
removePayment(paymentId: string): void;
|
|
109
111
|
setCustomer(customer: CustomerSummary | null): void;
|
|
110
112
|
setNote(note: string): void;
|
|
@@ -301,7 +303,7 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
301
303
|
...(fees.length ? { fees: displayFees } : {}),
|
|
302
304
|
...(shipping.length ? { shipping: displayShipping } : {}),
|
|
303
305
|
};
|
|
304
|
-
const paidMinor = payments
|
|
306
|
+
const paidMinor = capturedMinor(payments);
|
|
305
307
|
const balanceDueMinor = Math.max(0, totalMinor - paidMinor);
|
|
306
308
|
const changeDueMinor = Math.max(0, paidMinor - totalMinor);
|
|
307
309
|
|
|
@@ -564,6 +566,14 @@ export function createOrderBuilder(options: OrderBuilderOptions): OrderBuilder {
|
|
|
564
566
|
return id;
|
|
565
567
|
},
|
|
566
568
|
|
|
569
|
+
setPaymentStatus(paymentId, status) {
|
|
570
|
+
const payment = payments.find((p) => p.id === paymentId);
|
|
571
|
+
if (!payment || !canMoveLeg(legStatus(payment), status)) return false;
|
|
572
|
+
payments = payments.map((p) => p.id === paymentId ? { ...p, status } : p);
|
|
573
|
+
emit();
|
|
574
|
+
return true;
|
|
575
|
+
},
|
|
576
|
+
|
|
567
577
|
removePayment(paymentId) {
|
|
568
578
|
payments = payments.filter((p) => p.id !== paymentId);
|
|
569
579
|
emit();
|
|
@@ -2,6 +2,7 @@ import { map, type Observable } from 'rxjs';
|
|
|
2
2
|
import type { RxCollection, RxJsonSchema } from 'rxdb';
|
|
3
3
|
import type { TaxContext } from '../tax/types';
|
|
4
4
|
import { customerRefusal } from '../pos-order/command';
|
|
5
|
+
import { capturedMinor } from '../tender/payment-legs';
|
|
5
6
|
import { createOrderBuilder, type OrderBuilder } from './order-builder';
|
|
6
7
|
import type { Order } from './types';
|
|
7
8
|
|
|
@@ -30,6 +31,19 @@ export interface ParkedOrderSummary {
|
|
|
30
31
|
totalMinor: number;
|
|
31
32
|
parkedAt: string;
|
|
32
33
|
source: 'local' | 'server';
|
|
34
|
+
/** Read from the draft's data (open-sale tabs, u19): the captured money, the balance still due and the first line's name. */
|
|
35
|
+
paidMinor?: number;
|
|
36
|
+
balanceDueMinor?: number;
|
|
37
|
+
firstItem?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function draftExtras(data: unknown): Pick<ParkedOrderSummary, 'paidMinor' | 'balanceDueMinor' | 'firstItem'> {
|
|
41
|
+
try {
|
|
42
|
+
const saved = JSON.parse(String(data)) as Partial<Order>;
|
|
43
|
+
return { paidMinor: capturedMinor(saved.payments ?? []), balanceDueMinor: saved.balanceDueMinor, firstItem: saved.lineItems?.[0]?.name };
|
|
44
|
+
} catch {
|
|
45
|
+
return {}; // an unreadable draft still lists, without these figures
|
|
46
|
+
}
|
|
33
47
|
}
|
|
34
48
|
|
|
35
49
|
export async function writeOrderDraft(drafts: RxCollection, snapshot: Order): Promise<string> {
|
|
@@ -111,6 +125,7 @@ export function restoreOrderDraft(saved: Order, options: { currency: string; tax
|
|
|
111
125
|
tenderedMinor: payment.tenderedMinor,
|
|
112
126
|
changeMinor: payment.changeMinor,
|
|
113
127
|
reference: payment.reference,
|
|
128
|
+
...(payment.status !== undefined ? { status: payment.status } : {}),
|
|
114
129
|
});
|
|
115
130
|
}
|
|
116
131
|
return builder;
|
|
@@ -128,6 +143,7 @@ export function parkedOrderSummaries$(drafts: RxCollection): Observable<ParkedOr
|
|
|
128
143
|
totalMinor: json.total ?? 0,
|
|
129
144
|
parkedAt: json.parkedAt ?? '',
|
|
130
145
|
source: 'local' as const,
|
|
146
|
+
...draftExtras(json.data),
|
|
131
147
|
};
|
|
132
148
|
}),
|
|
133
149
|
),
|
package/src/order/types.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Money, TaxRounding } from '@tallyui/core';
|
|
2
|
+
import type { PaymentLegStatus } from '../tender/payment-legs';
|
|
2
3
|
|
|
3
4
|
export interface OrderCoupon {
|
|
4
5
|
code: string; // lower-case code
|
|
@@ -29,9 +30,9 @@ export interface Order {
|
|
|
29
30
|
taxMinor: number; // settlement: rounded once per order, unless taxRounding says otherwise (#287)
|
|
30
31
|
totalMinor: number; // settlement: what the customer pays
|
|
31
32
|
display: DisplayTotals;
|
|
32
|
-
paidMinor: number;
|
|
33
|
-
balanceDueMinor: number; // max(0, total − paid)
|
|
34
|
-
changeDueMinor: number; // max(0, paid − total)
|
|
33
|
+
paidMinor: number; // captured legs only
|
|
34
|
+
balanceDueMinor: number; // max(0, total − paid), counting captured legs only
|
|
35
|
+
changeDueMinor: number; // max(0, paid − total), counting captured legs only
|
|
35
36
|
createdAt: string;
|
|
36
37
|
updatedAt: string;
|
|
37
38
|
}
|
|
@@ -135,6 +136,8 @@ export interface AppliedDiscount extends Discount {
|
|
|
135
136
|
export interface Payment {
|
|
136
137
|
id: string;
|
|
137
138
|
method: string;
|
|
139
|
+
/** Absent means captured; only captured legs count toward paidMinor. */
|
|
140
|
+
status?: PaymentLegStatus;
|
|
138
141
|
// For cash, record the full amount tendered here, not the capped amount: `finalizeOrder`
|
|
139
142
|
// caps it at the balance due and writes out `tenderedMinor`/`changeMinor` itself.
|
|
140
143
|
amountMinor: number;
|
package/src/outbox/index.ts
CHANGED
|
@@ -2,10 +2,14 @@ export { createHttpCommandTransport } from './http-transport';
|
|
|
2
2
|
export type { HttpTransportOptions } from './http-transport';
|
|
3
3
|
export { createOrderOutbox, isRequeueable } from './order-outbox';
|
|
4
4
|
export type { OrderOutboxOptions, OrderOutbox } from './order-outbox';
|
|
5
|
-
export { createRegisterOutbox } from './register-outbox';
|
|
5
|
+
export { createRegisterOutbox, isRegisterRequeueable } from './register-outbox';
|
|
6
6
|
export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';
|
|
7
7
|
export { useRegisterOutbox } from './use-register-outbox';
|
|
8
8
|
export type { UseRegisterOutboxOptions, UseRegisterOutboxResult } from './use-register-outbox';
|
|
9
9
|
export type { TransportOutcome, CommandTransport, OrderTransportContext, OutboxState } from './types';
|
|
10
10
|
export { useOrderOutbox, outboxLogger } from './use-order-outbox';
|
|
11
11
|
export type { UseOrderOutboxOptions, UseOrderOutboxResult } from './use-order-outbox';
|
|
12
|
+
export { summarizeOutboxHealth, watchOutboxHealth } from './outbox-health';
|
|
13
|
+
export type { OutboxCounts, OutboxHealth } from './outbox-health';
|
|
14
|
+
export { useOutboxHealth } from './use-outbox-health';
|
|
15
|
+
export type { UseOutboxHealthOptions, UseOutboxHealthResult } from './use-outbox-health';
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { combineLatest, distinctUntilChanged, map, type Observable } from 'rxjs';
|
|
2
|
+
import type { OutboxState } from './types';
|
|
3
|
+
|
|
4
|
+
export interface OutboxCounts {
|
|
5
|
+
/** `OutboxState.pending`. */
|
|
6
|
+
pending: number;
|
|
7
|
+
/** `OutboxState.rejected`, 0 when unset. */
|
|
8
|
+
rejected: number;
|
|
9
|
+
/** `OutboxState.stuck.commandIds.length`, 0 when unset. These rows are pending too. */
|
|
10
|
+
stuck: number;
|
|
11
|
+
}
|
|
12
|
+
export interface OutboxHealth {
|
|
13
|
+
/** The order outbox (`useOrderOutbox`): sales. */
|
|
14
|
+
sales: OutboxCounts;
|
|
15
|
+
/** The register outbox (`useRegisterOutbox`): till updates. */
|
|
16
|
+
tillUpdates: OutboxCounts;
|
|
17
|
+
/** Rejected plus stuck rows across both outboxes. Not `needsAttention()`'s list, which also holds applied orders with warnings. */
|
|
18
|
+
attention: number;
|
|
19
|
+
/** Either outbox parked after repeated 401s (`OutboxState.authRequired`): the cashier signs in again, then both flush. */
|
|
20
|
+
authRequired: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** The health of both outboxes from their states. Pure. */
|
|
23
|
+
export function summarizeOutboxHealth(sales: OutboxState, tillUpdates: OutboxState): OutboxHealth {
|
|
24
|
+
const salesCounts = { pending: sales.pending, rejected: sales.rejected ?? 0, stuck: sales.stuck?.commandIds.length ?? 0 };
|
|
25
|
+
const tillCounts = { pending: tillUpdates.pending, rejected: tillUpdates.rejected ?? 0, stuck: tillUpdates.stuck?.commandIds.length ?? 0 };
|
|
26
|
+
return { sales: salesCounts, tillUpdates: tillCounts,
|
|
27
|
+
attention: salesCounts.rejected + salesCounts.stuck + tillCounts.rejected + tillCounts.stuck,
|
|
28
|
+
authRequired: !!(sales.authRequired || tillUpdates.authRequired) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** summarizeOutboxHealth over both state streams (combineLatest), emitting only when a field changes. */
|
|
32
|
+
export function watchOutboxHealth(sales$: Observable<OutboxState>, tillUpdates$: Observable<OutboxState>): Observable<OutboxHealth> {
|
|
33
|
+
return combineLatest([sales$, tillUpdates$]).pipe(
|
|
34
|
+
map(([sales, tillUpdates]) => summarizeOutboxHealth(sales, tillUpdates)),
|
|
35
|
+
distinctUntilChanged((a, b) => a.sales.pending === b.sales.pending && a.sales.rejected === b.sales.rejected &&
|
|
36
|
+
a.sales.stuck === b.sales.stuck && a.tillUpdates.pending === b.tillUpdates.pending &&
|
|
37
|
+
a.tillUpdates.rejected === b.tillUpdates.rejected && a.tillUpdates.stuck === b.tillUpdates.stuck &&
|
|
38
|
+
a.attention === b.attention && a.authRequired === b.authRequired),
|
|
39
|
+
);
|
|
40
|
+
}
|
|
@@ -6,11 +6,29 @@ import type { RegisterSessionCollection } from '../register/session-store';
|
|
|
6
6
|
import { countFresh, readFresh } from '../rxdb';
|
|
7
7
|
import { createBackendNotFound, type BackendNotFound } from './backend-not-found';
|
|
8
8
|
import { STUCK_AFTER_MS } from './order-outbox';
|
|
9
|
+
import { safeErrorMessage, safeErrorString } from './safe-error';
|
|
9
10
|
import type { CommandTransport, OutboxState } from './types';
|
|
10
11
|
|
|
11
12
|
/** Final rejections that do not stop their register's ledger (ADR-078): the commands behind them are still sent. */
|
|
12
13
|
export const NON_BLOCKING_REJECTIONS: ReadonlySet<string> = new Set(['register_session_superseded', 'register_session_abandoned']);
|
|
13
14
|
|
|
15
|
+
/** Refused approvals (ADR-082 decision 6). Like NON_BLOCKING_REJECTIONS they do not stop their register's ledger,
|
|
16
|
+
* but its next `register.closure.submit` and every command after it wait: the store numbers closures in order. */
|
|
17
|
+
export const CLOSURE_HOLDING_REJECTIONS: ReadonlySet<string> = new Set(['register_approval_required', 'register_approval_invalid']);
|
|
18
|
+
|
|
19
|
+
// Codes the register requeue never resends (ADR-068 decision 5, ADR-078 decisions 4, 6 and 8): the store recorded
|
|
20
|
+
// these business conflicts, so the same id replays the refusal; superseded and abandoned are final; an already-open
|
|
21
|
+
// refusal has its own exits (Take over, Choose another register); idempotency_mismatch means the bytes differ.
|
|
22
|
+
// A refused approval replays at the store for its command id; recovery is a new command id (ADR-082 decisions 6 and 7).
|
|
23
|
+
const REGISTER_NOT_REQUEUEABLE: ReadonlySet<string> = new Set(['register_session_already_open',
|
|
24
|
+
'register_session_closed', 'register_approval_required', 'register_approval_invalid', 'register_closure_exists',
|
|
25
|
+
'register_closure_number_invalid', 'register_session_superseded', 'register_session_abandoned',
|
|
26
|
+
'register_supersede_forbidden', 'idempotency_mismatch']);
|
|
27
|
+
/** Whether the register outbox's requeue() resends a rejection with this code. */
|
|
28
|
+
export function isRegisterRequeueable(code: string | undefined): boolean {
|
|
29
|
+
return !REGISTER_NOT_REQUEUEABLE.has(code ?? '');
|
|
30
|
+
}
|
|
31
|
+
|
|
14
32
|
export interface RegisterOutboxOptions {
|
|
15
33
|
collection: RxCollection<RegisterCommand>;
|
|
16
34
|
/** The till's `register_sessions`. With it, a refused open (`register_session_already_open`) stops blocking its register
|
|
@@ -34,6 +52,10 @@ export interface RegisterOutboxOptions {
|
|
|
34
52
|
}
|
|
35
53
|
export interface RegisterOutbox {
|
|
36
54
|
flush(): Promise<void>;
|
|
55
|
+
/** Moves rejected commands (all, or those whose commandId is listed) back to pending in their ledger place, under
|
|
56
|
+
* the same commandId and payload, then flushes: a refusal the store did not record is weighed again on a resend
|
|
57
|
+
* of the same id (ADR-068 decision 5). Codes isRegisterRequeueable refuses are left. Resolves to the number requeued. */
|
|
58
|
+
requeue(commandIds?: string[]): Promise<number>;
|
|
37
59
|
start(): void;
|
|
38
60
|
stop(): void;
|
|
39
61
|
state$: Observable<OutboxState>;
|
|
@@ -77,7 +99,8 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
77
99
|
// pauses every clock (`pausedAt`), and the next answer of any kind resumes them, moving `since` on by the offline
|
|
78
100
|
// gap, so `since` is now minus the answered time. A clock clears when its command is no longer pending under its
|
|
79
101
|
// commandId (applied or rejected), or when a blocking rejected command comes ahead of it in its ledger (it is not being
|
|
80
|
-
// sent: Front desk, 2026-09-30)
|
|
102
|
+
// sent: Front desk, 2026-09-30), or when it is a held closure or comes after one, behind a refused approval in its
|
|
103
|
+
// ledger (ADR-082 decision 6); commands never sent have none. Nothing is isolated: a stuck command at the head
|
|
81
104
|
// of a register's ledger holds up the commands behind it, by design, since register facts apply in `seq` order.
|
|
82
105
|
// In memory only: a restart starts with no clocks, and the first answered failure after it starts them afresh
|
|
83
106
|
// (accepted: register commands are few, and a restart re-sends at once).
|
|
@@ -99,25 +122,31 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
99
122
|
|
|
100
123
|
function isNonBlocking(command: RegisterCommand, abandoned: ReadonlySet<string>): boolean {
|
|
101
124
|
return NON_BLOCKING_REJECTIONS.has(command.error?.code ?? '') ||
|
|
125
|
+
CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? '') ||
|
|
102
126
|
(command.error?.code === 'register_session_already_open' &&
|
|
103
127
|
typeof command.payload.sessionId === 'string' && abandoned.has(command.payload.sessionId));
|
|
104
128
|
}
|
|
105
129
|
|
|
106
130
|
async function updateState(patch: Partial<OutboxState> = {}) {
|
|
107
|
-
const
|
|
131
|
+
const rejectedRows = await readFresh(collection, { selector: { syncStatus: 'rejected' } });
|
|
132
|
+
const abandoned = new Set(sessions && (clocks.size || rejectedRows.some((row) => row.error?.code === 'register_session_already_open'))
|
|
108
133
|
? (await readFresh(sessions, { selector: { status: 'abandoned' } })).map((session) => session.id) : []);
|
|
109
134
|
const pending = await countFresh(collection, { syncStatus: 'pending' });
|
|
135
|
+
const rejected = rejectedRows.filter((row) => !isNonBlocking(row, abandoned)).length;
|
|
110
136
|
// Only commands in a register's sendable prefix (pending, before its first rejected command) keep a clock.
|
|
111
137
|
const sendable = new Set<string>();
|
|
112
138
|
const blocked = new Set<string>();
|
|
139
|
+
const held = new Set<string>();
|
|
113
140
|
if (clocks.size) for (const command of await readFresh(collection, { selector: { syncStatus: { $in: ['pending', 'rejected'] } },
|
|
114
141
|
sort: [{ seq: 'asc' }, { key: 'asc' }] })) {
|
|
115
142
|
if (command.syncStatus === 'rejected') {
|
|
143
|
+
if (CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? '')) held.add(command.registerId);
|
|
116
144
|
if (!isNonBlocking(command, abandoned)) blocked.add(command.registerId);
|
|
117
|
-
} else if (
|
|
145
|
+
} else if (held.has(command.registerId) && command.type === 'register.closure.submit') blocked.add(command.registerId);
|
|
146
|
+
else if (!blocked.has(command.registerId)) sendable.add(command.commandId);
|
|
118
147
|
}
|
|
119
148
|
for (const id of clocks.keys()) if (!sendable.has(id)) clocks.delete(id);
|
|
120
|
-
state$.next({ ...state$.value, ...patch, pending, stuck: stuckState() });
|
|
149
|
+
state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
|
|
121
150
|
}
|
|
122
151
|
function scheduleRetry(reason: string, retryAfterMs = 0) {
|
|
123
152
|
state$.next({ ...state$.value, lastRetryReason: reason, stuck: stuckState() });
|
|
@@ -145,9 +174,12 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
145
174
|
sort: [{ seq: 'asc' }, { key: 'asc' }],
|
|
146
175
|
});
|
|
147
176
|
const commands: RegisterCommand[] = [];
|
|
177
|
+
let held = false;
|
|
148
178
|
for (const command of ledger) {
|
|
179
|
+
if (command.syncStatus === 'rejected' && CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? '')) held = true;
|
|
149
180
|
if (command.syncStatus === 'rejected' && isNonBlocking(command, abandoned)) continue;
|
|
150
181
|
if (command.syncStatus === 'rejected') break;
|
|
182
|
+
if (held && command.type === 'register.closure.submit') break;
|
|
151
183
|
commands.push(command);
|
|
152
184
|
if (command.type === 'register.session.open' || commands.length >= batchSize) break;
|
|
153
185
|
}
|
|
@@ -202,7 +234,7 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
202
234
|
? { id: result.id, status: 'rejected', error }
|
|
203
235
|
: { ...result, ...(error ? { error } : {}) };
|
|
204
236
|
try { await options.onResult?.(plainCommand(stored), normalized); }
|
|
205
|
-
catch (cause) { registerCommandsLogger.warn('Failed to apply register command result', { commandId: command.commandId, cause }); }
|
|
237
|
+
catch (cause) { registerCommandsLogger.warn('Failed to apply register command result', { commandId: command.commandId, error: safeErrorString(cause) }); }
|
|
206
238
|
const updatedAt = new Date(now()).toISOString();
|
|
207
239
|
await current.incrementalModify((row) => {
|
|
208
240
|
if (row.syncStatus !== 'pending' || row.commandId !== command.commandId) return row;
|
|
@@ -223,7 +255,7 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
223
255
|
}
|
|
224
256
|
if (!sent) return;
|
|
225
257
|
} catch (error) {
|
|
226
|
-
scheduleRetry('error: ' + (error
|
|
258
|
+
scheduleRetry('error: ' + safeErrorMessage(error));
|
|
227
259
|
return;
|
|
228
260
|
}
|
|
229
261
|
stoppedDuringRun = true;
|
|
@@ -246,6 +278,27 @@ export function createRegisterOutbox(options: RegisterOutboxOptions): RegisterOu
|
|
|
246
278
|
return {
|
|
247
279
|
state$,
|
|
248
280
|
flush,
|
|
281
|
+
async requeue(commandIds) {
|
|
282
|
+
const commands = (await readFresh(collection, { selector: { syncStatus: 'rejected',
|
|
283
|
+
...(commandIds ? { commandId: { $in: commandIds } } : {}) } }))
|
|
284
|
+
.filter((row) => isRegisterRequeueable(row.error?.code));
|
|
285
|
+
let count = 0;
|
|
286
|
+
for (const command of commands) {
|
|
287
|
+
let changed = false;
|
|
288
|
+
await (await collection.findOne(command.key).exec())?.incrementalModify((row) => {
|
|
289
|
+
changed = row.syncStatus === 'rejected' && row.commandId === command.commandId && isRegisterRequeueable(row.error?.code);
|
|
290
|
+
if (!changed) return row;
|
|
291
|
+
row.syncStatus = 'pending';
|
|
292
|
+
delete row.error;
|
|
293
|
+
row.updatedAt = new Date(now()).toISOString();
|
|
294
|
+
return row;
|
|
295
|
+
});
|
|
296
|
+
if (changed) count++;
|
|
297
|
+
}
|
|
298
|
+
await updateState();
|
|
299
|
+
if (count && !stopped) flush().catch(() => {});
|
|
300
|
+
return count;
|
|
301
|
+
},
|
|
249
302
|
start() {
|
|
250
303
|
stopped = false;
|
|
251
304
|
watchBackendMissing();
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// An RxError's message carries its parameters, which can hold a payload with the approval proof (ADR-082 d2).
|
|
2
|
+
|
|
3
|
+
/** Renders an error for logging without RxDB parameters. */
|
|
4
|
+
export function safeErrorString(error: unknown): string {
|
|
5
|
+
return (error as { rxdb?: unknown })?.rxdb === true ? (error as Error).name : String(error);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Renders an error message without RxDB parameters. */
|
|
9
|
+
export function safeErrorMessage(error: unknown): string {
|
|
10
|
+
return (error as { rxdb?: unknown })?.rxdb === true ? (error as Error).name : error instanceof Error ? error.message : String(error);
|
|
11
|
+
}
|
package/src/outbox/types.ts
CHANGED
|
@@ -22,7 +22,9 @@ export interface CommandTransport<E extends AnyCommandEnvelope = CommandEnvelope
|
|
|
22
22
|
export interface OutboxState {
|
|
23
23
|
pending: number;
|
|
24
24
|
/** The order outbox's count of `pos_orders` the store refused (`syncStatus: 'rejected'`), read with `pending`. Each
|
|
25
|
-
* stays until requeue() sends it again. The register outbox
|
|
25
|
+
* stays until requeue() sends it again. The register outbox's count of rejected `register_commands` that stop their
|
|
26
|
+
* register's ledger (superseded, abandoned and an abandoned session's already-open refusal are left out, ADR-078, and so
|
|
27
|
+
* are the two refused closure approvals, which hold only their register's next closure, ADR-082 decision 6). */
|
|
26
28
|
rejected?: number;
|
|
27
29
|
sending: boolean;
|
|
28
30
|
lastRetryReason?: string;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { useMemo } from 'react';
|
|
2
|
+
import { summarizeOutboxHealth, type OutboxHealth } from './outbox-health';
|
|
3
|
+
import type { UseOrderOutboxResult } from './use-order-outbox';
|
|
4
|
+
import type { UseRegisterOutboxResult } from './use-register-outbox';
|
|
5
|
+
|
|
6
|
+
export interface UseOutboxHealthOptions {
|
|
7
|
+
/** `useOrderOutbox()`'s result; only `state` and `flush` are read. */
|
|
8
|
+
sales: Pick<UseOrderOutboxResult, 'state' | 'flush'>;
|
|
9
|
+
/** `useRegisterOutbox()`'s result; only `state` and `flush` are read. */
|
|
10
|
+
tillUpdates: Pick<UseRegisterOutboxResult, 'state' | 'flush'>;
|
|
11
|
+
}
|
|
12
|
+
export interface UseOutboxHealthResult {
|
|
13
|
+
/** summarizeOutboxHealth of the two states; a new object only when a state changes. */
|
|
14
|
+
health: OutboxHealth;
|
|
15
|
+
/** Flushes both outboxes at once (after the cashier signs in again); rejects if either flush rejects. */
|
|
16
|
+
flush(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
export function useOutboxHealth(options: UseOutboxHealthOptions): UseOutboxHealthResult {
|
|
19
|
+
const { sales, tillUpdates } = options;
|
|
20
|
+
const health = useMemo(() => summarizeOutboxHealth(sales.state, tillUpdates.state), [sales.state, tillUpdates.state]);
|
|
21
|
+
return { health, async flush() { await Promise.all([sales.flush(), tillUpdates.flush()]); } };
|
|
22
|
+
}
|
|
@@ -27,6 +27,8 @@ export interface UseRegisterOutboxResult {
|
|
|
27
27
|
state: OutboxState;
|
|
28
28
|
/** Sends pending till updates; does nothing while there is no collection. */
|
|
29
29
|
flush(): Promise<void>;
|
|
30
|
+
/** Moves rejected till updates back to pending (see RegisterOutbox.requeue); resolves to 0 while there is no collection. */
|
|
31
|
+
requeue(commandIds?: string[]): Promise<number>;
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
export function useRegisterOutbox(options: UseRegisterOutboxOptions): UseRegisterOutboxResult {
|
|
@@ -55,5 +57,9 @@ export function useRegisterOutbox(options: UseRegisterOutboxOptions): UseRegiste
|
|
|
55
57
|
async flush() {
|
|
56
58
|
const active = current.current;
|
|
57
59
|
if (active?.commands === commands && active.deviceId === deviceId) await active.outbox.flush();
|
|
60
|
+
},
|
|
61
|
+
async requeue(commandIds) {
|
|
62
|
+
const active = current.current;
|
|
63
|
+
return active?.commands === commands && active.deviceId === deviceId ? active.outbox.requeue(commandIds) : 0;
|
|
58
64
|
} };
|
|
59
65
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createPaymentDriverRegistry, driverForMethod } from './registry';
|
|
2
|
+
export { createSimulatedDriver, SIMULATED_PROVIDER, SIMULATED_TIMING } from './simulated-driver';
|
|
3
|
+
export type {
|
|
4
|
+
DriverCapabilities, ReaderInfo, DriverStatus, DriverAvailability, CollectInput,
|
|
5
|
+
CollectOutcome, CollectResult, DriverStatusSource, PaymentDriver,
|
|
6
|
+
} from './types';
|
|
7
|
+
export type { PaymentDriverRegistry } from './registry';
|
|
8
|
+
export type { SimulatedReaderId, SimulatedDriverOptions } from './simulated-driver';
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Ported from WCPOS v2 packages/core/src/services/payment-drivers/registry.ts (monorepo 5ac185b0).
|
|
2
|
+
import type { PaymentMethodDescriptor } from '@tallyui/core';
|
|
3
|
+
import type { PaymentDriver } from './types';
|
|
4
|
+
|
|
5
|
+
export interface PaymentDriverRegistry {
|
|
6
|
+
/** Adds the driver under its `provider`, replacing any driver already there, then notifies subscribers. */
|
|
7
|
+
register(driver: PaymentDriver): void;
|
|
8
|
+
get(provider: string | null): PaymentDriver | undefined;
|
|
9
|
+
has(provider: string | null): boolean;
|
|
10
|
+
list(): PaymentDriver[];
|
|
11
|
+
/** Called after every `register`; returns an unsubscribe function. */
|
|
12
|
+
subscribe(listener: () => void): () => void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function createPaymentDriverRegistry(): PaymentDriverRegistry {
|
|
16
|
+
const drivers = new Map<string, PaymentDriver>();
|
|
17
|
+
const listeners = new Set<() => void>();
|
|
18
|
+
return {
|
|
19
|
+
register(driver) {
|
|
20
|
+
drivers.set(driver.provider, driver);
|
|
21
|
+
listeners.forEach((listener) => listener());
|
|
22
|
+
},
|
|
23
|
+
get: (provider) => provider === null ? undefined : drivers.get(provider),
|
|
24
|
+
has: (provider) => provider !== null && drivers.has(provider),
|
|
25
|
+
list: () => [...drivers.values()],
|
|
26
|
+
subscribe(listener) {
|
|
27
|
+
listeners.add(listener);
|
|
28
|
+
return () => { listeners.delete(listener); };
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The driver for a method taken on a device: `capture.mode === 'device'` and a driver registered under `capture.provider`. */
|
|
34
|
+
export function driverForMethod(
|
|
35
|
+
registry: PaymentDriverRegistry,
|
|
36
|
+
method: PaymentMethodDescriptor | null | undefined,
|
|
37
|
+
): PaymentDriver | undefined {
|
|
38
|
+
return method?.capture.mode === 'device' ? registry.get(method.capture.provider) : undefined;
|
|
39
|
+
}
|