@tallyui/pos 3.9.2 → 3.10.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
  }
@@ -339,6 +340,8 @@ interface LineItem {
339
340
  sku: string;
340
341
  imageUrl?: string;
341
342
  unitPriceMinor: number;
343
+ /** The catalogue's regular unit price, in the line's own tax mode like unitPriceMinor; absent on custom lines (ADR-077 d3). */
344
+ regularUnitPriceMinor?: number;
342
345
  quantity: number;
343
346
  taxLines: LineTaxLine[];
344
347
  discounts: AppliedDiscount[];
@@ -420,6 +423,7 @@ interface AddLineInput {
420
423
  unitPrice: Money & {
421
424
  taxInclusive?: boolean;
422
425
  };
426
+ regularUnitPriceMinor?: number;
423
427
  quantity?: number;
424
428
  taxRates?: Array<{
425
429
  code?: string;
@@ -430,6 +434,7 @@ interface AddLineInput {
430
434
 
431
435
  interface OrderCouponContext {
432
436
  configs: ReadonlyMap<string, woocommerceCoupons.CouponDiscountConfig>;
437
+ couponIds: ReadonlyMap<string, string>;
433
438
  productCategories: ReadonlyMap<number, {
434
439
  id: number;
435
440
  }[]>;
@@ -469,8 +474,8 @@ interface OrderBuilder {
469
474
  removePayment(paymentId: string): void;
470
475
  setCustomer(customer: CustomerSummary | null): void;
471
476
  setNote(note: string): void;
472
- /** Replaces the coupon codes with their trimmed, lower-case, deduplicated list. */
473
- setCoupons(codes: readonly string[]): void;
477
+ /** Replaces the coupon codes with their trimmed, lower-case, deduplicated list; a given context replaces the builder's coupon context. */
478
+ setCoupons(codes: readonly string[], context?: OrderCouponContext): void;
474
479
  clear(): void;
475
480
  getSnapshot(): Order;
476
481
  }
@@ -742,6 +747,13 @@ interface PosOrderServerFailures {
742
747
  /** The order failed when sent alone (as a probe or while isolated), so it is retried alone. */
743
748
  isolated: boolean;
744
749
  }
750
+ /** A WooCommerce coupon on the stored order (ADR-077 d2): its figures are the order builder's coupon replay. */
751
+ interface PosOrderCoupon {
752
+ code: string;
753
+ couponId: string;
754
+ discountMinor: number;
755
+ discountTaxMinor: number;
756
+ }
745
757
  interface PosOrderLine {
746
758
  id: string;
747
759
  productId: string;
@@ -752,6 +764,10 @@ interface PosOrderLine {
752
764
  sku: string;
753
765
  quantity: number;
754
766
  unitPriceMinor: number;
767
+ /** The chosen variation attributes, name to value (pos_orders v9, #495). */
768
+ attributes?: Record<string, string>;
769
+ /** The catalogue's regular unit price, in the line's own tax mode like `unitPriceMinor` (pos_orders v9, ADR-077 d2). */
770
+ regularUnitPriceMinor?: number;
755
771
  /** Line discounts plus the allocated order-discount share, in the line's own tax mode (ADR-062). */
756
772
  discountMinor: number;
757
773
  netMinor: number;
@@ -780,6 +796,8 @@ interface PosOrder {
780
796
  currency: string;
781
797
  pricesIncludeTax: boolean;
782
798
  lines: PosOrderLine[];
799
+ /** pos_orders v9, ADR-077 d2; present only on a sale with coupons */
800
+ coupons?: PosOrderCoupon[];
783
801
  fees?: FeeLine[];
784
802
  shipping?: ShippingLine[];
785
803
  subtotalMinor: number;
@@ -809,9 +827,9 @@ interface PosOrder {
809
827
  * The order.create version every attempt under this `commandId` goes out at: the outbox records it before the first
810
828
  * send, and lowers it only on a downgrade (ADR-065 amendment). Absent means not sent yet (or requeued).
811
829
  */
812
- sentVersion?: 1 | 2 | 3 | 4 | 5;
830
+ sentVersion?: 1 | 2 | 3 | 4 | 5 | 6;
813
831
  /** The version first tried, before the downgrade (the order's audit). */
814
- downgradedFrom?: 1 | 2 | 3 | 4 | 5;
832
+ downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6;
815
833
  /** ADR-065: the receipt's display figures, in integer minor units of `currency` at `exponent`. */
816
834
  display?: DisplayTotals & {
817
835
  currency: string;
@@ -840,6 +858,8 @@ interface PosOrder {
840
858
  serverFailures?: PosOrderServerFailures;
841
859
  error?: CommandError;
842
860
  updatedAt: string;
861
+ /** 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. */
862
+ reopenedAt?: string;
843
863
  }
844
864
 
845
865
  /** RFC 9562 UUIDv7: monotonic with no arguments; stateless with an explicit timestamp or random source. */
@@ -874,6 +894,7 @@ declare class UnsupportedOrderVersionError extends Error {
874
894
  * `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
875
895
  * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
876
896
  * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
897
+ * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
877
898
  */
878
899
  declare function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt?: number, options?: {
879
900
  maxVersion?: number;
@@ -898,6 +919,9 @@ declare function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attemp
898
919
  * Version 8 adds fees, shipping, custom lines (ADR-075) and the woocommerce tax rounding (ADR-076), and changes nothing else.
899
920
  * It also stores the WooCommerce 6dp net (`netMicros`) under the woocommerce rounding (ADR-076 amendment).
900
921
  * Its migration is the identity. It is one-way like version 7.
922
+ * Version 9 adds the order's `coupons` and the receipt's `display.coupons` (ADR-077 d2), and a line's `attributes` (#495)
923
+ * 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. Nothing writes them yet.
924
+ * Its migration is the identity. It is one-way like version 8.
901
925
  */
902
926
  declare const posOrderSchema: RxJsonSchema<PosOrder>;
903
927
  /**
@@ -956,38 +980,12 @@ declare function getDeviceId(storage: {
956
980
  * `stuckCommandIds` (the outbox's `OutboxState.stuck`: the store keeps failing it), newest first.
957
981
  * A warning code this till version doesn't know is not shown here (`knownWarnings`). Never changes `orders`.
958
982
  * `register_session_unknown` is not shown, because the store counts the order once its session arrives (ADR-078).
983
+ * A refused order is left out once its finalized successor is in `orders`.
959
984
  */
960
985
  declare function needsAttention(orders: PosOrder[], options?: {
961
986
  stuckCommandIds?: readonly string[];
962
987
  }): PosOrder[];
963
988
 
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
989
  type PosRefundStatus = 'pending' | 'applied' | 'rejected' | 'unsent';
992
990
  interface PosRefund {
993
991
  id: string;
@@ -1011,93 +1009,6 @@ declare const posRefundCollection: () => {
1011
1009
  schema: RxJsonSchema<PosRefund>;
1012
1010
  };
1013
1011
 
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
1012
  /**
1102
1013
  * The register's local collections (ADR-032): sessions, cash movements and closures. Port
1103
1014
  * provenance (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`, where they are at versions 1, 0
@@ -1201,24 +1112,6 @@ declare function registerSessionCollection(): never;
1201
1112
  declare const cashMovementSchema: RxJsonSchema<CashMovement>;
1202
1113
  declare const closureSchema: RxJsonSchema<Closure>;
1203
1114
 
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
1115
  type RegisterHost = RxLocalDocumentMutation<any>;
1223
1116
  type RegisterCounters = {
1224
1117
  last_closure_number: number;
@@ -1395,7 +1288,7 @@ declare function voidMovement(sessions: RegisterSessionCollection, movements: Ca
1395
1288
  * same snapshot and number, and its period reaches the perpetual totals exactly once.
1396
1289
  * Only a closed session (`closed` with `closed_at_gmt`) has a closure, and a closed session is
1397
1290
  * 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.
1291
+ * count in the drawer, because the cash was taken, until a finalized successor carries their payments (ADR-077 R5 amended).
1399
1292
  * A refund still pending at close is not counted, and the Z lists it.
1400
1293
  */
1401
1294
  declare function writeClosure({ closures, register, storeKey, session, counted, otherTenders, movements, orders, refunds, tillExpected, labels, resolveCashierName, softwareVersion, timezone, }: {
@@ -1425,6 +1318,160 @@ declare function writeClosure({ closures, register, storeKey, session, counted,
1425
1318
  timezone?: string;
1426
1319
  }): Promise<rxdb.RxDocument<Closure, {}, unknown>>;
1427
1320
 
1321
+ declare const REOPENABLE_CODES: readonly string[];
1322
+ type ReopenRefusal = 'not_found' | 'not_rejected' | 'code_not_reopenable' | 'already_replaced' | 'session_closed';
1323
+ declare class ReopenRefusedOrderError extends Error {
1324
+ readonly orderId: string;
1325
+ readonly reason: ReopenRefusal;
1326
+ constructor(orderId: string, reason: ReopenRefusal);
1327
+ }
1328
+ declare function reopenRefusedOrder(orderId: string, deps: {
1329
+ orders: RxCollection<PosOrder>;
1330
+ drafts: RxCollection;
1331
+ sessions: RegisterSessionCollection;
1332
+ taxContext: TaxContext;
1333
+ /** The product's tax class from the catalogue (ProductTraits.getTaxClass); undefined falls back to 'standard'. */
1334
+ taxClassOf?: (productId: string, variantId?: string) => string | undefined;
1335
+ now?: () => Date;
1336
+ }): Promise<string>;
1337
+
1338
+ /** Only tells that a reopen was started: a UI hint with no accounting meaning. */
1339
+ declare function isReopened(order: Pick<PosOrder, 'syncStatus' | 'reopenedAt'>): boolean;
1340
+ /** Payments count on the successor, so the refused order counts nowhere (ADR-077 R5 amended). Only this list is considered. */
1341
+ declare function replacedOrderIds(orders: readonly Pick<PosOrder, 'id' | 'saleId' | 'syncStatus'>[]): Set<string>;
1342
+
1343
+ type SaleContent = Pick<PosOrder, 'totalMinor' | 'currency' | 'lines' | 'payments'>;
1344
+ /**
1345
+ * Whether two orders carry the same money-bearing content: `totalMinor` and `currency`; each line's
1346
+ * `id`, `quantity` and `netMinor`, in order; each payment's `method` and `amountMinor`, in order.
1347
+ * An order `id` is minted once per sale (`finalizeOrder`), so the same `id` with other content is a defect.
1348
+ */
1349
+ declare function sameSale(stored: SaleContent, retried: SaleContent): boolean;
1350
+ /** A stored order has this order's `id` but other money-bearing content (see `sameSale`): never treated as stored. */
1351
+ declare class OrderContentMismatchError extends Error {
1352
+ readonly orderId: string;
1353
+ constructor(orderId: string);
1354
+ }
1355
+
1356
+ type MovementType = 'paid_in' | 'paid_out' | 'no_sale';
1357
+ declare function normalizeAmount(raw: string): string;
1358
+ /** Whether the server's `decimal()` would accept this string. */
1359
+ declare function isServerDecimal(value: string): boolean;
1360
+ /**
1361
+ * The field the server would name in its 400, or null when it would accept the movement.
1362
+ * A no sale carries no amount — the sheet sends '0' — but still needs a reason.
1363
+ */
1364
+ declare function movementFieldError(input: {
1365
+ type: MovementType;
1366
+ amount: string;
1367
+ reason: string;
1368
+ }): 'amount' | 'reason' | null;
1369
+
1370
+ /**
1371
+ * What the register should hold at close, per tender method: the session's cash float plus
1372
+ * captured payments and cash movements — never what the cashier counts. Port provenance
1373
+ * (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`.
1374
+ *
1375
+ * Refunds come from the till's applied `pos_refunds`, counted in the record's own `sessionId`
1376
+ * (ADR-080 amendment 1), by the server's rule. WCPOS's `attributeRefunds` fallbacks (allocations,
1377
+ * `refunded_amount`) are not ported: the store attributes each refund to a tender in `byMethod`.
1378
+ */
1379
+
1380
+ type RefundRow = Pick<PosRefund, 'id' | 'sessionId' | 'status' | 'result'>;
1381
+ /** `session_id`, `kind`, `method_id`, `status` kept as WCPOS names them; money is TallyUI's integer-minor-units convention. */
1382
+ type LedgerRow = {
1383
+ session_id?: string | null;
1384
+ kind: string;
1385
+ method_id: string;
1386
+ status: string;
1387
+ amountMinor: number;
1388
+ };
1389
+ /** `type`, `voids` and `voided_by` are kept as WCPOS names them: neutral across backends. */
1390
+ type Movement$1 = {
1391
+ id: string;
1392
+ session_id: string;
1393
+ type: string;
1394
+ amountMinor: number;
1395
+ voided_by?: string | null;
1396
+ voids?: string | null;
1397
+ };
1398
+ /**
1399
+ * Expected totals per tender method: the counted float, plus every captured ledger row for the
1400
+ * session (grouped under `cash` for cash rows, else `method_id`), plus its non-voided
1401
+ * paid-in/paid-out movements, minus its applied refunds.
1402
+ *
1403
+ * A movement is excluded when its own `voided_by` is set, or when a `type: 'void'` row's
1404
+ * `voids` names its id; the `void` row itself carries no amount of its own.
1405
+ */
1406
+ declare function deriveExpected({ session, movements, ledgerRowsBySession, refunds, }: {
1407
+ session: {
1408
+ id: string;
1409
+ countedFloatMinor: number;
1410
+ };
1411
+ movements: readonly Movement$1[];
1412
+ ledgerRowsBySession: readonly LedgerRow[];
1413
+ refunds?: readonly RefundRow[];
1414
+ }): Record<string, number>;
1415
+
1416
+ /**
1417
+ * The pure maths behind a register count: variance against the expected float, a display
1418
+ * string for it, and the denomination arithmetic the counting keypad uses. Port provenance
1419
+ * (ADR-032 amendment 1): WCPOS `next` `3b5331b5c`.
1420
+ *
1421
+ * Money here is TallyUI's convention: integer minor units. Everywhere WCPOS assumed two
1422
+ * decimals, these take the currency's `exponent` instead — 0 for JPY, 3 for KWD — except
1423
+ * `validAmount`, which like WCPOS still takes the cashier's typed text.
1424
+ */
1425
+ /**
1426
+ * Parses a decimal string the cashier typed into integer minor units at `exponent` decimal
1427
+ * places, without rounding. Returns `NaN` when the string carries more precision than the
1428
+ * currency allows, so a safe-integer check on the result also rejects it.
1429
+ */
1430
+ declare function parseMinor(text: string, exponent: number): number;
1431
+ declare const validAmount: (value: string, exponent: number) => boolean;
1432
+ /** Counted minus expected, both already in minor units. */
1433
+ declare const countVariance: (countedMinor: number, expectedMinor: number) => number;
1434
+ /** Whether the variance exceeds the store's configured threshold (minor units; none means never). */
1435
+ declare const overThreshold: (variance: number, thresholdMinor?: number | null) => boolean;
1436
+ /**
1437
+ * Whether a close's cash count needs a manager's approval: its cash variance against the expected
1438
+ * cash is over the threshold. The one definition `RegisterCount` and `useRegisterSession`'s
1439
+ * `closeSession` gate share (ADR-032).
1440
+ */
1441
+ declare const closeNeedsApproval: (countedCashMinor: number, expectedCashMinor: number, thresholdMinor?: number | null) => boolean;
1442
+ /** Sums denomination face values (already minor units) by piece count. */
1443
+ declare const denominationTotal: (pieces: Record<number, number>) => number;
1444
+ /**
1445
+ * The variance line under the count: exact, short or over. `format` takes a major-unit
1446
+ * amount, as an app's currency formatter expects, so `exponent` converts `variance` back for
1447
+ * it; `t` supplies the translated words for the `register.exact`/`register.short`/
1448
+ * `register.over` keys. Both are the app's own — neutral here.
1449
+ *
1450
+ * The direction lives in the word, not a sign (the Front desk, 2026-09-28): a signed amount
1451
+ * next to "short" read as a double negative, so the amount here is always its absolute value.
1452
+ */
1453
+ declare function varianceText(variance: number, exponent: number, format: (value: number) => string, t: (key: string) => string): string;
1454
+
1455
+ declare const denominations: Record<string, number[]>;
1456
+
1457
+ /** `addRegisterSessionCollection`'s logger: attach a sink to see dropped status writes during close. */
1458
+ declare const registerSessionsLogger: Logger;
1459
+ /** How long a close waits for the open; see `openMigratedCollection` for the cancellation mechanism. */
1460
+ declare const REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS = 10000;
1461
+ /** The database is closing; no session is lost. Reopen the database and call the opener again. */
1462
+ declare class RegisterSessionOpenClosedError extends Error {
1463
+ readonly databaseName: string;
1464
+ readonly code = "REGISTER_SESSION_OPEN_CLOSED";
1465
+ constructor(databaseName: string);
1466
+ }
1467
+ /**
1468
+ * Adds `register_sessions` and resolves once no older session is left to migrate; the register
1469
+ * document, a local document, is kept. On DM4 it rejects after migration stops and closes the collection.
1470
+ * A closing database rejects with `RegisterSessionOpenClosedError`; `closeWaitMs` is for tests only.
1471
+ * See `openMigratedCollection` for the migration and close mechanism.
1472
+ */
1473
+ declare function addRegisterSessionCollection(db: RxDatabase, closeWaitMs?: number): Promise<RxCollection<RegisterSession>>;
1474
+
1428
1475
  /**
1429
1476
  * Corrections layered onto a closure's recorded figures (ADR-032): late sales, late cash
1430
1477
  * movements and recounts, applied in order and deduplicated by id. Port provenance (ADR-032
@@ -2100,6 +2147,45 @@ declare function findEntryByCode<Doc>(entries: CatalogueEntry<Doc>[], code: stri
2100
2147
  /** Display the resolved price in the requested currency. */
2101
2148
  declare function variantPriceLabel(variant: VariantSummary, currency: string, locale?: string): string | undefined;
2102
2149
 
2150
+ /** applyCoupon's refusal when the store cannot take coupons (ADR-077 R2, R3). */
2151
+ declare const COUPONS_UNSUPPORTED = "This store's plugin does not support coupons yet";
2152
+ /** What a platform's discount codes see of the sale (ADR-077 amendment 3). */
2153
+ interface SaleDiscountState<Accepted> {
2154
+ /** The sale as it stands. */
2155
+ order: Order;
2156
+ /** 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. */
2157
+ accepted: ReadonlyMap<string, Accepted>;
2158
+ /** The categories the sale knows for each numeric product id; `beforeResume` may add to it. */
2159
+ categories: Map<number, {
2160
+ id: number;
2161
+ }[]>;
2162
+ settings: Pick<StoreSettings, 'calcDiscountsSequentially'>;
2163
+ }
2164
+ /**
2165
+ * A platform's discount codes, as `useSale` takes them (ADR-077 amendment 3; Paul, 2026-10-07: each platform its own way).
2166
+ * 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;
2167
+ * `useSale` normalizes the code, keeps the accepted codes in order, and refuses a code whose sale changed during `find`.
2168
+ */
2169
+ interface SaleDiscountCodes<Accepted = unknown> {
2170
+ /** Whether this store can take codes in this tax context; `useSale` also requires `capabilities.coupons` and `orderCreate >= 6`. */
2171
+ supports(store: {
2172
+ capabilities?: ServerCapabilities;
2173
+ rounding?: TaxRounding;
2174
+ }): boolean;
2175
+ /** Looks up a trimmed, lower-case code: what was found, or the refusal to show. */
2176
+ find(code: string, sale: SaleDiscountState<Accepted>): Promise<{
2177
+ found: Accepted;
2178
+ } | {
2179
+ refusal: string;
2180
+ }>;
2181
+ /** Checks a found code against the sale; the refusal to show, or null when it may be applied. */
2182
+ check(code: string, found: Accepted, sale: SaleDiscountState<Accepted>): string | null;
2183
+ /** Puts `sale.accepted`'s codes, in order, on the builder; throws an Error whose message is the refusal. */
2184
+ apply(builder: OrderBuilder, sale: SaleDiscountState<Accepted>): void;
2185
+ /** Called once, before a parked sale's codes are looked up again by `resume()`. */
2186
+ beforeResume?(sale: SaleDiscountState<Accepted>): Promise<void>;
2187
+ }
2188
+
2103
2189
  /** Logs a throw from onSaleCompleted for a confirmed pending completion newSale() has abandoned (Continue): nothing else would ever surface it. */
2104
2190
  declare const saleLogger: Logger;
2105
2191
  type SaleStage = {
@@ -2117,10 +2203,12 @@ declare const DISCOUNTS_UNSUPPORTED = "finalize: discounts are not supported by
2117
2203
  /** Every sale change refuses with this while a completion is pending (see `complete()`). */
2118
2204
  declare const SALE_SAVING = "This sale is being saved. Retry to finish it.";
2119
2205
  /** Call under a `TaxProvider`: its tax context and the settings' currency price every sale. */
2120
- declare function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
2206
+ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscountsSequentially'>, opts: {
2121
2207
  registerId: string;
2122
2208
  cashierRef: string;
2123
2209
  capabilities?: ServerCapabilities;
2210
+ /** The platform's discount codes (ADR-077 amendment 3), e.g. woocommerceDiscountCodes.createDiscountCodes(source); without them, applyCoupon refuses with COUPONS_UNSUPPORTED. */
2211
+ discountCodes?: SaleDiscountCodes<any>;
2124
2212
  /** Where `park()` keeps parked carts; create it with `orderDraftSchema` */
2125
2213
  drafts?: RxCollection;
2126
2214
  /**
@@ -2200,6 +2288,10 @@ declare function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
2200
2288
  /** A line's discount, or the order's without a line; returns the refusal to show, or null once applied. */
2201
2289
  applyDiscount(lineId: string | null, discount: Discount): string | null;
2202
2290
  removeDiscount(id: string): void;
2291
+ /** 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. */
2292
+ applyCoupon(code: string): Promise<string | null>;
2293
+ /** Removes an applied coupon; returns the refusal to show, or null once removed. */
2294
+ removeCoupon(code: string): string | null;
2203
2295
  /** the picked customer reaches the server as order.create v3's customer.customerId */
2204
2296
  setCustomer(customer: CustomerSummary | null): void;
2205
2297
  /**
@@ -2271,6 +2363,56 @@ declare function useSale(settings: Pick<StoreSettings, 'currency'>, opts: {
2271
2363
  continueSale(): void;
2272
2364
  };
2273
2365
 
2366
+ /** A WooCommerce coupon as the sale needs it: the engine's input and the connector's numeric id. */
2367
+ type SaleCoupon = woocommerceCoupons.CouponInput & {
2368
+ id: number;
2369
+ };
2370
+ /** Where the sale finds coupons (ADR-077 amendment 2); the app builds it over the till's coupons collection. */
2371
+ interface SaleCouponSource {
2372
+ /** The published coupon with this lower-case code, its usage already counting the till's own unsent orders; null when none. */
2373
+ find(code: string): Promise<SaleCoupon | null>;
2374
+ /** The WooCommerce category ids of each product asked for; a product it does not know is left out. */
2375
+ productCategories(productIds: readonly number[]): Promise<ReadonlyMap<number, readonly {
2376
+ id: number;
2377
+ }[]>>;
2378
+ }
2379
+ /** The cashier-facing reason for a validator refusal. */
2380
+ declare function couponRefusal(code: string, rejection: woocommerceCoupons.CouponRejection): string;
2381
+
2382
+ /** WooCommerce coupons as the sale's discount codes (ADR-077): the source's coupons, checked by woocommerceCoupons.validateCoupon. */
2383
+ declare function createDiscountCodes(source: SaleCouponSource): SaleDiscountCodes<SaleCoupon>;
2384
+
2385
+ declare function createSaleCouponSource(deps: {
2386
+ coupons: RxCollection;
2387
+ products: RxCollection;
2388
+ orders: RxCollection<PosOrder>;
2389
+ now?: () => number;
2390
+ }): SaleCouponSource;
2391
+
2392
+ declare function startCouponUsageRefetch(deps: {
2393
+ orders: RxCollection<PosOrder>;
2394
+ coupons: RxCollection;
2395
+ enqueue: (entries: Array<{
2396
+ key: string;
2397
+ local: unknown;
2398
+ refreshOnly: true;
2399
+ }>) => void;
2400
+ reSync: () => void;
2401
+ now?: () => number;
2402
+ }): {
2403
+ stop(): void;
2404
+ };
2405
+
2406
+ type index_SaleCoupon = SaleCoupon;
2407
+ type index_SaleCouponSource = SaleCouponSource;
2408
+ declare const index_couponRefusal: typeof couponRefusal;
2409
+ declare const index_createDiscountCodes: typeof createDiscountCodes;
2410
+ declare const index_createSaleCouponSource: typeof createSaleCouponSource;
2411
+ declare const index_startCouponUsageRefetch: typeof startCouponUsageRefetch;
2412
+ declare namespace index {
2413
+ 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 };
2414
+ }
2415
+
2274
2416
  declare class CartError extends Error {
2275
2417
  }
2276
2418
  declare function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry<Doc>, traits: ProductTraits<Doc>, currency: string): string;
@@ -2359,6 +2501,8 @@ interface BackendNotFound {
2359
2501
  }
2360
2502
  declare function createBackendNotFound(): BackendNotFound;
2361
2503
 
2504
+ /** Whether the outbox resends a rejection with this code. */
2505
+ declare function isRequeueable(code: string | undefined): boolean;
2362
2506
  interface OrderOutboxOptions {
2363
2507
  collection: RxCollection<PosOrder>;
2364
2508
  transport: CommandTransport<OrderCreateEnvelope>;
@@ -2728,4 +2872,4 @@ declare function tenderVoidCollection(): {
2728
2872
  readonly schema: RxJsonSchema<TenderVoid>;
2729
2873
  };
2730
2874
 
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 };
2875
+ 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 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 };