@tallyui/pos 3.16.0 → 3.17.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 CHANGED
@@ -9,7 +9,32 @@ import { Observable } from 'rxjs';
9
9
  export { countFresh, readFresh, watchFresh } from '@tallyui/core/rxdb';
10
10
 
11
11
  type LogLevel = 'debug' | 'info' | 'warn' | 'error';
12
- interface LogEntry {
12
+ /** Who did it: a person (a cashier or manager), not the system. WCPOS v2's log actor. */
13
+ interface LogActor {
14
+ id?: string;
15
+ name?: string;
16
+ role?: string;
17
+ }
18
+ /** `ok`: the store applied the record. `failed`: the store refused it. `pending`: the store keeps failing it on its
19
+ * own, and it is still retrying. */
20
+ type SyncRecordOutcome = 'ok' | 'failed' | 'pending';
21
+ /** One record's sync outcome (WCPOS v2's `sync.record` row). */
22
+ interface LogSyncRecord {
23
+ /** The local collection, e.g. `pos_orders`. */
24
+ collection: string;
25
+ /** The record's durable id (a PosOrder's `id`, not its commandId). */
26
+ recordId: string;
27
+ outcome: SyncRecordOutcome;
28
+ /** The store's error code. */
29
+ code?: string;
30
+ reason?: string;
31
+ }
32
+ /** Typed fields a call site puts on the entry itself; each is set on the entry only when given. */
33
+ interface LogMeta {
34
+ actor?: LogActor;
35
+ syncRecord?: LogSyncRecord;
36
+ }
37
+ interface LogEntry extends LogMeta {
13
38
  level: LogLevel;
14
39
  scope: string;
15
40
  message: string;
@@ -22,11 +47,12 @@ interface LogSink {
22
47
  scopes?: string[];
23
48
  write(entry: LogEntry): void;
24
49
  }
50
+ type LogMethod = (message: string, data?: Record<string, unknown>, meta?: LogMeta) => void;
25
51
  interface Logger {
26
- debug(message: string, data?: Record<string, unknown>): void;
27
- info(message: string, data?: Record<string, unknown>): void;
28
- warn(message: string, data?: Record<string, unknown>): void;
29
- error(message: string, data?: Record<string, unknown>): void;
52
+ debug: LogMethod;
53
+ info: LogMethod;
54
+ warn: LogMethod;
55
+ error: LogMethod;
30
56
  createScope(name: string): Logger;
31
57
  addSink(sink: LogSink): void;
32
58
  removeSink(sinkId: string): void;
@@ -48,6 +74,43 @@ interface CallbackSinkOptions {
48
74
  }
49
75
  declare function callbackSink(options: CallbackSinkOptions): LogSink;
50
76
 
77
+ /**
78
+ * Pure helpers for a Logs screen, ported from WCPOS v2 `packages/core/src/screens/main/logs/logs-logic.ts`
79
+ * (monorepo `main` 51e7c4351): `presetFilters` (its `has_actor` part) and `deriveStuckRecords`. v2 reads its
80
+ * stored log rows; these read TallyUI's `LogEntry`, with its typed `actor` and `syncRecord`. v2's `sync` preset
81
+ * filters on v2's `wcpos.sync` category, which TallyUI's log scopes have no counterpart for, so it is not ported.
82
+ */
83
+
84
+ type LogPreset = 'all' | 'actions' | 'errors';
85
+ interface LogPresetFilters {
86
+ level: LogLevel[];
87
+ /** Only entries a person did (`hasActor`). */
88
+ has_actor?: true;
89
+ }
90
+ /** Preset chip to filters. Debug entries count only while verbose diagnostics is on. */
91
+ declare function presetFilters(preset: LogPreset, verbose: boolean): LogPresetFilters;
92
+ /** A person did it: the entry's actor names an id or a name (v2 reads such a row as an action). */
93
+ declare function hasActor(entry: Pick<LogEntry, 'actor'>): boolean;
94
+ declare function matchesPresetFilters(entry: LogEntry, filters: LogPresetFilters): boolean;
95
+ interface StuckRecord {
96
+ /** `${collection}:${recordId}` */
97
+ key: string;
98
+ collection: string;
99
+ recordId: string;
100
+ /** `failed`: the store refused it. `pending`: the store keeps failing it, and it is still retrying. */
101
+ outcome: 'failed' | 'pending';
102
+ code?: string;
103
+ reason: string;
104
+ /** When its latest outcome was logged. */
105
+ lastSeen: number;
106
+ }
107
+ /**
108
+ * The records whose latest sync outcome is `failed` or `pending`; an `ok` clears. Entries without a `syncRecord`
109
+ * are no evidence either way. The latest is by timestamp, and on equal timestamps the entry later in `entries`
110
+ * (the order a sink receives them). Newest first.
111
+ */
112
+ declare function deriveStuckRecords(entries: readonly LogEntry[]): StuckRecord[];
113
+
51
114
  /**
52
115
  * Every cell is quoted (RFC 4180 style, so commas, quotes, CR and LF are safe). Lines use
53
116
  * CRLF, with no BOM or trailing line ending, matching the register export. The formula guard
@@ -3126,15 +3189,17 @@ type SessionTarget = {
3126
3189
  * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
3127
3190
  * Superseded rejections make open/counting sessions terminal; a conflict session leaves only by an applied open or abandon (ADR-078 decision 9); terminal/unknown states stay untouched.
3128
3191
  * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
3129
- * Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters`).
3192
+ * Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters`),
3193
+ * and given `closures` too, a closure refused for its number is renumbered once and requeued (#655, `renumberRefused`).
3130
3194
  * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
3131
3195
  */
3132
- declare function adoptRegisterResults({ commands, sessions, registerId, host, storeKey }: {
3196
+ declare function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }: {
3133
3197
  commands: RegisterCommandCollection;
3134
3198
  sessions: RegisterSessionCollection;
3135
3199
  registerId: string;
3136
3200
  host?: RegisterHost;
3137
3201
  storeKey?: string;
3202
+ closures?: ClosureCollection;
3138
3203
  }): Promise<void>;
3139
3204
  declare function takeOverSession({ commands, sessions, sessionId, now, registerContract }: SessionTarget & {
3140
3205
  /** The store's register contract (`capabilities.register`); take over needs 2, and a missing value counts as below 2. */
@@ -3650,7 +3715,10 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
3650
3715
  saving: boolean;
3651
3716
  /** The failed save's order is confirmed stored (see `isStored`): the UI also offers Continue (`continueSale()`). */
3652
3717
  canContinue: boolean;
3653
- add(entry: CatalogueEntry<any>, traits: ProductTraits<any>): void;
3718
+ /** Adds the entry, as a new line or one more on its line; returns that line's id, or the refusal `error` now shows. */
3719
+ add(entry: CatalogueEntry<any>, traits: ProductTraits<any>): {
3720
+ lineId: string;
3721
+ } | string;
3654
3722
  setQuantity(lineId: string, quantity: number): void;
3655
3723
  /** ADR-075: adds a fee; returns its id or the builder's refusal. */
3656
3724
  addFee(input: ChargeInput): {
@@ -4385,4 +4453,4 @@ declare function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin): Repo
4385
4453
  declare function reportOrderFromStoreOrder(order: StoreOrder, join?: LineJoin): ReportOrder;
4386
4454
  declare function reportRefundFromPosRefund(refund: PosRefund): ReportRefund | undefined;
4387
4455
 
4388
- export { APP_SETTING_DEFINITIONS, type Actor, type AddLineInput, type AppSettingCollection, type AppSettingDefinition, type AppSettingDoc, type AppSettingKey, type AppSettings, type AppliedDiscount, type ApprovalNeeded, type BackendNotFound, type BasketLine, type BroadcastChannelLike, COUPONS_UNSUPPORTED, CartError, type CartQuantityLine, type CashMovement, type CashMovementCollection, type CashierState, type CatalogueEntry, type CatalogueGridColumns, type CatalogueView, type CatalogueViewAction, type CatalogueViewState, type ChargeInput, type ChargeLine, type Closure, type ClosureApprovalStatus, type ClosureCollection, type ClosureContext, type ClosureScope, type CollectInput, type CollectOutcome, type CollectResult, type CommandTransport, type Correction, type CsvColumn, CurrencyProvider, type CurrencyProviderProps, type CustomerSummary, DATE_PRESETS, DEFAULT_APP_SETTINGS, DEFAULT_CATALOGUE_VIEW_STATE, DEFAULT_COOLDOWN_MS, DEFAULT_MIN_SCAN_CHARS, DEFAULT_RECEIPT_TEMPLATES, DEFAULT_WEDGE_SETTINGS, DISCOUNTS_UNSUPPORTED, DISPLAY_ACTIONS, DISPLAY_CHANNEL, DISPLAY_PROTOCOL_VERSION, DISPLAY_TEMPLATE, type DatePreset, type DayPoint, type DayRange, type DecodeRefusal, type DecodeResult, type Discount, type DisplayAction, type DisplayCart, type DisplayClock, type DisplayConfig, type DisplayEnvelope, type DisplayLine, type DisplayLink, type DisplayPayloads, type DisplayPayment, type DisplayState, type DisplayTemplate, type DisplayTotals, type DisplayTransport, type DisplayView, type DriverAvailability, type DriverCapabilities, type DriverStatus, type DriverStatusSource, ESCPOS_CODE_PAGES, type EarlierRefund, type EncodeEscPosOptions, type EscPosBuilder, type EscPosSink, type EscPosTransportOptions, type FeeLine, type FinalizeOptions, type FloatSuggestion, type GroupRow, HELLO_RETRY_MS, type HandoverSlipData, type HandoverSlipInput, type HttpTransportOptions, type LedgerRow, type LineItem, type LineJoin, type LineTaxLine, type LogEntry, type LogLevel, type LogSink, type Logger, MAX_MESSAGE_BYTES, MAX_TENDER_MINOR, MICROS_PER_MINOR, type Margin, type Movement$1 as Movement, type MovementType, type NoteDelivery, type OpenSale, type Order, type OrderBuilder, type OrderBuilderOptions, OrderContentMismatchError, type OrderCoupon, type OrderCouponContext, type OrderManager, type OrderManagerOptions, type OrderOutbox, type OrderOutboxOptions, type OrderRefundOutcome, type OrderTaxTotals, type OrderTransportContext, type OutboxCounts, type OutboxHealth, type OutboxState, PAPER_COLUMNS, PAYMENT_IN_MOTION, PRINTER_PROFILES_COLLECTION, PRODUCT_SORT_FIELDS, type ParkedOrderSummary, type Payment, type PaymentDriver, type PaymentDriverRegistry, type PaymentLegStatus, type PaymentMethod, type PaymentPhase, type PaymentRow, type PaymentTransport, type PlanLeg, type PosOrder, type PosOrderCoupon, type PosOrderLine, type PosOrderLocalWarning, PosOrderOpenClosedError, type PosOrderPayment, type PosOrderServerFailures, type PosOrderSyncStatus, type PosRefund, type PosRefundCollection, type PosRefundStatus, type PricedRefund, type PricedRefundLine, PrintError, type PrintErrorCode, type PrintJob, type PrintJobKind, type PrintQueue, type PrintQueueOptions, type PrintQueueState, type PrintTransport, type PrinterProfile, type PrinterProfileCollection, type ProductSort, type ProductSortValue, RECEIPT_SCHEMA_VERSION, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS, REOPENABLE_CODES, type RateTaxLine, type ReaderInfo, type ReceiptConfig, type ReceiptData, type ReceiptFiscal, type ReceiptLineItem, type ReceiptNode, type ReceiptPaper, type ReceiptRegister, type ReceiptSoftware, type ReceiptTemplateData, type ReceiptTemplateLine, type ReceiptTemplateOptions, type ReceiptTemplateRow, type RecordedFigures, RefundAnswerPendingError, type RefundableLine, type RefundableOrderLine, RegisterApprovalRequiredError, type RegisterBucket, RegisterCloseIncompleteError, type RegisterCommand, type RegisterCommandCollection, type RegisterCounters, type RegisterDocument, type RegisterFact, type RegisterHost, RegisterIdInvalidError, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, RegisterNeedsUpgradeError, type RegisterOutbox, type RegisterOutboxOptions, RegisterReapproveError, type RegisterSession, RegisterSessionAlreadyOpenError, RegisterSessionClosedError, type RegisterSessionCollection, RegisterSessionConflictError, RegisterSessionOpenClosedError, RegisterSessionRequiredError, type RegisterStore, RegisterTakeOverError, RegisterTenderInProgressError, type RenderReceiptOptions, type RenderSanitizeOptions, type ReopenRefusal, ReopenRefusedOrderError, type ReportCategory, type ReportLine, type ReportOrder, type ReportPayment, type ReportRefund, type ReportTax, type Repository, type ResolveStoreSettingsOptions, SALE_IN_TENDER, SALE_PARTLY_PAID, SALE_SAVING, SIMULATED_PROVIDER, SIMULATED_TIMING, SYSTEM_PRINTER_ID, SYSTEM_PRINT_TIMING, type SaleDiscountCodes, type SaleDiscountState, type SaleStage, type SalesFigures, type SalesFiguresInput, type SalesTotals, type SanitizeHtmlOptions, type ScanOfferResult, type ScanRejectReason, type ScanSession, type ScanSessionOptions, type SentOrder, type ShippingLine, type SimulatedDriverOptions, type SimulatedReaderId, type SplitTab, type StoreDay, type StoreSettingsResolution, type StoreSettingsState, type SwitchKind, type SwitchWarning, type SwitchWarningInput, type SwitchWarnings, type SystemPrintTransportOptions, TAX_ROUNDING_MIXED_NOTE, type TaxContext, type TaxLineInput, TaxProvider, type TaxProviderProps, type TaxRateMap, type TaxRow, type TenderAction, type TenderKey, type TenderLineId, type TenderPlan, type TenderRounding, type TenderState, type TenderView, type TenderVoid, type ThermalNode, type TraceKey, type TransportOutcome, UI_SCALES, UI_THEMES, type UiScale, type UiTheme, UnsupportedOrderVersionError, type UseBarcodeScannerOptions, type UseOrderOutboxOptions, type UseOrderOutboxResult, type UseOutboxHealthOptions, type UseOutboxHealthResult, type UseRegisterOutboxOptions, type UseRegisterOutboxResult, type UseRegisterSessionOptions, WEDGE_END_OF_SCAN_MS, type WedgeDetector, type WedgeDetectorOptions, type WedgeReplayResult, type WedgeSettings, type WedgeState, abandonSession, activePlan, addEntryToCart, addPosOrderCollection, addPrinterProfileCollection, addRegisterSessionCollection, adoptRegisterResults, advancePerpetual, allocateOrderDiscount, appSettingCollection, appSettingSchema, appSettings$, appliedMinor, backToSelling, bindRegister, buildClosureDocument, buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, buildXReportDocument, callbackSink, can, canMoveLeg, canVoidLeg, capturedMinor, cartQuantities, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureApprovalStatus, closureCommand, closureSchema, closureVariance, comparisonRange, computeOrderTax, consoleSink, countVariance, countsTowardPaid, createBackendNotFound, createBroadcastDisplayTransport, createDisplayLink, createEscPosTransport, createHttpCommandTransport, createLogger, createOrderBuilder, createOrderManager, createOrderOutbox, createPaymentDriverRegistry, createPrintQueue, createRegisterOutbox, createRepository, createScanSession, createSimulatedDriver, createSystemPrintTransport, createWedgeDetector, createWedgeState, csvCell, csvFromCells, daysOf, decode as decodeDisplayMessage, denominationTotal, denominations, deriveExpected, deriveSettled, displayCart, displayReducer, driverForMethod, encode as encodeDisplayMessage, encodeEscPos, ensureRegister, escpos, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, foldWedgeKey, formatClosureDate, getBoundRegisterId, getDeviceId, handoverSlip, hasValidRetailCheckDigit, inCategory, inMotionMinor, inRange, initTenderState, initialDisplayState, initialTenderState, isInMotion, isKnownSessionStatus, isLiveAtStore, isPartlyPaid, isRegisterRequeueable, isReopened, isRequeueable, isServerDecimal, labelKeys, legStatus, listCategories, makeEnvelope, marginOf, messageBytes, minorToDecimal, mintClosureNumber, mintUuid, movementCommand, movementFieldError, needsAttention, nextSaleCounter, normalizeAmount, normalizeCatalogueViewState, normalizeRetailCode, noteDelivery, observeRegister$, openSales, openSession, openSessionSelector, orderDraftSchema, outboxLogger, overThreshold, parkedOrderSummaries$, parseMinor, parseXml, planLegs, posOrderCollection, posOrderSchema, posOrdersLogger, posRefundCollection, posRefundSchema, presetRange, priceRefund, printerProfileCollection, printerProfileSchema, productCategories, productSortValue, quickTenderedAmounts, ratePpmFromPercent, readAppSettings, readBoundRegister, readRegister, reapproveClosure, receiptTemplateData, reconcileRegisterCommands, recordMovement, recordRegisterFact, refundableLines, registerCommandCollection, registerCommandSchema, registerCommandsLogger, registerFactsLogger, registerSessionCollection, registerSessionSchema, registerSessionsLogger, renderHtml, renderLogiclessTemplate, renderReceiptHtml, renderReceiptTemplate, renderThermalPreview, reopenRefusedOrder, replacedOrderIds, replayWedgeDetector, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund, requireOpenSession, resolveAppSettings, resolveGridColumns, resolveStoreSettings, restoreOrderDraft, retailCodeTwin, roundMicrosToMinor, roundedDue, saleLogger, salesFigures, sameSale, sanitizeHtml, searchProducts, selectClosureRows, sendOrderRefund, sessionOpenCommand, sessionTransitionCommand, sortProducts, stampSession, startCounting, stockOverlay$, stockOverlayAsOf$, stripBoundary, submitOrderRefund, suggestFloat, summarizeOutboxHealth, switchWarnings, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderRounding, tenderVoidCollection, tenderVoidSchema, toCsv, toOrderCreateEnvelope, toPrintError, unbindRegister, useAppSettings, useBarcodeScanner, useCashier, useCurrencyCode, useCurrencyFormatter, useCustomerDisplay, useOrderOutbox, useOutboxHealth, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, watchOutboxHealth, withPricingContext, index as woocommerceDiscountCodes, writeAppSetting, writeClosure, writeOrderDraft };
4456
+ export { APP_SETTING_DEFINITIONS, type Actor, type AddLineInput, type AppSettingCollection, type AppSettingDefinition, type AppSettingDoc, type AppSettingKey, type AppSettings, type AppliedDiscount, type ApprovalNeeded, type BackendNotFound, type BasketLine, type BroadcastChannelLike, COUPONS_UNSUPPORTED, CartError, type CartQuantityLine, type CashMovement, type CashMovementCollection, type CashierState, type CatalogueEntry, type CatalogueGridColumns, type CatalogueView, type CatalogueViewAction, type CatalogueViewState, type ChargeInput, type ChargeLine, type Closure, type ClosureApprovalStatus, type ClosureCollection, type ClosureContext, type ClosureScope, type CollectInput, type CollectOutcome, type CollectResult, type CommandTransport, type Correction, type CsvColumn, CurrencyProvider, type CurrencyProviderProps, type CustomerSummary, DATE_PRESETS, DEFAULT_APP_SETTINGS, DEFAULT_CATALOGUE_VIEW_STATE, DEFAULT_COOLDOWN_MS, DEFAULT_MIN_SCAN_CHARS, DEFAULT_RECEIPT_TEMPLATES, DEFAULT_WEDGE_SETTINGS, DISCOUNTS_UNSUPPORTED, DISPLAY_ACTIONS, DISPLAY_CHANNEL, DISPLAY_PROTOCOL_VERSION, DISPLAY_TEMPLATE, type DatePreset, type DayPoint, type DayRange, type DecodeRefusal, type DecodeResult, type Discount, type DisplayAction, type DisplayCart, type DisplayClock, type DisplayConfig, type DisplayEnvelope, type DisplayLine, type DisplayLink, type DisplayPayloads, type DisplayPayment, type DisplayState, type DisplayTemplate, type DisplayTotals, type DisplayTransport, type DisplayView, type DriverAvailability, type DriverCapabilities, type DriverStatus, type DriverStatusSource, ESCPOS_CODE_PAGES, type EarlierRefund, type EncodeEscPosOptions, type EscPosBuilder, type EscPosSink, type EscPosTransportOptions, type FeeLine, type FinalizeOptions, type FloatSuggestion, type GroupRow, HELLO_RETRY_MS, type HandoverSlipData, type HandoverSlipInput, type HttpTransportOptions, type LedgerRow, type LineItem, type LineJoin, type LineTaxLine, type LogActor, type LogEntry, type LogLevel, type LogMeta, type LogPreset, type LogPresetFilters, type LogSink, type LogSyncRecord, type Logger, MAX_MESSAGE_BYTES, MAX_TENDER_MINOR, MICROS_PER_MINOR, type Margin, type Movement$1 as Movement, type MovementType, type NoteDelivery, type OpenSale, type Order, type OrderBuilder, type OrderBuilderOptions, OrderContentMismatchError, type OrderCoupon, type OrderCouponContext, type OrderManager, type OrderManagerOptions, type OrderOutbox, type OrderOutboxOptions, type OrderRefundOutcome, type OrderTaxTotals, type OrderTransportContext, type OutboxCounts, type OutboxHealth, type OutboxState, PAPER_COLUMNS, PAYMENT_IN_MOTION, PRINTER_PROFILES_COLLECTION, PRODUCT_SORT_FIELDS, type ParkedOrderSummary, type Payment, type PaymentDriver, type PaymentDriverRegistry, type PaymentLegStatus, type PaymentMethod, type PaymentPhase, type PaymentRow, type PaymentTransport, type PlanLeg, type PosOrder, type PosOrderCoupon, type PosOrderLine, type PosOrderLocalWarning, PosOrderOpenClosedError, type PosOrderPayment, type PosOrderServerFailures, type PosOrderSyncStatus, type PosRefund, type PosRefundCollection, type PosRefundStatus, type PricedRefund, type PricedRefundLine, PrintError, type PrintErrorCode, type PrintJob, type PrintJobKind, type PrintQueue, type PrintQueueOptions, type PrintQueueState, type PrintTransport, type PrinterProfile, type PrinterProfileCollection, type ProductSort, type ProductSortValue, RECEIPT_SCHEMA_VERSION, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS, REOPENABLE_CODES, type RateTaxLine, type ReaderInfo, type ReceiptConfig, type ReceiptData, type ReceiptFiscal, type ReceiptLineItem, type ReceiptNode, type ReceiptPaper, type ReceiptRegister, type ReceiptSoftware, type ReceiptTemplateData, type ReceiptTemplateLine, type ReceiptTemplateOptions, type ReceiptTemplateRow, type RecordedFigures, RefundAnswerPendingError, type RefundableLine, type RefundableOrderLine, RegisterApprovalRequiredError, type RegisterBucket, RegisterCloseIncompleteError, type RegisterCommand, type RegisterCommandCollection, type RegisterCounters, type RegisterDocument, type RegisterFact, type RegisterHost, RegisterIdInvalidError, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, RegisterNeedsUpgradeError, type RegisterOutbox, type RegisterOutboxOptions, RegisterReapproveError, type RegisterSession, RegisterSessionAlreadyOpenError, RegisterSessionClosedError, type RegisterSessionCollection, RegisterSessionConflictError, RegisterSessionOpenClosedError, RegisterSessionRequiredError, type RegisterStore, RegisterTakeOverError, RegisterTenderInProgressError, type RenderReceiptOptions, type RenderSanitizeOptions, type ReopenRefusal, ReopenRefusedOrderError, type ReportCategory, type ReportLine, type ReportOrder, type ReportPayment, type ReportRefund, type ReportTax, type Repository, type ResolveStoreSettingsOptions, SALE_IN_TENDER, SALE_PARTLY_PAID, SALE_SAVING, SIMULATED_PROVIDER, SIMULATED_TIMING, SYSTEM_PRINTER_ID, SYSTEM_PRINT_TIMING, type SaleDiscountCodes, type SaleDiscountState, type SaleStage, type SalesFigures, type SalesFiguresInput, type SalesTotals, type SanitizeHtmlOptions, type ScanOfferResult, type ScanRejectReason, type ScanSession, type ScanSessionOptions, type SentOrder, type ShippingLine, type SimulatedDriverOptions, type SimulatedReaderId, type SplitTab, type StoreDay, type StoreSettingsResolution, type StoreSettingsState, type StuckRecord, type SwitchKind, type SwitchWarning, type SwitchWarningInput, type SwitchWarnings, type SyncRecordOutcome, type SystemPrintTransportOptions, TAX_ROUNDING_MIXED_NOTE, type TaxContext, type TaxLineInput, TaxProvider, type TaxProviderProps, type TaxRateMap, type TaxRow, type TenderAction, type TenderKey, type TenderLineId, type TenderPlan, type TenderRounding, type TenderState, type TenderView, type TenderVoid, type ThermalNode, type TraceKey, type TransportOutcome, UI_SCALES, UI_THEMES, type UiScale, type UiTheme, UnsupportedOrderVersionError, type UseBarcodeScannerOptions, type UseOrderOutboxOptions, type UseOrderOutboxResult, type UseOutboxHealthOptions, type UseOutboxHealthResult, type UseRegisterOutboxOptions, type UseRegisterOutboxResult, type UseRegisterSessionOptions, WEDGE_END_OF_SCAN_MS, type WedgeDetector, type WedgeDetectorOptions, type WedgeReplayResult, type WedgeSettings, type WedgeState, abandonSession, activePlan, addEntryToCart, addPosOrderCollection, addPrinterProfileCollection, addRegisterSessionCollection, adoptRegisterResults, advancePerpetual, allocateOrderDiscount, appSettingCollection, appSettingSchema, appSettings$, appliedMinor, backToSelling, bindRegister, buildClosureDocument, buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, buildXReportDocument, callbackSink, can, canMoveLeg, canVoidLeg, capturedMinor, cartQuantities, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureApprovalStatus, closureCommand, closureSchema, closureVariance, comparisonRange, computeOrderTax, consoleSink, countVariance, countsTowardPaid, createBackendNotFound, createBroadcastDisplayTransport, createDisplayLink, createEscPosTransport, createHttpCommandTransport, createLogger, createOrderBuilder, createOrderManager, createOrderOutbox, createPaymentDriverRegistry, createPrintQueue, createRegisterOutbox, createRepository, createScanSession, createSimulatedDriver, createSystemPrintTransport, createWedgeDetector, createWedgeState, csvCell, csvFromCells, daysOf, decode as decodeDisplayMessage, denominationTotal, denominations, deriveExpected, deriveSettled, deriveStuckRecords, displayCart, displayReducer, driverForMethod, encode as encodeDisplayMessage, encodeEscPos, ensureRegister, escpos, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, foldWedgeKey, formatClosureDate, getBoundRegisterId, getDeviceId, handoverSlip, hasActor, hasValidRetailCheckDigit, inCategory, inMotionMinor, inRange, initTenderState, initialDisplayState, initialTenderState, isInMotion, isKnownSessionStatus, isLiveAtStore, isPartlyPaid, isRegisterRequeueable, isReopened, isRequeueable, isServerDecimal, labelKeys, legStatus, listCategories, makeEnvelope, marginOf, matchesPresetFilters, messageBytes, minorToDecimal, mintClosureNumber, mintUuid, movementCommand, movementFieldError, needsAttention, nextSaleCounter, normalizeAmount, normalizeCatalogueViewState, normalizeRetailCode, noteDelivery, observeRegister$, openSales, openSession, openSessionSelector, orderDraftSchema, outboxLogger, overThreshold, parkedOrderSummaries$, parseMinor, parseXml, planLegs, posOrderCollection, posOrderSchema, posOrdersLogger, posRefundCollection, posRefundSchema, presetFilters, presetRange, priceRefund, printerProfileCollection, printerProfileSchema, productCategories, productSortValue, quickTenderedAmounts, ratePpmFromPercent, readAppSettings, readBoundRegister, readRegister, reapproveClosure, receiptTemplateData, reconcileRegisterCommands, recordMovement, recordRegisterFact, refundableLines, registerCommandCollection, registerCommandSchema, registerCommandsLogger, registerFactsLogger, registerSessionCollection, registerSessionSchema, registerSessionsLogger, renderHtml, renderLogiclessTemplate, renderReceiptHtml, renderReceiptTemplate, renderThermalPreview, reopenRefusedOrder, replacedOrderIds, replayWedgeDetector, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund, requireOpenSession, resolveAppSettings, resolveGridColumns, resolveStoreSettings, restoreOrderDraft, retailCodeTwin, roundMicrosToMinor, roundedDue, saleLogger, salesFigures, sameSale, sanitizeHtml, searchProducts, selectClosureRows, sendOrderRefund, sessionOpenCommand, sessionTransitionCommand, sortProducts, stampSession, startCounting, stockOverlay$, stockOverlayAsOf$, stripBoundary, submitOrderRefund, suggestFloat, summarizeOutboxHealth, switchWarnings, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderRounding, tenderVoidCollection, tenderVoidSchema, toCsv, toOrderCreateEnvelope, toPrintError, unbindRegister, useAppSettings, useBarcodeScanner, useCashier, useCurrencyCode, useCurrencyFormatter, useCustomerDisplay, useOrderOutbox, useOutboxHealth, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, watchOutboxHealth, withPricingContext, index as woocommerceDiscountCodes, writeAppSetting, writeClosure, writeOrderDraft };
package/dist/index.js CHANGED
@@ -6,39 +6,12 @@ var __export = (target, all) => {
6
6
 
7
7
  // src/logging/logger.ts
8
8
  function createLogger(scope = "root") {
9
- const sinks = /* @__PURE__ */ new Map();
10
- function log(level, message, data) {
11
- const entry = {
12
- level,
13
- scope,
14
- message,
15
- data,
16
- timestamp: Date.now()
17
- };
18
- for (const sink of sinks.values()) {
19
- if (!sink.levels.includes(level)) continue;
20
- if (sink.scopes && !sink.scopes.includes(scope)) continue;
21
- sink.write(entry);
22
- }
23
- }
24
- return {
25
- debug: (message, data) => log("debug", message, data),
26
- info: (message, data) => log("info", message, data),
27
- warn: (message, data) => log("warn", message, data),
28
- error: (message, data) => log("error", message, data),
29
- createScope(name) {
30
- return createChildLogger(sinks, name);
31
- },
32
- addSink(sink) {
33
- sinks.set(sink.id, sink);
34
- },
35
- removeSink(sinkId) {
36
- sinks.delete(sinkId);
37
- }
38
- };
9
+ return createChildLogger(/* @__PURE__ */ new Map(), scope);
39
10
  }
40
- function logWithSinks(sinks, level, scope, message, data) {
11
+ function logWithSinks(sinks, level, scope, message, data, meta) {
41
12
  const entry = { level, scope, message, data, timestamp: Date.now() };
13
+ if (meta?.actor) entry.actor = meta.actor;
14
+ if (meta?.syncRecord) entry.syncRecord = meta.syncRecord;
42
15
  for (const sink of sinks.values()) {
43
16
  if (!sink.levels.includes(level)) continue;
44
17
  if (sink.scopes && !sink.scopes.includes(scope)) continue;
@@ -47,13 +20,17 @@ function logWithSinks(sinks, level, scope, message, data) {
47
20
  }
48
21
  function createChildLogger(sinks, scope) {
49
22
  return {
50
- debug: (message, data) => logWithSinks(sinks, "debug", scope, message, data),
51
- info: (message, data) => logWithSinks(sinks, "info", scope, message, data),
52
- warn: (message, data) => logWithSinks(sinks, "warn", scope, message, data),
53
- error: (message, data) => logWithSinks(sinks, "error", scope, message, data),
23
+ debug: (message, data, meta) => logWithSinks(sinks, "debug", scope, message, data, meta),
24
+ info: (message, data, meta) => logWithSinks(sinks, "info", scope, message, data, meta),
25
+ warn: (message, data, meta) => logWithSinks(sinks, "warn", scope, message, data, meta),
26
+ error: (message, data, meta) => logWithSinks(sinks, "error", scope, message, data, meta),
54
27
  createScope: (childName) => createChildLogger(sinks, childName),
55
- addSink: (sink) => sinks.set(sink.id, sink),
56
- removeSink: (sinkId) => sinks.delete(sinkId)
28
+ addSink: (sink) => {
29
+ sinks.set(sink.id, sink);
30
+ },
31
+ removeSink: (sinkId) => {
32
+ sinks.delete(sinkId);
33
+ }
57
34
  };
58
35
  }
59
36
 
@@ -88,6 +65,49 @@ function callbackSink(options) {
88
65
  };
89
66
  }
90
67
 
68
+ // src/logging/logs-logic.ts
69
+ function presetFilters(preset, verbose) {
70
+ const level = verbose ? ["debug", "info", "warn", "error"] : ["info", "warn", "error"];
71
+ switch (preset) {
72
+ case "all":
73
+ return { level };
74
+ case "actions":
75
+ return { level, has_actor: true };
76
+ case "errors":
77
+ return { level: ["error"] };
78
+ }
79
+ }
80
+ function hasActor(entry) {
81
+ return !!(entry.actor?.id || entry.actor?.name);
82
+ }
83
+ function matchesPresetFilters(entry, filters) {
84
+ return filters.level.includes(entry.level) && (!filters.has_actor || hasActor(entry));
85
+ }
86
+ function deriveStuckRecords(entries) {
87
+ const latest = /* @__PURE__ */ new Map();
88
+ for (const entry of entries) {
89
+ if (!entry.syncRecord) continue;
90
+ const key = `${entry.syncRecord.collection}:${entry.syncRecord.recordId}`;
91
+ const seen = latest.get(key);
92
+ if (!seen || entry.timestamp >= seen.timestamp) latest.set(key, entry);
93
+ }
94
+ const stuck = [];
95
+ for (const [key, entry] of latest) {
96
+ const { collection, recordId, outcome, code, reason } = entry.syncRecord;
97
+ if (outcome === "ok") continue;
98
+ stuck.push({
99
+ key,
100
+ collection,
101
+ recordId,
102
+ outcome,
103
+ ...code ? { code } : {},
104
+ reason: reason || entry.message,
105
+ lastSeen: entry.timestamp
106
+ });
107
+ }
108
+ return stuck.sort((a, b) => b.lastSeen - a.lastSeen);
109
+ }
110
+
91
111
  // src/csv/csv.ts
92
112
  function csvCell(value) {
93
113
  const text2 = String(value ?? "");
@@ -4428,6 +4448,21 @@ function adoptStoreCounters(host, storeKey, registerId, counters) {
4428
4448
  return Object.keys(raised).length ? withRegister(store, registerId, { ...register, ...raised }) : void 0;
4429
4449
  });
4430
4450
  }
4451
+ function renumberClosures(host, storeKey, registerId, rows) {
4452
+ const last = rows[rows.length - 1];
4453
+ return modifyStore(host, storeKey, (store) => {
4454
+ const register = store?.registers?.[registerId] ?? {};
4455
+ const reservation = register.closure_reservation;
4456
+ const row = rows.find(({ id: id2 }) => id2 === reservation?.row.id);
4457
+ return withRegister(store, registerId, {
4458
+ ...register,
4459
+ last_closure_number: last.number,
4460
+ perpetual_sales_total_minor: last.perpetual_sales_total_minor,
4461
+ perpetual_refunds_total_minor: last.perpetual_refunds_total_minor,
4462
+ ...reservation && row ? { closure_reservation: { ...reservation, row } } : {}
4463
+ });
4464
+ });
4465
+ }
4431
4466
  function advancePerpetual(host, storeKey, registerId, period) {
4432
4467
  return modifyStore(host, storeKey, (store) => {
4433
4468
  const register = store?.registers?.[registerId] ?? {};
@@ -4476,7 +4511,12 @@ function identity(fact) {
4476
4511
  function recordRegisterFact(fact) {
4477
4512
  const terminal = identity(fact);
4478
4513
  const pair = { sessionId: fact.sessionId, registerId: fact.registerId };
4479
- const emit = (message, type, context = {}, level = "info") => registerFactsLogger[level](message, { actor: fact.actor, terminal, context: { type, ...pair, ...context } });
4514
+ const emit = (message, type, context = {}, level = "info") => registerFactsLogger[level](
4515
+ message,
4516
+ { actor: fact.actor, terminal, context: { type, ...pair, ...context } },
4517
+ // The cashier also rides on the entry itself, so a Logs screen's Actions preset finds it (#656).
4518
+ fact.actor ? { actor: fact.actor } : void 0
4519
+ );
4480
4520
  switch (fact.kind) {
4481
4521
  case "session-opened":
4482
4522
  return emit("Register session opened", "register.session-opened", { amount: fact.amount, variance: fact.variance });
@@ -4562,7 +4602,7 @@ var validAmount = (value, exponent) => /^(?:\d+\.?\d*|\.\d+)$/.test(value) && Nu
4562
4602
  var countVariance = (countedMinor, expectedMinor) => countedMinor - expectedMinor;
4563
4603
  var overThreshold = (variance, thresholdMinor) => thresholdMinor != null && Math.abs(variance) > thresholdMinor;
4564
4604
  var closeNeedsApproval = (countedCashMinor, expectedCashMinor, thresholdMinor) => overThreshold(countVariance(countedCashMinor, expectedCashMinor), thresholdMinor);
4565
- var closureVariance = (counted, tillExpected) => Object.fromEntries(Object.entries(counted).map(([method, value]) => [method, countVariance(value, tillExpected[method] ?? 0)]));
4605
+ var closureVariance = (counted2, tillExpected) => Object.fromEntries(Object.entries(counted2).map(([method, value]) => [method, countVariance(value, tillExpected[method] ?? 0)]));
4566
4606
  var denominationTotal = (pieces) => Object.entries(pieces).reduce((sum2, [value, count]) => sum2 + Number(value) * count, 0);
4567
4607
  function varianceText(variance, exponent, format2, t) {
4568
4608
  if (!variance) return t("register.exact");
@@ -4769,16 +4809,16 @@ async function recordMovement(sessions, movements, closures, input) {
4769
4809
  created_by: input.actor,
4770
4810
  created_at_gmt: (/* @__PURE__ */ new Date()).toISOString()
4771
4811
  });
4772
- let counted;
4812
+ let counted2;
4773
4813
  try {
4774
4814
  const after = await readSession(sessions, input.sessionId);
4775
4815
  if (after?.status !== "closed") return row;
4776
- counted = (await closures.findOne(input.sessionId).exec())?.movement_ids;
4816
+ counted2 = (await closures.findOne(input.sessionId).exec())?.movement_ids;
4777
4817
  } catch {
4778
4818
  return row;
4779
4819
  }
4780
- if (!counted) throw new RegisterMovementStrandedError(row);
4781
- if (counted.includes(row.id)) return row;
4820
+ if (!counted2) throw new RegisterMovementStrandedError(row);
4821
+ if (counted2.includes(row.id)) return row;
4782
4822
  try {
4783
4823
  await row.remove();
4784
4824
  } catch {
@@ -4807,15 +4847,15 @@ async function voidMovement(sessions, movements, movementId, actor, closures) {
4807
4847
  created_at_gmt: (/* @__PURE__ */ new Date()).toISOString(),
4808
4848
  voids: row.id
4809
4849
  });
4810
- let counted;
4850
+ let counted2;
4811
4851
  try {
4812
4852
  const after = await readSession(sessions, row.session_id);
4813
4853
  if (after?.status !== "closed") return reversal;
4814
- counted = (await readClosure(closures, row.session_id))?.movement_ids;
4854
+ counted2 = (await readClosure(closures, row.session_id))?.movement_ids;
4815
4855
  } catch {
4816
4856
  return reversal;
4817
4857
  }
4818
- if (counted?.includes(reversal.id)) return reversal;
4858
+ if (counted2?.includes(reversal.id)) return reversal;
4819
4859
  throw new RegisterMovementStrandedError(reversal);
4820
4860
  }
4821
4861
  async function writeClosure({
@@ -4823,7 +4863,7 @@ async function writeClosure({
4823
4863
  register,
4824
4864
  storeKey,
4825
4865
  session,
4826
- counted,
4866
+ counted: counted2,
4827
4867
  otherTenders,
4828
4868
  movements,
4829
4869
  orders,
@@ -4863,7 +4903,7 @@ async function writeClosure({
4863
4903
  ledgerRowsBySession: rows,
4864
4904
  refunds
4865
4905
  });
4866
- const counts = { cash: counted, ...otherTenders };
4906
+ const counts = { cash: counted2, ...otherTenders };
4867
4907
  const sum2 = (values) => values.reduce((total, value) => total + value, 0);
4868
4908
  const payment_methods = {};
4869
4909
  for (const row2 of rows) {
@@ -5341,11 +5381,11 @@ function exportCsv(rows, exponent, t, names = {}, storeName = "") {
5341
5381
  ...tenders2.flatMap((method) => {
5342
5382
  const values = (row) => {
5343
5383
  const expected = at(row.expected, method);
5344
- const counted = at(row.counted, method) ?? (expected === void 0 ? void 0 : 0);
5345
- const value = at(row.variance, method) ?? (expected === void 0 ? void 0 : (counted ?? 0) - expected);
5384
+ const counted2 = at(row.counted, method) ?? (expected === void 0 ? void 0 : 0);
5385
+ const value = at(row.variance, method) ?? (expected === void 0 ? void 0 : (counted2 ?? 0) - expected);
5346
5386
  return [
5347
5387
  expected === void 0 ? "" : minorToDecimal(expected, exponent),
5348
- counted === void 0 ? "" : minorToDecimal(counted, exponent),
5388
+ counted2 === void 0 ? "" : minorToDecimal(counted2, exponent),
5349
5389
  value === void 0 ? "" : `${minorToDecimal(Math.abs(value), exponent)} ${t(value < 0 ? "register.short" : value > 0 ? "register.over" : "reports.exact")}`
5350
5390
  ];
5351
5391
  };
@@ -5502,10 +5542,10 @@ function envelope(row, context, xreport = false) {
5502
5542
  ([entryKey, value]) => money({ ...value, name: value.name ?? value.method ?? value.rate ?? entryKey }, fields)
5503
5543
  );
5504
5544
  const methods = breakdowns.payment_methods ?? {};
5505
- const counted = row.counted ?? {};
5545
+ const counted2 = row.counted ?? {};
5506
5546
  const expected = row.expected ?? {};
5507
5547
  const variances = row.variance ?? {};
5508
- const tenders2 = [.../* @__PURE__ */ new Set([...Object.keys(counted), ...Object.keys(expected)])].map((name) => {
5548
+ const tenders2 = [.../* @__PURE__ */ new Set([...Object.keys(counted2), ...Object.keys(expected)])].map((name) => {
5509
5549
  const variance = variances[name] ?? "";
5510
5550
  const method = Object.values(methods).find((m) => m.method === name) ?? methods[name];
5511
5551
  return money(
@@ -5513,7 +5553,7 @@ function envelope(row, context, xreport = false) {
5513
5553
  name,
5514
5554
  label: method?.name || name.charAt(0).toUpperCase() + name.slice(1),
5515
5555
  expected: expected[name] ?? "",
5516
- counted: counted[name] ?? "",
5556
+ counted: counted2[name] ?? "",
5517
5557
  variance,
5518
5558
  has_variance: Number(variance || 0) !== 0,
5519
5559
  variance_label: variance === "" ? "" : context.i18n[Number(variance) > 0 ? "over" : Number(variance) < 0 ? "short" : "exact"],
@@ -5587,7 +5627,7 @@ function buildClosureDocument(row, context) {
5587
5627
  store_key,
5588
5628
  till_expected,
5589
5629
  expected,
5590
- counted,
5630
+ counted: counted2,
5591
5631
  variance,
5592
5632
  period_sales_total_minor,
5593
5633
  period_refunds_total_minor,
@@ -5603,7 +5643,7 @@ function buildClosureDocument(row, context) {
5603
5643
  store_id: store_key,
5604
5644
  till_expected: decimalMap(till_expected, exponent),
5605
5645
  expected: decimalMap(expected, exponent),
5606
- counted: decimalMap(counted, exponent),
5646
+ counted: decimalMap(counted2, exponent),
5607
5647
  variance: decimalMap(variance, exponent),
5608
5648
  period_sales_total: dec(period_sales_total_minor),
5609
5649
  period_refunds_total: dec(period_refunds_total_minor),
@@ -5841,6 +5881,7 @@ function isRequeueable(code) {
5841
5881
  return !NOT_REQUEUEABLE.has(code ?? "");
5842
5882
  }
5843
5883
  var REFUSAL_LOG_MESSAGE_MAX = 200;
5884
+ var syncRecordOf = (orderId, outcome) => ({ collection: "pos_orders", recordId: orderId, outcome });
5844
5885
  var ISOLATE_AFTER_ATTEMPTS = 5;
5845
5886
  var STUCK_AFTER_MS = 15 * 6e4;
5846
5887
  var validMax = (max) => typeof max === "number" && Number.isSafeInteger(max) && max > 0 ? max : void 0;
@@ -5954,7 +5995,7 @@ function createOrderOutbox(options) {
5954
5995
  if (runProgressed && retryAfterMs === void 0 && reason !== "status_429") return void 0;
5955
5996
  return Math.max(retryAfterMs ?? 0, isolated.get(id2).nextAt - now());
5956
5997
  }
5957
- if (alone === "probe") walk?.failed.set(id2, reason);
5998
+ if (alone === "probe") walk?.failed.set(id2, { orderId: orders[0].id, reason });
5958
5999
  else {
5959
6000
  head = { id: id2, count: head?.id === id2 ? head.count + 1 : 1 };
5960
6001
  if (head.count >= isolateAfter) walk ??= { failed: /* @__PURE__ */ new Map() };
@@ -6163,10 +6204,18 @@ function createOrderOutbox(options) {
6163
6204
  }
6164
6205
  }
6165
6206
  }
6166
- if (result.status === "rejected") outboxLogger[error?.code === "unsupported_version" ? "error" : "warn"](
6167
- "Order refused by the store",
6168
- { orderId: order.id, code: error?.code, message: error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX) }
6169
- );
6207
+ if (result.status === "rejected") {
6208
+ const message = error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX);
6209
+ outboxLogger[error?.code === "unsupported_version" ? "error" : "warn"](
6210
+ "Order refused by the store",
6211
+ { orderId: order.id, code: error?.code, message },
6212
+ { syncRecord: {
6213
+ ...syncRecordOf(order.id, "failed"),
6214
+ ...error?.code ? { code: error.code } : {},
6215
+ ...message ? { reason: message } : {}
6216
+ } }
6217
+ );
6218
+ }
6170
6219
  const updatedAt = new Date(now()).toISOString();
6171
6220
  await current.incrementalModify((data) => {
6172
6221
  delete data.serverFailures;
@@ -6177,6 +6226,9 @@ function createOrderOutbox(options) {
6177
6226
  updatedAt
6178
6227
  });
6179
6228
  });
6229
+ if (result.status !== "rejected") {
6230
+ outboxLogger.info("Order accepted by the store", { orderId: order.id }, { syncRecord: syncRecordOf(order.id, "ok") });
6231
+ }
6180
6232
  attempts.delete(order.commandId);
6181
6233
  isolated.delete(order.commandId);
6182
6234
  clocks.delete(order.commandId);
@@ -6191,7 +6243,14 @@ function createOrderOutbox(options) {
6191
6243
  runProgressed = true;
6192
6244
  if (alone !== "isolated") head = void 0;
6193
6245
  if (walk && alone === "probe") {
6194
- for (const [id2, reason] of walk.failed) isolate(id2, reason);
6246
+ for (const [id2, { orderId, reason }] of walk.failed) {
6247
+ isolate(id2, reason);
6248
+ outboxLogger.warn(
6249
+ "Order isolated: the store keeps failing it",
6250
+ { orderId, reason },
6251
+ { syncRecord: { ...syncRecordOf(orderId, "pending"), reason } }
6252
+ );
6253
+ }
6195
6254
  walk = void 0;
6196
6255
  }
6197
6256
  backoff = initialBackoff;
@@ -6633,7 +6692,62 @@ function createRegisterOutbox(options) {
6633
6692
 
6634
6693
  // src/register/register-adoption.ts
6635
6694
  var chains2 = /* @__PURE__ */ new WeakMap();
6636
- async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey }) {
6695
+ var figure = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
6696
+ var counted = (number, sales, refunds) => {
6697
+ const [n, s, r] = [figure(number), figure(sales), figure(refunds)];
6698
+ return n === void 0 || s === void 0 || r === void 0 ? void 0 : { number: n, sales: s, refunds: r };
6699
+ };
6700
+ async function renumberRefused(commands, closures, host, storeKey, registerId) {
6701
+ const [submits, local] = await Promise.all([
6702
+ readFresh(commands, { selector: { registerId, type: "register.closure.submit" }, sort: [{ seq: "asc" }, { key: "asc" }] }),
6703
+ readFresh(closures, { selector: { register_id: registerId } })
6704
+ ]);
6705
+ const refused = submits.find((submit) => submit.syncStatus === "rejected" && !NON_BLOCKING_REJECTIONS.has(submit.error?.code ?? ""));
6706
+ const row = local.find(({ id: id2, store_key }) => id2 === refused?.payload.closureId && (store_key ?? null) === storeKey);
6707
+ if (refused?.error?.code !== "register_closure_number_invalid" || !row) return;
6708
+ const sent = new Map(submits.map((submit) => [submit.payload.closureId, submit]));
6709
+ const unsent = (closure) => {
6710
+ const submit = sent.get(closure.id);
6711
+ return (closure.store_key ?? null) === storeKey && closure.closed_at >= row.closed_at && (!submit || submit.syncStatus === "pending" || submit.syncStatus === "rejected" && submit.error?.code === "register_closure_number_invalid");
6712
+ };
6713
+ let queued = local.filter(unsent).sort((a, b) => a.closed_at.localeCompare(b.closed_at) || a.id.localeCompare(b.id));
6714
+ if (!row.number_retried) {
6715
+ const store = refused.error.data?.counters ?? {};
6716
+ const base = counted(store.lastClosureNumber, store.perpetualSalesTotalMinor, store.perpetualRefundsTotalMinor);
6717
+ if (!base) return;
6718
+ let { number, sales, refunds } = base;
6719
+ queued = queued.map((closure) => ({
6720
+ ...closure,
6721
+ number: ++number,
6722
+ perpetual_sales_total_minor: sales += closure.period_sales_total_minor,
6723
+ perpetual_refunds_total_minor: refunds += closure.period_refunds_total_minor,
6724
+ number_retried: closure.number_retried || closure.id === row.id
6725
+ }));
6726
+ await renumberClosures(host, storeKey, registerId, queued);
6727
+ } else if (refused.payload.number === row.number) return;
6728
+ for (const closure of [...queued.filter(({ id: id2 }) => id2 !== row.id), ...queued.filter(({ id: id2 }) => id2 === row.id)]) {
6729
+ const { number, perpetual_sales_total_minor: sales, perpetual_refunds_total_minor: refunds, number_retried } = closure;
6730
+ if (!row.number_retried) await (await closures.findOne(closure.id).exec(true)).incrementalPatch({
6731
+ number,
6732
+ perpetual_sales_total_minor: sales,
6733
+ perpetual_refunds_total_minor: refunds,
6734
+ number_retried
6735
+ });
6736
+ const submit = sent.get(closure.id);
6737
+ if (!submit || submit.syncStatus === "pending" && submit.payload.number === number && submit.payload.perpetualSalesTotalMinor === sales && submit.payload.perpetualRefundsTotalMinor === refunds) continue;
6738
+ await (await commands.findOne(submit.key).exec())?.incrementalModify((doc) => {
6739
+ if (doc.commandId !== submit.commandId || doc.syncStatus !== submit.syncStatus) return doc;
6740
+ const { error: _refusal, ...rest } = doc;
6741
+ return { ...rest, commandId: uuidv7(), syncStatus: "pending", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), payload: {
6742
+ ...doc.payload,
6743
+ number,
6744
+ perpetualSalesTotalMinor: sales,
6745
+ perpetualRefundsTotalMinor: refunds
6746
+ } };
6747
+ });
6748
+ }
6749
+ }
6750
+ async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }) {
6637
6751
  const run = (chains2.get(commands) ?? Promise.resolve()).then(async () => {
6638
6752
  const [answers, transitions, rows] = await Promise.all([
6639
6753
  readFresh(commands, { selector: { registerId, syncStatus: { $in: ["applied", "rejected"] } }, sort: [{ seq: "asc" }, { key: "asc" }] }),
@@ -6668,6 +6782,7 @@ async function adoptRegisterResults({ commands, sessions, registerId, host, stor
6668
6782
  }
6669
6783
  const counters = answers.filter((answer) => answer.syncStatus === "applied" && answer.result?.counters).map((answer) => answer.result?.counters);
6670
6784
  if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
6785
+ if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
6671
6786
  }).catch((error) => {
6672
6787
  registerCommandsLogger.error("Register result adoption failed", { context: { registerId, error: String(error) } });
6673
6788
  });
@@ -6797,17 +6912,17 @@ var subscribeClosing = (listener) => {
6797
6912
  };
6798
6913
  };
6799
6914
  var closedFacts = /* @__PURE__ */ new Set();
6800
- var isTenderMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((figure) => typeof figure === "number");
6915
+ var isTenderMap = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((figure2) => typeof figure2 === "number");
6801
6916
  function approvalNeededOf(commandRows, sessions) {
6802
6917
  const row = commandRows.filter((command) => command.type === "register.closure.submit" && command.syncStatus === "rejected" && CLOSURE_HOLDING_REJECTIONS.has(command.error?.code ?? "")).sort((a, b) => a.seq - b.seq)[0];
6803
6918
  if (!row) return null;
6804
- const { closureId, sessionId, counted, tillExpected } = row.payload;
6919
+ const { closureId, sessionId, counted: counted2, tillExpected } = row.payload;
6805
6920
  const data = row.error?.data;
6806
6921
  return {
6807
6922
  closureId,
6808
6923
  sessionId,
6809
6924
  code: row.error.code,
6810
- variance: isTenderMap(data?.variance) ? data.variance : closureVariance(isTenderMap(counted) ? counted : {}, isTenderMap(tillExpected) ? tillExpected : {}),
6925
+ variance: isTenderMap(data?.variance) ? data.variance : closureVariance(isTenderMap(counted2) ? counted2 : {}, isTenderMap(tillExpected) ? tillExpected : {}),
6811
6926
  ...typeof data?.reason === "string" ? { reason: data.reason } : {},
6812
6927
  liveAtStore: isLiveAtStore(
6813
6928
  sessions.find((session) => session.id === sessionId),
@@ -6830,7 +6945,7 @@ function ledgerRows(orders, replaced = replacedOrderIds(orders)) {
6830
6945
  amountMinor: payment.amountMinor
6831
6946
  })));
6832
6947
  }
6833
- var closedCount = (counted) => ({ ...counted, cash: counted.cash ?? 0 });
6948
+ var closedCount = (counted2) => ({ ...counted2, cash: counted2.cash ?? 0 });
6834
6949
  var sameVariance = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.entries(b).every(([method, value]) => a[method] === value);
6835
6950
  function useRegisterSession(options) {
6836
6951
  const { sessions, movements, closures, orders, register, storeKey, registerId, enabled, actor, timezone, tenderInProgress, expectedCloseTime, labels } = options;
@@ -7187,10 +7302,10 @@ function useRegisterSession(options) {
7187
7302
  }
7188
7303
  },
7189
7304
  /** ADR-082 d3: the variance this count would close with, read as the gate reads it; the app sends it to its approval route and back as `approvedVariance`. */
7190
- closureVariance: async (counted) => {
7305
+ closureVariance: async (counted2) => {
7191
7306
  const stored = await readSession(live().sessions, current().id);
7192
7307
  if (!stored) throw new RegisterSessionRequiredError();
7193
- return closureVariance(closedCount(counted), await freshExpected(stored));
7308
+ return closureVariance(closedCount(counted2), await freshExpected(stored));
7194
7309
  },
7195
7310
  recordMovement: async (input) => {
7196
7311
  try {
@@ -7515,8 +7630,9 @@ function useSale(settings, opts) {
7515
7630
  saving,
7516
7631
  /** The failed save's order is confirmed stored (see `isStored`): the UI also offers Continue (`continueSale()`). */
7517
7632
  canContinue,
7633
+ /** Adds the entry, as a new line or one more on its line; returns that line's id, or the refusal `error` now shows. */
7518
7634
  add(entry, traits) {
7519
- if (locked()) return;
7635
+ if (locked()) return SALE_SAVING;
7520
7636
  const builder = builderNow.current;
7521
7637
  try {
7522
7638
  const known = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
@@ -7535,12 +7651,15 @@ function useSale(settings, opts) {
7535
7651
  ].find((message) => message !== null);
7536
7652
  if (refused) {
7537
7653
  builder.removeItem(lineId);
7538
- return setError(refused);
7654
+ setError(refused);
7655
+ return refused;
7539
7656
  }
7540
7657
  setError(null);
7658
+ return { lineId };
7541
7659
  } catch (error2) {
7542
7660
  if (!(error2 instanceof CartError)) throw error2;
7543
7661
  setError(error2.message);
7662
+ return error2.message;
7544
7663
  }
7545
7664
  },
7546
7665
  setQuantity(lineId, quantity) {
@@ -8112,9 +8231,9 @@ function createSaleCouponSource(deps) {
8112
8231
  const data = doc.toJSON(true);
8113
8232
  if (!["percent", "fixed_cart", "fixed_product"].includes(data.discount_type) || !Number.isInteger(data.id) || typeof data.amount !== "string") return null;
8114
8233
  const orders = await deps.orders.find({ selector: { syncStatus: { $in: ["pending", "applied"] } } }).exec();
8115
- const counted = orders.filter((order) => order.coupons?.some((coupon) => coupon.code === code) && (order.syncStatus === "pending" || Date.parse(order.updatedAt) > data._meta.lwt && now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS));
8234
+ const counted2 = orders.filter((order) => order.coupons?.some((coupon) => coupon.code === code) && (order.syncStatus === "pending" || Date.parse(order.updatedAt) > data._meta.lwt && now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS));
8116
8235
  const usedBy = [...data.used_by ?? []];
8117
- for (const order of counted) {
8236
+ for (const order of counted2) {
8118
8237
  const id2 = Number(order.customer?.id);
8119
8238
  const email = order.customer?.email;
8120
8239
  if (Number.isSafeInteger(id2) && id2 > 0) usedBy.push(String(id2));
@@ -8141,7 +8260,7 @@ function createSaleCouponSource(deps) {
8141
8260
  amount: data.amount,
8142
8261
  id: data.id,
8143
8262
  code,
8144
- usage_count: (data.usage_count ?? 0) + counted.length,
8263
+ usage_count: (data.usage_count ?? 0) + counted2.length,
8145
8264
  used_by: usedBy
8146
8265
  };
8147
8266
  },
@@ -9317,6 +9436,7 @@ export {
9317
9436
  denominations,
9318
9437
  deriveExpected,
9319
9438
  deriveSettled,
9439
+ deriveStuckRecords,
9320
9440
  displayCart,
9321
9441
  displayReducer,
9322
9442
  driverForMethod,
@@ -9334,6 +9454,7 @@ export {
9334
9454
  getDeviceId,
9335
9455
  getProductStock,
9336
9456
  handoverSlip,
9457
+ hasActor,
9337
9458
  hasValidRetailCheckDigit,
9338
9459
  inCategory,
9339
9460
  inMotionMinor,
@@ -9354,6 +9475,7 @@ export {
9354
9475
  listCategories,
9355
9476
  makeEnvelope,
9356
9477
  marginOf,
9478
+ matchesPresetFilters,
9357
9479
  messageBytes,
9358
9480
  minorToDecimal,
9359
9481
  mintClosureNumber,
@@ -9382,6 +9504,7 @@ export {
9382
9504
  posOrdersLogger,
9383
9505
  posRefundCollection,
9384
9506
  posRefundSchema,
9507
+ presetFilters,
9385
9508
  presetRange,
9386
9509
  priceRefund,
9387
9510
  printerProfileCollection,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "3.16.0",
3
+ "version": "3.17.0",
4
4
  "type": "module",
5
5
  "description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
6
6
  "main": "./dist/index.js",
@@ -34,20 +34,20 @@
34
34
  "mustache": "^4.2.0"
35
35
  },
36
36
  "peerDependencies": {
37
- "@tallyui/core": "^3.16.0",
37
+ "@tallyui/core": "^3.17.0",
38
38
  "react": ">=18",
39
39
  "rxdb": "~17.5.0",
40
40
  "rxjs": ">=7"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/core": "3.16.0",
43
+ "@tallyui/core": "3.17.0",
44
44
  "@types/react": ">=18",
45
45
  "react": "^19.2.4",
46
46
  "rxdb": "17.5.0",
47
47
  "rxjs": "7.8.2",
48
- "@tallyui/connector-medusa": "3.16.0",
49
- "@tallyui/connector-woocommerce": "3.16.0",
50
- "@tallyui/database": "3.16.0"
48
+ "@tallyui/connector-medusa": "3.17.0",
49
+ "@tallyui/connector-woocommerce": "3.17.0",
50
+ "@tallyui/database": "3.17.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",
package/src/index.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  // Logging
2
- export { createLogger, consoleSink, callbackSink } from './logging';
3
- export type { Logger, LogSink, LogEntry, LogLevel } from './logging';
2
+ export { createLogger, consoleSink, callbackSink, deriveStuckRecords, hasActor, matchesPresetFilters, presetFilters } from './logging';
3
+ export type {
4
+ Logger, LogSink, LogEntry, LogLevel, LogActor, LogMeta, LogSyncRecord, SyncRecordOutcome, LogPreset, LogPresetFilters, StuckRecord,
5
+ } from './logging';
4
6
 
5
7
  // CSV
6
8
  export { csvCell, csvFromCells, toCsv } from './csv';
@@ -1,3 +1,5 @@
1
1
  export { createLogger } from './logger';
2
2
  export { consoleSink, callbackSink } from './sinks';
3
- export type { Logger, LogSink, LogEntry, LogLevel } from './types';
3
+ export { deriveStuckRecords, hasActor, matchesPresetFilters, presetFilters } from './logs-logic';
4
+ export type { LogPreset, LogPresetFilters, StuckRecord } from './logs-logic';
5
+ export type { Logger, LogSink, LogEntry, LogLevel, LogActor, LogMeta, LogSyncRecord, SyncRecordOutcome } from './types';
@@ -1,42 +1,7 @@
1
- import type { Logger, LogEntry, LogLevel, LogSink } from './types';
1
+ import type { Logger, LogEntry, LogLevel, LogMeta, LogSink } from './types';
2
2
 
3
3
  export function createLogger(scope = 'root'): Logger {
4
- const sinks: Map<string, LogSink> = new Map();
5
-
6
- function log(level: LogLevel, message: string, data?: Record<string, unknown>) {
7
- const entry: LogEntry = {
8
- level,
9
- scope,
10
- message,
11
- data,
12
- timestamp: Date.now(),
13
- };
14
-
15
- for (const sink of sinks.values()) {
16
- if (!sink.levels.includes(level)) continue;
17
- if (sink.scopes && !sink.scopes.includes(scope)) continue;
18
- sink.write(entry);
19
- }
20
- }
21
-
22
- return {
23
- debug: (message, data) => log('debug', message, data),
24
- info: (message, data) => log('info', message, data),
25
- warn: (message, data) => log('warn', message, data),
26
- error: (message, data) => log('error', message, data),
27
-
28
- createScope(name: string): Logger {
29
- return createChildLogger(sinks, name);
30
- },
31
-
32
- addSink(sink: LogSink) {
33
- sinks.set(sink.id, sink);
34
- },
35
-
36
- removeSink(sinkId: string) {
37
- sinks.delete(sinkId);
38
- },
39
- };
4
+ return createChildLogger(new Map(), scope);
40
5
  }
41
6
 
42
7
  function logWithSinks(
@@ -45,8 +10,12 @@ function logWithSinks(
45
10
  scope: string,
46
11
  message: string,
47
12
  data?: Record<string, unknown>,
13
+ meta?: LogMeta,
48
14
  ) {
49
15
  const entry: LogEntry = { level, scope, message, data, timestamp: Date.now() };
16
+ // Set only when given, so an entry logged without them keeps its old shape.
17
+ if (meta?.actor) entry.actor = meta.actor;
18
+ if (meta?.syncRecord) entry.syncRecord = meta.syncRecord;
50
19
  for (const sink of sinks.values()) {
51
20
  if (!sink.levels.includes(level)) continue;
52
21
  if (sink.scopes && !sink.scopes.includes(scope)) continue;
@@ -56,12 +25,12 @@ function logWithSinks(
56
25
 
57
26
  function createChildLogger(sinks: Map<string, LogSink>, scope: string): Logger {
58
27
  return {
59
- debug: (message, data) => logWithSinks(sinks, 'debug', scope, message, data),
60
- info: (message, data) => logWithSinks(sinks, 'info', scope, message, data),
61
- warn: (message, data) => logWithSinks(sinks, 'warn', scope, message, data),
62
- error: (message, data) => logWithSinks(sinks, 'error', scope, message, data),
28
+ debug: (message, data, meta) => logWithSinks(sinks, 'debug', scope, message, data, meta),
29
+ info: (message, data, meta) => logWithSinks(sinks, 'info', scope, message, data, meta),
30
+ warn: (message, data, meta) => logWithSinks(sinks, 'warn', scope, message, data, meta),
31
+ error: (message, data, meta) => logWithSinks(sinks, 'error', scope, message, data, meta),
63
32
  createScope: (childName: string) => createChildLogger(sinks, childName),
64
- addSink: (sink: LogSink) => sinks.set(sink.id, sink),
65
- removeSink: (sinkId: string) => sinks.delete(sinkId),
33
+ addSink: (sink: LogSink) => { sinks.set(sink.id, sink); },
34
+ removeSink: (sinkId: string) => { sinks.delete(sinkId); },
66
35
  };
67
36
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Pure helpers for a Logs screen, ported from WCPOS v2 `packages/core/src/screens/main/logs/logs-logic.ts`
3
+ * (monorepo `main` 51e7c4351): `presetFilters` (its `has_actor` part) and `deriveStuckRecords`. v2 reads its
4
+ * stored log rows; these read TallyUI's `LogEntry`, with its typed `actor` and `syncRecord`. v2's `sync` preset
5
+ * filters on v2's `wcpos.sync` category, which TallyUI's log scopes have no counterpart for, so it is not ported.
6
+ */
7
+ import type { LogEntry, LogLevel } from './types';
8
+
9
+ export type LogPreset = 'all' | 'actions' | 'errors';
10
+
11
+ export interface LogPresetFilters {
12
+ level: LogLevel[];
13
+ /** Only entries a person did (`hasActor`). */
14
+ has_actor?: true;
15
+ }
16
+
17
+ /** Preset chip to filters. Debug entries count only while verbose diagnostics is on. */
18
+ export function presetFilters(preset: LogPreset, verbose: boolean): LogPresetFilters {
19
+ const level: LogLevel[] = verbose ? ['debug', 'info', 'warn', 'error'] : ['info', 'warn', 'error'];
20
+ switch (preset) {
21
+ case 'all':
22
+ return { level };
23
+ case 'actions':
24
+ return { level, has_actor: true };
25
+ case 'errors':
26
+ return { level: ['error'] };
27
+ }
28
+ }
29
+
30
+ /** A person did it: the entry's actor names an id or a name (v2 reads such a row as an action). */
31
+ export function hasActor(entry: Pick<LogEntry, 'actor'>): boolean {
32
+ return !!(entry.actor?.id || entry.actor?.name);
33
+ }
34
+
35
+ export function matchesPresetFilters(entry: LogEntry, filters: LogPresetFilters): boolean {
36
+ return filters.level.includes(entry.level) && (!filters.has_actor || hasActor(entry));
37
+ }
38
+
39
+ export interface StuckRecord {
40
+ /** `${collection}:${recordId}` */
41
+ key: string;
42
+ collection: string;
43
+ recordId: string;
44
+ /** `failed`: the store refused it. `pending`: the store keeps failing it, and it is still retrying. */
45
+ outcome: 'failed' | 'pending';
46
+ code?: string;
47
+ reason: string;
48
+ /** When its latest outcome was logged. */
49
+ lastSeen: number;
50
+ }
51
+
52
+ /**
53
+ * The records whose latest sync outcome is `failed` or `pending`; an `ok` clears. Entries without a `syncRecord`
54
+ * are no evidence either way. The latest is by timestamp, and on equal timestamps the entry later in `entries`
55
+ * (the order a sink receives them). Newest first.
56
+ */
57
+ export function deriveStuckRecords(entries: readonly LogEntry[]): StuckRecord[] {
58
+ const latest = new Map<string, LogEntry>();
59
+ for (const entry of entries) {
60
+ if (!entry.syncRecord) continue;
61
+ const key = `${entry.syncRecord.collection}:${entry.syncRecord.recordId}`;
62
+ const seen = latest.get(key);
63
+ if (!seen || entry.timestamp >= seen.timestamp) latest.set(key, entry);
64
+ }
65
+ const stuck: StuckRecord[] = [];
66
+ for (const [key, entry] of latest) {
67
+ const { collection, recordId, outcome, code, reason } = entry.syncRecord!;
68
+ if (outcome === 'ok') continue;
69
+ stuck.push({ key, collection, recordId, outcome, ...(code ? { code } : {}), reason: reason || entry.message,
70
+ lastSeen: entry.timestamp });
71
+ }
72
+ return stuck.sort((a, b) => b.lastSeen - a.lastSeen);
73
+ }
@@ -1,6 +1,35 @@
1
1
  export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
2
 
3
- export interface LogEntry {
3
+ /** Who did it: a person (a cashier or manager), not the system. WCPOS v2's log actor. */
4
+ export interface LogActor {
5
+ id?: string;
6
+ name?: string;
7
+ role?: string;
8
+ }
9
+
10
+ /** `ok`: the store applied the record. `failed`: the store refused it. `pending`: the store keeps failing it on its
11
+ * own, and it is still retrying. */
12
+ export type SyncRecordOutcome = 'ok' | 'failed' | 'pending';
13
+
14
+ /** One record's sync outcome (WCPOS v2's `sync.record` row). */
15
+ export interface LogSyncRecord {
16
+ /** The local collection, e.g. `pos_orders`. */
17
+ collection: string;
18
+ /** The record's durable id (a PosOrder's `id`, not its commandId). */
19
+ recordId: string;
20
+ outcome: SyncRecordOutcome;
21
+ /** The store's error code. */
22
+ code?: string;
23
+ reason?: string;
24
+ }
25
+
26
+ /** Typed fields a call site puts on the entry itself; each is set on the entry only when given. */
27
+ export interface LogMeta {
28
+ actor?: LogActor;
29
+ syncRecord?: LogSyncRecord;
30
+ }
31
+
32
+ export interface LogEntry extends LogMeta {
4
33
  level: LogLevel;
5
34
  scope: string;
6
35
  message: string;
@@ -15,11 +44,13 @@ export interface LogSink {
15
44
  write(entry: LogEntry): void;
16
45
  }
17
46
 
47
+ type LogMethod = (message: string, data?: Record<string, unknown>, meta?: LogMeta) => void;
48
+
18
49
  export interface Logger {
19
- debug(message: string, data?: Record<string, unknown>): void;
20
- info(message: string, data?: Record<string, unknown>): void;
21
- warn(message: string, data?: Record<string, unknown>): void;
22
- error(message: string, data?: Record<string, unknown>): void;
50
+ debug: LogMethod;
51
+ info: LogMethod;
52
+ warn: LogMethod;
53
+ error: LogMethod;
23
54
  createScope(name: string): Logger;
24
55
  addSink(sink: LogSink): void;
25
56
  removeSink(sinkId: string): void;
@@ -2,6 +2,7 @@ import type { OrderCreateEnvelope } from '@tallyui/core';
2
2
  import { deepEqual, type RxCollection, type RxDocumentData } from 'rxdb';
3
3
  import { BehaviorSubject, type Observable, type Subscription } from 'rxjs';
4
4
  import { outboxLogger } from './logger';
5
+ import type { LogSyncRecord, SyncRecordOutcome } from '../logging';
5
6
  import { toOrderCreateEnvelope, UnsupportedOrderVersionError, uuidv7, replacedOrderIds, type PosOrder, type PosOrderServerFailures } from '../pos-order';
6
7
  import { freezeSentForm } from '../pos-order/finalize';
7
8
  import { countFresh, readFresh } from '../rxdb';
@@ -23,6 +24,10 @@ export function isRequeueable(code: string | undefined): boolean {
23
24
  // The store's message in the refusal log is cut to this many characters, the cap connectors use for a foreign 426 message.
24
25
  const REFUSAL_LOG_MESSAGE_MAX = 200;
25
26
 
27
+ /** An order's sync record, keyed by its durable `id` (a resend gets a new commandId). */
28
+ const syncRecordOf = (orderId: string, outcome: SyncRecordOutcome): LogSyncRecord =>
29
+ ({ collection: 'pos_orders', recordId: orderId, outcome });
30
+
26
31
  // After this many consecutive failures the store answered (not offline) with the same head order and
27
32
  // no progress, the queue is probed one order at a time, so an order the store can't take holds up only
28
33
  // itself. With the default backoff the first probe goes after about 30 s: sales keep flowing within minutes.
@@ -100,7 +105,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
100
105
  // the orders whose probes failed are isolated and batching resumes. When no order is left to probe, the
101
106
  // store is down: nothing is isolated, and batching resumes with its backoff.
102
107
  let head: { id: string; count: number } | undefined;
103
- let walk: { failed: Map<string, string> } | undefined;
108
+ let walk: { failed: Map<string, { orderId: string; reason: string }> } | undefined;
104
109
  // Isolated orders are left out of batches and retried alone, each on its own backoff, while pending
105
110
  // under their commandId.
106
111
  const isolated = new Map<string, { backoff: number; nextAt: number; reason: string }>();
@@ -211,7 +216,7 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
211
216
  if (runProgressed && retryAfterMs === undefined && reason !== 'status_429') return undefined;
212
217
  return Math.max(retryAfterMs ?? 0, isolated.get(id)!.nextAt - now());
213
218
  }
214
- if (alone === 'probe') walk?.failed.set(id, reason);
219
+ if (alone === 'probe') walk?.failed.set(id, { orderId: orders[0].id, reason });
215
220
  else {
216
221
  head = { id, count: head?.id === id ? head.count + 1 : 1 };
217
222
  if (head.count >= isolateAfter) walk ??= { failed: new Map() };
@@ -402,8 +407,15 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
402
407
  }
403
408
  // Every refusal goes to the sync log once, with the store's code and message (the orders list shows the cashier
404
409
  // only the code's sentence, #269); unsupported_version stays an error.
405
- if (result.status === 'rejected') outboxLogger[error?.code === 'unsupported_version' ? 'error' : 'warn']('Order refused by the store',
406
- { orderId: order.id, code: error?.code, message: error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX) });
410
+ // Each refusal and each apply also carries the order's sync record, so a Logs screen can tell which orders are
411
+ // stuck: the latest outcome per order rules (`deriveStuckRecords`, #656).
412
+ if (result.status === 'rejected') {
413
+ const message = error?.message?.slice(0, REFUSAL_LOG_MESSAGE_MAX);
414
+ outboxLogger[error?.code === 'unsupported_version' ? 'error' : 'warn']('Order refused by the store',
415
+ { orderId: order.id, code: error?.code, message },
416
+ { syncRecord: { ...syncRecordOf(order.id, 'failed'), ...(error?.code ? { code: error.code } : {}),
417
+ ...(message ? { reason: message } : {}) } });
418
+ }
407
419
  const updatedAt = new Date(now()).toISOString();
408
420
  // Progress removes the stored serverFailures in the write that marks the order applied or rejected.
409
421
  await current.incrementalModify((data) => {
@@ -413,6 +425,9 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
413
425
  : { syncStatus: 'applied' as const, serverRefs: result.serverRefs,
414
426
  ...(result.warnings ? { warnings: result.warnings } : {}), updatedAt });
415
427
  });
428
+ if (result.status !== 'rejected') {
429
+ outboxLogger.info('Order accepted by the store', { orderId: order.id }, { syncRecord: syncRecordOf(order.id, 'ok') });
430
+ }
416
431
  attempts.delete(order.commandId);
417
432
  isolated.delete(order.commandId);
418
433
  clocks.delete(order.commandId);
@@ -428,7 +443,12 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
428
443
  if (alone !== 'isolated') head = undefined;
429
444
  if (walk && alone === 'probe') {
430
445
  // The store took a probe, so it is up: the orders whose probes failed are isolated, and batching resumes.
431
- for (const [id, reason] of walk.failed) isolate(id, reason);
446
+ // Each is logged once, as pending: it stays queued and retries alone, so it is stuck but not refused (#656).
447
+ for (const [id, { orderId, reason }] of walk.failed) {
448
+ isolate(id, reason);
449
+ outboxLogger.warn('Order isolated: the store keeps failing it', { orderId, reason },
450
+ { syncRecord: { ...syncRecordOf(orderId, 'pending'), reason } });
451
+ }
432
452
  walk = undefined;
433
453
  }
434
454
  backoff = initialBackoff;
@@ -67,7 +67,9 @@ export function recordRegisterFact(fact: RegisterFact): void {
67
67
  type: string,
68
68
  context: Record<string, unknown> = {},
69
69
  level: 'info' | 'warn' = 'info',
70
- ) => registerFactsLogger[level](message, { actor: fact.actor, terminal, context: { type, ...pair, ...context } });
70
+ ) => registerFactsLogger[level](message, { actor: fact.actor, terminal, context: { type, ...pair, ...context } },
71
+ // The cashier also rides on the entry itself, so a Logs screen's Actions preset finds it (#656).
72
+ fact.actor ? { actor: fact.actor } : undefined);
71
73
  switch (fact.kind) {
72
74
  case 'session-opened':
73
75
  return emit('Register session opened', 'register.session-opened', { amount: fact.amount, variance: fact.variance });
@@ -1,26 +1,86 @@
1
1
  import type { ServerCapabilities } from '@tallyui/core';
2
- import { CLOSURE_HOLDING_REJECTIONS } from '../outbox/register-outbox';
2
+ import { CLOSURE_HOLDING_REJECTIONS, NON_BLOCKING_REJECTIONS } from '../outbox/register-outbox';
3
3
  import { readFresh } from '../rxdb';
4
4
  import { uuidv7 } from '../pos-order/uuidv7';
5
5
  import { countVariance, overThreshold } from './register-count.helpers';
6
- import { adoptStoreCounters, type RegisterHost } from './register-document';
6
+ import { adoptStoreCounters, renumberClosures, type RegisterHost } from './register-document';
7
7
  import { registerCommandsLogger, type RegisterCommand, type RegisterCommandCollection } from './register-commands';
8
8
  import type { Closure, RegisterSession } from './schemas';
9
- import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type RegisterSessionCollection } from './session-store';
9
+ import { isKnownSessionStatus, RegisterSessionRequiredError, RegisterTakeOverError, type ClosureCollection,
10
+ type RegisterSessionCollection } from './session-store';
10
11
 
11
12
  const chains = new WeakMap<RegisterCommandCollection, Promise<void>>();
13
+ const figure = (value: unknown) => (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
14
+ type Counted = { number: number; sales: number; refunds: number };
15
+ const counted = (number: unknown, sales: unknown, refunds: unknown): Counted | undefined => {
16
+ const [n, s, r] = [figure(number), figure(sales), figure(refunds)];
17
+ return n === undefined || s === undefined || r === undefined ? undefined : { number: n, sales: s, refunds: r };
18
+ };
19
+
20
+ /**
21
+ * The store takes a closure only as its last number plus one; it refuses any other `register_closure_number_invalid`
22
+ * with its counters (ADR-068 d5). The register's first refused closure submit, past the outbox's non-blocking
23
+ * refusals, is the one: when the store refused it for its number, every unsent closure of this register and store
24
+ * (closed since, its submit missing, pending or refused for its number) is renumbered in one pass, in closed order,
25
+ * consecutively from the store's counter, the truth, with chained totals. Only the refused closure spends its retry
26
+ * (`number_retried`). The register document, the closure rows and the command rows are rewritten in that order, the
27
+ * refused closure's last, and each changed command is requeued under a new command id (ADR-068 d6). Any other
28
+ * refusal, a second refusal of a renumbered closure, or malformed counters writes nothing.
29
+ */
30
+ async function renumberRefused(commands: RegisterCommandCollection, closures: ClosureCollection, host: RegisterHost,
31
+ storeKey: string, registerId: string) {
32
+ const [submits, local] = await Promise.all([
33
+ readFresh(commands, { selector: { registerId, type: 'register.closure.submit' }, sort: [{ seq: 'asc' }, { key: 'asc' }] }),
34
+ readFresh(closures, { selector: { register_id: registerId } }),
35
+ ]);
36
+ const refused = submits.find((submit) => submit.syncStatus === 'rejected' && !NON_BLOCKING_REJECTIONS.has(submit.error?.code ?? ''));
37
+ const row = local.find(({ id, store_key }) => id === refused?.payload.closureId && (store_key ?? null) === storeKey);
38
+ if (refused?.error?.code !== 'register_closure_number_invalid' || !row) return;
39
+ const sent = new Map(submits.map((submit) => [submit.payload.closureId, submit]));
40
+ const unsent = (closure: Closure) => {
41
+ const submit = sent.get(closure.id);
42
+ return (closure.store_key ?? null) === storeKey && closure.closed_at >= row.closed_at && (!submit || submit.syncStatus === 'pending'
43
+ || (submit.syncStatus === 'rejected' && submit.error?.code === 'register_closure_number_invalid'));
44
+ };
45
+ let queued = local.filter(unsent).sort((a, b) => a.closed_at.localeCompare(b.closed_at) || a.id.localeCompare(b.id));
46
+ if (!row.number_retried) {
47
+ const store = (refused.error.data?.counters ?? {}) as Record<string, unknown>;
48
+ const base = counted(store.lastClosureNumber, store.perpetualSalesTotalMinor, store.perpetualRefundsTotalMinor);
49
+ if (!base) return;
50
+ let { number, sales, refunds } = base;
51
+ queued = queued.map((closure) => ({ ...closure, number: ++number, perpetual_sales_total_minor: sales += closure.period_sales_total_minor,
52
+ perpetual_refunds_total_minor: refunds += closure.period_refunds_total_minor, number_retried: closure.number_retried || closure.id === row.id }));
53
+ await renumberClosures(host, storeKey, registerId, queued);
54
+ } else if (refused.payload.number === row.number) return;
55
+ // The refused closure goes last, so a crash part way leaves it refused and unretried, or retried with a stale command.
56
+ for (const closure of [...queued.filter(({ id }) => id !== row.id), ...queued.filter(({ id }) => id === row.id)]) {
57
+ const { number, perpetual_sales_total_minor: sales, perpetual_refunds_total_minor: refunds, number_retried } = closure;
58
+ if (!row.number_retried) await (await closures.findOne(closure.id).exec(true)).incrementalPatch({ number,
59
+ perpetual_sales_total_minor: sales, perpetual_refunds_total_minor: refunds, number_retried });
60
+ const submit = sent.get(closure.id);
61
+ if (!submit || (submit.syncStatus === 'pending' && submit.payload.number === number
62
+ && submit.payload.perpetualSalesTotalMinor === sales && submit.payload.perpetualRefundsTotalMinor === refunds)) continue;
63
+ await (await commands.findOne(submit.key).exec())?.incrementalModify((doc) => {
64
+ if (doc.commandId !== submit.commandId || doc.syncStatus !== submit.syncStatus) return doc;
65
+ const { error: _refusal, ...rest } = doc;
66
+ return { ...rest, commandId: uuidv7(), syncStatus: 'pending', updatedAt: new Date().toISOString(), payload: { ...doc.payload,
67
+ number, perpetualSalesTotalMinor: sales, perpetualRefundsTotalMinor: refunds } };
68
+ });
69
+ }
70
+ }
12
71
  type SessionTarget = { commands: RegisterCommandCollection; sessions: RegisterSessionCollection; sessionId: string; now?: string };
13
72
 
14
73
  /**
15
74
  * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
16
75
  * Superseded rejections make open/counting sessions terminal; a conflict session leaves only by an applied open or abandon (ADR-078 decision 9); terminal/unknown states stay untouched.
17
76
  * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
18
- * Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters`).
77
+ * Given `host` and `storeKey`, applied rows also raise the register's counters to the store's (#651, `adoptStoreCounters`),
78
+ * and given `closures` too, a closure refused for its number is renumbered once and requeued (#655, `renumberRefused`).
19
79
  * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
20
80
  */
21
- export async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey }: {
81
+ export async function adoptRegisterResults({ commands, sessions, registerId, host, storeKey, closures }: {
22
82
  commands: RegisterCommandCollection; sessions: RegisterSessionCollection; registerId: string;
23
- host?: RegisterHost; storeKey?: string;
83
+ host?: RegisterHost; storeKey?: string; closures?: ClosureCollection;
24
84
  }): Promise<void> {
25
85
  const run = (chains.get(commands) ?? Promise.resolve()).then(async () => {
26
86
  const [answers, transitions, rows] = await Promise.all([
@@ -59,6 +119,7 @@ export async function adoptRegisterResults({ commands, sessions, registerId, hos
59
119
  }
60
120
  const counters = answers.filter((answer) => answer.syncStatus === 'applied' && answer.result?.counters).map((answer) => answer.result?.counters);
61
121
  if (host && storeKey && counters.length) await adoptStoreCounters(host, storeKey, registerId, counters);
122
+ if (host && storeKey && closures) await renumberRefused(commands, closures, host, storeKey, registerId);
62
123
  }).catch((error: unknown) => {
63
124
  registerCommandsLogger.error('Register result adoption failed', { context: { registerId, error: String(error) } });
64
125
  });
@@ -245,6 +245,28 @@ export function adoptStoreCounters(host: RegisterHost, storeKey: string, registe
245
245
  });
246
246
  }
247
247
 
248
+ /**
249
+ * Records the closures renumbered after a refusal (#655), in number order: the register's last number and totals are
250
+ * set outright to the last one's, the store's counter plus this till's unsent closures (no max: on a refusal the
251
+ * store's counter is the truth), and a reservation holding one of them takes its new row, keeping `applied`. Each
252
+ * field is set, not added, so a repeat changes nothing.
253
+ */
254
+ export function renumberClosures(host: RegisterHost, storeKey: string, registerId: string, rows: Closure[]) {
255
+ const last = rows[rows.length - 1];
256
+ return modifyStore(host, storeKey, (store) => {
257
+ const register = store?.registers?.[registerId] ?? {};
258
+ const reservation = register.closure_reservation;
259
+ const row = rows.find(({ id }) => id === reservation?.row.id);
260
+ return withRegister(store, registerId, {
261
+ ...register,
262
+ last_closure_number: last.number,
263
+ perpetual_sales_total_minor: last.perpetual_sales_total_minor,
264
+ perpetual_refunds_total_minor: last.perpetual_refunds_total_minor,
265
+ ...(reservation && row ? { closure_reservation: { ...reservation, row } } : {}),
266
+ });
267
+ });
268
+ }
269
+
248
270
  /**
249
271
  * Adds a closed period to the register's perpetual totals. With `closureId`, it applies that
250
272
  * reserved closure once: the totals become the reservation's, and a repeat does nothing.
@@ -291,8 +291,9 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
291
291
  saving,
292
292
  /** The failed save's order is confirmed stored (see `isStored`): the UI also offers Continue (`continueSale()`). */
293
293
  canContinue,
294
- add(entry: CatalogueEntry<any>, traits: ProductTraits<any>) {
295
- if (locked()) return;
294
+ /** Adds the entry, as a new line or one more on its line; returns that line's id, or the refusal `error` now shows. */
295
+ add(entry: CatalogueEntry<any>, traits: ProductTraits<any>): { lineId: string } | string {
296
+ if (locked()) return SALE_SAVING;
296
297
  const builder = builderNow.current;
297
298
  try {
298
299
  const known = new Set(builder.getSnapshot().lineItems.map((line) => line.id));
@@ -310,11 +311,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
310
311
  const refused = line && [line.variantId !== undefined ? referenceError(`${name}: the variant id`, line.variantId)
311
312
  : referenceError(`${name}: the product id`, line.productId),
312
313
  ...taxLines.map((tax) => referenceError(`${name}: the tax code`, tax.code))].find((message) => message !== null);
313
- if (refused) { builder.removeItem(lineId); return setError(refused); }
314
+ if (refused) { builder.removeItem(lineId); setError(refused); return refused; }
314
315
  setError(null);
316
+ return { lineId };
315
317
  } catch (error) {
316
318
  if (!(error instanceof CartError)) throw error;
317
319
  setError(error.message);
320
+ return error.message;
318
321
  }
319
322
  },
320
323
  setQuantity(lineId: string, quantity: number) { if (!locked()) builderNow.current.updateQuantity(lineId, quantity); },