@tallyui/connector-woocommerce 3.20.1 → 4.0.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/connector-woocommerce",
3
- "version": "3.20.1",
3
+ "version": "4.0.1",
4
4
  "type": "module",
5
5
  "description": "WooCommerce connector for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -27,15 +27,14 @@
27
27
  "directory": "connectors/woocommerce"
28
28
  },
29
29
  "peerDependencies": {
30
- "@tallyui/core": "^3.20.1"
30
+ "@tallyui/core": "^4.0.1"
31
31
  },
32
32
  "devDependencies": {
33
- "@tallyui/database": "3.20.1",
33
+ "@tallyui/database": "4.0.1",
34
34
  "rxdb": "17.5.0"
35
35
  },
36
36
  "scripts": {
37
37
  "build": "tsup",
38
- "typecheck": "tsc --noEmit",
39
- "test": "echo \"no tests yet\""
38
+ "typecheck": "tsc --noEmit"
40
39
  }
41
40
  }
@@ -0,0 +1,184 @@
1
+ // Woo 24: the store's Z closures against WCPOS 2.0.4 (API/V2/Closures_Controller.php, Services/Closure_Store.php), ADR-093.
2
+ import { ConnectorUnauthorizedError, minorUnitDigits, type ClosureReads, type Correction, type StoreClosure, type SyncContext } from '@tallyui/core';
3
+ import { wooDecimal, wooSignedMinor } from './commands/register-transport';
4
+ import { wooStoreCurrency } from './registers';
5
+ import { throwIfUnauthorized } from './unauthorized';
6
+
7
+ type Row = Record<string, unknown>;
8
+
9
+ // Closure_Store::tenders (v2.0.4 Services/Closure_Store.php:537-551).
10
+ const TENDER_KEY = /^[a-zA-Z0-9_-]{1,191}$/;
11
+ // Closure_Store ROW times are `YYYY-MM-DD HH:MM:SS` in UTC (Closure_Store.php:37-76).
12
+ const STORE_TIME = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/;
13
+
14
+ const isRow = (value: unknown): value is Row => typeof value === 'object' && value !== null && !Array.isArray(value);
15
+ const unexpected = () => new Error('WooCommerce closures: unexpected body');
16
+
17
+ function request(context: SyncContext, path: string, body?: Record<string, unknown>): Promise<Response> {
18
+ const init: RequestInit = body
19
+ ? { method: 'POST', headers: { 'Content-Type': 'application/json', ...context.headers }, body: JSON.stringify(body), signal: context.signal }
20
+ : { method: 'GET', headers: context.headers, signal: context.signal };
21
+ return (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/${path}`, init);
22
+ }
23
+
24
+ const errorCode = (response: Response): Promise<string | undefined> =>
25
+ response.json().then((body) => (typeof body?.code === 'string' ? body.code : undefined), () => undefined);
26
+
27
+ function amount(value: unknown, currency: string, field: string): number {
28
+ const minor = wooSignedMinor(value, currency);
29
+ if (minor === undefined) throw new Error(`WooCommerce closures: bad amount ${field}`);
30
+ return minor;
31
+ }
32
+
33
+ function tenders(value: unknown, currency: string, field: string): Record<string, number> {
34
+ // PHP encodes an empty tender map as `[]`.
35
+ if (Array.isArray(value) && value.length === 0) return {};
36
+ if (!isRow(value)) throw new Error(`WooCommerce closures: bad amount ${field}`);
37
+ return Object.fromEntries(Object.entries(value).map(([tender, text]) => [tender, amount(text, currency, `${field}.${tender}`)]));
38
+ }
39
+
40
+ const storeTime = (value: string) => value.replace(STORE_TIME, '$1T$2Z');
41
+
42
+ // Correction rows: Closure_Store::corrections_for (v2.0.4 Closure_Store.php:402-416).
43
+ function toCorrection(row: unknown, currency: string): Correction {
44
+ if (!isRow(row) || typeof row.id !== 'number' || !isRow(row.actor) || !isRow(row.figures)) throw unexpected();
45
+ const figures: Correction['figures'] = {};
46
+ for (const key of ['expected_delta', 'counted', 'variance'] as const)
47
+ if (row.figures[key] != null) figures[key] = tenders(row.figures[key], currency, key);
48
+ for (const key of ['cash_delta', 'sales_delta', 'refunds_delta'] as const)
49
+ if (row.figures[key] != null) figures[key] = amount(row.figures[key], currency, key);
50
+ const approver = isRow(row.approver) ? { id: String(row.approver.id), name: String(row.approver.name) } : null;
51
+ return {
52
+ id: row.id, type: row.type as Correction['type'], created_at: row.created_at as string,
53
+ actor: { id: String(row.actor.id), name: String(row.actor.name) }, approver, reason: row.reason as string, figures,
54
+ };
55
+ }
56
+
57
+ // Closure rows: Closure_Store ROW and INTEGERS (v2.0.4 Closure_Store.php:37-79). visible() (Closures_Controller.php:109-121)
58
+ // removes the figures a blind cashier may not see, so an absent or null key leaves its field absent, never 0.
59
+ function toClosure(row: unknown, currency: string): StoreClosure {
60
+ if (!isRow(row) || typeof row.id !== 'string' || typeof row.register_id !== 'string' || typeof row.session_id !== 'string'
61
+ || typeof row.number !== 'number' || typeof row.opened_at_gmt !== 'string' || typeof row.closed_at_gmt !== 'string') throw unexpected();
62
+ const closure: StoreClosure = {
63
+ id: row.id, number: row.number, registerId: row.register_id, sessionId: row.session_id,
64
+ reason: typeof row.reason === 'string' ? row.reason : 'end_of_day',
65
+ openedAt: storeTime(row.opened_at_gmt), closedAt: storeTime(row.closed_at_gmt),
66
+ printCount: typeof row.print_count === 'number' ? row.print_count : 0,
67
+ unsyncedCount: typeof row.unsynced_count === 'number' ? row.unsynced_count : 0,
68
+ };
69
+ const map = (key: string) => (row[key] == null ? undefined : tenders(row[key], currency, key));
70
+ const total = (key: string) => (row[key] == null ? undefined : amount(row[key], currency, key));
71
+ const optional: Partial<StoreClosure> = {
72
+ storeId: typeof row.store_id === 'number' ? String(row.store_id) : undefined,
73
+ businessDay: typeof row.business_day === 'string' ? row.business_day : undefined,
74
+ printedAt: typeof row.printed_at_gmt === 'string' ? storeTime(row.printed_at_gmt) : undefined,
75
+ lastPrintedAt: typeof row.last_printed_at_gmt === 'string' ? storeTime(row.last_printed_at_gmt) : undefined,
76
+ expected: map('expected'), tillExpected: map('till_expected'), counted: map('counted'), variance: map('variance'),
77
+ periodSalesTotalMinor: total('period_sales_total'), periodRefundsTotalMinor: total('period_refunds_total'),
78
+ perpetualSalesTotalMinor: total('perpetual_sales_total'), perpetualRefundsTotalMinor: total('perpetual_refunds_total'),
79
+ unsyncedTotalMinor: total('unsynced_total'),
80
+ correctionsCount: typeof row.corrections_count === 'number' ? row.corrections_count : undefined,
81
+ corrections: Array.isArray(row.corrections) ? row.corrections.map((correction) => toCorrection(correction, currency)) : undefined,
82
+ };
83
+ for (const [key, value] of Object.entries(optional)) if (value !== undefined) Object.assign(closure, { [key]: value });
84
+ return closure;
85
+ }
86
+
87
+ /** A closures read: the parsed body, or `null` for a 404. */
88
+ async function read(context: SyncContext, path: string): Promise<unknown> {
89
+ const response = await request(context, path);
90
+ // Reads need view_woocommerce_pos_reports (Closures_Controller.php:79-81).
91
+ throwIfUnauthorized(response, 'closures');
92
+ if (response.status === 404) return null;
93
+ if (!response.ok) throw new Error(`WooCommerce closures: HTTP ${response.status}`);
94
+ return response.json().catch(() => { throw unexpected(); });
95
+ }
96
+
97
+ // The route is read before `stores`, so a store without it never needs `stores`; recount passes the currency it holds.
98
+ async function getClosure(context: SyncContext, id: string, currency?: string): Promise<StoreClosure | null> {
99
+ const body = await read(context, `closures/${encodeURIComponent(id)}`);
100
+ return body === null ? null : toClosure(body, currency ?? await wooStoreCurrency(context));
101
+ }
102
+
103
+ export const wooClosures: ClosureReads = {
104
+ async list(context, query = {}) {
105
+ // per_page defaults to 50 and anything above 100 is a 400 (list_args :381, Closure_Store.php:23).
106
+ const perPage = Math.min(query.perPage ?? 50, 100);
107
+ const params = new URLSearchParams();
108
+ if (query.registerId !== undefined) params.set('register_id', query.registerId);
109
+ if (query.after !== undefined) params.set('after', query.after);
110
+ if (query.before !== undefined) params.set('before', query.before);
111
+ if (query.page !== undefined) params.set('page', String(query.page));
112
+ params.set('per_page', String(perPage));
113
+ // Below 2.0 the store has no closures route (404).
114
+ const body = await read(context, `closures?${params}`);
115
+ if (body === null) return { items: [], hasMore: false };
116
+ if (!Array.isArray(body)) throw unexpected();
117
+ const currency = await wooStoreCurrency(context);
118
+ // The list sends no paging header (Closures_Controller.php:209), so a full page means there may be more.
119
+ return { items: body.map((row) => toClosure(row, currency)), hasMore: body.length === perPage };
120
+ },
121
+
122
+ async get(context, id) {
123
+ // Only GET closures/{id} carries `corrections` (Closures_Controller.php:173-175).
124
+ return getClosure(context, id);
125
+ },
126
+
127
+ async last(context, registerId) {
128
+ // Needs register_id; with no closure the store answers 200 with `null` (Closures_Controller.php:187-207).
129
+ const body = await read(context, `closures/last?${new URLSearchParams({ register_id: registerId })}`);
130
+ return body === null ? null : toClosure(body, await wooStoreCurrency(context));
131
+ },
132
+
133
+ async recount(context, id, input) {
134
+ const { correctionId, counted, reason, approval } = input;
135
+ // The store needs `cash` and unsigned decimals under tender keys (Closure_Store::tenders, :537-551).
136
+ if (!Object.hasOwn(counted, 'cash')
137
+ || !Object.entries(counted).every(([tender, minor]) => TENDER_KEY.test(tender) && Number.isInteger(minor) && minor >= 0)) {
138
+ throw new Error('WooCommerce closure recount: invalid counted');
139
+ }
140
+ // Unlike the reads, `stores` comes first here: `counted` is encoded with the currency's digits before the POST.
141
+ const currency = await wooStoreCurrency(context);
142
+ const digits = minorUnitDigits(currency);
143
+ const response = await request(context, `closures/${encodeURIComponent(id)}/recount`, {
144
+ id: correctionId,
145
+ counted: Object.fromEntries(Object.entries(counted).map(([tender, minor]) => [tender, wooDecimal(minor, digits)])),
146
+ reason,
147
+ ...(approval ? { approval: { username: approval.username, password: approval.password } } : {}),
148
+ });
149
+ if (response.status === 200 || response.status === 201) {
150
+ // The POST answers with the fiscal record, not the closure (Closure_Store.php:1010-1048), so read the closure back.
151
+ // A retry with the same correctionId is safe: the fiscal table is UNIQUE(type, source_id) (Fiscal_Record_Store.php:89).
152
+ try {
153
+ const closure = await getClosure(context, id, currency);
154
+ return closure ? { closure } : { refused: 'not_found' };
155
+ } catch (error) {
156
+ // The recount stands; this user may not read closures (Closures_Controller.php:79-81).
157
+ if (error instanceof ConnectorUnauthorizedError && error.status === 403) return {};
158
+ throw error;
159
+ }
160
+ }
161
+ const code = await errorCode(response);
162
+ // Refusals: permissions_check (:72-76, :92) and the approval check in dispatch (:137-146).
163
+ if (response.status === 403 && code === 'rest_forbidden' && !approval) return { refused: 'approval_required' };
164
+ if (response.status === 403 && code === 'wcpos_recount_approval_invalid') return { refused: 'approval_invalid' };
165
+ if (response.status === 403 && code === 'wcpos_recount_approval_forbidden') return { refused: 'approval_forbidden' };
166
+ if (response.status === 404) return { refused: 'not_found' };
167
+ throwIfUnauthorized(response, 'closure recount');
168
+ throw new Error(`WooCommerce closure recount: HTTP ${response.status}${code ? ` ${code}` : ''}`);
169
+ },
170
+
171
+ async markPrinted(context, id) {
172
+ // Like recount, `stores` comes first: the store counts every print (Closure_Store.php:1063), so a failed `stores` read must send no print.
173
+ const currency = await wooStoreCurrency(context);
174
+ // Answers with the closure row after recording the print (Closures_Controller.php:156-165).
175
+ const response = await request(context, `closures/${encodeURIComponent(id)}/print`, {});
176
+ if (response.status === 200) return toClosure(await response.json().catch(() => { throw unexpected(); }), currency);
177
+ const code = await errorCode(response);
178
+ // A print needs manage_woocommerce_pos_cash and view_woocommerce_pos_reports (Closures_Controller.php:77-86).
179
+ if (response.status === 403 && code === 'rest_forbidden') return { refused: 'forbidden' };
180
+ if (response.status === 404) return { refused: 'not_found' };
181
+ if (response.status === 401) throwIfUnauthorized(response, 'closure print');
182
+ throw new Error(`WooCommerce closure print: HTTP ${response.status}`);
183
+ },
184
+ };
@@ -0,0 +1,37 @@
1
+ import type { WooTransportOutcome } from './transport';
2
+
3
+ export type Answer = { status: number; body?: Awaited<ReturnType<Response['json']>>; retryAfter?: string | null; aborted: boolean };
4
+
5
+ /** One JSON request to the store, and the retry outcome for an answer: shared by the order and register transports. */
6
+ export function createWooCall(options: {
7
+ baseUrl: string;
8
+ getHeaders: () => Record<string, string> | Promise<Record<string, string>>;
9
+ fetch?: typeof globalThis.fetch;
10
+ timeoutMs?: number;
11
+ }): { call(path: string, init: { method: string; body?: unknown }): Promise<Answer>; retry(answer: Answer, reason: string): WooTransportOutcome } {
12
+ const fetch = options.fetch ?? globalThis.fetch;
13
+ let baseUrl = options.baseUrl;
14
+ while (baseUrl.endsWith('/')) baseUrl = baseUrl.slice(0, -1);
15
+ const call = async (path: string, init: { method: string; body?: unknown }): Promise<Answer> => {
16
+ const controller = new AbortController();
17
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 30000);
18
+ try {
19
+ const response = await fetch(`${baseUrl}/${path}`, { method: init.method,
20
+ headers: { ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...await options.getHeaders() },
21
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }), signal: controller.signal });
22
+ let body;
23
+ try { body = await response.json(); } catch { /* not JSON: body stays undefined */ }
24
+ return { status: response.status, body, retryAfter: response.headers.get('Retry-After'), aborted: controller.signal.aborted };
25
+ } catch {
26
+ return { status: 0, aborted: controller.signal.aborted };
27
+ } finally {
28
+ clearTimeout(timeout);
29
+ }
30
+ };
31
+ const retry = (answer: Answer, reason: string): WooTransportOutcome => {
32
+ if (answer.status === 0) return { kind: 'retry', reason: answer.aborted ? 'timeout' : 'network' };
33
+ const seconds = answer.retryAfter == null ? NaN : Number(answer.retryAfter);
34
+ return { kind: 'retry', reason, ...(Number.isFinite(seconds) && seconds >= 0 ? { retryAfterMs: seconds * 1000 } : {}) };
35
+ };
36
+ return { call, retry };
37
+ }
@@ -0,0 +1,212 @@
1
+ // Woo 23: register commands against WCPOS 2.0.4's routes (API/V2/Sessions_Controller.php:38-56, Closures_Controller.php:215-241).
2
+ import { minorUnitDigits, type ApproverCredentials, type CommandResult, type RegisterClosureSubmitPayload, type RegisterCommandEnvelope, type RegisterCommandResult,
3
+ type RegisterMovementRecordPayload, type RegisterMovementVoidPayload, type RegisterSessionOpenPayload,
4
+ type RegisterSessionTransitionPayload, type SyncContext } from '@tallyui/core';
5
+ import { wooThresholdMinor } from '../store-settings';
6
+ import { throwIfUnauthorized } from '../unauthorized';
7
+ import { createWooCall, type Answer } from './http';
8
+ import { wooMinorFromDecimal, type WooCommandTransportOptions, type WooTransportOutcome } from './transport';
9
+
10
+ export interface WooRegisterTransportOptions extends Pick<WooCommandTransportOptions, 'baseUrl' | 'getHeaders' | 'fetch' | 'timeoutMs'> {
11
+ /** The store currency, read once per `send`. */
12
+ currency: string | (() => string | Promise<string>);
13
+ }
14
+
15
+ // Closure_Store::tenders (v2.0.4 Services/Closure_Store.php:537-551).
16
+ const TENDER_KEY = /^[a-zA-Z0-9_-]{1,191}$/;
17
+
18
+ /** A whole minor amount as a decimal string at `digits`, by string slicing (no float maths). */
19
+ export function wooDecimal(minor: number, digits: number): string {
20
+ const text = String(Math.abs(minor)).padStart(digits + 1, '0');
21
+ return `${minor < 0 ? '-' : ''}${digits ? `${text.slice(0, -digits)}.${text.slice(-digits)}` : text}`;
22
+ }
23
+
24
+ /** A store decimal, with an optional leading `-`, as minor. */
25
+ export function wooSignedMinor(value: unknown, currency: string): number | undefined {
26
+ if (typeof value !== 'string') return undefined;
27
+ const text = value.trim();
28
+ if (!text.startsWith('-')) return wooMinorFromDecimal(text, currency);
29
+ const minor = wooMinorFromDecimal(text.slice(1), currency);
30
+ return minor === undefined ? undefined : 0 - minor;
31
+ }
32
+
33
+ /** A tender map as decimals; the store needs `cash`, so a map without it gets cash at zero. */
34
+ function wooTenders(map: Record<string, number>, digits: number): Record<string, string> {
35
+ return Object.fromEntries(Object.entries({ cash: 0, ...map }).map(([key, minor]) => [key, wooDecimal(minor, digits)]));
36
+ }
37
+
38
+ function rejected(id: string, code: string, message: unknown, data?: Record<string, unknown>): CommandResult {
39
+ return { id, status: 'rejected', error: { code, message: typeof message === 'string' && message ? message : code, ...(data ? { data } : {}) } };
40
+ }
41
+
42
+ function storeCode(answer: Answer): Record<string, unknown> | undefined {
43
+ return typeof answer.body?.code === 'string' ? { storeCode: answer.body.code } : undefined;
44
+ }
45
+
46
+ function sessionResult(id: unknown, status: unknown): RegisterCommandResult {
47
+ const known = status === 'open' || status === 'counting' || status === 'closed';
48
+ return { session: { id: String(id), ...(known ? { status } : {}) } as NonNullable<RegisterCommandResult['session']> };
49
+ }
50
+
51
+ export function createWooRegisterTransport(options: WooRegisterTransportOptions): {
52
+ send(batch: RegisterCommandEnvelope[]): Promise<WooTransportOutcome>;
53
+ } {
54
+ const { call, retry } = createWooCall(options);
55
+ const post = (path: string, body: Record<string, unknown>) => call(path, { method: 'POST', body });
56
+
57
+ // The answers every request shares; undefined leaves the status to its command.
58
+ const shared = (answer: Answer, id: string): CommandResult | WooTransportOutcome | undefined => {
59
+ const { status, body } = answer;
60
+ if (status === 0) return retry(answer, 'network');
61
+ if (status === 401 || (status === 403 && body?.code === 'rest_forbidden')) return { kind: 'unauthorized' };
62
+ if (status === 426) return { kind: 'refused', status, reason: typeof body?.code === 'string' ? body.code : 'update_required' };
63
+ if (status === 400) return rejected(id, 'invalid_payload', body?.message, storeCode(answer));
64
+ return undefined;
65
+ };
66
+
67
+ const sendOne = async (envelope: RegisterCommandEnvelope, currency: string): Promise<CommandResult | WooTransportOutcome> => {
68
+ const id = envelope.id, digits = minorUnitDigits(currency);
69
+ const decimal = (minor: number) => wooDecimal(minor, digits);
70
+ const answered = (answer: Answer, own: (answer: Answer) => CommandResult | undefined) =>
71
+ shared(answer, id) ?? own(answer) ?? retry(answer, `status_${answer.status}`);
72
+
73
+ switch (envelope.type) {
74
+ case 'register.session.open': {
75
+ const p = envelope.payload as unknown as RegisterSessionOpenPayload;
76
+ return answered(await post('sessions', {
77
+ id: p.sessionId, register_id: p.registerId, opened_at: p.openedAt, counted_float: decimal(p.countedFloatMinor),
78
+ ...(typeof p.expectedFloatMinor === 'number' ? { expected_float: decimal(p.expectedFloatMinor) } : {}),
79
+ ...(typeof p.businessDay === 'string' && p.businessDay ? { business_day: p.businessDay } : {}),
80
+ }), (answer) => {
81
+ const { status, body } = answer;
82
+ if (status === 201 || status === 200) return { id, status: 'applied', register: sessionResult(body?.id, body?.status) };
83
+ if (status === 409 && body?.code === 'wcpos_session_already_open') {
84
+ return rejected(id, 'register_session_already_open', body?.message,
85
+ { sessionId: typeof body?.data?.session_id === 'string' ? body.data.session_id : p.sessionId });
86
+ }
87
+ if (status === 409) return rejected(id, 'register_session_open_refused', body?.message, storeCode(answer));
88
+ return undefined;
89
+ });
90
+ }
91
+ case 'register.session.transition': {
92
+ const p = envelope.payload as unknown as RegisterSessionTransitionPayload;
93
+ // The store closes a session only through its closure (`register.closure.submit`).
94
+ if (p.status === 'closed') return { id, status: 'applied' };
95
+ return answered(await post(`sessions/${p.sessionId}/status`, { status: p.status, at: p.at }), (answer) => {
96
+ if (answer.status === 200) return { id, status: 'applied', register: sessionResult(answer.body?.id, answer.body?.status) };
97
+ if (answer.status === 409) return rejected(id, 'register_session_transition_refused', answer.body?.message, storeCode(answer));
98
+ if (answer.status === 404) return rejected(id, 'register_session_unknown', answer.body?.message);
99
+ return undefined;
100
+ });
101
+ }
102
+ case 'register.movement.record':
103
+ case 'register.movement.void': {
104
+ let body: Record<string, unknown>;
105
+ if (envelope.type === 'register.movement.record') {
106
+ const p = envelope.payload as unknown as RegisterMovementRecordPayload;
107
+ if (!Number.isSafeInteger(p.amountMinor) || p.amountMinor < 0) {
108
+ return rejected(id, 'invalid_payload', 'A cash movement amount must be a whole number of minor units, 0 or more.');
109
+ }
110
+ body = { id: p.movementId, session_id: p.sessionId, type: p.type, amount: decimal(p.amountMinor), reason: p.reason, created_at: p.createdAt };
111
+ } else {
112
+ const p = envelope.payload as unknown as RegisterMovementVoidPayload;
113
+ body = { id: p.movementId, session_id: p.sessionId, type: 'void', amount: '0', reason: '', voids: p.voids, created_at: p.createdAt };
114
+ }
115
+ return answered(await post('movements', body), (answer) => {
116
+ if (answer.status === 201 || answer.status === 200) return { id, status: 'applied' };
117
+ if (answer.status === 409) return rejected(id, 'register_movement_refused', answer.body?.message, storeCode(answer));
118
+ return undefined;
119
+ });
120
+ }
121
+ case 'register.closure.submit': {
122
+ const p = envelope.payload as unknown as RegisterClosureSubmitPayload;
123
+ const keys = [...Object.keys(p.tillExpected), ...Object.keys(p.counted)];
124
+ if (keys.some((key) => !TENDER_KEY.test(key)) || Object.values(p.counted).some((minor) => minor < 0)) {
125
+ return rejected(id, 'invalid_payload', 'A closure tender must be named with letters, digits, _ or -, and counted at 0 or more.');
126
+ }
127
+ const counting = await post(`sessions/${p.sessionId}/status`, { status: 'counting', at: p.closedAt });
128
+ if (counting.status !== 200 && counting.status !== 409) {
129
+ return answered(counting, (answer) => answer.status === 404 ? rejected(id, 'register_session_unknown', answer.body?.message) : undefined);
130
+ }
131
+ return answered(await post('closures', {
132
+ id: p.closureId, session_id: p.sessionId, number: p.number, opened_at: p.openedAt, closed_at: p.closedAt,
133
+ ...(typeof p.businessDay === 'string' && p.businessDay ? { business_day: p.businessDay } : {}),
134
+ software_version: p.softwareVersion, breakdowns: {},
135
+ till_expected: wooTenders(p.tillExpected, digits), counted: wooTenders(p.counted, digits),
136
+ period_sales_total: decimal(p.periodSalesTotalMinor), period_refunds_total: decimal(p.periodRefundsTotalMinor),
137
+ perpetual_sales_total: decimal(p.perpetualSalesTotalMinor), perpetual_refunds_total: decimal(p.perpetualRefundsTotalMinor),
138
+ unsynced_total: decimal(p.unsyncedTotalMinor), unsynced_count: p.unsyncedCount,
139
+ }), (answer) => {
140
+ const { status, body } = answer;
141
+ // The store may renumber the closure (Closure_Store.php:724-760), so its number is the one carried.
142
+ if (status === 201 || status === 200) {
143
+ return { id, status: 'applied', register: { session: { id: p.sessionId, status: 'closed' },
144
+ closure: { serverClosureId: String(body?.id), number: body?.number } } };
145
+ }
146
+ if (status === 404) return rejected(id, 'register_session_unknown', body?.message, storeCode(answer));
147
+ if (status === 403 && body?.code === 'wcpos_override_refused') {
148
+ const variance = wooSignedMinor(body?.data?.variance, currency);
149
+ const thresholdMinor = wooThresholdMinor(body?.data?.threshold, currency);
150
+ return variance === undefined || typeof body?.data?.variance !== 'string'
151
+ ? rejected(id, 'register_approval_invalid', body?.message, { reason: 'unknown' })
152
+ : rejected(id, 'register_approval_required', body?.message, { sessionId: p.sessionId, thresholdMinor, variance: { cash: variance } });
153
+ }
154
+ if (status === 409 && body?.code === 'wcpos_closure_exists') return rejected(id, 'register_closure_exists', body?.message);
155
+ if (status === 409 && body?.code === 'wcpos_closure_number_invalid') return rejected(id, 'register_closure_number_invalid', body?.message);
156
+ if (status === 409) return rejected(id, 'register_closure_refused', body?.message, storeCode(answer));
157
+ return undefined;
158
+ });
159
+ }
160
+ default:
161
+ return rejected(id, 'invalid_payload', `unsupported register command ${String(envelope.type)}`);
162
+ }
163
+ };
164
+
165
+ return {
166
+ async send(batch) {
167
+ if (batch.length === 0) return { kind: 'results', results: [] };
168
+ const currency = typeof options.currency === 'function' ? await options.currency() : options.currency;
169
+ const results: CommandResult[] = [];
170
+ for (const envelope of batch) {
171
+ const outcome = await sendOne(envelope, currency);
172
+ if ('kind' in outcome) return results.length ? { kind: 'results', results } : outcome;
173
+ results.push(outcome);
174
+ }
175
+ return { kind: 'results', results };
176
+ },
177
+ };
178
+ }
179
+
180
+ /** Asks WCPOS 2.0.4 to approve a counted session (Sessions_Controller.php:309-325): the session is moved to counting first. */
181
+ export async function wooApproveSession(context: SyncContext, input: {
182
+ sessionId: string; credentials: ApproverCredentials; counted: Record<string, number>; currency: string;
183
+ }): Promise<{ approval: string; approvedBy: string } | { refused: 'override_refused' | 'not_counting' }> {
184
+ const post = async (path: string, body: Record<string, unknown>) => {
185
+ const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/${path}`, {
186
+ method: 'POST', headers: { 'Content-Type': 'application/json', ...context.headers }, body: JSON.stringify(body), signal: context.signal,
187
+ });
188
+ let json;
189
+ try { json = await response.json(); } catch { /* not JSON: body stays undefined */ }
190
+ return { response, body: json };
191
+ };
192
+ const fail = (response: Response): never => {
193
+ throwIfUnauthorized(response, 'approve');
194
+ throw new Error(`WooCommerce approve: HTTP ${response.status}`);
195
+ };
196
+ const counting = await post(`sessions/${input.sessionId}/status`, { status: 'counting', at: new Date().toISOString() });
197
+ if (counting.response.status === 404) return { refused: 'not_counting' };
198
+ if (counting.response.status !== 200 && counting.response.status !== 409) fail(counting.response);
199
+ const counted = wooTenders(input.counted, minorUnitDigits(input.currency));
200
+ const { response, body } = await post(`sessions/${input.sessionId}/approve`,
201
+ { username: input.credentials.username, password: input.credentials.password, counted });
202
+ if (response.status === 403) return { refused: 'override_refused' };
203
+ if (response.status === 404 || response.status === 409) return { refused: 'not_counting' };
204
+ if (response.status !== 200) fail(response);
205
+ const approved = body?.approved_counted, approvedBy = body?.approved_by;
206
+ const expected = { cash: 0, ...input.counted };
207
+ const matches = approved !== null && typeof approved === 'object' && !Array.isArray(approved)
208
+ && Object.keys(approved).length === Object.keys(expected).length
209
+ && Object.entries(expected).every(([key, minor]) => wooSignedMinor(approved[key], input.currency) === minor);
210
+ if (typeof approvedBy !== 'number' || !Number.isInteger(approvedBy) || !matches) return { refused: 'override_refused' };
211
+ return { approval: `wcpos-approve:${input.sessionId}:${approvedBy}`, approvedBy: String(approvedBy) };
212
+ }