@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.
- package/LICENSE +21 -0
- package/dist/chunk-C4PWPOKO.js +18 -0
- package/dist/commands-BW4YYgRG.d.ts +306 -0
- package/dist/index.d.ts +636 -8
- package/dist/index.js +468 -4
- package/dist/rxdb/index.d.ts +37 -0
- package/dist/rxdb/index.js +26 -0
- package/dist/server/index.d.ts +213 -0
- package/dist/server/index.js +591 -0
- package/package.json +33 -3
- package/src/commands.ts +32 -0
- package/src/context/connector-context.tsx +78 -4
- package/src/index.ts +53 -0
- package/src/known-warnings.ts +77 -0
- package/src/money.ts +142 -0
- package/src/replication/combine.ts +77 -0
- package/src/replication/reconcile-feed.ts +116 -0
- package/src/rxdb/index.ts +4 -0
- package/src/rxdb/read-fresh.ts +32 -0
- package/src/rxdb/watch-fresh.ts +19 -0
- package/src/rxdb-remote-version-mismatch.ts +30 -0
- package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
- package/src/server/__fixtures__/order-create-v3.json +97 -0
- package/src/server/batch-outcome.ts +19 -0
- package/src/server/batch.ts +112 -0
- package/src/server/command-result.ts +138 -0
- package/src/server/fingerprint.ts +18 -0
- package/src/server/fiscal-figures.ts +84 -0
- package/src/server/index.ts +20 -0
- package/src/server/money.ts +34 -0
- package/src/server/order-payload-shape.ts +112 -0
- package/src/server/register-figures.ts +32 -0
- package/src/server/register-outcome.ts +12 -0
- package/src/server/register-payload-shape.ts +86 -0
- package/src/server/rejection-codes.ts +49 -0
- package/src/server/total-warnings.ts +10 -0
- package/src/server/versions.ts +9 -0
- package/src/sign-in.ts +21 -0
- package/src/stock-overlay.ts +35 -0
- package/src/store-settings.ts +29 -0
- package/src/sync-notice.ts +26 -0
- package/src/types/commands.ts +236 -0
- package/src/types/connector.ts +127 -0
- package/src/types/customers.ts +26 -0
- package/src/types/index.ts +23 -1
- package/src/types/money.ts +33 -0
- package/src/types/reconcile.ts +73 -0
- package/src/types/replication.ts +12 -0
- package/src/types/stock.ts +18 -0
- package/src/types/store-settings.ts +27 -0
- package/src/types/traits/product.ts +62 -6
- package/src/unauthorized.ts +13 -0
- 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
|
@@ -0,0 +1,236 @@
|
|
|
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
|
+
/** 3 when the order carries ADR-065's `display` and `taxByRate` (the store accepts 3), else 2 when discounted, else 1;
|
|
9
|
+
* 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286). */
|
|
10
|
+
version: 1 | 2 | 3 | 4;
|
|
11
|
+
payload: P;
|
|
12
|
+
createdAt: string; // ISO 8601, client clock
|
|
13
|
+
deviceId: string;
|
|
14
|
+
attempt: number; // 1-based, informational
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The register commands (ADR-068); each versions on its own, from 1. */
|
|
18
|
+
export type RegisterCommandType = 'register.session.open' | 'register.session.transition'
|
|
19
|
+
| 'register.movement.record' | 'register.movement.void' | 'register.closure.submit';
|
|
20
|
+
/** A register command's envelope: the same fields as CommandEnvelope, with its own type and a numeric version. */
|
|
21
|
+
export type RegisterCommandEnvelope<P = Record<string, unknown>> =
|
|
22
|
+
Omit<CommandEnvelope<P>, 'type' | 'version'> & { type: RegisterCommandType; version: number };
|
|
23
|
+
/** Any command a transport can carry. */
|
|
24
|
+
export type AnyCommandEnvelope = CommandEnvelope<unknown> | RegisterCommandEnvelope<unknown>;
|
|
25
|
+
|
|
26
|
+
/** An order.create envelope: its version is 1 | 2 | 3 | 4 (ADR-062, ADR-065, #286). */
|
|
27
|
+
export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 };
|
|
28
|
+
|
|
29
|
+
/** Outcome of processing a command. */
|
|
30
|
+
export type CommandStatus = 'applied' | 'duplicate' | 'rejected';
|
|
31
|
+
|
|
32
|
+
/** Server order identifiers and authoritative total. */
|
|
33
|
+
export interface CommandServerRefs {
|
|
34
|
+
orderId: string;
|
|
35
|
+
displayId?: string;
|
|
36
|
+
totalMinor: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Non-fatal discrepancies reported while processing a command. A server may send codes not
|
|
41
|
+
* listed here (a newer contract); readers go through `knownWarnings`, which drops them, and a
|
|
42
|
+
* warning never rejects a sale.
|
|
43
|
+
*/
|
|
44
|
+
export type CommandWarning =
|
|
45
|
+
| {
|
|
46
|
+
code: 'total_mismatch'; expectedMinor: number; serverMinor: number;
|
|
47
|
+
/**
|
|
48
|
+
* Present if and only if the server added an untaxed rounding surcharge so its total
|
|
49
|
+
* matches the till's; signed, in minor units, `expectedMinor - serverMinor`, where
|
|
50
|
+
* `serverMinor` is the platform's total before the bridge.
|
|
51
|
+
*/
|
|
52
|
+
bridgeMinor?: number;
|
|
53
|
+
}
|
|
54
|
+
| { code: 'insufficient_stock'; variantId: string; quantity: number }
|
|
55
|
+
| {
|
|
56
|
+
/**
|
|
57
|
+
* One warning per tax rate whose tax differs by more than the server's rounding tolerance
|
|
58
|
+
* (order.create v3 only); `expectedMinor` is the till's `taxByRate[].taxMinor` for that
|
|
59
|
+
* rate and `serverMinor` the platform's tax for it.
|
|
60
|
+
*/
|
|
61
|
+
code: 'tax_rate_mismatch'; ratePpm: number; expectedMinor: number; serverMinor: number;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The sale's `customerId` (1 to 64 characters) was unknown, deleted or in another channel, so
|
|
65
|
+
* the sale was kept as a guest sale rather than held (ADR-070).
|
|
66
|
+
*/
|
|
67
|
+
| { code: 'customer_ignored'; customerId: string }
|
|
68
|
+
/**
|
|
69
|
+
* One warning per sale, never a refusal: each of the till's figures that differs from the
|
|
70
|
+
* server's own computation, once, with both values (#257). `total_mismatch` stays separate.
|
|
71
|
+
* `parseCommandResult` refuses a `field` it doesn't know; `knownWarnings` keeps it (a newer
|
|
72
|
+
* store's figure), so the type admits any non-empty string besides the three names.
|
|
73
|
+
*/
|
|
74
|
+
| {
|
|
75
|
+
code: 'figures_mismatch';
|
|
76
|
+
fields: Array<{ field: 'subtotalMinor' | 'taxMinor' | 'discountMinor' | (string & {}); tillMinor: number; serverMinor: number }>;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** Error reported when a command is rejected. */
|
|
80
|
+
export interface CommandError {
|
|
81
|
+
code: string;
|
|
82
|
+
message: string;
|
|
83
|
+
/** A refusal's details, e.g. the server's supported version. */
|
|
84
|
+
data?: Record<string, unknown>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Server result for a single command. */
|
|
88
|
+
export interface CommandResult {
|
|
89
|
+
id: string;
|
|
90
|
+
status: CommandStatus;
|
|
91
|
+
serverRefs?: CommandServerRefs;
|
|
92
|
+
warnings?: CommandWarning[];
|
|
93
|
+
error?: CommandError;
|
|
94
|
+
register?: RegisterCommandResult;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A register command's server figures (registers c2b applies them). */
|
|
98
|
+
export interface RegisterCommandResult {
|
|
99
|
+
/** The session's server state after this command. `expected` is absent when the server redacts it (blind). */
|
|
100
|
+
session?: { id: string; status: 'open' | 'counting' | 'closed'; expected?: Record<string, number>; salesCount?: number };
|
|
101
|
+
/** The register's counters: a floor for the till's own, never lowered. */
|
|
102
|
+
counters?: { lastClosureNumber: number; perpetualSalesTotalMinor: number; perpetualRefundsTotalMinor: number };
|
|
103
|
+
/** `register.closure.submit` only. */
|
|
104
|
+
closure?: { serverClosureId: string; number: number; expected?: Record<string, number>; variance?: Record<string, number> };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface RegisterSessionOpenPayload {
|
|
108
|
+
sessionId: string; registerId: string; storeKey?: string; businessDay?: string; openedAt: string; openedBy?: string;
|
|
109
|
+
expectedFloatMinor?: number; countedFloatMinor: number; openingVarianceMinor?: number;
|
|
110
|
+
}
|
|
111
|
+
export interface RegisterSessionTransitionPayload {
|
|
112
|
+
sessionId: string; status: 'open' | 'counting' | 'closed'; at: string;
|
|
113
|
+
/** Closing only. */ counted?: Record<string, number>; closedBy?: string; approvedBy?: string;
|
|
114
|
+
}
|
|
115
|
+
export interface RegisterMovementRecordPayload {
|
|
116
|
+
movementId: string; sessionId: string; type: 'paid_in' | 'paid_out' | 'no_sale'; amountMinor: number; reason: string;
|
|
117
|
+
createdAt: string; createdBy?: string;
|
|
118
|
+
}
|
|
119
|
+
export interface RegisterMovementVoidPayload {
|
|
120
|
+
movementId: string; sessionId: string; voids: string; createdAt: string; createdBy?: string;
|
|
121
|
+
}
|
|
122
|
+
export interface RegisterClosureSubmitPayload {
|
|
123
|
+
closureId: string; sessionId: string; registerId: string; number: number; businessDay?: string;
|
|
124
|
+
openedAt: string; closedAt: string; closedBy?: string; approvedBy?: string;
|
|
125
|
+
tillExpected: Record<string, number>; counted: Record<string, number>;
|
|
126
|
+
periodSalesTotalMinor: number; periodRefundsTotalMinor: number;
|
|
127
|
+
perpetualSalesTotalMinor: number; perpetualRefundsTotalMinor: number;
|
|
128
|
+
unsyncedCount: number; unsyncedTotalMinor: number; softwareVersion: string;
|
|
129
|
+
orderIds: string[]; movementIds: string[];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Order line with client identity and price in minor units. */
|
|
133
|
+
export interface OrderCreateLine {
|
|
134
|
+
clientLineId: string;
|
|
135
|
+
variantId: string;
|
|
136
|
+
title?: string;
|
|
137
|
+
quantity: number;
|
|
138
|
+
unitPriceMinor: number;
|
|
139
|
+
/**
|
|
140
|
+
* This line's own tax mode, when it differs from the order's `pricesIncludeTax`
|
|
141
|
+
* (a price that carries its own flag, D2c). Absent means the order's flag, so
|
|
142
|
+
* older clients and single-mode orders are unchanged.
|
|
143
|
+
*/
|
|
144
|
+
taxInclusive?: boolean;
|
|
145
|
+
/**
|
|
146
|
+
* Version 2 (ADR-062): this line's total discount, its own line discounts plus its allocated share of
|
|
147
|
+
* the order discount, in the line's own tax mode and integer minor units. The line is taxed on
|
|
148
|
+
* `unitPriceMinor × quantity − discountMinor`. Present only when above 0.
|
|
149
|
+
* Version 4 (#286): tax-exclusive (net) in every mode; an inclusive line's is `net(A) − net(A − D)`.
|
|
150
|
+
*/
|
|
151
|
+
discountMinor?: number;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Supported order payment method. */
|
|
155
|
+
export type PaymentMethodKind = 'cash' | 'external';
|
|
156
|
+
|
|
157
|
+
/** Order payment with client identity and amounts in minor units. */
|
|
158
|
+
export interface OrderCreatePayment {
|
|
159
|
+
clientPaymentId: string;
|
|
160
|
+
method: PaymentMethodKind;
|
|
161
|
+
amountMinor: number;
|
|
162
|
+
tenderedMinor?: number;
|
|
163
|
+
changeMinor?: number;
|
|
164
|
+
reference?: string;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Version 3 (ADR-065): the receipt's display figures, integer minor units of `currency` at `exponent`. */
|
|
168
|
+
export interface OrderCreateDisplay {
|
|
169
|
+
currency: string;
|
|
170
|
+
exponent: number;
|
|
171
|
+
taxInclusive: boolean;
|
|
172
|
+
subtotalMinor: number;
|
|
173
|
+
discountMinor: number;
|
|
174
|
+
taxMinor: number;
|
|
175
|
+
totalMinor: number;
|
|
176
|
+
orderDiscountMinor: number;
|
|
177
|
+
lines: Array<{
|
|
178
|
+
clientLineId: string;
|
|
179
|
+
amountMinor: number;
|
|
180
|
+
discounts: Array<{ discountId: string; label?: string; amountMinor: number }>;
|
|
181
|
+
}>;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Version 3 (ADR-065): one tax rate's net, tax and gross, as the receipt's tax summary splits them. */
|
|
185
|
+
export interface OrderCreateTaxRate {
|
|
186
|
+
ratePpm: number;
|
|
187
|
+
code?: string;
|
|
188
|
+
netMinor: number;
|
|
189
|
+
taxMinor: number;
|
|
190
|
+
grossMinor: number;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Client order data submitted by an order.create command. */
|
|
194
|
+
export interface OrderCreatePayload {
|
|
195
|
+
clientOrderId: string;
|
|
196
|
+
createdAt: string;
|
|
197
|
+
currency: string;
|
|
198
|
+
pricesIncludeTax: boolean;
|
|
199
|
+
lines: OrderCreateLine[];
|
|
200
|
+
subtotalMinor: number;
|
|
201
|
+
/**
|
|
202
|
+
* Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0.
|
|
203
|
+
* Version 4 (#286) means every `discountMinor`, this and each line's, is tax-exclusive, so the sum still holds.
|
|
204
|
+
*/
|
|
205
|
+
discountMinor?: number;
|
|
206
|
+
taxMinor: number;
|
|
207
|
+
totalMinor: number;
|
|
208
|
+
payments: OrderCreatePayment[];
|
|
209
|
+
/** version 3 only; both or neither. */
|
|
210
|
+
display?: OrderCreateDisplay;
|
|
211
|
+
/** version 3 only; both or neither. */
|
|
212
|
+
taxByRate?: OrderCreateTaxRate[];
|
|
213
|
+
customer?: {
|
|
214
|
+
email?: string;
|
|
215
|
+
/** Version 3 only: the platform's id for the customer picked at the till, a soft reference of at most 64 characters. Absent for a guest sale, or when no customer was picked. */
|
|
216
|
+
customerId?: string;
|
|
217
|
+
} | null;
|
|
218
|
+
registerId?: string;
|
|
219
|
+
cashierRef?: string;
|
|
220
|
+
locationId?: string;
|
|
221
|
+
/** Version 3 only: the register session the sale was taken for, stamped or late (ADR-032). A late sale names the session that refused its stamp; the server tells the two apart by the session's closure `orderIds`. Absent when the sale had no session. */
|
|
222
|
+
sessionId?: string;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Batch of commands submitted to the server. */
|
|
226
|
+
export interface CommandBatchRequest<E extends AnyCommandEnvelope = CommandEnvelope> {
|
|
227
|
+
commands: E[];
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Results returned by the server for a command batch. */
|
|
231
|
+
export interface CommandBatchResponse {
|
|
232
|
+
results: CommandResult[];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The `413` body for a batch over the limit (ADR-038; Front desk ruling 18). */
|
|
236
|
+
export type BatchTooLargeBody = { code: 'batch_too_large'; maxCommands: number; message: string };
|
package/src/types/connector.ts
CHANGED
|
@@ -3,6 +3,9 @@ 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 { CatalogueReconcileAdapter, FingerprintReconcileAdapter, IdReconcileAdapter, StockReconcileAdapter } from './reconcile';
|
|
7
|
+
import type { StoreSettings, StoreSettingsChoice } from './store-settings';
|
|
8
|
+
import type { Customer, CustomerInput } from './customers';
|
|
6
9
|
|
|
7
10
|
/**
|
|
8
11
|
* Authentication configuration for a connector.
|
|
@@ -18,6 +21,87 @@ export interface ConnectorAuth {
|
|
|
18
21
|
getHeaders: (credentials: Record<string, string>) => Record<string, string>;
|
|
19
22
|
/** Optional: validate that credentials work (e.g., test API call) */
|
|
20
23
|
validate?: (credentials: Record<string, string>) => Promise<boolean>;
|
|
24
|
+
/**
|
|
25
|
+
* Exchanges a user's email and password for a credential (token) to store and pass back to getHeaders as `token`.
|
|
26
|
+
* Rejects with a `SignInError`: `invalid_credentials`, `unsupported` or `failed`.
|
|
27
|
+
*/
|
|
28
|
+
signIn?: (baseUrl: string, login: { email: string; password: string }, init?: { signal?: AbortSignal; fetch?: typeof fetch }) => Promise<SignInResult>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface SignInResult {
|
|
32
|
+
token: string;
|
|
33
|
+
/** ISO 8601, when the backend says when the token expires */
|
|
34
|
+
expiresAt?: string;
|
|
35
|
+
/** The store's contract capabilities (ADR-062), when the read was conclusive. */
|
|
36
|
+
capabilities?: ServerCapabilities;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The highest `order.create` contract version a store's server currently accepts (ADR-062). */
|
|
40
|
+
export interface ServerCapabilities {
|
|
41
|
+
orderCreate: number;
|
|
42
|
+
/** The highest `register` contract version; absent or 0 means no register sync. */
|
|
43
|
+
register?: number;
|
|
44
|
+
/** How the store rounds tax (#287). Absent: an older server, per_order + half_away_from_zero. */
|
|
45
|
+
taxRounding?: TaxRounding;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
|
|
49
|
+
export type TaxRounding =
|
|
50
|
+
| { granularity: 'per_order' | 'per_line_items' | 'per_rate_group_items'; mode: 'half_away_from_zero' | 'half_up' }
|
|
51
|
+
| { granularity: 'custom' };
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Resolves the capabilities to act on: a definitive fresh read always wins,
|
|
55
|
+
* even a downgrade to 1; an inconclusive fresh read (`undefined`) keeps the
|
|
56
|
+
* last known value. The app persists `stored` with its session, the way it
|
|
57
|
+
* persists the store-settings choice, and copies the result into
|
|
58
|
+
* `SyncContext.capabilities`. `finalizeOrder` treats `undefined` as 1, which
|
|
59
|
+
* only happens when the value has never been read (ADR-062).
|
|
60
|
+
*/
|
|
61
|
+
export function resolveCapabilities(
|
|
62
|
+
fresh: ServerCapabilities | undefined,
|
|
63
|
+
stored: ServerCapabilities | undefined,
|
|
64
|
+
): ServerCapabilities | undefined {
|
|
65
|
+
return fresh ?? stored;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const GRANULARITIES = ['per_order', 'per_line_items', 'per_rate_group_items'];
|
|
69
|
+
const MODES = ['half_away_from_zero', 'half_up'];
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Reads the `taxRounding` of `GET /tally/v1/info` (#287): a valid value comes back without
|
|
73
|
+
* extra keys, and `custom` drops any `mode`. Absent gives `undefined`, the default. Core has
|
|
74
|
+
* no logger, so a malformed value gives `undefined` and one reason to `warn` for the caller to log.
|
|
75
|
+
*/
|
|
76
|
+
export function parseTaxRounding(value: unknown, warn?: (reason: string) => void): TaxRounding | undefined {
|
|
77
|
+
if (value === undefined) return undefined;
|
|
78
|
+
const { granularity, mode } = (value ?? {}) as { granularity?: unknown; mode?: unknown };
|
|
79
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
80
|
+
if (granularity === 'custom') return { granularity };
|
|
81
|
+
if (GRANULARITIES.includes(granularity as string) && MODES.includes(mode as string)) {
|
|
82
|
+
return { granularity, mode } as TaxRounding;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
warn?.(`ignoring a malformed taxRounding, so the default applies: ${JSON.stringify(value)}`);
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const maxVersion = (list: unknown): number | undefined => {
|
|
90
|
+
const valid = Array.isArray(list) ? list.filter((v): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v > 0) : [];
|
|
91
|
+
return valid.length > 0 ? Math.max(...valid) : undefined;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Reads a 2xx body of `GET /tally/v1/info` (ADR-062): `orderCreate` is the max of
|
|
96
|
+
* `contracts["order.create"]`, or 1 when it's missing or malformed; `register` is the max of
|
|
97
|
+
* `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287).
|
|
98
|
+
*/
|
|
99
|
+
export function parseInfoCapabilities(body: unknown, warn?: (reason: string) => void): ServerCapabilities {
|
|
100
|
+
const { contracts, taxRounding } = (body ?? {}) as { contracts?: Record<string, unknown> | null; taxRounding?: unknown };
|
|
101
|
+
const register = maxVersion(contracts?.register);
|
|
102
|
+
const rounding = parseTaxRounding(taxRounding, warn);
|
|
103
|
+
return { orderCreate: maxVersion(contracts?.['order.create']) ?? 1,
|
|
104
|
+
...(register !== undefined ? { register } : {}), ...(rounding ? { taxRounding: rounding } : {}) };
|
|
21
105
|
}
|
|
22
106
|
|
|
23
107
|
export interface AuthField {
|
|
@@ -64,11 +148,20 @@ export interface SyncContext {
|
|
|
64
148
|
headers: Record<string, string>;
|
|
65
149
|
/** Optional abort signal */
|
|
66
150
|
signal?: AbortSignal;
|
|
151
|
+
/** From `storeSettings().pricingContext`; opaque to the app; the connector prices documents with it. Never logged. */
|
|
152
|
+
pricingContext?: Record<string, string>;
|
|
153
|
+
/** The store's contract capabilities (ADR-062), copied from the sign-in result. */
|
|
154
|
+
capabilities?: ServerCapabilities;
|
|
67
155
|
}
|
|
68
156
|
|
|
69
157
|
/**
|
|
70
158
|
* Schema definitions for a connector.
|
|
71
159
|
* Each connector provides its own RxDB schemas that mirror its API shape.
|
|
160
|
+
*
|
|
161
|
+
* Each describes a server-owned, pull-replicated collection (ADR-060), so its
|
|
162
|
+
* versions never transform documents: a version bump drops and resyncs.
|
|
163
|
+
* `createTallyDatabase` drops the old documents, and `startReplication` resets
|
|
164
|
+
* the checkpoint, so the first sync after the bump downloads the collection again.
|
|
72
165
|
*/
|
|
73
166
|
export interface ConnectorSchemas {
|
|
74
167
|
products: RxJsonSchema<any>;
|
|
@@ -122,4 +215,38 @@ export interface TallyConnector {
|
|
|
122
215
|
products?: ReplicationAdapter<any>;
|
|
123
216
|
[key: string]: ReplicationAdapter<any> | undefined;
|
|
124
217
|
};
|
|
218
|
+
|
|
219
|
+
/** Periodic re-reads of state that replication misses (ADR-060) */
|
|
220
|
+
reconcile?: {
|
|
221
|
+
stock?: StockReconcileAdapter;
|
|
222
|
+
ids?: IdReconcileAdapter;
|
|
223
|
+
prices?: FingerprintReconcileAdapter;
|
|
224
|
+
/** Prices the backend calculates for the sales context (price lists, sale dates), which change without a timestamp bump. */
|
|
225
|
+
calculatedPrices?: FingerprintReconcileAdapter;
|
|
226
|
+
/** The daily catalogue check (#248): refetches what differs, deletes only with proof. */
|
|
227
|
+
catalogue?: CatalogueReconcileAdapter;
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Reads the store's own settings (TV4): currency, tax inclusivity, tax
|
|
232
|
+
* rates and a connector-specific pricing context. Read once after
|
|
233
|
+
* sign-in; the app feeds all three consumers from the result. Read-only,
|
|
234
|
+
* never writes to the store (ADR-048).
|
|
235
|
+
*/
|
|
236
|
+
storeSettings?: (context: SyncContext, choice?: StoreSettingsChoice) => Promise<StoreSettings>;
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Re-reads the store's contract capabilities (ADR-062) for a session
|
|
240
|
+
* restored without signing in again — otherwise a restored session would
|
|
241
|
+
* block discounts until the cashier signed in again. `undefined` means
|
|
242
|
+
* the read was inconclusive (offline or a server error), not version 1;
|
|
243
|
+
* see `resolveCapabilities`.
|
|
244
|
+
*/
|
|
245
|
+
capabilities?: (context: SyncContext) => Promise<ServerCapabilities | undefined>;
|
|
246
|
+
/** Customer search: online only; `undefined` when the connector has no customer support. */
|
|
247
|
+
searchCustomers?: (context: SyncContext, query: string, options?: { limit?: number }) => Promise<Customer[]>;
|
|
248
|
+
/** Customer creation: online only; `undefined` when the connector has no customer support. */
|
|
249
|
+
createCustomer?: (context: SyncContext, input: CustomerInput) => Promise<Customer>;
|
|
250
|
+
/** Customer lookup: online only; `undefined` when the connector has no customer support. */
|
|
251
|
+
getCustomer?: (context: SyncContext, id: string) => Promise<Customer | null>;
|
|
125
252
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { CustomerTraits } from './traits/customer';
|
|
2
|
+
|
|
3
|
+
/** A store customer, as the till shows and picks it (programme item 14). Platform-neutral. */
|
|
4
|
+
export interface Customer {
|
|
5
|
+
/** The platform's id: order.create v3 sends it as `customer.customerId`. */
|
|
6
|
+
id: string;
|
|
7
|
+
/** Display name: first + last, else company, else email, else id. Never empty. */
|
|
8
|
+
name: string;
|
|
9
|
+
firstName?: string; lastName?: string; email?: string; phone?: string; company?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** What the till collects to create a customer. v1 requires an email. */
|
|
13
|
+
export interface CustomerInput { email: string; firstName?: string; lastName?: string; phone?: string; company?: string }
|
|
14
|
+
|
|
15
|
+
export const customerTraits: CustomerTraits<Customer> = {
|
|
16
|
+
getId: (customer) => customer.id,
|
|
17
|
+
getName: (customer) => customer.name,
|
|
18
|
+
getEmail: (customer) => customer.email,
|
|
19
|
+
getPhone: (customer) => customer.phone,
|
|
20
|
+
getAddressSummary: () => undefined,
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** A customer call that failed for a reason other than credentials (credentials throw ConnectorUnauthorizedError). */
|
|
24
|
+
export class CustomerServiceError extends Error {
|
|
25
|
+
constructor(readonly code: 'network' | 'server' | 'invalid', message: string) { super(message); this.name = 'CustomerServiceError'; }
|
|
26
|
+
}
|
package/src/types/index.ts
CHANGED
|
@@ -7,10 +7,32 @@ export type {
|
|
|
7
7
|
CollectionSync,
|
|
8
8
|
RemoteIdEntry,
|
|
9
9
|
SyncContext,
|
|
10
|
+
ServerCapabilities,
|
|
11
|
+
TaxRounding,
|
|
10
12
|
} from './connector';
|
|
11
13
|
|
|
12
14
|
export type { ReplicationAdapter } from './replication';
|
|
13
15
|
|
|
14
|
-
export type {
|
|
16
|
+
export type { FingerprintReconcileAdapter, IdReconcileAdapter, StockReconcileAdapter } from './reconcile';
|
|
17
|
+
|
|
18
|
+
export type { StoreSettings, StoreSettingsChoice } from './store-settings';
|
|
19
|
+
export { customerTraits, CustomerServiceError, type Customer, type CustomerInput } from './customers';
|
|
20
|
+
|
|
21
|
+
export type { ProductTraits, TraitContext, VariantSummary } from './traits/product';
|
|
22
|
+
|
|
23
|
+
export type { Money, ProductPrice, ResolvedPrice } from './money';
|
|
24
|
+
|
|
25
|
+
export type { StockLevel, StockStatus } from './stock';
|
|
15
26
|
|
|
16
27
|
export type { CustomerTraits } from './traits/customer';
|
|
28
|
+
|
|
29
|
+
export type {
|
|
30
|
+
CommandType, CommandEnvelope, CommandStatus, CommandServerRefs,
|
|
31
|
+
RegisterCommandType, RegisterCommandEnvelope, AnyCommandEnvelope,
|
|
32
|
+
CommandWarning, CommandError, CommandResult, OrderCreateLine,
|
|
33
|
+
PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
|
|
34
|
+
OrderCreateDisplay, OrderCreateTaxRate,
|
|
35
|
+
CommandBatchRequest, CommandBatchResponse, BatchTooLargeBody,
|
|
36
|
+
RegisterCommandResult, RegisterSessionOpenPayload, RegisterSessionTransitionPayload,
|
|
37
|
+
RegisterMovementRecordPayload, RegisterMovementVoidPayload, RegisterClosureSubmitPayload,
|
|
38
|
+
} from './commands';
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A monetary amount in integer minor units (cents for EUR/USD, yen for JPY)
|
|
3
|
+
* with its ISO 4217 currency code. Integers keep arithmetic exact, and the
|
|
4
|
+
* code travels with the amount so nothing assumes a store-wide currency.
|
|
5
|
+
*/
|
|
6
|
+
export interface Money {
|
|
7
|
+
/** Integer amount in the currency's minor unit, e.g. 1250 for €12.50. */
|
|
8
|
+
amount: number;
|
|
9
|
+
/** Upper-case ISO 4217 code, e.g. 'EUR'. 'XXX' when the backend gives none. */
|
|
10
|
+
currency: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* One entry in a product's price list.
|
|
15
|
+
*
|
|
16
|
+
* `base` is the everyday price. `sale` is a temporary reduction that replaces
|
|
17
|
+
* the base price in the same currency while it applies. Backends express
|
|
18
|
+
* sales differently (WooCommerce sale_price, Medusa sale price lists, Shopify
|
|
19
|
+
* compare_at_price) and each connector maps its own form into these entries,
|
|
20
|
+
* so components never need regular/sale/on-sale flags.
|
|
21
|
+
*/
|
|
22
|
+
export interface ProductPrice extends Money {
|
|
23
|
+
kind: 'base' | 'sale';
|
|
24
|
+
/** Set when the backend says so for this price; it wins over the store-level `pricesIncludeTax`. Undefined: use the store-level setting. */
|
|
25
|
+
taxInclusive?: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The price to charge, and the price it replaces when a sale applies; each keeps its source's `taxInclusive` when set. */
|
|
29
|
+
export interface ResolvedPrice {
|
|
30
|
+
current: Money & { taxInclusive?: boolean };
|
|
31
|
+
/** Set only when a sale price applies: the base price it replaces. */
|
|
32
|
+
was?: Money & { taxInclusive?: boolean };
|
|
33
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { SyncContext } from './connector';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Re-reads stock from the backend, because replication misses stock changes
|
|
5
|
+
* that bump no product timestamp (ADR-060). The runner stores `fetchPages`
|
|
6
|
+
* output in the non-replicated `stock_levels` collection; readers merge it
|
|
7
|
+
* into a read-only view of each product with `overlay`. Nothing is written
|
|
8
|
+
* into the replicated products.
|
|
9
|
+
*/
|
|
10
|
+
export interface StockReconcileAdapter<Doc = any> {
|
|
11
|
+
/** Current stock, one backend request per page, keyed as the connector chooses (variant, inventory item). */
|
|
12
|
+
fetchPages(context: SyncContext): AsyncIterable<Map<string, unknown>>;
|
|
13
|
+
/**
|
|
14
|
+
* Pure: the fields of `doc` that `stock` changes, or undefined when nothing
|
|
15
|
+
* differs. Keys absent from `stock` are left alone. The result is merged
|
|
16
|
+
* into a read-only view of the document and never written.
|
|
17
|
+
*/
|
|
18
|
+
overlay(doc: Doc, stock: Map<string, unknown>): Partial<Doc> | undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 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. */
|
|
22
|
+
export interface IdReconcileAdapter<Doc = any> {
|
|
23
|
+
/** Every live product with its live variant ids, one backend request per page. */
|
|
24
|
+
fetchPages(context: SyncContext): AsyncIterable<Array<{ id: string; variantIds: string[] }>>;
|
|
25
|
+
/** The variant ids a local product document lists. */
|
|
26
|
+
variantIds(doc: Doc): string[];
|
|
27
|
+
/** Hand local documents that disagree with the backend to the collection's pull (see createReconcileFeed). */
|
|
28
|
+
enqueue(entries: Array<{ id: string; local: Doc }>): void;
|
|
29
|
+
/** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
|
|
30
|
+
refetchBatchSize?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Re-delivers products whose remote fingerprint differs from the local one (ADR-060). */
|
|
34
|
+
export interface FingerprintReconcileAdapter<Doc = any> {
|
|
35
|
+
/** Remote fingerprints by product id, one backend request per page. Products the backend doesn't report are left alone. */
|
|
36
|
+
fetchPages(context: SyncContext): AsyncIterable<Map<string, string>>;
|
|
37
|
+
/** The same fingerprint computed from a local product document. */
|
|
38
|
+
fingerprint(doc: Doc): string;
|
|
39
|
+
/**
|
|
40
|
+
* Hands products to the collection's pull (the reconcile feed). `refreshOnly`
|
|
41
|
+
* marks an entry so a missing product is skipped, never tombstoned: only the
|
|
42
|
+
* id reconcile, with its mass-delete brake, may delete.
|
|
43
|
+
*/
|
|
44
|
+
enqueue(entries: Array<{ id: string; local: Doc; refreshOnly?: boolean }>): void;
|
|
45
|
+
/** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
|
|
46
|
+
refetchBatchSize?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** One product in the catalogue listing. `key` is the local primary key value; `remote` is whatever the connector needs to refetch it (a numeric backend id, say). */
|
|
50
|
+
export interface CatalogueReconcileEntry { key: string; fingerprint: string; remote?: unknown }
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The daily catalogue check (#248): one walk that refetches what differs and
|
|
54
|
+
* deletes only with proof. Nothing is written locally: `enqueue` hands
|
|
55
|
+
* documents to the collection's pull (the reconcile feed). `Cursor` must be
|
|
56
|
+
* JSON-serialisable, since the runner persists it to resume a stopped pass.
|
|
57
|
+
*/
|
|
58
|
+
export interface CatalogueReconcileAdapter<Doc = any, Cursor = unknown> {
|
|
59
|
+
/** Remote listing, one backend request per page, from `from` (a cursor this adapter yielded earlier) or the start. */
|
|
60
|
+
fetchPages(context: SyncContext, from?: Cursor): AsyncIterable<{ entries: CatalogueReconcileEntry[]; cursor: Cursor }>;
|
|
61
|
+
/** Pure: the same fingerprint from a local document. */
|
|
62
|
+
fingerprint(doc: Doc): string;
|
|
63
|
+
/**
|
|
64
|
+
* Deletion proof, required: of these local documents (the ones the listing did not name), the keys
|
|
65
|
+
* the backend confirms gone (absent, or no longer sellable). One or more requests. Only confirmed
|
|
66
|
+
* keys are tombstoned; an adapter that never deletes returns none.
|
|
67
|
+
*/
|
|
68
|
+
confirmGone(locals: Doc[], context: SyncContext): Promise<string[]>;
|
|
69
|
+
/** Hand documents to the collection's pull (the reconcile feed). */
|
|
70
|
+
enqueue(entries: Array<{ key: string; local?: Doc; remote?: unknown; tombstone?: boolean }>): void;
|
|
71
|
+
/** Ids per `fetchByIds` request of the feed this adapter enqueues into: a page's `n` refetches take `ceil(n / refetchBatchSize)` budget slots (1 when unset). */
|
|
72
|
+
refetchBatchSize?: number;
|
|
73
|
+
}
|
package/src/types/replication.ts
CHANGED
|
@@ -26,6 +26,18 @@ export interface ReplicationAdapter<RxDocType, CheckpointType = any> {
|
|
|
26
26
|
checkpoint: CheckpointType;
|
|
27
27
|
}>;
|
|
28
28
|
|
|
29
|
+
/**
|
|
30
|
+
* Documents per pull page, passed to handler as batchSize. RxDB treats a
|
|
31
|
+
* shorter page as the end of the cycle. Defaults to RxDB's 100.
|
|
32
|
+
*/
|
|
33
|
+
batchSize?: number;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Fresh install only: the checkpoint this feed starts from instead of a full first pass,
|
|
37
|
+
* read before any feed runs (combinePullAdapters). Absent: a full first pass, as today.
|
|
38
|
+
*/
|
|
39
|
+
seedCheckpoint?: (context: SyncContext) => Promise<CheckpointType>;
|
|
40
|
+
|
|
29
41
|
/**
|
|
30
42
|
* Optional real-time event stream.
|
|
31
43
|
* Emit { documents, checkpoint } for live updates,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backend-neutral stock state.
|
|
3
|
+
*
|
|
4
|
+
* - `in_stock`: sellable now. `quantity` is set when the backend tracks it.
|
|
5
|
+
* - `out_of_stock`: tracked and none left; not sellable.
|
|
6
|
+
* - `backorder`: none left but the backend accepts orders anyway.
|
|
7
|
+
* - `unknown`: the backend did not say.
|
|
8
|
+
*
|
|
9
|
+
* `quantity` is undefined when stock is not tracked, which is different from
|
|
10
|
+
* a tracked quantity of 0.
|
|
11
|
+
*/
|
|
12
|
+
export type StockStatus = 'in_stock' | 'out_of_stock' | 'backorder' | 'unknown';
|
|
13
|
+
|
|
14
|
+
export interface StockLevel {
|
|
15
|
+
status: StockStatus;
|
|
16
|
+
/** Units on hand, when tracked. May be negative on backorder. */
|
|
17
|
+
quantity?: number;
|
|
18
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { TaxRounding } from './connector';
|
|
2
|
+
|
|
3
|
+
/** What the POS needs from the store's own settings (TV4). Read once after sign-in; the app feeds all three consumers from it. */
|
|
4
|
+
export interface StoreSettings {
|
|
5
|
+
/** ISO 4217, upper case (the currency prices are sold in). */
|
|
6
|
+
currency: string;
|
|
7
|
+
/** Whether the store's catalogue prices include tax. It feeds both the connector's traits and the POS TaxProvider, so the two cannot disagree. */
|
|
8
|
+
pricesIncludeTax: boolean;
|
|
9
|
+
/** 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. */
|
|
10
|
+
taxRatesPpm: { default: number; [taxClass: string]: number };
|
|
11
|
+
/** 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. */
|
|
12
|
+
pricingContext?: Record<string, string>;
|
|
13
|
+
/** Derived, never read by `storeSettings`: the store's `ServerCapabilities.taxRounding`, which `useStoreSettings` fills in (#324). */
|
|
14
|
+
taxRounding?: TaxRounding;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Picks among several regions, countries or sales channels when the store has more than one.
|
|
19
|
+
* The app persists the choice per store, in its own settings, so it is asked once. A stored
|
|
20
|
+
* choice that no longer resolves (for example, the region was deleted) raises `choice_required`
|
|
21
|
+
* again instead of failing. Backends without the concept ignore a field.
|
|
22
|
+
*/
|
|
23
|
+
export interface StoreSettingsChoice {
|
|
24
|
+
region?: string;
|
|
25
|
+
country?: string;
|
|
26
|
+
channel?: string;
|
|
27
|
+
}
|