@tallyui/pos 3.12.0 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/index.d.ts +1844 -359
  2. package/dist/index.js +4620 -2211
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +108 -0
  5. package/src/app-settings/index.ts +8 -0
  6. package/src/app-settings/use-app-settings.ts +23 -0
  7. package/src/cashier/can.ts +12 -0
  8. package/src/cashier/index.ts +2 -0
  9. package/src/cashier/use-cashier.ts +81 -0
  10. package/src/csv/csv.ts +33 -0
  11. package/src/csv/index.ts +2 -0
  12. package/src/customer-display/display-link.ts +72 -0
  13. package/src/customer-display/display-state.ts +30 -0
  14. package/src/customer-display/index.ts +13 -0
  15. package/src/customer-display/protocol.ts +87 -0
  16. package/src/customer-display/snapshot.ts +65 -0
  17. package/src/customer-display/transport.ts +54 -0
  18. package/src/customer-display/use-customer-display.ts +36 -0
  19. package/src/index.ts +73 -10
  20. package/src/order/order-builder.ts +11 -1
  21. package/src/order/order-drafts.ts +16 -0
  22. package/src/order/types.ts +6 -3
  23. package/src/outbox/index.ts +5 -1
  24. package/src/outbox/outbox-health.ts +40 -0
  25. package/src/outbox/register-outbox.ts +59 -6
  26. package/src/outbox/safe-error.ts +11 -0
  27. package/src/outbox/types.ts +3 -1
  28. package/src/outbox/use-outbox-health.ts +22 -0
  29. package/src/outbox/use-register-outbox.ts +6 -0
  30. package/src/payment-driver/index.ts +8 -0
  31. package/src/payment-driver/registry.ts +39 -0
  32. package/src/payment-driver/simulated-driver.ts +104 -0
  33. package/src/payment-driver/types.ts +73 -0
  34. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  35. package/src/pos-order/command.ts +36 -16
  36. package/src/pos-order/finalize.ts +7 -3
  37. package/src/pos-order/index.ts +1 -0
  38. package/src/pos-order/note-delivery.ts +13 -0
  39. package/src/pos-order/reopen.ts +3 -2
  40. package/src/pos-order/schema.ts +5 -4
  41. package/src/pos-order/types.ts +3 -2
  42. package/src/print/escpos/code-page.ts +48 -0
  43. package/src/print/escpos/commands.ts +53 -0
  44. package/src/print/escpos/encode.ts +127 -0
  45. package/src/print/escpos/index.ts +7 -0
  46. package/src/print/escpos/transport.ts +45 -0
  47. package/src/print/index.ts +12 -0
  48. package/src/print/print-queue.ts +67 -0
  49. package/src/print/printer-profiles.ts +71 -0
  50. package/src/print/system-transport.ts +101 -0
  51. package/src/print/types.ts +44 -0
  52. package/src/receipt/reprint.ts +2 -1
  53. package/src/receipt/types.ts +2 -0
  54. package/src/receipt-template/default-templates.ts +78 -0
  55. package/src/receipt-template/index.ts +15 -0
  56. package/src/receipt-template/parse-xml.ts +175 -0
  57. package/src/receipt-template/render-html.ts +152 -0
  58. package/src/receipt-template/render-receipt.ts +19 -0
  59. package/src/receipt-template/render-template.ts +35 -0
  60. package/src/receipt-template/sanitize-html.ts +146 -0
  61. package/src/receipt-template/template-data.ts +97 -0
  62. package/src/receipt-template/types.ts +49 -0
  63. package/src/refund/index.ts +2 -0
  64. package/src/refund/refundable-lines.ts +91 -0
  65. package/src/register/export-csv.ts +24 -35
  66. package/src/register/float-suggestion.ts +22 -0
  67. package/src/register/handover.ts +103 -0
  68. package/src/register/index.ts +10 -3
  69. package/src/register/register-adoption.ts +71 -2
  70. package/src/register/register-commands.ts +7 -4
  71. package/src/register/register-count.helpers.ts +4 -0
  72. package/src/register/session-store.ts +4 -1
  73. package/src/register/use-register-session.ts +112 -28
  74. package/src/reports/adapters.ts +67 -0
  75. package/src/reports/index.ts +5 -0
  76. package/src/reports/presets.ts +27 -0
  77. package/src/reports/sales-figures.ts +187 -0
  78. package/src/reports/types.ts +63 -0
  79. package/src/sale/in-cart.ts +18 -0
  80. package/src/sale/index.ts +5 -1
  81. package/src/sale/open-sales.ts +40 -0
  82. package/src/sale/use-sale.ts +72 -8
  83. package/src/scanner/index.ts +6 -0
  84. package/src/scanner/scan-session.ts +84 -0
  85. package/src/scanner/use-barcode-scanner.ts +61 -0
  86. package/src/scanner/wedge-detector.ts +137 -0
  87. package/src/tender/cash-rounding.ts +74 -0
  88. package/src/tender/index.ts +4 -0
  89. package/src/tender/payment-legs.ts +48 -0
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { Money, TaxRounding, StoreSettings, TallyConnector, SyncContext, StoreSettingsChoice, StoreSettingsChoices, ProductTraits, woocommerceCoupons, OrderCreateLine, PaymentMethodKind, CommandServerRefs, CommandWarning, CommandError, StoreOrder, ProductCategory, TraitContext, ServerCapabilities, OrderCreateEnvelope, OrderRefundEnvelope, OrderRefundResult, RegisterCommandType, RegisterCommandResult, RegisterSessionTransitionPayload, VariantSummary, CommandResult, AnyCommandEnvelope, CommandEnvelope, OrderCreatePayload, RegisterCommandEnvelope } from '@tallyui/core';
3
+ import { Money, TaxRounding, StoreSettings, TallyConnector, SyncContext, StoreSettingsChoice, StoreSettingsChoices, Cashier, CashierPermission, PaymentMethodDescriptor, ProductTraits, woocommerceCoupons, OrderCreateLine, PaymentMethodKind, CommandServerRefs, CommandWarning, CommandError, StoreOrder, ProductCategory, TraitContext, ServerCapabilities, OrderCreateEnvelope, OrderRefundEnvelope, OrderRefundResult, RegisterInfo, RegisterCommandType, RegisterCommandResult, RegisterSessionTransitionPayload, CommandResult, AnyCommandEnvelope, CommandEnvelope, OrderCreatePayload, VariantSummary, RegisterCommandEnvelope, OrderRefundLine, StoreOrderLine } from '@tallyui/core';
4
4
  export { getProductStock, withStockOverlay } from '@tallyui/core';
5
- export { countFresh, readFresh, watchFresh } from '@tallyui/core/rxdb';
6
5
  import * as rxdb from 'rxdb';
7
- import { MangoQuery, RxCollection, RxJsonSchema, MigrationStrategies, RxDatabase, RxLocalDocumentMutation } from 'rxdb';
6
+ import { RxCollection, RxJsonSchema, MangoQuery, RxDatabase, MigrationStrategies, RxLocalDocumentMutation } from 'rxdb';
8
7
  import * as rxjs from 'rxjs';
9
8
  import { Observable } from 'rxjs';
9
+ export { countFresh, readFresh, watchFresh } from '@tallyui/core/rxdb';
10
10
 
11
11
  type LogLevel = 'debug' | 'info' | 'warn' | 'error';
12
12
  interface LogEntry {
@@ -48,6 +48,29 @@ interface CallbackSinkOptions {
48
48
  }
49
49
  declare function callbackSink(options: CallbackSinkOptions): LogSink;
50
50
 
51
+ /**
52
+ * Every cell is quoted (RFC 4180 style, so commas, quotes, CR and LF are safe). Lines use
53
+ * CRLF, with no BOM or trailing line ending, matching the register export. The formula guard
54
+ * prefixes `'` to text starting with `=`, `+`, `-`, `@`, tab, CR or LF, including formula
55
+ * markers after leading whitespace/control characters, as WCPOS v2's `csvCell` in the monorepo
56
+ * `reports/closures/export-csv.ts`. Numbers are NOT exempt: -5 exports as `'-5`, matching v2,
57
+ * which runs the guard on `String(value)`.
58
+ */
59
+ /** One CSV column: a header and either a row key or an accessor. */
60
+ type CsvColumn<Row> = {
61
+ header: string;
62
+ key: keyof Row & string;
63
+ } | {
64
+ header: string;
65
+ value: (row: Row) => unknown;
66
+ };
67
+ /** One cell, quoted and formula-guarded. */
68
+ declare function csvCell(value: unknown): string;
69
+ /** Rows of already-ordered cells (the first row is usually the header) to a CSV string. */
70
+ declare function csvFromCells(lines: readonly (readonly unknown[])[]): string;
71
+ /** Header row from `columns`, then one line per row. */
72
+ declare function toCsv<Row>(rows: readonly Row[], columns: readonly CsvColumn<Row>[]): string;
73
+
51
74
  interface CurrencyProviderProps {
52
75
  currencyCode: string;
53
76
  locale?: string;
@@ -233,6 +256,98 @@ type StoreSettingsState = {
233
256
  */
234
257
  declare function useStoreSettings(options: ResolveStoreSettingsOptions): StoreSettingsState;
235
258
 
259
+ /**
260
+ * Whether `cashier` may do `permission`. A `null` or `undefined` cashier (a connector with no `cashier()`, or one
261
+ * that resolved `null`) is allowed everything: today's behaviour, before connectors had permissions. A name that is
262
+ * not a `CashierPermission` is never allowed, and a permission the cashier's list does not name is denied.
263
+ */
264
+ declare function can(cashier: Cashier | null | undefined, permission: CashierPermission): boolean;
265
+
266
+ interface CashierState {
267
+ /** The cashier with unknown permission names dropped; `null` while loading, after an error, with no `cashier()`, or when it resolved `null`. */
268
+ cashier: Cashier | null;
269
+ /** `can(cashier, permission)` once known; `false` while loading or after an error, so nothing flashes. */
270
+ can: (permission: CashierPermission) => boolean;
271
+ /** `cashier()` is in flight, or there is no connector or context yet. */
272
+ loading: boolean;
273
+ /** What `cashier()` rejected with; `undefined` otherwise. */
274
+ error: unknown;
275
+ /** For `useRegisterSession`'s `blind` option: `!can('viewReports')`, as v2's blind count. */
276
+ blind: boolean;
277
+ /** The Reports gate: `'pending'` while loading, `'allowed'` with `viewReports`, else `'denied'`. */
278
+ reports: 'pending' | 'allowed' | 'denied';
279
+ }
280
+ /**
281
+ * The signed-in cashier's permissions (v2 parity A12): reads `connector.cashier(context)` on mount, and again when
282
+ * `connector` or `context` changes by identity (memoise both); the last read wins. A connector without `cashier()`
283
+ * allows everything at once, as before. While the read is in flight, and after it rejects, `can` is `false` and the
284
+ * count is blind, so a blind cashier never sees figures flash; nothing is retried.
285
+ *
286
+ * ```tsx
287
+ * const cashier = useCashier(connector, context);
288
+ * const register = useRegisterSession({ ...options, blind: cashier.blind });
289
+ * if (cashier.reports === 'denied') return <NoReportsAccess />;
290
+ * ```
291
+ */
292
+ declare function useCashier(connector: TallyConnector | null, context: SyncContext | null): CashierState;
293
+
294
+ /**
295
+ * Device UI preferences, one JSON-encoded value per key. Local only, never replicated;
296
+ * the app adds the collection as `app_settings`.
297
+ * v2 provenance: WCPOS monorepo `packages/database/src/collections/schemas/stores.ts`
298
+ * keeps scale (auto|compact|regular|spacious, default auto) and fonts (default auto)
299
+ * device-local beside the theme, never server-owned. TallyUI has no replicated
300
+ * store document for them; TallyUI CLAUDE.md forbids local writes to replicated collections.
301
+ */
302
+
303
+ declare const UI_SCALES: readonly ["auto", "compact", "regular", "spacious"];
304
+ type UiScale = (typeof UI_SCALES)[number];
305
+ /** v2's first three themes (`core/screens/main/settings/theme.tsx`); TallyUI's tokens define light and dark. */
306
+ declare const UI_THEMES: readonly ["system", "light", "dark"];
307
+ type UiTheme = (typeof UI_THEMES)[number];
308
+ /** The typed key map. Add a key here and in APP_SETTING_DEFINITIONS; no schema change is needed. */
309
+ interface AppSettings {
310
+ /** The app applies it (e.g. Uniwind's setTheme); this store only records it. */
311
+ 'ui.theme': UiTheme;
312
+ 'ui.scale': UiScale;
313
+ /** A font id; `'auto'` follows the theme. Not an enum: the font list lives in the UI layer. */
314
+ 'ui.font': string;
315
+ /**
316
+ * The cart's quick-discount keys in percent, for `Cart`'s `quickDiscounts`. v2 keeps them per screen,
317
+ * `pos-cart.quickDiscounts: [5, 10, 15]` (`core/src/screens/main/contexts/ui-settings/initial-settings.json`).
318
+ */
319
+ 'cart.quickDiscounts': readonly number[];
320
+ }
321
+ type AppSettingKey = keyof AppSettings;
322
+ /** One key's default and its check: `parse` returns the value when valid, else `undefined`. */
323
+ interface AppSettingDefinition<T> {
324
+ default: T;
325
+ parse: (value: unknown) => T | undefined;
326
+ }
327
+ declare const APP_SETTING_DEFINITIONS: {
328
+ [K in AppSettingKey]: AppSettingDefinition<AppSettings[K]>;
329
+ };
330
+ declare const DEFAULT_APP_SETTINGS: AppSettings;
331
+ /** One stored setting. `value` is the JSON encoding of the setting's value, so the schema never changes when a key is added. */
332
+ interface AppSettingDoc {
333
+ key: string;
334
+ value: string;
335
+ }
336
+ declare const appSettingSchema: RxJsonSchema<AppSettingDoc>;
337
+ declare function appSettingCollection(): {
338
+ readonly schema: RxJsonSchema<AppSettingDoc>;
339
+ };
340
+ type AppSettingCollection = RxCollection<AppSettingDoc>;
341
+ declare function resolveAppSettings(docs: readonly AppSettingDoc[]): AppSettings;
342
+ declare function readAppSettings(collection: AppSettingCollection): Promise<AppSettings>;
343
+ declare function appSettings$(collection: AppSettingCollection): Observable<AppSettings>;
344
+ declare function writeAppSetting<K extends AppSettingKey>(collection: AppSettingCollection, key: K, value: AppSettings[K]): Promise<void>;
345
+
346
+ declare function useAppSettings(collection: AppSettingCollection | undefined): {
347
+ settings: AppSettings;
348
+ setSetting: <K extends AppSettingKey>(key: K, value: AppSettings[K]) => Promise<void>;
349
+ };
350
+
236
351
  interface Repository<T> {
237
352
  findById$(id: string): Observable<T | null>;
238
353
  findAll$(query?: MangoQuery<T>): Observable<T[]>;
@@ -249,6 +364,36 @@ declare function createRepository<T extends {
249
364
  id: string;
250
365
  }>(collection: RxCollection<T>): Repository<T>;
251
366
 
367
+ /** Local sale state; the order.create wire does not carry payment status yet. */
368
+
369
+ type PaymentLegStatus = 'pending' | 'authorized' | 'captured' | 'failed' | 'voided';
370
+ type Leg = {
371
+ amountMinor: number;
372
+ status?: PaymentLegStatus;
373
+ };
374
+ /** Defaults legacy legs to captured using v2 payments/types.ts PaymentStatus. */
375
+ declare function legStatus(leg: {
376
+ status?: PaymentLegStatus;
377
+ }): PaymentLegStatus;
378
+ /** Only captured money is paid: v2 payments/derive.ts countsTowardPaid (ADR 0040 D6). */
379
+ declare function countsTowardPaid(leg: {
380
+ status?: PaymentLegStatus;
381
+ }): boolean;
382
+ /** Pending and authorized are in motion: v2 payments/ledger.ts isInMotionPaymentStatus. */
383
+ declare function isInMotion(leg: {
384
+ status?: PaymentLegStatus;
385
+ }): boolean;
386
+ /** Sums integer minor units using v2 payments/derive.ts countsTowardPaid. */
387
+ declare function capturedMinor(legs: readonly Leg[]): number;
388
+ /** Sums holds in integer minor units using v2 payments/ledger.ts isInMotionPaymentStatus. */
389
+ declare function inMotionMinor(legs: readonly Leg[]): number;
390
+ /** Local transitions for v2 payments/ledger.ts isInMotionPaymentStatus and isFinalPaymentStatus. */
391
+ declare function canMoveLeg(from: PaymentLegStatus, to: PaymentLegStatus): boolean;
392
+ /** Voids live legs, captured only manually: v2 payments/ledger.ts partitionVoidableRows. */
393
+ declare function canVoidLeg(leg: {
394
+ status?: PaymentLegStatus;
395
+ }, method: PaymentMethodDescriptor): boolean;
396
+
252
397
  interface OrderCoupon {
253
398
  code: string;
254
399
  couponId: string;
@@ -400,6 +545,8 @@ interface AppliedDiscount extends Discount {
400
545
  interface Payment {
401
546
  id: string;
402
547
  method: string;
548
+ /** Absent means captured; only captured legs count toward paidMinor. */
549
+ status?: PaymentLegStatus;
403
550
  amountMinor: number;
404
551
  tenderedMinor?: number;
405
552
  changeMinor?: number;
@@ -479,6 +626,7 @@ interface OrderBuilder {
479
626
  applyOrderDiscount(discount: Discount): void;
480
627
  removeDiscount(discountId: string): void;
481
628
  addPayment(payment: Omit<Payment, 'id'>): string;
629
+ setPaymentStatus(paymentId: string, status: PaymentLegStatus): boolean;
482
630
  removePayment(paymentId: string): void;
483
631
  setCustomer(customer: CustomerSummary | null): void;
484
632
  setNote(note: string): void;
@@ -540,6 +688,10 @@ interface ParkedOrderSummary {
540
688
  totalMinor: number;
541
689
  parkedAt: string;
542
690
  source: 'local' | 'server';
691
+ /** Read from the draft's data (open-sale tabs, u19): the captured money, the balance still due and the first line's name. */
692
+ paidMinor?: number;
693
+ balanceDueMinor?: number;
694
+ firstItem?: string;
543
695
  }
544
696
  declare function writeOrderDraft(drafts: RxCollection, snapshot: Order): Promise<string>;
545
697
  declare function restoreOrderDraft(saved: Order, options: {
@@ -656,6 +808,8 @@ interface ReceiptData {
656
808
  changeDueMinor: number;
657
809
  footer: {
658
810
  note?: string;
811
+ /** ADR-083 condition 2: set only on a reprint of a till order whose note was not sent to the store. */
812
+ noteNotSent?: true;
659
813
  barcode?: string;
660
814
  };
661
815
  currency: string;
@@ -755,6 +909,7 @@ interface PosOrder {
755
909
  name?: string;
756
910
  email?: string;
757
911
  } | null;
912
+ /** The sale's note; sent as order.create version 7's `note` (ADR-083), cut to ORDER_NOTE_MAX when frozen. */
758
913
  note?: string;
759
914
  registerId?: string;
760
915
  /**
@@ -772,9 +927,9 @@ interface PosOrder {
772
927
  * The order.create version every attempt under this `commandId` goes out at: the outbox records it before the first
773
928
  * send, and lowers it only on a downgrade (ADR-065 amendment). Absent means not sent yet (or requeued).
774
929
  */
775
- sentVersion?: 1 | 2 | 3 | 4 | 5 | 6;
930
+ sentVersion?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
776
931
  /** The version first tried, before the downgrade (the order's audit). */
777
- downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6;
932
+ downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
778
933
  /** ADR-065: the receipt's display figures, in integer minor units of `currency` at `exponent`. */
779
934
  display?: DisplayTotals & {
780
935
  currency: string;
@@ -815,6 +970,357 @@ declare function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptCo
815
970
  /** Receipt data for reprinting an order read from the store with `getOrders`/`listOrders` (ADR-081). */
816
971
  declare function buildReceiptDataFromStoreOrder(order: StoreOrder, config: ReceiptConfig): ReceiptData;
817
972
 
973
+ type DrawerConnector = 'pin2' | 'pin5';
974
+ type ThermalNode = ReceiptNode | TextNode | RawTextNode | BoldNode | UnderlineNode | InvertNode | SizeNode | AlignNode | RowNode | ColNode | LineNode | BarcodeNode | QrcodeNode | ImageNode | CutNode | FeedNode | DrawerNode;
975
+ interface ReceiptNode {
976
+ type: 'receipt';
977
+ paperWidth: number;
978
+ children: ThermalNode[];
979
+ }
980
+ interface RawTextNode {
981
+ type: 'raw-text';
982
+ value: string;
983
+ }
984
+ interface TextNode {
985
+ type: 'text';
986
+ children: ThermalNode[];
987
+ }
988
+ interface BoldNode {
989
+ type: 'bold';
990
+ children: ThermalNode[];
991
+ }
992
+ interface UnderlineNode {
993
+ type: 'underline';
994
+ children: ThermalNode[];
995
+ }
996
+ interface InvertNode {
997
+ type: 'invert';
998
+ children: ThermalNode[];
999
+ }
1000
+ interface SizeNode {
1001
+ type: 'size';
1002
+ width: number;
1003
+ height: number;
1004
+ children: ThermalNode[];
1005
+ }
1006
+ interface AlignNode {
1007
+ type: 'align';
1008
+ mode: 'left' | 'center' | 'right';
1009
+ children: ThermalNode[];
1010
+ }
1011
+ interface RowNode {
1012
+ type: 'row';
1013
+ children: ColNode[];
1014
+ }
1015
+ interface ColNode {
1016
+ type: 'col';
1017
+ width: number | '*';
1018
+ align: 'left' | 'right';
1019
+ children: ThermalNode[];
1020
+ }
1021
+ interface LineNode {
1022
+ type: 'line';
1023
+ style: 'single' | 'double' | 'dashed' | 'dotted';
1024
+ }
1025
+ interface BarcodeNode {
1026
+ type: 'barcode';
1027
+ barcodeType: string;
1028
+ height: number;
1029
+ value: string;
1030
+ }
1031
+ interface QrcodeNode {
1032
+ type: 'qrcode';
1033
+ size: number;
1034
+ value: string;
1035
+ }
1036
+ interface ImageNode {
1037
+ type: 'image';
1038
+ src: string;
1039
+ width: number;
1040
+ }
1041
+ interface CutNode {
1042
+ type: 'cut';
1043
+ cutType: 'full' | 'partial';
1044
+ }
1045
+ interface FeedNode {
1046
+ type: 'feed';
1047
+ lines: number;
1048
+ }
1049
+ interface DrawerNode {
1050
+ type: 'drawer';
1051
+ connector?: DrawerConnector;
1052
+ }
1053
+
1054
+ /** Parse a thermal XML template string into an AST using the native DOMParser or xmldom. */
1055
+ declare function parseXml(xml: string): ReceiptNode;
1056
+
1057
+ declare function renderHtml(ast: ReceiptNode): string;
1058
+
1059
+ interface SanitizeHtmlOptions {
1060
+ /** Additional tag names to allow beyond DOMPurify's default HTML profile. */
1061
+ addTags?: string[];
1062
+ /** Additional attribute names to allow beyond DOMPurify's default HTML profile. */
1063
+ addAttributes?: string[];
1064
+ }
1065
+ /**
1066
+ * Sanitize rendered receipt HTML before it is inserted into an admin/browser DOM
1067
+ * (or a native WebView via `srcDoc`).
1068
+ *
1069
+ * The default profile deliberately excludes SVG/MathML and strips scripts,
1070
+ * event handlers, and unsafe URL protocols while preserving normal receipt HTML.
1071
+ *
1072
+ * Three execution paths, in priority order:
1073
+ * 1. Browser/DOM with `window.document` → DOMPurify (the strongest profile).
1074
+ * 2. A runtime that exposes a global `DOMParser` (e.g. jsdom/SSR) → DOM walk.
1075
+ * 3. React Native, which has neither → parse via `@xmldom/xmldom` and walk.
1076
+ *
1077
+ * The xmldom fallback mirrors `parse-xml.ts`, which already uses xmldom on
1078
+ * native. Without it, native runtimes hit the escaped-text last resort and the
1079
+ * receipt preview renders raw HTML markup as visible text instead of HTML.
1080
+ */
1081
+ declare function sanitizeHtml(html: string, options?: SanitizeHtmlOptions): string;
1082
+
1083
+ interface RenderSanitizeOptions extends SanitizeHtmlOptions {
1084
+ /** Disable sanitization only for trusted test/debug output. Defaults to true. */
1085
+ sanitize?: boolean;
1086
+ }
1087
+ /** Mustache only. */
1088
+ declare function renderReceiptTemplate(template: string, data: object): string;
1089
+ /** Mustache HTML template, then sanitize (unless sanitize === false). No <barcode>/<qrcode> resolution. */
1090
+ declare function renderLogiclessTemplate(template: string, data: object, options?: RenderSanitizeOptions): string;
1091
+ /** Mustache, then parseXml, then renderHtml, then sanitize (unless sanitize === false). */
1092
+ declare function renderThermalPreview(template: string, data: object, options?: RenderSanitizeOptions): string;
1093
+
1094
+ interface ReceiptTemplateRow {
1095
+ label: string;
1096
+ amount: string;
1097
+ }
1098
+ interface ReceiptTemplateLine {
1099
+ name: string;
1100
+ /** `Name: value` per variant option, in `attributes` order. */
1101
+ options: {
1102
+ text: string;
1103
+ }[];
1104
+ /** `<quantity> × <unit price>`. */
1105
+ detail: string;
1106
+ /** displayAmountMinor, before any discount. */
1107
+ amount: string;
1108
+ /** The line's own displayDiscounts; amount carries a leading `−`. */
1109
+ discounts: ReceiptTemplateRow[];
1110
+ }
1111
+ interface ReceiptTemplateData {
1112
+ store: {
1113
+ name: string;
1114
+ addressLines: {
1115
+ line: string;
1116
+ }[];
1117
+ };
1118
+ document: {
1119
+ title: string;
1120
+ isReprint: boolean;
1121
+ reprintCount: number;
1122
+ };
1123
+ order: {
1124
+ number: string;
1125
+ date: string;
1126
+ };
1127
+ cashier: string;
1128
+ register: string;
1129
+ customer: string;
1130
+ lines: ReceiptTemplateLine[];
1131
+ subtotal: string;
1132
+ lineDiscount: string;
1133
+ orderDiscount: string;
1134
+ charges: ReceiptTemplateRow[];
1135
+ taxes: ReceiptTemplateRow[];
1136
+ total: string;
1137
+ payments: {
1138
+ method: string;
1139
+ amount: string;
1140
+ reference: string;
1141
+ }[];
1142
+ change: string;
1143
+ note: string;
1144
+ qrPayload: string;
1145
+ }
1146
+ interface ReceiptTemplateOptions {
1147
+ /** Default: formatMoney({ amount: minor, currency }) ?? ''. */
1148
+ formatMoney?: (minor: number, currency: string) => string;
1149
+ /** Default: Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' });
1150
+ * an unparseable date is returned as given. */
1151
+ formatDate?: (iso: string) => string;
1152
+ /** Default: 'cash' → 'Cash', 'external' → 'Card terminal', anything else as given. */
1153
+ paymentLabel?: (method: string) => string;
1154
+ }
1155
+ declare function receiptTemplateData(receipt: ReceiptData, options?: ReceiptTemplateOptions): ReceiptTemplateData;
1156
+
1157
+ type ReceiptPaper = '58mm' | '80mm';
1158
+ /** Characters per line (v2 encode-receipt.ts:18). */
1159
+ declare const PAPER_COLUMNS: Record<ReceiptPaper, number>;
1160
+ declare const DEFAULT_RECEIPT_TEMPLATES: Record<ReceiptPaper, string>;
1161
+
1162
+ interface RenderReceiptOptions extends ReceiptTemplateOptions {
1163
+ /** Default '80mm'. Picks DEFAULT_RECEIPT_TEMPLATES[paper] when no template is given. */
1164
+ paper?: ReceiptPaper;
1165
+ /** A thermal-XML Mustache template over ReceiptTemplateData. */
1166
+ template?: string;
1167
+ }
1168
+ /** receiptTemplateData, then renderThermalPreview (sanitized). Needs a global DOMParser (browsers, jsdom). */
1169
+ declare function renderReceiptHtml(receipt: ReceiptData, options?: RenderReceiptOptions): string;
1170
+
1171
+ declare const DISPLAY_PROTOCOL_VERSION = 1;
1172
+ type PaymentPhase = 'started' | 'approved' | 'declined' | 'complete';
1173
+ interface DisplayTemplate {
1174
+ id: string | number;
1175
+ version: number;
1176
+ }
1177
+ /** The cart snapshot: the receipt as it stands, and whether lines were dropped to fit the message cap. */
1178
+ interface DisplayCart {
1179
+ receipt: ReceiptData;
1180
+ linesTruncated: boolean;
1181
+ }
1182
+ interface DisplayPayment {
1183
+ state: PaymentPhase;
1184
+ leg?: {
1185
+ method: string;
1186
+ amountMinor: number;
1187
+ };
1188
+ message?: string;
1189
+ }
1190
+ interface DisplayConfig {
1191
+ contract: '1.0';
1192
+ display: {
1193
+ id: string;
1194
+ name: string;
1195
+ };
1196
+ store: {
1197
+ id: string;
1198
+ name: string;
1199
+ currency: string;
1200
+ locale: string;
1201
+ timezone?: string;
1202
+ logo?: string;
1203
+ };
1204
+ presentation_hints: Record<string, unknown>;
1205
+ i18n: Record<string, string>;
1206
+ template?: DisplayTemplate;
1207
+ idle: {
1208
+ afterCompleteMs: number;
1209
+ };
1210
+ }
1211
+ interface DisplayPayloads {
1212
+ 'cart.updated': DisplayCart;
1213
+ 'payment.state': DisplayCart & DisplayPayment;
1214
+ 'display.idle': {
1215
+ reason: string;
1216
+ };
1217
+ /** Sent by the display to the till. */
1218
+ 'display.hello': {
1219
+ template: DisplayTemplate;
1220
+ };
1221
+ 'display.config': DisplayConfig;
1222
+ }
1223
+ type DisplayAction = keyof DisplayPayloads;
1224
+ declare const DISPLAY_ACTIONS: readonly DisplayAction[];
1225
+ type DisplayEnvelope<A extends DisplayAction = DisplayAction> = {
1226
+ [K in A]: {
1227
+ tally: 1;
1228
+ id: string;
1229
+ action: K;
1230
+ payload: DisplayPayloads[K];
1231
+ };
1232
+ }[A];
1233
+ declare function makeEnvelope<A extends DisplayAction>(action: A, payload: DisplayPayloads[A], id?: string): DisplayEnvelope<A>;
1234
+ declare function displayCart(receipt: ReceiptData): DisplayCart;
1235
+ type DecodeRefusal = 'malformed' | 'version' | 'action' | 'payload';
1236
+ type DecodeResult = {
1237
+ ok: true;
1238
+ envelope: DisplayEnvelope;
1239
+ } | {
1240
+ ok: false;
1241
+ refusal: DecodeRefusal;
1242
+ };
1243
+ /** Reads a message from the other side. Never throws: anything it cannot trust comes back as a refusal. */
1244
+ declare function decode(text: unknown): DecodeResult;
1245
+
1246
+ /** The display contract caps each message at 200 KiB: UTF-8 bytes of the JSON text. */
1247
+ declare const MAX_MESSAGE_BYTES: number;
1248
+ declare function messageBytes(text: string): number;
1249
+ /**
1250
+ * Serialises a message within MAX_MESSAGE_BYTES, trimming a copy in v2's order. If it is still over after every
1251
+ * step (a non-cart action, or a receipt whose fixed fields alone are too big), the text is returned anyway, as v2
1252
+ * sends it; check with messageBytes.
1253
+ */
1254
+ declare function encode(envelope: DisplayEnvelope): string;
1255
+
1256
+ /** What the customer display shows: nothing to sell, the cart, or a payment in progress or complete. */
1257
+ type DisplayView = {
1258
+ screen: 'idle';
1259
+ reason: string;
1260
+ } | {
1261
+ screen: 'cart';
1262
+ cart: DisplayCart;
1263
+ } | {
1264
+ screen: 'payment';
1265
+ cart: DisplayCart;
1266
+ payment: DisplayPayment;
1267
+ };
1268
+ interface DisplayState {
1269
+ config: DisplayConfig | null;
1270
+ view: DisplayView;
1271
+ }
1272
+ declare const initialDisplayState: DisplayState;
1273
+ /** The display side's state, driven by decoded messages from the till. */
1274
+ declare function displayReducer(state: DisplayState, envelope: DisplayEnvelope): DisplayState;
1275
+
1276
+ /** How the till and the customer display reach each other. The first is a second window on this device (ADR-084 3). */
1277
+ interface DisplayTransport {
1278
+ /** False when the channel refuses (closed); never throws. */
1279
+ send(envelope: DisplayEnvelope): boolean;
1280
+ /** Decoded messages from the other window; returns the unsubscribe. */
1281
+ onMessage(listener: (envelope: DisplayEnvelope) => void): () => void;
1282
+ close(): void;
1283
+ }
1284
+ declare const DISPLAY_CHANNEL = "tallyui.customer-display";
1285
+ /** The structural part of BroadcastChannel the transport uses (a test passes a fake). */
1286
+ interface BroadcastChannelLike {
1287
+ postMessage(message: unknown): void;
1288
+ close(): void;
1289
+ onmessage: ((event: MessageEvent) => void) | null;
1290
+ }
1291
+ /** A same-origin second window over BroadcastChannel. Whatever arrives is decoded; anything refused is dropped. */
1292
+ declare function createBroadcastDisplayTransport(channelName?: string, open?: (name: string) => BroadcastChannelLike): DisplayTransport;
1293
+
1294
+ interface DisplayClock {
1295
+ setTimeout(run: () => void, ms: number): unknown;
1296
+ clearTimeout(handle: unknown): void;
1297
+ }
1298
+ interface DisplayLink {
1299
+ /** The order as it stands; null, or no lines, fees or shipping, shows idle. */
1300
+ showCart(receipt: ReceiptData | null): void;
1301
+ showPayment(receipt: ReceiptData, payment: DisplayPayment): void;
1302
+ close(): void;
1303
+ }
1304
+ /**
1305
+ * The till's side of the customer display. Ported from WCPOS v2 (monorepo main 51e7c43,
1306
+ * core/services/customer-display/display-session.ts and service.ts) without the WebRTC: each `display.hello` is
1307
+ * answered with `display.config` under the hello's id, then the current state; a completed payment stays up for
1308
+ * `config.idle.afterCompleteMs` before `display.idle`, and an empty cart inside that window waits for it.
1309
+ */
1310
+ declare function createDisplayLink(transport: DisplayTransport, options: {
1311
+ config: DisplayConfig;
1312
+ clock?: DisplayClock;
1313
+ }): DisplayLink;
1314
+
1315
+ declare const DISPLAY_TEMPLATE: DisplayTemplate;
1316
+ /** The hello is re-sent until a config answers it, so a till opened after the display still finds it. */
1317
+ declare const HELLO_RETRY_MS = 2000;
1318
+ /**
1319
+ * The customer display's side: says `display.hello`, then shows what the till sends. As v2's display page
1320
+ * (Pro packages/display/src/session.ts), nothing is applied before the `display.config` that answers this hello.
1321
+ */
1322
+ declare function useCustomerDisplay(transport: DisplayTransport | null): DisplayState;
1323
+
818
1324
  /**
819
1325
  * Filters product documents by a cashier's search term, through traits, so
820
1326
  * it works the same on every backend.
@@ -882,120 +1388,697 @@ declare function stockOverlay$(collection: RxCollection): Observable<Map<string,
882
1388
  */
883
1389
  declare function stockOverlayAsOf$(collection: RxCollection): Observable<string | undefined>;
884
1390
 
885
- /** RFC 9562 UUIDv7: monotonic with no arguments; stateless with an explicit timestamp or random source. */
886
- declare function uuidv7(now?: number, randomBytes?: (n: number) => Uint8Array): string;
887
-
888
- interface FinalizeOptions {
889
- localWarnings?: PosOrderLocalWarning[];
890
- registerId?: string;
891
- cashierRef?: string;
892
- now?: Date;
893
- /** Tests only: replaces uuidv7. Every id it returns must be at most 255 characters with no NUL (order.create's bound). */
894
- newId?: () => string;
895
- /** The store's `order.create` capability (ADR-062); `undefined` is treated as 1. */
896
- capabilities?: ServerCapabilities;
1391
+ /** The wedge detector distinguishes scanner bursts from typing using a folded
1392
+ * running average of inter-key gaps. Live and replay paths share the reducer. */
1393
+ interface WedgeSettings {
1394
+ /** Folded-average gap (ms) below which input latches as a scan. */
1395
+ threshold: number;
1396
+ /** Stripped only when it equals the first key. */
1397
+ prefix: string;
1398
+ /** Stripped only when it equals the last key. */
1399
+ suffix: string;
897
1400
  }
898
- /**
899
- * Turns a fully paid builder Order into a pending PosOrder without mutating it. The PosOrder holds the sent form,
900
- * frozen: line names and v3 discount labels are cut to PAYLOAD_STRING_MAX with NUL stripped (`cutText`), and a
901
- * customer email or id the shape check would refuse is left out, so `toOrderCreateEnvelope` sends it unchanged.
902
- */
903
- declare function finalizeOrder(order: Order, options?: FinalizeOptions): PosOrder;
904
-
905
- declare class UnsupportedOrderVersionError extends Error {
906
- readonly needed: number;
907
- readonly supported: number;
908
- readonly code = "UNSUPPORTED_ORDER_VERSION";
909
- constructor(needed: number, supported: number);
1401
+ /** v2 store defaults: threshold 24 ms (stores.ts barcode_scanning_avg_time_input_threshold), no prefix/suffix. */
1402
+ declare const DEFAULT_WEDGE_SETTINGS: WedgeSettings;
1403
+ /** v2 store default barcode_scanning_min_chars. */
1404
+ declare const DEFAULT_MIN_SCAN_CHARS = 8;
1405
+ /** End-of-scan settle: a burst is complete this long after its last key. */
1406
+ declare const WEDGE_END_OF_SCAN_MS = 150;
1407
+ interface WedgeState {
1408
+ avg: number;
1409
+ detecting: boolean;
1410
+ stack: string[];
1411
+ lastTimeMs: number | null;
910
1412
  }
911
- /**
912
- * Builds the ADR-038 order.create envelope for a PosOrder. It sends the stored order unchanged, so every resend of
913
- * an order is byte-identical, and an order stored by an older till goes out exactly as that till sent it:
914
- * `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
915
- * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
916
- * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
917
- * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
918
- * Orders with Any picks (#495) need version 6 too, carrying a line's `anyAttributes`, and coupons only when they have some.
919
- */
920
- declare function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt?: number, options?: {
921
- maxVersion?: number;
922
- }): OrderCreateEnvelope;
923
-
924
- /**
925
- * Version 1 adds the optional `sessionId` (ADR-032); nothing else changed from version 0.
926
- * Version 2 adds three optional fields and changes nothing else: `lateSessionId` (ADR-032, late
927
- * sale), and ADR-065's `display` and `taxByRate`, declared ahead of the job that writes them so a
928
- * till migrates once. Create the collection with `posOrderCollection()`, never with this schema
929
- * alone: RxDB refuses a version above 0 without its migration strategies.
930
- * Version 3 adds an index on `sessionId` (with its `maxLength`), and the optional `sentVersion` and `downgradedFrom` (the outbox's version fallback), and changes nothing else.
931
- * Version 4 adds the optional `localWarnings` and `serverFailures` (the outbox's stuck clock start, latest reason and
932
- * isolation, restored when an outbox starts), and changes nothing else.
933
- * Version 5 lets `sentVersion` and `downgradedFrom` be 4 (order.create version 4, #286), and changes nothing else. Its
934
- * migration sets a row's missing `sentVersion` to its content version, the version any earlier attempt went out at.
935
- * Like version 4 (ADR-069), it is one-way: an older build shows no orders.
936
- * Version 6 adds `taxRounding`, the strategy the sale's figures were computed with (#287; never sent), and changes
937
- * nothing else. Its migration sets it on every older row. It is one-way like version 5.
938
- * Version 7 adds `saleId`, the sale order's id (ADR-072; never sent), and changes nothing else. Its migration is the
939
- * identity: older orders have no `saleId`. It is one-way like version 6.
940
- * Version 8 adds fees, shipping, custom lines (ADR-075) and the woocommerce tax rounding (ADR-076), and changes nothing else.
941
- * It also stores the WooCommerce 6dp net (`netMicros`) under the woocommerce rounding (ADR-076 amendment).
942
- * Its migration is the identity. It is one-way like version 7.
943
- * Version 9 adds the order's `coupons` and the receipt's `display.coupons` (ADR-077 d2), and a line's `attributes` (#495)
944
- * 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.
945
- * `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them only at version 6.
946
- * Its migration is the identity. It is one-way like version 8.
947
- * Version 10 adds a line's `anyAttributes` (#495 c/d) and changes nothing else. Its migration is the identity. It is one-way like version 9.
948
- */
949
- declare const posOrderSchema: RxJsonSchema<PosOrder>;
950
- /**
951
- * The `pos_orders` collection config, with its migration strategies. Open the collection with
952
- * `addPosOrderCollection(db)`, which uses this and settles the migration safely; adding this config
953
- * directly leaves RxDB's own open path. `pos_orders` holds sales not yet sent, so no step may drop a
954
- * document: versions 1 and 2 only add optional fields, so every order from version 0 or 1 passes
955
- * unchanged.
956
- *
957
- * Within one run, RxDB 16.21 keeps an order that fails the new schema's validation: with a
958
- * validating storage the migration stops with DM4 and the order stays in the older version's
959
- * storage; without one it is copied as is. **Across runs, RxDB's own open path can lose it**: a
960
- * failed run can leave its checkpoint past that order, and the next run then removes the older
961
- * version's storage without copying it. `addPosOrderCollection` resets that checkpoint, so use it
962
- * (`migration.test.ts`).
963
- */
964
- declare function posOrderCollection(): {
965
- schema: RxJsonSchema<PosOrder>;
966
- migrationStrategies: MigrationStrategies;
967
- };
1413
+ declare function createWedgeState(): WedgeState;
1414
+ /** Fold one key, mutating and returning state. Kept bug-for-bug with v2:
1415
+ * only length-1 keys advance timing; the first gap is +Infinity; the average
1416
+ * folds as (avg + gap) / 2. Scanning latches below threshold for the burst;
1417
+ * a slow key outside a burst resets the average and restarts the stack. */
1418
+ declare function foldWedgeKey(state: WedgeState, key: string, timeMs: number, threshold: number): WedgeState;
1419
+ /** Strip a configured prefix/suffix only when it equals the single key at
1420
+ * that edge of the stack — never as a substring. */
1421
+ declare function stripBoundary(stack: string[], settings: WedgeSettings): string;
1422
+ interface TraceKey {
1423
+ key: string;
1424
+ timeMs: number;
1425
+ }
1426
+ interface WedgeReplayResult {
1427
+ /** Whether the detector would latch onto this trace as a scan. */
1428
+ detectedAsScan: boolean;
1429
+ /** The barcode the detector would emit, with prefix/suffix stripped. */
1430
+ code: string;
1431
+ }
1432
+ /** Replay the detector over a completed keystroke trace. */
1433
+ declare function replayWedgeDetector(keys: TraceKey[], settings: WedgeSettings): WedgeReplayResult;
1434
+ interface WedgeDetectorOptions {
1435
+ /** Read current settings per keystroke so live changes apply. */
1436
+ getSettings: () => WedgeSettings;
1437
+ /** A completed burst, prefix/suffix already stripped. */
1438
+ onScan: (code: string) => void;
1439
+ /** Injectable clock/timers so hosts and tests control time. */
1440
+ now?: () => number;
1441
+ setTimeout?: (fn: () => void, ms: number) => unknown;
1442
+ clearTimeout?: (handle: unknown) => void;
1443
+ }
1444
+ interface WedgeDetector {
1445
+ /** True for a latched burst key: the host must prevent its default action. */
1446
+ handleKey: (key: string, timeMs?: number) => boolean;
1447
+ /** Cancel any pending end-of-scan timer on host teardown. */
1448
+ dispose: () => void;
1449
+ }
1450
+ /** Stream keys through the reducer, emitting after the settle window and
1451
+ * once the quiet period exceeds the threshold, mirroring the original hook. */
1452
+ declare function createWedgeDetector(options: WedgeDetectorOptions): WedgeDetector;
968
1453
 
969
- /** `addPosOrderCollection`'s logger: attach a sink to see, for example, the status writes a closing open dropped. */
970
- declare const posOrdersLogger: Logger;
971
- /**
972
- * `addPosOrderCollection` stopped, before any further write, because its database is closing: it
973
- * was called once `close()` had begun, the close cancelled its migration (RxDB 17.5), or the close
974
- * stopped waiting for it (after `POS_ORDER_MIGRATION_CLOSE_WAIT_MS`). No order is lost: reopen the
975
- * database and call it again.
976
- */
977
- declare class PosOrderOpenClosedError extends Error {
978
- readonly databaseName: string;
979
- readonly code = "POS_ORDER_OPEN_CLOSED";
980
- constructor(databaseName: string);
1454
+ /** Suppress repeated reads within a cooldown and reject retail check-digit misreads. */
1455
+ declare const DEFAULT_COOLDOWN_MS = 1200;
1456
+ type ScanRejectReason = 'cooldown' | 'bad-check-digit';
1457
+ interface ScanOfferResult {
1458
+ accepted: boolean;
1459
+ reason?: ScanRejectReason;
981
1460
  }
982
- /**
983
- * Adds `pos_orders` to `db` and resolves once no order of an older version is left to migrate.
984
- * On DM4 it rejects after the migration has stopped and closes the collection. It rejects with
985
- * `PosOrderOpenClosedError` when the database is closing. `closeWaitMs` is for tests only.
986
- * See `openMigratedCollection` for the migration and close mechanism.
987
- */
988
- declare function addPosOrderCollection(db: RxDatabase, closeWaitMs?: number): Promise<RxCollection<PosOrder>>;
1461
+ interface ScanSessionOptions {
1462
+ onAccept: (code: string, symbology?: string) => void;
1463
+ cooldownMs?: number;
1464
+ now?: () => number;
1465
+ }
1466
+ interface ScanSession {
1467
+ offer: (code: string, symbology?: string) => ScanOfferResult;
1468
+ reset: () => void;
1469
+ }
1470
+ /** Report the printed UPC-A digits by dropping an implied zero from labelled
1471
+ * EAN-13/UPC reads. Unlabelled reads and printed 8-digit UPC-E stay unchanged. */
1472
+ declare function normalizeRetailCode(code: string, symbology?: string): string;
1473
+ /** Validate EAN-13/EAN-8/UPC-A check digits; non-retail-length inputs pass. */
1474
+ declare function hasValidRetailCheckDigit(code: string): boolean;
1475
+ /** The other printing of the same UPC-A: `0`+12 digits -> the 12; 12 digits -> `0`+12; anything else undefined.
1476
+ * Ported from the UPC-A <-> EAN-13 branch of v2 barcodeMatchCandidates (sync-core/src/barcodeResolve.ts).
1477
+ * Match the twin against barcodes only, never SKUs (v2 BARCODE_SYMBOLOGY_FIELDS excludes sku). */
1478
+ declare function retailCodeTwin(code: string): string | undefined;
1479
+ declare function createScanSession(options: ScanSessionOptions): ScanSession;
989
1480
 
990
- /**
991
- * Returns this device's id (a UUIDv7), stored under `key` in `storage` (web storage, or an app's
992
- * equivalent) and minted on first use; medusapos passes `'medusapos.register_id'`. With no storage,
993
- * or one that throws on read or write, it falls back to one id per process.
1481
+ interface UseBarcodeScannerOptions {
1482
+ onScan: (code: string) => void;
1483
+ /** Listen only while true (default true). */
1484
+ enabled?: boolean;
1485
+ threshold?: number;
1486
+ prefix?: string;
1487
+ suffix?: string;
1488
+ minChars?: number;
1489
+ }
1490
+ /** Listen for keyboard-wedge scans outside INPUT/TEXTAREA, with a minimum length gate.
1491
+ * Ported from WCPOS v2 packages/core/src/screens/main/hooks/barcodes/use-barcode-detection.ts (monorepo 5ac185b0).
1492
+ * @example
1493
+ * useBarcodeScanner({ onScan: (code) => {
1494
+ * const twin = retailCodeTwin(code);
1495
+ * const entry = findEntryByCode(entries, code)
1496
+ * ?? (twin ? entries.find(({ variant }) => variant.barcode === twin) : undefined);
1497
+ * if (entry) addEntryToCart(builder, entry, traits, currency);
1498
+ * else setSearchTerm(code); // searchProducts returns just the exact barcode/SKU matches
1499
+ * } });
994
1500
  */
995
- declare function getDeviceId(storage: {
996
- getItem(key: string): string | null;
997
- setItem(key: string, value: string): void;
998
- } | null, key: string): string;
1501
+ declare function useBarcodeScanner(options: UseBarcodeScannerOptions): void;
1502
+
1503
+ /** The transport a payment terminal is reached over: hardware-neutral, not tied to any backend. */
1504
+ type PaymentTransport = 'bluetooth' | 'usb' | 'network' | 'tap_to_pay';
1505
+ type TenderView = 'select' | 'amount' | 'cancel';
1506
+ type TenderLineId = string | number;
1507
+ type TenderPlan = {
1508
+ kind: 'even';
1509
+ ways: number;
1510
+ from: number;
1511
+ } | {
1512
+ kind: 'fixed';
1513
+ firstMinor: number;
1514
+ title: string | null;
1515
+ from: number;
1516
+ } | {
1517
+ kind: 'items';
1518
+ lineIds: TenderLineId[];
1519
+ firstMinor: number;
1520
+ ways: number;
1521
+ from: number;
1522
+ };
1523
+ type SplitTab = 'even' | 'amount' | 'percent' | 'item';
1524
+ interface TenderState {
1525
+ view: TenderView;
1526
+ /** Method id being tendered; null in the 'select' and 'cancel' views. */
1527
+ methodId: string | null;
1528
+ readerId: string | null;
1529
+ transport: PaymentTransport | null;
1530
+ /** Keypad entry in minor units. */
1531
+ entryMinor: number;
1532
+ /** False until the cashier has touched the keypad since the entry was pre-filled. */
1533
+ entryDirty: boolean;
1534
+ plan: TenderPlan | null;
1535
+ splitView: boolean;
1536
+ splitTab: SplitTab;
1537
+ pickedLineIds: TenderLineId[];
1538
+ linesPaidBy: Record<TenderLineId, string[]>;
1539
+ }
1540
+ /** '0'..'9' plus the two edit keys. There is deliberately no decimal key: digits shift in from the right. */
1541
+ type TenderKey = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'clear' | 'backspace';
1542
+ type TenderAction = {
1543
+ type: 'pick-method';
1544
+ methodId: string;
1545
+ prefillMinor: number;
1546
+ readerId: string | null;
1547
+ transport?: PaymentTransport | null;
1548
+ } | {
1549
+ type: 'pick-transport';
1550
+ transport: PaymentTransport;
1551
+ } | {
1552
+ type: 'pick-reader';
1553
+ readerId: string | null;
1554
+ } | {
1555
+ type: 'tender-started';
1556
+ } | {
1557
+ type: 'key';
1558
+ key: TenderKey;
1559
+ } | {
1560
+ type: 'set-entry';
1561
+ minor: number;
1562
+ } | {
1563
+ type: 'back';
1564
+ } | {
1565
+ type: 'tender-recorded';
1566
+ rowsSinceFrom: {
1567
+ title: string;
1568
+ amountMinor: number;
1569
+ }[];
1570
+ /** The order's balance once this row counts, so the next leg can be pre-typed. */
1571
+ balanceMinor: number;
1572
+ } | {
1573
+ type: 'open-split';
1574
+ } | {
1575
+ type: 'close-split';
1576
+ } | {
1577
+ type: 'set-split-tab';
1578
+ tab: SplitTab;
1579
+ } | {
1580
+ type: 'toggle-split-line';
1581
+ lineId: TenderLineId;
1582
+ } | {
1583
+ type: 'set-plan';
1584
+ plan: TenderPlan;
1585
+ balanceMinor: number;
1586
+ } | {
1587
+ type: 'clear-plan';
1588
+ balanceMinor: number;
1589
+ } | {
1590
+ type: 'arm-custom';
1591
+ } | {
1592
+ type: 'request-cancel';
1593
+ } | {
1594
+ type: 'reset';
1595
+ };
1596
+ /** $9,999,999.99 at two decimals — a till will never legitimately take more, and it stops a stuck key running the display off the screen. */
1597
+ declare const MAX_TENDER_MINOR = 999999999;
1598
+ declare const initialTenderState: TenderState;
1599
+ /**
1600
+ * Reducer init. An order whose method the checkout store already holds — a URL seed, or a
1601
+ * tab the cashier is coming back to — reopens its keypad prefilled with the balance, exactly
1602
+ * as a tap on that tile would. Everything else starts from scratch.
1603
+ */
1604
+ declare function initTenderState({ methodId, balanceMinor, }: {
1605
+ methodId: string | null;
1606
+ balanceMinor: number;
1607
+ }): TenderState;
1608
+ declare function tenderReducer(state: TenderState, action: TenderAction): TenderState;
1609
+ /**
1610
+ * What the leg applies to the order. Cash may be tendered above the balance;
1611
+ * the excess is change, never an overpayment on the order.
1612
+ */
1613
+ declare function appliedMinor(entryMinor: number, balanceMinor: number): number;
1614
+ /** Change handed back. Zero for any tender whose method cannot give change. */
1615
+ declare function changeMinor(entryMinor: number, appliedAmountMinor: number, givesChange: boolean): number;
1616
+ /**
1617
+ * Quick tendered amounts under a cash keypad: the balance itself, then the next
1618
+ * whole 5, 10 and 50 above it. Deduped, ascending, never below the balance.
1619
+ * The caller supplies those major-unit steps already scaled to minor units.
1620
+ */
1621
+ declare function quickTenderedAmounts(balanceMinor: number, stepsMinor: readonly number[]): number[];
1622
+ /**
1623
+ * Even split shares. Returns the next tender's share, rounded half-up to the
1624
+ * minor unit; the last leg remains whatever balance is left.
1625
+ */
1626
+ declare function evenSplitShareMinor(balanceMinor: number, ways: number): number;
1627
+ /** Completion is derived from payment rows, never an extra counter in the reducer. */
1628
+ declare function activePlan(plan: TenderPlan | null, taken: number, balanceMinor: number): TenderPlan | null;
1629
+ interface PlanLeg {
1630
+ minor: number;
1631
+ state: 'done' | 'now' | 'todo' | 'rest';
1632
+ title?: string;
1633
+ }
1634
+ /** Label pieces stay untranslated here; the flow supplies localized copy and item names. */
1635
+ declare function planLegs(plan: TenderPlan, rowsSinceFrom: {
1636
+ minor: number;
1637
+ title: string;
1638
+ }[], balanceMinor: number): {
1639
+ legs: PlanLeg[];
1640
+ thisPaymentMinor: number;
1641
+ label: {
1642
+ n: number;
1643
+ ways: number;
1644
+ rest: boolean;
1645
+ title: string | null;
1646
+ };
1647
+ };
1648
+
1649
+ interface DriverCapabilities {
1650
+ /** `harness`: the till lists readers and connects; `sdk_ui`: the vendor SDK shows its own picker. */
1651
+ discovery: 'harness' | 'sdk_ui';
1652
+ /** `app`: the till can cancel a collection; `on_device`: only the reader can. */
1653
+ cancel: 'app' | 'on_device';
1654
+ refund: boolean;
1655
+ }
1656
+ interface ReaderInfo {
1657
+ id: string;
1658
+ label: string;
1659
+ model?: string;
1660
+ serial?: string;
1661
+ battery?: number | null;
1662
+ transport: PaymentTransport;
1663
+ }
1664
+ interface DriverStatus {
1665
+ connection: 'disconnected' | 'discovering' | 'connecting' | 'updating' | 'connected';
1666
+ reader: ReaderInfo | null;
1667
+ progress?: number | null;
1668
+ pairingCode?: string | null;
1669
+ message?: string | null;
1670
+ }
1671
+ type DriverAvailability = {
1672
+ available: true;
1673
+ } | {
1674
+ available: false;
1675
+ reason: 'web' | 'permission' | 'bluetooth_off' | 'not_logged_in' | 'unsupported';
1676
+ };
1677
+ interface CollectInput {
1678
+ /** The payment leg's id; a driver may use it to make its provider reference. */
1679
+ legId: string;
1680
+ /** The leg's amount in minor units of `currency`. */
1681
+ amountMinor: number;
1682
+ /** ISO 4217 code. */
1683
+ currency: string;
1684
+ method: PaymentMethodDescriptor;
1685
+ transport: PaymentTransport;
1686
+ /** Provider data from the server (credentials, an intent), or null. */
1687
+ handoff: Record<string, unknown> | null;
1688
+ /** The amount a tip may be taken on, in minor units; null when the leg takes no tip. */
1689
+ tipEligibleMinor: number | null;
1690
+ }
1691
+ type CollectOutcome = 'captured' | 'authorized' | 'declined' | 'cancelled';
1692
+ interface CollectResult {
1693
+ outcome: CollectOutcome;
1694
+ /** The provider's own references for the payment (opaque to the till). */
1695
+ providerRefs: Record<string, unknown>;
1696
+ /** Card details to print (brand, last four and so on). */
1697
+ receipt: Record<string, unknown>;
1698
+ /** What the reader charged in minor units, tip included; null when the driver cannot say. */
1699
+ amountMinor: number | null;
1700
+ transport: PaymentTransport;
1701
+ /** Why a leg was declined or cancelled; `'timed_out'` when the reader's own collect window ran out. */
1702
+ failureReason?: string | null;
1703
+ }
1704
+ interface DriverStatusSource {
1705
+ subscribe(listener: (status: DriverStatus) => void): () => void;
1706
+ get(): DriverStatus;
1707
+ }
1708
+ interface PaymentDriver {
1709
+ /** Matches a payment method's `capture.provider`. */
1710
+ readonly provider: string;
1711
+ readonly capabilities: DriverCapabilities;
1712
+ availability(): DriverAvailability;
1713
+ /** Scan for readers; `until` names a reader id the caller waits for, so a driver may stop early. */
1714
+ discoverReaders?(transport: PaymentTransport, options?: {
1715
+ until?: string;
1716
+ }): Promise<ReaderInfo[]>;
1717
+ connect?(reader: ReaderInfo, handoff: Record<string, unknown> | null): Promise<void>;
1718
+ disconnect?(): Promise<void>;
1719
+ collect(input: CollectInput): Promise<CollectResult>;
1720
+ cancel?(): Promise<void>;
1721
+ status$: DriverStatusSource;
1722
+ }
1723
+
1724
+ interface PaymentDriverRegistry {
1725
+ /** Adds the driver under its `provider`, replacing any driver already there, then notifies subscribers. */
1726
+ register(driver: PaymentDriver): void;
1727
+ get(provider: string | null): PaymentDriver | undefined;
1728
+ has(provider: string | null): boolean;
1729
+ list(): PaymentDriver[];
1730
+ /** Called after every `register`; returns an unsubscribe function. */
1731
+ subscribe(listener: () => void): () => void;
1732
+ }
1733
+ declare function createPaymentDriverRegistry(): PaymentDriverRegistry;
1734
+ /** The driver for a method taken on a device: `capture.mode === 'device'` and a driver registered under `capture.provider`. */
1735
+ declare function driverForMethod(registry: PaymentDriverRegistry, method: PaymentMethodDescriptor | null | undefined): PaymentDriver | undefined;
1736
+
1737
+ declare const SIMULATED_PROVIDER = "simulated";
1738
+ declare const SIMULATED_TIMING: {
1739
+ readonly connectMs: 300;
1740
+ readonly decisionMs: 500;
1741
+ readonly readWindowMs: 1500;
1742
+ };
1743
+ type SimulatedReaderId = 'sim-approve' | 'sim-decline' | 'sim-cancel' | 'sim-timeout' | 'sim-tip' | 'sim-tap';
1744
+ interface SimulatedDriverOptions {
1745
+ /** Override any of the delays in SIMULATED_TIMING. */
1746
+ timing?: Partial<{
1747
+ connectMs: number;
1748
+ decisionMs: number;
1749
+ readWindowMs: number;
1750
+ }>;
1751
+ /** Timer functions; default to globalThis.setTimeout / clearTimeout. */
1752
+ timers?: {
1753
+ setTimeout: (fn: () => void, ms: number) => unknown;
1754
+ clearTimeout: (handle: unknown) => void;
1755
+ };
1756
+ /** What `availability()` returns; default `{ available: true }`. */
1757
+ availability?: DriverAvailability;
1758
+ }
1759
+ declare function createSimulatedDriver(options?: SimulatedDriverOptions): PaymentDriver;
1760
+
1761
+ /**
1762
+ * The printing seam. Ported from WCPOS v2 `packages/printer/src/types.ts` (monorepo main): v2's
1763
+ * `PrinterTransport` has `printRaw(bytes)` and `printHtml(html)`; here one `print(job)` takes a job that
1764
+ * carries HTML, bytes or both, and each transport prints what it can.
1765
+ */
1766
+
1767
+ type PrintJobKind = 'receipt' | 'report' | 'test';
1768
+ interface PrintJob {
1769
+ id: string;
1770
+ kind: PrintJobKind;
1771
+ /** Rendered HTML, for the system dialog (see `renderReceiptHtml`). */
1772
+ html?: string;
1773
+ /** Pre-encoded printer bytes (ESC/POS and the like), for a raw transport. */
1774
+ bytes?: Uint8Array;
1775
+ /** The receipt itself, for a transport that lays it out (`createEscPosTransport`). */
1776
+ receipt?: ReceiptData;
1777
+ }
1778
+ /** `unsupported`: this transport cannot print the job; `unavailable`: the platform has no way to print; `failed`: the print went wrong. */
1779
+ type PrintErrorCode = 'unsupported' | 'unavailable' | 'failed';
1780
+ declare class PrintError extends Error {
1781
+ readonly code: PrintErrorCode;
1782
+ constructor(code: PrintErrorCode, message: string, options?: {
1783
+ cause?: unknown;
1784
+ });
1785
+ }
1786
+ declare function toPrintError(error: unknown): PrintError;
1787
+ interface PrintTransport {
1788
+ /** For logs, e.g. `system-print-web`. */
1789
+ readonly name: string;
1790
+ /** Resolves once the job is handed to the printer or dialog; rejects with a `PrintError`. */
1791
+ print(job: PrintJob): Promise<void>;
1792
+ disconnect?(): Promise<void>;
1793
+ }
1794
+
1795
+ /**
1796
+ * One serial queue per printer id. Ported from WCPOS v2 `packages/printer/src/printer-service.ts` (monorepo
1797
+ * main), which keeps a `PQueue({ concurrency: 1 })` per profile because one shared queue let a stalled printer
1798
+ * stall the till (its gotcha N44). Here a promise chain per printer id does the same without p-queue.
1799
+ */
1800
+
1801
+ /** v2's queue id for the OS print dialog, which is one shared resource on the device. */
1802
+ declare const SYSTEM_PRINTER_ID = "system";
1803
+ interface PrintQueueState {
1804
+ printerId: string;
1805
+ /** The id of the job printing now, or null. */
1806
+ running: string | null;
1807
+ /** Ids of the jobs waiting, in the order they will print. */
1808
+ queued: string[];
1809
+ }
1810
+ interface PrintQueueOptions {
1811
+ transportFor: (printerId: string) => PrintTransport | Promise<PrintTransport>;
1812
+ }
1813
+ interface PrintQueue {
1814
+ /** Resolves when this job has printed; rejects with a `PrintError`. A failure never holds up the next job. */
1815
+ print(printerId: string, job: PrintJob): Promise<void>;
1816
+ state(printerId: string): PrintQueueState;
1817
+ subscribe(listener: (state: PrintQueueState) => void): () => void;
1818
+ }
1819
+ declare function createPrintQueue({ transportFor }: PrintQueueOptions): PrintQueue;
1820
+
1821
+ /**
1822
+ * Printers set up on this device. Local only, never replicated; the app adds the collection as
1823
+ * `printer_profiles`. Ported from WCPOS v2 `packages/database/src/collections/schemas/printer-profiles.ts`
1824
+ * (monorepo main, version 0, device-local). Left out: v2's cloud fields (`cloudPrinterId`, `cloudProvider`,
1825
+ * `connectionType: 'cloud'`; vendor services stay out of the MIT packages, ADR-084 decision 2), its vendor-SDK and
1826
+ * encoder-library hints (`nativeInterfaceType`, `printerModel`), `emitEscPrintMode` and `fullReceiptRaster`.
1827
+ * v2's schema defaults are kept as comments, not schema `default`s; a reader treats a missing field as its default.
1828
+ */
1829
+
1830
+ declare const PRINTER_PROFILES_COLLECTION = "printer_profiles";
1831
+ interface PrinterProfile {
1832
+ id: string;
1833
+ /** User-assigned, e.g. "Front counter". */
1834
+ name: string;
1835
+ connectionType: 'system' | 'network' | 'bluetooth' | 'usb';
1836
+ /** Default `generic`. */
1837
+ vendor?: 'epson' | 'star' | 'generic';
1838
+ /** IP address, Bluetooth address or USB path. */
1839
+ address?: string;
1840
+ /** Default 9100. */
1841
+ port?: number;
1842
+ /** Default `esc-pos`. */
1843
+ language?: 'esc-pos' | 'star-prnt' | 'star-line';
1844
+ /** Characters per line: 32 for 58 mm, 42 or 48 for 80 mm. Default 42. */
1845
+ columns?: number;
1846
+ /** The encoder's code page name, e.g. `cp437`; absent lets the encoder choose. */
1847
+ codePage?: string;
1848
+ /** Default true. */
1849
+ autoCut?: boolean;
1850
+ /** Default false. */
1851
+ autoOpenDrawer?: boolean;
1852
+ /** Default `pin2` (drawer 1). */
1853
+ drawerConnector?: 'pin2' | 'pin5';
1854
+ isDefault?: boolean;
1855
+ /** A platform printer (the print dialog) that cannot be deleted. */
1856
+ isBuiltIn?: boolean;
1857
+ }
1858
+ declare const printerProfileSchema: RxJsonSchema<PrinterProfile>;
1859
+ declare function printerProfileCollection(): {
1860
+ readonly schema: RxJsonSchema<PrinterProfile>;
1861
+ };
1862
+ type PrinterProfileCollection = RxCollection<PrinterProfile>;
1863
+ declare function addPrinterProfileCollection(db: RxDatabase): Promise<PrinterProfileCollection>;
1864
+
1865
+ /**
1866
+ * Prints rendered HTML through the platform print dialog. Ported from WCPOS v2 (monorepo main)
1867
+ * `packages/printer/src/transport/system-print-adapter.web.ts` (hidden iframe, `print()`, `afterprint`) and
1868
+ * `system-print-adapter.ts` (native, `expo-print`). On native the app injects `printHtml` (for example
1869
+ * `(html) => Print.printAsync({ html })`), so this package takes no native dependency.
1870
+ */
1871
+
1872
+ /** v2's waits: let the frame render, give images 5 s, and settle after 60 s if `afterprint` never fires. */
1873
+ declare const SYSTEM_PRINT_TIMING: {
1874
+ renderDelayMs: number;
1875
+ imageTimeoutMs: number;
1876
+ afterPrintTimeoutMs: number;
1877
+ removeDelayMs: number;
1878
+ };
1879
+ type SystemPrintTiming = typeof SYSTEM_PRINT_TIMING;
1880
+ interface SystemPrintTransportOptions {
1881
+ /** Native: prints HTML through the OS dialog. When given, the iframe path is not used. */
1882
+ printHtml?: (html: string) => Promise<void>;
1883
+ /** Web: the document to print from; defaults to `globalThis.document`. */
1884
+ document?: Document;
1885
+ timing?: Partial<SystemPrintTiming>;
1886
+ }
1887
+ declare function createSystemPrintTransport(options?: SystemPrintTransportOptions): PrintTransport;
1888
+
1889
+ /**
1890
+ * Character tables for ESC/POS text. WCPOS v2 (monorepo main) leaves the code page to
1891
+ * `@point-of-sale/receipt-printer-encoder`; here two fixed tables cover Latin receipts without a dependency.
1892
+ * `high` holds the characters for bytes 0x80-0xFF; `id` is the `ESC t n` table number.
1893
+ */
1894
+ declare const ESCPOS_CODE_PAGES: {
1895
+ readonly cp437: {
1896
+ readonly id: 0;
1897
+ readonly high: string;
1898
+ };
1899
+ readonly cp858: {
1900
+ readonly id: 19;
1901
+ readonly high: string;
1902
+ };
1903
+ };
1904
+ interface EscPosCodePage {
1905
+ id: number;
1906
+ high: string;
1907
+ }
1908
+
1909
+ /**
1910
+ * A small ESC/POS command builder. The command bytes follow WCPOS v2 (monorepo main): `escpos-text.ts`
1911
+ * opens every job with `ESC @` then `ESC M 0` (Font A, so the profile's column count holds whatever the
1912
+ * printer's memory switch says; v2 gotcha N39), and `render-escpos.ts` `writeCut` cuts with `GS V 0x41|0x42 0`
1913
+ * (feed to the cutter, then cut). Text goes through `foldText`, so no multibyte UTF-8 ever reaches the printer.
1914
+ */
1915
+
1916
+ interface EscPosBuilder {
1917
+ /** `ESC @` (reset), then `ESC M 0` (Font A). */
1918
+ init(): EscPosBuilder;
1919
+ /** `ESC t n`: select the builder's code page. */
1920
+ codePage(): EscPosBuilder;
1921
+ align(mode: 'left' | 'center' | 'right'): EscPosBuilder;
1922
+ bold(on: boolean): EscPosBuilder;
1923
+ /** `GS ! n`: character width and height multipliers, 1-8 each. */
1924
+ size(width: number, height: number): EscPosBuilder;
1925
+ /** Folded to the code page, one byte per character; `\n` is LF. */
1926
+ text(value: string): EscPosBuilder;
1927
+ /** `ESC d n`: print and feed n lines. */
1928
+ feed(lines: number): EscPosBuilder;
1929
+ cut(type?: 'full' | 'partial'): EscPosBuilder;
1930
+ /** `ESC p m 25 250`: a drawer kick, on 50 ms and off 500 ms; m 0 for pin 2, 1 for pin 5. */
1931
+ pulse(connector?: DrawerConnector): EscPosBuilder;
1932
+ bytes(): Uint8Array;
1933
+ }
1934
+ declare function escpos(page?: EscPosCodePage): EscPosBuilder;
1935
+
1936
+ interface EncodeEscPosOptions extends ReceiptTemplateOptions {
1937
+ /** Characters per line: 32 for 58 mm, 42 or 48 for 80 mm. */
1938
+ columns: number;
1939
+ /** `cp437` (the default, also for an unknown name) or `cp858`. */
1940
+ codePage?: string;
1941
+ /** Default true: a partial cut after the feed. */
1942
+ cut?: boolean;
1943
+ /** Default false: kick the drawer before the cut. */
1944
+ openDrawer?: boolean;
1945
+ /** Default `pin2`. */
1946
+ drawerConnector?: DrawerConnector;
1947
+ }
1948
+ declare function encodeEscPos(receipt: ReceiptData, options: EncodeEscPosOptions): Uint8Array;
1949
+
1950
+ /**
1951
+ * A `PrintTransport` that writes ESC/POS bytes to a sink the app supplies (WebUSB, WebSerial, a TCP socket,
1952
+ * Bluetooth). It holds no device code; ADR-084 decision 2 keeps vendor SDKs out of the MIT packages. Run it
1953
+ * through `createPrintQueue`, like the system transport, so one printer prints one job at a time.
1954
+ */
1955
+
1956
+ interface EscPosSink {
1957
+ write(bytes: Uint8Array): Promise<void>;
1958
+ }
1959
+ interface EscPosTransportOptions {
1960
+ sink: EscPosSink;
1961
+ profile: PrinterProfile;
1962
+ format?: Pick<ReceiptTemplateOptions, 'formatMoney' | 'formatDate' | 'paymentLabel'>;
1963
+ }
1964
+ declare function createEscPosTransport({ sink, profile, format }: EscPosTransportOptions): PrintTransport;
1965
+
1966
+ /** RFC 9562 UUIDv7: monotonic with no arguments; stateless with an explicit timestamp or random source. */
1967
+ declare function uuidv7(now?: number, randomBytes?: (n: number) => Uint8Array): string;
1968
+
1969
+ interface FinalizeOptions {
1970
+ localWarnings?: PosOrderLocalWarning[];
1971
+ registerId?: string;
1972
+ cashierRef?: string;
1973
+ now?: Date;
1974
+ /** Tests only: replaces uuidv7. Every id it returns must be at most 255 characters with no NUL (order.create's bound). */
1975
+ newId?: () => string;
1976
+ /** The store's `order.create` capability (ADR-062); `undefined` is treated as 1. */
1977
+ capabilities?: ServerCapabilities;
1978
+ }
1979
+ /**
1980
+ * Turns a fully paid builder Order into a pending PosOrder without mutating it. The PosOrder holds the sent form,
1981
+ * frozen: line names and v3 discount labels are cut to PAYLOAD_STRING_MAX with NUL stripped (`cutText`), and a
1982
+ * customer email or id the shape check would refuse is left out, so `toOrderCreateEnvelope` sends it unchanged.
1983
+ */
1984
+ declare function finalizeOrder(order: Order, options?: FinalizeOptions): PosOrder;
1985
+
1986
+ declare class UnsupportedOrderVersionError extends Error {
1987
+ readonly needed: number;
1988
+ readonly supported: number;
1989
+ readonly code = "UNSUPPORTED_ORDER_VERSION";
1990
+ constructor(needed: number, supported: number);
1991
+ }
1992
+ /**
1993
+ * Builds the ADR-038 order.create envelope for a PosOrder. It sends the stored order unchanged, so every resend of
1994
+ * an order is byte-identical, and an order stored by an older till goes out exactly as that till sent it:
1995
+ * `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
1996
+ * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
1997
+ * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
1998
+ * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
1999
+ * A sale with a note goes as version 7 when capped at 7 or more and it has figures; otherwise the note is not sent.
2000
+ * Orders with Any picks (#495) need version 6 too, carrying a line's `anyAttributes`, and coupons only when they have some.
2001
+ */
2002
+ declare function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt?: number, options?: {
2003
+ maxVersion?: number;
2004
+ }): OrderCreateEnvelope;
2005
+
2006
+ /**
2007
+ * Version 1 adds the optional `sessionId` (ADR-032); nothing else changed from version 0.
2008
+ * Version 2 adds three optional fields and changes nothing else: `lateSessionId` (ADR-032, late
2009
+ * sale), and ADR-065's `display` and `taxByRate`, declared ahead of the job that writes them so a
2010
+ * till migrates once. Create the collection with `posOrderCollection()`, never with this schema
2011
+ * alone: RxDB refuses a version above 0 without its migration strategies.
2012
+ * Version 3 adds an index on `sessionId` (with its `maxLength`), and the optional `sentVersion` and `downgradedFrom` (the outbox's version fallback), and changes nothing else.
2013
+ * Version 4 adds the optional `localWarnings` and `serverFailures` (the outbox's stuck clock start, latest reason and
2014
+ * isolation, restored when an outbox starts), and changes nothing else.
2015
+ * Version 5 lets `sentVersion` and `downgradedFrom` be 4 (order.create version 4, #286), and changes nothing else. Its
2016
+ * migration sets a row's missing `sentVersion` to its content version, the version any earlier attempt went out at.
2017
+ * Like version 4 (ADR-069), it is one-way: an older build shows no orders.
2018
+ * Version 6 adds `taxRounding`, the strategy the sale's figures were computed with (#287; never sent), and changes
2019
+ * nothing else. Its migration sets it on every older row. It is one-way like version 5.
2020
+ * Version 7 adds `saleId`, the sale order's id (ADR-072; never sent), and changes nothing else. Its migration is the
2021
+ * identity: older orders have no `saleId`. It is one-way like version 6.
2022
+ * Version 8 adds fees, shipping, custom lines (ADR-075) and the woocommerce tax rounding (ADR-076), and changes nothing else.
2023
+ * It also stores the WooCommerce 6dp net (`netMicros`) under the woocommerce rounding (ADR-076 amendment).
2024
+ * Its migration is the identity. It is one-way like version 7.
2025
+ * Version 9 adds the order's `coupons` and the receipt's `display.coupons` (ADR-077 d2), and a line's `attributes` (#495)
2026
+ * 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.
2027
+ * `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them only at version 6.
2028
+ * Its migration is the identity. It is one-way like version 8.
2029
+ * Version 10 adds a line's `anyAttributes` (#495 c/d) and changes nothing else. Its migration is the identity. It is one-way like version 9.
2030
+ * Version 11 lets `sentVersion` and `downgradedFrom` be 7 (order.create version 7, ADR-083), and changes nothing else. Its migration is the identity. It is one-way like version 10.
2031
+ */
2032
+ declare const posOrderSchema: RxJsonSchema<PosOrder>;
2033
+ /**
2034
+ * The `pos_orders` collection config, with its migration strategies. Open the collection with
2035
+ * `addPosOrderCollection(db)`, which uses this and settles the migration safely; adding this config
2036
+ * directly leaves RxDB's own open path. `pos_orders` holds sales not yet sent, so no step may drop a
2037
+ * document: versions 1 and 2 only add optional fields, so every order from version 0 or 1 passes
2038
+ * unchanged.
2039
+ *
2040
+ * Within one run, RxDB 16.21 keeps an order that fails the new schema's validation: with a
2041
+ * validating storage the migration stops with DM4 and the order stays in the older version's
2042
+ * storage; without one it is copied as is. **Across runs, RxDB's own open path can lose it**: a
2043
+ * failed run can leave its checkpoint past that order, and the next run then removes the older
2044
+ * version's storage without copying it. `addPosOrderCollection` resets that checkpoint, so use it
2045
+ * (`migration.test.ts`).
2046
+ */
2047
+ declare function posOrderCollection(): {
2048
+ schema: RxJsonSchema<PosOrder>;
2049
+ migrationStrategies: MigrationStrategies;
2050
+ };
2051
+
2052
+ /** `addPosOrderCollection`'s logger: attach a sink to see, for example, the status writes a closing open dropped. */
2053
+ declare const posOrdersLogger: Logger;
2054
+ /**
2055
+ * `addPosOrderCollection` stopped, before any further write, because its database is closing: it
2056
+ * was called once `close()` had begun, the close cancelled its migration (RxDB 17.5), or the close
2057
+ * stopped waiting for it (after `POS_ORDER_MIGRATION_CLOSE_WAIT_MS`). No order is lost: reopen the
2058
+ * database and call it again.
2059
+ */
2060
+ declare class PosOrderOpenClosedError extends Error {
2061
+ readonly databaseName: string;
2062
+ readonly code = "POS_ORDER_OPEN_CLOSED";
2063
+ constructor(databaseName: string);
2064
+ }
2065
+ /**
2066
+ * Adds `pos_orders` to `db` and resolves once no order of an older version is left to migrate.
2067
+ * On DM4 it rejects after the migration has stopped and closes the collection. It rejects with
2068
+ * `PosOrderOpenClosedError` when the database is closing. `closeWaitMs` is for tests only.
2069
+ * See `openMigratedCollection` for the migration and close mechanism.
2070
+ */
2071
+ declare function addPosOrderCollection(db: RxDatabase, closeWaitMs?: number): Promise<RxCollection<PosOrder>>;
2072
+
2073
+ /**
2074
+ * Returns this device's id (a UUIDv7), stored under `key` in `storage` (web storage, or an app's
2075
+ * equivalent) and minted on first use; medusapos passes `'medusapos.register_id'`. With no storage,
2076
+ * or one that throws on read or write, it falls back to one id per process.
2077
+ */
2078
+ declare function getDeviceId(storage: {
2079
+ getItem(key: string): string | null;
2080
+ setItem(key: string, value: string): void;
2081
+ } | null, key: string): string;
999
2082
 
1000
2083
  /**
1001
2084
  * The orders a cashier must look at: rejected, applied with a known warning, taken after their
@@ -1279,11 +2362,14 @@ declare const backToSelling: (sessions: RegisterSessionCollection, id: string) =
1279
2362
  * Closes the session with its counted tenders (minor units); `timezone` dates a session opened
1280
2363
  * without a business day. `approvedBy`, the manager who approved the count, is written in the same
1281
2364
  * write as the close, and a repeat close keeps the first close's approver as it keeps its count.
2365
+ * `approval`, the store's opaque proof (ADR-082), is written to `approver_token` in the same
2366
+ * write; it never reaches the closure or its breakdowns.
1282
2367
  */
1283
2368
  declare function closeSession(sessions: RegisterSessionCollection, id: string, input: {
1284
2369
  counted: Record<string, number>;
1285
2370
  closedBy?: string;
1286
2371
  approvedBy?: string;
2372
+ approval?: string;
1287
2373
  timezone?: string;
1288
2374
  }): Promise<rxdb.RxDocument<RegisterSession, {}, unknown>>;
1289
2375
  /**
@@ -1363,6 +2449,13 @@ declare function isReopened(order: Pick<PosOrder, 'syncStatus' | 'reopenedAt'>):
1363
2449
  /** Payments count on the successor, so the refused order counts nowhere (ADR-077 R5 amended). Only this list is considered. */
1364
2450
  declare function replacedOrderIds(orders: readonly Pick<PosOrder, 'id' | 'saleId' | 'syncStatus'>[]): Set<string>;
1365
2451
 
2452
+ type NoteDelivery = 'none' | 'pending' | 'sent' | 'not_sent';
2453
+ /**
2454
+ * ADR-083 condition 2: a note goes only at order.create 7, and the outbox stores the version every attempt goes out at
2455
+ * (`sentVersion`, lowered on a downgrade), so a sale whose stored version is below 7 went without its note.
2456
+ */
2457
+ declare function noteDelivery(order: Pick<PosOrder, 'note' | 'sentVersion'>): NoteDelivery;
2458
+
1366
2459
  type SaleContent = Pick<PosOrder, 'totalMinor' | 'currency' | 'lines' | 'payments'>;
1367
2460
  /**
1368
2461
  * Whether two orders carry the same money-bearing content: `totalMinor` and `currency`; each line's
@@ -1462,6 +2555,10 @@ declare const overThreshold: (variance: number, thresholdMinor?: number | null)
1462
2555
  * `closeSession` gate share (ADR-032).
1463
2556
  */
1464
2557
  declare const closeNeedsApproval: (countedCashMinor: number, expectedCashMinor: number, thresholdMinor?: number | null) => boolean;
2558
+ /** ADR-082 d3: counted minus till-expected for each key of `counted`, the variance a store approval is bound to. */
2559
+ declare const closureVariance: (counted: Record<string, number>, tillExpected: Record<string, number>) => {
2560
+ [k: string]: number;
2561
+ };
1465
2562
  /** Sums denomination face values (already minor units) by piece count. */
1466
2563
  declare const denominationTotal: (pieces: Record<number, number>) => number;
1467
2564
  /**
@@ -1553,6 +2650,27 @@ declare function deriveSettled(recorded: RecordedFigures, corrections: readonly
1553
2650
  touched: Set<string>;
1554
2651
  };
1555
2652
 
2653
+ /**
2654
+ * The opening float the open-register card suggests (v2 parity A4): the register's default float, else the cash
2655
+ * counted at the last close, else none. Port provenance: WCPOS v2 monorepo `main` `5ac185b0e`,
2656
+ * `packages/core/src/screens/main/pos/cart/open-register-card.tsx:40-50` (`defaultFloat ?? lastCount ?? null`), with
2657
+ * `seedAmount` from `packages/core/src/services/register-session/count-money.ts`. Money is TallyUI's integer
2658
+ * minor-units convention, so `seedAmount`'s rounding of four-decimal server strings has no counterpart here.
2659
+ */
2660
+
2661
+ type FloatSuggestion = {
2662
+ amountMinor: number;
2663
+ source: 'default' | 'last_count';
2664
+ } | {
2665
+ amountMinor: null;
2666
+ source: null;
2667
+ };
2668
+ /** A default float of zero is still the default, as in v2 (`??`, not `||`). */
2669
+ declare function suggestFloat({ register, lastCountedCashMinor }: {
2670
+ register?: Pick<RegisterInfo, 'defaultFloatMinor'> | null;
2671
+ lastCountedCashMinor?: number | null;
2672
+ }): FloatSuggestion;
2673
+
1556
2674
  declare function exportCsv(rows: readonly Closure[], exponent: number, t: (key: string) => string, names?: Record<string, string>, storeName?: string): string;
1557
2675
 
1558
2676
  declare const labelKeys: {
@@ -1968,7 +3086,7 @@ declare const registerCommandCollection: () => {
1968
3086
  schema: RxJsonSchema<RegisterCommand>;
1969
3087
  };
1970
3088
  type BuiltCommand = Pick<RegisterCommand, 'key' | 'type' | 'payload'> & {
1971
- version: 1 | 2;
3089
+ version: 1 | 2 | 3;
1972
3090
  };
1973
3091
  declare function sessionOpenCommand(s: RegisterSession, v2?: {
1974
3092
  deviceName?: string | null;
@@ -1978,7 +3096,11 @@ declare function sessionTransitionCommand(s: RegisterSession & {
1978
3096
  status_at: string;
1979
3097
  }): BuiltCommand;
1980
3098
  declare function movementCommand(m: CashMovement): BuiltCommand;
1981
- declare function closureCommand(c: Closure): BuiltCommand;
3099
+ /** ADR-082 d1: version 3 with the store's opaque approval at register contract 3; below 3 or unknown, version 1 and today's bytes. */
3100
+ declare function closureCommand(c: Closure, v3?: {
3101
+ registerContract?: number;
3102
+ approval?: string | null;
3103
+ }): BuiltCommand;
1982
3104
  /** Appends missing facts in dependency order; the bytes of an existing key never change. */
1983
3105
  declare function reconcileRegisterCommands({ commands, sessions, movements, closures, host, storeKey, registerId, now, observed, registerContract, deviceName }: {
1984
3106
  commands: RegisterCommandCollection;
@@ -1994,6 +3116,62 @@ declare function reconcileRegisterCommands({ commands, sessions, movements, clos
1994
3116
  deviceName?: string | null;
1995
3117
  }): Promise<string[]>;
1996
3118
 
3119
+ type SessionTarget = {
3120
+ commands: RegisterCommandCollection;
3121
+ sessions: RegisterSessionCollection;
3122
+ sessionId: string;
3123
+ now?: string;
3124
+ };
3125
+ /**
3126
+ * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
3127
+ * Superseded rejections make open/counting sessions terminal; a conflict session leaves only by an applied open or abandon (ADR-078 decision 9); terminal/unknown states stay untouched.
3128
+ * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
3129
+ * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
3130
+ */
3131
+ declare function adoptRegisterResults({ commands, sessions, registerId }: {
3132
+ commands: RegisterCommandCollection;
3133
+ sessions: RegisterSessionCollection;
3134
+ registerId: string;
3135
+ }): Promise<void>;
3136
+ declare function takeOverSession({ commands, sessions, sessionId, now, registerContract }: SessionTarget & {
3137
+ /** The store's register contract (`capabilities.register`); take over needs 2, and a missing value counts as below 2. */
3138
+ registerContract?: number;
3139
+ }): Promise<void>;
3140
+ declare function abandonSession(input: SessionTarget): Promise<void>;
3141
+ /**
3142
+ * ADR-082 d4: the store holds this session, so the app's approval route can be used for it. Its open row is applied (a
3143
+ * resumed open and an error-free duplicate are recorded applied), and it is not conflict, superseded or abandoned. A
3144
+ * closed session still counts: the route accepts it.
3145
+ */
3146
+ declare function isLiveAtStore(session: Pick<RegisterSession, 'id' | 'status'> | null | undefined, openRow: Pick<RegisterCommand, 'key' | 'syncStatus'> | null | undefined): boolean;
3147
+ /** `verified` once the store has applied a version 3 closure carrying a proof; `not_required` for a close the store does not check. */
3148
+ type ClosureApprovalStatus = 'verified' | 'unverified' | 'not_required';
3149
+ /**
3150
+ * ADR-082 d9, derived from the closure's `register.closure.submit` row; nothing is stored. A verified approval is
3151
+ * needed at register contract 3 with the store's `registerApproval`, over its threshold on cash (the store's rule).
3152
+ * Until the store applies a version 3 row with a proof, a recorded approver is `unverified`: no row yet, pending,
3153
+ * refused, or a version 1 row the store recorded without checking.
3154
+ */
3155
+ declare function closureApprovalStatus(closure: Pick<Closure, 'counted' | 'till_expected'>, row: Pick<RegisterCommand, 'syncStatus' | 'version' | 'payload'> | null | undefined, capabilities: Pick<ServerCapabilities, 'register' | 'registerApproval'> | undefined): ClosureApprovalStatus;
3156
+ /** `reapproveClosure` refused. Its message can be shown to a cashier as it is. */
3157
+ declare class RegisterReapproveError extends Error {
3158
+ readonly code: 'REGISTER_REAPPROVE_UNSUPPORTED' | 'REGISTER_REAPPROVE_NOT_REFUSED' | 'REGISTER_REAPPROVE_PROOF_MISSING';
3159
+ constructor(code: 'REGISTER_REAPPROVE_UNSUPPORTED' | 'REGISTER_REAPPROVE_NOT_REFUSED' | 'REGISTER_REAPPROVE_PROOF_MISSING');
3160
+ }
3161
+ /**
3162
+ * ADR-082 d7: requeues a closure the store refused with either approval code, in its ledger place (the same key and
3163
+ * `seq`), with a new command id (the store replays a stored refusal for the old one), version 3, the new proof and
3164
+ * approver, and every other payload field as it was. The local closure, its Z and the session are not rewritten.
3165
+ */
3166
+ declare function reapproveClosure({ commands, closureId, approval, approvedBy, registerContract, now }: {
3167
+ commands: RegisterCommandCollection;
3168
+ closureId: string;
3169
+ approval: string;
3170
+ approvedBy: string;
3171
+ registerContract?: number;
3172
+ now?: string;
3173
+ }): Promise<void>;
3174
+
1997
3175
  /** A sale is at tender, so the till can't count or close under it. Its message can be shown to a cashier as it is. */
1998
3176
  declare class RegisterTenderInProgressError extends Error {
1999
3177
  constructor();
@@ -2042,11 +3220,11 @@ interface UseRegisterSessionOptions {
2042
3220
  softwareVersion: string;
2043
3221
  /** A sale is at tender (`sale.stage.kind === 'tender'`): counting and closing refuse. */
2044
3222
  tenderInProgress: boolean;
2045
- /** The count variance, in minor units, over which the app asks for approval. */
3223
+ /** The count variance, in minor units, over which the app asks for approval. The store's `capabilities.registerApproval.thresholdMinor` wins over it (ADR-082). */
2046
3224
  varianceThreshold?: number;
2047
3225
  /** `'HH:mm'` on the device's clock; an open session after it is `overdue`. */
2048
3226
  expectedCloseTime?: string;
2049
- /** The cashier may not see expected figures while counting. */
3227
+ /** The cashier may not see expected figures while counting: pass `useCashier(connector, context).blind` (no `viewReports`). */
2050
3228
  blind?: boolean;
2051
3229
  /** The closure's register name, and a person id's display name. */
2052
3230
  labels?: {
@@ -2054,6 +3232,17 @@ interface UseRegisterSessionOptions {
2054
3232
  resolveCashierName?: (id: string) => string;
2055
3233
  };
2056
3234
  }
3235
+ /** ADR-082 d7: a closure the store refused with either approval code, for the app's "Manager approval needed again" card. */
3236
+ interface ApprovalNeeded {
3237
+ closureId: string;
3238
+ sessionId: string;
3239
+ /** The variance to send to the approval route: the refusal's, else counted minus tillExpected from the row. */
3240
+ variance: Record<string, number>;
3241
+ code: 'register_approval_required' | 'register_approval_invalid';
3242
+ reason?: string;
3243
+ /** `isLiveAtStore` for the refused closure's session: the approval route can be used for it. */
3244
+ liveAtStore: boolean;
3245
+ }
2057
3246
  declare function useRegisterSession(options: UseRegisterSessionOptions): {
2058
3247
  session: RegisterSession | null;
2059
3248
  /** The other till's live session, or the session this till is waiting to take over. */
@@ -2081,6 +3270,12 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2081
3270
  lastClosure: Closure;
2082
3271
  lastClosed: RegisterSession;
2083
3272
  varianceThreshold: number | undefined;
3273
+ /** ADR-082 d4: the store holds the current session (`isLiveAtStore`), so the app's approval route can be used. */
3274
+ liveAtStore: boolean;
3275
+ /** ADR-082 d7: a closure the store refused with either approval code, or `null`; recover it with `actions.reapproveClosure`. */
3276
+ approvalNeeded: ApprovalNeeded | null;
3277
+ /** ADR-082 d9: each listed closure's approval status by closure id; show `unverified` beside the approver's name. */
3278
+ closureApprovalStatus: Record<string, ClosureApprovalStatus>;
2084
3279
  enabled: boolean;
2085
3280
  blind: boolean;
2086
3281
  /** Pass straight to useSale's `session` option: `complete()` then stamps through `stampSession`. */
@@ -2098,6 +3293,12 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2098
3293
  actions: {
2099
3294
  takeOver: () => Promise<void>;
2100
3295
  chooseAnotherRegister: () => Promise<void>;
3296
+ /** ADR-082 d7: sends `approvalNeeded`'s closure again with a new proof and approver; `RegisterReapproveError` unless it is refused with either approval code at contract 3. */
3297
+ reapproveClosure: (input: {
3298
+ closureId: string;
3299
+ approval: string;
3300
+ approvedBy: string;
3301
+ }) => Promise<void>;
2101
3302
  /**
2102
3303
  * Refuses with `RegisterSessionAlreadyOpenError` while the register has a live session or
2103
3304
  * another open is running (in any hook instance), and with `RegisterCloseIncompleteError`
@@ -2115,9 +3316,14 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2115
3316
  * `counted` maps each tender to its counted minor units. An interrupted close resumes with
2116
3317
  * the count persisted on the session, not the one passed to the retry (WCPOS uses the retry's).
2117
3318
  * Over `varianceThreshold` (`closeNeedsApproval`, as `RegisterCount`), a close without
2118
- * `approvedBy` throws `RegisterApprovalRequiredError` before any write, blind or not; a
3319
+ * `approvedBy` throws `RegisterApprovalRequiredError` before any write, blind or not; so does one without
3320
+ * `approval` at contract 3 with the store's `registerApproval` while the session is `liveAtStore` (ADR-082 d5); a
2119
3321
  * resumed close (the stored session already closed) isn't gated again. `approvedBy` reaches the Z
2120
3322
  * (`breakdowns.approved_by`), and `approvedByName` its `approved_by_name`.
3323
+ * `approval` is the store's opaque proof (ADR-082): it goes to the session's
3324
+ * `approver_token` and from there only onto a version 3 closure command, never onto the Z, a fact or a log. With
3325
+ * `approvedVariance` (the variance the app sent to its approval route), a close whose `closureVariance` differs
3326
+ * throws `RegisterApprovalRequiredError` before any write. A resumed close checks neither.
2121
3327
  * One close per register runs at a time, in any hook instance: a call while one is in flight joins
2122
3328
  * it, getting its closure or error, and its own `counted`, `approvedBy` and `approvedByName` are ignored.
2123
3329
  */
@@ -2125,7 +3331,13 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2125
3331
  counted: Record<string, number>;
2126
3332
  approvedBy?: string;
2127
3333
  approvedByName?: string;
3334
+ approval?: string;
3335
+ approvedVariance?: Record<string, number>;
2128
3336
  }) => Promise<rxdb.RxDocument<Closure, {}, unknown>>;
3337
+ /** ADR-082 d3: the variance this count would close with, read as the gate reads it; the app sends it to its approval route and back as `approvedVariance`. */
3338
+ closureVariance: (counted: Record<string, number>) => Promise<{
3339
+ [k: string]: number;
3340
+ }>;
2129
3341
  recordMovement: (input: {
2130
3342
  type: "paid_in" | "paid_out" | "no_sale";
2131
3343
  amountMinor: number;
@@ -2135,28 +3347,181 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2135
3347
  };
2136
3348
  };
2137
3349
 
2138
- type SessionTarget = {
2139
- commands: RegisterCommandCollection;
2140
- sessions: RegisterSessionCollection;
2141
- sessionId: string;
2142
- now?: string;
3350
+ /** Local-only context for a transport (ADR-076 amendment 1): never serialised, never part of a payload. */
3351
+ interface OrderTransportContext {
3352
+ /** The stored (frozen) order of each envelope in the batch, keyed by the envelope's `id` (its commandId). */
3353
+ local: {
3354
+ orders: ReadonlyMap<string, PosOrder>;
3355
+ };
3356
+ }
3357
+ type TransportOutcome = {
3358
+ kind: 'results';
3359
+ results: CommandResult[];
3360
+ } | {
3361
+ kind: 'unauthorized';
3362
+ } | {
3363
+ kind: 'refused';
3364
+ status: number;
3365
+ reason: string;
3366
+ }
3367
+ /** `reason` is `network` when the store could not be reached, `timeout` when a sent request got no answer in time,
3368
+ * else what the store answered (`status_503`, `bad_body`, ...). The order outbox counts every reason but `network`. */
3369
+ | {
3370
+ kind: 'retry';
3371
+ reason: string;
3372
+ retryAfterMs?: number;
2143
3373
  };
3374
+ interface CommandTransport<E extends AnyCommandEnvelope = CommandEnvelope<OrderCreatePayload>> {
3375
+ send(batch: E[], context?: OrderTransportContext): Promise<TransportOutcome>;
3376
+ }
3377
+ interface OutboxState {
3378
+ pending: number;
3379
+ /** The order outbox's count of `pos_orders` the store refused (`syncStatus: 'rejected'`), read with `pending`. Each
3380
+ * stays until requeue() sends it again. The register outbox's count of rejected `register_commands` that stop their
3381
+ * register's ledger (superseded, abandoned and an abandoned session's already-open refusal are left out, ADR-078, and so
3382
+ * are the two refused closure approvals, which hold only their register's next closure, ADR-082 decision 6). */
3383
+ rejected?: number;
3384
+ sending: boolean;
3385
+ lastRetryReason?: string;
3386
+ nextAttemptAt?: number;
3387
+ /** Set after 3 consecutive 401s; the app should ask the cashier to sign in, then call flush(). */
3388
+ authRequired?: boolean;
3389
+ /** Set when the server refused a whole batch (HTTP 400, 403, 413, 415, 422). No order is changed; sending pauses until the next flush(). */
3390
+ refused?: {
3391
+ status: number;
3392
+ reason: string;
3393
+ };
3394
+ /** Set while the store (not offline) has kept failing some orders for 15 minutes, each on its own clock. Those
3395
+ * orders stay pending and keep retrying. `orders` has each order's own entry: its `since` is when its clock
3396
+ * would have started had there been no offline gaps (now minus its answered time; while offline, as of the
3397
+ * moment the clock paused), and its latest `reason`. `since` is the earliest of theirs, virtual for the threshold;
3398
+ * `reason` the latest. `firstFailedAt` is the earliest real wall-clock first failure, only when every stuck clock
3399
+ * has one. Each order entry has its own real wall-clock `firstFailedAt`. Both are in memory only, absent after restart. */
3400
+ stuck?: {
3401
+ commandIds: string[];
3402
+ since: number;
3403
+ firstFailedAt?: number;
3404
+ reason: string;
3405
+ orders: {
3406
+ commandId: string;
3407
+ since: number;
3408
+ firstFailedAt?: number;
3409
+ reason: string;
3410
+ }[];
3411
+ };
3412
+ /** Set after 3 consecutive 404 answers (counted across the outboxes sharing one BackendNotFound): the store address
3413
+ * may be wrong, or the store's plugin isn't installed or is switched off. The outbox keeps retrying; the next answer
3414
+ * that isn't a 404 clears it (offline changes nothing). `since` is when the first of those 404s arrived. */
3415
+ backendMissing?: {
3416
+ since: number;
3417
+ };
3418
+ }
3419
+
3420
+ interface OutboxCounts {
3421
+ /** `OutboxState.pending`. */
3422
+ pending: number;
3423
+ /** `OutboxState.rejected`, 0 when unset. */
3424
+ rejected: number;
3425
+ /** `OutboxState.stuck.commandIds.length`, 0 when unset. These rows are pending too. */
3426
+ stuck: number;
3427
+ }
3428
+ interface OutboxHealth {
3429
+ /** The order outbox (`useOrderOutbox`): sales. */
3430
+ sales: OutboxCounts;
3431
+ /** The register outbox (`useRegisterOutbox`): till updates. */
3432
+ tillUpdates: OutboxCounts;
3433
+ /** Rejected plus stuck rows across both outboxes. Not `needsAttention()`'s list, which also holds applied orders with warnings. */
3434
+ attention: number;
3435
+ /** Either outbox parked after repeated 401s (`OutboxState.authRequired`): the cashier signs in again, then both flush. */
3436
+ authRequired: boolean;
3437
+ }
3438
+ /** The health of both outboxes from their states. Pure. */
3439
+ declare function summarizeOutboxHealth(sales: OutboxState, tillUpdates: OutboxState): OutboxHealth;
3440
+ /** summarizeOutboxHealth over both state streams (combineLatest), emitting only when a field changes. */
3441
+ declare function watchOutboxHealth(sales$: Observable<OutboxState>, tillUpdates$: Observable<OutboxState>): Observable<OutboxHealth>;
3442
+
2144
3443
  /**
2145
- * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
2146
- * Superseded rejections make open/counting sessions terminal; a conflict session leaves only by an applied open or abandon (ADR-078 decision 9); terminal/unknown states stay untouched.
2147
- * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
2148
- * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
3444
+ * What a cashier switch, a register switch or a sign-out leaves behind, and the hand-over slip (v2 parity A4, A12).
3445
+ * Port provenance: WCPOS v2 monorepo `main` 51e7c4351, `packages/core/src/screens/main/pos/cart/switch-confirm.tsx`
3446
+ * (the warnings it shows) and `services/register-session/use-session-report.ts:26-65` with
3447
+ * `closure-document.ts:206-273` (the slip is the open session's X report, marked as a hand-over, naming the cashier).
2149
3448
  */
2150
- declare function adoptRegisterResults({ commands, sessions, registerId }: {
2151
- commands: RegisterCommandCollection;
2152
- sessions: RegisterSessionCollection;
2153
- registerId: string;
2154
- }): Promise<void>;
2155
- declare function takeOverSession({ commands, sessions, sessionId, now, registerContract }: SessionTarget & {
2156
- /** The store's register contract (`capabilities.register`); take over needs 2, and a missing value counts as below 2. */
2157
- registerContract?: number;
2158
- }): Promise<void>;
2159
- declare function abandonSession(input: SessionTarget): Promise<void>;
3449
+
3450
+ type SwitchKind = 'cashier' | 'register' | 'signOut';
3451
+ type SwitchWarning = {
3452
+ code: 'unsentSales';
3453
+ count: number;
3454
+ } | {
3455
+ code: 'unsentTillUpdates';
3456
+ count: number;
3457
+ } | {
3458
+ code: 'parkedSales';
3459
+ count: number;
3460
+ } | {
3461
+ code: 'partlyPaidSale';
3462
+ } | {
3463
+ code: 'openSession';
3464
+ };
3465
+ interface SwitchWarningInput {
3466
+ kind: SwitchKind;
3467
+ /** `summarizeOutboxHealth`'s result (or `useOutboxHealth().health`). */
3468
+ outbox: Pick<OutboxHealth, 'sales' | 'tillUpdates'>;
3469
+ /** `useParkedSales(...).parked.length`. */
3470
+ parkedSales: number;
3471
+ /** Captured minor units on the sale in progress; 0 when nothing is paid. */
3472
+ paidMinor: number;
3473
+ /** The bound register's session status; `null` or absent when no session. */
3474
+ sessionStatus?: RegisterSession['status'] | null;
3475
+ }
3476
+ interface SwitchWarnings {
3477
+ kind: SwitchKind;
3478
+ /** In this order: unsentSales, unsentTillUpdates, parkedSales, partlyPaidSale, openSession; only those that apply. */
3479
+ warnings: SwitchWarning[];
3480
+ /** `outbox.sales.pending`: the confirm wording reads it. */
3481
+ unsentSales: number;
3482
+ /** An `open` or `counting` session, for `register` and `signOut` only (a cashier switch keeps the drawer open by design). */
3483
+ sessionOpen: boolean;
3484
+ }
3485
+ /** What the switch would leave behind. Pure. */
3486
+ declare function switchWarnings({ kind, outbox, parkedSales, paidMinor, sessionStatus }: SwitchWarningInput): SwitchWarnings;
3487
+ interface HandoverSlipInput {
3488
+ session: RegisterSession;
3489
+ /** The cashier handing over. */
3490
+ cashier: Pick<Cashier, 'name'>;
3491
+ registerName: string;
3492
+ /** Who opened the session; '' when unknown. */
3493
+ openedByName?: string;
3494
+ /** `useRegisterSession().salesCount`. */
3495
+ salesCount: number;
3496
+ /** `useRegisterSession().expected`, minor units per tender. */
3497
+ expected: Record<string, number>;
3498
+ /** `useRegisterSession().blind`: no expected figures on the slip. */
3499
+ blind: boolean;
3500
+ outbox: Pick<OutboxHealth, 'sales' | 'tillUpdates'>;
3501
+ context: ClosureContext;
3502
+ }
3503
+ type XReportDocument = ReturnType<typeof buildXReportDocument>;
3504
+ interface HandoverSlipData {
3505
+ registerName: string;
3506
+ cashierName: string;
3507
+ openedByName: string;
3508
+ /** `document.closure.opened_at.time`. */
3509
+ openedAtTime: string;
3510
+ salesCount: number;
3511
+ /** `null` while blind. */
3512
+ expected: Record<string, number> | null;
3513
+ unsentSales: number;
3514
+ unsentTillUpdates: number;
3515
+ /** The X-report envelope for the closure template and the print queue (`kind: 'report'`), marked as a hand-over. */
3516
+ document: XReportDocument & {
3517
+ fiscal: XReportDocument['fiscal'] & {
3518
+ document_type: 'handover';
3519
+ is_handover: true;
3520
+ };
3521
+ };
3522
+ }
3523
+ /** The hand-over slip's data and its printable envelope. Pure. */
3524
+ declare function handoverSlip({ session, cashier, registerName, openedByName, salesCount, expected, blind, outbox, context, }: HandoverSlipInput): HandoverSlipData;
2160
3525
 
2161
3526
  type CatalogueEntry<Doc> = {
2162
3527
  product: Doc;
@@ -2227,6 +3592,14 @@ type SaleStage = {
2227
3592
  declare const DISCOUNTS_UNSUPPORTED = "finalize: discounts are not supported by the server yet (order.create v2)";
2228
3593
  /** Every sale change refuses with this while a completion is pending (see `complete()`). */
2229
3594
  declare const SALE_SAVING = "This sale is being saved. Retry to finish it.";
3595
+ declare const PAYMENT_IN_MOTION = "Finish or void the payment in progress before completing the sale";
3596
+ /**
3597
+ * `switchSale()` and `closeSale()` refuse a sale whose legs took money (u19). v2 keeps a partly paid order's legs on
3598
+ * switching, but a TallyUI draft keeps no tender stage, the next `startTender` replaces every leg, and `resume`
3599
+ * re-checks coupons: so the sale stays on the till until it is paid or its paid legs are voided.
3600
+ */
3601
+ declare const SALE_PARTLY_PAID = "This sale is partly paid. Take the rest of the payment or void the paid legs first.";
3602
+ declare const SALE_IN_TENDER = "Finish or cancel the payment before switching sales";
2230
3603
  /** Call under a `TaxProvider`: its tax context and the settings' currency price every sale. */
2231
3604
  declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscountsSequentially'>, opts: {
2232
3605
  registerId: string;
@@ -2317,6 +3690,8 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
2317
3690
  applyCoupon(code: string): Promise<string | null>;
2318
3691
  /** Removes an applied coupon; returns the refusal to show, or null once removed. */
2319
3692
  removeCoupon(code: string): string | null;
3693
+ /** The sale's note, kept on the open sale (parked and resumed with it, cleared by newSale) and sent as order.create v7's note (ADR-083). */
3694
+ setNote(note: string): void;
2320
3695
  /** the picked customer reaches the server as order.create v3's customer.customerId */
2321
3696
  setCustomer(customer: CustomerSummary | null): void;
2322
3697
  /**
@@ -2335,12 +3710,16 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
2335
3710
  amountMinor: number;
2336
3711
  reference?: string;
2337
3712
  } | null) => void;
2338
- /** ADR-072: external is capped at the balance due; change comes only from cash. */
3713
+ /** ADR-072: external is capped at the balance due; change comes only from cash. A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. */
2339
3714
  addTender(tender: {
2340
3715
  method: "cash" | "external";
2341
3716
  amountMinor: number;
2342
3717
  reference?: string;
3718
+ status?: "pending" | "authorized" | "captured";
2343
3719
  }): string | null;
3720
+ setTenderStatus(paymentId: string, status: "authorized" | "captured" | "failed"): boolean;
3721
+ /** The leg stays in order.payments as voided and counts nothing; removeTender still removes a leg outright. */
3722
+ voidTender(paymentId: string): boolean;
2344
3723
  /** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
2345
3724
  removeTender(paymentId: string): void;
2346
3725
  cancelTender(): void;
@@ -2380,6 +3759,15 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
2380
3759
  resume(draftId: string, options?: {
2381
3760
  keepParkedPrices?: boolean;
2382
3761
  }): Promise<string | null>;
3762
+ /**
3763
+ * Opens the parked draft `draftId`, or an empty sale for null (New), as a tab switch (u19, v2 cart/tabs.tsx):
3764
+ * parks the current sale first when it has lines, fees or shipping (a receipt is done and is not parked).
3765
+ * Refused, changing nothing, while saving, for a partly paid sale (SALE_PARTLY_PAID), a payment in motion or
3766
+ * the tender stage. Resolves to a refusal (park's, or `resume`'s for the chosen draft), or null.
3767
+ */
3768
+ switchSale(draftId: string | null): Promise<string | null>;
3769
+ /** Discards the current sale (nothing is parked) and starts an empty one; refused while saving, once a leg of an unfinished sale took or holds money, or in the tender stage. */
3770
+ closeSale(): string | null;
2383
3771
  /**
2384
3772
  * Continue after a failed save whose order is confirmed stored (`canContinue`): exactly `newSale()`.
2385
3773
  * The order stays pending in the outbox, which will send it; it isn't handed to `onSaleCompleted` again, and
@@ -2388,6 +3776,27 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
2388
3776
  continueSale(): void;
2389
3777
  };
2390
3778
 
3779
+ /** One tab of the till's open sales: the current sale or a parked draft (v2 cart/tabs.tsx). */
3780
+ interface OpenSale {
3781
+ id: string;
3782
+ customerName?: string;
3783
+ itemCount: number;
3784
+ firstItem?: string;
3785
+ totalMinor: number;
3786
+ paidMinor: number;
3787
+ balanceDueMinor: number;
3788
+ /** The sale on the till now. */
3789
+ current: boolean;
3790
+ }
3791
+ /** v2 cart/tab-chip.tsx: captured money and a balance still due. */
3792
+ declare function isPartlyPaid(sale: Pick<OpenSale, 'paidMinor' | 'balanceDueMinor'>): boolean;
3793
+ /**
3794
+ * The current sale (when it has lines, fees or shipping; a blank cart is no tab) and the parked drafts, in creation
3795
+ * order: sorted by id with numeric collation, so a tab keeps its place across switches (a re-park changes
3796
+ * `parkedAt`, never the id). A draft with the current sale's id is that sale and is skipped.
3797
+ */
3798
+ declare function openSales(order: Order, parked: readonly ParkedOrderSummary[]): OpenSale[];
3799
+
2391
3800
  /** A WooCommerce coupon as the sale needs it: the engine's input and the connector's numeric id. */
2392
3801
  type SaleCoupon = woocommerceCoupons.CouponInput & {
2393
3802
  id: number;
@@ -2430,85 +3839,32 @@ declare function startCouponUsageRefetch(deps: {
2430
3839
 
2431
3840
  type index_SaleCoupon = SaleCoupon;
2432
3841
  type index_SaleCouponSource = SaleCouponSource;
2433
- declare const index_couponRefusal: typeof couponRefusal;
2434
- declare const index_createDiscountCodes: typeof createDiscountCodes;
2435
- declare const index_createSaleCouponSource: typeof createSaleCouponSource;
2436
- declare const index_startCouponUsageRefetch: typeof startCouponUsageRefetch;
2437
- declare namespace index {
2438
- 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 };
2439
- }
2440
-
2441
- declare class CartError extends Error {
2442
- }
2443
- declare function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry<Doc>, traits: ProductTraits<Doc>, currency: string): string;
2444
-
2445
- /** Local-only context for a transport (ADR-076 amendment 1): never serialised, never part of a payload. */
2446
- interface OrderTransportContext {
2447
- /** The stored (frozen) order of each envelope in the batch, keyed by the envelope's `id` (its commandId). */
2448
- local: {
2449
- orders: ReadonlyMap<string, PosOrder>;
2450
- };
2451
- }
2452
- type TransportOutcome = {
2453
- kind: 'results';
2454
- results: CommandResult[];
2455
- } | {
2456
- kind: 'unauthorized';
2457
- } | {
2458
- kind: 'refused';
2459
- status: number;
2460
- reason: string;
2461
- }
2462
- /** `reason` is `network` when the store could not be reached, `timeout` when a sent request got no answer in time,
2463
- * else what the store answered (`status_503`, `bad_body`, ...). The order outbox counts every reason but `network`. */
2464
- | {
2465
- kind: 'retry';
2466
- reason: string;
2467
- retryAfterMs?: number;
2468
- };
2469
- interface CommandTransport<E extends AnyCommandEnvelope = CommandEnvelope<OrderCreatePayload>> {
2470
- send(batch: E[], context?: OrderTransportContext): Promise<TransportOutcome>;
2471
- }
2472
- interface OutboxState {
2473
- pending: number;
2474
- /** The order outbox's count of `pos_orders` the store refused (`syncStatus: 'rejected'`), read with `pending`. Each
2475
- * stays until requeue() sends it again. The register outbox leaves it unset. */
2476
- rejected?: number;
2477
- sending: boolean;
2478
- lastRetryReason?: string;
2479
- nextAttemptAt?: number;
2480
- /** Set after 3 consecutive 401s; the app should ask the cashier to sign in, then call flush(). */
2481
- authRequired?: boolean;
2482
- /** Set when the server refused a whole batch (HTTP 400, 403, 413, 415, 422). No order is changed; sending pauses until the next flush(). */
2483
- refused?: {
2484
- status: number;
2485
- reason: string;
2486
- };
2487
- /** Set while the store (not offline) has kept failing some orders for 15 minutes, each on its own clock. Those
2488
- * orders stay pending and keep retrying. `orders` has each order's own entry: its `since` is when its clock
2489
- * would have started had there been no offline gaps (now minus its answered time; while offline, as of the
2490
- * moment the clock paused), and its latest `reason`. `since` is the earliest of theirs, virtual for the threshold;
2491
- * `reason` the latest. `firstFailedAt` is the earliest real wall-clock first failure, only when every stuck clock
2492
- * has one. Each order entry has its own real wall-clock `firstFailedAt`. Both are in memory only, absent after restart. */
2493
- stuck?: {
2494
- commandIds: string[];
2495
- since: number;
2496
- firstFailedAt?: number;
2497
- reason: string;
2498
- orders: {
2499
- commandId: string;
2500
- since: number;
2501
- firstFailedAt?: number;
2502
- reason: string;
2503
- }[];
2504
- };
2505
- /** Set after 3 consecutive 404 answers (counted across the outboxes sharing one BackendNotFound): the store address
2506
- * may be wrong, or the store's plugin isn't installed or is switched off. The outbox keeps retrying; the next answer
2507
- * that isn't a 404 clears it (offline changes nothing). `since` is when the first of those 404s arrived. */
2508
- backendMissing?: {
2509
- since: number;
2510
- };
3842
+ declare const index_couponRefusal: typeof couponRefusal;
3843
+ declare const index_createDiscountCodes: typeof createDiscountCodes;
3844
+ declare const index_createSaleCouponSource: typeof createSaleCouponSource;
3845
+ declare const index_startCouponUsageRefetch: typeof startCouponUsageRefetch;
3846
+ declare namespace index {
3847
+ 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 };
3848
+ }
3849
+
3850
+ declare class CartError extends Error {
2511
3851
  }
3852
+ declare function addEntryToCart<Doc>(builder: OrderBuilder, entry: CatalogueEntry<Doc>, traits: ProductTraits<Doc>, currency: string): string;
3853
+
3854
+ /** The part of a cart line the in-cart count reads (`LineItem` has all three). */
3855
+ type CartQuantityLine = {
3856
+ productId: string;
3857
+ quantity: number;
3858
+ custom?: true;
3859
+ };
3860
+ /**
3861
+ * Quantity per product id, summed across the product's lines, so a product with variants counts every
3862
+ * variant's lines; a custom line belongs to no catalogue product and counts for none.
3863
+ *
3864
+ * Ported from WCPOS v2 `useProductCount`, packages/core/src/screens/main/pos/products/rows/product-row.tsx
3865
+ * (MIT, WCPOS): the cashier reads how many are in the cart, not how many lines.
3866
+ */
3867
+ declare function cartQuantities(lines: readonly CartQuantityLine[]): Map<string, number>;
2512
3868
 
2513
3869
  interface HttpTransportOptions {
2514
3870
  baseUrl: string;
@@ -2560,6 +3916,8 @@ interface OrderOutbox {
2560
3916
  }
2561
3917
  declare function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox;
2562
3918
 
3919
+ /** Whether the register outbox's requeue() resends a rejection with this code. */
3920
+ declare function isRegisterRequeueable(code: string | undefined): boolean;
2563
3921
  interface RegisterOutboxOptions {
2564
3922
  collection: RxCollection<RegisterCommand>;
2565
3923
  /** The till's `register_sessions`. With it, a refused open (`register_session_already_open`) stops blocking its register
@@ -2583,6 +3941,10 @@ interface RegisterOutboxOptions {
2583
3941
  }
2584
3942
  interface RegisterOutbox {
2585
3943
  flush(): Promise<void>;
3944
+ /** Moves rejected commands (all, or those whose commandId is listed) back to pending in their ledger place, under
3945
+ * the same commandId and payload, then flushes: a refusal the store did not record is weighed again on a resend
3946
+ * of the same id (ADR-068 decision 5). Codes isRegisterRequeueable refuses are left. Resolves to the number requeued. */
3947
+ requeue(commandIds?: string[]): Promise<number>;
2586
3948
  start(): void;
2587
3949
  stop(): void;
2588
3950
  state$: Observable<OutboxState>;
@@ -2609,6 +3971,8 @@ interface UseRegisterOutboxResult {
2609
3971
  state: OutboxState;
2610
3972
  /** Sends pending till updates; does nothing while there is no collection. */
2611
3973
  flush(): Promise<void>;
3974
+ /** Moves rejected till updates back to pending (see RegisterOutbox.requeue); resolves to 0 while there is no collection. */
3975
+ requeue(commandIds?: string[]): Promise<number>;
2612
3976
  }
2613
3977
  declare function useRegisterOutbox(options: UseRegisterOutboxOptions): UseRegisterOutboxResult;
2614
3978
 
@@ -2672,6 +4036,20 @@ interface UseOrderOutboxResult {
2672
4036
  /** Opens the order store for `storeKey`, runs its outbox and watches the recent orders (lifted from medusapos/app, ADR-052). */
2673
4037
  declare function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxResult;
2674
4038
 
4039
+ interface UseOutboxHealthOptions {
4040
+ /** `useOrderOutbox()`'s result; only `state` and `flush` are read. */
4041
+ sales: Pick<UseOrderOutboxResult, 'state' | 'flush'>;
4042
+ /** `useRegisterOutbox()`'s result; only `state` and `flush` are read. */
4043
+ tillUpdates: Pick<UseRegisterOutboxResult, 'state' | 'flush'>;
4044
+ }
4045
+ interface UseOutboxHealthResult {
4046
+ /** summarizeOutboxHealth of the two states; a new object only when a state changes. */
4047
+ health: OutboxHealth;
4048
+ /** Flushes both outboxes at once (after the cashier signs in again); rejects if either flush rejects. */
4049
+ flush(): Promise<void>;
4050
+ }
4051
+ declare function useOutboxHealth(options: UseOutboxHealthOptions): UseOutboxHealthResult;
4052
+
2675
4053
  type OrderRefundOutcome = {
2676
4054
  kind: 'applied';
2677
4055
  refund: OrderRefundResult;
@@ -2712,151 +4090,53 @@ declare function submitOrderRefund({ refunds, transport, envelope, now }: {
2712
4090
  record: PosRefund;
2713
4091
  }>;
2714
4092
 
2715
- /** The transport a payment terminal is reached over: hardware-neutral, not tied to any backend. */
2716
- type PaymentTransport = 'bluetooth' | 'usb' | 'network' | 'tap_to_pay';
2717
- type TenderView = 'select' | 'amount' | 'cancel';
2718
- type TenderLineId = string | number;
2719
- type TenderPlan = {
2720
- kind: 'even';
2721
- ways: number;
2722
- from: number;
2723
- } | {
2724
- kind: 'fixed';
2725
- firstMinor: number;
2726
- title: string | null;
2727
- from: number;
2728
- } | {
2729
- kind: 'items';
2730
- lineIds: TenderLineId[];
2731
- firstMinor: number;
2732
- ways: number;
2733
- from: number;
2734
- };
2735
- type SplitTab = 'even' | 'amount' | 'percent' | 'item';
2736
- interface TenderState {
2737
- view: TenderView;
2738
- /** Method id being tendered; null in the 'select' and 'cancel' views. */
2739
- methodId: string | null;
2740
- readerId: string | null;
2741
- transport: PaymentTransport | null;
2742
- /** Keypad entry in minor units. */
2743
- entryMinor: number;
2744
- /** False until the cashier has touched the keypad since the entry was pre-filled. */
2745
- entryDirty: boolean;
2746
- plan: TenderPlan | null;
2747
- splitView: boolean;
2748
- splitTab: SplitTab;
2749
- pickedLineIds: TenderLineId[];
2750
- linesPaidBy: Record<TenderLineId, string[]>;
2751
- }
2752
- /** '0'..'9' plus the two edit keys. There is deliberately no decimal key: digits shift in from the right. */
2753
- type TenderKey = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'clear' | 'backspace';
2754
- type TenderAction = {
2755
- type: 'pick-method';
2756
- methodId: string;
2757
- prefillMinor: number;
2758
- readerId: string | null;
2759
- transport?: PaymentTransport | null;
2760
- } | {
2761
- type: 'pick-transport';
2762
- transport: PaymentTransport;
2763
- } | {
2764
- type: 'pick-reader';
2765
- readerId: string | null;
2766
- } | {
2767
- type: 'tender-started';
2768
- } | {
2769
- type: 'key';
2770
- key: TenderKey;
2771
- } | {
2772
- type: 'set-entry';
2773
- minor: number;
2774
- } | {
2775
- type: 'back';
2776
- } | {
2777
- type: 'tender-recorded';
2778
- rowsSinceFrom: {
2779
- title: string;
2780
- amountMinor: number;
2781
- }[];
2782
- /** The order's balance once this row counts, so the next leg can be pre-typed. */
2783
- balanceMinor: number;
2784
- } | {
2785
- type: 'open-split';
2786
- } | {
2787
- type: 'close-split';
2788
- } | {
2789
- type: 'set-split-tab';
2790
- tab: SplitTab;
2791
- } | {
2792
- type: 'toggle-split-line';
2793
- lineId: TenderLineId;
2794
- } | {
2795
- type: 'set-plan';
2796
- plan: TenderPlan;
2797
- balanceMinor: number;
2798
- } | {
2799
- type: 'clear-plan';
2800
- balanceMinor: number;
2801
- } | {
2802
- type: 'arm-custom';
2803
- } | {
2804
- type: 'request-cancel';
2805
- } | {
2806
- type: 'reset';
2807
- };
2808
- /** $9,999,999.99 at two decimals — a till will never legitimately take more, and it stops a stuck key running the display off the screen. */
2809
- declare const MAX_TENDER_MINOR = 999999999;
2810
- declare const initialTenderState: TenderState;
2811
- /**
2812
- * Reducer init. An order whose method the checkout store already holds — a URL seed, or a
2813
- * tab the cashier is coming back to — reopens its keypad prefilled with the balance, exactly
2814
- * as a tap on that tile would. Everything else starts from scratch.
2815
- */
2816
- declare function initTenderState({ methodId, balanceMinor, }: {
2817
- methodId: string | null;
2818
- balanceMinor: number;
2819
- }): TenderState;
2820
- declare function tenderReducer(state: TenderState, action: TenderAction): TenderState;
2821
4093
  /**
2822
- * What the leg applies to the order. Cash may be tendered above the balance;
2823
- * the excess is change, never an overpayment on the order.
2824
- */
2825
- declare function appliedMinor(entryMinor: number, balanceMinor: number): number;
2826
- /** Change handed back. Zero for any tender whose method cannot give change. */
2827
- declare function changeMinor(entryMinor: number, appliedAmountMinor: number, givesChange: boolean): number;
2828
- /**
2829
- * Quick tendered amounts under a cash keypad: the balance itself, then the next
2830
- * whole 5, 10 and 50 above it. Deduped, ascending, never below the balance.
2831
- * The caller supplies those major-unit steps already scaled to minor units.
2832
- */
2833
- declare function quickTenderedAmounts(balanceMinor: number, stepsMinor: readonly number[]): number[];
2834
- /**
2835
- * Even split shares. Returns the next tender's share, rounded half-up to the
2836
- * minor unit; the last leg remains whatever balance is left.
4094
+ * Ports v2 calculate-refund.ts (calculateLineItemRefund, computeRemainingRefundQuantity).
4095
+ * Amounts follow ADR-080 amendment 2's cumulative-share rule.
2837
4096
  */
2838
- declare function evenSplitShareMinor(balanceMinor: number, ways: number): number;
2839
- /** Completion is derived from payment rows, never an extra counter in the reducer. */
2840
- declare function activePlan(plan: TenderPlan | null, taken: number, balanceMinor: number): TenderPlan | null;
2841
- interface PlanLeg {
2842
- minor: number;
2843
- state: 'done' | 'now' | 'todo' | 'rest';
2844
- title?: string;
4097
+
4098
+ /** The fields of an order line this needs; a StoreOrderLine fits. */
4099
+ type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
4100
+ /** Earlier refund lines; negative quantities count by magnitude. */
4101
+ interface EarlierRefund {
4102
+ lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>>;
2845
4103
  }
2846
- /** Label pieces stay untranslated here; the flow supplies localized copy and item names. */
2847
- declare function planLegs(plan: TenderPlan, rowsSinceFrom: {
2848
- minor: number;
2849
- title: string;
2850
- }[], balanceMinor: number): {
2851
- legs: PlanLeg[];
2852
- thisPaymentMinor: number;
2853
- label: {
2854
- n: number;
2855
- ways: number;
2856
- rest: boolean;
2857
- title: string | null;
2858
- };
2859
- };
4104
+ /** Remaining quantities and amounts, with earlier refund magnitudes capped at the line quantity. */
4105
+ interface RefundableLine {
4106
+ orderLineId: string;
4107
+ refundedQuantity: number;
4108
+ refundableQuantity: number;
4109
+ netMinor: number;
4110
+ taxMinor: number;
4111
+ }
4112
+ /** A selected quantity's cumulative shares of net and tax, and their sum. */
4113
+ interface PricedRefundLine {
4114
+ orderLineId: string;
4115
+ quantity: number;
4116
+ netMinor: number;
4117
+ taxMinor: number;
4118
+ totalMinor: number;
4119
+ }
4120
+ /** Payload-ready lines and their amounts; the caller adds shipping and adjustment to totalMinor. */
4121
+ interface PricedRefund {
4122
+ /** Exactly orderLineId, quantity (>= 1), and restock. */
4123
+ lines: OrderRefundLine[];
4124
+ /** Amounts in the same order as lines. */
4125
+ priced: PricedRefundLine[];
4126
+ /** Requests cut to availability, including unknown lines cut to zero. */
4127
+ clamped: Array<{
4128
+ orderLineId: string;
4129
+ requestedQuantity: number;
4130
+ quantity: number;
4131
+ }>;
4132
+ netMinor: number;
4133
+ taxMinor: number;
4134
+ totalMinor: number;
4135
+ }
4136
+ /** Returns the quantities and amounts still refundable, in order-line order. */
4137
+ declare function refundableLines(lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[]): RefundableLine[];
4138
+ /** Prices requested quantities with cumulative shares, clamping them to what remains refundable. */
4139
+ declare function priceRefund(lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[], request: readonly OrderRefundLine[]): PricedRefund;
2860
4140
 
2861
4141
  /**
2862
4142
  * One record per voided tender leg: its v2 ledger row plus the provenance a v2 `void`
@@ -2897,4 +4177,209 @@ declare function tenderVoidCollection(): {
2897
4177
  readonly schema: RxJsonSchema<TenderVoid>;
2898
4178
  };
2899
4179
 
2900
- 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, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, 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 };
4180
+ /**
4181
+ * Port of v2's cash rounding: packages/order-math/src/payments/rounding.ts and
4182
+ * packages/core/src/screens/main/pos/checkout/tender/tender-figures.ts.
4183
+ * v2's tender LEDGER: "a partial or short cash entry and every other method keep full precision".
4184
+ * Local figures only; writing the rounding as an order line is unit 24.
4185
+ */
4186
+
4187
+ /** The balance under a manual method's rounding, with its signed difference. */
4188
+ declare function roundedDue(balanceMinor: number, method: PaymentMethodDescriptor | null): {
4189
+ dueMinor: number;
4190
+ roundingMinor: number;
4191
+ };
4192
+ /** Local tender figures under the method's cash rounding. */
4193
+ interface TenderRounding {
4194
+ /** The balance under the method's rounding (the balance itself when none applies). */
4195
+ roundedDueMinor: number;
4196
+ /** `roundedDueMinor - balanceMinor` when the entry settles at the rounded due, else 0. Signed. */
4197
+ roundingMinor: number;
4198
+ /** The entry as the cashier sees it: an untouched prefill of the balance shows the rounded due. */
4199
+ entryMinor: number;
4200
+ /** What the entry applies to the order: the rounded due when rounding applies, else the capped entry. */
4201
+ appliedMinor: number;
4202
+ }
4203
+ /** Figure the displayed entry and applied amount, rounding only a leg that settles at the due. */
4204
+ declare function tenderRounding(state: Pick<TenderState, 'entryMinor' | 'entryDirty'>, balanceMinor: number, method: PaymentMethodDescriptor | null): TenderRounding;
4205
+
4206
+ /** A store day, `yyyy-MM-dd` in the store's timezone. */
4207
+ type StoreDay = string;
4208
+ /** Inclusive range of store days. */
4209
+ interface DayRange {
4210
+ from: StoreDay;
4211
+ to: StoreDay;
4212
+ }
4213
+ interface ReportCategory {
4214
+ id: string;
4215
+ name: string;
4216
+ }
4217
+ interface ReportLine {
4218
+ /** Grouping identity: variant, else product, else name. */
4219
+ key: string;
4220
+ name: string;
4221
+ quantity: number;
4222
+ /** After discounts, excluding tax. */
4223
+ netMinor: number;
4224
+ taxMinor: number;
4225
+ /** Cost of goods for the whole line (quantity × unit cost). Absent or null means the cost is missing, never 0. */
4226
+ costMinor?: number | null;
4227
+ /** The line's first category, when the caller joined one. */
4228
+ category?: ReportCategory;
4229
+ }
4230
+ interface ReportPayment {
4231
+ method: string;
4232
+ label?: string;
4233
+ amountMinor: number;
4234
+ }
4235
+ interface ReportTax {
4236
+ ratePpm: number;
4237
+ code?: string;
4238
+ label: string;
4239
+ taxMinor: number;
4240
+ /** The net this rate taxed; null when the source does not carry it. */
4241
+ netMinor: number | null;
4242
+ }
4243
+ /** An order as the reports read it. Money in integer minor units. */
4244
+ interface ReportOrder {
4245
+ id: string;
4246
+ /** ISO 8601 UTC instant the sale was made. */
4247
+ at: string;
4248
+ /** Gross, including tax. */
4249
+ totalMinor: number;
4250
+ taxMinor: number;
4251
+ discountMinor: number;
4252
+ /** True when the order still owes money: its unpaid remainder is `unpaid`, not `unknown`. */
4253
+ needsPayment?: boolean;
4254
+ lines: ReportLine[];
4255
+ payments: ReportPayment[];
4256
+ taxes: ReportTax[];
4257
+ /** Refunds embedded on the order, undated (a store order's own list). Positive. */
4258
+ refunds: Array<{
4259
+ id: string;
4260
+ amountMinor: number;
4261
+ }>;
4262
+ }
4263
+ /** A refund dated by when it was made, counted on that store day. */
4264
+ interface ReportRefund {
4265
+ id: string;
4266
+ orderId: string;
4267
+ /** ISO 8601 UTC instant the refund was made. */
4268
+ at: string;
4269
+ /** Positive. */
4270
+ amountMinor: number;
4271
+ }
4272
+ /** The caller's product directory: a line's unit cost and first category. */
4273
+ type LineJoin = (line: {
4274
+ productId?: string;
4275
+ variantId?: string;
4276
+ }) => {
4277
+ unitCostMinor?: number | null;
4278
+ category?: ReportCategory;
4279
+ } | undefined;
4280
+
4281
+ type DatePreset = 'today' | 'yesterday' | 'thisWeek' | 'lastWeek' | 'thisMonth' | 'lastMonth';
4282
+ declare const DATE_PRESETS: readonly DatePreset[];
4283
+ /**
4284
+ * The preset's store days at `now` in `timezone` (IANA or 'device'). Weeks start Monday;
4285
+ * this week and this month end today, as WCPOS v2's date button clamps a preset to today.
4286
+ */
4287
+ declare function presetRange(preset: DatePreset, now: Date, timezone: string): DayRange;
4288
+
4289
+ interface Margin {
4290
+ costedNetMinor: number;
4291
+ costMinor: number;
4292
+ profitMinor: number;
4293
+ marginPct: number | null;
4294
+ missingLines: number;
4295
+ missingQuantity: number;
4296
+ }
4297
+ interface SalesTotals {
4298
+ grossMinor: number;
4299
+ netMinor: number;
4300
+ taxMinor: number;
4301
+ discountMinor: number;
4302
+ refundsMinor: number;
4303
+ embeddedRefundsMinor: number;
4304
+ orderCount: number;
4305
+ averageMinor: number;
4306
+ items: number;
4307
+ margin: Margin;
4308
+ }
4309
+ interface PaymentRow {
4310
+ method: string;
4311
+ label: string;
4312
+ amountMinor: number;
4313
+ orders: number;
4314
+ }
4315
+ interface GroupRow {
4316
+ key: string;
4317
+ name: string;
4318
+ quantity: number;
4319
+ netMinor: number;
4320
+ margin: Margin;
4321
+ }
4322
+ interface TaxRow {
4323
+ key: string;
4324
+ ratePpm: number;
4325
+ code?: string;
4326
+ label: string;
4327
+ taxMinor: number;
4328
+ netMinor: number | null;
4329
+ }
4330
+ interface DayPoint {
4331
+ day: StoreDay;
4332
+ grossMinor: number;
4333
+ orderCount: number;
4334
+ refundsMinor: number;
4335
+ }
4336
+ interface SalesFiguresInput {
4337
+ orders: readonly ReportOrder[];
4338
+ refunds?: readonly ReportRefund[];
4339
+ range: DayRange;
4340
+ compare?: DayRange;
4341
+ /** IANA zone of the store, or 'device'. */
4342
+ timezone: string;
4343
+ }
4344
+ interface SalesFigures {
4345
+ range: DayRange;
4346
+ totals: SalesTotals;
4347
+ payments: {
4348
+ rows: PaymentRow[];
4349
+ takenMinor: number;
4350
+ };
4351
+ products: GroupRow[];
4352
+ categories: GroupRow[];
4353
+ taxes: TaxRow[];
4354
+ refunds: {
4355
+ count: number;
4356
+ amountMinor: number;
4357
+ orders: number;
4358
+ };
4359
+ series: DayPoint[];
4360
+ comparison?: {
4361
+ range: DayRange;
4362
+ totals: SalesTotals;
4363
+ series: DayPoint[];
4364
+ };
4365
+ }
4366
+ declare function inRange(at: string, range: DayRange, timezone: string): boolean;
4367
+ declare function daysOf(range: DayRange): StoreDay[];
4368
+ /**
4369
+ * The range a report is compared with, period to date. Port of WCPOS v2 `useReportsPeriod`
4370
+ * (`screens/main/reports/context.tsx`). A week or month preset is a week or a month; any other
4371
+ * range is a day (one day), a week (up to seven) or a month (longer). A day goes back one day
4372
+ * (`previous`) or seven (`week`), and a week seven, so Monday to today meets the same weekdays of
4373
+ * the week before. A month starts a month earlier, a 31st clamped to a shorter month's last day:
4374
+ * a whole calendar month meets the whole month before, and any other range keeps its day count,
4375
+ * so 1–10 Nov meets 1–10 Oct.
4376
+ */
4377
+ declare function comparisonRange(range: DayRange, mode: 'previous' | 'week', preset?: DatePreset): DayRange;
4378
+ declare function marginOf(lines: readonly ReportLine[]): Margin;
4379
+ declare function salesFigures(input: SalesFiguresInput): SalesFigures;
4380
+
4381
+ declare function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin): ReportOrder;
4382
+ declare function reportOrderFromStoreOrder(order: StoreOrder, join?: LineJoin): ReportOrder;
4383
+ declare function reportRefundFromPosRefund(refund: PosRefund): ReportRefund | undefined;
4384
+
4385
+ export { APP_SETTING_DEFINITIONS, type Actor, type AddLineInput, type AppSettingCollection, type AppSettingDefinition, type AppSettingDoc, type AppSettingKey, type AppSettings, type AppliedDiscount, type ApprovalNeeded, type BackendNotFound, type BasketLine, type BroadcastChannelLike, COUPONS_UNSUPPORTED, CartError, type CartQuantityLine, type CashMovement, type CashMovementCollection, type CashierState, type CatalogueEntry, type CatalogueGridColumns, type CatalogueView, type CatalogueViewAction, type CatalogueViewState, type ChargeInput, type ChargeLine, type Closure, type ClosureApprovalStatus, type ClosureCollection, type ClosureContext, type ClosureScope, type CollectInput, type CollectOutcome, type CollectResult, type CommandTransport, type Correction, type CsvColumn, CurrencyProvider, type CurrencyProviderProps, type CustomerSummary, DATE_PRESETS, DEFAULT_APP_SETTINGS, DEFAULT_CATALOGUE_VIEW_STATE, DEFAULT_COOLDOWN_MS, DEFAULT_MIN_SCAN_CHARS, DEFAULT_RECEIPT_TEMPLATES, DEFAULT_WEDGE_SETTINGS, DISCOUNTS_UNSUPPORTED, DISPLAY_ACTIONS, DISPLAY_CHANNEL, DISPLAY_PROTOCOL_VERSION, DISPLAY_TEMPLATE, type DatePreset, type DayPoint, type DayRange, type DecodeRefusal, type DecodeResult, type Discount, type DisplayAction, type DisplayCart, type DisplayClock, type DisplayConfig, type DisplayEnvelope, type DisplayLine, type DisplayLink, type DisplayPayloads, type DisplayPayment, type DisplayState, type DisplayTemplate, type DisplayTotals, type DisplayTransport, type DisplayView, type DriverAvailability, type DriverCapabilities, type DriverStatus, type DriverStatusSource, ESCPOS_CODE_PAGES, type EarlierRefund, type EncodeEscPosOptions, type EscPosBuilder, type EscPosSink, type EscPosTransportOptions, type FeeLine, type FinalizeOptions, type FloatSuggestion, type GroupRow, HELLO_RETRY_MS, type HandoverSlipData, type HandoverSlipInput, type HttpTransportOptions, type LedgerRow, type LineItem, type LineJoin, type LineTaxLine, type LogEntry, type LogLevel, type LogSink, type Logger, MAX_MESSAGE_BYTES, MAX_TENDER_MINOR, MICROS_PER_MINOR, type Margin, type Movement$1 as Movement, type MovementType, type NoteDelivery, type OpenSale, type Order, type OrderBuilder, type OrderBuilderOptions, OrderContentMismatchError, type OrderCoupon, type OrderCouponContext, type OrderManager, type OrderManagerOptions, type OrderOutbox, type OrderOutboxOptions, type OrderRefundOutcome, type OrderTaxTotals, type OrderTransportContext, type OutboxCounts, type OutboxHealth, type OutboxState, PAPER_COLUMNS, PAYMENT_IN_MOTION, PRINTER_PROFILES_COLLECTION, PRODUCT_SORT_FIELDS, type ParkedOrderSummary, type Payment, type PaymentDriver, type PaymentDriverRegistry, type PaymentLegStatus, type PaymentMethod, type PaymentPhase, type PaymentRow, type PaymentTransport, type PlanLeg, type PosOrder, type PosOrderCoupon, type PosOrderLine, type PosOrderLocalWarning, PosOrderOpenClosedError, type PosOrderPayment, type PosOrderServerFailures, type PosOrderSyncStatus, type PosRefund, type PosRefundCollection, type PosRefundStatus, type PricedRefund, type PricedRefundLine, PrintError, type PrintErrorCode, type PrintJob, type PrintJobKind, type PrintQueue, type PrintQueueOptions, type PrintQueueState, type PrintTransport, type PrinterProfile, type PrinterProfileCollection, type ProductSort, type ProductSortValue, RECEIPT_SCHEMA_VERSION, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS, REOPENABLE_CODES, type RateTaxLine, type ReaderInfo, type ReceiptConfig, type ReceiptData, type ReceiptFiscal, type ReceiptLineItem, type ReceiptNode, type ReceiptPaper, type ReceiptRegister, type ReceiptSoftware, type ReceiptTemplateData, type ReceiptTemplateLine, type ReceiptTemplateOptions, type ReceiptTemplateRow, type RecordedFigures, RefundAnswerPendingError, type RefundableLine, type RefundableOrderLine, RegisterApprovalRequiredError, type RegisterBucket, RegisterCloseIncompleteError, type RegisterCommand, type RegisterCommandCollection, type RegisterCounters, type RegisterDocument, type RegisterFact, type RegisterHost, RegisterIdInvalidError, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, RegisterNeedsUpgradeError, type RegisterOutbox, type RegisterOutboxOptions, RegisterReapproveError, type RegisterSession, RegisterSessionAlreadyOpenError, RegisterSessionClosedError, type RegisterSessionCollection, RegisterSessionConflictError, RegisterSessionOpenClosedError, RegisterSessionRequiredError, type RegisterStore, RegisterTakeOverError, RegisterTenderInProgressError, type RenderReceiptOptions, type RenderSanitizeOptions, type ReopenRefusal, ReopenRefusedOrderError, type ReportCategory, type ReportLine, type ReportOrder, type ReportPayment, type ReportRefund, type ReportTax, type Repository, type ResolveStoreSettingsOptions, SALE_IN_TENDER, SALE_PARTLY_PAID, SALE_SAVING, SIMULATED_PROVIDER, SIMULATED_TIMING, SYSTEM_PRINTER_ID, SYSTEM_PRINT_TIMING, type SaleDiscountCodes, type SaleDiscountState, type SaleStage, type SalesFigures, type SalesFiguresInput, type SalesTotals, type SanitizeHtmlOptions, type ScanOfferResult, type ScanRejectReason, type ScanSession, type ScanSessionOptions, type SentOrder, type ShippingLine, type SimulatedDriverOptions, type SimulatedReaderId, type SplitTab, type StoreDay, type StoreSettingsResolution, type StoreSettingsState, type SwitchKind, type SwitchWarning, type SwitchWarningInput, type SwitchWarnings, type SystemPrintTransportOptions, TAX_ROUNDING_MIXED_NOTE, type TaxContext, type TaxLineInput, TaxProvider, type TaxProviderProps, type TaxRateMap, type TaxRow, type TenderAction, type TenderKey, type TenderLineId, type TenderPlan, type TenderRounding, type TenderState, type TenderView, type TenderVoid, type ThermalNode, type TraceKey, type TransportOutcome, UI_SCALES, UI_THEMES, type UiScale, type UiTheme, UnsupportedOrderVersionError, type UseBarcodeScannerOptions, type UseOrderOutboxOptions, type UseOrderOutboxResult, type UseOutboxHealthOptions, type UseOutboxHealthResult, type UseRegisterOutboxOptions, type UseRegisterOutboxResult, type UseRegisterSessionOptions, WEDGE_END_OF_SCAN_MS, type WedgeDetector, type WedgeDetectorOptions, type WedgeReplayResult, type WedgeSettings, type WedgeState, abandonSession, activePlan, addEntryToCart, addPosOrderCollection, addPrinterProfileCollection, addRegisterSessionCollection, adoptRegisterResults, advancePerpetual, allocateOrderDiscount, appSettingCollection, appSettingSchema, appSettings$, appliedMinor, backToSelling, bindRegister, buildClosureDocument, buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, buildXReportDocument, callbackSink, can, canMoveLeg, canVoidLeg, capturedMinor, cartQuantities, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureApprovalStatus, closureCommand, closureSchema, closureVariance, comparisonRange, computeOrderTax, consoleSink, countVariance, countsTowardPaid, createBackendNotFound, createBroadcastDisplayTransport, createDisplayLink, createEscPosTransport, createHttpCommandTransport, createLogger, createOrderBuilder, createOrderManager, createOrderOutbox, createPaymentDriverRegistry, createPrintQueue, createRegisterOutbox, createRepository, createScanSession, createSimulatedDriver, createSystemPrintTransport, createWedgeDetector, createWedgeState, csvCell, csvFromCells, daysOf, decode as decodeDisplayMessage, denominationTotal, denominations, deriveExpected, deriveSettled, displayCart, displayReducer, driverForMethod, encode as encodeDisplayMessage, encodeEscPos, ensureRegister, escpos, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, foldWedgeKey, formatClosureDate, getBoundRegisterId, getDeviceId, handoverSlip, hasValidRetailCheckDigit, inCategory, inMotionMinor, inRange, initTenderState, initialDisplayState, initialTenderState, isInMotion, isKnownSessionStatus, isLiveAtStore, isPartlyPaid, isRegisterRequeueable, isReopened, isRequeueable, isServerDecimal, labelKeys, legStatus, listCategories, makeEnvelope, marginOf, messageBytes, minorToDecimal, mintClosureNumber, mintUuid, movementCommand, movementFieldError, needsAttention, nextSaleCounter, normalizeAmount, normalizeCatalogueViewState, normalizeRetailCode, noteDelivery, observeRegister$, openSales, openSession, openSessionSelector, orderDraftSchema, outboxLogger, overThreshold, parkedOrderSummaries$, parseMinor, parseXml, planLegs, posOrderCollection, posOrderSchema, posOrdersLogger, posRefundCollection, posRefundSchema, presetRange, priceRefund, printerProfileCollection, printerProfileSchema, productCategories, productSortValue, quickTenderedAmounts, ratePpmFromPercent, readAppSettings, readBoundRegister, readRegister, reapproveClosure, receiptTemplateData, reconcileRegisterCommands, recordMovement, recordRegisterFact, refundableLines, registerCommandCollection, registerCommandSchema, registerCommandsLogger, registerFactsLogger, registerSessionCollection, registerSessionSchema, registerSessionsLogger, renderHtml, renderLogiclessTemplate, renderReceiptHtml, renderReceiptTemplate, renderThermalPreview, reopenRefusedOrder, replacedOrderIds, replayWedgeDetector, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund, requireOpenSession, resolveAppSettings, resolveGridColumns, resolveStoreSettings, restoreOrderDraft, retailCodeTwin, roundMicrosToMinor, roundedDue, saleLogger, salesFigures, sameSale, sanitizeHtml, searchProducts, selectClosureRows, sendOrderRefund, sessionOpenCommand, sessionTransitionCommand, sortProducts, stampSession, startCounting, stockOverlay$, stockOverlayAsOf$, stripBoundary, submitOrderRefund, suggestFloat, summarizeOutboxHealth, switchWarnings, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderRounding, tenderVoidCollection, tenderVoidSchema, toCsv, toOrderCreateEnvelope, toPrintError, unbindRegister, useAppSettings, useBarcodeScanner, useCashier, useCurrencyCode, useCurrencyFormatter, useCustomerDisplay, useOrderOutbox, useOutboxHealth, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, watchOutboxHealth, withPricingContext, index as woocommerceDiscountCodes, writeAppSetting, writeClosure, writeOrderDraft };