@tallyui/pos 3.11.0 → 3.13.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 (82) hide show
  1. package/dist/index.d.ts +1621 -358
  2. package/dist/index.js +6515 -4314
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +93 -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-state.ts +30 -0
  13. package/src/customer-display/index.ts +8 -0
  14. package/src/customer-display/protocol.ts +87 -0
  15. package/src/customer-display/snapshot.ts +65 -0
  16. package/src/index.ts +68 -11
  17. package/src/order/order-builder.ts +19 -2
  18. package/src/order/order-drafts.ts +17 -0
  19. package/src/order/types.ts +10 -3
  20. package/src/outbox/index.ts +5 -1
  21. package/src/outbox/outbox-health.ts +40 -0
  22. package/src/outbox/register-outbox.ts +59 -6
  23. package/src/outbox/safe-error.ts +11 -0
  24. package/src/outbox/types.ts +3 -1
  25. package/src/outbox/use-outbox-health.ts +22 -0
  26. package/src/outbox/use-register-outbox.ts +6 -0
  27. package/src/payment-driver/index.ts +8 -0
  28. package/src/payment-driver/registry.ts +39 -0
  29. package/src/payment-driver/simulated-driver.ts +104 -0
  30. package/src/payment-driver/types.ts +73 -0
  31. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  32. package/src/pos-order/command.ts +39 -17
  33. package/src/pos-order/finalize.ts +11 -3
  34. package/src/pos-order/index.ts +1 -0
  35. package/src/pos-order/note-delivery.ts +13 -0
  36. package/src/pos-order/reopen.ts +4 -2
  37. package/src/pos-order/schema.ts +7 -4
  38. package/src/pos-order/types.ts +5 -2
  39. package/src/print/index.ts +10 -0
  40. package/src/print/print-queue.ts +67 -0
  41. package/src/print/printer-profiles.ts +71 -0
  42. package/src/print/system-transport.ts +101 -0
  43. package/src/print/types.ts +40 -0
  44. package/src/receipt/index.ts +1 -0
  45. package/src/receipt/reprint.ts +149 -0
  46. package/src/receipt/types.ts +2 -0
  47. package/src/receipt-template/default-templates.ts +78 -0
  48. package/src/receipt-template/index.ts +15 -0
  49. package/src/receipt-template/parse-xml.ts +175 -0
  50. package/src/receipt-template/render-html.ts +152 -0
  51. package/src/receipt-template/render-receipt.ts +19 -0
  52. package/src/receipt-template/render-template.ts +35 -0
  53. package/src/receipt-template/sanitize-html.ts +146 -0
  54. package/src/receipt-template/template-data.ts +97 -0
  55. package/src/receipt-template/types.ts +49 -0
  56. package/src/refund/index.ts +2 -0
  57. package/src/refund/refundable-lines.ts +91 -0
  58. package/src/register/export-csv.ts +24 -35
  59. package/src/register/float-suggestion.ts +22 -0
  60. package/src/register/index.ts +8 -3
  61. package/src/register/register-adoption.ts +71 -2
  62. package/src/register/register-commands.ts +7 -4
  63. package/src/register/register-count.helpers.ts +4 -0
  64. package/src/register/session-store.ts +4 -1
  65. package/src/register/use-register-session.ts +112 -28
  66. package/src/reports/adapters.ts +67 -0
  67. package/src/reports/index.ts +5 -0
  68. package/src/reports/presets.ts +27 -0
  69. package/src/reports/sales-figures.ts +173 -0
  70. package/src/reports/types.ts +63 -0
  71. package/src/sale/cart.ts +15 -3
  72. package/src/sale/catalogue.ts +5 -1
  73. package/src/sale/index.ts +3 -1
  74. package/src/sale/open-sales.ts +40 -0
  75. package/src/sale/use-sale.ts +72 -8
  76. package/src/scanner/index.ts +6 -0
  77. package/src/scanner/scan-session.ts +84 -0
  78. package/src/scanner/use-barcode-scanner.ts +61 -0
  79. package/src/scanner/wedge-detector.ts +137 -0
  80. package/src/tender/cash-rounding.ts +74 -0
  81. package/src/tender/index.ts +4 -0
  82. 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, ProductCategory, TraitContext, OrderCreateLine, PaymentMethodKind, CommandServerRefs, CommandWarning, CommandError, 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, VariantSummary, CommandResult, AnyCommandEnvelope, CommandEnvelope, OrderCreatePayload, 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,93 @@ 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
+ type AppSettingKey = keyof AppSettings;
317
+ /** One key's default and its check: `parse` returns the value when valid, else `undefined`. */
318
+ interface AppSettingDefinition<T> {
319
+ default: T;
320
+ parse: (value: unknown) => T | undefined;
321
+ }
322
+ declare const APP_SETTING_DEFINITIONS: {
323
+ [K in AppSettingKey]: AppSettingDefinition<AppSettings[K]>;
324
+ };
325
+ declare const DEFAULT_APP_SETTINGS: AppSettings;
326
+ /** One stored setting. `value` is the JSON encoding of the setting's value, so the schema never changes when a key is added. */
327
+ interface AppSettingDoc {
328
+ key: string;
329
+ value: string;
330
+ }
331
+ declare const appSettingSchema: RxJsonSchema<AppSettingDoc>;
332
+ declare function appSettingCollection(): {
333
+ readonly schema: RxJsonSchema<AppSettingDoc>;
334
+ };
335
+ type AppSettingCollection = RxCollection<AppSettingDoc>;
336
+ declare function resolveAppSettings(docs: readonly AppSettingDoc[]): AppSettings;
337
+ declare function readAppSettings(collection: AppSettingCollection): Promise<AppSettings>;
338
+ declare function appSettings$(collection: AppSettingCollection): Observable<AppSettings>;
339
+ declare function writeAppSetting<K extends AppSettingKey>(collection: AppSettingCollection, key: K, value: AppSettings[K]): Promise<void>;
340
+
341
+ declare function useAppSettings(collection: AppSettingCollection | undefined): {
342
+ settings: AppSettings;
343
+ setSetting: <K extends AppSettingKey>(key: K, value: AppSettings[K]) => Promise<void>;
344
+ };
345
+
236
346
  interface Repository<T> {
237
347
  findById$(id: string): Observable<T | null>;
238
348
  findAll$(query?: MangoQuery<T>): Observable<T[]>;
@@ -249,6 +359,36 @@ declare function createRepository<T extends {
249
359
  id: string;
250
360
  }>(collection: RxCollection<T>): Repository<T>;
251
361
 
362
+ /** Local sale state; the order.create wire does not carry payment status yet. */
363
+
364
+ type PaymentLegStatus = 'pending' | 'authorized' | 'captured' | 'failed' | 'voided';
365
+ type Leg = {
366
+ amountMinor: number;
367
+ status?: PaymentLegStatus;
368
+ };
369
+ /** Defaults legacy legs to captured using v2 payments/types.ts PaymentStatus. */
370
+ declare function legStatus(leg: {
371
+ status?: PaymentLegStatus;
372
+ }): PaymentLegStatus;
373
+ /** Only captured money is paid: v2 payments/derive.ts countsTowardPaid (ADR 0040 D6). */
374
+ declare function countsTowardPaid(leg: {
375
+ status?: PaymentLegStatus;
376
+ }): boolean;
377
+ /** Pending and authorized are in motion: v2 payments/ledger.ts isInMotionPaymentStatus. */
378
+ declare function isInMotion(leg: {
379
+ status?: PaymentLegStatus;
380
+ }): boolean;
381
+ /** Sums integer minor units using v2 payments/derive.ts countsTowardPaid. */
382
+ declare function capturedMinor(legs: readonly Leg[]): number;
383
+ /** Sums holds in integer minor units using v2 payments/ledger.ts isInMotionPaymentStatus. */
384
+ declare function inMotionMinor(legs: readonly Leg[]): number;
385
+ /** Local transitions for v2 payments/ledger.ts isInMotionPaymentStatus and isFinalPaymentStatus. */
386
+ declare function canMoveLeg(from: PaymentLegStatus, to: PaymentLegStatus): boolean;
387
+ /** Voids live legs, captured only manually: v2 payments/ledger.ts partitionVoidableRows. */
388
+ declare function canVoidLeg(leg: {
389
+ status?: PaymentLegStatus;
390
+ }, method: PaymentMethodDescriptor): boolean;
391
+
252
392
  interface OrderCoupon {
253
393
  code: string;
254
394
  couponId: string;
@@ -339,6 +479,8 @@ interface LineItem {
339
479
  name: string;
340
480
  /** The variant's chosen options, name to value (#495). */
341
481
  attributes?: Record<string, string>;
482
+ /** The names in attributes the cashier picked for the variant's "Any" option groups (#495); absent when none. */
483
+ anyAttributes?: string[];
342
484
  sku: string;
343
485
  imageUrl?: string;
344
486
  unitPriceMinor: number;
@@ -398,6 +540,8 @@ interface AppliedDiscount extends Discount {
398
540
  interface Payment {
399
541
  id: string;
400
542
  method: string;
543
+ /** Absent means captured; only captured legs count toward paidMinor. */
544
+ status?: PaymentLegStatus;
401
545
  amountMinor: number;
402
546
  tenderedMinor?: number;
403
547
  changeMinor?: number;
@@ -422,6 +566,8 @@ interface AddLineInput {
422
566
  name: string;
423
567
  /** The variant's chosen options, name to value (#495). */
424
568
  attributes?: Record<string, string>;
569
+ /** The names in attributes the cashier picked for the variant's "Any" option groups (#495); absent when none. */
570
+ anyAttributes?: string[];
425
571
  sku?: string;
426
572
  imageUrl?: string;
427
573
  unitPrice: Money & {
@@ -475,6 +621,7 @@ interface OrderBuilder {
475
621
  applyOrderDiscount(discount: Discount): void;
476
622
  removeDiscount(discountId: string): void;
477
623
  addPayment(payment: Omit<Payment, 'id'>): string;
624
+ setPaymentStatus(paymentId: string, status: PaymentLegStatus): boolean;
478
625
  removePayment(paymentId: string): void;
479
626
  setCustomer(customer: CustomerSummary | null): void;
480
627
  setNote(note: string): void;
@@ -536,6 +683,10 @@ interface ParkedOrderSummary {
536
683
  totalMinor: number;
537
684
  parkedAt: string;
538
685
  source: 'local' | 'server';
686
+ /** Read from the draft's data (open-sale tabs, u19): the captured money, the balance still due and the first line's name. */
687
+ paidMinor?: number;
688
+ balanceDueMinor?: number;
689
+ firstItem?: string;
539
690
  }
540
691
  declare function writeOrderDraft(drafts: RxCollection, snapshot: Order): Promise<string>;
541
692
  declare function restoreOrderDraft(saved: Order, options: {
@@ -652,6 +803,8 @@ interface ReceiptData {
652
803
  changeDueMinor: number;
653
804
  footer: {
654
805
  note?: string;
806
+ /** ADR-083 condition 2: set only on a reprint of a till order whose note was not sent to the store. */
807
+ noteNotSent?: true;
655
808
  barcode?: string;
656
809
  };
657
810
  currency: string;
@@ -669,73 +822,6 @@ interface ReceiptConfig {
669
822
 
670
823
  declare function buildReceiptData(order: SentOrder, config: ReceiptConfig): ReceiptData;
671
824
 
672
- /**
673
- * Filters product documents by a cashier's search term, through traits, so
674
- * it works the same on every backend.
675
- *
676
- * Every word of the term must appear in the product name, SKU or barcode
677
- * (case-insensitive, any order). A term that exactly equals a barcode or SKU
678
- * returns just those products, so a scanner hit is never buried among name
679
- * matches. An empty term returns the input unchanged.
680
- */
681
- declare function searchProducts<Doc>(docs: Doc[], term: string, traits: ProductTraits<Doc>): Doc[];
682
-
683
- /** The product's categories: `getCategories`, else `getCategoryNames` with each name as its id. */
684
- declare function productCategories<Doc>(doc: Doc, traits: ProductTraits<Doc>): ProductCategory[];
685
- /** Every category across `docs`, once per id (the first name seen wins), sorted by name (natural, case-insensitive), ties by id. */
686
- declare function listCategories<Doc>(docs: readonly Doc[], traits: ProductTraits<Doc>): ProductCategory[];
687
- /** Whether `doc` is in the category with this id. */
688
- declare function inCategory<Doc>(doc: Doc, categoryId: string, traits: ProductTraits<Doc>): boolean;
689
-
690
- /** A sort on one field: ascending or descending. */
691
- interface ProductSort {
692
- field: string;
693
- dir: 'asc' | 'desc';
694
- }
695
- type ProductSortValue = string | number | undefined;
696
- /** The fields productSortValue knows, in the default column order. */
697
- declare const PRODUCT_SORT_FIELDS: readonly ["name", "sku", "barcode", "price", "stock", "category"];
698
- declare function productSortValue<Doc>(doc: Doc, field: string, traits: ProductTraits<Doc>, context?: TraitContext): ProductSortValue;
699
- declare function sortProducts<Doc>(docs: Doc[], sort: ProductSort | null | undefined, valueOf: (doc: Doc, field: string) => ProductSortValue): Doc[];
700
-
701
- type CatalogueView = 'grid' | 'table';
702
- type CatalogueGridColumns = 'auto' | 2 | 3 | 4 | 5 | 6 | 7 | 8;
703
- interface CatalogueViewState {
704
- view: CatalogueView;
705
- gridColumns: CatalogueGridColumns;
706
- sort: ProductSort | null;
707
- categoryId: string | null;
708
- }
709
- declare const DEFAULT_CATALOGUE_VIEW_STATE: CatalogueViewState;
710
- type CatalogueViewAction = {
711
- type: 'setView';
712
- view: CatalogueView;
713
- } | {
714
- type: 'setGridColumns';
715
- gridColumns: CatalogueGridColumns;
716
- } | {
717
- type: 'setSort';
718
- sort: ProductSort | null;
719
- } | {
720
- type: 'setCategory';
721
- categoryId: string | null;
722
- } | {
723
- type: 'replace';
724
- state: CatalogueViewState;
725
- };
726
- declare function catalogueViewReducer(state: CatalogueViewState, action: CatalogueViewAction): CatalogueViewState;
727
- declare function normalizeCatalogueViewState(raw: unknown, defaults?: CatalogueViewState): CatalogueViewState;
728
- declare function resolveGridColumns(gridColumns: CatalogueGridColumns, containerWidth: number): number;
729
-
730
- /** The `stock_levels` collection as a live map of key to stock value. */
731
- declare function stockOverlay$(collection: RxCollection): Observable<Map<string, unknown>>;
732
- /**
733
- * When the overlay was last confirmed by a successful pass (ISO 8601), or
734
- * undefined before any pass. Read from the collection's local document, so a
735
- * tab or screen that does not hold the runner can show it too.
736
- */
737
- declare function stockOverlayAsOf$(collection: RxCollection): Observable<string | undefined>;
738
-
739
825
  type PosOrderSyncStatus = 'pending' | 'applied' | 'rejected';
740
826
  type PosOrderLocalWarning = {
741
827
  code: 'customer_omitted';
@@ -772,6 +858,8 @@ interface PosOrderLine {
772
858
  unitPriceMinor: number;
773
859
  /** The chosen variation attributes, name to value (pos_orders v9, #495). */
774
860
  attributes?: Record<string, string>;
861
+ /** The names in attributes the cashier picked for the variant's "Any" option groups (#495); absent when none. */
862
+ anyAttributes?: string[];
775
863
  /** The catalogue's regular unit price, in the line's own tax mode like `unitPriceMinor` (pos_orders v9, ADR-077 d2). */
776
864
  regularUnitPriceMinor?: number;
777
865
  /** Line discounts plus the allocated order-discount share, in the line's own tax mode (ADR-062). */
@@ -816,6 +904,7 @@ interface PosOrder {
816
904
  name?: string;
817
905
  email?: string;
818
906
  } | null;
907
+ /** The sale's note; sent as order.create version 7's `note` (ADR-083), cut to ORDER_NOTE_MAX when frozen. */
819
908
  note?: string;
820
909
  registerId?: string;
821
910
  /**
@@ -833,9 +922,9 @@ interface PosOrder {
833
922
  * The order.create version every attempt under this `commandId` goes out at: the outbox records it before the first
834
923
  * send, and lowers it only on a downgrade (ADR-065 amendment). Absent means not sent yet (or requeued).
835
924
  */
836
- sentVersion?: 1 | 2 | 3 | 4 | 5 | 6;
925
+ sentVersion?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
837
926
  /** The version first tried, before the downgrade (the order's audit). */
838
- downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6;
927
+ downgradedFrom?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
839
928
  /** ADR-065: the receipt's display figures, in integer minor units of `currency` at `exponent`. */
840
929
  display?: DisplayTotals & {
841
930
  currency: string;
@@ -868,130 +957,1007 @@ interface PosOrder {
868
957
  reopenedAt?: string;
869
958
  }
870
959
 
871
- /** RFC 9562 UUIDv7: monotonic with no arguments; stateless with an explicit timestamp or random source. */
872
- declare function uuidv7(now?: number, randomBytes?: (n: number) => Uint8Array): string;
873
-
874
- interface FinalizeOptions {
875
- localWarnings?: PosOrderLocalWarning[];
876
- registerId?: string;
877
- cashierRef?: string;
878
- now?: Date;
879
- /** Tests only: replaces uuidv7. Every id it returns must be at most 255 characters with no NUL (order.create's bound). */
880
- newId?: () => string;
881
- /** The store's `order.create` capability (ADR-062); `undefined` is treated as 1. */
882
- capabilities?: ServerCapabilities;
883
- }
884
960
  /**
885
- * Turns a fully paid builder Order into a pending PosOrder without mutating it. The PosOrder holds the sent form,
886
- * frozen: line names and v3 discount labels are cut to PAYLOAD_STRING_MAX with NUL stripped (`cutText`), and a
887
- * customer email or id the shape check would refuse is left out, so `toOrderCreateEnvelope` sends it unchanged.
961
+ * Receipt data for reprinting the till's own stored order (ADR-081). A stored order keeps no discount labels: the order discount
962
+ * is one row, `Order discount`, in the display mode when lines were converted. Without `display`, a converted line's discount is in its own mode.
888
963
  */
889
- declare function finalizeOrder(order: Order, options?: FinalizeOptions): PosOrder;
964
+ declare function buildReceiptDataFromPosOrder(order: PosOrder, config: ReceiptConfig): ReceiptData;
965
+ /** Receipt data for reprinting an order read from the store with `getOrders`/`listOrders` (ADR-081). */
966
+ declare function buildReceiptDataFromStoreOrder(order: StoreOrder, config: ReceiptConfig): ReceiptData;
890
967
 
891
- declare class UnsupportedOrderVersionError extends Error {
892
- readonly needed: number;
893
- readonly supported: number;
894
- readonly code = "UNSUPPORTED_ORDER_VERSION";
895
- constructor(needed: number, supported: number);
968
+ type DrawerConnector = 'pin2' | 'pin5';
969
+ type ThermalNode = ReceiptNode | TextNode | RawTextNode | BoldNode | UnderlineNode | InvertNode | SizeNode | AlignNode | RowNode | ColNode | LineNode | BarcodeNode | QrcodeNode | ImageNode | CutNode | FeedNode | DrawerNode;
970
+ interface ReceiptNode {
971
+ type: 'receipt';
972
+ paperWidth: number;
973
+ children: ThermalNode[];
974
+ }
975
+ interface RawTextNode {
976
+ type: 'raw-text';
977
+ value: string;
978
+ }
979
+ interface TextNode {
980
+ type: 'text';
981
+ children: ThermalNode[];
982
+ }
983
+ interface BoldNode {
984
+ type: 'bold';
985
+ children: ThermalNode[];
986
+ }
987
+ interface UnderlineNode {
988
+ type: 'underline';
989
+ children: ThermalNode[];
990
+ }
991
+ interface InvertNode {
992
+ type: 'invert';
993
+ children: ThermalNode[];
994
+ }
995
+ interface SizeNode {
996
+ type: 'size';
997
+ width: number;
998
+ height: number;
999
+ children: ThermalNode[];
1000
+ }
1001
+ interface AlignNode {
1002
+ type: 'align';
1003
+ mode: 'left' | 'center' | 'right';
1004
+ children: ThermalNode[];
1005
+ }
1006
+ interface RowNode {
1007
+ type: 'row';
1008
+ children: ColNode[];
1009
+ }
1010
+ interface ColNode {
1011
+ type: 'col';
1012
+ width: number | '*';
1013
+ align: 'left' | 'right';
1014
+ children: ThermalNode[];
1015
+ }
1016
+ interface LineNode {
1017
+ type: 'line';
1018
+ style: 'single' | 'double' | 'dashed' | 'dotted';
1019
+ }
1020
+ interface BarcodeNode {
1021
+ type: 'barcode';
1022
+ barcodeType: string;
1023
+ height: number;
1024
+ value: string;
1025
+ }
1026
+ interface QrcodeNode {
1027
+ type: 'qrcode';
1028
+ size: number;
1029
+ value: string;
1030
+ }
1031
+ interface ImageNode {
1032
+ type: 'image';
1033
+ src: string;
1034
+ width: number;
1035
+ }
1036
+ interface CutNode {
1037
+ type: 'cut';
1038
+ cutType: 'full' | 'partial';
1039
+ }
1040
+ interface FeedNode {
1041
+ type: 'feed';
1042
+ lines: number;
1043
+ }
1044
+ interface DrawerNode {
1045
+ type: 'drawer';
1046
+ connector?: DrawerConnector;
896
1047
  }
897
- /**
898
- * Builds the ADR-038 order.create envelope for a PosOrder. It sends the stored order unchanged, so every resend of
899
- * an order is byte-identical, and an order stored by an older till goes out exactly as that till sent it:
900
- * `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
901
- * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
902
- * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
903
- * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
904
- */
905
- declare function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt?: number, options?: {
906
- maxVersion?: number;
907
- }): OrderCreateEnvelope;
908
1048
 
1049
+ /** Parse a thermal XML template string into an AST using the native DOMParser or xmldom. */
1050
+ declare function parseXml(xml: string): ReceiptNode;
1051
+
1052
+ declare function renderHtml(ast: ReceiptNode): string;
1053
+
1054
+ interface SanitizeHtmlOptions {
1055
+ /** Additional tag names to allow beyond DOMPurify's default HTML profile. */
1056
+ addTags?: string[];
1057
+ /** Additional attribute names to allow beyond DOMPurify's default HTML profile. */
1058
+ addAttributes?: string[];
1059
+ }
909
1060
  /**
910
- * Version 1 adds the optional `sessionId` (ADR-032); nothing else changed from version 0.
911
- * Version 2 adds three optional fields and changes nothing else: `lateSessionId` (ADR-032, late
912
- * sale), and ADR-065's `display` and `taxByRate`, declared ahead of the job that writes them so a
913
- * till migrates once. Create the collection with `posOrderCollection()`, never with this schema
914
- * alone: RxDB refuses a version above 0 without its migration strategies.
915
- * 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.
916
- * Version 4 adds the optional `localWarnings` and `serverFailures` (the outbox's stuck clock start, latest reason and
917
- * isolation, restored when an outbox starts), and changes nothing else.
918
- * Version 5 lets `sentVersion` and `downgradedFrom` be 4 (order.create version 4, #286), and changes nothing else. Its
919
- * migration sets a row's missing `sentVersion` to its content version, the version any earlier attempt went out at.
920
- * Like version 4 (ADR-069), it is one-way: an older build shows no orders.
921
- * Version 6 adds `taxRounding`, the strategy the sale's figures were computed with (#287; never sent), and changes
922
- * nothing else. Its migration sets it on every older row. It is one-way like version 5.
923
- * Version 7 adds `saleId`, the sale order's id (ADR-072; never sent), and changes nothing else. Its migration is the
924
- * identity: older orders have no `saleId`. It is one-way like version 6.
925
- * Version 8 adds fees, shipping, custom lines (ADR-075) and the woocommerce tax rounding (ADR-076), and changes nothing else.
926
- * It also stores the WooCommerce 6dp net (`netMicros`) under the woocommerce rounding (ADR-076 amendment).
927
- * Its migration is the identity. It is one-way like version 7.
928
- * Version 9 adds the order's `coupons` and the receipt's `display.coupons` (ADR-077 d2), and a line's `attributes` (#495)
929
- * and `regularUnitPriceMinor` (ADR-077 d2), and `reopenedAt`: when a refused order was reopened as a parked sale (ADR-077 d4b), and lets `sentVersion` and `downgradedFrom` be 6 (order.create version 6, ADR-077 d4), and changes nothing else.
930
- * `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them only at version 6.
931
- * Its migration is the identity. It is one-way like version 8.
932
- */
933
- declare const posOrderSchema: RxJsonSchema<PosOrder>;
934
- /**
935
- * The `pos_orders` collection config, with its migration strategies. Open the collection with
936
- * `addPosOrderCollection(db)`, which uses this and settles the migration safely; adding this config
937
- * directly leaves RxDB's own open path. `pos_orders` holds sales not yet sent, so no step may drop a
938
- * document: versions 1 and 2 only add optional fields, so every order from version 0 or 1 passes
939
- * unchanged.
1061
+ * Sanitize rendered receipt HTML before it is inserted into an admin/browser DOM
1062
+ * (or a native WebView via `srcDoc`).
940
1063
  *
941
- * Within one run, RxDB 16.21 keeps an order that fails the new schema's validation: with a
942
- * validating storage the migration stops with DM4 and the order stays in the older version's
943
- * storage; without one it is copied as is. **Across runs, RxDB's own open path can lose it**: a
944
- * failed run can leave its checkpoint past that order, and the next run then removes the older
945
- * version's storage without copying it. `addPosOrderCollection` resets that checkpoint, so use it
946
- * (`migration.test.ts`).
1064
+ * The default profile deliberately excludes SVG/MathML and strips scripts,
1065
+ * event handlers, and unsafe URL protocols while preserving normal receipt HTML.
1066
+ *
1067
+ * Three execution paths, in priority order:
1068
+ * 1. Browser/DOM with `window.document` → DOMPurify (the strongest profile).
1069
+ * 2. A runtime that exposes a global `DOMParser` (e.g. jsdom/SSR) → DOM walk.
1070
+ * 3. React Native, which has neither → parse via `@xmldom/xmldom` and walk.
1071
+ *
1072
+ * The xmldom fallback mirrors `parse-xml.ts`, which already uses xmldom on
1073
+ * native. Without it, native runtimes hit the escaped-text last resort and the
1074
+ * receipt preview renders raw HTML markup as visible text instead of HTML.
947
1075
  */
948
- declare function posOrderCollection(): {
949
- schema: RxJsonSchema<PosOrder>;
950
- migrationStrategies: MigrationStrategies;
951
- };
1076
+ declare function sanitizeHtml(html: string, options?: SanitizeHtmlOptions): string;
952
1077
 
953
- /** `addPosOrderCollection`'s logger: attach a sink to see, for example, the status writes a closing open dropped. */
954
- declare const posOrdersLogger: Logger;
955
- /**
956
- * `addPosOrderCollection` stopped, before any further write, because its database is closing: it
957
- * was called once `close()` had begun, the close cancelled its migration (RxDB 17.5), or the close
958
- * stopped waiting for it (after `POS_ORDER_MIGRATION_CLOSE_WAIT_MS`). No order is lost: reopen the
959
- * database and call it again.
960
- */
961
- declare class PosOrderOpenClosedError extends Error {
962
- readonly databaseName: string;
963
- readonly code = "POS_ORDER_OPEN_CLOSED";
964
- constructor(databaseName: string);
1078
+ interface RenderSanitizeOptions extends SanitizeHtmlOptions {
1079
+ /** Disable sanitization only for trusted test/debug output. Defaults to true. */
1080
+ sanitize?: boolean;
965
1081
  }
966
- /**
967
- * Adds `pos_orders` to `db` and resolves once no order of an older version is left to migrate.
968
- * On DM4 it rejects after the migration has stopped and closes the collection. It rejects with
969
- * `PosOrderOpenClosedError` when the database is closing. `closeWaitMs` is for tests only.
970
- * See `openMigratedCollection` for the migration and close mechanism.
971
- */
972
- declare function addPosOrderCollection(db: RxDatabase, closeWaitMs?: number): Promise<RxCollection<PosOrder>>;
1082
+ /** Mustache only. */
1083
+ declare function renderReceiptTemplate(template: string, data: object): string;
1084
+ /** Mustache HTML template, then sanitize (unless sanitize === false). No <barcode>/<qrcode> resolution. */
1085
+ declare function renderLogiclessTemplate(template: string, data: object, options?: RenderSanitizeOptions): string;
1086
+ /** Mustache, then parseXml, then renderHtml, then sanitize (unless sanitize === false). */
1087
+ declare function renderThermalPreview(template: string, data: object, options?: RenderSanitizeOptions): string;
973
1088
 
974
- /**
975
- * Returns this device's id (a UUIDv7), stored under `key` in `storage` (web storage, or an app's
976
- * equivalent) and minted on first use; medusapos passes `'medusapos.register_id'`. With no storage,
977
- * or one that throws on read or write, it falls back to one id per process.
978
- */
979
- declare function getDeviceId(storage: {
980
- getItem(key: string): string | null;
981
- setItem(key: string, value: string): void;
982
- } | null, key: string): string;
1089
+ interface ReceiptTemplateRow {
1090
+ label: string;
1091
+ amount: string;
1092
+ }
1093
+ interface ReceiptTemplateLine {
1094
+ name: string;
1095
+ /** `Name: value` per variant option, in `attributes` order. */
1096
+ options: {
1097
+ text: string;
1098
+ }[];
1099
+ /** `<quantity> × <unit price>`. */
1100
+ detail: string;
1101
+ /** displayAmountMinor, before any discount. */
1102
+ amount: string;
1103
+ /** The line's own displayDiscounts; amount carries a leading `−`. */
1104
+ discounts: ReceiptTemplateRow[];
1105
+ }
1106
+ interface ReceiptTemplateData {
1107
+ store: {
1108
+ name: string;
1109
+ addressLines: {
1110
+ line: string;
1111
+ }[];
1112
+ };
1113
+ document: {
1114
+ title: string;
1115
+ isReprint: boolean;
1116
+ reprintCount: number;
1117
+ };
1118
+ order: {
1119
+ number: string;
1120
+ date: string;
1121
+ };
1122
+ cashier: string;
1123
+ register: string;
1124
+ customer: string;
1125
+ lines: ReceiptTemplateLine[];
1126
+ subtotal: string;
1127
+ lineDiscount: string;
1128
+ orderDiscount: string;
1129
+ charges: ReceiptTemplateRow[];
1130
+ taxes: ReceiptTemplateRow[];
1131
+ total: string;
1132
+ payments: {
1133
+ method: string;
1134
+ amount: string;
1135
+ reference: string;
1136
+ }[];
1137
+ change: string;
1138
+ note: string;
1139
+ qrPayload: string;
1140
+ }
1141
+ interface ReceiptTemplateOptions {
1142
+ /** Default: formatMoney({ amount: minor, currency }) ?? ''. */
1143
+ formatMoney?: (minor: number, currency: string) => string;
1144
+ /** Default: Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' });
1145
+ * an unparseable date is returned as given. */
1146
+ formatDate?: (iso: string) => string;
1147
+ /** Default: 'cash' → 'Cash', 'external' → 'Card terminal', anything else as given. */
1148
+ paymentLabel?: (method: string) => string;
1149
+ }
1150
+ declare function receiptTemplateData(receipt: ReceiptData, options?: ReceiptTemplateOptions): ReceiptTemplateData;
983
1151
 
984
- /**
985
- * The orders a cashier must look at: rejected, applied with a known warning, taken after their
986
- * session closed (`lateSessionId`) or with local warnings (whatever the sync status), or pending with a `commandId` in
987
- * `stuckCommandIds` (the outbox's `OutboxState.stuck`: the store keeps failing it), newest first.
988
- * A warning code this till version doesn't know is not shown here (`knownWarnings`). Never changes `orders`.
989
- * `register_session_unknown` is not shown, because the store counts the order once its session arrives (ADR-078).
990
- * A refused order is left out once its finalized successor is in `orders`.
991
- */
992
- declare function needsAttention(orders: PosOrder[], options?: {
993
- stuckCommandIds?: readonly string[];
994
- }): PosOrder[];
1152
+ type ReceiptPaper = '58mm' | '80mm';
1153
+ /** Characters per line (v2 encode-receipt.ts:18). */
1154
+ declare const PAPER_COLUMNS: Record<ReceiptPaper, number>;
1155
+ declare const DEFAULT_RECEIPT_TEMPLATES: Record<ReceiptPaper, string>;
1156
+
1157
+ interface RenderReceiptOptions extends ReceiptTemplateOptions {
1158
+ /** Default '80mm'. Picks DEFAULT_RECEIPT_TEMPLATES[paper] when no template is given. */
1159
+ paper?: ReceiptPaper;
1160
+ /** A thermal-XML Mustache template over ReceiptTemplateData. */
1161
+ template?: string;
1162
+ }
1163
+ /** receiptTemplateData, then renderThermalPreview (sanitized). Needs a global DOMParser (browsers, jsdom). */
1164
+ declare function renderReceiptHtml(receipt: ReceiptData, options?: RenderReceiptOptions): string;
1165
+
1166
+ declare const DISPLAY_PROTOCOL_VERSION = 1;
1167
+ type PaymentPhase = 'started' | 'approved' | 'declined' | 'complete';
1168
+ interface DisplayTemplate {
1169
+ id: string | number;
1170
+ version: number;
1171
+ }
1172
+ /** The cart snapshot: the receipt as it stands, and whether lines were dropped to fit the message cap. */
1173
+ interface DisplayCart {
1174
+ receipt: ReceiptData;
1175
+ linesTruncated: boolean;
1176
+ }
1177
+ interface DisplayPayment {
1178
+ state: PaymentPhase;
1179
+ leg?: {
1180
+ method: string;
1181
+ amountMinor: number;
1182
+ };
1183
+ message?: string;
1184
+ }
1185
+ interface DisplayConfig {
1186
+ contract: '1.0';
1187
+ display: {
1188
+ id: string;
1189
+ name: string;
1190
+ };
1191
+ store: {
1192
+ id: string;
1193
+ name: string;
1194
+ currency: string;
1195
+ locale: string;
1196
+ timezone?: string;
1197
+ logo?: string;
1198
+ };
1199
+ presentation_hints: Record<string, unknown>;
1200
+ i18n: Record<string, string>;
1201
+ template?: DisplayTemplate;
1202
+ idle: {
1203
+ afterCompleteMs: number;
1204
+ };
1205
+ }
1206
+ interface DisplayPayloads {
1207
+ 'cart.updated': DisplayCart;
1208
+ 'payment.state': DisplayCart & DisplayPayment;
1209
+ 'display.idle': {
1210
+ reason: string;
1211
+ };
1212
+ /** Sent by the display to the till. */
1213
+ 'display.hello': {
1214
+ template: DisplayTemplate;
1215
+ };
1216
+ 'display.config': DisplayConfig;
1217
+ }
1218
+ type DisplayAction = keyof DisplayPayloads;
1219
+ declare const DISPLAY_ACTIONS: readonly DisplayAction[];
1220
+ type DisplayEnvelope<A extends DisplayAction = DisplayAction> = {
1221
+ [K in A]: {
1222
+ tally: 1;
1223
+ id: string;
1224
+ action: K;
1225
+ payload: DisplayPayloads[K];
1226
+ };
1227
+ }[A];
1228
+ declare function makeEnvelope<A extends DisplayAction>(action: A, payload: DisplayPayloads[A], id?: string): DisplayEnvelope<A>;
1229
+ declare function displayCart(receipt: ReceiptData): DisplayCart;
1230
+ type DecodeRefusal = 'malformed' | 'version' | 'action' | 'payload';
1231
+ type DecodeResult = {
1232
+ ok: true;
1233
+ envelope: DisplayEnvelope;
1234
+ } | {
1235
+ ok: false;
1236
+ refusal: DecodeRefusal;
1237
+ };
1238
+ /** Reads a message from the other side. Never throws: anything it cannot trust comes back as a refusal. */
1239
+ declare function decode(text: unknown): DecodeResult;
1240
+
1241
+ /** The display contract caps each message at 200 KiB: UTF-8 bytes of the JSON text. */
1242
+ declare const MAX_MESSAGE_BYTES: number;
1243
+ declare function messageBytes(text: string): number;
1244
+ /**
1245
+ * Serialises a message within MAX_MESSAGE_BYTES, trimming a copy in v2's order. If it is still over after every
1246
+ * step (a non-cart action, or a receipt whose fixed fields alone are too big), the text is returned anyway, as v2
1247
+ * sends it; check with messageBytes.
1248
+ */
1249
+ declare function encode(envelope: DisplayEnvelope): string;
1250
+
1251
+ /** What the customer display shows: nothing to sell, the cart, or a payment in progress or complete. */
1252
+ type DisplayView = {
1253
+ screen: 'idle';
1254
+ reason: string;
1255
+ } | {
1256
+ screen: 'cart';
1257
+ cart: DisplayCart;
1258
+ } | {
1259
+ screen: 'payment';
1260
+ cart: DisplayCart;
1261
+ payment: DisplayPayment;
1262
+ };
1263
+ interface DisplayState {
1264
+ config: DisplayConfig | null;
1265
+ view: DisplayView;
1266
+ }
1267
+ declare const initialDisplayState: DisplayState;
1268
+ /** The display side's state, driven by decoded messages from the till. */
1269
+ declare function displayReducer(state: DisplayState, envelope: DisplayEnvelope): DisplayState;
1270
+
1271
+ /**
1272
+ * Filters product documents by a cashier's search term, through traits, so
1273
+ * it works the same on every backend.
1274
+ *
1275
+ * Every word of the term must appear in the product name, SKU or barcode
1276
+ * (case-insensitive, any order). A term that exactly equals a barcode or SKU
1277
+ * returns just those products, so a scanner hit is never buried among name
1278
+ * matches. An empty term returns the input unchanged.
1279
+ */
1280
+ declare function searchProducts<Doc>(docs: Doc[], term: string, traits: ProductTraits<Doc>): Doc[];
1281
+
1282
+ /** The product's categories: `getCategories`, else `getCategoryNames` with each name as its id. */
1283
+ declare function productCategories<Doc>(doc: Doc, traits: ProductTraits<Doc>): ProductCategory[];
1284
+ /** Every category across `docs`, once per id (the first name seen wins), sorted by name (natural, case-insensitive), ties by id. */
1285
+ declare function listCategories<Doc>(docs: readonly Doc[], traits: ProductTraits<Doc>): ProductCategory[];
1286
+ /** Whether `doc` is in the category with this id. */
1287
+ declare function inCategory<Doc>(doc: Doc, categoryId: string, traits: ProductTraits<Doc>): boolean;
1288
+
1289
+ /** A sort on one field: ascending or descending. */
1290
+ interface ProductSort {
1291
+ field: string;
1292
+ dir: 'asc' | 'desc';
1293
+ }
1294
+ type ProductSortValue = string | number | undefined;
1295
+ /** The fields productSortValue knows, in the default column order. */
1296
+ declare const PRODUCT_SORT_FIELDS: readonly ["name", "sku", "barcode", "price", "stock", "category"];
1297
+ declare function productSortValue<Doc>(doc: Doc, field: string, traits: ProductTraits<Doc>, context?: TraitContext): ProductSortValue;
1298
+ declare function sortProducts<Doc>(docs: Doc[], sort: ProductSort | null | undefined, valueOf: (doc: Doc, field: string) => ProductSortValue): Doc[];
1299
+
1300
+ type CatalogueView = 'grid' | 'table';
1301
+ type CatalogueGridColumns = 'auto' | 2 | 3 | 4 | 5 | 6 | 7 | 8;
1302
+ interface CatalogueViewState {
1303
+ view: CatalogueView;
1304
+ gridColumns: CatalogueGridColumns;
1305
+ sort: ProductSort | null;
1306
+ categoryId: string | null;
1307
+ }
1308
+ declare const DEFAULT_CATALOGUE_VIEW_STATE: CatalogueViewState;
1309
+ type CatalogueViewAction = {
1310
+ type: 'setView';
1311
+ view: CatalogueView;
1312
+ } | {
1313
+ type: 'setGridColumns';
1314
+ gridColumns: CatalogueGridColumns;
1315
+ } | {
1316
+ type: 'setSort';
1317
+ sort: ProductSort | null;
1318
+ } | {
1319
+ type: 'setCategory';
1320
+ categoryId: string | null;
1321
+ } | {
1322
+ type: 'replace';
1323
+ state: CatalogueViewState;
1324
+ };
1325
+ declare function catalogueViewReducer(state: CatalogueViewState, action: CatalogueViewAction): CatalogueViewState;
1326
+ declare function normalizeCatalogueViewState(raw: unknown, defaults?: CatalogueViewState): CatalogueViewState;
1327
+ declare function resolveGridColumns(gridColumns: CatalogueGridColumns, containerWidth: number): number;
1328
+
1329
+ /** The `stock_levels` collection as a live map of key to stock value. */
1330
+ declare function stockOverlay$(collection: RxCollection): Observable<Map<string, unknown>>;
1331
+ /**
1332
+ * When the overlay was last confirmed by a successful pass (ISO 8601), or
1333
+ * undefined before any pass. Read from the collection's local document, so a
1334
+ * tab or screen that does not hold the runner can show it too.
1335
+ */
1336
+ declare function stockOverlayAsOf$(collection: RxCollection): Observable<string | undefined>;
1337
+
1338
+ /** The wedge detector distinguishes scanner bursts from typing using a folded
1339
+ * running average of inter-key gaps. Live and replay paths share the reducer. */
1340
+ interface WedgeSettings {
1341
+ /** Folded-average gap (ms) below which input latches as a scan. */
1342
+ threshold: number;
1343
+ /** Stripped only when it equals the first key. */
1344
+ prefix: string;
1345
+ /** Stripped only when it equals the last key. */
1346
+ suffix: string;
1347
+ }
1348
+ /** v2 store defaults: threshold 24 ms (stores.ts barcode_scanning_avg_time_input_threshold), no prefix/suffix. */
1349
+ declare const DEFAULT_WEDGE_SETTINGS: WedgeSettings;
1350
+ /** v2 store default barcode_scanning_min_chars. */
1351
+ declare const DEFAULT_MIN_SCAN_CHARS = 8;
1352
+ /** End-of-scan settle: a burst is complete this long after its last key. */
1353
+ declare const WEDGE_END_OF_SCAN_MS = 150;
1354
+ interface WedgeState {
1355
+ avg: number;
1356
+ detecting: boolean;
1357
+ stack: string[];
1358
+ lastTimeMs: number | null;
1359
+ }
1360
+ declare function createWedgeState(): WedgeState;
1361
+ /** Fold one key, mutating and returning state. Kept bug-for-bug with v2:
1362
+ * only length-1 keys advance timing; the first gap is +Infinity; the average
1363
+ * folds as (avg + gap) / 2. Scanning latches below threshold for the burst;
1364
+ * a slow key outside a burst resets the average and restarts the stack. */
1365
+ declare function foldWedgeKey(state: WedgeState, key: string, timeMs: number, threshold: number): WedgeState;
1366
+ /** Strip a configured prefix/suffix only when it equals the single key at
1367
+ * that edge of the stack — never as a substring. */
1368
+ declare function stripBoundary(stack: string[], settings: WedgeSettings): string;
1369
+ interface TraceKey {
1370
+ key: string;
1371
+ timeMs: number;
1372
+ }
1373
+ interface WedgeReplayResult {
1374
+ /** Whether the detector would latch onto this trace as a scan. */
1375
+ detectedAsScan: boolean;
1376
+ /** The barcode the detector would emit, with prefix/suffix stripped. */
1377
+ code: string;
1378
+ }
1379
+ /** Replay the detector over a completed keystroke trace. */
1380
+ declare function replayWedgeDetector(keys: TraceKey[], settings: WedgeSettings): WedgeReplayResult;
1381
+ interface WedgeDetectorOptions {
1382
+ /** Read current settings per keystroke so live changes apply. */
1383
+ getSettings: () => WedgeSettings;
1384
+ /** A completed burst, prefix/suffix already stripped. */
1385
+ onScan: (code: string) => void;
1386
+ /** Injectable clock/timers so hosts and tests control time. */
1387
+ now?: () => number;
1388
+ setTimeout?: (fn: () => void, ms: number) => unknown;
1389
+ clearTimeout?: (handle: unknown) => void;
1390
+ }
1391
+ interface WedgeDetector {
1392
+ /** True for a latched burst key: the host must prevent its default action. */
1393
+ handleKey: (key: string, timeMs?: number) => boolean;
1394
+ /** Cancel any pending end-of-scan timer on host teardown. */
1395
+ dispose: () => void;
1396
+ }
1397
+ /** Stream keys through the reducer, emitting after the settle window and
1398
+ * once the quiet period exceeds the threshold, mirroring the original hook. */
1399
+ declare function createWedgeDetector(options: WedgeDetectorOptions): WedgeDetector;
1400
+
1401
+ /** Suppress repeated reads within a cooldown and reject retail check-digit misreads. */
1402
+ declare const DEFAULT_COOLDOWN_MS = 1200;
1403
+ type ScanRejectReason = 'cooldown' | 'bad-check-digit';
1404
+ interface ScanOfferResult {
1405
+ accepted: boolean;
1406
+ reason?: ScanRejectReason;
1407
+ }
1408
+ interface ScanSessionOptions {
1409
+ onAccept: (code: string, symbology?: string) => void;
1410
+ cooldownMs?: number;
1411
+ now?: () => number;
1412
+ }
1413
+ interface ScanSession {
1414
+ offer: (code: string, symbology?: string) => ScanOfferResult;
1415
+ reset: () => void;
1416
+ }
1417
+ /** Report the printed UPC-A digits by dropping an implied zero from labelled
1418
+ * EAN-13/UPC reads. Unlabelled reads and printed 8-digit UPC-E stay unchanged. */
1419
+ declare function normalizeRetailCode(code: string, symbology?: string): string;
1420
+ /** Validate EAN-13/EAN-8/UPC-A check digits; non-retail-length inputs pass. */
1421
+ declare function hasValidRetailCheckDigit(code: string): boolean;
1422
+ /** The other printing of the same UPC-A: `0`+12 digits -> the 12; 12 digits -> `0`+12; anything else undefined.
1423
+ * Ported from the UPC-A <-> EAN-13 branch of v2 barcodeMatchCandidates (sync-core/src/barcodeResolve.ts).
1424
+ * Match the twin against barcodes only, never SKUs (v2 BARCODE_SYMBOLOGY_FIELDS excludes sku). */
1425
+ declare function retailCodeTwin(code: string): string | undefined;
1426
+ declare function createScanSession(options: ScanSessionOptions): ScanSession;
1427
+
1428
+ interface UseBarcodeScannerOptions {
1429
+ onScan: (code: string) => void;
1430
+ /** Listen only while true (default true). */
1431
+ enabled?: boolean;
1432
+ threshold?: number;
1433
+ prefix?: string;
1434
+ suffix?: string;
1435
+ minChars?: number;
1436
+ }
1437
+ /** Listen for keyboard-wedge scans outside INPUT/TEXTAREA, with a minimum length gate.
1438
+ * Ported from WCPOS v2 packages/core/src/screens/main/hooks/barcodes/use-barcode-detection.ts (monorepo 5ac185b0).
1439
+ * @example
1440
+ * useBarcodeScanner({ onScan: (code) => {
1441
+ * const twin = retailCodeTwin(code);
1442
+ * const entry = findEntryByCode(entries, code)
1443
+ * ?? (twin ? entries.find(({ variant }) => variant.barcode === twin) : undefined);
1444
+ * if (entry) addEntryToCart(builder, entry, traits, currency);
1445
+ * else setSearchTerm(code); // searchProducts returns just the exact barcode/SKU matches
1446
+ * } });
1447
+ */
1448
+ declare function useBarcodeScanner(options: UseBarcodeScannerOptions): void;
1449
+
1450
+ /** The transport a payment terminal is reached over: hardware-neutral, not tied to any backend. */
1451
+ type PaymentTransport = 'bluetooth' | 'usb' | 'network' | 'tap_to_pay';
1452
+ type TenderView = 'select' | 'amount' | 'cancel';
1453
+ type TenderLineId = string | number;
1454
+ type TenderPlan = {
1455
+ kind: 'even';
1456
+ ways: number;
1457
+ from: number;
1458
+ } | {
1459
+ kind: 'fixed';
1460
+ firstMinor: number;
1461
+ title: string | null;
1462
+ from: number;
1463
+ } | {
1464
+ kind: 'items';
1465
+ lineIds: TenderLineId[];
1466
+ firstMinor: number;
1467
+ ways: number;
1468
+ from: number;
1469
+ };
1470
+ type SplitTab = 'even' | 'amount' | 'percent' | 'item';
1471
+ interface TenderState {
1472
+ view: TenderView;
1473
+ /** Method id being tendered; null in the 'select' and 'cancel' views. */
1474
+ methodId: string | null;
1475
+ readerId: string | null;
1476
+ transport: PaymentTransport | null;
1477
+ /** Keypad entry in minor units. */
1478
+ entryMinor: number;
1479
+ /** False until the cashier has touched the keypad since the entry was pre-filled. */
1480
+ entryDirty: boolean;
1481
+ plan: TenderPlan | null;
1482
+ splitView: boolean;
1483
+ splitTab: SplitTab;
1484
+ pickedLineIds: TenderLineId[];
1485
+ linesPaidBy: Record<TenderLineId, string[]>;
1486
+ }
1487
+ /** '0'..'9' plus the two edit keys. There is deliberately no decimal key: digits shift in from the right. */
1488
+ type TenderKey = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'clear' | 'backspace';
1489
+ type TenderAction = {
1490
+ type: 'pick-method';
1491
+ methodId: string;
1492
+ prefillMinor: number;
1493
+ readerId: string | null;
1494
+ transport?: PaymentTransport | null;
1495
+ } | {
1496
+ type: 'pick-transport';
1497
+ transport: PaymentTransport;
1498
+ } | {
1499
+ type: 'pick-reader';
1500
+ readerId: string | null;
1501
+ } | {
1502
+ type: 'tender-started';
1503
+ } | {
1504
+ type: 'key';
1505
+ key: TenderKey;
1506
+ } | {
1507
+ type: 'set-entry';
1508
+ minor: number;
1509
+ } | {
1510
+ type: 'back';
1511
+ } | {
1512
+ type: 'tender-recorded';
1513
+ rowsSinceFrom: {
1514
+ title: string;
1515
+ amountMinor: number;
1516
+ }[];
1517
+ /** The order's balance once this row counts, so the next leg can be pre-typed. */
1518
+ balanceMinor: number;
1519
+ } | {
1520
+ type: 'open-split';
1521
+ } | {
1522
+ type: 'close-split';
1523
+ } | {
1524
+ type: 'set-split-tab';
1525
+ tab: SplitTab;
1526
+ } | {
1527
+ type: 'toggle-split-line';
1528
+ lineId: TenderLineId;
1529
+ } | {
1530
+ type: 'set-plan';
1531
+ plan: TenderPlan;
1532
+ balanceMinor: number;
1533
+ } | {
1534
+ type: 'clear-plan';
1535
+ balanceMinor: number;
1536
+ } | {
1537
+ type: 'arm-custom';
1538
+ } | {
1539
+ type: 'request-cancel';
1540
+ } | {
1541
+ type: 'reset';
1542
+ };
1543
+ /** $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. */
1544
+ declare const MAX_TENDER_MINOR = 999999999;
1545
+ declare const initialTenderState: TenderState;
1546
+ /**
1547
+ * Reducer init. An order whose method the checkout store already holds — a URL seed, or a
1548
+ * tab the cashier is coming back to — reopens its keypad prefilled with the balance, exactly
1549
+ * as a tap on that tile would. Everything else starts from scratch.
1550
+ */
1551
+ declare function initTenderState({ methodId, balanceMinor, }: {
1552
+ methodId: string | null;
1553
+ balanceMinor: number;
1554
+ }): TenderState;
1555
+ declare function tenderReducer(state: TenderState, action: TenderAction): TenderState;
1556
+ /**
1557
+ * What the leg applies to the order. Cash may be tendered above the balance;
1558
+ * the excess is change, never an overpayment on the order.
1559
+ */
1560
+ declare function appliedMinor(entryMinor: number, balanceMinor: number): number;
1561
+ /** Change handed back. Zero for any tender whose method cannot give change. */
1562
+ declare function changeMinor(entryMinor: number, appliedAmountMinor: number, givesChange: boolean): number;
1563
+ /**
1564
+ * Quick tendered amounts under a cash keypad: the balance itself, then the next
1565
+ * whole 5, 10 and 50 above it. Deduped, ascending, never below the balance.
1566
+ * The caller supplies those major-unit steps already scaled to minor units.
1567
+ */
1568
+ declare function quickTenderedAmounts(balanceMinor: number, stepsMinor: readonly number[]): number[];
1569
+ /**
1570
+ * Even split shares. Returns the next tender's share, rounded half-up to the
1571
+ * minor unit; the last leg remains whatever balance is left.
1572
+ */
1573
+ declare function evenSplitShareMinor(balanceMinor: number, ways: number): number;
1574
+ /** Completion is derived from payment rows, never an extra counter in the reducer. */
1575
+ declare function activePlan(plan: TenderPlan | null, taken: number, balanceMinor: number): TenderPlan | null;
1576
+ interface PlanLeg {
1577
+ minor: number;
1578
+ state: 'done' | 'now' | 'todo' | 'rest';
1579
+ title?: string;
1580
+ }
1581
+ /** Label pieces stay untranslated here; the flow supplies localized copy and item names. */
1582
+ declare function planLegs(plan: TenderPlan, rowsSinceFrom: {
1583
+ minor: number;
1584
+ title: string;
1585
+ }[], balanceMinor: number): {
1586
+ legs: PlanLeg[];
1587
+ thisPaymentMinor: number;
1588
+ label: {
1589
+ n: number;
1590
+ ways: number;
1591
+ rest: boolean;
1592
+ title: string | null;
1593
+ };
1594
+ };
1595
+
1596
+ interface DriverCapabilities {
1597
+ /** `harness`: the till lists readers and connects; `sdk_ui`: the vendor SDK shows its own picker. */
1598
+ discovery: 'harness' | 'sdk_ui';
1599
+ /** `app`: the till can cancel a collection; `on_device`: only the reader can. */
1600
+ cancel: 'app' | 'on_device';
1601
+ refund: boolean;
1602
+ }
1603
+ interface ReaderInfo {
1604
+ id: string;
1605
+ label: string;
1606
+ model?: string;
1607
+ serial?: string;
1608
+ battery?: number | null;
1609
+ transport: PaymentTransport;
1610
+ }
1611
+ interface DriverStatus {
1612
+ connection: 'disconnected' | 'discovering' | 'connecting' | 'updating' | 'connected';
1613
+ reader: ReaderInfo | null;
1614
+ progress?: number | null;
1615
+ pairingCode?: string | null;
1616
+ message?: string | null;
1617
+ }
1618
+ type DriverAvailability = {
1619
+ available: true;
1620
+ } | {
1621
+ available: false;
1622
+ reason: 'web' | 'permission' | 'bluetooth_off' | 'not_logged_in' | 'unsupported';
1623
+ };
1624
+ interface CollectInput {
1625
+ /** The payment leg's id; a driver may use it to make its provider reference. */
1626
+ legId: string;
1627
+ /** The leg's amount in minor units of `currency`. */
1628
+ amountMinor: number;
1629
+ /** ISO 4217 code. */
1630
+ currency: string;
1631
+ method: PaymentMethodDescriptor;
1632
+ transport: PaymentTransport;
1633
+ /** Provider data from the server (credentials, an intent), or null. */
1634
+ handoff: Record<string, unknown> | null;
1635
+ /** The amount a tip may be taken on, in minor units; null when the leg takes no tip. */
1636
+ tipEligibleMinor: number | null;
1637
+ }
1638
+ type CollectOutcome = 'captured' | 'authorized' | 'declined' | 'cancelled';
1639
+ interface CollectResult {
1640
+ outcome: CollectOutcome;
1641
+ /** The provider's own references for the payment (opaque to the till). */
1642
+ providerRefs: Record<string, unknown>;
1643
+ /** Card details to print (brand, last four and so on). */
1644
+ receipt: Record<string, unknown>;
1645
+ /** What the reader charged in minor units, tip included; null when the driver cannot say. */
1646
+ amountMinor: number | null;
1647
+ transport: PaymentTransport;
1648
+ /** Why a leg was declined or cancelled; `'timed_out'` when the reader's own collect window ran out. */
1649
+ failureReason?: string | null;
1650
+ }
1651
+ interface DriverStatusSource {
1652
+ subscribe(listener: (status: DriverStatus) => void): () => void;
1653
+ get(): DriverStatus;
1654
+ }
1655
+ interface PaymentDriver {
1656
+ /** Matches a payment method's `capture.provider`. */
1657
+ readonly provider: string;
1658
+ readonly capabilities: DriverCapabilities;
1659
+ availability(): DriverAvailability;
1660
+ /** Scan for readers; `until` names a reader id the caller waits for, so a driver may stop early. */
1661
+ discoverReaders?(transport: PaymentTransport, options?: {
1662
+ until?: string;
1663
+ }): Promise<ReaderInfo[]>;
1664
+ connect?(reader: ReaderInfo, handoff: Record<string, unknown> | null): Promise<void>;
1665
+ disconnect?(): Promise<void>;
1666
+ collect(input: CollectInput): Promise<CollectResult>;
1667
+ cancel?(): Promise<void>;
1668
+ status$: DriverStatusSource;
1669
+ }
1670
+
1671
+ interface PaymentDriverRegistry {
1672
+ /** Adds the driver under its `provider`, replacing any driver already there, then notifies subscribers. */
1673
+ register(driver: PaymentDriver): void;
1674
+ get(provider: string | null): PaymentDriver | undefined;
1675
+ has(provider: string | null): boolean;
1676
+ list(): PaymentDriver[];
1677
+ /** Called after every `register`; returns an unsubscribe function. */
1678
+ subscribe(listener: () => void): () => void;
1679
+ }
1680
+ declare function createPaymentDriverRegistry(): PaymentDriverRegistry;
1681
+ /** The driver for a method taken on a device: `capture.mode === 'device'` and a driver registered under `capture.provider`. */
1682
+ declare function driverForMethod(registry: PaymentDriverRegistry, method: PaymentMethodDescriptor | null | undefined): PaymentDriver | undefined;
1683
+
1684
+ declare const SIMULATED_PROVIDER = "simulated";
1685
+ declare const SIMULATED_TIMING: {
1686
+ readonly connectMs: 300;
1687
+ readonly decisionMs: 500;
1688
+ readonly readWindowMs: 1500;
1689
+ };
1690
+ type SimulatedReaderId = 'sim-approve' | 'sim-decline' | 'sim-cancel' | 'sim-timeout' | 'sim-tip' | 'sim-tap';
1691
+ interface SimulatedDriverOptions {
1692
+ /** Override any of the delays in SIMULATED_TIMING. */
1693
+ timing?: Partial<{
1694
+ connectMs: number;
1695
+ decisionMs: number;
1696
+ readWindowMs: number;
1697
+ }>;
1698
+ /** Timer functions; default to globalThis.setTimeout / clearTimeout. */
1699
+ timers?: {
1700
+ setTimeout: (fn: () => void, ms: number) => unknown;
1701
+ clearTimeout: (handle: unknown) => void;
1702
+ };
1703
+ /** What `availability()` returns; default `{ available: true }`. */
1704
+ availability?: DriverAvailability;
1705
+ }
1706
+ declare function createSimulatedDriver(options?: SimulatedDriverOptions): PaymentDriver;
1707
+
1708
+ /**
1709
+ * The printing seam. Ported from WCPOS v2 `packages/printer/src/types.ts` (monorepo main): v2's
1710
+ * `PrinterTransport` has `printRaw(bytes)` and `printHtml(html)`; here one `print(job)` takes a job that
1711
+ * carries HTML, bytes or both, and each transport prints what it can.
1712
+ */
1713
+ type PrintJobKind = 'receipt' | 'report' | 'test';
1714
+ interface PrintJob {
1715
+ id: string;
1716
+ kind: PrintJobKind;
1717
+ /** Rendered HTML, for the system dialog (see `renderReceiptHtml`). */
1718
+ html?: string;
1719
+ /** Pre-encoded printer bytes (ESC/POS and the like), for a raw transport. */
1720
+ bytes?: Uint8Array;
1721
+ }
1722
+ /** `unsupported`: this transport cannot print the job; `unavailable`: the platform has no way to print; `failed`: the print went wrong. */
1723
+ type PrintErrorCode = 'unsupported' | 'unavailable' | 'failed';
1724
+ declare class PrintError extends Error {
1725
+ readonly code: PrintErrorCode;
1726
+ constructor(code: PrintErrorCode, message: string, options?: {
1727
+ cause?: unknown;
1728
+ });
1729
+ }
1730
+ declare function toPrintError(error: unknown): PrintError;
1731
+ interface PrintTransport {
1732
+ /** For logs, e.g. `system-print-web`. */
1733
+ readonly name: string;
1734
+ /** Resolves once the job is handed to the printer or dialog; rejects with a `PrintError`. */
1735
+ print(job: PrintJob): Promise<void>;
1736
+ disconnect?(): Promise<void>;
1737
+ }
1738
+
1739
+ /**
1740
+ * One serial queue per printer id. Ported from WCPOS v2 `packages/printer/src/printer-service.ts` (monorepo
1741
+ * main), which keeps a `PQueue({ concurrency: 1 })` per profile because one shared queue let a stalled printer
1742
+ * stall the till (its gotcha N44). Here a promise chain per printer id does the same without p-queue.
1743
+ */
1744
+
1745
+ /** v2's queue id for the OS print dialog, which is one shared resource on the device. */
1746
+ declare const SYSTEM_PRINTER_ID = "system";
1747
+ interface PrintQueueState {
1748
+ printerId: string;
1749
+ /** The id of the job printing now, or null. */
1750
+ running: string | null;
1751
+ /** Ids of the jobs waiting, in the order they will print. */
1752
+ queued: string[];
1753
+ }
1754
+ interface PrintQueueOptions {
1755
+ transportFor: (printerId: string) => PrintTransport | Promise<PrintTransport>;
1756
+ }
1757
+ interface PrintQueue {
1758
+ /** Resolves when this job has printed; rejects with a `PrintError`. A failure never holds up the next job. */
1759
+ print(printerId: string, job: PrintJob): Promise<void>;
1760
+ state(printerId: string): PrintQueueState;
1761
+ subscribe(listener: (state: PrintQueueState) => void): () => void;
1762
+ }
1763
+ declare function createPrintQueue({ transportFor }: PrintQueueOptions): PrintQueue;
1764
+
1765
+ /**
1766
+ * Printers set up on this device. Local only, never replicated; the app adds the collection as
1767
+ * `printer_profiles`. Ported from WCPOS v2 `packages/database/src/collections/schemas/printer-profiles.ts`
1768
+ * (monorepo main, version 0, device-local). Left out: v2's cloud fields (`cloudPrinterId`, `cloudProvider`,
1769
+ * `connectionType: 'cloud'`; vendor services stay out of the MIT packages, ADR-084 decision 2), its vendor-SDK and
1770
+ * encoder-library hints (`nativeInterfaceType`, `printerModel`), `emitEscPrintMode` and `fullReceiptRaster`.
1771
+ * v2's schema defaults are kept as comments, not schema `default`s; a reader treats a missing field as its default.
1772
+ */
1773
+
1774
+ declare const PRINTER_PROFILES_COLLECTION = "printer_profiles";
1775
+ interface PrinterProfile {
1776
+ id: string;
1777
+ /** User-assigned, e.g. "Front counter". */
1778
+ name: string;
1779
+ connectionType: 'system' | 'network' | 'bluetooth' | 'usb';
1780
+ /** Default `generic`. */
1781
+ vendor?: 'epson' | 'star' | 'generic';
1782
+ /** IP address, Bluetooth address or USB path. */
1783
+ address?: string;
1784
+ /** Default 9100. */
1785
+ port?: number;
1786
+ /** Default `esc-pos`. */
1787
+ language?: 'esc-pos' | 'star-prnt' | 'star-line';
1788
+ /** Characters per line: 32 for 58 mm, 42 or 48 for 80 mm. Default 42. */
1789
+ columns?: number;
1790
+ /** The encoder's code page name, e.g. `cp437`; absent lets the encoder choose. */
1791
+ codePage?: string;
1792
+ /** Default true. */
1793
+ autoCut?: boolean;
1794
+ /** Default false. */
1795
+ autoOpenDrawer?: boolean;
1796
+ /** Default `pin2` (drawer 1). */
1797
+ drawerConnector?: 'pin2' | 'pin5';
1798
+ isDefault?: boolean;
1799
+ /** A platform printer (the print dialog) that cannot be deleted. */
1800
+ isBuiltIn?: boolean;
1801
+ }
1802
+ declare const printerProfileSchema: RxJsonSchema<PrinterProfile>;
1803
+ declare function printerProfileCollection(): {
1804
+ readonly schema: RxJsonSchema<PrinterProfile>;
1805
+ };
1806
+ type PrinterProfileCollection = RxCollection<PrinterProfile>;
1807
+ declare function addPrinterProfileCollection(db: RxDatabase): Promise<PrinterProfileCollection>;
1808
+
1809
+ /**
1810
+ * Prints rendered HTML through the platform print dialog. Ported from WCPOS v2 (monorepo main)
1811
+ * `packages/printer/src/transport/system-print-adapter.web.ts` (hidden iframe, `print()`, `afterprint`) and
1812
+ * `system-print-adapter.ts` (native, `expo-print`). On native the app injects `printHtml` (for example
1813
+ * `(html) => Print.printAsync({ html })`), so this package takes no native dependency.
1814
+ */
1815
+
1816
+ /** v2's waits: let the frame render, give images 5 s, and settle after 60 s if `afterprint` never fires. */
1817
+ declare const SYSTEM_PRINT_TIMING: {
1818
+ renderDelayMs: number;
1819
+ imageTimeoutMs: number;
1820
+ afterPrintTimeoutMs: number;
1821
+ removeDelayMs: number;
1822
+ };
1823
+ type SystemPrintTiming = typeof SYSTEM_PRINT_TIMING;
1824
+ interface SystemPrintTransportOptions {
1825
+ /** Native: prints HTML through the OS dialog. When given, the iframe path is not used. */
1826
+ printHtml?: (html: string) => Promise<void>;
1827
+ /** Web: the document to print from; defaults to `globalThis.document`. */
1828
+ document?: Document;
1829
+ timing?: Partial<SystemPrintTiming>;
1830
+ }
1831
+ declare function createSystemPrintTransport(options?: SystemPrintTransportOptions): PrintTransport;
1832
+
1833
+ /** RFC 9562 UUIDv7: monotonic with no arguments; stateless with an explicit timestamp or random source. */
1834
+ declare function uuidv7(now?: number, randomBytes?: (n: number) => Uint8Array): string;
1835
+
1836
+ interface FinalizeOptions {
1837
+ localWarnings?: PosOrderLocalWarning[];
1838
+ registerId?: string;
1839
+ cashierRef?: string;
1840
+ now?: Date;
1841
+ /** Tests only: replaces uuidv7. Every id it returns must be at most 255 characters with no NUL (order.create's bound). */
1842
+ newId?: () => string;
1843
+ /** The store's `order.create` capability (ADR-062); `undefined` is treated as 1. */
1844
+ capabilities?: ServerCapabilities;
1845
+ }
1846
+ /**
1847
+ * Turns a fully paid builder Order into a pending PosOrder without mutating it. The PosOrder holds the sent form,
1848
+ * frozen: line names and v3 discount labels are cut to PAYLOAD_STRING_MAX with NUL stripped (`cutText`), and a
1849
+ * customer email or id the shape check would refuse is left out, so `toOrderCreateEnvelope` sends it unchanged.
1850
+ */
1851
+ declare function finalizeOrder(order: Order, options?: FinalizeOptions): PosOrder;
1852
+
1853
+ declare class UnsupportedOrderVersionError extends Error {
1854
+ readonly needed: number;
1855
+ readonly supported: number;
1856
+ readonly code = "UNSUPPORTED_ORDER_VERSION";
1857
+ constructor(needed: number, supported: number);
1858
+ }
1859
+ /**
1860
+ * Builds the ADR-038 order.create envelope for a PosOrder. It sends the stored order unchanged, so every resend of
1861
+ * an order is byte-identical, and an order stored by an older till goes out exactly as that till sent it:
1862
+ * `finalizeOrder` freezes the sent form (names and labels cut, an unsendable customer email or id left out).
1863
+ * ADR-065's figures make version 3; otherwise a discounted order is version 2 (ADR-062), else version 1, byte-identical.
1864
+ * A version-3 order goes as version 4 (#286) only when `maxVersion` is at least 4 and its `sentVersion` doesn't cap it.
1865
+ * Coupon orders need version 6, carrying coupons, stored regular prices, line attributes and receipt coupons.
1866
+ * 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.
1867
+ * Orders with Any picks (#495) need version 6 too, carrying a line's `anyAttributes`, and coupons only when they have some.
1868
+ */
1869
+ declare function toOrderCreateEnvelope(order: PosOrder, deviceId: string, attempt?: number, options?: {
1870
+ maxVersion?: number;
1871
+ }): OrderCreateEnvelope;
1872
+
1873
+ /**
1874
+ * Version 1 adds the optional `sessionId` (ADR-032); nothing else changed from version 0.
1875
+ * Version 2 adds three optional fields and changes nothing else: `lateSessionId` (ADR-032, late
1876
+ * sale), and ADR-065's `display` and `taxByRate`, declared ahead of the job that writes them so a
1877
+ * till migrates once. Create the collection with `posOrderCollection()`, never with this schema
1878
+ * alone: RxDB refuses a version above 0 without its migration strategies.
1879
+ * 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.
1880
+ * Version 4 adds the optional `localWarnings` and `serverFailures` (the outbox's stuck clock start, latest reason and
1881
+ * isolation, restored when an outbox starts), and changes nothing else.
1882
+ * Version 5 lets `sentVersion` and `downgradedFrom` be 4 (order.create version 4, #286), and changes nothing else. Its
1883
+ * migration sets a row's missing `sentVersion` to its content version, the version any earlier attempt went out at.
1884
+ * Like version 4 (ADR-069), it is one-way: an older build shows no orders.
1885
+ * Version 6 adds `taxRounding`, the strategy the sale's figures were computed with (#287; never sent), and changes
1886
+ * nothing else. Its migration sets it on every older row. It is one-way like version 5.
1887
+ * Version 7 adds `saleId`, the sale order's id (ADR-072; never sent), and changes nothing else. Its migration is the
1888
+ * identity: older orders have no `saleId`. It is one-way like version 6.
1889
+ * Version 8 adds fees, shipping, custom lines (ADR-075) and the woocommerce tax rounding (ADR-076), and changes nothing else.
1890
+ * It also stores the WooCommerce 6dp net (`netMicros`) under the woocommerce rounding (ADR-076 amendment).
1891
+ * Its migration is the identity. It is one-way like version 7.
1892
+ * Version 9 adds the order's `coupons` and the receipt's `display.coupons` (ADR-077 d2), and a line's `attributes` (#495)
1893
+ * 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.
1894
+ * `finalizeOrder` writes a line's `attributes`; the order.create envelope sends them only at version 6.
1895
+ * Its migration is the identity. It is one-way like version 8.
1896
+ * 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.
1897
+ * 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.
1898
+ */
1899
+ declare const posOrderSchema: RxJsonSchema<PosOrder>;
1900
+ /**
1901
+ * The `pos_orders` collection config, with its migration strategies. Open the collection with
1902
+ * `addPosOrderCollection(db)`, which uses this and settles the migration safely; adding this config
1903
+ * directly leaves RxDB's own open path. `pos_orders` holds sales not yet sent, so no step may drop a
1904
+ * document: versions 1 and 2 only add optional fields, so every order from version 0 or 1 passes
1905
+ * unchanged.
1906
+ *
1907
+ * Within one run, RxDB 16.21 keeps an order that fails the new schema's validation: with a
1908
+ * validating storage the migration stops with DM4 and the order stays in the older version's
1909
+ * storage; without one it is copied as is. **Across runs, RxDB's own open path can lose it**: a
1910
+ * failed run can leave its checkpoint past that order, and the next run then removes the older
1911
+ * version's storage without copying it. `addPosOrderCollection` resets that checkpoint, so use it
1912
+ * (`migration.test.ts`).
1913
+ */
1914
+ declare function posOrderCollection(): {
1915
+ schema: RxJsonSchema<PosOrder>;
1916
+ migrationStrategies: MigrationStrategies;
1917
+ };
1918
+
1919
+ /** `addPosOrderCollection`'s logger: attach a sink to see, for example, the status writes a closing open dropped. */
1920
+ declare const posOrdersLogger: Logger;
1921
+ /**
1922
+ * `addPosOrderCollection` stopped, before any further write, because its database is closing: it
1923
+ * was called once `close()` had begun, the close cancelled its migration (RxDB 17.5), or the close
1924
+ * stopped waiting for it (after `POS_ORDER_MIGRATION_CLOSE_WAIT_MS`). No order is lost: reopen the
1925
+ * database and call it again.
1926
+ */
1927
+ declare class PosOrderOpenClosedError extends Error {
1928
+ readonly databaseName: string;
1929
+ readonly code = "POS_ORDER_OPEN_CLOSED";
1930
+ constructor(databaseName: string);
1931
+ }
1932
+ /**
1933
+ * Adds `pos_orders` to `db` and resolves once no order of an older version is left to migrate.
1934
+ * On DM4 it rejects after the migration has stopped and closes the collection. It rejects with
1935
+ * `PosOrderOpenClosedError` when the database is closing. `closeWaitMs` is for tests only.
1936
+ * See `openMigratedCollection` for the migration and close mechanism.
1937
+ */
1938
+ declare function addPosOrderCollection(db: RxDatabase, closeWaitMs?: number): Promise<RxCollection<PosOrder>>;
1939
+
1940
+ /**
1941
+ * Returns this device's id (a UUIDv7), stored under `key` in `storage` (web storage, or an app's
1942
+ * equivalent) and minted on first use; medusapos passes `'medusapos.register_id'`. With no storage,
1943
+ * or one that throws on read or write, it falls back to one id per process.
1944
+ */
1945
+ declare function getDeviceId(storage: {
1946
+ getItem(key: string): string | null;
1947
+ setItem(key: string, value: string): void;
1948
+ } | null, key: string): string;
1949
+
1950
+ /**
1951
+ * The orders a cashier must look at: rejected, applied with a known warning, taken after their
1952
+ * session closed (`lateSessionId`) or with local warnings (whatever the sync status), or pending with a `commandId` in
1953
+ * `stuckCommandIds` (the outbox's `OutboxState.stuck`: the store keeps failing it), newest first.
1954
+ * A warning code this till version doesn't know is not shown here (`knownWarnings`). Never changes `orders`.
1955
+ * `register_session_unknown` is not shown, because the store counts the order once its session arrives (ADR-078).
1956
+ * A refused order is left out once its finalized successor is in `orders`.
1957
+ */
1958
+ declare function needsAttention(orders: PosOrder[], options?: {
1959
+ stuckCommandIds?: readonly string[];
1960
+ }): PosOrder[];
995
1961
 
996
1962
  type PosRefundStatus = 'pending' | 'applied' | 'rejected' | 'unsent';
997
1963
  interface PosRefund {
@@ -1263,11 +2229,14 @@ declare const backToSelling: (sessions: RegisterSessionCollection, id: string) =
1263
2229
  * Closes the session with its counted tenders (minor units); `timezone` dates a session opened
1264
2230
  * without a business day. `approvedBy`, the manager who approved the count, is written in the same
1265
2231
  * write as the close, and a repeat close keeps the first close's approver as it keeps its count.
2232
+ * `approval`, the store's opaque proof (ADR-082), is written to `approver_token` in the same
2233
+ * write; it never reaches the closure or its breakdowns.
1266
2234
  */
1267
2235
  declare function closeSession(sessions: RegisterSessionCollection, id: string, input: {
1268
2236
  counted: Record<string, number>;
1269
2237
  closedBy?: string;
1270
2238
  approvedBy?: string;
2239
+ approval?: string;
1271
2240
  timezone?: string;
1272
2241
  }): Promise<rxdb.RxDocument<RegisterSession, {}, unknown>>;
1273
2242
  /**
@@ -1347,6 +2316,13 @@ declare function isReopened(order: Pick<PosOrder, 'syncStatus' | 'reopenedAt'>):
1347
2316
  /** Payments count on the successor, so the refused order counts nowhere (ADR-077 R5 amended). Only this list is considered. */
1348
2317
  declare function replacedOrderIds(orders: readonly Pick<PosOrder, 'id' | 'saleId' | 'syncStatus'>[]): Set<string>;
1349
2318
 
2319
+ type NoteDelivery = 'none' | 'pending' | 'sent' | 'not_sent';
2320
+ /**
2321
+ * ADR-083 condition 2: a note goes only at order.create 7, and the outbox stores the version every attempt goes out at
2322
+ * (`sentVersion`, lowered on a downgrade), so a sale whose stored version is below 7 went without its note.
2323
+ */
2324
+ declare function noteDelivery(order: Pick<PosOrder, 'note' | 'sentVersion'>): NoteDelivery;
2325
+
1350
2326
  type SaleContent = Pick<PosOrder, 'totalMinor' | 'currency' | 'lines' | 'payments'>;
1351
2327
  /**
1352
2328
  * Whether two orders carry the same money-bearing content: `totalMinor` and `currency`; each line's
@@ -1446,6 +2422,10 @@ declare const overThreshold: (variance: number, thresholdMinor?: number | null)
1446
2422
  * `closeSession` gate share (ADR-032).
1447
2423
  */
1448
2424
  declare const closeNeedsApproval: (countedCashMinor: number, expectedCashMinor: number, thresholdMinor?: number | null) => boolean;
2425
+ /** ADR-082 d3: counted minus till-expected for each key of `counted`, the variance a store approval is bound to. */
2426
+ declare const closureVariance: (counted: Record<string, number>, tillExpected: Record<string, number>) => {
2427
+ [k: string]: number;
2428
+ };
1449
2429
  /** Sums denomination face values (already minor units) by piece count. */
1450
2430
  declare const denominationTotal: (pieces: Record<number, number>) => number;
1451
2431
  /**
@@ -1537,6 +2517,27 @@ declare function deriveSettled(recorded: RecordedFigures, corrections: readonly
1537
2517
  touched: Set<string>;
1538
2518
  };
1539
2519
 
2520
+ /**
2521
+ * The opening float the open-register card suggests (v2 parity A4): the register's default float, else the cash
2522
+ * counted at the last close, else none. Port provenance: WCPOS v2 monorepo `main` `5ac185b0e`,
2523
+ * `packages/core/src/screens/main/pos/cart/open-register-card.tsx:40-50` (`defaultFloat ?? lastCount ?? null`), with
2524
+ * `seedAmount` from `packages/core/src/services/register-session/count-money.ts`. Money is TallyUI's integer
2525
+ * minor-units convention, so `seedAmount`'s rounding of four-decimal server strings has no counterpart here.
2526
+ */
2527
+
2528
+ type FloatSuggestion = {
2529
+ amountMinor: number;
2530
+ source: 'default' | 'last_count';
2531
+ } | {
2532
+ amountMinor: null;
2533
+ source: null;
2534
+ };
2535
+ /** A default float of zero is still the default, as in v2 (`??`, not `||`). */
2536
+ declare function suggestFloat({ register, lastCountedCashMinor }: {
2537
+ register?: Pick<RegisterInfo, 'defaultFloatMinor'> | null;
2538
+ lastCountedCashMinor?: number | null;
2539
+ }): FloatSuggestion;
2540
+
1540
2541
  declare function exportCsv(rows: readonly Closure[], exponent: number, t: (key: string) => string, names?: Record<string, string>, storeName?: string): string;
1541
2542
 
1542
2543
  declare const labelKeys: {
@@ -1952,7 +2953,7 @@ declare const registerCommandCollection: () => {
1952
2953
  schema: RxJsonSchema<RegisterCommand>;
1953
2954
  };
1954
2955
  type BuiltCommand = Pick<RegisterCommand, 'key' | 'type' | 'payload'> & {
1955
- version: 1 | 2;
2956
+ version: 1 | 2 | 3;
1956
2957
  };
1957
2958
  declare function sessionOpenCommand(s: RegisterSession, v2?: {
1958
2959
  deviceName?: string | null;
@@ -1962,7 +2963,11 @@ declare function sessionTransitionCommand(s: RegisterSession & {
1962
2963
  status_at: string;
1963
2964
  }): BuiltCommand;
1964
2965
  declare function movementCommand(m: CashMovement): BuiltCommand;
1965
- declare function closureCommand(c: Closure): BuiltCommand;
2966
+ /** 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. */
2967
+ declare function closureCommand(c: Closure, v3?: {
2968
+ registerContract?: number;
2969
+ approval?: string | null;
2970
+ }): BuiltCommand;
1966
2971
  /** Appends missing facts in dependency order; the bytes of an existing key never change. */
1967
2972
  declare function reconcileRegisterCommands({ commands, sessions, movements, closures, host, storeKey, registerId, now, observed, registerContract, deviceName }: {
1968
2973
  commands: RegisterCommandCollection;
@@ -1978,6 +2983,62 @@ declare function reconcileRegisterCommands({ commands, sessions, movements, clos
1978
2983
  deviceName?: string | null;
1979
2984
  }): Promise<string[]>;
1980
2985
 
2986
+ type SessionTarget = {
2987
+ commands: RegisterCommandCollection;
2988
+ sessions: RegisterSessionCollection;
2989
+ sessionId: string;
2990
+ now?: string;
2991
+ };
2992
+ /**
2993
+ * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
2994
+ * 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.
2995
+ * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
2996
+ * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
2997
+ */
2998
+ declare function adoptRegisterResults({ commands, sessions, registerId }: {
2999
+ commands: RegisterCommandCollection;
3000
+ sessions: RegisterSessionCollection;
3001
+ registerId: string;
3002
+ }): Promise<void>;
3003
+ declare function takeOverSession({ commands, sessions, sessionId, now, registerContract }: SessionTarget & {
3004
+ /** The store's register contract (`capabilities.register`); take over needs 2, and a missing value counts as below 2. */
3005
+ registerContract?: number;
3006
+ }): Promise<void>;
3007
+ declare function abandonSession(input: SessionTarget): Promise<void>;
3008
+ /**
3009
+ * 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
3010
+ * resumed open and an error-free duplicate are recorded applied), and it is not conflict, superseded or abandoned. A
3011
+ * closed session still counts: the route accepts it.
3012
+ */
3013
+ declare function isLiveAtStore(session: Pick<RegisterSession, 'id' | 'status'> | null | undefined, openRow: Pick<RegisterCommand, 'key' | 'syncStatus'> | null | undefined): boolean;
3014
+ /** `verified` once the store has applied a version 3 closure carrying a proof; `not_required` for a close the store does not check. */
3015
+ type ClosureApprovalStatus = 'verified' | 'unverified' | 'not_required';
3016
+ /**
3017
+ * ADR-082 d9, derived from the closure's `register.closure.submit` row; nothing is stored. A verified approval is
3018
+ * needed at register contract 3 with the store's `registerApproval`, over its threshold on cash (the store's rule).
3019
+ * Until the store applies a version 3 row with a proof, a recorded approver is `unverified`: no row yet, pending,
3020
+ * refused, or a version 1 row the store recorded without checking.
3021
+ */
3022
+ declare function closureApprovalStatus(closure: Pick<Closure, 'counted' | 'till_expected'>, row: Pick<RegisterCommand, 'syncStatus' | 'version' | 'payload'> | null | undefined, capabilities: Pick<ServerCapabilities, 'register' | 'registerApproval'> | undefined): ClosureApprovalStatus;
3023
+ /** `reapproveClosure` refused. Its message can be shown to a cashier as it is. */
3024
+ declare class RegisterReapproveError extends Error {
3025
+ readonly code: 'REGISTER_REAPPROVE_UNSUPPORTED' | 'REGISTER_REAPPROVE_NOT_REFUSED' | 'REGISTER_REAPPROVE_PROOF_MISSING';
3026
+ constructor(code: 'REGISTER_REAPPROVE_UNSUPPORTED' | 'REGISTER_REAPPROVE_NOT_REFUSED' | 'REGISTER_REAPPROVE_PROOF_MISSING');
3027
+ }
3028
+ /**
3029
+ * ADR-082 d7: requeues a closure the store refused with either approval code, in its ledger place (the same key and
3030
+ * `seq`), with a new command id (the store replays a stored refusal for the old one), version 3, the new proof and
3031
+ * approver, and every other payload field as it was. The local closure, its Z and the session are not rewritten.
3032
+ */
3033
+ declare function reapproveClosure({ commands, closureId, approval, approvedBy, registerContract, now }: {
3034
+ commands: RegisterCommandCollection;
3035
+ closureId: string;
3036
+ approval: string;
3037
+ approvedBy: string;
3038
+ registerContract?: number;
3039
+ now?: string;
3040
+ }): Promise<void>;
3041
+
1981
3042
  /** 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. */
1982
3043
  declare class RegisterTenderInProgressError extends Error {
1983
3044
  constructor();
@@ -2026,11 +3087,11 @@ interface UseRegisterSessionOptions {
2026
3087
  softwareVersion: string;
2027
3088
  /** A sale is at tender (`sale.stage.kind === 'tender'`): counting and closing refuse. */
2028
3089
  tenderInProgress: boolean;
2029
- /** The count variance, in minor units, over which the app asks for approval. */
3090
+ /** The count variance, in minor units, over which the app asks for approval. The store's `capabilities.registerApproval.thresholdMinor` wins over it (ADR-082). */
2030
3091
  varianceThreshold?: number;
2031
3092
  /** `'HH:mm'` on the device's clock; an open session after it is `overdue`. */
2032
3093
  expectedCloseTime?: string;
2033
- /** The cashier may not see expected figures while counting. */
3094
+ /** The cashier may not see expected figures while counting: pass `useCashier(connector, context).blind` (no `viewReports`). */
2034
3095
  blind?: boolean;
2035
3096
  /** The closure's register name, and a person id's display name. */
2036
3097
  labels?: {
@@ -2038,6 +3099,17 @@ interface UseRegisterSessionOptions {
2038
3099
  resolveCashierName?: (id: string) => string;
2039
3100
  };
2040
3101
  }
3102
+ /** ADR-082 d7: a closure the store refused with either approval code, for the app's "Manager approval needed again" card. */
3103
+ interface ApprovalNeeded {
3104
+ closureId: string;
3105
+ sessionId: string;
3106
+ /** The variance to send to the approval route: the refusal's, else counted minus tillExpected from the row. */
3107
+ variance: Record<string, number>;
3108
+ code: 'register_approval_required' | 'register_approval_invalid';
3109
+ reason?: string;
3110
+ /** `isLiveAtStore` for the refused closure's session: the approval route can be used for it. */
3111
+ liveAtStore: boolean;
3112
+ }
2041
3113
  declare function useRegisterSession(options: UseRegisterSessionOptions): {
2042
3114
  session: RegisterSession | null;
2043
3115
  /** The other till's live session, or the session this till is waiting to take over. */
@@ -2065,6 +3137,12 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2065
3137
  lastClosure: Closure;
2066
3138
  lastClosed: RegisterSession;
2067
3139
  varianceThreshold: number | undefined;
3140
+ /** ADR-082 d4: the store holds the current session (`isLiveAtStore`), so the app's approval route can be used. */
3141
+ liveAtStore: boolean;
3142
+ /** ADR-082 d7: a closure the store refused with either approval code, or `null`; recover it with `actions.reapproveClosure`. */
3143
+ approvalNeeded: ApprovalNeeded | null;
3144
+ /** ADR-082 d9: each listed closure's approval status by closure id; show `unverified` beside the approver's name. */
3145
+ closureApprovalStatus: Record<string, ClosureApprovalStatus>;
2068
3146
  enabled: boolean;
2069
3147
  blind: boolean;
2070
3148
  /** Pass straight to useSale's `session` option: `complete()` then stamps through `stampSession`. */
@@ -2082,6 +3160,12 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2082
3160
  actions: {
2083
3161
  takeOver: () => Promise<void>;
2084
3162
  chooseAnotherRegister: () => Promise<void>;
3163
+ /** 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. */
3164
+ reapproveClosure: (input: {
3165
+ closureId: string;
3166
+ approval: string;
3167
+ approvedBy: string;
3168
+ }) => Promise<void>;
2085
3169
  /**
2086
3170
  * Refuses with `RegisterSessionAlreadyOpenError` while the register has a live session or
2087
3171
  * another open is running (in any hook instance), and with `RegisterCloseIncompleteError`
@@ -2099,9 +3183,14 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2099
3183
  * `counted` maps each tender to its counted minor units. An interrupted close resumes with
2100
3184
  * the count persisted on the session, not the one passed to the retry (WCPOS uses the retry's).
2101
3185
  * Over `varianceThreshold` (`closeNeedsApproval`, as `RegisterCount`), a close without
2102
- * `approvedBy` throws `RegisterApprovalRequiredError` before any write, blind or not; a
3186
+ * `approvedBy` throws `RegisterApprovalRequiredError` before any write, blind or not; so does one without
3187
+ * `approval` at contract 3 with the store's `registerApproval` while the session is `liveAtStore` (ADR-082 d5); a
2103
3188
  * resumed close (the stored session already closed) isn't gated again. `approvedBy` reaches the Z
2104
3189
  * (`breakdowns.approved_by`), and `approvedByName` its `approved_by_name`.
3190
+ * `approval` is the store's opaque proof (ADR-082): it goes to the session's
3191
+ * `approver_token` and from there only onto a version 3 closure command, never onto the Z, a fact or a log. With
3192
+ * `approvedVariance` (the variance the app sent to its approval route), a close whose `closureVariance` differs
3193
+ * throws `RegisterApprovalRequiredError` before any write. A resumed close checks neither.
2105
3194
  * One close per register runs at a time, in any hook instance: a call while one is in flight joins
2106
3195
  * it, getting its closure or error, and its own `counted`, `approvedBy` and `approvedByName` are ignored.
2107
3196
  */
@@ -2109,7 +3198,13 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2109
3198
  counted: Record<string, number>;
2110
3199
  approvedBy?: string;
2111
3200
  approvedByName?: string;
3201
+ approval?: string;
3202
+ approvedVariance?: Record<string, number>;
2112
3203
  }) => Promise<rxdb.RxDocument<Closure, {}, unknown>>;
3204
+ /** 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`. */
3205
+ closureVariance: (counted: Record<string, number>) => Promise<{
3206
+ [k: string]: number;
3207
+ }>;
2113
3208
  recordMovement: (input: {
2114
3209
  type: "paid_in" | "paid_out" | "no_sale";
2115
3210
  amountMinor: number;
@@ -2117,34 +3212,13 @@ declare function useRegisterSession(options: UseRegisterSessionOptions): {
2117
3212
  }) => Promise<rxdb.RxDocument<CashMovement, {}, unknown>>;
2118
3213
  voidMovement: (id: string) => Promise<rxdb.RxDocument<CashMovement, {}, unknown>>;
2119
3214
  };
2120
- };
2121
-
2122
- type SessionTarget = {
2123
- commands: RegisterCommandCollection;
2124
- sessions: RegisterSessionCollection;
2125
- sessionId: string;
2126
- now?: string;
2127
- };
2128
- /**
2129
- * Applied opens fill a missing resume id; refused opens make open/counting sessions conflict.
2130
- * 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.
2131
- * Applied conflict opens restore the latest transition's counting state, otherwise open; pending rows do nothing.
2132
- * Answers are walked in seq/key order; adoption is idempotent and safe to run at any time.
2133
- */
2134
- declare function adoptRegisterResults({ commands, sessions, registerId }: {
2135
- commands: RegisterCommandCollection;
2136
- sessions: RegisterSessionCollection;
2137
- registerId: string;
2138
- }): Promise<void>;
2139
- declare function takeOverSession({ commands, sessions, sessionId, now, registerContract }: SessionTarget & {
2140
- /** The store's register contract (`capabilities.register`); take over needs 2, and a missing value counts as below 2. */
2141
- registerContract?: number;
2142
- }): Promise<void>;
2143
- declare function abandonSession(input: SessionTarget): Promise<void>;
3215
+ };
2144
3216
 
2145
3217
  type CatalogueEntry<Doc> = {
2146
3218
  product: Doc;
2147
3219
  variant: VariantSummary;
3220
+ /** The cashier's value for each of the variant's local "Any" option groups, group name to value (#495). */
3221
+ picks?: Record<string, string>;
2148
3222
  };
2149
3223
  /** Variants in product/variant order, passing context through; without getVariants,
2150
3224
  * simple products use their own traits and products with variants contribute no entries. */
@@ -2209,6 +3283,14 @@ type SaleStage = {
2209
3283
  declare const DISCOUNTS_UNSUPPORTED = "finalize: discounts are not supported by the server yet (order.create v2)";
2210
3284
  /** Every sale change refuses with this while a completion is pending (see `complete()`). */
2211
3285
  declare const SALE_SAVING = "This sale is being saved. Retry to finish it.";
3286
+ declare const PAYMENT_IN_MOTION = "Finish or void the payment in progress before completing the sale";
3287
+ /**
3288
+ * `switchSale()` and `closeSale()` refuse a sale whose legs took money (u19). v2 keeps a partly paid order's legs on
3289
+ * switching, but a TallyUI draft keeps no tender stage, the next `startTender` replaces every leg, and `resume`
3290
+ * re-checks coupons: so the sale stays on the till until it is paid or its paid legs are voided.
3291
+ */
3292
+ declare const SALE_PARTLY_PAID = "This sale is partly paid. Take the rest of the payment or void the paid legs first.";
3293
+ declare const SALE_IN_TENDER = "Finish or cancel the payment before switching sales";
2212
3294
  /** Call under a `TaxProvider`: its tax context and the settings' currency price every sale. */
2213
3295
  declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscountsSequentially'>, opts: {
2214
3296
  registerId: string;
@@ -2299,6 +3381,8 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
2299
3381
  applyCoupon(code: string): Promise<string | null>;
2300
3382
  /** Removes an applied coupon; returns the refusal to show, or null once removed. */
2301
3383
  removeCoupon(code: string): string | null;
3384
+ /** 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). */
3385
+ setNote(note: string): void;
2302
3386
  /** the picked customer reaches the server as order.create v3's customer.customerId */
2303
3387
  setCustomer(customer: CustomerSummary | null): void;
2304
3388
  /**
@@ -2317,12 +3401,16 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
2317
3401
  amountMinor: number;
2318
3402
  reference?: string;
2319
3403
  } | null) => void;
2320
- /** ADR-072: external is capped at the balance due; change comes only from cash. */
3404
+ /** 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. */
2321
3405
  addTender(tender: {
2322
3406
  method: "cash" | "external";
2323
3407
  amountMinor: number;
2324
3408
  reference?: string;
3409
+ status?: "pending" | "authorized" | "captured";
2325
3410
  }): string | null;
3411
+ setTenderStatus(paymentId: string, status: "authorized" | "captured" | "failed"): boolean;
3412
+ /** The leg stays in order.payments as voided and counts nothing; removeTender still removes a leg outright. */
3413
+ voidTender(paymentId: string): boolean;
2326
3414
  /** ADR-072: remove one tender and its dropped-reference warning. An id not among the payments changes nothing. */
2327
3415
  removeTender(paymentId: string): void;
2328
3416
  cancelTender(): void;
@@ -2362,6 +3450,15 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
2362
3450
  resume(draftId: string, options?: {
2363
3451
  keepParkedPrices?: boolean;
2364
3452
  }): Promise<string | null>;
3453
+ /**
3454
+ * Opens the parked draft `draftId`, or an empty sale for null (New), as a tab switch (u19, v2 cart/tabs.tsx):
3455
+ * parks the current sale first when it has lines, fees or shipping (a receipt is done and is not parked).
3456
+ * Refused, changing nothing, while saving, for a partly paid sale (SALE_PARTLY_PAID), a payment in motion or
3457
+ * the tender stage. Resolves to a refusal (park's, or `resume`'s for the chosen draft), or null.
3458
+ */
3459
+ switchSale(draftId: string | null): Promise<string | null>;
3460
+ /** 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. */
3461
+ closeSale(): string | null;
2365
3462
  /**
2366
3463
  * Continue after a failed save whose order is confirmed stored (`canContinue`): exactly `newSale()`.
2367
3464
  * The order stays pending in the outbox, which will send it; it isn't handed to `onSaleCompleted` again, and
@@ -2370,6 +3467,27 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
2370
3467
  continueSale(): void;
2371
3468
  };
2372
3469
 
3470
+ /** One tab of the till's open sales: the current sale or a parked draft (v2 cart/tabs.tsx). */
3471
+ interface OpenSale {
3472
+ id: string;
3473
+ customerName?: string;
3474
+ itemCount: number;
3475
+ firstItem?: string;
3476
+ totalMinor: number;
3477
+ paidMinor: number;
3478
+ balanceDueMinor: number;
3479
+ /** The sale on the till now. */
3480
+ current: boolean;
3481
+ }
3482
+ /** v2 cart/tab-chip.tsx: captured money and a balance still due. */
3483
+ declare function isPartlyPaid(sale: Pick<OpenSale, 'paidMinor' | 'balanceDueMinor'>): boolean;
3484
+ /**
3485
+ * The current sale (when it has lines, fees or shipping; a blank cart is no tab) and the parked drafts, in creation
3486
+ * order: sorted by id with numeric collation, so a tab keeps its place across switches (a re-park changes
3487
+ * `parkedAt`, never the id). A draft with the current sale's id is that sale and is skipped.
3488
+ */
3489
+ declare function openSales(order: Order, parked: readonly ParkedOrderSummary[]): OpenSale[];
3490
+
2373
3491
  /** A WooCommerce coupon as the sale needs it: the engine's input and the connector's numeric id. */
2374
3492
  type SaleCoupon = woocommerceCoupons.CouponInput & {
2375
3493
  id: number;
@@ -2454,7 +3572,9 @@ interface CommandTransport<E extends AnyCommandEnvelope = CommandEnvelope<OrderC
2454
3572
  interface OutboxState {
2455
3573
  pending: number;
2456
3574
  /** The order outbox's count of `pos_orders` the store refused (`syncStatus: 'rejected'`), read with `pending`. Each
2457
- * stays until requeue() sends it again. The register outbox leaves it unset. */
3575
+ * stays until requeue() sends it again. The register outbox's count of rejected `register_commands` that stop their
3576
+ * register's ledger (superseded, abandoned and an abandoned session's already-open refusal are left out, ADR-078, and so
3577
+ * are the two refused closure approvals, which hold only their register's next closure, ADR-082 decision 6). */
2458
3578
  rejected?: number;
2459
3579
  sending: boolean;
2460
3580
  lastRetryReason?: string;
@@ -2542,6 +3662,8 @@ interface OrderOutbox {
2542
3662
  }
2543
3663
  declare function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox;
2544
3664
 
3665
+ /** Whether the register outbox's requeue() resends a rejection with this code. */
3666
+ declare function isRegisterRequeueable(code: string | undefined): boolean;
2545
3667
  interface RegisterOutboxOptions {
2546
3668
  collection: RxCollection<RegisterCommand>;
2547
3669
  /** The till's `register_sessions`. With it, a refused open (`register_session_already_open`) stops blocking its register
@@ -2565,6 +3687,10 @@ interface RegisterOutboxOptions {
2565
3687
  }
2566
3688
  interface RegisterOutbox {
2567
3689
  flush(): Promise<void>;
3690
+ /** Moves rejected commands (all, or those whose commandId is listed) back to pending in their ledger place, under
3691
+ * the same commandId and payload, then flushes: a refusal the store did not record is weighed again on a resend
3692
+ * of the same id (ADR-068 decision 5). Codes isRegisterRequeueable refuses are left. Resolves to the number requeued. */
3693
+ requeue(commandIds?: string[]): Promise<number>;
2568
3694
  start(): void;
2569
3695
  stop(): void;
2570
3696
  state$: Observable<OutboxState>;
@@ -2591,6 +3717,8 @@ interface UseRegisterOutboxResult {
2591
3717
  state: OutboxState;
2592
3718
  /** Sends pending till updates; does nothing while there is no collection. */
2593
3719
  flush(): Promise<void>;
3720
+ /** Moves rejected till updates back to pending (see RegisterOutbox.requeue); resolves to 0 while there is no collection. */
3721
+ requeue(commandIds?: string[]): Promise<number>;
2594
3722
  }
2595
3723
  declare function useRegisterOutbox(options: UseRegisterOutboxOptions): UseRegisterOutboxResult;
2596
3724
 
@@ -2654,6 +3782,43 @@ interface UseOrderOutboxResult {
2654
3782
  /** Opens the order store for `storeKey`, runs its outbox and watches the recent orders (lifted from medusapos/app, ADR-052). */
2655
3783
  declare function useOrderOutbox(options: UseOrderOutboxOptions): UseOrderOutboxResult;
2656
3784
 
3785
+ interface OutboxCounts {
3786
+ /** `OutboxState.pending`. */
3787
+ pending: number;
3788
+ /** `OutboxState.rejected`, 0 when unset. */
3789
+ rejected: number;
3790
+ /** `OutboxState.stuck.commandIds.length`, 0 when unset. These rows are pending too. */
3791
+ stuck: number;
3792
+ }
3793
+ interface OutboxHealth {
3794
+ /** The order outbox (`useOrderOutbox`): sales. */
3795
+ sales: OutboxCounts;
3796
+ /** The register outbox (`useRegisterOutbox`): till updates. */
3797
+ tillUpdates: OutboxCounts;
3798
+ /** Rejected plus stuck rows across both outboxes. Not `needsAttention()`'s list, which also holds applied orders with warnings. */
3799
+ attention: number;
3800
+ /** Either outbox parked after repeated 401s (`OutboxState.authRequired`): the cashier signs in again, then both flush. */
3801
+ authRequired: boolean;
3802
+ }
3803
+ /** The health of both outboxes from their states. Pure. */
3804
+ declare function summarizeOutboxHealth(sales: OutboxState, tillUpdates: OutboxState): OutboxHealth;
3805
+ /** summarizeOutboxHealth over both state streams (combineLatest), emitting only when a field changes. */
3806
+ declare function watchOutboxHealth(sales$: Observable<OutboxState>, tillUpdates$: Observable<OutboxState>): Observable<OutboxHealth>;
3807
+
3808
+ interface UseOutboxHealthOptions {
3809
+ /** `useOrderOutbox()`'s result; only `state` and `flush` are read. */
3810
+ sales: Pick<UseOrderOutboxResult, 'state' | 'flush'>;
3811
+ /** `useRegisterOutbox()`'s result; only `state` and `flush` are read. */
3812
+ tillUpdates: Pick<UseRegisterOutboxResult, 'state' | 'flush'>;
3813
+ }
3814
+ interface UseOutboxHealthResult {
3815
+ /** summarizeOutboxHealth of the two states; a new object only when a state changes. */
3816
+ health: OutboxHealth;
3817
+ /** Flushes both outboxes at once (after the cashier signs in again); rejects if either flush rejects. */
3818
+ flush(): Promise<void>;
3819
+ }
3820
+ declare function useOutboxHealth(options: UseOutboxHealthOptions): UseOutboxHealthResult;
3821
+
2657
3822
  type OrderRefundOutcome = {
2658
3823
  kind: 'applied';
2659
3824
  refund: OrderRefundResult;
@@ -2694,151 +3859,53 @@ declare function submitOrderRefund({ refunds, transport, envelope, now }: {
2694
3859
  record: PosRefund;
2695
3860
  }>;
2696
3861
 
2697
- /** The transport a payment terminal is reached over: hardware-neutral, not tied to any backend. */
2698
- type PaymentTransport = 'bluetooth' | 'usb' | 'network' | 'tap_to_pay';
2699
- type TenderView = 'select' | 'amount' | 'cancel';
2700
- type TenderLineId = string | number;
2701
- type TenderPlan = {
2702
- kind: 'even';
2703
- ways: number;
2704
- from: number;
2705
- } | {
2706
- kind: 'fixed';
2707
- firstMinor: number;
2708
- title: string | null;
2709
- from: number;
2710
- } | {
2711
- kind: 'items';
2712
- lineIds: TenderLineId[];
2713
- firstMinor: number;
2714
- ways: number;
2715
- from: number;
2716
- };
2717
- type SplitTab = 'even' | 'amount' | 'percent' | 'item';
2718
- interface TenderState {
2719
- view: TenderView;
2720
- /** Method id being tendered; null in the 'select' and 'cancel' views. */
2721
- methodId: string | null;
2722
- readerId: string | null;
2723
- transport: PaymentTransport | null;
2724
- /** Keypad entry in minor units. */
2725
- entryMinor: number;
2726
- /** False until the cashier has touched the keypad since the entry was pre-filled. */
2727
- entryDirty: boolean;
2728
- plan: TenderPlan | null;
2729
- splitView: boolean;
2730
- splitTab: SplitTab;
2731
- pickedLineIds: TenderLineId[];
2732
- linesPaidBy: Record<TenderLineId, string[]>;
2733
- }
2734
- /** '0'..'9' plus the two edit keys. There is deliberately no decimal key: digits shift in from the right. */
2735
- type TenderKey = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'clear' | 'backspace';
2736
- type TenderAction = {
2737
- type: 'pick-method';
2738
- methodId: string;
2739
- prefillMinor: number;
2740
- readerId: string | null;
2741
- transport?: PaymentTransport | null;
2742
- } | {
2743
- type: 'pick-transport';
2744
- transport: PaymentTransport;
2745
- } | {
2746
- type: 'pick-reader';
2747
- readerId: string | null;
2748
- } | {
2749
- type: 'tender-started';
2750
- } | {
2751
- type: 'key';
2752
- key: TenderKey;
2753
- } | {
2754
- type: 'set-entry';
2755
- minor: number;
2756
- } | {
2757
- type: 'back';
2758
- } | {
2759
- type: 'tender-recorded';
2760
- rowsSinceFrom: {
2761
- title: string;
2762
- amountMinor: number;
2763
- }[];
2764
- /** The order's balance once this row counts, so the next leg can be pre-typed. */
2765
- balanceMinor: number;
2766
- } | {
2767
- type: 'open-split';
2768
- } | {
2769
- type: 'close-split';
2770
- } | {
2771
- type: 'set-split-tab';
2772
- tab: SplitTab;
2773
- } | {
2774
- type: 'toggle-split-line';
2775
- lineId: TenderLineId;
2776
- } | {
2777
- type: 'set-plan';
2778
- plan: TenderPlan;
2779
- balanceMinor: number;
2780
- } | {
2781
- type: 'clear-plan';
2782
- balanceMinor: number;
2783
- } | {
2784
- type: 'arm-custom';
2785
- } | {
2786
- type: 'request-cancel';
2787
- } | {
2788
- type: 'reset';
2789
- };
2790
- /** $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. */
2791
- declare const MAX_TENDER_MINOR = 999999999;
2792
- declare const initialTenderState: TenderState;
2793
- /**
2794
- * Reducer init. An order whose method the checkout store already holds — a URL seed, or a
2795
- * tab the cashier is coming back to — reopens its keypad prefilled with the balance, exactly
2796
- * as a tap on that tile would. Everything else starts from scratch.
2797
- */
2798
- declare function initTenderState({ methodId, balanceMinor, }: {
2799
- methodId: string | null;
2800
- balanceMinor: number;
2801
- }): TenderState;
2802
- declare function tenderReducer(state: TenderState, action: TenderAction): TenderState;
2803
- /**
2804
- * What the leg applies to the order. Cash may be tendered above the balance;
2805
- * the excess is change, never an overpayment on the order.
2806
- */
2807
- declare function appliedMinor(entryMinor: number, balanceMinor: number): number;
2808
- /** Change handed back. Zero for any tender whose method cannot give change. */
2809
- declare function changeMinor(entryMinor: number, appliedAmountMinor: number, givesChange: boolean): number;
2810
- /**
2811
- * Quick tendered amounts under a cash keypad: the balance itself, then the next
2812
- * whole 5, 10 and 50 above it. Deduped, ascending, never below the balance.
2813
- * The caller supplies those major-unit steps already scaled to minor units.
2814
- */
2815
- declare function quickTenderedAmounts(balanceMinor: number, stepsMinor: readonly number[]): number[];
2816
3862
  /**
2817
- * Even split shares. Returns the next tender's share, rounded half-up to the
2818
- * minor unit; the last leg remains whatever balance is left.
3863
+ * Ports v2 calculate-refund.ts (calculateLineItemRefund, computeRemainingRefundQuantity).
3864
+ * Amounts follow ADR-080 amendment 2's cumulative-share rule.
2819
3865
  */
2820
- declare function evenSplitShareMinor(balanceMinor: number, ways: number): number;
2821
- /** Completion is derived from payment rows, never an extra counter in the reducer. */
2822
- declare function activePlan(plan: TenderPlan | null, taken: number, balanceMinor: number): TenderPlan | null;
2823
- interface PlanLeg {
2824
- minor: number;
2825
- state: 'done' | 'now' | 'todo' | 'rest';
2826
- title?: string;
3866
+
3867
+ /** The fields of an order line this needs; a StoreOrderLine fits. */
3868
+ type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
3869
+ /** Earlier refund lines; negative quantities count by magnitude. */
3870
+ interface EarlierRefund {
3871
+ lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>>;
2827
3872
  }
2828
- /** Label pieces stay untranslated here; the flow supplies localized copy and item names. */
2829
- declare function planLegs(plan: TenderPlan, rowsSinceFrom: {
2830
- minor: number;
2831
- title: string;
2832
- }[], balanceMinor: number): {
2833
- legs: PlanLeg[];
2834
- thisPaymentMinor: number;
2835
- label: {
2836
- n: number;
2837
- ways: number;
2838
- rest: boolean;
2839
- title: string | null;
2840
- };
2841
- };
3873
+ /** Remaining quantities and amounts, with earlier refund magnitudes capped at the line quantity. */
3874
+ interface RefundableLine {
3875
+ orderLineId: string;
3876
+ refundedQuantity: number;
3877
+ refundableQuantity: number;
3878
+ netMinor: number;
3879
+ taxMinor: number;
3880
+ }
3881
+ /** A selected quantity's cumulative shares of net and tax, and their sum. */
3882
+ interface PricedRefundLine {
3883
+ orderLineId: string;
3884
+ quantity: number;
3885
+ netMinor: number;
3886
+ taxMinor: number;
3887
+ totalMinor: number;
3888
+ }
3889
+ /** Payload-ready lines and their amounts; the caller adds shipping and adjustment to totalMinor. */
3890
+ interface PricedRefund {
3891
+ /** Exactly orderLineId, quantity (>= 1), and restock. */
3892
+ lines: OrderRefundLine[];
3893
+ /** Amounts in the same order as lines. */
3894
+ priced: PricedRefundLine[];
3895
+ /** Requests cut to availability, including unknown lines cut to zero. */
3896
+ clamped: Array<{
3897
+ orderLineId: string;
3898
+ requestedQuantity: number;
3899
+ quantity: number;
3900
+ }>;
3901
+ netMinor: number;
3902
+ taxMinor: number;
3903
+ totalMinor: number;
3904
+ }
3905
+ /** Returns the quantities and amounts still refundable, in order-line order. */
3906
+ declare function refundableLines(lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[]): RefundableLine[];
3907
+ /** Prices requested quantities with cumulative shares, clamping them to what remains refundable. */
3908
+ declare function priceRefund(lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[], request: readonly OrderRefundLine[]): PricedRefund;
2842
3909
 
2843
3910
  /**
2844
3911
  * One record per voided tender leg: its v2 ledger row plus the provenance a v2 `void`
@@ -2879,4 +3946,200 @@ declare function tenderVoidCollection(): {
2879
3946
  readonly schema: RxJsonSchema<TenderVoid>;
2880
3947
  };
2881
3948
 
2882
- export { type Actor, type AddLineInput, type AppliedDiscount, type BackendNotFound, type BasketLine, COUPONS_UNSUPPORTED, CartError, type CashMovement, type CashMovementCollection, type CatalogueEntry, type CatalogueGridColumns, type CatalogueView, type CatalogueViewAction, type CatalogueViewState, type ChargeInput, type ChargeLine, type Closure, type ClosureCollection, type ClosureContext, type ClosureScope, type CommandTransport, type Correction, CurrencyProvider, type CurrencyProviderProps, type CustomerSummary, DEFAULT_CATALOGUE_VIEW_STATE, DISCOUNTS_UNSUPPORTED, type Discount, type DisplayLine, type DisplayTotals, type FeeLine, type FinalizeOptions, type HttpTransportOptions, type LedgerRow, type LineItem, type LineTaxLine, type LogEntry, type LogLevel, type LogSink, type Logger, MAX_TENDER_MINOR, MICROS_PER_MINOR, type Movement$1 as Movement, type MovementType, type Order, type OrderBuilder, type OrderBuilderOptions, OrderContentMismatchError, type OrderCoupon, type OrderCouponContext, type OrderManager, type OrderManagerOptions, type OrderOutbox, type OrderOutboxOptions, type OrderRefundOutcome, type OrderTaxTotals, type OrderTransportContext, type OutboxState, PRODUCT_SORT_FIELDS, type ParkedOrderSummary, type Payment, type PaymentMethod, type PaymentTransport, type PlanLeg, type PosOrder, type PosOrderCoupon, type PosOrderLine, type PosOrderLocalWarning, PosOrderOpenClosedError, type PosOrderPayment, type PosOrderServerFailures, type PosOrderSyncStatus, type PosRefund, type PosRefundCollection, type PosRefundStatus, type ProductSort, type ProductSortValue, RECEIPT_SCHEMA_VERSION, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS, REOPENABLE_CODES, type RateTaxLine, type ReceiptConfig, type ReceiptData, type ReceiptFiscal, type ReceiptLineItem, type ReceiptRegister, type ReceiptSoftware, type RecordedFigures, RefundAnswerPendingError, RegisterApprovalRequiredError, type RegisterBucket, RegisterCloseIncompleteError, type RegisterCommand, type RegisterCommandCollection, type RegisterCounters, type RegisterDocument, type RegisterFact, type RegisterHost, RegisterIdInvalidError, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, RegisterNeedsUpgradeError, type RegisterOutbox, type RegisterOutboxOptions, type RegisterSession, RegisterSessionAlreadyOpenError, RegisterSessionClosedError, type RegisterSessionCollection, RegisterSessionConflictError, RegisterSessionOpenClosedError, RegisterSessionRequiredError, type RegisterStore, RegisterTakeOverError, RegisterTenderInProgressError, type ReopenRefusal, ReopenRefusedOrderError, type Repository, type ResolveStoreSettingsOptions, SALE_SAVING, type SaleDiscountCodes, type SaleDiscountState, type SaleStage, type SentOrder, type ShippingLine, type SplitTab, type StoreSettingsResolution, type StoreSettingsState, TAX_ROUNDING_MIXED_NOTE, type TaxContext, type TaxLineInput, TaxProvider, type TaxProviderProps, type TaxRateMap, type TenderAction, type TenderKey, type TenderLineId, type TenderPlan, type TenderState, type TenderView, type TenderVoid, type TransportOutcome, UnsupportedOrderVersionError, type UseOrderOutboxOptions, type UseOrderOutboxResult, type UseRegisterOutboxOptions, type UseRegisterOutboxResult, type UseRegisterSessionOptions, abandonSession, activePlan, addEntryToCart, addPosOrderCollection, addRegisterSessionCollection, adoptRegisterResults, advancePerpetual, allocateOrderDiscount, appliedMinor, backToSelling, bindRegister, buildClosureDocument, buildReceiptData, buildXReportDocument, callbackSink, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureCommand, closureSchema, computeOrderTax, consoleSink, countVariance, createBackendNotFound, createHttpCommandTransport, createLogger, createOrderBuilder, createOrderManager, createOrderOutbox, createRegisterOutbox, createRepository, denominationTotal, denominations, deriveExpected, deriveSettled, ensureRegister, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, formatClosureDate, getBoundRegisterId, getDeviceId, inCategory, initTenderState, initialTenderState, isKnownSessionStatus, isReopened, isRequeueable, isServerDecimal, labelKeys, listCategories, minorToDecimal, mintClosureNumber, mintUuid, movementCommand, movementFieldError, needsAttention, nextSaleCounter, normalizeAmount, normalizeCatalogueViewState, observeRegister$, openSession, openSessionSelector, orderDraftSchema, outboxLogger, overThreshold, parkedOrderSummaries$, parseMinor, planLegs, posOrderCollection, posOrderSchema, posOrdersLogger, posRefundCollection, posRefundSchema, productCategories, productSortValue, quickTenderedAmounts, ratePpmFromPercent, readBoundRegister, readRegister, reconcileRegisterCommands, recordMovement, recordRegisterFact, registerCommandCollection, registerCommandSchema, registerCommandsLogger, registerFactsLogger, registerSessionCollection, registerSessionSchema, registerSessionsLogger, reopenRefusedOrder, replacedOrderIds, requireOpenSession, resolveGridColumns, resolveStoreSettings, restoreOrderDraft, roundMicrosToMinor, saleLogger, sameSale, searchProducts, selectClosureRows, sendOrderRefund, sessionOpenCommand, sessionTransitionCommand, sortProducts, stampSession, startCounting, stockOverlay$, stockOverlayAsOf$, submitOrderRefund, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderVoidCollection, tenderVoidSchema, toOrderCreateEnvelope, unbindRegister, useCurrencyCode, useCurrencyFormatter, useOrderOutbox, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, withPricingContext, index as woocommerceDiscountCodes, writeClosure, writeOrderDraft };
3949
+ /**
3950
+ * Port of v2's cash rounding: packages/order-math/src/payments/rounding.ts and
3951
+ * packages/core/src/screens/main/pos/checkout/tender/tender-figures.ts.
3952
+ * v2's tender LEDGER: "a partial or short cash entry and every other method keep full precision".
3953
+ * Local figures only; writing the rounding as an order line is unit 24.
3954
+ */
3955
+
3956
+ /** The balance under a manual method's rounding, with its signed difference. */
3957
+ declare function roundedDue(balanceMinor: number, method: PaymentMethodDescriptor | null): {
3958
+ dueMinor: number;
3959
+ roundingMinor: number;
3960
+ };
3961
+ /** Local tender figures under the method's cash rounding. */
3962
+ interface TenderRounding {
3963
+ /** The balance under the method's rounding (the balance itself when none applies). */
3964
+ roundedDueMinor: number;
3965
+ /** `roundedDueMinor - balanceMinor` when the entry settles at the rounded due, else 0. Signed. */
3966
+ roundingMinor: number;
3967
+ /** The entry as the cashier sees it: an untouched prefill of the balance shows the rounded due. */
3968
+ entryMinor: number;
3969
+ /** What the entry applies to the order: the rounded due when rounding applies, else the capped entry. */
3970
+ appliedMinor: number;
3971
+ }
3972
+ /** Figure the displayed entry and applied amount, rounding only a leg that settles at the due. */
3973
+ declare function tenderRounding(state: Pick<TenderState, 'entryMinor' | 'entryDirty'>, balanceMinor: number, method: PaymentMethodDescriptor | null): TenderRounding;
3974
+
3975
+ /** A store day, `yyyy-MM-dd` in the store's timezone. */
3976
+ type StoreDay = string;
3977
+ /** Inclusive range of store days. */
3978
+ interface DayRange {
3979
+ from: StoreDay;
3980
+ to: StoreDay;
3981
+ }
3982
+ interface ReportCategory {
3983
+ id: string;
3984
+ name: string;
3985
+ }
3986
+ interface ReportLine {
3987
+ /** Grouping identity: variant, else product, else name. */
3988
+ key: string;
3989
+ name: string;
3990
+ quantity: number;
3991
+ /** After discounts, excluding tax. */
3992
+ netMinor: number;
3993
+ taxMinor: number;
3994
+ /** Cost of goods for the whole line (quantity × unit cost). Absent or null means the cost is missing, never 0. */
3995
+ costMinor?: number | null;
3996
+ /** The line's first category, when the caller joined one. */
3997
+ category?: ReportCategory;
3998
+ }
3999
+ interface ReportPayment {
4000
+ method: string;
4001
+ label?: string;
4002
+ amountMinor: number;
4003
+ }
4004
+ interface ReportTax {
4005
+ ratePpm: number;
4006
+ code?: string;
4007
+ label: string;
4008
+ taxMinor: number;
4009
+ /** The net this rate taxed; null when the source does not carry it. */
4010
+ netMinor: number | null;
4011
+ }
4012
+ /** An order as the reports read it. Money in integer minor units. */
4013
+ interface ReportOrder {
4014
+ id: string;
4015
+ /** ISO 8601 UTC instant the sale was made. */
4016
+ at: string;
4017
+ /** Gross, including tax. */
4018
+ totalMinor: number;
4019
+ taxMinor: number;
4020
+ discountMinor: number;
4021
+ /** True when the order still owes money: its unpaid remainder is `unpaid`, not `unknown`. */
4022
+ needsPayment?: boolean;
4023
+ lines: ReportLine[];
4024
+ payments: ReportPayment[];
4025
+ taxes: ReportTax[];
4026
+ /** Refunds embedded on the order, undated (a store order's own list). Positive. */
4027
+ refunds: Array<{
4028
+ id: string;
4029
+ amountMinor: number;
4030
+ }>;
4031
+ }
4032
+ /** A refund dated by when it was made, counted on that store day. */
4033
+ interface ReportRefund {
4034
+ id: string;
4035
+ orderId: string;
4036
+ /** ISO 8601 UTC instant the refund was made. */
4037
+ at: string;
4038
+ /** Positive. */
4039
+ amountMinor: number;
4040
+ }
4041
+ /** The caller's product directory: a line's unit cost and first category. */
4042
+ type LineJoin = (line: {
4043
+ productId?: string;
4044
+ variantId?: string;
4045
+ }) => {
4046
+ unitCostMinor?: number | null;
4047
+ category?: ReportCategory;
4048
+ } | undefined;
4049
+
4050
+ interface Margin {
4051
+ costedNetMinor: number;
4052
+ costMinor: number;
4053
+ profitMinor: number;
4054
+ marginPct: number | null;
4055
+ missingLines: number;
4056
+ missingQuantity: number;
4057
+ }
4058
+ interface SalesTotals {
4059
+ grossMinor: number;
4060
+ netMinor: number;
4061
+ taxMinor: number;
4062
+ discountMinor: number;
4063
+ refundsMinor: number;
4064
+ embeddedRefundsMinor: number;
4065
+ orderCount: number;
4066
+ averageMinor: number;
4067
+ items: number;
4068
+ margin: Margin;
4069
+ }
4070
+ interface PaymentRow {
4071
+ method: string;
4072
+ label: string;
4073
+ amountMinor: number;
4074
+ orders: number;
4075
+ }
4076
+ interface GroupRow {
4077
+ key: string;
4078
+ name: string;
4079
+ quantity: number;
4080
+ netMinor: number;
4081
+ margin: Margin;
4082
+ }
4083
+ interface TaxRow {
4084
+ key: string;
4085
+ ratePpm: number;
4086
+ code?: string;
4087
+ label: string;
4088
+ taxMinor: number;
4089
+ netMinor: number | null;
4090
+ }
4091
+ interface DayPoint {
4092
+ day: StoreDay;
4093
+ grossMinor: number;
4094
+ orderCount: number;
4095
+ refundsMinor: number;
4096
+ }
4097
+ interface SalesFiguresInput {
4098
+ orders: readonly ReportOrder[];
4099
+ refunds?: readonly ReportRefund[];
4100
+ range: DayRange;
4101
+ compare?: DayRange;
4102
+ /** IANA zone of the store, or 'device'. */
4103
+ timezone: string;
4104
+ }
4105
+ interface SalesFigures {
4106
+ range: DayRange;
4107
+ totals: SalesTotals;
4108
+ payments: {
4109
+ rows: PaymentRow[];
4110
+ takenMinor: number;
4111
+ };
4112
+ products: GroupRow[];
4113
+ categories: GroupRow[];
4114
+ taxes: TaxRow[];
4115
+ refunds: {
4116
+ count: number;
4117
+ amountMinor: number;
4118
+ orders: number;
4119
+ };
4120
+ series: DayPoint[];
4121
+ comparison?: {
4122
+ range: DayRange;
4123
+ totals: SalesTotals;
4124
+ series: DayPoint[];
4125
+ };
4126
+ }
4127
+ declare function inRange(at: string, range: DayRange, timezone: string): boolean;
4128
+ declare function daysOf(range: DayRange): StoreDay[];
4129
+ declare function comparisonRange(range: DayRange, mode: 'previous' | 'week'): DayRange;
4130
+ declare function marginOf(lines: readonly ReportLine[]): Margin;
4131
+ declare function salesFigures(input: SalesFiguresInput): SalesFigures;
4132
+
4133
+ type DatePreset = 'today' | 'yesterday' | 'thisWeek' | 'lastWeek' | 'thisMonth' | 'lastMonth';
4134
+ declare const DATE_PRESETS: readonly DatePreset[];
4135
+ /**
4136
+ * The preset's store days at `now` in `timezone` (IANA or 'device'). Weeks start Monday;
4137
+ * this week and this month end today, as WCPOS v2's date button clamps a preset to today.
4138
+ */
4139
+ declare function presetRange(preset: DatePreset, now: Date, timezone: string): DayRange;
4140
+
4141
+ declare function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin): ReportOrder;
4142
+ declare function reportOrderFromStoreOrder(order: StoreOrder, join?: LineJoin): ReportOrder;
4143
+ declare function reportRefundFromPosRefund(refund: PosRefund): ReportRefund | undefined;
4144
+
4145
+ 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, COUPONS_UNSUPPORTED, CartError, 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_PROTOCOL_VERSION, type DatePreset, type DayPoint, type DayRange, type DecodeRefusal, type DecodeResult, type Discount, type DisplayAction, type DisplayCart, type DisplayConfig, type DisplayEnvelope, type DisplayLine, type DisplayPayloads, type DisplayPayment, type DisplayState, type DisplayTemplate, type DisplayTotals, type DisplayView, type DriverAvailability, type DriverCapabilities, type DriverStatus, type DriverStatusSource, type EarlierRefund, type FeeLine, type FinalizeOptions, type FloatSuggestion, type GroupRow, 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 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, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureApprovalStatus, closureCommand, closureSchema, closureVariance, comparisonRange, computeOrderTax, consoleSink, countVariance, countsTowardPaid, createBackendNotFound, 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, ensureRegister, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, foldWedgeKey, formatClosureDate, getBoundRegisterId, getDeviceId, 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, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderRounding, tenderVoidCollection, tenderVoidSchema, toCsv, toOrderCreateEnvelope, toPrintError, unbindRegister, useAppSettings, useBarcodeScanner, useCashier, useCurrencyCode, useCurrencyFormatter, useOrderOutbox, useOutboxHealth, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, watchOutboxHealth, withPricingContext, index as woocommerceDiscountCodes, writeAppSetting, writeClosure, writeOrderDraft };