@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
@@ -0,0 +1,32 @@
1
+ import type { CommandBatchResponse } from './types/commands';
2
+
3
+ /** Path of the command endpoint, relative to the backend's base URL. */
4
+ export const COMMANDS_PATH = '/tally/v1/commands';
5
+ /** Header carrying the protocol version. */
6
+ export const PROTOCOL_HEADER = 'X-Tally-Protocol';
7
+ /** Current protocol version. */
8
+ export const PROTOCOL_VERSION = 1;
9
+ /** The ADR-038 batch limit; a server answers more with 413 and a BatchTooLargeBody. */
10
+ export const MAX_COMMANDS_PER_BATCH = 50;
11
+
12
+ /**
13
+ * True if `value` has the shape of a CommandBatchResponse: an object with a
14
+ * `results` array whose every entry has a string `id` and a `status` of
15
+ * 'applied' | 'duplicate' | 'rejected'. Optional fields are not deep-checked.
16
+ */
17
+ export function isCommandBatchResponse(value: unknown): value is CommandBatchResponse {
18
+ return (
19
+ typeof value === 'object' &&
20
+ value !== null &&
21
+ 'results' in value &&
22
+ Array.isArray(value.results) &&
23
+ value.results.every((result: unknown) =>
24
+ typeof result === 'object' &&
25
+ result !== null &&
26
+ 'id' in result &&
27
+ typeof result.id === 'string' &&
28
+ 'status' in result &&
29
+ (result.status === 'applied' || result.status === 'duplicate' || result.status === 'rejected'),
30
+ )
31
+ );
32
+ }
@@ -1,6 +1,7 @@
1
- import { createContext, useContext, type ReactNode } from 'react';
1
+ import { createContext, useContext, useMemo, type ReactNode } from 'react';
2
2
 
3
- import type { TallyConnector } from '../types';
3
+ import { getProductStock, withStockOverlay } from '../stock-overlay';
4
+ import type { StockLevel, TallyConnector, TraitContext } from '../types';
4
5
 
5
6
  /**
6
7
  * React context that holds the active connector.
@@ -9,15 +10,37 @@ import type { TallyConnector } from '../types';
9
10
  */
10
11
  const ConnectorContext = createContext<TallyConnector | null>(null);
11
12
 
13
+ const EMPTY_TRAIT_CONTEXT: TraitContext = {};
14
+ const TraitContextContext = createContext<TraitContext>(EMPTY_TRAIT_CONTEXT);
15
+
16
+ interface StockOverlayValue { overlay?: ReadonlyMap<string, unknown>; asOf?: string }
17
+ const EMPTY_STOCK_OVERLAY: StockOverlayValue = {};
18
+ const StockOverlayContext = createContext<StockOverlayValue>(EMPTY_STOCK_OVERLAY);
19
+
12
20
  export interface ConnectorProviderProps {
13
21
  connector: TallyConnector;
22
+ /**
23
+ * Store-level facts passed to traits that need them, such as the store
24
+ * currency for backends whose product documents omit it.
25
+ */
26
+ traitContext?: TraitContext;
27
+ /** Reconciled stock (ADR-060), e.g. from `stockOverlay$` in `@tallyui/pos`. */
28
+ stockOverlay?: ReadonlyMap<string, unknown>;
29
+ /** ISO time the overlay was last confirmed, e.g. from `stockOverlayAsOf$`. */
30
+ stockOverlayAsOf?: string;
14
31
  children: ReactNode;
15
32
  }
16
33
 
17
- export function ConnectorProvider({ connector, children }: ConnectorProviderProps) {
34
+ export function ConnectorProvider({ connector, traitContext, stockOverlay, stockOverlayAsOf, children }: ConnectorProviderProps) {
35
+ const overlay = useMemo(
36
+ () => (stockOverlay || stockOverlayAsOf ? { overlay: stockOverlay, asOf: stockOverlayAsOf } : EMPTY_STOCK_OVERLAY),
37
+ [stockOverlay, stockOverlayAsOf],
38
+ );
18
39
  return (
19
40
  <ConnectorContext.Provider value={connector}>
20
- {children}
41
+ <TraitContextContext.Provider value={traitContext ?? EMPTY_TRAIT_CONTEXT}>
42
+ <StockOverlayContext.Provider value={overlay}>{children}</StockOverlayContext.Provider>
43
+ </TraitContextContext.Provider>
21
44
  </ConnectorContext.Provider>
22
45
  );
23
46
  }
@@ -44,6 +67,57 @@ export function useProductTraits() {
44
67
  return connector.traits.product;
45
68
  }
46
69
 
70
+ /**
71
+ * The store-level TraitContext given to the nearest ConnectorProvider.
72
+ */
73
+ export function useTraitContext(): TraitContext {
74
+ return useContext(TraitContextContext);
75
+ }
76
+
77
+ /**
78
+ * The product's stock, from the reconciled overlay given to the nearest
79
+ * ConnectorProvider where it has an entry, otherwise from the document.
80
+ * `asOf` is set only when an overlay is given and the connector reconciles stock.
81
+ */
82
+ export function useProductStock(doc: any): StockLevel & { asOf?: string } {
83
+ const connector = useConnector();
84
+ const { overlay, asOf } = useContext(StockOverlayContext);
85
+ const adapter = connector.reconcile?.stock;
86
+ if (!overlay) return connector.traits.product.getStock(doc);
87
+ // The helpers never mutate the map; they take Map for the adapter contract.
88
+ const stock = getProductStock(doc, connector.traits.product, adapter, overlay as Map<string, unknown>);
89
+ return adapter && asOf ? { ...stock, asOf } : stock;
90
+ }
91
+
92
+ /**
93
+ * The products with the nearest ConnectorProvider's reconciled stock overlay merged in (copies only; the
94
+ * documents are never changed), for components that derive stock from documents themselves. Returns
95
+ * `products` itself, unchanged, when there is no provider, no overlay, or the connector has no stock
96
+ * reconcile adapter, and the same array while its inputs are unchanged.
97
+ */
98
+ export function useStockOverlaid<Doc>(products: readonly Doc[]): readonly Doc[] {
99
+ const connector = useContext(ConnectorContext);
100
+ const { overlay } = useContext(StockOverlayContext);
101
+ const adapter = connector?.reconcile?.stock;
102
+ return useMemo(() => {
103
+ if (!adapter || !overlay) return products;
104
+ let changed = false;
105
+ const mapped = products.map((doc) => {
106
+ const next = withStockOverlay(doc, adapter, overlay as Map<string, unknown>);
107
+ if (next !== doc) changed = true;
108
+ return next;
109
+ });
110
+ return changed ? mapped : products;
111
+ }, [products, overlay, adapter]);
112
+ }
113
+
114
+ /** 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). */
115
+ export function useStockOverlayAsOf(): string | undefined {
116
+ const connector = useContext(ConnectorContext);
117
+ const { asOf } = useContext(StockOverlayContext);
118
+ return connector?.reconcile?.stock ? asOf : undefined;
119
+ }
120
+
47
121
  /**
48
122
  * Convenience hook: grab just the customer traits from the active connector.
49
123
  * Returns undefined if the connector doesn't implement customer traits.
package/src/index.ts CHANGED
@@ -8,10 +8,59 @@ export type {
8
8
  CollectionSync,
9
9
  RemoteIdEntry,
10
10
  ReplicationAdapter,
11
+ StockReconcileAdapter,
12
+ IdReconcileAdapter,
13
+ FingerprintReconcileAdapter,
11
14
  SyncContext,
12
15
  ProductTraits,
16
+ TraitContext,
17
+ VariantSummary,
13
18
  CustomerTraits,
19
+ Money,
20
+ ProductPrice,
21
+ ResolvedPrice,
22
+ StockLevel,
23
+ StockStatus,
24
+ StoreSettings,
25
+ StoreSettingsChoice,
14
26
  } from './types';
27
+ export type { SignInResult, ServerCapabilities, TaxRounding } from './types/connector';
28
+ export type { CatalogueReconcileAdapter, CatalogueReconcileEntry } from './types/reconcile';
29
+ export { parseInfoCapabilities, parseTaxRounding, resolveCapabilities } from './types/connector';
30
+ export { SignInError } from './sign-in';
31
+ export { ConnectorUnauthorizedError } from './unauthorized';
32
+ export { isRxdbRemoteVersionMismatch } from './rxdb-remote-version-mismatch';
33
+ export { errorKind, type ErrorKind, type SyncNotice } from './sync-notice';
34
+ export type { SignInErrorCode } from './sign-in';
35
+ export { StoreSettingsError } from './store-settings';
36
+ export { customerTraits, CustomerServiceError, type Customer, type CustomerInput } from './types/customers';
37
+ export type { StoreSettingsErrorCode, StoreSettingsChoices } from './store-settings';
38
+
39
+ export type {
40
+ CommandType, CommandEnvelope, CommandStatus, CommandServerRefs,
41
+ RegisterCommandType, RegisterCommandEnvelope, AnyCommandEnvelope,
42
+ CommandWarning, CommandError, CommandResult, OrderCreateLine,
43
+ PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
44
+ OrderCreateDisplay, OrderCreateTaxRate,
45
+ CommandBatchRequest, CommandBatchResponse, BatchTooLargeBody,
46
+ RegisterCommandResult, RegisterSessionOpenPayload, RegisterSessionTransitionPayload,
47
+ RegisterMovementRecordPayload, RegisterMovementVoidPayload, RegisterClosureSubmitPayload,
48
+ } from './types';
49
+
50
+ export {
51
+ COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, MAX_COMMANDS_PER_BATCH,
52
+ isCommandBatchResponse,
53
+ } from './commands';
54
+
55
+ // Money helpers
56
+ export { currencySymbol, formatMoney, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, resolvePrice, resolvePriceRange } from './money';
57
+ export { findVariantByCode } from './variants';
58
+ export { knownWarnings } from './known-warnings';
59
+ export { compareIds } from './utils/compare-ids';
60
+ export { STOCK_LEVELS_LAST_PASS, withStockOverlay, getProductStock } from './stock-overlay';
61
+ export { combinePullAdapters } from './replication/combine';
62
+ export { createReconcileFeed } from './replication/reconcile-feed';
63
+ export type { ReconcileFeed, ReconcileFeedEntry, ReconcileFetchEntry, KeyedReconcileFeedOptions } from './replication/reconcile-feed';
15
64
 
16
65
  // Context & hooks
17
66
  export {
@@ -19,5 +68,9 @@ export {
19
68
  useConnector,
20
69
  useProductTraits,
21
70
  useCustomerTraits,
71
+ useTraitContext,
72
+ useProductStock,
73
+ useStockOverlaid,
74
+ useStockOverlayAsOf,
22
75
  } from './context/connector-context';
23
76
  export type { ConnectorProviderProps } from './context/connector-context';
@@ -0,0 +1,77 @@
1
+ import type { CommandWarning } from './types/commands';
2
+
3
+ function isSafeInt(value: unknown): value is number {
4
+ return typeof value === 'number' && Number.isSafeInteger(value);
5
+ }
6
+
7
+ type FiguresMismatchField = Extract<CommandWarning, { code: 'figures_mismatch' }>['fields'][number];
8
+
9
+ function figuresMismatchFields(fields: unknown): FiguresMismatchField[] | null {
10
+ if (!Array.isArray(fields) || fields.length === 0) return null;
11
+ const rebuilt: FiguresMismatchField[] = [];
12
+ for (const entry of fields) {
13
+ if (typeof entry !== 'object' || entry === null) return null;
14
+ const { field, tillMinor, serverMinor } = entry as Record<string, unknown>;
15
+ if (typeof field !== 'string' || field === '' || rebuilt.some((kept) => kept.field === field)) return null;
16
+ if (!isSafeInt(tillMinor) || !isSafeInt(serverMinor) || tillMinor === serverMinor) return null;
17
+ rebuilt.push({ field, tillMinor, serverMinor });
18
+ }
19
+ return rebuilt;
20
+ }
21
+
22
+ /**
23
+ * The till's single reader of stored warnings. `[]` for anything that isn't a warnings array.
24
+ * A `total_mismatch`'s `bridgeMinor` is dropped (the rest of the warning is kept) when it's
25
+ * absent, `null`, not a safe integer, zero, or not equal to `expectedMinor - serverMinor`.
26
+ * A `tax_rate_mismatch` with a negative `ratePpm` is dropped entirely; zero stays valid.
27
+ * A `customer_ignored` is dropped unless its `customerId` is a string of 1 to 64 characters.
28
+ * A `figures_mismatch` is dropped entirely unless `fields` is non-empty and each entry names a
29
+ * different figure with two differing safe integers; each entry is rebuilt from its known keys.
30
+ * A figure name it doesn't know (any non-empty string) is kept, since a newer store may send one.
31
+ */
32
+ export function knownWarnings(warnings: unknown): CommandWarning[] {
33
+ if (!Array.isArray(warnings)) return [];
34
+ const kept: CommandWarning[] = [];
35
+ for (const item of warnings) {
36
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) continue;
37
+ const warning = item as Record<string, unknown>;
38
+ switch (warning.code) {
39
+ case 'total_mismatch': {
40
+ if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
41
+ const { bridgeMinor } = warning;
42
+ const validBridge = isSafeInt(bridgeMinor) && bridgeMinor !== 0
43
+ && bridgeMinor === warning.expectedMinor - warning.serverMinor;
44
+ kept.push(validBridge
45
+ ? { code: 'total_mismatch', expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor, bridgeMinor }
46
+ : { code: 'total_mismatch', expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
47
+ break;
48
+ }
49
+ case 'insufficient_stock': {
50
+ if (typeof warning.variantId !== 'string' || warning.variantId === '') continue;
51
+ if (!isSafeInt(warning.quantity) || warning.quantity < 1) continue;
52
+ kept.push({ code: 'insufficient_stock', variantId: warning.variantId, quantity: warning.quantity });
53
+ break;
54
+ }
55
+ case 'tax_rate_mismatch': {
56
+ if (!isSafeInt(warning.ratePpm) || warning.ratePpm < 0) continue;
57
+ if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
58
+ kept.push({ code: 'tax_rate_mismatch', ratePpm: warning.ratePpm, expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
59
+ break;
60
+ }
61
+ case 'customer_ignored': {
62
+ const { customerId } = warning;
63
+ if (typeof customerId !== 'string' || customerId === '' || customerId.length > 64) continue;
64
+ kept.push({ code: 'customer_ignored', customerId });
65
+ break;
66
+ }
67
+ case 'figures_mismatch': {
68
+ const fields = figuresMismatchFields(warning.fields);
69
+ if (fields !== null) kept.push({ code: 'figures_mismatch', fields });
70
+ break;
71
+ }
72
+ default:
73
+ continue;
74
+ }
75
+ }
76
+ return kept;
77
+ }
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,77 @@
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
+ * `options.batchSize` sets the combined pull page size; sub-adapters' own
16
+ * `pull.batchSize` is ignored.
17
+ * Pull only: a sub-adapter with `push` or `pull.stream$` throws here.
18
+ */
19
+ export function combinePullAdapters<Doc>(
20
+ adapters: Record<string, ReplicationAdapter<Doc, any>>,
21
+ options: { legacyKey?: string; batchSize?: number } = {},
22
+ ): ReplicationAdapter<Doc, Record<string, any>> {
23
+ const keys = Object.keys(adapters);
24
+ for (const key of keys) {
25
+ if (adapters[key].push || adapters[key].pull.stream$) {
26
+ throw new Error(`combinePullAdapters: sub-adapter "${key}" has push or pull.stream$; only pull handlers can be combined.`);
27
+ }
28
+ }
29
+ return {
30
+ pull: {
31
+ batchSize: options.batchSize,
32
+ async handler(lastCheckpoint, batchSize, context) {
33
+ let previous = lastCheckpoint;
34
+ if (options.legacyKey && previous && typeof previous === 'object'
35
+ && Object.keys(previous).length && !keys.some((key) => key in previous!)) {
36
+ previous = { [options.legacyKey]: previous };
37
+ }
38
+ if (!previous || !Object.keys(previous).length) {
39
+ // A true fresh install: no stored checkpoint, legacy or otherwise (an
40
+ // upgrade keeps its healing full pass). Seeding reads the marks before
41
+ // the first product page, so every edit after a mark is caught by that
42
+ // feed's inclusive `$gte`, and every edit before it is in the product
43
+ // feed's first pass, which fetches later. The seeds are saved with this
44
+ // call's combined checkpoint, which carries the product feed's first
45
+ // documents; with an empty catalogue nothing is lost either way.
46
+ const seeded: Record<string, any> = {};
47
+ for (const key of keys) {
48
+ const { pull } = adapters[key];
49
+ if (pull.seedCheckpoint) seeded[key] = await pull.seedCheckpoint(context);
50
+ }
51
+ previous = seeded;
52
+ }
53
+ const byId = new Map<unknown, Doc & { _deleted: boolean }>();
54
+ const checkpoint: Record<string, any> = {};
55
+ // Call sub-adapters strictly one after another, in key order: a
56
+ // correctness rule, not politeness. Each feed writes whole documents.
57
+ // Sequential calls with the last duplicate winning mean every document
58
+ // comes from the latest fetch of this call. RxDB 16.21.1 can fetch the next
59
+ // call before these writes finish, but its persistence queue keeps fetch
60
+ // order (pending duplicates keep the latest). Concurrent feeds could let a
61
+ // fetch made before another feed's newer write land after it and revert
62
+ // it, with neither checkpoint ever revisiting the document.
63
+ for (const key of keys) {
64
+ const result = await adapters[key].pull.handler(previous?.[key], batchSize, context);
65
+ for (const doc of result.documents) byId.set((doc as { id?: unknown }).id, doc);
66
+ // RxDB merges only the top level of the combined checkpoint, so merge
67
+ // each sub-checkpoint here as it would for a single adapter. Spread
68
+ // keeps a sub-adapter's explicit undefined (cleared pass state).
69
+ checkpoint[key] = { ...previous?.[key], ...result.checkpoint };
70
+ }
71
+ // Each sub-adapter returns unique ids, so one full sub-page makes the
72
+ // combined page full: RxDB keeps pulling while any sub-adapter has more.
73
+ return { documents: [...byId.values()], checkpoint };
74
+ },
75
+ },
76
+ };
77
+ }
@@ -0,0 +1,116 @@
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
+ /**
8
+ * One queued correction, keyed by the local primary key: `key`, or `id`, its
9
+ * older name. `local` is the till's copy, if it has one; `remote` is whatever
10
+ * the connector needs to refetch it.
11
+ */
12
+ export type ReconcileFeedEntry<Doc = any> = ({ key: string; id?: undefined } | { id: string; key?: undefined }) & {
13
+ local?: Doc;
14
+ remote?: unknown;
15
+ /**
16
+ * Re-deliver if the product still exists; never tombstone if missing (the
17
+ * fingerprint path, ADR-060). Only the id reconcile, with its mass-delete
18
+ * brake, enqueues deletable entries.
19
+ */
20
+ refreshOnly?: boolean;
21
+ /** Proven gone (the catalogue reconcile, #248): written as deleted from `local`, without a fetch. */
22
+ tombstone?: boolean;
23
+ };
24
+ /** What a keyed feed's `fetchByIds` receives for each entry. */
25
+ export interface ReconcileFetchEntry<Doc = any> { key: string; local?: Doc; remote?: unknown }
26
+ export interface CreateReconcileFeedOptions<Doc = any> {
27
+ /** The current projected documents for the ids that still exist, matched back by `doc.id`. */
28
+ fetchByIds(ids: string[], context: SyncContext): Promise<Doc[]>;
29
+ }
30
+ /** A feed keyed by the primary key where that is not `doc.id` (WooCommerce's uuid, #248). */
31
+ export interface KeyedReconcileFeedOptions<Doc = any> {
32
+ /** The local primary key of a fetched document; fetched documents are matched to entries by it. */
33
+ key(doc: Doc): string;
34
+ /** The current documents for the entries that still exist. A document may carry `_deleted: true` (an unpublished product). */
35
+ fetchByIds(entries: Array<ReconcileFetchEntry<Doc>>, context: SyncContext): Promise<Doc[]>;
36
+ }
37
+ export interface ReconcileFeed<Doc = any> {
38
+ /** Pull-only; meant as the last key of `combinePullAdapters` so its fetch wins duplicates. */
39
+ adapter: ReplicationAdapter<Doc, { n: number }>;
40
+ /**
41
+ * Add entries to the in-memory queue, de-duplicated by key, last entry wins.
42
+ * `refreshOnly` is merged separately: it is true only when every merged
43
+ * entry for that key was `refreshOnly`, so a deletable entry (the id
44
+ * reconcile's) is never downgraded by a later refresh-only one.
45
+ */
46
+ enqueue(entries: Array<ReconcileFeedEntry<Doc>>): void;
47
+ }
48
+
49
+ /**
50
+ * Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060).
51
+ * Two overloads: with `key`, `fetchByIds` receives the entries and fetched documents are matched by
52
+ * `key(doc)`; without it, `fetchByIds` receives bare ids and documents are matched by `doc.id`.
53
+ */
54
+ export function createReconcileFeed<Doc = any>(options: KeyedReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
55
+ export function createReconcileFeed<Doc = any>(options: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
56
+ export function createReconcileFeed<Doc = any>(
57
+ options: KeyedReconcileFeedOptions<Doc> | CreateReconcileFeedOptions<Doc>,
58
+ ): ReconcileFeed<Doc> {
59
+ const keyed = 'key' in options && typeof options.key === 'function' ? options : undefined;
60
+ const docKey = keyed ? keyed.key : (doc: Doc) => (doc as { id?: unknown }).id;
61
+ const fetch = (chunk: Array<ReconcileFeedEntry<Doc>>, context: SyncContext): Promise<Doc[]> => keyed
62
+ ? keyed.fetchByIds(chunk.map((e) => ({ key: keyOf(e), local: e.local, remote: e.remote })), context)
63
+ : (options as CreateReconcileFeedOptions<Doc>).fetchByIds(chunk.map(keyOf), context);
64
+ let queue = new Map<string, ReconcileFeedEntry<Doc>>();
65
+ // refreshOnly is true only if both the prior and the incoming entry were
66
+ // refreshOnly: a deletable entry is never downgraded by a later refresh-only one.
67
+ const merge = (prior: ReconcileFeedEntry<Doc> | undefined, e: ReconcileFeedEntry<Doc>): ReconcileFeedEntry<Doc> =>
68
+ ({ ...e, refreshOnly: Boolean(e.refreshOnly) && (prior?.refreshOnly ?? true) });
69
+ const enqueue = (entries: Array<ReconcileFeedEntry<Doc>>) => {
70
+ for (const e of entries) queue.set(keyOf(e), merge(queue.get(keyOf(e)), e));
71
+ };
72
+
73
+ const adapter: ReplicationAdapter<Doc, { n: number }> = {
74
+ pull: {
75
+ async handler(lastCheckpoint, _batchSize, context) {
76
+ if (queue.size === 0) return { documents: [], checkpoint: lastCheckpoint ?? { n: 0 } };
77
+ // Drain the whole queue; anything enqueued while this pass runs lands in the fresh map.
78
+ const entries = [...queue.values()];
79
+ queue = new Map();
80
+ try {
81
+ const documents: Array<Doc & { _deleted: boolean }> = [];
82
+ // Fetch in chunks of at most MAX_CHUNK entries per call; a tombstone is never fetched.
83
+ for (let i = 0; i < entries.length; i += MAX_CHUNK) {
84
+ const chunk = entries.slice(i, i + MAX_CHUNK);
85
+ const toFetch = chunk.filter((e) => !e.tombstone);
86
+ const fetched = toFetch.length ? await fetch(toFetch, context) : [];
87
+ const byKey = new Map(fetched.map((doc) => [docKey(doc), doc]));
88
+ for (const entry of chunk) {
89
+ const doc = entry.tombstone ? undefined : byKey.get(keyOf(entry));
90
+ // A fetched document keeps a `_deleted` the connector set (an unpublished product, #248).
91
+ if (doc) documents.push({ ...doc, _deleted: (doc as { _deleted?: boolean })._deleted ?? false });
92
+ // A refreshOnly entry (the fingerprint path) is skipped, not tombstoned, when the
93
+ // product is missing: only the id reconcile's braked entries may delete (ADR-060).
94
+ // An entry with no local copy has nothing to delete.
95
+ else if (!entry.refreshOnly && entry.local) documents.push({ ...entry.local, _deleted: true });
96
+ }
97
+ }
98
+ return { documents, checkpoint: { n: (lastCheckpoint?.n ?? 0) + 1 } };
99
+ } catch (error) {
100
+ // Put entries back at the front; anything queued mid-fetch wins, merged
101
+ // by the same rule, so a failed fetch never downgrades a deletable entry. RxDB retries.
102
+ const restored = new Map(entries.map((e) => [keyOf(e), e]));
103
+ for (const [key, e] of queue) restored.set(key, merge(restored.get(key), e));
104
+ queue = restored;
105
+ throw error;
106
+ }
107
+ },
108
+ },
109
+ };
110
+ return { adapter, enqueue };
111
+ }
112
+
113
+ /** An entry's local primary key: `key`, or `id`, its older name. */
114
+ function keyOf(entry: ReconcileFeedEntry): string {
115
+ return (entry.key ?? entry.id) as string;
116
+ }
@@ -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,32 @@
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
+ * Originally bypassed RxDB 16.21.1's bug 4, fixed in RxDB 17 (rxdb#7067) by snapshotting the
7
+ * change counter before a read and rerunning when it moves. `readFresh`, `countFresh` and
8
+ * `watchFresh` remain correct public API; retiring them is a separate decision.
9
+ *
10
+ * The prepared query is RxDB's own (`find(query).getPreparedQuery()`), so it already carries the
11
+ * `_deleted: false` filter, the query's sort and its limit. The read goes through the same wrapped
12
+ * storage instance an `RxQuery` uses, but skips `RxQuery` and `RxDocument`, so it is untested with
13
+ * key compression and field encryption; no TallyUI collection uses either.
14
+ *
15
+ * Returns plain, deep-cloned document data without RxDB's metadata. Use `findOne(id)` for an
16
+ * `RxDocument` to write through; its `incrementalModify` modifier sees the stored state.
17
+ */
18
+ export async function readFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>): Promise<T[]> {
19
+ const { documents } = await collection.storageInstance.query(collection.find(query).getPreparedQuery());
20
+ return documents.map((document) => {
21
+ const { _meta, _rev, _attachments, _deleted, ...data } = clone(document);
22
+ return data as T;
23
+ });
24
+ }
25
+
26
+ /**
27
+ * Counts straight from the collection's storage, past RxDB's cached count (see `readFresh`).
28
+ * Unlike `count().exec()`, it doesn't refuse a storage that reports a slow count.
29
+ */
30
+ export async function countFresh<T>(collection: RxCollection<T>, selector: MangoQuerySelector<T>): Promise<number> {
31
+ return (await collection.storageInstance.count(collection.count({ selector }).getPreparedQuery())).count;
32
+ }