@tallyui/pos 3.9.2 → 3.11.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
@@ -251,6 +251,7 @@ declare function createRepository<T extends {
251
251
 
252
252
  interface OrderCoupon {
253
253
  code: string;
254
+ couponId: string;
254
255
  discountMinor: number;
255
256
  discountTaxMinor: number;
256
257
  }
@@ -336,9 +337,13 @@ interface LineItem {
336
337
  productId: string;
337
338
  variantId?: string;
338
339
  name: string;
340
+ /** The variant's chosen options, name to value (#495). */
341
+ attributes?: Record<string, string>;
339
342
  sku: string;
340
343
  imageUrl?: string;
341
344
  unitPriceMinor: number;
345
+ /** The catalogue's regular unit price, in the line's own tax mode like unitPriceMinor; absent on custom lines (ADR-077 d3). */
346
+ regularUnitPriceMinor?: number;
342
347
  quantity: number;
343
348
  taxLines: LineTaxLine[];
344
349
  discounts: AppliedDiscount[];
@@ -415,11 +420,14 @@ interface AddLineInput {
415
420
  taxStatus?: 'taxable' | 'none';
416
421
  variantId?: string;
417
422
  name: string;
423
+ /** The variant's chosen options, name to value (#495). */
424
+ attributes?: Record<string, string>;
418
425
  sku?: string;
419
426
  imageUrl?: string;
420
427
  unitPrice: Money & {
421
428
  taxInclusive?: boolean;
422
429
  };
430
+ regularUnitPriceMinor?: number;
423
431
  quantity?: number;
424
432
  taxRates?: Array<{
425
433
  code?: string;
@@ -430,6 +438,7 @@ interface AddLineInput {
430
438
 
431
439
  interface OrderCouponContext {
432
440
  configs: ReadonlyMap<string, woocommerceCoupons.CouponDiscountConfig>;
441
+ couponIds: ReadonlyMap<string, string>;
433
442
  productCategories: ReadonlyMap<number, {
434
443
  id: number;
435
444
  }[]>;
@@ -469,8 +478,8 @@ interface OrderBuilder {
469
478
  removePayment(paymentId: string): void;
470
479
  setCustomer(customer: CustomerSummary | null): void;
471
480
  setNote(note: string): void;
472
- /** Replaces the coupon codes with their trimmed, lower-case, deduplicated list. */
473
- setCoupons(codes: readonly string[]): void;
481
+ /** Replaces the coupon codes with their trimmed, lower-case, deduplicated list; a given context replaces the builder's coupon context. */
482
+ setCoupons(codes: readonly string[], context?: OrderCouponContext): void;
474
483
  clear(): void;
475
484
  getSnapshot(): Order;
476
485
  }
@@ -580,6 +589,8 @@ interface ReceiptFiscal {
580
589
  }
581
590
  interface ReceiptLineItem {
582
591
  name: string;
592
+ /** The variant's chosen options, name to value (#495); absent when none. */
593
+ attributes?: Record<string, string>;
583
594
  sku: string;
584
595
  quantity: number;
585
596
  unitPriceMinor: number;
@@ -742,6 +753,13 @@ interface PosOrderServerFailures {
742
753
  /** The order failed when sent alone (as a probe or while isolated), so it is retried alone. */
743
754
  isolated: boolean;
744
755
  }
756
+ /** A WooCommerce coupon on the stored order (ADR-077 d2): its figures are the order builder's coupon replay. */
757
+ interface PosOrderCoupon {
758
+ code: string;
759
+ couponId: string;
760
+ discountMinor: number;
761
+ discountTaxMinor: number;
762
+ }
745
763
  interface PosOrderLine {
746
764
  id: string;
747
765
  productId: string;
@@ -752,6 +770,10 @@ interface PosOrderLine {
752
770
  sku: string;
753
771
  quantity: number;
754
772
  unitPriceMinor: number;
773
+ /** The chosen variation attributes, name to value (pos_orders v9, #495). */
774
+ attributes?: Record<string, string>;
775
+ /** The catalogue's regular unit price, in the line's own tax mode like `unitPriceMinor` (pos_orders v9, ADR-077 d2). */
776
+ regularUnitPriceMinor?: number;
755
777
  /** Line discounts plus the allocated order-discount share, in the line's own tax mode (ADR-062). */
756
778
  discountMinor: number;
757
779
  netMinor: number;
@@ -780,6 +802,8 @@ interface PosOrder {
780
802
  currency: string;
781
803
  pricesIncludeTax: boolean;
782
804
  lines: PosOrderLine[];
805
+ /** pos_orders v9, ADR-077 d2; present only on a sale with coupons */
806
+ coupons?: PosOrderCoupon[];
783
807
  fees?: FeeLine[];
784
808
  shipping?: ShippingLine[];
785
809
  subtotalMinor: number;
@@ -809,9 +833,9 @@ interface PosOrder {
809
833
  * The order.create version every attempt under this `commandId` goes out at: the outbox records it before the first
810
834
  * send, and lowers it only on a downgrade (ADR-065 amendment). Absent means not sent yet (or requeued).
811
835
  */
812
- sentVersion?: 1 | 2 | 3 | 4 | 5;
836
+ sentVersion?: 1 | 2 | 3 | 4 | 5 | 6;
813
837
  /** The version first tried, before the downgrade (the order's audit). */
814
- downgradedFrom?: 1 | 2 | 3 | 4 | 5;
838
+ downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6;
815
839
  /** ADR-065: the receipt's display figures, in integer minor units of `currency` at `exponent`. */
816
840
  display?: DisplayTotals & {
817
841
  currency: string;
@@ -840,6 +864,8 @@ interface PosOrder {
840
864
  serverFailures?: PosOrderServerFailures;
841
865
  error?: CommandError;
842
866
  updatedAt: string;
867
+ /** When the till reopened this refused order as a parked sale (ADR-077 d4b). Needs attention hides it, and it stays as the record of the refusal. */
868
+ reopenedAt?: string;
843
869
  }
844
870
 
845
871
  /** RFC 9562 UUIDv7: monotonic with no arguments; stateless with an explicit timestamp or random source. */
@@ -874,6 +900,7 @@ declare class UnsupportedOrderVersionError extends Error {
874
900
  * `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
875
901
  * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
876
902
  * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
903
+ * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
877
904
  */
878
905
  declare function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt?: number, options?: {
879
906
  maxVersion?: number;
@@ -898,6 +925,10 @@ declare function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attemp
898
925
  * Version 8 adds fees, shipping, custom lines (ADR-075) and the woocommerce tax rounding (ADR-076), and changes nothing else.
899
926
  * It also stores the WooCommerce 6dp net (`netMicros`) under the woocommerce rounding (ADR-076 amendment).
900
927
  * Its migration is the identity. It is one-way like version 7.
928
+ * Version 9 adds the order's `coupons` and the receipt's `display.coupons` (ADR-077 d2), and a line's `attributes` (#495)
929
+ * and `regularUnitPriceMinor` (ADR-077 d2), and `reopenedAt`: when a refused order was reopened as a parked sale (ADR-077 d4b), and lets `sentVersion` and `downgradedFrom` be 6 (order.create version 6, ADR-077 d4), and changes nothing else.
930
+ * `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them only at version 6.
931
+ * Its migration is the identity. It is one-way like version 8.
901
932
  */
902
933
  declare const posOrderSchema: RxJsonSchema<PosOrder>;
903
934
  /**
@@ -956,38 +987,12 @@ declare function getDeviceId(storage: {
956
987
  * `stuckCommandIds` (the outbox's `OutboxState.stuck`: the store keeps failing it), newest first.
957
988
  * A warning code this till version doesn't know is not shown here (`knownWarnings`). Never changes `orders`.
958
989
  * `register_session_unknown` is not shown, because the store counts the order once its session arrives (ADR-078).
990
+ * A refused order is left out once its finalized successor is in `orders`.
959
991
  */
960
992
  declare function needsAttention(orders: PosOrder[], options?: {
961
993
  stuckCommandIds?: readonly string[];
962
994
  }): PosOrder[];
963
995
 
964
- type SaleContent = Pick<PosOrder, 'totalMinor' | 'currency' | 'lines' | 'payments'>;
965
- /**
966
- * Whether two orders carry the same money-bearing content: `totalMinor` and `currency`; each line's
967
- * `id`, `quantity` and `netMinor`, in order; each payment's `method` and `amountMinor`, in order.
968
- * An order `id` is minted once per sale (`finalizeOrder`), so the same `id` with other content is a defect.
969
- */
970
- declare function sameSale(stored: SaleContent, retried: SaleContent): boolean;
971
- /** A stored order has this order's `id` but other money-bearing content (see `sameSale`): never treated as stored. */
972
- declare class OrderContentMismatchError extends Error {
973
- readonly orderId: string;
974
- constructor(orderId: string);
975
- }
976
-
977
- type MovementType = 'paid_in' | 'paid_out' | 'no_sale';
978
- declare function normalizeAmount(raw: string): string;
979
- /** Whether the server's `decimal()` would accept this string. */
980
- declare function isServerDecimal(value: string): boolean;
981
- /**
982
- * The field the server would name in its 400, or null when it would accept the movement.
983
- * A no sale carries no amount — the sheet sends '0' — but still needs a reason.
984
- */
985
- declare function movementFieldError(input: {
986
- type: MovementType;
987
- amount: string;
988
- reason: string;
989
- }): 'amount' | 'reason' | null;
990
-
991
996
  type PosRefundStatus = 'pending' | 'applied' | 'rejected' | 'unsent';
992
997
  interface PosRefund {
993
998
  id: string;
@@ -1011,93 +1016,6 @@ declare const posRefundCollection: () => {
1011
1016
  schema: RxJsonSchema<PosRefund>;
1012
1017
  };
1013
1018
 
1014
- /**
1015
- * What the register should hold at close, per tender method: the session's cash float plus
1016
- * captured payments and cash movements — never what the cashier counts. Port provenance
1017
- * (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`.
1018
- *
1019
- * Refunds come from the till's applied `pos_refunds`, counted in the record's own `sessionId`
1020
- * (ADR-080 amendment 1), by the server's rule. WCPOS's `attributeRefunds` fallbacks (allocations,
1021
- * `refunded_amount`) are not ported: the store attributes each refund to a tender in `byMethod`.
1022
- */
1023
-
1024
- type RefundRow = Pick<PosRefund, 'id' | 'sessionId' | 'status' | 'result'>;
1025
- /** `session_id`, `kind`, `method_id`, `status` kept as WCPOS names them; money is TallyUI's integer-minor-units convention. */
1026
- type LedgerRow = {
1027
- session_id?: string | null;
1028
- kind: string;
1029
- method_id: string;
1030
- status: string;
1031
- amountMinor: number;
1032
- };
1033
- /** `type`, `voids` and `voided_by` are kept as WCPOS names them: neutral across backends. */
1034
- type Movement$1 = {
1035
- id: string;
1036
- session_id: string;
1037
- type: string;
1038
- amountMinor: number;
1039
- voided_by?: string | null;
1040
- voids?: string | null;
1041
- };
1042
- /**
1043
- * Expected totals per tender method: the counted float, plus every captured ledger row for the
1044
- * session (grouped under `cash` for cash rows, else `method_id`), plus its non-voided
1045
- * paid-in/paid-out movements, minus its applied refunds.
1046
- *
1047
- * A movement is excluded when its own `voided_by` is set, or when a `type: 'void'` row's
1048
- * `voids` names its id; the `void` row itself carries no amount of its own.
1049
- */
1050
- declare function deriveExpected({ session, movements, ledgerRowsBySession, refunds, }: {
1051
- session: {
1052
- id: string;
1053
- countedFloatMinor: number;
1054
- };
1055
- movements: readonly Movement$1[];
1056
- ledgerRowsBySession: readonly LedgerRow[];
1057
- refunds?: readonly RefundRow[];
1058
- }): Record<string, number>;
1059
-
1060
- /**
1061
- * The pure maths behind a register count: variance against the expected float, a display
1062
- * string for it, and the denomination arithmetic the counting keypad uses. Port provenance
1063
- * (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`.
1064
- *
1065
- * Money here is TallyUI's convention: integer minor units. Everywhere WCPOS assumed two
1066
- * decimals, these take the currency's `exponent` instead — 0 for JPY, 3 for KWD — except
1067
- * `validAmount`, which like WCPOS still takes the cashier's typed text.
1068
- */
1069
- /**
1070
- * Parses a decimal string the cashier typed into integer minor units at `exponent` decimal
1071
- * places, without rounding. Returns `NaN` when the string carries more precision than the
1072
- * currency allows, so a safe-integer check on the result also rejects it.
1073
- */
1074
- declare function parseMinor(text: string, exponent: number): number;
1075
- declare const validAmount: (value: string, exponent: number) => boolean;
1076
- /** Counted minus expected, both already in minor units. */
1077
- declare const countVariance: (countedMinor: number, expectedMinor: number) => number;
1078
- /** Whether the variance exceeds the store's configured threshold (minor units; none means never). */
1079
- declare const overThreshold: (variance: number, thresholdMinor?: number | null) => boolean;
1080
- /**
1081
- * Whether a close's cash count needs a manager's approval: its cash variance against the expected
1082
- * cash is over the threshold. The one definition `RegisterCount` and `useRegisterSession`'s
1083
- * `closeSession` gate share (ADR-032).
1084
- */
1085
- declare const closeNeedsApproval: (countedCashMinor: number, expectedCashMinor: number, thresholdMinor?: number | null) => boolean;
1086
- /** Sums denomination face values (already minor units) by piece count. */
1087
- declare const denominationTotal: (pieces: Record<number, number>) => number;
1088
- /**
1089
- * The variance line under the count: exact, short or over. `format` takes a major-unit
1090
- * amount, as an app's currency formatter expects, so `exponent` converts `variance` back for
1091
- * it; `t` supplies the translated words for the `register.exact`/`register.short`/
1092
- * `register.over` keys. Both are the app's own — neutral here.
1093
- *
1094
- * The direction lives in the word, not a sign (the Front desk, 2026-09-28): a signed amount
1095
- * next to "short" read as a double negative, so the amount here is always its absolute value.
1096
- */
1097
- declare function varianceText(variance: number, exponent: number, format: (value: number) => string, t: (key: string) => string): string;
1098
-
1099
- declare const denominations: Record<string, number[]>;
1100
-
1101
1019
  /**
1102
1020
  * The register's local collections (ADR-032): sessions, cash movements and closures. Port
1103
1021
  * provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`, where they are at versions 1, 0
@@ -1201,24 +1119,6 @@ declare function registerSessionCollection(): never;
1201
1119
  declare const cashMovementSchema: RxJsonSchema<CashMovement>;
1202
1120
  declare const closureSchema: RxJsonSchema<Closure>;
1203
1121
 
1204
- /** `addRegisterSessionCollection`'s logger: attach a sink to see dropped status writes during close. */
1205
- declare const registerSessionsLogger: Logger;
1206
- /** How long a close waits for the open; see `openMigratedCollection` for the cancellation mechanism. */
1207
- declare const REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS = 10000;
1208
- /** The database is closing; no session is lost. Reopen the database and call the opener again. */
1209
- declare class RegisterSessionOpenClosedError extends Error {
1210
- readonly databaseName: string;
1211
- readonly code = "REGISTER_SESSION_OPEN_CLOSED";
1212
- constructor(databaseName: string);
1213
- }
1214
- /**
1215
- * Adds `register_sessions` and resolves once no older session is left to migrate; the register
1216
- * document, a local document, is kept. On DM4 it rejects after migration stops and closes the collection.
1217
- * A closing database rejects with `RegisterSessionOpenClosedError`; `closeWaitMs` is for tests only.
1218
- * See `openMigratedCollection` for the migration and close mechanism.
1219
- */
1220
- declare function addRegisterSessionCollection(db: RxDatabase, closeWaitMs?: number): Promise<RxCollection<RegisterSession>>;
1221
-
1222
1122
  type RegisterHost = RxLocalDocumentMutation<any>;
1223
1123
  type RegisterCounters = {
1224
1124
  last_closure_number: number;
@@ -1395,7 +1295,7 @@ declare function voidMovement(sessions: RegisterSessionCollection, movements: Ca
1395
1295
  * same snapshot and number, and its period reaches the perpetual totals exactly once.
1396
1296
  * Only a closed session (`closed` with `closed_at_gmt`) has a closure, and a closed session is
1397
1297
  * final, so its existing closure is returned as it was frozen. Orders the server rejected still
1398
- * count in the drawer, because the cash was taken.
1298
+ * count in the drawer, because the cash was taken, until a finalized successor carries their payments (ADR-077 R5 amended).
1399
1299
  * A refund still pending at close is not counted, and the Z lists it.
1400
1300
  */
1401
1301
  declare function writeClosure({ closures, register, storeKey, session, counted, otherTenders, movements, orders, refunds, tillExpected, labels, resolveCashierName, softwareVersion, timezone, }: {
@@ -1425,6 +1325,160 @@ declare function writeClosure({ closures, register, storeKey, session, counted,
1425
1325
  timezone?: string;
1426
1326
  }): Promise<rxdb.RxDocument<Closure, {}, unknown>>;
1427
1327
 
1328
+ declare const REOPENABLE_CODES: readonly string[];
1329
+ type ReopenRefusal = 'not_found' | 'not_rejected' | 'code_not_reopenable' | 'already_replaced' | 'session_closed';
1330
+ declare class ReopenRefusedOrderError extends Error {
1331
+ readonly orderId: string;
1332
+ readonly reason: ReopenRefusal;
1333
+ constructor(orderId: string, reason: ReopenRefusal);
1334
+ }
1335
+ declare function reopenRefusedOrder(orderId: string, deps: {
1336
+ orders: RxCollection<PosOrder>;
1337
+ drafts: RxCollection;
1338
+ sessions: RegisterSessionCollection;
1339
+ taxContext: TaxContext;
1340
+ /** The product's tax class from the catalogue (ProductTraits.getTaxClass); undefined falls back to 'standard'. */
1341
+ taxClassOf?: (productId: string, variantId?: string) => string | undefined;
1342
+ now?: () => Date;
1343
+ }): Promise<string>;
1344
+
1345
+ /** Only tells that a reopen was started: a UI hint with no accounting meaning. */
1346
+ declare function isReopened(order: Pick<PosOrder, 'syncStatus' | 'reopenedAt'>): boolean;
1347
+ /** Payments count on the successor, so the refused order counts nowhere (ADR-077 R5 amended). Only this list is considered. */
1348
+ declare function replacedOrderIds(orders: readonly Pick<PosOrder, 'id' | 'saleId' | 'syncStatus'>[]): Set<string>;
1349
+
1350
+ type SaleContent = Pick<PosOrder, 'totalMinor' | 'currency' | 'lines' | 'payments'>;
1351
+ /**
1352
+ * Whether two orders carry the same money-bearing content: `totalMinor` and `currency`; each line's
1353
+ * `id`, `quantity` and `netMinor`, in order; each payment's `method` and `amountMinor`, in order.
1354
+ * An order `id` is minted once per sale (`finalizeOrder`), so the same `id` with other content is a defect.
1355
+ */
1356
+ declare function sameSale(stored: SaleContent, retried: SaleContent): boolean;
1357
+ /** A stored order has this order's `id` but other money-bearing content (see `sameSale`): never treated as stored. */
1358
+ declare class OrderContentMismatchError extends Error {
1359
+ readonly orderId: string;
1360
+ constructor(orderId: string);
1361
+ }
1362
+
1363
+ type MovementType = 'paid_in' | 'paid_out' | 'no_sale';
1364
+ declare function normalizeAmount(raw: string): string;
1365
+ /** Whether the server's `decimal()` would accept this string. */
1366
+ declare function isServerDecimal(value: string): boolean;
1367
+ /**
1368
+ * The field the server would name in its 400, or null when it would accept the movement.
1369
+ * A no sale carries no amount — the sheet sends '0' — but still needs a reason.
1370
+ */
1371
+ declare function movementFieldError(input: {
1372
+ type: MovementType;
1373
+ amount: string;
1374
+ reason: string;
1375
+ }): 'amount' | 'reason' | null;
1376
+
1377
+ /**
1378
+ * What the register should hold at close, per tender method: the session's cash float plus
1379
+ * captured payments and cash movements — never what the cashier counts. Port provenance
1380
+ * (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`.
1381
+ *
1382
+ * Refunds come from the till's applied `pos_refunds`, counted in the record's own `sessionId`
1383
+ * (ADR-080 amendment 1), by the server's rule. WCPOS's `attributeRefunds` fallbacks (allocations,
1384
+ * `refunded_amount`) are not ported: the store attributes each refund to a tender in `byMethod`.
1385
+ */
1386
+
1387
+ type RefundRow = Pick<PosRefund, 'id' | 'sessionId' | 'status' | 'result'>;
1388
+ /** `session_id`, `kind`, `method_id`, `status` kept as WCPOS names them; money is TallyUI's integer-minor-units convention. */
1389
+ type LedgerRow = {
1390
+ session_id?: string | null;
1391
+ kind: string;
1392
+ method_id: string;
1393
+ status: string;
1394
+ amountMinor: number;
1395
+ };
1396
+ /** `type`, `voids` and `voided_by` are kept as WCPOS names them: neutral across backends. */
1397
+ type Movement$1 = {
1398
+ id: string;
1399
+ session_id: string;
1400
+ type: string;
1401
+ amountMinor: number;
1402
+ voided_by?: string | null;
1403
+ voids?: string | null;
1404
+ };
1405
+ /**
1406
+ * Expected totals per tender method: the counted float, plus every captured ledger row for the
1407
+ * session (grouped under `cash` for cash rows, else `method_id`), plus its non-voided
1408
+ * paid-in/paid-out movements, minus its applied refunds.
1409
+ *
1410
+ * A movement is excluded when its own `voided_by` is set, or when a `type: 'void'` row's
1411
+ * `voids` names its id; the `void` row itself carries no amount of its own.
1412
+ */
1413
+ declare function deriveExpected({ session, movements, ledgerRowsBySession, refunds, }: {
1414
+ session: {
1415
+ id: string;
1416
+ countedFloatMinor: number;
1417
+ };
1418
+ movements: readonly Movement$1[];
1419
+ ledgerRowsBySession: readonly LedgerRow[];
1420
+ refunds?: readonly RefundRow[];
1421
+ }): Record<string, number>;
1422
+
1423
+ /**
1424
+ * The pure maths behind a register count: variance against the expected float, a display
1425
+ * string for it, and the denomination arithmetic the counting keypad uses. Port provenance
1426
+ * (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`.
1427
+ *
1428
+ * Money here is TallyUI's convention: integer minor units. Everywhere WCPOS assumed two
1429
+ * decimals, these take the currency's `exponent` instead — 0 for JPY, 3 for KWD — except
1430
+ * `validAmount`, which like WCPOS still takes the cashier's typed text.
1431
+ */
1432
+ /**
1433
+ * Parses a decimal string the cashier typed into integer minor units at `exponent` decimal
1434
+ * places, without rounding. Returns `NaN` when the string carries more precision than the
1435
+ * currency allows, so a safe-integer check on the result also rejects it.
1436
+ */
1437
+ declare function parseMinor(text: string, exponent: number): number;
1438
+ declare const validAmount: (value: string, exponent: number) => boolean;
1439
+ /** Counted minus expected, both already in minor units. */
1440
+ declare const countVariance: (countedMinor: number, expectedMinor: number) => number;
1441
+ /** Whether the variance exceeds the store's configured threshold (minor units; none means never). */
1442
+ declare const overThreshold: (variance: number, thresholdMinor?: number | null) => boolean;
1443
+ /**
1444
+ * Whether a close's cash count needs a manager's approval: its cash variance against the expected
1445
+ * cash is over the threshold. The one definition `RegisterCount` and `useRegisterSession`'s
1446
+ * `closeSession` gate share (ADR-032).
1447
+ */
1448
+ declare const closeNeedsApproval: (countedCashMinor: number, expectedCashMinor: number, thresholdMinor?: number | null) => boolean;
1449
+ /** Sums denomination face values (already minor units) by piece count. */
1450
+ declare const denominationTotal: (pieces: Record<number, number>) => number;
1451
+ /**
1452
+ * The variance line under the count: exact, short or over. `format` takes a major-unit
1453
+ * amount, as an app's currency formatter expects, so `exponent` converts `variance` back for
1454
+ * it; `t` supplies the translated words for the `register.exact`/`register.short`/
1455
+ * `register.over` keys. Both are the app's own — neutral here.
1456
+ *
1457
+ * The direction lives in the word, not a sign (the Front desk, 2026-09-28): a signed amount
1458
+ * next to "short" read as a double negative, so the amount here is always its absolute value.
1459
+ */
1460
+ declare function varianceText(variance: number, exponent: number, format: (value: number) => string, t: (key: string) => string): string;
1461
+
1462
+ declare const denominations: Record<string, number[]>;
1463
+
1464
+ /** `addRegisterSessionCollection`'s logger: attach a sink to see dropped status writes during close. */
1465
+ declare const registerSessionsLogger: Logger;
1466
+ /** How long a close waits for the open; see `openMigratedCollection` for the cancellation mechanism. */
1467
+ declare const REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS = 10000;
1468
+ /** The database is closing; no session is lost. Reopen the database and call the opener again. */
1469
+ declare class RegisterSessionOpenClosedError extends Error {
1470
+ readonly databaseName: string;
1471
+ readonly code = "REGISTER_SESSION_OPEN_CLOSED";
1472
+ constructor(databaseName: string);
1473
+ }
1474
+ /**
1475
+ * Adds `register_sessions` and resolves once no older session is left to migrate; the register
1476
+ * document, a local document, is kept. On DM4 it rejects after migration stops and closes the collection.
1477
+ * A closing database rejects with `RegisterSessionOpenClosedError`; `closeWaitMs` is for tests only.
1478
+ * See `openMigratedCollection` for the migration and close mechanism.
1479
+ */
1480
+ declare function addRegisterSessionCollection(db: RxDatabase, closeWaitMs?: number): Promise<RxCollection<RegisterSession>>;
1481
+
1428
1482
  /**
1429
1483
  * Corrections layered onto a closure's recorded figures (ADR-032): late sales, late cash
1430
1484
  * movements and recounts, applied in order and deduplicated by id. Port provenance (ADR-032
@@ -2100,6 +2154,45 @@ declare function findEntryByCode<Doc>(entries: CatalogueEntry<Doc>[], code: stri
2100
2154
  /** Display the resolved price in the requested currency. */
2101
2155
  declare function variantPriceLabel(variant: VariantSummary, currency: string, locale?: string): string | undefined;
2102
2156
 
2157
+ /** applyCoupon's refusal when the store cannot take coupons (ADR-077 R2, R3). */
2158
+ declare const COUPONS_UNSUPPORTED = "This store's plugin does not support coupons yet";
2159
+ /** What a platform's discount codes see of the sale (ADR-077 amendment 3). */
2160
+ interface SaleDiscountState<Accepted> {
2161
+ /** The sale as it stands. */
2162
+ order: Order;
2163
+ /** The codes on the sale, in the order applied, each with what `find` gave for it: a copy taken for this call, so codes accepted later do not appear in it. */
2164
+ accepted: ReadonlyMap<string, Accepted>;
2165
+ /** The categories the sale knows for each numeric product id; `beforeResume` may add to it. */
2166
+ categories: Map<number, {
2167
+ id: number;
2168
+ }[]>;
2169
+ settings: Pick<StoreSettings, 'calcDiscountsSequentially'>;
2170
+ }
2171
+ /**
2172
+ * A platform's discount codes, as `useSale` takes them (ADR-077 amendment 3; Paul, 2026-10-07: each platform its own way).
2173
+ * The platform's side decides what a code is, which rules it must pass, how it reaches the order and how a refusal is worded;
2174
+ * `useSale` normalizes the code, keeps the accepted codes in order, and refuses a code whose sale changed during `find`.
2175
+ */
2176
+ interface SaleDiscountCodes<Accepted = unknown> {
2177
+ /** Whether this store can take codes in this tax context; `useSale` also requires `capabilities.coupons` and `orderCreate >= 6`. */
2178
+ supports(store: {
2179
+ capabilities?: ServerCapabilities;
2180
+ rounding?: TaxRounding;
2181
+ }): boolean;
2182
+ /** Looks up a trimmed, lower-case code: what was found, or the refusal to show. */
2183
+ find(code: string, sale: SaleDiscountState<Accepted>): Promise<{
2184
+ found: Accepted;
2185
+ } | {
2186
+ refusal: string;
2187
+ }>;
2188
+ /** Checks a found code against the sale; the refusal to show, or null when it may be applied. */
2189
+ check(code: string, found: Accepted, sale: SaleDiscountState<Accepted>): string | null;
2190
+ /** Puts `sale.accepted`'s codes, in order, on the builder; throws an Error whose message is the refusal. */
2191
+ apply(builder: OrderBuilder, sale: SaleDiscountState<Accepted>): void;
2192
+ /** Called once, before a parked sale's codes are looked up again by `resume()`. */
2193
+ beforeResume?(sale: SaleDiscountState<Accepted>): Promise<void>;
2194
+ }
2195
+
2103
2196
  /** Logs a throw from onSaleCompleted for a confirmed pending completion newSale() has abandoned (Continue): nothing else would ever surface it. */
2104
2197
  declare const saleLogger: Logger;
2105
2198
  type SaleStage = {
@@ -2117,10 +2210,12 @@ declare const DISCOUNTS_UNSUPPORTED = "finalize: discounts are not supported by
2117
2210
  /** Every sale change refuses with this while a completion is pending (see `complete()`). */
2118
2211
  declare const SALE_SAVING = "This sale is being saved. Retry to finish it.";
2119
2212
  /** Call under a `TaxProvider`: its tax context and the settings' currency price every sale. */
2120
- declare function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
2213
+ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscountsSequentially'>, opts: {
2121
2214
  registerId: string;
2122
2215
  cashierRef: string;
2123
2216
  capabilities?: ServerCapabilities;
2217
+ /** The platform's discount codes (ADR-077 amendment 3), e.g. woocommerceDiscountCodes.createDiscountCodes(source); without them, applyCoupon refuses with COUPONS_UNSUPPORTED. */
2218
+ discountCodes?: SaleDiscountCodes<any>;
2124
2219
  /** Where `park()` keeps parked carts; create it with `orderDraftSchema` */
2125
2220
  drafts?: RxCollection;
2126
2221
  /**
@@ -2200,6 +2295,10 @@ declare function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
2200
2295
  /** A line's discount, or the order's without a line; returns the refusal to show, or null once applied. */
2201
2296
  applyDiscount(lineId: string | null, discount: Discount): string | null;
2202
2297
  removeDiscount(id: string): void;
2298
+ /** ADR-077: looks up, checks and applies a discount code through the platform's discount codes; resolves to the refusal to show, or null once applied. */
2299
+ applyCoupon(code: string): Promise<string | null>;
2300
+ /** Removes an applied coupon; returns the refusal to show, or null once removed. */
2301
+ removeCoupon(code: string): string | null;
2203
2302
  /** the picked customer reaches the server as order.create v3's customer.customerId */
2204
2303
  setCustomer(customer: CustomerSummary | null): void;
2205
2304
  /**
@@ -2271,6 +2370,56 @@ declare function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
2271
2370
  continueSale(): void;
2272
2371
  };
2273
2372
 
2373
+ /** A WooCommerce coupon as the sale needs it: the engine's input and the connector's numeric id. */
2374
+ type SaleCoupon = woocommerceCoupons.CouponInput & {
2375
+ id: number;
2376
+ };
2377
+ /** Where the sale finds coupons (ADR-077 amendment 2); the app builds it over the till's coupons collection. */
2378
+ interface SaleCouponSource {
2379
+ /** The published coupon with this lower-case code, its usage already counting the till's own unsent orders; null when none. */
2380
+ find(code: string): Promise<SaleCoupon | null>;
2381
+ /** The WooCommerce category ids of each product asked for; a product it does not know is left out. */
2382
+ productCategories(productIds: readonly number[]): Promise<ReadonlyMap<number, readonly {
2383
+ id: number;
2384
+ }[]>>;
2385
+ }
2386
+ /** The cashier-facing reason for a validator refusal. */
2387
+ declare function couponRefusal(code: string, rejection: woocommerceCoupons.CouponRejection): string;
2388
+
2389
+ /** WooCommerce coupons as the sale's discount codes (ADR-077): the source's coupons, checked by woocommerceCoupons.validateCoupon. */
2390
+ declare function createDiscountCodes(source: SaleCouponSource): SaleDiscountCodes<SaleCoupon>;
2391
+
2392
+ declare function createSaleCouponSource(deps: {
2393
+ coupons: RxCollection;
2394
+ products: RxCollection;
2395
+ orders: RxCollection<PosOrder>;
2396
+ now?: () => number;
2397
+ }): SaleCouponSource;
2398
+
2399
+ declare function startCouponUsageRefetch(deps: {
2400
+ orders: RxCollection<PosOrder>;
2401
+ coupons: RxCollection;
2402
+ enqueue: (entries: Array<{
2403
+ key: string;
2404
+ local: unknown;
2405
+ refreshOnly: true;
2406
+ }>) => void;
2407
+ reSync: () => void;
2408
+ now?: () => number;
2409
+ }): {
2410
+ stop(): void;
2411
+ };
2412
+
2413
+ type index_SaleCoupon = SaleCoupon;
2414
+ type index_SaleCouponSource = SaleCouponSource;
2415
+ declare const index_couponRefusal: typeof couponRefusal;
2416
+ declare const index_createDiscountCodes: typeof createDiscountCodes;
2417
+ declare const index_createSaleCouponSource: typeof createSaleCouponSource;
2418
+ declare const index_startCouponUsageRefetch: typeof startCouponUsageRefetch;
2419
+ declare namespace index {
2420
+ export { type index_SaleCoupon as SaleCoupon, type index_SaleCouponSource as SaleCouponSource, index_couponRefusal as couponRefusal, index_createDiscountCodes as createDiscountCodes, index_createSaleCouponSource as createSaleCouponSource, index_startCouponUsageRefetch as startCouponUsageRefetch };
2421
+ }
2422
+
2274
2423
  declare class CartError extends Error {
2275
2424
  }
2276
2425
  declare function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry<Doc>, traits: ProductTraits<Doc>, currency: string): string;
@@ -2359,6 +2508,8 @@ interface BackendNotFound {
2359
2508
  }
2360
2509
  declare function createBackendNotFound(): BackendNotFound;
2361
2510
 
2511
+ /** Whether the outbox resends a rejection with this code. */
2512
+ declare function isRequeueable(code: string | undefined): boolean;
2362
2513
  interface OrderOutboxOptions {
2363
2514
  collection: RxCollection<PosOrder>;
2364
2515
  transport: CommandTransport<OrderCreateEnvelope>;
@@ -2728,4 +2879,4 @@ declare function tenderVoidCollection(): {
2728
2879
  readonly schema: RxJsonSchema<TenderVoid>;
2729
2880
  };
2730
2881
 
2731
- export { type Actor, type AddLineInput, type AppliedDiscount, type BackendNotFound, type BasketLine, CartError, type CashMovement, type CashMovementCollection, type CatalogueEntry, type CatalogueGridColumns, type CatalogueView, type CatalogueViewAction, type CatalogueViewState, type ChargeInput, type ChargeLine, type Closure, type ClosureCollection, type ClosureContext, type ClosureScope, type CommandTransport, type Correction, CurrencyProvider, type CurrencyProviderProps, type CustomerSummary, DEFAULT_CATALOGUE_VIEW_STATE, DISCOUNTS_UNSUPPORTED, type Discount, type DisplayLine, type DisplayTotals, type FeeLine, type FinalizeOptions, type HttpTransportOptions, type LedgerRow, type LineItem, type LineTaxLine, type LogEntry, type LogLevel, type LogSink, type Logger, MAX_TENDER_MINOR, MICROS_PER_MINOR, type Movement$1 as Movement, type MovementType, 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 OutboxState, PRODUCT_SORT_FIELDS, type ParkedOrderSummary, type Payment, type PaymentMethod, type PaymentTransport, type PlanLeg, type PosOrder, type PosOrderLine, type PosOrderLocalWarning, PosOrderOpenClosedError, type PosOrderPayment, type PosOrderServerFailures, type PosOrderSyncStatus, type PosRefund, type PosRefundCollection, type PosRefundStatus, type ProductSort, type ProductSortValue, RECEIPT_SCHEMA_VERSION, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS, type RateTaxLine, type ReceiptConfig, type ReceiptData, type ReceiptFiscal, type ReceiptLineItem, type ReceiptRegister, type ReceiptSoftware, type RecordedFigures, RefundAnswerPendingError, 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, type RegisterSession, RegisterSessionAlreadyOpenError, RegisterSessionClosedError, type RegisterSessionCollection, RegisterSessionConflictError, RegisterSessionOpenClosedError, RegisterSessionRequiredError, type RegisterStore, RegisterTakeOverError, RegisterTenderInProgressError, type Repository, type ResolveStoreSettingsOptions, SALE_SAVING, type SaleStage, type SentOrder, type ShippingLine, type SplitTab, type StoreSettingsResolution, type StoreSettingsState, TAX_ROUNDING_MIXED_NOTE, type TaxContext, type TaxLineInput, TaxProvider, type TaxProviderProps, type TaxRateMap, type TenderAction, type TenderKey, type TenderLineId, type TenderPlan, type TenderState, type TenderView, type TenderVoid, type TransportOutcome, UnsupportedOrderVersionError, type UseOrderOutboxOptions, type UseOrderOutboxResult, type UseRegisterOutboxOptions, type UseRegisterOutboxResult, type UseRegisterSessionOptions, abandonSession, activePlan, addEntryToCart, addPosOrderCollection, addRegisterSessionCollection, adoptRegisterResults, advancePerpetual, allocateOrderDiscount, appliedMinor, backToSelling, bindRegister, buildClosureDocument, buildReceiptData, buildXReportDocument, callbackSink, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureCommand, closureSchema, computeOrderTax, consoleSink, countVariance, createBackendNotFound, createHttpCommandTransport, createLogger, createOrderBuilder, createOrderManager, createOrderOutbox, createRegisterOutbox, createRepository, denominationTotal, denominations, deriveExpected, deriveSettled, ensureRegister, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, formatClosureDate, getBoundRegisterId, getDeviceId, inCategory, initTenderState, initialTenderState, isKnownSessionStatus, isServerDecimal, labelKeys, listCategories, minorToDecimal, mintClosureNumber, mintUuid, movementCommand, movementFieldError, needsAttention, nextSaleCounter, normalizeAmount, normalizeCatalogueViewState, observeRegister$, openSession, openSessionSelector, orderDraftSchema, outboxLogger, overThreshold, parkedOrderSummaries$, parseMinor, planLegs, posOrderCollection, posOrderSchema, posOrdersLogger, posRefundCollection, posRefundSchema, productCategories, productSortValue, quickTenderedAmounts, ratePpmFromPercent, readBoundRegister, readRegister, reconcileRegisterCommands, recordMovement, recordRegisterFact, registerCommandCollection, registerCommandSchema, registerCommandsLogger, registerFactsLogger, registerSessionCollection, registerSessionSchema, registerSessionsLogger, requireOpenSession, resolveGridColumns, resolveStoreSettings, restoreOrderDraft, roundMicrosToMinor, saleLogger, sameSale, searchProducts, selectClosureRows, sendOrderRefund, sessionOpenCommand, sessionTransitionCommand, sortProducts, stampSession, startCounting, stockOverlay$, stockOverlayAsOf$, submitOrderRefund, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderVoidCollection, tenderVoidSchema, toOrderCreateEnvelope, unbindRegister, useCurrencyCode, useCurrencyFormatter, useOrderOutbox, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, withPricingContext, writeClosure, writeOrderDraft };
2882
+ export { type Actor, type AddLineInput, type AppliedDiscount, type BackendNotFound, type BasketLine, COUPONS_UNSUPPORTED, CartError, type CashMovement, type CashMovementCollection, type CatalogueEntry, type CatalogueGridColumns, type CatalogueView, type CatalogueViewAction, type CatalogueViewState, type ChargeInput, type ChargeLine, type Closure, type ClosureCollection, type ClosureContext, type ClosureScope, type CommandTransport, type Correction, CurrencyProvider, type CurrencyProviderProps, type CustomerSummary, DEFAULT_CATALOGUE_VIEW_STATE, DISCOUNTS_UNSUPPORTED, type Discount, type DisplayLine, type DisplayTotals, type FeeLine, type FinalizeOptions, type HttpTransportOptions, type LedgerRow, type LineItem, type LineTaxLine, type LogEntry, type LogLevel, type LogSink, type Logger, MAX_TENDER_MINOR, MICROS_PER_MINOR, type Movement$1 as Movement, type MovementType, 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 OutboxState, PRODUCT_SORT_FIELDS, type ParkedOrderSummary, type Payment, type PaymentMethod, 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 ProductSort, type ProductSortValue, RECEIPT_SCHEMA_VERSION, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS, REOPENABLE_CODES, type RateTaxLine, type ReceiptConfig, type ReceiptData, type ReceiptFiscal, type ReceiptLineItem, type ReceiptRegister, type ReceiptSoftware, type RecordedFigures, RefundAnswerPendingError, 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, type RegisterSession, RegisterSessionAlreadyOpenError, RegisterSessionClosedError, type RegisterSessionCollection, RegisterSessionConflictError, RegisterSessionOpenClosedError, RegisterSessionRequiredError, type RegisterStore, RegisterTakeOverError, RegisterTenderInProgressError, type ReopenRefusal, ReopenRefusedOrderError, type Repository, type ResolveStoreSettingsOptions, SALE_SAVING, type SaleDiscountCodes, type SaleDiscountState, type SaleStage, type SentOrder, type ShippingLine, type SplitTab, type StoreSettingsResolution, type StoreSettingsState, TAX_ROUNDING_MIXED_NOTE, type TaxContext, type TaxLineInput, TaxProvider, type TaxProviderProps, type TaxRateMap, type TenderAction, type TenderKey, type TenderLineId, type TenderPlan, type TenderState, type TenderView, type TenderVoid, type TransportOutcome, UnsupportedOrderVersionError, type UseOrderOutboxOptions, type UseOrderOutboxResult, type UseRegisterOutboxOptions, type UseRegisterOutboxResult, type UseRegisterSessionOptions, abandonSession, activePlan, addEntryToCart, addPosOrderCollection, addRegisterSessionCollection, adoptRegisterResults, advancePerpetual, allocateOrderDiscount, appliedMinor, backToSelling, bindRegister, buildClosureDocument, buildReceiptData, buildXReportDocument, callbackSink, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureCommand, closureSchema, computeOrderTax, consoleSink, countVariance, createBackendNotFound, createHttpCommandTransport, createLogger, createOrderBuilder, createOrderManager, createOrderOutbox, createRegisterOutbox, createRepository, denominationTotal, denominations, deriveExpected, deriveSettled, ensureRegister, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, formatClosureDate, getBoundRegisterId, getDeviceId, inCategory, initTenderState, initialTenderState, isKnownSessionStatus, isReopened, isRequeueable, isServerDecimal, labelKeys, listCategories, minorToDecimal, mintClosureNumber, mintUuid, movementCommand, movementFieldError, needsAttention, nextSaleCounter, normalizeAmount, normalizeCatalogueViewState, observeRegister$, openSession, openSessionSelector, orderDraftSchema, outboxLogger, overThreshold, parkedOrderSummaries$, parseMinor, planLegs, posOrderCollection, posOrderSchema, posOrdersLogger, posRefundCollection, posRefundSchema, productCategories, productSortValue, quickTenderedAmounts, ratePpmFromPercent, readBoundRegister, readRegister, reconcileRegisterCommands, recordMovement, recordRegisterFact, registerCommandCollection, registerCommandSchema, registerCommandsLogger, registerFactsLogger, registerSessionCollection, registerSessionSchema, registerSessionsLogger, reopenRefusedOrder, replacedOrderIds, requireOpenSession, resolveGridColumns, resolveStoreSettings, restoreOrderDraft, roundMicrosToMinor, saleLogger, sameSale, searchProducts, selectClosureRows, sendOrderRefund, sessionOpenCommand, sessionTransitionCommand, sortProducts, stampSession, startCounting, stockOverlay$, stockOverlayAsOf$, submitOrderRefund, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderVoidCollection, tenderVoidSchema, toOrderCreateEnvelope, unbindRegister, useCurrencyCode, useCurrencyFormatter, useOrderOutbox, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, withPricingContext, index as woocommerceDiscountCodes, writeClosure, writeOrderDraft };