@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/src/money.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import type { Money, ProductPrice, ResolvedPrice } from './types/money';
|
|
2
|
+
|
|
3
|
+
const digitsCache = new Map<string, number>();
|
|
4
|
+
|
|
5
|
+
/** Number of minor-unit digits for an ISO 4217 code (2 for EUR, 0 for JPY). */
|
|
6
|
+
export function minorUnitDigits(currency: string): number {
|
|
7
|
+
const code = currency.toUpperCase();
|
|
8
|
+
let digits = digitsCache.get(code);
|
|
9
|
+
if (digits === undefined) {
|
|
10
|
+
try {
|
|
11
|
+
digits = new Intl.NumberFormat('en', { style: 'currency', currency: code })
|
|
12
|
+
.resolvedOptions().maximumFractionDigits ?? 2;
|
|
13
|
+
} catch {
|
|
14
|
+
// Unknown or placeholder code (e.g. 'XXX'): assume cents.
|
|
15
|
+
digits = 2;
|
|
16
|
+
}
|
|
17
|
+
digitsCache.set(code, digits);
|
|
18
|
+
}
|
|
19
|
+
return digits;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const symbolCache = new Map<string, string>();
|
|
23
|
+
|
|
24
|
+
/** The currency's symbol for a plain-English label ('€' for EUR, '$' for USD), not a full amount. */
|
|
25
|
+
export function currencySymbol(currency: string, locale?: string): string {
|
|
26
|
+
const code = currency.toUpperCase();
|
|
27
|
+
const key = `${code}:${locale ?? ''}`;
|
|
28
|
+
let symbol = symbolCache.get(key);
|
|
29
|
+
if (symbol === undefined) {
|
|
30
|
+
try {
|
|
31
|
+
const part = new Intl.NumberFormat(locale, { style: 'currency', currency: code })
|
|
32
|
+
.formatToParts(0)
|
|
33
|
+
.find((p) => p.type === 'currency');
|
|
34
|
+
symbol = part?.value ?? code;
|
|
35
|
+
} catch {
|
|
36
|
+
symbol = code;
|
|
37
|
+
}
|
|
38
|
+
symbolCache.set(key, symbol);
|
|
39
|
+
}
|
|
40
|
+
return symbol;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Converts a major-unit amount ('12.50', 12.5) into Money.
|
|
45
|
+
* Returns undefined for empty or non-numeric input.
|
|
46
|
+
*/
|
|
47
|
+
export function moneyFromMajor(
|
|
48
|
+
value: string | number | null | undefined,
|
|
49
|
+
currency: string,
|
|
50
|
+
): Money | undefined {
|
|
51
|
+
if (value === null || value === undefined || value === '') return undefined;
|
|
52
|
+
const major = typeof value === 'number' ? value : Number(value);
|
|
53
|
+
if (!Number.isFinite(major)) return undefined;
|
|
54
|
+
const code = currency.toUpperCase();
|
|
55
|
+
return { amount: Math.round(major * 10 ** minorUnitDigits(code)), currency: code };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Parses trimmed decimal text into safe integer minor units, without rounding. */
|
|
59
|
+
export function moneyFromDecimalString(text: string, currency: string): Money | undefined {
|
|
60
|
+
const trimmed = text.trim();
|
|
61
|
+
if (!/^\d+(\.\d+)?$/.test(trimmed)) return undefined;
|
|
62
|
+
const code = currency.toUpperCase();
|
|
63
|
+
const digits = minorUnitDigits(code);
|
|
64
|
+
const [whole, fraction = ''] = trimmed.split('.');
|
|
65
|
+
if (fraction.length > digits) return undefined;
|
|
66
|
+
const amount = Number(whole) * 10 ** digits + Number(fraction.padEnd(digits, '0'));
|
|
67
|
+
return Number.isSafeInteger(amount) ? { amount, currency: code } : undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Converts Money back to a major-unit number, e.g. for Intl formatting. */
|
|
71
|
+
export function moneyToMajor(money: Money): number {
|
|
72
|
+
return money.amount / 10 ** minorUnitDigits(money.currency);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const formatters = new Map<string, Intl.NumberFormat>();
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Formats Money for display with Intl, e.g. '€12.50' or '¥1,200'.
|
|
79
|
+
* Returns undefined for 'XXX' (currency unknown), so callers can fall back.
|
|
80
|
+
*/
|
|
81
|
+
export function formatMoney(money: Money, locale?: string): string | undefined {
|
|
82
|
+
if (money.currency === 'XXX') return undefined;
|
|
83
|
+
const key = `${money.currency}:${locale ?? ''}`;
|
|
84
|
+
let formatter = formatters.get(key);
|
|
85
|
+
if (!formatter) {
|
|
86
|
+
try {
|
|
87
|
+
formatter = new Intl.NumberFormat(locale, { style: 'currency', currency: money.currency });
|
|
88
|
+
} catch {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
formatters.set(key, formatter);
|
|
92
|
+
}
|
|
93
|
+
return formatter.format(moneyToMajor(money));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Picks the price to charge from a price list, in `currency` if given, else in
|
|
98
|
+
* the first currency listed. A sale entry wins over the base entry.
|
|
99
|
+
*/
|
|
100
|
+
export function resolvePrice(
|
|
101
|
+
prices: ProductPrice[],
|
|
102
|
+
currency?: string,
|
|
103
|
+
): ResolvedPrice | undefined {
|
|
104
|
+
const code = (currency ?? prices[0]?.currency)?.toUpperCase();
|
|
105
|
+
const inCurrency = prices.filter((p) => p.currency === code);
|
|
106
|
+
const base = inCurrency.find((p) => p.kind === 'base');
|
|
107
|
+
const sale = inCurrency.find((p) => p.kind === 'sale');
|
|
108
|
+
const strip = (p: ProductPrice): ResolvedPrice['current'] => ({
|
|
109
|
+
amount: p.amount, currency: p.currency,
|
|
110
|
+
...(p.taxInclusive !== undefined ? { taxInclusive: p.taxInclusive } : {}),
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
if (sale && (!base || sale.amount < base.amount)) {
|
|
114
|
+
return { current: strip(sale), was: base ? strip(base) : undefined };
|
|
115
|
+
}
|
|
116
|
+
return base ? { current: strip(base) } : undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The lowest and highest price to charge across variants, in `currency` if
|
|
121
|
+
* given, else each variant's first currency; undefined when no variant
|
|
122
|
+
* resolves. Only amounts in the first resolved variant's currency are
|
|
123
|
+
* compared; a variant that resolves to another currency is skipped.
|
|
124
|
+
*/
|
|
125
|
+
export function resolvePriceRange(
|
|
126
|
+
variants: Array<{ prices: ProductPrice[] }>,
|
|
127
|
+
currency?: string,
|
|
128
|
+
): { min: Money; max: Money } | undefined {
|
|
129
|
+
let range: { min: Money; max: Money } | undefined;
|
|
130
|
+
for (const variant of variants) {
|
|
131
|
+
const resolved = resolvePrice(variant.prices, currency);
|
|
132
|
+
if (!resolved) continue;
|
|
133
|
+
const money = resolved.current;
|
|
134
|
+
if (!range) {
|
|
135
|
+
range = { min: money, max: money };
|
|
136
|
+
} else if (money.currency === range.min.currency) {
|
|
137
|
+
if (money.amount < range.min.amount) range.min = money;
|
|
138
|
+
if (money.amount > range.max.amount) range.max = money;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return range;
|
|
142
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { ReplicationAdapter } from '../types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Combine several pull adapters into the one adapter a collection replicates with.
|
|
5
|
+
*
|
|
6
|
+
* Run one replication per collection: two replications on one collection each
|
|
7
|
+
* see the other's writes as local writes, so either can skip a pulled version.
|
|
8
|
+
* Give a collection several feeds (products and variants, say) through this.
|
|
9
|
+
*
|
|
10
|
+
* The checkpoint is `{ [key]: subCheckpoint }`; each sub-adapter sees only its
|
|
11
|
+
* own. `legacyKey` carries over an install's single-feed checkpoint: a stored
|
|
12
|
+
* checkpoint with none of the keys becomes that key's checkpoint. With no stored
|
|
13
|
+
* checkpoint at all, each sub-adapter with `pull.seedCheckpoint` starts from its seed.
|
|
14
|
+
*
|
|
15
|
+
* Pull only: a sub-adapter with `push` or `pull.stream$` throws here.
|
|
16
|
+
*/
|
|
17
|
+
export function combinePullAdapters<Doc>(
|
|
18
|
+
adapters: Record<string, ReplicationAdapter<Doc, any>>,
|
|
19
|
+
options: { legacyKey?: string } = {},
|
|
20
|
+
): ReplicationAdapter<Doc, Record<string, any>> {
|
|
21
|
+
const keys = Object.keys(adapters);
|
|
22
|
+
for (const key of keys) {
|
|
23
|
+
if (adapters[key].push || adapters[key].pull.stream$) {
|
|
24
|
+
throw new Error(`combinePullAdapters: sub-adapter "${key}" has push or pull.stream$; only pull handlers can be combined.`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
pull: {
|
|
29
|
+
async handler(lastCheckpoint, batchSize, context) {
|
|
30
|
+
let previous = lastCheckpoint;
|
|
31
|
+
if (options.legacyKey && previous && typeof previous === 'object'
|
|
32
|
+
&& Object.keys(previous).length && !keys.some((key) => key in previous!)) {
|
|
33
|
+
previous = { [options.legacyKey]: previous };
|
|
34
|
+
}
|
|
35
|
+
if (!previous || !Object.keys(previous).length) {
|
|
36
|
+
// A true fresh install: no stored checkpoint, legacy or otherwise (an
|
|
37
|
+
// upgrade keeps its healing full pass). Seeding reads the marks before
|
|
38
|
+
// the first product page, so every edit after a mark is caught by that
|
|
39
|
+
// feed's inclusive `$gte`, and every edit before it is in the product
|
|
40
|
+
// feed's first pass, which fetches later. The seeds are saved with this
|
|
41
|
+
// call's combined checkpoint, which carries the product feed's first
|
|
42
|
+
// documents; with an empty catalogue nothing is lost either way.
|
|
43
|
+
const seeded: Record<string, any> = {};
|
|
44
|
+
for (const key of keys) {
|
|
45
|
+
const { pull } = adapters[key];
|
|
46
|
+
if (pull.seedCheckpoint) seeded[key] = await pull.seedCheckpoint(context);
|
|
47
|
+
}
|
|
48
|
+
previous = seeded;
|
|
49
|
+
}
|
|
50
|
+
const byId = new Map<unknown, Doc & { _deleted: boolean }>();
|
|
51
|
+
const checkpoint: Record<string, any> = {};
|
|
52
|
+
// Call sub-adapters strictly one after another, in key order: a
|
|
53
|
+
// correctness rule, not politeness. Each feed writes whole documents.
|
|
54
|
+
// Sequential calls with the last duplicate winning mean every document
|
|
55
|
+
// comes from the latest fetch of this call, and every fetch in the next
|
|
56
|
+
// call happens after this call's writes. Concurrent feeds could let a
|
|
57
|
+
// fetch made before another feed's newer write land after it and revert
|
|
58
|
+
// it, with neither checkpoint ever revisiting the document.
|
|
59
|
+
for (const key of keys) {
|
|
60
|
+
const result = await adapters[key].pull.handler(previous?.[key], batchSize, context);
|
|
61
|
+
for (const doc of result.documents) byId.set((doc as { id?: unknown }).id, doc);
|
|
62
|
+
// RxDB merges only the top level of the combined checkpoint, so merge
|
|
63
|
+
// each sub-checkpoint here as it would for a single adapter. Spread
|
|
64
|
+
// keeps a sub-adapter's explicit undefined (cleared pass state).
|
|
65
|
+
checkpoint[key] = { ...previous?.[key], ...result.checkpoint };
|
|
66
|
+
}
|
|
67
|
+
// Each sub-adapter returns unique ids, so one full sub-page makes the
|
|
68
|
+
// combined page full: RxDB keeps pulling while any sub-adapter has more.
|
|
69
|
+
return { documents: [...byId.values()], checkpoint };
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { SyncContext } from '../types/connector';
|
|
2
|
+
import type { ReplicationAdapter } from '../types/replication';
|
|
3
|
+
|
|
4
|
+
/** At most this many ids per `fetchByIds` call (ADR-060). */
|
|
5
|
+
const MAX_CHUNK = 1000;
|
|
6
|
+
|
|
7
|
+
export interface ReconcileFeedEntry<Doc = any> {
|
|
8
|
+
id: string;
|
|
9
|
+
local: Doc;
|
|
10
|
+
/**
|
|
11
|
+
* Re-deliver if the product still exists; never tombstone if missing (the
|
|
12
|
+
* fingerprint path, ADR-060). Only the id reconcile, with its mass-delete
|
|
13
|
+
* brake, enqueues deletable entries.
|
|
14
|
+
*/
|
|
15
|
+
refreshOnly?: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface CreateReconcileFeedOptions<Doc = any> {
|
|
18
|
+
/** The current projected documents for the ids that still exist. */
|
|
19
|
+
fetchByIds(ids: string[], context: SyncContext): Promise<Doc[]>;
|
|
20
|
+
}
|
|
21
|
+
export interface ReconcileFeed<Doc = any> {
|
|
22
|
+
/** Pull-only; meant as the last key of `combinePullAdapters` so its fetch wins duplicates. */
|
|
23
|
+
adapter: ReplicationAdapter<Doc, { n: number }>;
|
|
24
|
+
/**
|
|
25
|
+
* Add entries to the in-memory queue, de-duplicated by id, last entry's
|
|
26
|
+
* `local` wins. `refreshOnly` is merged separately: it is true only when
|
|
27
|
+
* every merged entry for that id was `refreshOnly`, so a deletable entry
|
|
28
|
+
* (the id reconcile's) is never downgraded by a later refresh-only one.
|
|
29
|
+
*/
|
|
30
|
+
enqueue(entries: Array<ReconcileFeedEntry<Doc>>): void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060). */
|
|
34
|
+
export function createReconcileFeed<Doc = any>({ fetchByIds }: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc> {
|
|
35
|
+
let queue = new Map<string, ReconcileFeedEntry<Doc>>();
|
|
36
|
+
// refreshOnly is true only if both the prior and the incoming entry were
|
|
37
|
+
// refreshOnly: a deletable entry is never downgraded by a later refresh-only one.
|
|
38
|
+
const merge = (prior: ReconcileFeedEntry<Doc> | undefined, e: ReconcileFeedEntry<Doc>): ReconcileFeedEntry<Doc> =>
|
|
39
|
+
({ ...e, refreshOnly: Boolean(e.refreshOnly) && (prior?.refreshOnly ?? true) });
|
|
40
|
+
const enqueue = (entries: Array<ReconcileFeedEntry<Doc>>) => {
|
|
41
|
+
for (const e of entries) queue.set(e.id, merge(queue.get(e.id), e));
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const adapter: ReplicationAdapter<Doc, { n: number }> = {
|
|
45
|
+
pull: {
|
|
46
|
+
async handler(lastCheckpoint, _batchSize, context) {
|
|
47
|
+
if (queue.size === 0) return { documents: [], checkpoint: lastCheckpoint ?? { n: 0 } };
|
|
48
|
+
// Drain the whole queue; anything enqueued while this pass runs lands in the fresh map.
|
|
49
|
+
const entries = [...queue.values()];
|
|
50
|
+
queue = new Map();
|
|
51
|
+
try {
|
|
52
|
+
const documents: Array<Doc & { _deleted: boolean }> = [];
|
|
53
|
+
// Fetch in chunks of at most MAX_CHUNK ids per call.
|
|
54
|
+
for (let i = 0; i < entries.length; i += MAX_CHUNK) {
|
|
55
|
+
const chunk = entries.slice(i, i + MAX_CHUNK);
|
|
56
|
+
const fetched = await fetchByIds(chunk.map((e) => e.id), context);
|
|
57
|
+
const byId = new Map(fetched.map((doc) => [(doc as { id?: unknown }).id, doc]));
|
|
58
|
+
for (const entry of chunk) {
|
|
59
|
+
const doc = byId.get(entry.id);
|
|
60
|
+
if (doc) documents.push({ ...doc, _deleted: false });
|
|
61
|
+
// A refreshOnly entry (the fingerprint path) is skipped, not tombstoned, when the
|
|
62
|
+
// product is missing: only the id reconcile's braked entries may delete (ADR-060).
|
|
63
|
+
else if (!entry.refreshOnly) documents.push({ ...entry.local, _deleted: true });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { documents, checkpoint: { n: (lastCheckpoint?.n ?? 0) + 1 } };
|
|
67
|
+
} catch (error) {
|
|
68
|
+
// Put entries back at the front; anything queued mid-fetch wins, merged
|
|
69
|
+
// by the same rule, so a failed fetch never downgrades a deletable entry. RxDB retries.
|
|
70
|
+
const restored = new Map(entries.map((e) => [e.id, e]));
|
|
71
|
+
for (const [id, e] of queue) restored.set(id, merge(restored.get(id), e));
|
|
72
|
+
queue = restored;
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
return { adapter, enqueue };
|
|
79
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// `@tallyui/core/rxdb`: the RxDB-dependent helpers, kept out of core's main entry so that entry
|
|
2
|
+
// stays free of rxdb and rxjs (optional peers, needed only by this subpath).
|
|
3
|
+
export { readFresh, countFresh } from './read-fresh';
|
|
4
|
+
export { watchFresh } from './watch-fresh';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { clone, type MangoQuery, type MangoQuerySelector, type RxCollection } from 'rxdb';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Reads straight from the collection's storage, past RxDB's cached query result.
|
|
5
|
+
*
|
|
6
|
+
* Why: in RxDB 16.21.1, a document written while a query's storage read is in flight (about one
|
|
7
|
+
* to three microtasks after it starts) is counted as seen but is missing from the result. RxDB
|
|
8
|
+
* caches that `RxQuery` per query string, so every later `find(sameQuery).exec()` or
|
|
9
|
+
* `count(sameQuery).exec()` returns the stale result, and a later matching write doesn't heal it.
|
|
10
|
+
* No subscription is needed. This is "bug 4" in TallyUI's local RxDB repro (the query-cache-stale
|
|
11
|
+
* script beside the migration checkpoint repro). For the order outbox it left a sale unsent until
|
|
12
|
+
* the app restarted.
|
|
13
|
+
*
|
|
14
|
+
* The prepared query is RxDB's own (`find(query).getPreparedQuery()`), so it already carries the
|
|
15
|
+
* `_deleted: false` filter, the query's sort and its limit. The read goes through the same wrapped
|
|
16
|
+
* storage instance an `RxQuery` uses, but skips `RxQuery` and `RxDocument`, so it is untested with
|
|
17
|
+
* key compression and field encryption; no TallyUI collection uses either.
|
|
18
|
+
*
|
|
19
|
+
* Returns plain, deep-cloned document data without RxDB's metadata. Use `findOne(id)` for an
|
|
20
|
+
* `RxDocument` to write through; its `incrementalModify` modifier sees the stored state.
|
|
21
|
+
*/
|
|
22
|
+
export async function readFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>): Promise<T[]> {
|
|
23
|
+
const { documents } = await collection.storageInstance.query(collection.find(query).getPreparedQuery());
|
|
24
|
+
return documents.map((document) => {
|
|
25
|
+
const { _meta, _rev, _attachments, _deleted, ...data } = clone(document);
|
|
26
|
+
return data as T;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Counts straight from the collection's storage, past RxDB's cached count (see `readFresh`).
|
|
32
|
+
* Unlike `count().exec()`, it doesn't refuse a storage that reports a slow count.
|
|
33
|
+
*/
|
|
34
|
+
export async function countFresh<T>(collection: RxCollection<T>, selector: MangoQuerySelector<T>): Promise<number> {
|
|
35
|
+
return (await collection.storageInstance.count(collection.count({ selector }).getPreparedQuery())).count;
|
|
36
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type Observable, startWith, switchMap } from 'rxjs';
|
|
2
|
+
import type { MangoQuery, RxCollection } from 'rxdb';
|
|
3
|
+
import { readFresh } from './read-fresh';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A live list a cached `RxQuery` can't leave stale (bug 4 in the local RxDB 16.21.1 repro,
|
|
7
|
+
* `readFresh`'s doc comment): a write during a query's storage read never reaches it, for good.
|
|
8
|
+
* `collection.eventBulks$` fires on every write and never touches that cache, so re-reading with
|
|
9
|
+
* `readFresh` on subscribe and again on every event bulk can't miss one; `switchMap` drops a read
|
|
10
|
+
* still in flight when a newer one starts. It is one event per storage change bulk, not per
|
|
11
|
+
* document (`collection.$`), so a `bulkInsert` of 100 documents costs one re-read, not 100. Still
|
|
12
|
+
* one storage read per write, so it's for a list a cashier would act on going stale, not every list.
|
|
13
|
+
*/
|
|
14
|
+
export function watchFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>): Observable<T[]> {
|
|
15
|
+
return collection.eventBulks$.pipe(
|
|
16
|
+
startWith(null),
|
|
17
|
+
switchMap(() => readFresh(collection, query)),
|
|
18
|
+
);
|
|
19
|
+
}
|
package/src/sign-in.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why `ConnectorAuth.signIn` failed:
|
|
3
|
+
* - `failed`: no response arrived (network error, DNS, TLS, refused);
|
|
4
|
+
* - `server_error`: a response arrived but was unusable;
|
|
5
|
+
* - `unsupported`: the backend needs a sign-in flow this connector can't do;
|
|
6
|
+
* - `invalid_credentials`: wrong email or password.
|
|
7
|
+
*/
|
|
8
|
+
export type SignInErrorCode = 'invalid_credentials' | 'unsupported' | 'failed' | 'server_error';
|
|
9
|
+
|
|
10
|
+
/** The rejection from `ConnectorAuth.signIn`; the app picks its message from `code`. */
|
|
11
|
+
export class SignInError extends Error {
|
|
12
|
+
readonly code: SignInErrorCode;
|
|
13
|
+
readonly status?: number;
|
|
14
|
+
|
|
15
|
+
constructor(code: SignInErrorCode, message: string, status?: number) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = 'SignInError';
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.status = status;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ProductTraits, StockLevel, StockReconcileAdapter } from './types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Local document id, in the `stock_levels` collection, that holds the time of
|
|
5
|
+
* the last successful reconcile pass (`{ completedAt }`). Lives here so the
|
|
6
|
+
* runner in `@tallyui/database` and the readers in `@tallyui/pos` share it.
|
|
7
|
+
*/
|
|
8
|
+
export const STOCK_LEVELS_LAST_PASS = 'last-pass';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A read-only view of `doc` with reconciled stock merged in (ADR-060).
|
|
12
|
+
* Returns `doc` itself when there is nothing to merge; never mutates it.
|
|
13
|
+
*/
|
|
14
|
+
export function withStockOverlay<Doc>(
|
|
15
|
+
doc: Doc,
|
|
16
|
+
adapter: StockReconcileAdapter<Doc> | undefined,
|
|
17
|
+
overlay: Map<string, unknown> | undefined,
|
|
18
|
+
): Doc {
|
|
19
|
+
if (!adapter || !overlay) return doc;
|
|
20
|
+
const fields = adapter.overlay(doc, overlay);
|
|
21
|
+
return fields ? { ...doc, ...fields } : doc;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The product's stock, from the overlay where it has an entry for a variant
|
|
26
|
+
* or item, otherwise from the replicated document.
|
|
27
|
+
*/
|
|
28
|
+
export function getProductStock<Doc>(
|
|
29
|
+
doc: Doc,
|
|
30
|
+
traits: ProductTraits<Doc>,
|
|
31
|
+
adapter: StockReconcileAdapter<Doc> | undefined,
|
|
32
|
+
overlay: Map<string, unknown> | undefined,
|
|
33
|
+
): StockLevel {
|
|
34
|
+
return traits.getStock(withStockOverlay(doc, adapter, overlay));
|
|
35
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why `TallyConnector.storeSettings` failed:
|
|
3
|
+
* - `choice_required`: the store has more than one region, country or
|
|
4
|
+
* channel and none is chosen yet (or the stored choice no longer
|
|
5
|
+
* resolves); `choices` says what the app can offer;
|
|
6
|
+
* - `failed`: the read could not complete (network error, non-OK response,
|
|
7
|
+
* a GraphQL/API error).
|
|
8
|
+
*/
|
|
9
|
+
export type StoreSettingsErrorCode = 'choice_required' | 'failed';
|
|
10
|
+
|
|
11
|
+
/** What the app can offer the user when `StoreSettingsError.code` is `choice_required`. */
|
|
12
|
+
export interface StoreSettingsChoices {
|
|
13
|
+
regions?: Array<{ id: string; name: string }>;
|
|
14
|
+
countries?: string[];
|
|
15
|
+
channels?: Array<{ id: string; name: string }>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The rejection from `TallyConnector.storeSettings`; the app picks its message from `code`. */
|
|
19
|
+
export class StoreSettingsError extends Error {
|
|
20
|
+
readonly code: StoreSettingsErrorCode;
|
|
21
|
+
readonly choices?: StoreSettingsChoices;
|
|
22
|
+
|
|
23
|
+
constructor(code: StoreSettingsErrorCode, message: string, choices?: StoreSettingsChoices) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = 'StoreSettingsError';
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.choices = choices;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/** Supported command operation. */
|
|
2
|
+
export type CommandType = 'order.create';
|
|
3
|
+
|
|
4
|
+
/** Client command with a stable idempotency key and typed payload. */
|
|
5
|
+
export interface CommandEnvelope<P = unknown> {
|
|
6
|
+
id: string; // UUIDv7, the idempotency key; never reused
|
|
7
|
+
type: CommandType;
|
|
8
|
+
/** 2 only when an `order.create` carries a discount (ADR-062); a discount-free payload stays 1, byte-identical. */
|
|
9
|
+
version: 1 | 2;
|
|
10
|
+
payload: P;
|
|
11
|
+
createdAt: string; // ISO 8601, client clock
|
|
12
|
+
deviceId: string;
|
|
13
|
+
attempt: number; // 1-based, informational
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Outcome of processing a command. */
|
|
17
|
+
export type CommandStatus = 'applied' | 'duplicate' | 'rejected';
|
|
18
|
+
|
|
19
|
+
/** Server order identifiers and authoritative total. */
|
|
20
|
+
export interface CommandServerRefs {
|
|
21
|
+
orderId: string;
|
|
22
|
+
displayId?: string;
|
|
23
|
+
totalMinor: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Non-fatal discrepancies reported while processing a command. */
|
|
27
|
+
export type CommandWarning =
|
|
28
|
+
| { code: 'total_mismatch'; expectedMinor: number; serverMinor: number }
|
|
29
|
+
| { code: 'insufficient_stock'; variantId: string; quantity: number };
|
|
30
|
+
|
|
31
|
+
/** Error reported when a command is rejected. */
|
|
32
|
+
export interface CommandError {
|
|
33
|
+
code: string;
|
|
34
|
+
message: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Server result for a single command. */
|
|
38
|
+
export interface CommandResult {
|
|
39
|
+
id: string;
|
|
40
|
+
status: CommandStatus;
|
|
41
|
+
serverRefs?: CommandServerRefs;
|
|
42
|
+
warnings?: CommandWarning[];
|
|
43
|
+
error?: CommandError;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Order line with client identity and price in minor units. */
|
|
47
|
+
export interface OrderCreateLine {
|
|
48
|
+
clientLineId: string;
|
|
49
|
+
variantId: string;
|
|
50
|
+
title?: string;
|
|
51
|
+
quantity: number;
|
|
52
|
+
unitPriceMinor: number;
|
|
53
|
+
/**
|
|
54
|
+
* This line's own tax mode, when it differs from the order's `pricesIncludeTax`
|
|
55
|
+
* (a price that carries its own flag, D2c). Absent means the order's flag, so
|
|
56
|
+
* older clients and single-mode orders are unchanged.
|
|
57
|
+
*/
|
|
58
|
+
taxInclusive?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Version 2 (ADR-062): this line's total discount, its own line discounts plus its allocated share of
|
|
61
|
+
* the order discount, in the line's own tax mode and integer minor units. The line is taxed on
|
|
62
|
+
* `unitPriceMinor × quantity − discountMinor`. Present only when above 0.
|
|
63
|
+
*/
|
|
64
|
+
discountMinor?: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Supported order payment method. */
|
|
68
|
+
export type PaymentMethodKind = 'cash' | 'external';
|
|
69
|
+
|
|
70
|
+
/** Order payment with client identity and amounts in minor units. */
|
|
71
|
+
export interface OrderCreatePayment {
|
|
72
|
+
clientPaymentId: string;
|
|
73
|
+
method: PaymentMethodKind;
|
|
74
|
+
amountMinor: number;
|
|
75
|
+
tenderedMinor?: number;
|
|
76
|
+
changeMinor?: number;
|
|
77
|
+
reference?: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Client order data submitted by an order.create command. */
|
|
81
|
+
export interface OrderCreatePayload {
|
|
82
|
+
clientOrderId: string;
|
|
83
|
+
createdAt: string;
|
|
84
|
+
currency: string;
|
|
85
|
+
pricesIncludeTax: boolean;
|
|
86
|
+
lines: OrderCreateLine[];
|
|
87
|
+
subtotalMinor: number;
|
|
88
|
+
/** Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0. */
|
|
89
|
+
discountMinor?: number;
|
|
90
|
+
taxMinor: number;
|
|
91
|
+
totalMinor: number;
|
|
92
|
+
payments: OrderCreatePayment[];
|
|
93
|
+
customer?: { email?: string } | null;
|
|
94
|
+
registerId?: string;
|
|
95
|
+
cashierRef?: string;
|
|
96
|
+
locationId?: string;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Batch of commands submitted to the server. */
|
|
100
|
+
export interface CommandBatchRequest {
|
|
101
|
+
commands: CommandEnvelope[];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Results returned by the server for a command batch. */
|
|
105
|
+
export interface CommandBatchResponse {
|
|
106
|
+
results: CommandResult[];
|
|
107
|
+
}
|
package/src/types/connector.ts
CHANGED
|
@@ -3,6 +3,8 @@ import type { RxJsonSchema } from 'rxdb';
|
|
|
3
3
|
import type { ProductTraits } from './traits/product';
|
|
4
4
|
import type { CustomerTraits } from './traits/customer';
|
|
5
5
|
import type { ReplicationAdapter } from './replication';
|
|
6
|
+
import type { FingerprintReconcileAdapter, IdReconcileAdapter, StockReconcileAdapter } from './reconcile';
|
|
7
|
+
import type { StoreSettings, StoreSettingsChoice } from './store-settings';
|
|
6
8
|
|
|
7
9
|
/**
|
|
8
10
|
* Authentication configuration for a connector.
|
|
@@ -18,6 +20,39 @@ export interface ConnectorAuth {
|
|
|
18
20
|
getHeaders: (credentials: Record<string, string>) => Record<string, string>;
|
|
19
21
|
/** Optional: validate that credentials work (e.g., test API call) */
|
|
20
22
|
validate?: (credentials: Record<string, string>) => Promise<boolean>;
|
|
23
|
+
/**
|
|
24
|
+
* Exchanges a user's email and password for a credential (token) to store and pass back to getHeaders as `token`.
|
|
25
|
+
* Rejects with a `SignInError`: `invalid_credentials`, `unsupported` or `failed`.
|
|
26
|
+
*/
|
|
27
|
+
signIn?: (baseUrl: string, login: { email: string; password: string }, init?: { signal?: AbortSignal; fetch?: typeof fetch }) => Promise<SignInResult>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SignInResult {
|
|
31
|
+
token: string;
|
|
32
|
+
/** ISO 8601, when the backend says when the token expires */
|
|
33
|
+
expiresAt?: string;
|
|
34
|
+
/** The store's contract capabilities (ADR-062), when the read was conclusive. */
|
|
35
|
+
capabilities?: ServerCapabilities;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The highest `order.create` contract version a store's server currently accepts (ADR-062). */
|
|
39
|
+
export interface ServerCapabilities {
|
|
40
|
+
orderCreate: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Resolves the capabilities to act on: a definitive fresh read always wins,
|
|
45
|
+
* even a downgrade to 1; an inconclusive fresh read (`undefined`) keeps the
|
|
46
|
+
* last known value. The app persists `stored` with its session, the way it
|
|
47
|
+
* persists the store-settings choice, and copies the result into
|
|
48
|
+
* `SyncContext.capabilities`. `finalizeOrder` treats `undefined` as 1, which
|
|
49
|
+
* only happens when the value has never been read (ADR-062).
|
|
50
|
+
*/
|
|
51
|
+
export function resolveCapabilities(
|
|
52
|
+
fresh: ServerCapabilities | undefined,
|
|
53
|
+
stored: ServerCapabilities | undefined,
|
|
54
|
+
): ServerCapabilities | undefined {
|
|
55
|
+
return fresh ?? stored;
|
|
21
56
|
}
|
|
22
57
|
|
|
23
58
|
export interface AuthField {
|
|
@@ -64,11 +99,20 @@ export interface SyncContext {
|
|
|
64
99
|
headers: Record<string, string>;
|
|
65
100
|
/** Optional abort signal */
|
|
66
101
|
signal?: AbortSignal;
|
|
102
|
+
/** From `storeSettings().pricingContext`; opaque to the app; the connector prices documents with it. Never logged. */
|
|
103
|
+
pricingContext?: Record<string, string>;
|
|
104
|
+
/** The store's contract capabilities (ADR-062), copied from the sign-in result. */
|
|
105
|
+
capabilities?: ServerCapabilities;
|
|
67
106
|
}
|
|
68
107
|
|
|
69
108
|
/**
|
|
70
109
|
* Schema definitions for a connector.
|
|
71
110
|
* Each connector provides its own RxDB schemas that mirror its API shape.
|
|
111
|
+
*
|
|
112
|
+
* Each describes a server-owned, pull-replicated collection (ADR-060), so its
|
|
113
|
+
* versions never transform documents: a version bump drops and resyncs.
|
|
114
|
+
* `createTallyDatabase` drops the old documents, and `startReplication` resets
|
|
115
|
+
* the checkpoint, so the first sync after the bump downloads the collection again.
|
|
72
116
|
*/
|
|
73
117
|
export interface ConnectorSchemas {
|
|
74
118
|
products: RxJsonSchema<any>;
|
|
@@ -122,4 +166,30 @@ export interface TallyConnector {
|
|
|
122
166
|
products?: ReplicationAdapter<any>;
|
|
123
167
|
[key: string]: ReplicationAdapter<any> | undefined;
|
|
124
168
|
};
|
|
169
|
+
|
|
170
|
+
/** Periodic re-reads of state that replication misses (ADR-060) */
|
|
171
|
+
reconcile?: {
|
|
172
|
+
stock?: StockReconcileAdapter;
|
|
173
|
+
ids?: IdReconcileAdapter;
|
|
174
|
+
prices?: FingerprintReconcileAdapter;
|
|
175
|
+
/** Prices the backend calculates for the sales context (price lists, sale dates), which change without a timestamp bump. */
|
|
176
|
+
calculatedPrices?: FingerprintReconcileAdapter;
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Reads the store's own settings (TV4): currency, tax inclusivity, tax
|
|
181
|
+
* rates and a connector-specific pricing context. Read once after
|
|
182
|
+
* sign-in; the app feeds all three consumers from the result. Read-only,
|
|
183
|
+
* never writes to the store (ADR-048).
|
|
184
|
+
*/
|
|
185
|
+
storeSettings?: (context: SyncContext, choice?: StoreSettingsChoice) => Promise<StoreSettings>;
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Re-reads the store's contract capabilities (ADR-062) for a session
|
|
189
|
+
* restored without signing in again — otherwise a restored session would
|
|
190
|
+
* block discounts until the cashier signed in again. `undefined` means
|
|
191
|
+
* the read was inconclusive (offline or a server error), not version 1;
|
|
192
|
+
* see `resolveCapabilities`.
|
|
193
|
+
*/
|
|
194
|
+
capabilities?: (context: SyncContext) => Promise<ServerCapabilities | undefined>;
|
|
125
195
|
}
|