@tallyui/core 0.2.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/index.d.ts +540 -8
- package/dist/index.js +294 -4
- package/dist/rxdb/index.d.ts +41 -0
- package/dist/rxdb/index.js +26 -0
- package/package.json +27 -3
- package/src/commands.ts +32 -0
- package/src/context/connector-context.tsx +49 -4
- package/src/index.ts +41 -0
- package/src/money.ts +142 -0
- package/src/replication/combine.ts +73 -0
- package/src/replication/reconcile-feed.ts +79 -0
- package/src/rxdb/index.ts +4 -0
- package/src/rxdb/read-fresh.ts +36 -0
- package/src/rxdb/watch-fresh.ts +19 -0
- package/src/sign-in.ts +21 -0
- package/src/stock-overlay.ts +35 -0
- package/src/store-settings.ts +29 -0
- package/src/types/commands.ts +107 -0
- package/src/types/connector.ts +70 -0
- package/src/types/index.ts +16 -1
- package/src/types/money.ts +33 -0
- package/src/types/reconcile.ts +43 -0
- package/src/types/replication.ts +6 -0
- package/src/types/stock.ts +18 -0
- package/src/types/store-settings.ts +23 -0
- package/src/types/traits/product.ts +55 -6
- package/src/utils/compare-ids.ts +16 -0
- package/src/variants.ts +14 -0
- package/src/__tests__/connector-context.test.tsx +0 -100
- package/src/types/replication.test-d.ts +0 -20
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Paul Kilmurray and TallyUI contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,81 @@ import { Observable } from 'rxjs';
|
|
|
3
3
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
4
|
import { ReactNode } from 'react';
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* A monetary amount in integer minor units (cents for EUR/USD, yen for JPY)
|
|
8
|
+
* with its ISO 4217 currency code. Integers keep arithmetic exact, and the
|
|
9
|
+
* code travels with the amount so nothing assumes a store-wide currency.
|
|
10
|
+
*/
|
|
11
|
+
interface Money {
|
|
12
|
+
/** Integer amount in the currency's minor unit, e.g. 1250 for €12.50. */
|
|
13
|
+
amount: number;
|
|
14
|
+
/** Upper-case ISO 4217 code, e.g. 'EUR'. 'XXX' when the backend gives none. */
|
|
15
|
+
currency: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* One entry in a product's price list.
|
|
19
|
+
*
|
|
20
|
+
* `base` is the everyday price. `sale` is a temporary reduction that replaces
|
|
21
|
+
* the base price in the same currency while it applies. Backends express
|
|
22
|
+
* sales differently (WooCommerce sale_price, Medusa sale price lists, Shopify
|
|
23
|
+
* compare_at_price) and each connector maps its own form into these entries,
|
|
24
|
+
* so components never need regular/sale/on-sale flags.
|
|
25
|
+
*/
|
|
26
|
+
interface ProductPrice extends Money {
|
|
27
|
+
kind: 'base' | 'sale';
|
|
28
|
+
/** Set when the backend says so for this price; it wins over the store-level `pricesIncludeTax`. Undefined: use the store-level setting. */
|
|
29
|
+
taxInclusive?: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** The price to charge, and the price it replaces when a sale applies; each keeps its source's `taxInclusive` when set. */
|
|
32
|
+
interface ResolvedPrice {
|
|
33
|
+
current: Money & {
|
|
34
|
+
taxInclusive?: boolean;
|
|
35
|
+
};
|
|
36
|
+
/** Set only when a sale price applies: the base price it replaces. */
|
|
37
|
+
was?: Money & {
|
|
38
|
+
taxInclusive?: boolean;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Backend-neutral stock state.
|
|
44
|
+
*
|
|
45
|
+
* - `in_stock`: sellable now. `quantity` is set when the backend tracks it.
|
|
46
|
+
* - `out_of_stock`: tracked and none left; not sellable.
|
|
47
|
+
* - `backorder`: none left but the backend accepts orders anyway.
|
|
48
|
+
* - `unknown`: the backend did not say.
|
|
49
|
+
*
|
|
50
|
+
* `quantity` is undefined when stock is not tracked, which is different from
|
|
51
|
+
* a tracked quantity of 0.
|
|
52
|
+
*/
|
|
53
|
+
type StockStatus = 'in_stock' | 'out_of_stock' | 'backorder' | 'unknown';
|
|
54
|
+
interface StockLevel {
|
|
55
|
+
status: StockStatus;
|
|
56
|
+
/** Units on hand, when tracked. May be negative on backorder. */
|
|
57
|
+
quantity?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One purchasable variant of a product, in backend-neutral terms. */
|
|
61
|
+
interface VariantSummary {
|
|
62
|
+
/** Backend variant id; the id sent in order lines. */
|
|
63
|
+
id: string;
|
|
64
|
+
/** Variant label, e.g. 'S / White'; undefined when the backend has none. */
|
|
65
|
+
title?: string;
|
|
66
|
+
sku?: string;
|
|
67
|
+
/** First non-empty of the backend's barcode fields. */
|
|
68
|
+
barcode?: string;
|
|
69
|
+
prices: ProductPrice[];
|
|
70
|
+
stock: StockLevel;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Store-level facts a connector may need to interpret a raw document, for
|
|
74
|
+
* backends whose documents omit them (WooCommerce product prices carry no
|
|
75
|
+
* currency).
|
|
76
|
+
*/
|
|
77
|
+
interface TraitContext {
|
|
78
|
+
/** The store's ISO 4217 currency code. */
|
|
79
|
+
currency?: string;
|
|
80
|
+
}
|
|
6
81
|
/**
|
|
7
82
|
* Product traits — the stable interface that UI components program against.
|
|
8
83
|
*
|
|
@@ -12,19 +87,33 @@ import { ReactNode } from 'react';
|
|
|
12
87
|
* Vendure, Shopify, etc.
|
|
13
88
|
*
|
|
14
89
|
* The generic `Doc` type is the connector's raw RxDB document type.
|
|
90
|
+
*
|
|
91
|
+
* Price and stock are read through the backend-neutral `getPrices` and
|
|
92
|
+
* `getStock`. The older string-price and WooCommerce-style stock accessors
|
|
93
|
+
* remain for existing consumers and are deprecated.
|
|
15
94
|
*/
|
|
16
95
|
interface ProductTraits<Doc = any> {
|
|
17
96
|
/** Product display name */
|
|
18
97
|
getName: (doc: Doc) => string;
|
|
19
98
|
/** SKU / stock keeping unit */
|
|
20
99
|
getSku: (doc: Doc) => string | undefined;
|
|
21
|
-
/**
|
|
100
|
+
/**
|
|
101
|
+
* The product's price list: base prices, plus sale prices while a sale
|
|
102
|
+
* applies, per currency. Pass the list to `resolvePrice` for the price to
|
|
103
|
+
* charge. For variable products this describes the default variant.
|
|
104
|
+
*/
|
|
105
|
+
getPrices: (doc: Doc, context?: TraitContext) => ProductPrice[];
|
|
106
|
+
/** Stock state of the whole product across its variants; `quantity` is the total on hand when every variant is tracked, else undefined. */
|
|
107
|
+
getStock: (doc: Doc) => StockLevel;
|
|
108
|
+
/** All purchasable variants, in id order (connectors store variants sorted by id). Optional: connectors without variant support omit it. */
|
|
109
|
+
getVariants?: (doc: Doc, context?: TraitContext) => VariantSummary[];
|
|
110
|
+
/** @deprecated Use `getPrices` with `resolvePrice`. */
|
|
22
111
|
getPrice: (doc: Doc) => string | undefined;
|
|
23
|
-
/** Regular (non-sale) price */
|
|
112
|
+
/** Regular (non-sale) price. @deprecated Use `getPrices` with `resolvePrice`. */
|
|
24
113
|
getRegularPrice: (doc: Doc) => string | undefined;
|
|
25
|
-
/** Sale price, if on sale */
|
|
114
|
+
/** Sale price, if on sale. @deprecated Use `getPrices` with `resolvePrice`. */
|
|
26
115
|
getSalePrice: (doc: Doc) => string | undefined;
|
|
27
|
-
/** Whether the product is currently on sale */
|
|
116
|
+
/** Whether the product is currently on sale. @deprecated Use `getPrices` with `resolvePrice`. */
|
|
28
117
|
isOnSale: (doc: Doc) => boolean;
|
|
29
118
|
/** Primary image URL */
|
|
30
119
|
getImageUrl: (doc: Doc) => string | undefined;
|
|
@@ -32,12 +121,16 @@ interface ProductTraits<Doc = any> {
|
|
|
32
121
|
getImageUrls: (doc: Doc) => string[];
|
|
33
122
|
/** Short description / excerpt */
|
|
34
123
|
getDescription: (doc: Doc) => string | undefined;
|
|
35
|
-
/** Stock status */
|
|
124
|
+
/** Stock status. @deprecated Use `getStock`. */
|
|
36
125
|
getStockStatus: (doc: Doc) => 'instock' | 'outofstock' | 'onbackorder' | 'unknown';
|
|
37
|
-
/** Stock quantity (null if not tracked) */
|
|
126
|
+
/** Stock quantity (null if not tracked). @deprecated Use `getStock`. */
|
|
38
127
|
getStockQuantity: (doc: Doc) => number | null;
|
|
39
128
|
/** Whether this product has variants/variations */
|
|
40
129
|
hasVariants: (doc: Doc) => boolean;
|
|
130
|
+
/** Whether the product may be sold at the register now: published/active, not a draft, archived or disabled. */
|
|
131
|
+
isSellable: (doc: Doc) => boolean;
|
|
132
|
+
/** Number of purchasable variants; 1 for a simple product. */
|
|
133
|
+
getVariantCount: (doc: Doc) => number;
|
|
41
134
|
/** Product type (simple, variable, etc. — connector-specific but useful for UI hints) */
|
|
42
135
|
getType: (doc: Doc) => string;
|
|
43
136
|
/** Barcode / UPC / EAN */
|
|
@@ -87,6 +180,11 @@ interface ReplicationAdapter<RxDocType, CheckpointType = any> {
|
|
|
87
180
|
}>;
|
|
88
181
|
checkpoint: CheckpointType;
|
|
89
182
|
}>;
|
|
183
|
+
/**
|
|
184
|
+
* Fresh install only: the checkpoint this feed starts from instead of a full first pass,
|
|
185
|
+
* read before any feed runs (combinePullAdapters). Absent: a full first pass, as today.
|
|
186
|
+
*/
|
|
187
|
+
seedCheckpoint?: (context: SyncContext) => Promise<CheckpointType>;
|
|
90
188
|
/**
|
|
91
189
|
* Optional real-time event stream.
|
|
92
190
|
* Emit { documents, checkpoint } for live updates,
|
|
@@ -108,6 +206,82 @@ interface ReplicationAdapter<RxDocType, CheckpointType = any> {
|
|
|
108
206
|
};
|
|
109
207
|
}
|
|
110
208
|
|
|
209
|
+
/**
|
|
210
|
+
* Re-reads stock from the backend, because replication misses stock changes
|
|
211
|
+
* that bump no product timestamp (ADR-060). The runner stores `fetchPages`
|
|
212
|
+
* output in the non-replicated `stock_levels` collection; readers merge it
|
|
213
|
+
* into a read-only view of each product with `overlay`. Nothing is written
|
|
214
|
+
* into the replicated products.
|
|
215
|
+
*/
|
|
216
|
+
interface StockReconcileAdapter<Doc = any> {
|
|
217
|
+
/** Current stock, one backend request per page, keyed as the connector chooses (variant, inventory item). */
|
|
218
|
+
fetchPages(context: SyncContext): AsyncIterable<Map<string, unknown>>;
|
|
219
|
+
/**
|
|
220
|
+
* Pure: the fields of `doc` that `stock` changes, or undefined when nothing
|
|
221
|
+
* differs. Keys absent from `stock` are left alone. The result is merged
|
|
222
|
+
* into a read-only view of the document and never written.
|
|
223
|
+
*/
|
|
224
|
+
overlay(doc: Doc, stock: Map<string, unknown>): Partial<Doc> | undefined;
|
|
225
|
+
}
|
|
226
|
+
/** 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. */
|
|
227
|
+
interface IdReconcileAdapter<Doc = any> {
|
|
228
|
+
/** Every live product with its live variant ids, one backend request per page. */
|
|
229
|
+
fetchPages(context: SyncContext): AsyncIterable<Array<{
|
|
230
|
+
id: string;
|
|
231
|
+
variantIds: string[];
|
|
232
|
+
}>>;
|
|
233
|
+
/** The variant ids a local product document lists. */
|
|
234
|
+
variantIds(doc: Doc): string[];
|
|
235
|
+
/** Hand local documents that disagree with the backend to the collection's pull (see createReconcileFeed). */
|
|
236
|
+
enqueue(entries: Array<{
|
|
237
|
+
id: string;
|
|
238
|
+
local: Doc;
|
|
239
|
+
}>): void;
|
|
240
|
+
}
|
|
241
|
+
/** Re-delivers products whose remote fingerprint differs from the local one (ADR-060). */
|
|
242
|
+
interface FingerprintReconcileAdapter<Doc = any> {
|
|
243
|
+
/** Remote fingerprints by product id, one backend request per page. Products the backend doesn't report are left alone. */
|
|
244
|
+
fetchPages(context: SyncContext): AsyncIterable<Map<string, string>>;
|
|
245
|
+
/** The same fingerprint computed from a local product document. */
|
|
246
|
+
fingerprint(doc: Doc): string;
|
|
247
|
+
/**
|
|
248
|
+
* Hands products to the collection's pull (the reconcile feed). `refreshOnly`
|
|
249
|
+
* marks an entry so a missing product is skipped, never tombstoned: only the
|
|
250
|
+
* id reconcile, with its mass-delete brake, may delete.
|
|
251
|
+
*/
|
|
252
|
+
enqueue(entries: Array<{
|
|
253
|
+
id: string;
|
|
254
|
+
local: Doc;
|
|
255
|
+
refreshOnly?: boolean;
|
|
256
|
+
}>): void;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** What the POS needs from the store's own settings (TV4). Read once after sign-in; the app feeds all three consumers from it. */
|
|
260
|
+
interface StoreSettings {
|
|
261
|
+
/** ISO 4217, upper case (the currency prices are sold in). */
|
|
262
|
+
currency: string;
|
|
263
|
+
/** Whether the store's catalogue prices include tax. It feeds both the connector's traits and the POS TaxProvider, so the two cannot disagree. */
|
|
264
|
+
pricesIncludeTax: boolean;
|
|
265
|
+
/** 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. */
|
|
266
|
+
taxRatesPpm: {
|
|
267
|
+
default: number;
|
|
268
|
+
[taxClass: string]: number;
|
|
269
|
+
};
|
|
270
|
+
/** 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. */
|
|
271
|
+
pricingContext?: Record<string, string>;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Picks among several regions, countries or sales channels when the store has more than one.
|
|
275
|
+
* The app persists the choice per store, in its own settings, so it is asked once. A stored
|
|
276
|
+
* choice that no longer resolves (for example, the region was deleted) raises `choice_required`
|
|
277
|
+
* again instead of failing. Backends without the concept ignore a field.
|
|
278
|
+
*/
|
|
279
|
+
interface StoreSettingsChoice {
|
|
280
|
+
region?: string;
|
|
281
|
+
country?: string;
|
|
282
|
+
channel?: string;
|
|
283
|
+
}
|
|
284
|
+
|
|
111
285
|
/**
|
|
112
286
|
* Authentication configuration for a connector.
|
|
113
287
|
* Each API has wildly different auth — JWT, API keys, OAuth, etc.
|
|
@@ -122,7 +296,38 @@ interface ConnectorAuth {
|
|
|
122
296
|
getHeaders: (credentials: Record<string, string>) => Record<string, string>;
|
|
123
297
|
/** Optional: validate that credentials work (e.g., test API call) */
|
|
124
298
|
validate?: (credentials: Record<string, string>) => Promise<boolean>;
|
|
299
|
+
/**
|
|
300
|
+
* Exchanges a user's email and password for a credential (token) to store and pass back to getHeaders as `token`.
|
|
301
|
+
* Rejects with a `SignInError`: `invalid_credentials`, `unsupported` or `failed`.
|
|
302
|
+
*/
|
|
303
|
+
signIn?: (baseUrl: string, login: {
|
|
304
|
+
email: string;
|
|
305
|
+
password: string;
|
|
306
|
+
}, init?: {
|
|
307
|
+
signal?: AbortSignal;
|
|
308
|
+
fetch?: typeof fetch;
|
|
309
|
+
}) => Promise<SignInResult>;
|
|
310
|
+
}
|
|
311
|
+
interface SignInResult {
|
|
312
|
+
token: string;
|
|
313
|
+
/** ISO 8601, when the backend says when the token expires */
|
|
314
|
+
expiresAt?: string;
|
|
315
|
+
/** The store's contract capabilities (ADR-062), when the read was conclusive. */
|
|
316
|
+
capabilities?: ServerCapabilities;
|
|
317
|
+
}
|
|
318
|
+
/** The highest `order.create` contract version a store's server currently accepts (ADR-062). */
|
|
319
|
+
interface ServerCapabilities {
|
|
320
|
+
orderCreate: number;
|
|
125
321
|
}
|
|
322
|
+
/**
|
|
323
|
+
* Resolves the capabilities to act on: a definitive fresh read always wins,
|
|
324
|
+
* even a downgrade to 1; an inconclusive fresh read (`undefined`) keeps the
|
|
325
|
+
* last known value. The app persists `stored` with its session, the way it
|
|
326
|
+
* persists the store-settings choice, and copies the result into
|
|
327
|
+
* `SyncContext.capabilities`. `finalizeOrder` treats `undefined` as 1, which
|
|
328
|
+
* only happens when the value has never been read (ADR-062).
|
|
329
|
+
*/
|
|
330
|
+
declare function resolveCapabilities(fresh: ServerCapabilities | undefined, stored: ServerCapabilities | undefined): ServerCapabilities | undefined;
|
|
126
331
|
interface AuthField {
|
|
127
332
|
key: string;
|
|
128
333
|
label: string;
|
|
@@ -164,10 +369,19 @@ interface SyncContext {
|
|
|
164
369
|
headers: Record<string, string>;
|
|
165
370
|
/** Optional abort signal */
|
|
166
371
|
signal?: AbortSignal;
|
|
372
|
+
/** From `storeSettings().pricingContext`; opaque to the app; the connector prices documents with it. Never logged. */
|
|
373
|
+
pricingContext?: Record<string, string>;
|
|
374
|
+
/** The store's contract capabilities (ADR-062), copied from the sign-in result. */
|
|
375
|
+
capabilities?: ServerCapabilities;
|
|
167
376
|
}
|
|
168
377
|
/**
|
|
169
378
|
* Schema definitions for a connector.
|
|
170
379
|
* Each connector provides its own RxDB schemas that mirror its API shape.
|
|
380
|
+
*
|
|
381
|
+
* Each describes a server-owned, pull-replicated collection (ADR-060), so its
|
|
382
|
+
* versions never transform documents: a version bump drops and resyncs.
|
|
383
|
+
* `createTallyDatabase` drops the old documents, and `startReplication` resets
|
|
384
|
+
* the checkpoint, so the first sync after the bump downloads the collection again.
|
|
171
385
|
*/
|
|
172
386
|
interface ConnectorSchemas {
|
|
173
387
|
products: RxJsonSchema<any>;
|
|
@@ -213,13 +427,319 @@ interface TallyConnector {
|
|
|
213
427
|
products?: ReplicationAdapter<any>;
|
|
214
428
|
[key: string]: ReplicationAdapter<any> | undefined;
|
|
215
429
|
};
|
|
430
|
+
/** Periodic re-reads of state that replication misses (ADR-060) */
|
|
431
|
+
reconcile?: {
|
|
432
|
+
stock?: StockReconcileAdapter;
|
|
433
|
+
ids?: IdReconcileAdapter;
|
|
434
|
+
prices?: FingerprintReconcileAdapter;
|
|
435
|
+
/** Prices the backend calculates for the sales context (price lists, sale dates), which change without a timestamp bump. */
|
|
436
|
+
calculatedPrices?: FingerprintReconcileAdapter;
|
|
437
|
+
};
|
|
438
|
+
/**
|
|
439
|
+
* Reads the store's own settings (TV4): currency, tax inclusivity, tax
|
|
440
|
+
* rates and a connector-specific pricing context. Read once after
|
|
441
|
+
* sign-in; the app feeds all three consumers from the result. Read-only,
|
|
442
|
+
* never writes to the store (ADR-048).
|
|
443
|
+
*/
|
|
444
|
+
storeSettings?: (context: SyncContext, choice?: StoreSettingsChoice) => Promise<StoreSettings>;
|
|
445
|
+
/**
|
|
446
|
+
* Re-reads the store's contract capabilities (ADR-062) for a session
|
|
447
|
+
* restored without signing in again — otherwise a restored session would
|
|
448
|
+
* block discounts until the cashier signed in again. `undefined` means
|
|
449
|
+
* the read was inconclusive (offline or a server error), not version 1;
|
|
450
|
+
* see `resolveCapabilities`.
|
|
451
|
+
*/
|
|
452
|
+
capabilities?: (context: SyncContext) => Promise<ServerCapabilities | undefined>;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Supported command operation. */
|
|
456
|
+
type CommandType = 'order.create';
|
|
457
|
+
/** Client command with a stable idempotency key and typed payload. */
|
|
458
|
+
interface CommandEnvelope<P = unknown> {
|
|
459
|
+
id: string;
|
|
460
|
+
type: CommandType;
|
|
461
|
+
/** 2 only when an `order.create` carries a discount (ADR-062); a discount-free payload stays 1, byte-identical. */
|
|
462
|
+
version: 1 | 2;
|
|
463
|
+
payload: P;
|
|
464
|
+
createdAt: string;
|
|
465
|
+
deviceId: string;
|
|
466
|
+
attempt: number;
|
|
467
|
+
}
|
|
468
|
+
/** Outcome of processing a command. */
|
|
469
|
+
type CommandStatus = 'applied' | 'duplicate' | 'rejected';
|
|
470
|
+
/** Server order identifiers and authoritative total. */
|
|
471
|
+
interface CommandServerRefs {
|
|
472
|
+
orderId: string;
|
|
473
|
+
displayId?: string;
|
|
474
|
+
totalMinor: number;
|
|
475
|
+
}
|
|
476
|
+
/** Non-fatal discrepancies reported while processing a command. */
|
|
477
|
+
type CommandWarning = {
|
|
478
|
+
code: 'total_mismatch';
|
|
479
|
+
expectedMinor: number;
|
|
480
|
+
serverMinor: number;
|
|
481
|
+
} | {
|
|
482
|
+
code: 'insufficient_stock';
|
|
483
|
+
variantId: string;
|
|
484
|
+
quantity: number;
|
|
485
|
+
};
|
|
486
|
+
/** Error reported when a command is rejected. */
|
|
487
|
+
interface CommandError {
|
|
488
|
+
code: string;
|
|
489
|
+
message: string;
|
|
490
|
+
}
|
|
491
|
+
/** Server result for a single command. */
|
|
492
|
+
interface CommandResult {
|
|
493
|
+
id: string;
|
|
494
|
+
status: CommandStatus;
|
|
495
|
+
serverRefs?: CommandServerRefs;
|
|
496
|
+
warnings?: CommandWarning[];
|
|
497
|
+
error?: CommandError;
|
|
216
498
|
}
|
|
499
|
+
/** Order line with client identity and price in minor units. */
|
|
500
|
+
interface OrderCreateLine {
|
|
501
|
+
clientLineId: string;
|
|
502
|
+
variantId: string;
|
|
503
|
+
title?: string;
|
|
504
|
+
quantity: number;
|
|
505
|
+
unitPriceMinor: number;
|
|
506
|
+
/**
|
|
507
|
+
* This line's own tax mode, when it differs from the order's `pricesIncludeTax`
|
|
508
|
+
* (a price that carries its own flag, D2c). Absent means the order's flag, so
|
|
509
|
+
* older clients and single-mode orders are unchanged.
|
|
510
|
+
*/
|
|
511
|
+
taxInclusive?: boolean;
|
|
512
|
+
/**
|
|
513
|
+
* Version 2 (ADR-062): this line's total discount, its own line discounts plus its allocated share of
|
|
514
|
+
* the order discount, in the line's own tax mode and integer minor units. The line is taxed on
|
|
515
|
+
* `unitPriceMinor × quantity − discountMinor`. Present only when above 0.
|
|
516
|
+
*/
|
|
517
|
+
discountMinor?: number;
|
|
518
|
+
}
|
|
519
|
+
/** Supported order payment method. */
|
|
520
|
+
type PaymentMethodKind = 'cash' | 'external';
|
|
521
|
+
/** Order payment with client identity and amounts in minor units. */
|
|
522
|
+
interface OrderCreatePayment {
|
|
523
|
+
clientPaymentId: string;
|
|
524
|
+
method: PaymentMethodKind;
|
|
525
|
+
amountMinor: number;
|
|
526
|
+
tenderedMinor?: number;
|
|
527
|
+
changeMinor?: number;
|
|
528
|
+
reference?: string;
|
|
529
|
+
}
|
|
530
|
+
/** Client order data submitted by an order.create command. */
|
|
531
|
+
interface OrderCreatePayload {
|
|
532
|
+
clientOrderId: string;
|
|
533
|
+
createdAt: string;
|
|
534
|
+
currency: string;
|
|
535
|
+
pricesIncludeTax: boolean;
|
|
536
|
+
lines: OrderCreateLine[];
|
|
537
|
+
subtotalMinor: number;
|
|
538
|
+
/** Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0. */
|
|
539
|
+
discountMinor?: number;
|
|
540
|
+
taxMinor: number;
|
|
541
|
+
totalMinor: number;
|
|
542
|
+
payments: OrderCreatePayment[];
|
|
543
|
+
customer?: {
|
|
544
|
+
email?: string;
|
|
545
|
+
} | null;
|
|
546
|
+
registerId?: string;
|
|
547
|
+
cashierRef?: string;
|
|
548
|
+
locationId?: string;
|
|
549
|
+
}
|
|
550
|
+
/** Batch of commands submitted to the server. */
|
|
551
|
+
interface CommandBatchRequest {
|
|
552
|
+
commands: CommandEnvelope[];
|
|
553
|
+
}
|
|
554
|
+
/** Results returned by the server for a command batch. */
|
|
555
|
+
interface CommandBatchResponse {
|
|
556
|
+
results: CommandResult[];
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Why `ConnectorAuth.signIn` failed:
|
|
561
|
+
* - `failed`: no response arrived (network error, DNS, TLS, refused);
|
|
562
|
+
* - `server_error`: a response arrived but was unusable;
|
|
563
|
+
* - `unsupported`: the backend needs a sign-in flow this connector can't do;
|
|
564
|
+
* - `invalid_credentials`: wrong email or password.
|
|
565
|
+
*/
|
|
566
|
+
type SignInErrorCode = 'invalid_credentials' | 'unsupported' | 'failed' | 'server_error';
|
|
567
|
+
/** The rejection from `ConnectorAuth.signIn`; the app picks its message from `code`. */
|
|
568
|
+
declare class SignInError extends Error {
|
|
569
|
+
readonly code: SignInErrorCode;
|
|
570
|
+
readonly status?: number;
|
|
571
|
+
constructor(code: SignInErrorCode, message: string, status?: number);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Why `TallyConnector.storeSettings` failed:
|
|
576
|
+
* - `choice_required`: the store has more than one region, country or
|
|
577
|
+
* channel and none is chosen yet (or the stored choice no longer
|
|
578
|
+
* resolves); `choices` says what the app can offer;
|
|
579
|
+
* - `failed`: the read could not complete (network error, non-OK response,
|
|
580
|
+
* a GraphQL/API error).
|
|
581
|
+
*/
|
|
582
|
+
type StoreSettingsErrorCode = 'choice_required' | 'failed';
|
|
583
|
+
/** What the app can offer the user when `StoreSettingsError.code` is `choice_required`. */
|
|
584
|
+
interface StoreSettingsChoices {
|
|
585
|
+
regions?: Array<{
|
|
586
|
+
id: string;
|
|
587
|
+
name: string;
|
|
588
|
+
}>;
|
|
589
|
+
countries?: string[];
|
|
590
|
+
channels?: Array<{
|
|
591
|
+
id: string;
|
|
592
|
+
name: string;
|
|
593
|
+
}>;
|
|
594
|
+
}
|
|
595
|
+
/** The rejection from `TallyConnector.storeSettings`; the app picks its message from `code`. */
|
|
596
|
+
declare class StoreSettingsError extends Error {
|
|
597
|
+
readonly code: StoreSettingsErrorCode;
|
|
598
|
+
readonly choices?: StoreSettingsChoices;
|
|
599
|
+
constructor(code: StoreSettingsErrorCode, message: string, choices?: StoreSettingsChoices);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** Path of the command endpoint, relative to the backend's base URL. */
|
|
603
|
+
declare const COMMANDS_PATH = "/tally/v1/commands";
|
|
604
|
+
/** Header carrying the protocol version. */
|
|
605
|
+
declare const PROTOCOL_HEADER = "X-Tally-Protocol";
|
|
606
|
+
/** Current protocol version. */
|
|
607
|
+
declare const PROTOCOL_VERSION = 1;
|
|
608
|
+
/** Maximum commands per batch request. */
|
|
609
|
+
declare const MAX_COMMANDS_PER_BATCH = 50;
|
|
610
|
+
/**
|
|
611
|
+
* True if `value` has the shape of a CommandBatchResponse: an object with a
|
|
612
|
+
* `results` array whose every entry has a string `id` and a `status` of
|
|
613
|
+
* 'applied' | 'duplicate' | 'rejected'. Optional fields are not deep-checked.
|
|
614
|
+
*/
|
|
615
|
+
declare function isCommandBatchResponse(value: unknown): value is CommandBatchResponse;
|
|
616
|
+
|
|
617
|
+
/** Number of minor-unit digits for an ISO 4217 code (2 for EUR, 0 for JPY). */
|
|
618
|
+
declare function minorUnitDigits(currency: string): number;
|
|
619
|
+
/** The currency's symbol for a plain-English label ('€' for EUR, '$' for USD), not a full amount. */
|
|
620
|
+
declare function currencySymbol(currency: string, locale?: string): string;
|
|
621
|
+
/**
|
|
622
|
+
* Converts a major-unit amount ('12.50', 12.5) into Money.
|
|
623
|
+
* Returns undefined for empty or non-numeric input.
|
|
624
|
+
*/
|
|
625
|
+
declare function moneyFromMajor(value: string | number | null | undefined, currency: string): Money | undefined;
|
|
626
|
+
/** Parses trimmed decimal text into safe integer minor units, without rounding. */
|
|
627
|
+
declare function moneyFromDecimalString(text: string, currency: string): Money | undefined;
|
|
628
|
+
/** Converts Money back to a major-unit number, e.g. for Intl formatting. */
|
|
629
|
+
declare function moneyToMajor(money: Money): number;
|
|
630
|
+
/**
|
|
631
|
+
* Formats Money for display with Intl, e.g. '€12.50' or '¥1,200'.
|
|
632
|
+
* Returns undefined for 'XXX' (currency unknown), so callers can fall back.
|
|
633
|
+
*/
|
|
634
|
+
declare function formatMoney(money: Money, locale?: string): string | undefined;
|
|
635
|
+
/**
|
|
636
|
+
* Picks the price to charge from a price list, in `currency` if given, else in
|
|
637
|
+
* the first currency listed. A sale entry wins over the base entry.
|
|
638
|
+
*/
|
|
639
|
+
declare function resolvePrice(prices: ProductPrice[], currency?: string): ResolvedPrice | undefined;
|
|
640
|
+
/**
|
|
641
|
+
* The lowest and highest price to charge across variants, in `currency` if
|
|
642
|
+
* given, else each variant's first currency; undefined when no variant
|
|
643
|
+
* resolves. Only amounts in the first resolved variant's currency are
|
|
644
|
+
* compared; a variant that resolves to another currency is skipped.
|
|
645
|
+
*/
|
|
646
|
+
declare function resolvePriceRange(variants: Array<{
|
|
647
|
+
prices: ProductPrice[];
|
|
648
|
+
}>, currency?: string): {
|
|
649
|
+
min: Money;
|
|
650
|
+
max: Money;
|
|
651
|
+
} | undefined;
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* The variant whose barcode or SKU equals `code`, compared after trimming
|
|
655
|
+
* both sides and ignoring case. A barcode match wins over a SKU match. When
|
|
656
|
+
* several variants match the same way, the first one wins. Returns undefined
|
|
657
|
+
* for an empty code or no match.
|
|
658
|
+
*/
|
|
659
|
+
declare function findVariantByCode(variants: VariantSummary[], code: string): VariantSummary | undefined;
|
|
660
|
+
|
|
661
|
+
/** 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. */
|
|
662
|
+
declare function compareIds(a: string | number, b: string | number): number;
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* Local document id, in the `stock_levels` collection, that holds the time of
|
|
666
|
+
* the last successful reconcile pass (`{ completedAt }`). Lives here so the
|
|
667
|
+
* runner in `@tallyui/database` and the readers in `@tallyui/pos` share it.
|
|
668
|
+
*/
|
|
669
|
+
declare const STOCK_LEVELS_LAST_PASS = "last-pass";
|
|
670
|
+
/**
|
|
671
|
+
* A read-only view of `doc` with reconciled stock merged in (ADR-060).
|
|
672
|
+
* Returns `doc` itself when there is nothing to merge; never mutates it.
|
|
673
|
+
*/
|
|
674
|
+
declare function withStockOverlay<Doc>(doc: Doc, adapter: StockReconcileAdapter<Doc> | undefined, overlay: Map<string, unknown> | undefined): Doc;
|
|
675
|
+
/**
|
|
676
|
+
* The product's stock, from the overlay where it has an entry for a variant
|
|
677
|
+
* or item, otherwise from the replicated document.
|
|
678
|
+
*/
|
|
679
|
+
declare function getProductStock<Doc>(doc: Doc, traits: ProductTraits<Doc>, adapter: StockReconcileAdapter<Doc> | undefined, overlay: Map<string, unknown> | undefined): StockLevel;
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* Combine several pull adapters into the one adapter a collection replicates with.
|
|
683
|
+
*
|
|
684
|
+
* Run one replication per collection: two replications on one collection each
|
|
685
|
+
* see the other's writes as local writes, so either can skip a pulled version.
|
|
686
|
+
* Give a collection several feeds (products and variants, say) through this.
|
|
687
|
+
*
|
|
688
|
+
* The checkpoint is `{ [key]: subCheckpoint }`; each sub-adapter sees only its
|
|
689
|
+
* own. `legacyKey` carries over an install's single-feed checkpoint: a stored
|
|
690
|
+
* checkpoint with none of the keys becomes that key's checkpoint. With no stored
|
|
691
|
+
* checkpoint at all, each sub-adapter with `pull.seedCheckpoint` starts from its seed.
|
|
692
|
+
*
|
|
693
|
+
* Pull only: a sub-adapter with `push` or `pull.stream$` throws here.
|
|
694
|
+
*/
|
|
695
|
+
declare function combinePullAdapters<Doc>(adapters: Record<string, ReplicationAdapter<Doc, any>>, options?: {
|
|
696
|
+
legacyKey?: string;
|
|
697
|
+
}): ReplicationAdapter<Doc, Record<string, any>>;
|
|
698
|
+
|
|
699
|
+
interface ReconcileFeedEntry<Doc = any> {
|
|
700
|
+
id: string;
|
|
701
|
+
local: Doc;
|
|
702
|
+
/**
|
|
703
|
+
* Re-deliver if the product still exists; never tombstone if missing (the
|
|
704
|
+
* fingerprint path, ADR-060). Only the id reconcile, with its mass-delete
|
|
705
|
+
* brake, enqueues deletable entries.
|
|
706
|
+
*/
|
|
707
|
+
refreshOnly?: boolean;
|
|
708
|
+
}
|
|
709
|
+
interface CreateReconcileFeedOptions<Doc = any> {
|
|
710
|
+
/** The current projected documents for the ids that still exist. */
|
|
711
|
+
fetchByIds(ids: string[], context: SyncContext): Promise<Doc[]>;
|
|
712
|
+
}
|
|
713
|
+
interface ReconcileFeed<Doc = any> {
|
|
714
|
+
/** Pull-only; meant as the last key of `combinePullAdapters` so its fetch wins duplicates. */
|
|
715
|
+
adapter: ReplicationAdapter<Doc, {
|
|
716
|
+
n: number;
|
|
717
|
+
}>;
|
|
718
|
+
/**
|
|
719
|
+
* Add entries to the in-memory queue, de-duplicated by id, last entry's
|
|
720
|
+
* `local` wins. `refreshOnly` is merged separately: it is true only when
|
|
721
|
+
* every merged entry for that id was `refreshOnly`, so a deletable entry
|
|
722
|
+
* (the id reconcile's) is never downgraded by a later refresh-only one.
|
|
723
|
+
*/
|
|
724
|
+
enqueue(entries: Array<ReconcileFeedEntry<Doc>>): void;
|
|
725
|
+
}
|
|
726
|
+
/** Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060). */
|
|
727
|
+
declare function createReconcileFeed<Doc = any>({ fetchByIds }: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
|
|
217
728
|
|
|
218
729
|
interface ConnectorProviderProps {
|
|
219
730
|
connector: TallyConnector;
|
|
731
|
+
/**
|
|
732
|
+
* Store-level facts passed to traits that need them, such as the store
|
|
733
|
+
* currency for backends whose product documents omit it.
|
|
734
|
+
*/
|
|
735
|
+
traitContext?: TraitContext;
|
|
736
|
+
/** Reconciled stock (ADR-060), e.g. from `stockOverlay$` in `@tallyui/pos`. */
|
|
737
|
+
stockOverlay?: ReadonlyMap<string, unknown>;
|
|
738
|
+
/** ISO time the overlay was last confirmed, e.g. from `stockOverlayAsOf$`. */
|
|
739
|
+
stockOverlayAsOf?: string;
|
|
220
740
|
children: ReactNode;
|
|
221
741
|
}
|
|
222
|
-
declare function ConnectorProvider({ connector, children }: ConnectorProviderProps): react_jsx_runtime.JSX.Element;
|
|
742
|
+
declare function ConnectorProvider({ connector, traitContext, stockOverlay, stockOverlayAsOf, children }: ConnectorProviderProps): react_jsx_runtime.JSX.Element;
|
|
223
743
|
/**
|
|
224
744
|
* Access the active connector. Throws if used outside a ConnectorProvider.
|
|
225
745
|
*/
|
|
@@ -228,10 +748,22 @@ declare function useConnector(): TallyConnector;
|
|
|
228
748
|
* Convenience hook: grab just the product traits from the active connector.
|
|
229
749
|
*/
|
|
230
750
|
declare function useProductTraits(): ProductTraits<any>;
|
|
751
|
+
/**
|
|
752
|
+
* The store-level TraitContext given to the nearest ConnectorProvider.
|
|
753
|
+
*/
|
|
754
|
+
declare function useTraitContext(): TraitContext;
|
|
755
|
+
/**
|
|
756
|
+
* The product's stock, from the reconciled overlay given to the nearest
|
|
757
|
+
* ConnectorProvider where it has an entry, otherwise from the document.
|
|
758
|
+
* `asOf` is set only when an overlay is given and the connector reconciles stock.
|
|
759
|
+
*/
|
|
760
|
+
declare function useProductStock(doc: any): StockLevel & {
|
|
761
|
+
asOf?: string;
|
|
762
|
+
};
|
|
231
763
|
/**
|
|
232
764
|
* Convenience hook: grab just the customer traits from the active connector.
|
|
233
765
|
* Returns undefined if the connector doesn't implement customer traits.
|
|
234
766
|
*/
|
|
235
767
|
declare function useCustomerTraits(): CustomerTraits<any> | undefined;
|
|
236
768
|
|
|
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 };
|
|
769
|
+
export { type AuthField, COMMANDS_PATH, type CollectionSync, type CommandBatchRequest, type CommandBatchResponse, type CommandEnvelope, type CommandError, type CommandResult, type CommandServerRefs, type CommandStatus, type CommandType, type CommandWarning, type ConnectorAuth, ConnectorProvider, type ConnectorProviderProps, type ConnectorSchemas, type ConnectorTraits, type CustomerTraits, type FingerprintReconcileAdapter, type IdReconcileAdapter, MAX_COMMANDS_PER_BATCH, type Money, type OrderCreateLine, type OrderCreatePayload, type OrderCreatePayment, PROTOCOL_HEADER, PROTOCOL_VERSION, type PaymentMethodKind, type ProductPrice, type ProductTraits, type ReconcileFeed, type ReconcileFeedEntry, 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 TallyConnector, type TraitContext, type VariantSummary, combinePullAdapters, compareIds, createReconcileFeed, currencySymbol, findVariantByCode, formatMoney, getProductStock, isCommandBatchResponse, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, resolveCapabilities, resolvePrice, resolvePriceRange, useConnector, useCustomerTraits, useProductStock, useProductTraits, useTraitContext, withStockOverlay };
|