@tallyui/core 0.2.0 → 3.0.0-next.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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chunk-C4PWPOKO.js +18 -0
  3. package/dist/commands-BW4YYgRG.d.ts +306 -0
  4. package/dist/index.d.ts +636 -8
  5. package/dist/index.js +468 -4
  6. package/dist/rxdb/index.d.ts +37 -0
  7. package/dist/rxdb/index.js +26 -0
  8. package/dist/server/index.d.ts +213 -0
  9. package/dist/server/index.js +591 -0
  10. package/package.json +33 -3
  11. package/src/commands.ts +32 -0
  12. package/src/context/connector-context.tsx +78 -4
  13. package/src/index.ts +53 -0
  14. package/src/known-warnings.ts +77 -0
  15. package/src/money.ts +142 -0
  16. package/src/replication/combine.ts +77 -0
  17. package/src/replication/reconcile-feed.ts +116 -0
  18. package/src/rxdb/index.ts +4 -0
  19. package/src/rxdb/read-fresh.ts +32 -0
  20. package/src/rxdb/watch-fresh.ts +19 -0
  21. package/src/rxdb-remote-version-mismatch.ts +30 -0
  22. package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
  23. package/src/server/__fixtures__/order-create-v3.json +97 -0
  24. package/src/server/batch-outcome.ts +19 -0
  25. package/src/server/batch.ts +112 -0
  26. package/src/server/command-result.ts +138 -0
  27. package/src/server/fingerprint.ts +18 -0
  28. package/src/server/fiscal-figures.ts +84 -0
  29. package/src/server/index.ts +20 -0
  30. package/src/server/money.ts +34 -0
  31. package/src/server/order-payload-shape.ts +112 -0
  32. package/src/server/register-figures.ts +32 -0
  33. package/src/server/register-outcome.ts +12 -0
  34. package/src/server/register-payload-shape.ts +86 -0
  35. package/src/server/rejection-codes.ts +49 -0
  36. package/src/server/total-warnings.ts +10 -0
  37. package/src/server/versions.ts +9 -0
  38. package/src/sign-in.ts +21 -0
  39. package/src/stock-overlay.ts +35 -0
  40. package/src/store-settings.ts +29 -0
  41. package/src/sync-notice.ts +26 -0
  42. package/src/types/commands.ts +236 -0
  43. package/src/types/connector.ts +127 -0
  44. package/src/types/customers.ts +26 -0
  45. package/src/types/index.ts +23 -1
  46. package/src/types/money.ts +33 -0
  47. package/src/types/reconcile.ts +73 -0
  48. package/src/types/replication.ts +12 -0
  49. package/src/types/stock.ts +18 -0
  50. package/src/types/store-settings.ts +27 -0
  51. package/src/types/traits/product.ts +62 -6
  52. package/src/unauthorized.ts +13 -0
  53. package/src/utils/compare-ids.ts +16 -0
  54. package/src/variants.ts +14 -0
  55. package/src/__tests__/connector-context.test.tsx +0 -100
  56. package/src/types/replication.test-d.ts +0 -20
package/dist/index.d.ts CHANGED
@@ -1,8 +1,85 @@
1
1
  import { RxReplicationPullStreamItem, RxReplicationWriteToMasterRow, RxJsonSchema } from 'rxdb';
2
2
  import { Observable } from 'rxjs';
3
+ import { C as CommandWarning } from './commands-BW4YYgRG.js';
4
+ export { A as AnyCommandEnvelope, B as BatchTooLargeBody, a as COMMANDS_PATH, b as CommandBatchRequest, c as CommandBatchResponse, d as CommandEnvelope, e as CommandError, f as CommandResult, g as CommandServerRefs, h as CommandStatus, i as CommandType, M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, j as OrderCreateEnvelope, k as OrderCreateLine, l as OrderCreatePayload, m as OrderCreatePayment, n as OrderCreateTaxRate, P as PROTOCOL_HEADER, o as PROTOCOL_VERSION, p as PaymentMethodKind, R as RegisterClosureSubmitPayload, q as RegisterCommandEnvelope, r as RegisterCommandResult, s as RegisterCommandType, t as RegisterMovementRecordPayload, u as RegisterMovementVoidPayload, v as RegisterSessionOpenPayload, w as RegisterSessionTransitionPayload, x as isCommandBatchResponse } from './commands-BW4YYgRG.js';
3
5
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
6
  import { ReactNode } from 'react';
5
7
 
8
+ /**
9
+ * A monetary amount in integer minor units (cents for EUR/USD, yen for JPY)
10
+ * with its ISO 4217 currency code. Integers keep arithmetic exact, and the
11
+ * code travels with the amount so nothing assumes a store-wide currency.
12
+ */
13
+ interface Money {
14
+ /** Integer amount in the currency's minor unit, e.g. 1250 for €12.50. */
15
+ amount: number;
16
+ /** Upper-case ISO 4217 code, e.g. 'EUR'. 'XXX' when the backend gives none. */
17
+ currency: string;
18
+ }
19
+ /**
20
+ * One entry in a product's price list.
21
+ *
22
+ * `base` is the everyday price. `sale` is a temporary reduction that replaces
23
+ * the base price in the same currency while it applies. Backends express
24
+ * sales differently (WooCommerce sale_price, Medusa sale price lists, Shopify
25
+ * compare_at_price) and each connector maps its own form into these entries,
26
+ * so components never need regular/sale/on-sale flags.
27
+ */
28
+ interface ProductPrice extends Money {
29
+ kind: 'base' | 'sale';
30
+ /** Set when the backend says so for this price; it wins over the store-level `pricesIncludeTax`. Undefined: use the store-level setting. */
31
+ taxInclusive?: boolean;
32
+ }
33
+ /** The price to charge, and the price it replaces when a sale applies; each keeps its source's `taxInclusive` when set. */
34
+ interface ResolvedPrice {
35
+ current: Money & {
36
+ taxInclusive?: boolean;
37
+ };
38
+ /** Set only when a sale price applies: the base price it replaces. */
39
+ was?: Money & {
40
+ taxInclusive?: boolean;
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Backend-neutral stock state.
46
+ *
47
+ * - `in_stock`: sellable now. `quantity` is set when the backend tracks it.
48
+ * - `out_of_stock`: tracked and none left; not sellable.
49
+ * - `backorder`: none left but the backend accepts orders anyway.
50
+ * - `unknown`: the backend did not say.
51
+ *
52
+ * `quantity` is undefined when stock is not tracked, which is different from
53
+ * a tracked quantity of 0.
54
+ */
55
+ type StockStatus = 'in_stock' | 'out_of_stock' | 'backorder' | 'unknown';
56
+ interface StockLevel {
57
+ status: StockStatus;
58
+ /** Units on hand, when tracked. May be negative on backorder. */
59
+ quantity?: number;
60
+ }
61
+
62
+ /** One purchasable variant of a product, in backend-neutral terms. */
63
+ interface VariantSummary {
64
+ /** Backend variant id; the id sent in order lines. */
65
+ id: string;
66
+ /** Variant label, e.g. 'S / White'; undefined when the backend has none. */
67
+ title?: string;
68
+ sku?: string;
69
+ /** First non-empty of the backend's barcode fields. */
70
+ barcode?: string;
71
+ prices: ProductPrice[];
72
+ stock: StockLevel;
73
+ }
74
+ /**
75
+ * Store-level facts a connector may need to interpret a raw document, for
76
+ * backends whose documents omit them (WooCommerce product prices carry no
77
+ * currency).
78
+ */
79
+ interface TraitContext {
80
+ /** The store's ISO 4217 currency code. */
81
+ currency?: string;
82
+ }
6
83
  /**
7
84
  * Product traits — the stable interface that UI components program against.
8
85
  *
@@ -12,19 +89,39 @@ import { ReactNode } from 'react';
12
89
  * Vendure, Shopify, etc.
13
90
  *
14
91
  * The generic `Doc` type is the connector's raw RxDB document type.
92
+ *
93
+ * Price and stock are read through the backend-neutral `getPrices` and
94
+ * `getStock`. The older string-price and WooCommerce-style stock accessors
95
+ * remain for existing consumers and are deprecated.
15
96
  */
16
97
  interface ProductTraits<Doc = any> {
17
98
  /** Product display name */
18
99
  getName: (doc: Doc) => string;
19
100
  /** SKU / stock keeping unit */
20
101
  getSku: (doc: Doc) => string | undefined;
21
- /** Current selling price as a string (connector-native format) */
102
+ /**
103
+ * The product's price list: base prices, plus sale prices while a sale
104
+ * applies, per currency. Pass the list to `resolvePrice` for the price to
105
+ * charge. For variable products this describes the default variant.
106
+ */
107
+ getPrices: (doc: Doc, context?: TraitContext) => ProductPrice[];
108
+ /** Stock state of the whole product across its variants; `quantity` is the total on hand when every variant is tracked, else undefined. */
109
+ getStock: (doc: Doc) => StockLevel;
110
+ /** All purchasable variants, in id order (connectors store variants sorted by id). Optional: connectors without variant support omit it. */
111
+ getVariants?: (doc: Doc, context?: TraitContext) => VariantSummary[];
112
+ /**
113
+ * The backend's tax class id for the variant `variantId`, or for the product (its default variant) when omitted.
114
+ * The id is a key of `StoreSettings.taxRatesPpm`; undefined means the default class. Optional: without it, every
115
+ * line is taxed at the default rate.
116
+ */
117
+ getTaxClass?: (doc: Doc, variantId?: string) => string | undefined;
118
+ /** @deprecated Use `getPrices` with `resolvePrice`. */
22
119
  getPrice: (doc: Doc) => string | undefined;
23
- /** Regular (non-sale) price */
120
+ /** Regular (non-sale) price. @deprecated Use `getPrices` with `resolvePrice`. */
24
121
  getRegularPrice: (doc: Doc) => string | undefined;
25
- /** Sale price, if on sale */
122
+ /** Sale price, if on sale. @deprecated Use `getPrices` with `resolvePrice`. */
26
123
  getSalePrice: (doc: Doc) => string | undefined;
27
- /** Whether the product is currently on sale */
124
+ /** Whether the product is currently on sale. @deprecated Use `getPrices` with `resolvePrice`. */
28
125
  isOnSale: (doc: Doc) => boolean;
29
126
  /** Primary image URL */
30
127
  getImageUrl: (doc: Doc) => string | undefined;
@@ -32,12 +129,16 @@ interface ProductTraits<Doc = any> {
32
129
  getImageUrls: (doc: Doc) => string[];
33
130
  /** Short description / excerpt */
34
131
  getDescription: (doc: Doc) => string | undefined;
35
- /** Stock status */
132
+ /** Stock status. @deprecated Use `getStock`. */
36
133
  getStockStatus: (doc: Doc) => 'instock' | 'outofstock' | 'onbackorder' | 'unknown';
37
- /** Stock quantity (null if not tracked) */
134
+ /** Stock quantity (null if not tracked). @deprecated Use `getStock`. */
38
135
  getStockQuantity: (doc: Doc) => number | null;
39
136
  /** Whether this product has variants/variations */
40
137
  hasVariants: (doc: Doc) => boolean;
138
+ /** Whether the product may be sold at the register now: published/active, not a draft, archived or disabled. */
139
+ isSellable: (doc: Doc) => boolean;
140
+ /** Number of purchasable variants; 1 for a simple product. */
141
+ getVariantCount: (doc: Doc) => number;
41
142
  /** Product type (simple, variable, etc. — connector-specific but useful for UI hints) */
42
143
  getType: (doc: Doc) => string;
43
144
  /** Barcode / UPC / EAN */
@@ -87,6 +188,16 @@ interface ReplicationAdapter<RxDocType, CheckpointType = any> {
87
188
  }>;
88
189
  checkpoint: CheckpointType;
89
190
  }>;
191
+ /**
192
+ * Documents per pull page, passed to handler as batchSize. RxDB treats a
193
+ * shorter page as the end of the cycle. Defaults to RxDB's 100.
194
+ */
195
+ batchSize?: number;
196
+ /**
197
+ * Fresh install only: the checkpoint this feed starts from instead of a full first pass,
198
+ * read before any feed runs (combinePullAdapters). Absent: a full first pass, as today.
199
+ */
200
+ seedCheckpoint?: (context: SyncContext) => Promise<CheckpointType>;
90
201
  /**
91
202
  * Optional real-time event stream.
92
203
  * Emit { documents, checkpoint } for live updates,
@@ -108,6 +219,151 @@ interface ReplicationAdapter<RxDocType, CheckpointType = any> {
108
219
  };
109
220
  }
110
221
 
222
+ /**
223
+ * Re-reads stock from the backend, because replication misses stock changes
224
+ * that bump no product timestamp (ADR-060). The runner stores `fetchPages`
225
+ * output in the non-replicated `stock_levels` collection; readers merge it
226
+ * into a read-only view of each product with `overlay`. Nothing is written
227
+ * into the replicated products.
228
+ */
229
+ interface StockReconcileAdapter<Doc = any> {
230
+ /** Current stock, one backend request per page, keyed as the connector chooses (variant, inventory item). */
231
+ fetchPages(context: SyncContext): AsyncIterable<Map<string, unknown>>;
232
+ /**
233
+ * Pure: the fields of `doc` that `stock` changes, or undefined when nothing
234
+ * differs. Keys absent from `stock` are left alone. The result is merged
235
+ * into a read-only view of the document and never written.
236
+ */
237
+ overlay(doc: Doc, stock: Map<string, unknown>): Partial<Doc> | undefined;
238
+ }
239
+ /** Catches a deleted product or a deleted variant that replication misses (ADR-060). Nothing is written locally: `enqueue` hands disagreeing documents to a `createReconcileFeed` pull adapter instead. */
240
+ interface IdReconcileAdapter<Doc = any> {
241
+ /** Every live product with its live variant ids, one backend request per page. */
242
+ fetchPages(context: SyncContext): AsyncIterable<Array<{
243
+ id: string;
244
+ variantIds: string[];
245
+ }>>;
246
+ /** The variant ids a local product document lists. */
247
+ variantIds(doc: Doc): string[];
248
+ /** Hand local documents that disagree with the backend to the collection's pull (see createReconcileFeed). */
249
+ enqueue(entries: Array<{
250
+ id: string;
251
+ local: Doc;
252
+ }>): void;
253
+ /** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
254
+ refetchBatchSize?: number;
255
+ }
256
+ /** Re-delivers products whose remote fingerprint differs from the local one (ADR-060). */
257
+ interface FingerprintReconcileAdapter<Doc = any> {
258
+ /** Remote fingerprints by product id, one backend request per page. Products the backend doesn't report are left alone. */
259
+ fetchPages(context: SyncContext): AsyncIterable<Map<string, string>>;
260
+ /** The same fingerprint computed from a local product document. */
261
+ fingerprint(doc: Doc): string;
262
+ /**
263
+ * Hands products to the collection's pull (the reconcile feed). `refreshOnly`
264
+ * marks an entry so a missing product is skipped, never tombstoned: only the
265
+ * id reconcile, with its mass-delete brake, may delete.
266
+ */
267
+ enqueue(entries: Array<{
268
+ id: string;
269
+ local: Doc;
270
+ refreshOnly?: boolean;
271
+ }>): void;
272
+ /** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
273
+ refetchBatchSize?: number;
274
+ }
275
+ /** One product in the catalogue listing. `key` is the local primary key value; `remote` is whatever the connector needs to refetch it (a numeric backend id, say). */
276
+ interface CatalogueReconcileEntry {
277
+ key: string;
278
+ fingerprint: string;
279
+ remote?: unknown;
280
+ }
281
+ /**
282
+ * The daily catalogue check (#248): one walk that refetches what differs and
283
+ * deletes only with proof. Nothing is written locally: `enqueue` hands
284
+ * documents to the collection's pull (the reconcile feed). `Cursor` must be
285
+ * JSON-serialisable, since the runner persists it to resume a stopped pass.
286
+ */
287
+ interface CatalogueReconcileAdapter<Doc = any, Cursor = unknown> {
288
+ /** Remote listing, one backend request per page, from `from` (a cursor this adapter yielded earlier) or the start. */
289
+ fetchPages(context: SyncContext, from?: Cursor): AsyncIterable<{
290
+ entries: CatalogueReconcileEntry[];
291
+ cursor: Cursor;
292
+ }>;
293
+ /** Pure: the same fingerprint from a local document. */
294
+ fingerprint(doc: Doc): string;
295
+ /**
296
+ * Deletion proof, required: of these local documents (the ones the listing did not name), the keys
297
+ * the backend confirms gone (absent, or no longer sellable). One or more requests. Only confirmed
298
+ * keys are tombstoned; an adapter that never deletes returns none.
299
+ */
300
+ confirmGone(locals: Doc[], context: SyncContext): Promise<string[]>;
301
+ /** Hand documents to the collection's pull (the reconcile feed). */
302
+ enqueue(entries: Array<{
303
+ key: string;
304
+ local?: Doc;
305
+ remote?: unknown;
306
+ tombstone?: boolean;
307
+ }>): void;
308
+ /** Ids per `fetchByIds` request of the feed this adapter enqueues into: a page's `n` refetches take `ceil(n / refetchBatchSize)` budget slots (1 when unset). */
309
+ refetchBatchSize?: number;
310
+ }
311
+
312
+ /** What the POS needs from the store's own settings (TV4). Read once after sign-in; the app feeds all three consumers from it. */
313
+ interface StoreSettings {
314
+ /** ISO 4217, upper case (the currency prices are sold in). */
315
+ currency: string;
316
+ /** Whether the store's catalogue prices include tax. It feeds both the connector's traits and the POS TaxProvider, so the two cannot disagree. */
317
+ pricesIncludeTax: boolean;
318
+ /** Tax rates for the store's location as integer parts per million (25% = 250000), keyed by the backend's tax class; `default` applies to a product with no class. Always integers: a connector rounds a backend's decimal rate once, at its edge. Structurally the same as @tallyui/pos's TaxRateMap. */
319
+ taxRatesPpm: {
320
+ default: number;
321
+ [taxClass: string]: number;
322
+ };
323
+ /** Connector-specific and opaque to the app: what the connector needs to price documents. The app passes it back to the connector unchanged, and never logs it. */
324
+ pricingContext?: Record<string, string>;
325
+ /** Derived, never read by `storeSettings`: the store's `ServerCapabilities.taxRounding`, which `useStoreSettings` fills in (#324). */
326
+ taxRounding?: TaxRounding;
327
+ }
328
+ /**
329
+ * Picks among several regions, countries or sales channels when the store has more than one.
330
+ * The app persists the choice per store, in its own settings, so it is asked once. A stored
331
+ * choice that no longer resolves (for example, the region was deleted) raises `choice_required`
332
+ * again instead of failing. Backends without the concept ignore a field.
333
+ */
334
+ interface StoreSettingsChoice {
335
+ region?: string;
336
+ country?: string;
337
+ channel?: string;
338
+ }
339
+
340
+ /** A store customer, as the till shows and picks it (programme item 14). Platform-neutral. */
341
+ interface Customer {
342
+ /** The platform's id: order.create v3 sends it as `customer.customerId`. */
343
+ id: string;
344
+ /** Display name: first + last, else company, else email, else id. Never empty. */
345
+ name: string;
346
+ firstName?: string;
347
+ lastName?: string;
348
+ email?: string;
349
+ phone?: string;
350
+ company?: string;
351
+ }
352
+ /** What the till collects to create a customer. v1 requires an email. */
353
+ interface CustomerInput {
354
+ email: string;
355
+ firstName?: string;
356
+ lastName?: string;
357
+ phone?: string;
358
+ company?: string;
359
+ }
360
+ declare const customerTraits: CustomerTraits<Customer>;
361
+ /** A customer call that failed for a reason other than credentials (credentials throw ConnectorUnauthorizedError). */
362
+ declare class CustomerServiceError extends Error {
363
+ readonly code: 'network' | 'server' | 'invalid';
364
+ constructor(code: 'network' | 'server' | 'invalid', message: string);
365
+ }
366
+
111
367
  /**
112
368
  * Authentication configuration for a connector.
113
369
  * Each API has wildly different auth — JWT, API keys, OAuth, etc.
@@ -122,7 +378,61 @@ interface ConnectorAuth {
122
378
  getHeaders: (credentials: Record<string, string>) => Record<string, string>;
123
379
  /** Optional: validate that credentials work (e.g., test API call) */
124
380
  validate?: (credentials: Record<string, string>) => Promise<boolean>;
381
+ /**
382
+ * Exchanges a user's email and password for a credential (token) to store and pass back to getHeaders as `token`.
383
+ * Rejects with a `SignInError`: `invalid_credentials`, `unsupported` or `failed`.
384
+ */
385
+ signIn?: (baseUrl: string, login: {
386
+ email: string;
387
+ password: string;
388
+ }, init?: {
389
+ signal?: AbortSignal;
390
+ fetch?: typeof fetch;
391
+ }) => Promise<SignInResult>;
392
+ }
393
+ interface SignInResult {
394
+ token: string;
395
+ /** ISO 8601, when the backend says when the token expires */
396
+ expiresAt?: string;
397
+ /** The store's contract capabilities (ADR-062), when the read was conclusive. */
398
+ capabilities?: ServerCapabilities;
125
399
  }
400
+ /** The highest `order.create` contract version a store's server currently accepts (ADR-062). */
401
+ interface ServerCapabilities {
402
+ orderCreate: number;
403
+ /** The highest `register` contract version; absent or 0 means no register sync. */
404
+ register?: number;
405
+ /** How the store rounds tax (#287). Absent: an older server, per_order + half_away_from_zero. */
406
+ taxRounding?: TaxRounding;
407
+ }
408
+ /** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
409
+ type TaxRounding = {
410
+ granularity: 'per_order' | 'per_line_items' | 'per_rate_group_items';
411
+ mode: 'half_away_from_zero' | 'half_up';
412
+ } | {
413
+ granularity: 'custom';
414
+ };
415
+ /**
416
+ * Resolves the capabilities to act on: a definitive fresh read always wins,
417
+ * even a downgrade to 1; an inconclusive fresh read (`undefined`) keeps the
418
+ * last known value. The app persists `stored` with its session, the way it
419
+ * persists the store-settings choice, and copies the result into
420
+ * `SyncContext.capabilities`. `finalizeOrder` treats `undefined` as 1, which
421
+ * only happens when the value has never been read (ADR-062).
422
+ */
423
+ declare function resolveCapabilities(fresh: ServerCapabilities | undefined, stored: ServerCapabilities | undefined): ServerCapabilities | undefined;
424
+ /**
425
+ * Reads the `taxRounding` of `GET /tally/v1/info` (#287): a valid value comes back without
426
+ * extra keys, and `custom` drops any `mode`. Absent gives `undefined`, the default. Core has
427
+ * no logger, so a malformed value gives `undefined` and one reason to `warn` for the caller to log.
428
+ */
429
+ declare function parseTaxRounding(value: unknown, warn?: (reason: string) => void): TaxRounding | undefined;
430
+ /**
431
+ * Reads a 2xx body of `GET /tally/v1/info` (ADR-062): `orderCreate` is the max of
432
+ * `contracts["order.create"]`, or 1 when it's missing or malformed; `register` is the max of
433
+ * `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287).
434
+ */
435
+ declare function parseInfoCapabilities(body: unknown, warn?: (reason: string) => void): ServerCapabilities;
126
436
  interface AuthField {
127
437
  key: string;
128
438
  label: string;
@@ -164,10 +474,19 @@ interface SyncContext {
164
474
  headers: Record<string, string>;
165
475
  /** Optional abort signal */
166
476
  signal?: AbortSignal;
477
+ /** From `storeSettings().pricingContext`; opaque to the app; the connector prices documents with it. Never logged. */
478
+ pricingContext?: Record<string, string>;
479
+ /** The store's contract capabilities (ADR-062), copied from the sign-in result. */
480
+ capabilities?: ServerCapabilities;
167
481
  }
168
482
  /**
169
483
  * Schema definitions for a connector.
170
484
  * Each connector provides its own RxDB schemas that mirror its API shape.
485
+ *
486
+ * Each describes a server-owned, pull-replicated collection (ADR-060), so its
487
+ * versions never transform documents: a version bump drops and resyncs.
488
+ * `createTallyDatabase` drops the old documents, and `startReplication` resets
489
+ * the checkpoint, so the first sync after the bump downloads the collection again.
171
490
  */
172
491
  interface ConnectorSchemas {
173
492
  products: RxJsonSchema<any>;
@@ -213,13 +532,301 @@ interface TallyConnector {
213
532
  products?: ReplicationAdapter<any>;
214
533
  [key: string]: ReplicationAdapter<any> | undefined;
215
534
  };
535
+ /** Periodic re-reads of state that replication misses (ADR-060) */
536
+ reconcile?: {
537
+ stock?: StockReconcileAdapter;
538
+ ids?: IdReconcileAdapter;
539
+ prices?: FingerprintReconcileAdapter;
540
+ /** Prices the backend calculates for the sales context (price lists, sale dates), which change without a timestamp bump. */
541
+ calculatedPrices?: FingerprintReconcileAdapter;
542
+ /** The daily catalogue check (#248): refetches what differs, deletes only with proof. */
543
+ catalogue?: CatalogueReconcileAdapter;
544
+ };
545
+ /**
546
+ * Reads the store's own settings (TV4): currency, tax inclusivity, tax
547
+ * rates and a connector-specific pricing context. Read once after
548
+ * sign-in; the app feeds all three consumers from the result. Read-only,
549
+ * never writes to the store (ADR-048).
550
+ */
551
+ storeSettings?: (context: SyncContext, choice?: StoreSettingsChoice) => Promise<StoreSettings>;
552
+ /**
553
+ * Re-reads the store's contract capabilities (ADR-062) for a session
554
+ * restored without signing in again — otherwise a restored session would
555
+ * block discounts until the cashier signed in again. `undefined` means
556
+ * the read was inconclusive (offline or a server error), not version 1;
557
+ * see `resolveCapabilities`.
558
+ */
559
+ capabilities?: (context: SyncContext) => Promise<ServerCapabilities | undefined>;
560
+ /** Customer search: online only; `undefined` when the connector has no customer support. */
561
+ searchCustomers?: (context: SyncContext, query: string, options?: {
562
+ limit?: number;
563
+ }) => Promise<Customer[]>;
564
+ /** Customer creation: online only; `undefined` when the connector has no customer support. */
565
+ createCustomer?: (context: SyncContext, input: CustomerInput) => Promise<Customer>;
566
+ /** Customer lookup: online only; `undefined` when the connector has no customer support. */
567
+ getCustomer?: (context: SyncContext, id: string) => Promise<Customer | null>;
568
+ }
569
+
570
+ /**
571
+ * Why `ConnectorAuth.signIn` failed:
572
+ * - `failed`: no response arrived (network error, DNS, TLS, refused);
573
+ * - `server_error`: a response arrived but was unusable;
574
+ * - `unsupported`: the backend needs a sign-in flow this connector can't do;
575
+ * - `invalid_credentials`: wrong email or password.
576
+ */
577
+ type SignInErrorCode = 'invalid_credentials' | 'unsupported' | 'failed' | 'server_error';
578
+ /** The rejection from `ConnectorAuth.signIn`; the app picks its message from `code`. */
579
+ declare class SignInError extends Error {
580
+ readonly code: SignInErrorCode;
581
+ readonly status?: number;
582
+ constructor(code: SignInErrorCode, message: string, status?: number);
583
+ }
584
+
585
+ /** A backend refused the stored credentials (expired, revoked or insufficient); the app should sign in again. */
586
+ declare class ConnectorUnauthorizedError extends Error {
587
+ readonly code: "unauthorized";
588
+ /** Only signing in on this till fixes it, so the pull stops until `resume()` (`errorKind`). */
589
+ readonly fixedBy: "till";
590
+ readonly status?: number;
591
+ constructor(message: string, status?: number);
592
+ }
593
+
594
+ /**
595
+ * True for RxDB's RM1: the remote storage worker was built on another RxDB
596
+ * version than the main thread, e.g. a stale worker the browser cached from
597
+ * before an upgrade. Reloading loads the matching worker.
598
+ *
599
+ * Matched by structure, never by substring. An `RxError` (rxdb 17.5.0
600
+ * src/rx-error.ts) has own `code`, `message`, `url`, `parameters` and
601
+ * `rxdb: true`; its `name` is a getter. So RM1 is either an object whose own
602
+ * `code` is `'RM1'` (with `rxdb === true` when `rxdb` is present), or an
603
+ * error, `{ message }` copy or string whose message is the remote storage's
604
+ * `could not create instance ` followed by JSON with `rxdb: true` and
605
+ * `code: 'RM1'`. Needs no rxdb import.
606
+ */
607
+ declare function isRxdbRemoteVersionMismatch(error: unknown): boolean;
608
+
609
+ /**
610
+ * A pull that stopped until someone acts; `SyncStatus` owns the words for each `code`.
611
+ * `fixedBy` says who can fix it: the till (sign in again) or the store owner.
612
+ * `software` / `minVersion` / `fix` are copied from the error when it names them.
613
+ */
614
+ type SyncNotice = {
615
+ code: string;
616
+ since: number;
617
+ fixedBy: 'till' | 'store';
618
+ software?: string;
619
+ minVersion?: string;
620
+ fix?: string;
621
+ };
622
+ /** Who can fix a pull error: the till, the store owner, or nobody (it passes, so it is retried). */
623
+ type ErrorKind = 'till' | 'store' | 'transient';
624
+ /**
625
+ * 'till' or 'store' for an error whose class sets `fixedBy` to that value and a
626
+ * string `code`; 'transient' for anything else.
627
+ */
628
+ declare function errorKind(error: unknown): ErrorKind;
629
+
630
+ /**
631
+ * Why `TallyConnector.storeSettings` failed:
632
+ * - `choice_required`: the store has more than one region, country or
633
+ * channel and none is chosen yet (or the stored choice no longer
634
+ * resolves); `choices` says what the app can offer;
635
+ * - `failed`: the read could not complete (network error, non-OK response,
636
+ * a GraphQL/API error).
637
+ */
638
+ type StoreSettingsErrorCode = 'choice_required' | 'failed';
639
+ /** What the app can offer the user when `StoreSettingsError.code` is `choice_required`. */
640
+ interface StoreSettingsChoices {
641
+ regions?: Array<{
642
+ id: string;
643
+ name: string;
644
+ }>;
645
+ countries?: string[];
646
+ channels?: Array<{
647
+ id: string;
648
+ name: string;
649
+ }>;
650
+ }
651
+ /** The rejection from `TallyConnector.storeSettings`; the app picks its message from `code`. */
652
+ declare class StoreSettingsError extends Error {
653
+ readonly code: StoreSettingsErrorCode;
654
+ readonly choices?: StoreSettingsChoices;
655
+ constructor(code: StoreSettingsErrorCode, message: string, choices?: StoreSettingsChoices);
216
656
  }
217
657
 
658
+ /** Number of minor-unit digits for an ISO 4217 code (2 for EUR, 0 for JPY). */
659
+ declare function minorUnitDigits(currency: string): number;
660
+ /** The currency's symbol for a plain-English label ('€' for EUR, '$' for USD), not a full amount. */
661
+ declare function currencySymbol(currency: string, locale?: string): string;
662
+ /**
663
+ * Converts a major-unit amount ('12.50', 12.5) into Money.
664
+ * Returns undefined for empty or non-numeric input.
665
+ */
666
+ declare function moneyFromMajor(value: string | number | null | undefined, currency: string): Money | undefined;
667
+ /** Parses trimmed decimal text into safe integer minor units, without rounding. */
668
+ declare function moneyFromDecimalString(text: string, currency: string): Money | undefined;
669
+ /** Converts Money back to a major-unit number, e.g. for Intl formatting. */
670
+ declare function moneyToMajor(money: Money): number;
671
+ /**
672
+ * Formats Money for display with Intl, e.g. '€12.50' or '¥1,200'.
673
+ * Returns undefined for 'XXX' (currency unknown), so callers can fall back.
674
+ */
675
+ declare function formatMoney(money: Money, locale?: string): string | undefined;
676
+ /**
677
+ * Picks the price to charge from a price list, in `currency` if given, else in
678
+ * the first currency listed. A sale entry wins over the base entry.
679
+ */
680
+ declare function resolvePrice(prices: ProductPrice[], currency?: string): ResolvedPrice | undefined;
681
+ /**
682
+ * The lowest and highest price to charge across variants, in `currency` if
683
+ * given, else each variant's first currency; undefined when no variant
684
+ * resolves. Only amounts in the first resolved variant's currency are
685
+ * compared; a variant that resolves to another currency is skipped.
686
+ */
687
+ declare function resolvePriceRange(variants: Array<{
688
+ prices: ProductPrice[];
689
+ }>, currency?: string): {
690
+ min: Money;
691
+ max: Money;
692
+ } | undefined;
693
+
694
+ /**
695
+ * The variant whose barcode or SKU equals `code`, compared after trimming
696
+ * both sides and ignoring case. A barcode match wins over a SKU match. When
697
+ * several variants match the same way, the first one wins. Returns undefined
698
+ * for an empty code or no match.
699
+ */
700
+ declare function findVariantByCode(variants: VariantSummary[], code: string): VariantSummary | undefined;
701
+
702
+ /**
703
+ * The till's single reader of stored warnings. `[]` for anything that isn't a warnings array.
704
+ * A `total_mismatch`'s `bridgeMinor` is dropped (the rest of the warning is kept) when it's
705
+ * absent, `null`, not a safe integer, zero, or not equal to `expectedMinor - serverMinor`.
706
+ * A `tax_rate_mismatch` with a negative `ratePpm` is dropped entirely; zero stays valid.
707
+ * A `customer_ignored` is dropped unless its `customerId` is a string of 1 to 64 characters.
708
+ * A `figures_mismatch` is dropped entirely unless `fields` is non-empty and each entry names a
709
+ * different figure with two differing safe integers; each entry is rebuilt from its known keys.
710
+ * A figure name it doesn't know (any non-empty string) is kept, since a newer store may send one.
711
+ */
712
+ declare function knownWarnings(warnings: unknown): CommandWarning[];
713
+
714
+ /** Orders backend ids: numerically when both are integer strings (Vendure '9' < '10', compared with BigInt so long ids stay exact), with ties in numeric value (e.g. '01' vs '1') broken by plain string order; an integer id always sorts before a non-integer one; otherwise (neither is an integer string) by plain string order (not `localeCompare`, which is locale-dependent). This is a total order, so sorting is consistent regardless of input order. */
715
+ declare function compareIds(a: string | number, b: string | number): number;
716
+
717
+ /**
718
+ * Local document id, in the `stock_levels` collection, that holds the time of
719
+ * the last successful reconcile pass (`{ completedAt }`). Lives here so the
720
+ * runner in `@tallyui/database` and the readers in `@tallyui/pos` share it.
721
+ */
722
+ declare const STOCK_LEVELS_LAST_PASS = "last-pass";
723
+ /**
724
+ * A read-only view of `doc` with reconciled stock merged in (ADR-060).
725
+ * Returns `doc` itself when there is nothing to merge; never mutates it.
726
+ */
727
+ declare function withStockOverlay<Doc>(doc: Doc, adapter: StockReconcileAdapter<Doc> | undefined, overlay: Map<string, unknown> | undefined): Doc;
728
+ /**
729
+ * The product's stock, from the overlay where it has an entry for a variant
730
+ * or item, otherwise from the replicated document.
731
+ */
732
+ declare function getProductStock<Doc>(doc: Doc, traits: ProductTraits<Doc>, adapter: StockReconcileAdapter<Doc> | undefined, overlay: Map<string, unknown> | undefined): StockLevel;
733
+
734
+ /**
735
+ * Combine several pull adapters into the one adapter a collection replicates with.
736
+ *
737
+ * Run one replication per collection: two replications on one collection each
738
+ * see the other's writes as local writes, so either can skip a pulled version.
739
+ * Give a collection several feeds (products and variants, say) through this.
740
+ *
741
+ * The checkpoint is `{ [key]: subCheckpoint }`; each sub-adapter sees only its
742
+ * own. `legacyKey` carries over an install's single-feed checkpoint: a stored
743
+ * checkpoint with none of the keys becomes that key's checkpoint. With no stored
744
+ * checkpoint at all, each sub-adapter with `pull.seedCheckpoint` starts from its seed.
745
+ *
746
+ * `options.batchSize` sets the combined pull page size; sub-adapters' own
747
+ * `pull.batchSize` is ignored.
748
+ * Pull only: a sub-adapter with `push` or `pull.stream$` throws here.
749
+ */
750
+ declare function combinePullAdapters<Doc>(adapters: Record<string, ReplicationAdapter<Doc, any>>, options?: {
751
+ legacyKey?: string;
752
+ batchSize?: number;
753
+ }): ReplicationAdapter<Doc, Record<string, any>>;
754
+
755
+ /**
756
+ * One queued correction, keyed by the local primary key: `key`, or `id`, its
757
+ * older name. `local` is the till's copy, if it has one; `remote` is whatever
758
+ * the connector needs to refetch it.
759
+ */
760
+ type ReconcileFeedEntry<Doc = any> = ({
761
+ key: string;
762
+ id?: undefined;
763
+ } | {
764
+ id: string;
765
+ key?: undefined;
766
+ }) & {
767
+ local?: Doc;
768
+ remote?: unknown;
769
+ /**
770
+ * Re-deliver if the product still exists; never tombstone if missing (the
771
+ * fingerprint path, ADR-060). Only the id reconcile, with its mass-delete
772
+ * brake, enqueues deletable entries.
773
+ */
774
+ refreshOnly?: boolean;
775
+ /** Proven gone (the catalogue reconcile, #248): written as deleted from `local`, without a fetch. */
776
+ tombstone?: boolean;
777
+ };
778
+ /** What a keyed feed's `fetchByIds` receives for each entry. */
779
+ interface ReconcileFetchEntry<Doc = any> {
780
+ key: string;
781
+ local?: Doc;
782
+ remote?: unknown;
783
+ }
784
+ interface CreateReconcileFeedOptions<Doc = any> {
785
+ /** The current projected documents for the ids that still exist, matched back by `doc.id`. */
786
+ fetchByIds(ids: string[], context: SyncContext): Promise<Doc[]>;
787
+ }
788
+ /** A feed keyed by the primary key where that is not `doc.id` (WooCommerce's uuid, #248). */
789
+ interface KeyedReconcileFeedOptions<Doc = any> {
790
+ /** The local primary key of a fetched document; fetched documents are matched to entries by it. */
791
+ key(doc: Doc): string;
792
+ /** The current documents for the entries that still exist. A document may carry `_deleted: true` (an unpublished product). */
793
+ fetchByIds(entries: Array<ReconcileFetchEntry<Doc>>, context: SyncContext): Promise<Doc[]>;
794
+ }
795
+ interface ReconcileFeed<Doc = any> {
796
+ /** Pull-only; meant as the last key of `combinePullAdapters` so its fetch wins duplicates. */
797
+ adapter: ReplicationAdapter<Doc, {
798
+ n: number;
799
+ }>;
800
+ /**
801
+ * Add entries to the in-memory queue, de-duplicated by key, last entry wins.
802
+ * `refreshOnly` is merged separately: it is true only when every merged
803
+ * entry for that key was `refreshOnly`, so a deletable entry (the id
804
+ * reconcile's) is never downgraded by a later refresh-only one.
805
+ */
806
+ enqueue(entries: Array<ReconcileFeedEntry<Doc>>): void;
807
+ }
808
+ /**
809
+ * Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060).
810
+ * Two overloads: with `key`, `fetchByIds` receives the entries and fetched documents are matched by
811
+ * `key(doc)`; without it, `fetchByIds` receives bare ids and documents are matched by `doc.id`.
812
+ */
813
+ declare function createReconcileFeed<Doc = any>(options: KeyedReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
814
+ declare function createReconcileFeed<Doc = any>(options: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
815
+
218
816
  interface ConnectorProviderProps {
219
817
  connector: TallyConnector;
818
+ /**
819
+ * Store-level facts passed to traits that need them, such as the store
820
+ * currency for backends whose product documents omit it.
821
+ */
822
+ traitContext?: TraitContext;
823
+ /** Reconciled stock (ADR-060), e.g. from `stockOverlay$` in `@tallyui/pos`. */
824
+ stockOverlay?: ReadonlyMap<string, unknown>;
825
+ /** ISO time the overlay was last confirmed, e.g. from `stockOverlayAsOf$`. */
826
+ stockOverlayAsOf?: string;
220
827
  children: ReactNode;
221
828
  }
222
- declare function ConnectorProvider({ connector, children }: ConnectorProviderProps): react_jsx_runtime.JSX.Element;
829
+ declare function ConnectorProvider({ connector, traitContext, stockOverlay, stockOverlayAsOf, children }: ConnectorProviderProps): react_jsx_runtime.JSX.Element;
223
830
  /**
224
831
  * Access the active connector. Throws if used outside a ConnectorProvider.
225
832
  */
@@ -228,10 +835,31 @@ declare function useConnector(): TallyConnector;
228
835
  * Convenience hook: grab just the product traits from the active connector.
229
836
  */
230
837
  declare function useProductTraits(): ProductTraits<any>;
838
+ /**
839
+ * The store-level TraitContext given to the nearest ConnectorProvider.
840
+ */
841
+ declare function useTraitContext(): TraitContext;
842
+ /**
843
+ * The product's stock, from the reconciled overlay given to the nearest
844
+ * ConnectorProvider where it has an entry, otherwise from the document.
845
+ * `asOf` is set only when an overlay is given and the connector reconciles stock.
846
+ */
847
+ declare function useProductStock(doc: any): StockLevel & {
848
+ asOf?: string;
849
+ };
850
+ /**
851
+ * The products with the nearest ConnectorProvider's reconciled stock overlay merged in (copies only; the
852
+ * documents are never changed), for components that derive stock from documents themselves. Returns
853
+ * `products` itself, unchanged, when there is no provider, no overlay, or the connector has no stock
854
+ * reconcile adapter, and the same array while its inputs are unchanged.
855
+ */
856
+ declare function useStockOverlaid<Doc>(products: readonly Doc[]): readonly Doc[];
857
+ /** The reconciled stock overlay's confirmed-as-of time from the nearest ConnectorProvider, or undefined without one or when its connector has no `reconcile.stock` (the same gate `useProductStock` uses). */
858
+ declare function useStockOverlayAsOf(): string | undefined;
231
859
  /**
232
860
  * Convenience hook: grab just the customer traits from the active connector.
233
861
  * Returns undefined if the connector doesn't implement customer traits.
234
862
  */
235
863
  declare function useCustomerTraits(): CustomerTraits<any> | undefined;
236
864
 
237
- export { type AuthField, type CollectionSync, type ConnectorAuth, ConnectorProvider, type ConnectorProviderProps, type ConnectorSchemas, type ConnectorTraits, type CustomerTraits, type ProductTraits, type RemoteIdEntry, type ReplicationAdapter, type SyncContext, type TallyConnector, useConnector, useCustomerTraits, useProductTraits };
865
+ export { type AuthField, type CatalogueReconcileAdapter, type CatalogueReconcileEntry, type CollectionSync, CommandWarning, type ConnectorAuth, ConnectorProvider, type ConnectorProviderProps, type ConnectorSchemas, type ConnectorTraits, ConnectorUnauthorizedError, type Customer, type CustomerInput, CustomerServiceError, type CustomerTraits, type ErrorKind, type FingerprintReconcileAdapter, type IdReconcileAdapter, type KeyedReconcileFeedOptions, type Money, type ProductPrice, type ProductTraits, type ReconcileFeed, type ReconcileFeedEntry, type ReconcileFetchEntry, type RemoteIdEntry, type ReplicationAdapter, type ResolvedPrice, STOCK_LEVELS_LAST_PASS, type ServerCapabilities, SignInError, type SignInErrorCode, type SignInResult, type StockLevel, type StockReconcileAdapter, type StockStatus, type StoreSettings, type StoreSettingsChoice, type StoreSettingsChoices, StoreSettingsError, type StoreSettingsErrorCode, type SyncContext, type SyncNotice, type TallyConnector, type TaxRounding, type TraitContext, type VariantSummary, combinePullAdapters, compareIds, createReconcileFeed, currencySymbol, customerTraits, errorKind, findVariantByCode, formatMoney, getProductStock, isRxdbRemoteVersionMismatch, knownWarnings, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, parseInfoCapabilities, parseTaxRounding, resolveCapabilities, resolvePrice, resolvePriceRange, useConnector, useCustomerTraits, useProductStock, useProductTraits, useStockOverlaid, useStockOverlayAsOf, useTraitContext, withStockOverlay };