@tallyui/connector-medusa 1.0.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/README.md +7 -0
- package/dist/index.d.ts +144 -10
- package/dist/index.js +738 -75
- package/package.json +13 -4
- package/src/capabilities.ts +35 -0
- package/src/customers.ts +69 -0
- package/src/index.ts +154 -32
- package/src/pricing/calculated.ts +58 -0
- package/src/reconcile/calculated-prices.ts +44 -0
- package/src/reconcile/ids.ts +58 -0
- package/src/reconcile/prices.ts +73 -0
- package/src/reconcile/stock.ts +58 -0
- package/src/replication/products.ts +92 -56
- package/src/replication/variant-feed.ts +119 -0
- package/src/schemas/products.ts +54 -2
- package/src/store-settings.ts +115 -0
- package/src/sync/products.ts +2 -1
- package/src/traits/product.ts +133 -9
- package/src/__tests__/product-traits.test.ts +0 -260
- package/src/replication/products.test.ts +0 -169
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/connector-medusa",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0-next.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "MedusaJS v2 connector for Tally UI",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -15,14 +15,23 @@
|
|
|
15
15
|
},
|
|
16
16
|
"files": [
|
|
17
17
|
"dist",
|
|
18
|
-
"src"
|
|
18
|
+
"src",
|
|
19
|
+
"!src/**/*.test.ts",
|
|
20
|
+
"!src/**/*.test.tsx",
|
|
21
|
+
"!src/**/*.fixture.json"
|
|
19
22
|
],
|
|
20
23
|
"license": "MIT",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/TallyUI/tallyui.git",
|
|
27
|
+
"directory": "connectors/medusa"
|
|
28
|
+
},
|
|
21
29
|
"peerDependencies": {
|
|
22
|
-
"@tallyui/core": "0.
|
|
30
|
+
"@tallyui/core": "^3.0.0-next.0"
|
|
23
31
|
},
|
|
24
32
|
"devDependencies": {
|
|
25
|
-
"
|
|
33
|
+
"@tallyui/database": "3.0.0-next.0",
|
|
34
|
+
"rxdb": "17.5.0"
|
|
26
35
|
},
|
|
27
36
|
"scripts": {
|
|
28
37
|
"build": "tsup",
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { parseInfoCapabilities, SignInError, type ServerCapabilities } from '@tallyui/core';
|
|
2
|
+
|
|
3
|
+
/** Path of Medusa's own contract-capability endpoint (ADR-062), relative to the backend's base URL. */
|
|
4
|
+
export const CAPABILITIES_PATH = '/tally/v1/info';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Reads the store's contract capabilities (ADR-062) and `taxRounding` (#287), with the
|
|
8
|
+
* connector's usual injectable `fetch`. A 2xx gives `parseInfoCapabilities`; a 2xx with the field missing/malformed, a non-JSON body, or a 404
|
|
9
|
+
* both mean an old plugin and give `{ orderCreate: 1 }`. A network failure,
|
|
10
|
+
* a 5xx or any other non-2xx that isn't 404/401 is unknown and gives
|
|
11
|
+
* `undefined`, never 1. A 401 means rejected/expired credentials and throws.
|
|
12
|
+
*/
|
|
13
|
+
export async function readCapabilities(
|
|
14
|
+
baseUrl: string,
|
|
15
|
+
headers: Record<string, string>,
|
|
16
|
+
init: { fetch?: typeof fetch; signal?: AbortSignal } = {},
|
|
17
|
+
): Promise<ServerCapabilities | undefined> {
|
|
18
|
+
const doFetch = init.fetch ?? fetch;
|
|
19
|
+
let res: Response;
|
|
20
|
+
try {
|
|
21
|
+
res = await doFetch(`${baseUrl}${CAPABILITIES_PATH}`, { method: 'GET', headers, signal: init.signal });
|
|
22
|
+
} catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
if (res.status === 401) throw new SignInError('invalid_credentials', `Medusa rejected the credentials reading capabilities (HTTP 401)`);
|
|
26
|
+
if (res.status === 404) return { orderCreate: 1 };
|
|
27
|
+
if (!res.ok) return undefined;
|
|
28
|
+
let body: unknown;
|
|
29
|
+
try {
|
|
30
|
+
body = await res.json();
|
|
31
|
+
} catch {
|
|
32
|
+
return { orderCreate: 1 };
|
|
33
|
+
}
|
|
34
|
+
return parseInfoCapabilities(body, (reason) => console.warn(`@tallyui/connector-medusa: ${reason}`));
|
|
35
|
+
}
|
package/src/customers.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError, CustomerServiceError, type Customer, type CustomerInput } from '@tallyui/core';
|
|
2
|
+
|
|
3
|
+
type MedusaCustomer = { id: string; deleted_at?: string | null } & Record<string, unknown>;
|
|
4
|
+
type CustomerInit = { signal?: AbortSignal; fetch?: typeof fetch };
|
|
5
|
+
|
|
6
|
+
export function toCustomer(raw: MedusaCustomer): Customer {
|
|
7
|
+
const customer: Customer = { id: raw.id, name: raw.id };
|
|
8
|
+
for (const [key, value] of [
|
|
9
|
+
['firstName', raw.first_name], ['lastName', raw.last_name], ['email', raw.email],
|
|
10
|
+
['phone', raw.phone], ['company', raw.company_name],
|
|
11
|
+
] as const) {
|
|
12
|
+
if (typeof value === 'string' && value.length > 0) customer[key] = value;
|
|
13
|
+
}
|
|
14
|
+
customer.name = [customer.firstName, customer.lastName].filter(Boolean).join(' ') || customer.company || customer.email || customer.id;
|
|
15
|
+
return customer;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function errorMessage(error: unknown): string {
|
|
19
|
+
if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {
|
|
20
|
+
return error.message;
|
|
21
|
+
}
|
|
22
|
+
return String(error);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function customerRequest(url: string, key: 'customers' | 'customer', init: RequestInit & CustomerInit) {
|
|
26
|
+
const { fetch: doFetch = fetch, ...requestInit } = init;
|
|
27
|
+
let res: Response;
|
|
28
|
+
try {
|
|
29
|
+
res = await doFetch(url, requestInit);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
throw new CustomerServiceError('network', errorMessage(error));
|
|
32
|
+
}
|
|
33
|
+
if (res.status === 401 || res.status === 403) throw new ConnectorUnauthorizedError(`Medusa rejected the credentials (HTTP ${res.status})`, res.status);
|
|
34
|
+
if (res.status === 404 && key === 'customer' && init.method === 'GET') return null;
|
|
35
|
+
if (!res.ok && res.status !== 400) throw new CustomerServiceError('server', `HTTP ${res.status}`);
|
|
36
|
+
let body;
|
|
37
|
+
try {
|
|
38
|
+
body = await res.json();
|
|
39
|
+
} catch {
|
|
40
|
+
throw new CustomerServiceError(res.status === 400 ? 'invalid' : 'server', res.status === 400 ? 'HTTP 400' : 'unexpected response');
|
|
41
|
+
}
|
|
42
|
+
if (res.status === 400) throw new CustomerServiceError('invalid', body?.message ?? 'HTTP 400');
|
|
43
|
+
if (key === 'customers' ? !Array.isArray(body?.[key]) : !body?.[key]) throw new CustomerServiceError('server', 'unexpected response');
|
|
44
|
+
return body[key];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function searchMedusaCustomers(baseUrl: string, headers: Record<string, string>, query: string, init: CustomerInit & { limit?: number } = {}): Promise<Customer[]> {
|
|
48
|
+
if (!query.trim()) return [];
|
|
49
|
+
const limit = Math.max(1, Math.min(50, init.limit ?? 20));
|
|
50
|
+
const customers: MedusaCustomer[] = await customerRequest(`${baseUrl}/admin/customers?q=${encodeURIComponent(query.trim())}&limit=${limit}`, 'customers', { method: 'GET', headers, signal: init.signal, fetch: init.fetch });
|
|
51
|
+
return customers.filter((raw) => raw.deleted_at == null).map(toCustomer);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function createMedusaCustomer(baseUrl: string, headers: Record<string, string>, input: CustomerInput, init: CustomerInit = {}): Promise<Customer> {
|
|
55
|
+
const body = {
|
|
56
|
+
email: input.email,
|
|
57
|
+
...(input.firstName ? { first_name: input.firstName } : {}),
|
|
58
|
+
...(input.lastName ? { last_name: input.lastName } : {}),
|
|
59
|
+
...(input.phone ? { phone: input.phone } : {}),
|
|
60
|
+
...(input.company ? { company_name: input.company } : {}),
|
|
61
|
+
};
|
|
62
|
+
const customer = await customerRequest(`${baseUrl}/admin/customers`, 'customer', { ...init, method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
63
|
+
return toCustomer(customer);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function getMedusaCustomer(baseUrl: string, headers: Record<string, string>, id: string, init: CustomerInit = {}): Promise<Customer | null> {
|
|
67
|
+
const customer: MedusaCustomer | null = await customerRequest(`${baseUrl}/admin/customers/${encodeURIComponent(id)}`, 'customer', { ...init, method: 'GET', headers });
|
|
68
|
+
return customer === null || customer.deleted_at != null ? null : toCustomer(customer);
|
|
69
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,53 +1,148 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { combinePullAdapters, createReconcileFeed, SignInError, type ConnectorAuth, type CustomerInput, type ServerCapabilities, type SyncContext, type TallyConnector } from '@tallyui/core';
|
|
2
2
|
|
|
3
|
+
import { readCapabilities } from './capabilities';
|
|
4
|
+
import { searchMedusaCustomers, createMedusaCustomer, getMedusaCustomer } from './customers';
|
|
3
5
|
import { medusaProductSchema } from './schemas/products';
|
|
4
6
|
import { medusaProductTraits } from './traits/product';
|
|
5
7
|
import { medusaProductSync } from './sync/products';
|
|
6
|
-
import { medusaProductReplication } from './replication/products';
|
|
8
|
+
import { MEDUSA_PULL_BATCH_SIZE, medusaProductReplication } from './replication/products';
|
|
9
|
+
import { createMedusaVariantFeedReplication } from './replication/variant-feed';
|
|
10
|
+
import { medusaStockReconcile } from './reconcile/stock';
|
|
11
|
+
import { fetchByIds, fetchPages, MAX_IDS_PER_REQUEST, variantIds } from './reconcile/ids';
|
|
12
|
+
import { fetchPages as fetchPricePages, fingerprint as priceFingerprint } from './reconcile/prices';
|
|
13
|
+
import { fetchPages as fetchCalculatedPricePages, fingerprint as calculatedPriceFingerprint } from './reconcile/calculated-prices';
|
|
14
|
+
import { medusaStoreSettings } from './store-settings';
|
|
15
|
+
|
|
16
|
+
export const medusaSecretKeyAuth: ConnectorAuth = {
|
|
17
|
+
type: 'Medusa Admin API',
|
|
18
|
+
fields: [
|
|
19
|
+
{ key: 'url', label: 'Backend URL', type: 'url', placeholder: 'https://my-medusa-backend.com', required: true },
|
|
20
|
+
{ key: 'api_token', label: 'Secret API Key', type: 'password', placeholder: 'sk_...', required: true },
|
|
21
|
+
],
|
|
22
|
+
// Medusa v2 only accepts secret API keys over HTTP Basic auth, with the
|
|
23
|
+
// key as the username and an empty password. Bearer is for user JWTs.
|
|
24
|
+
getHeaders: (credentials) => ({ Authorization: `Basic ${btoa(`${credentials.api_token}:`)}` }),
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// Reads exp from a JWT payload without verifying it: for display and refresh timing only.
|
|
28
|
+
const jwtExpiresAt = (token: string): string | undefined => {
|
|
29
|
+
try {
|
|
30
|
+
const part = token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/');
|
|
31
|
+
const { exp } = JSON.parse(atob(part.padEnd(Math.ceil(part.length / 4) * 4, '=')));
|
|
32
|
+
return typeof exp === 'number' ? new Date(exp * 1000).toISOString() : undefined;
|
|
33
|
+
} catch { return undefined; }
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const medusaSignIn: NonNullable<ConnectorAuth['signIn']> = async (baseUrl, { email, password }, init = {}) => {
|
|
37
|
+
const doFetch = init.fetch ?? fetch;
|
|
38
|
+
let res: Response;
|
|
39
|
+
try {
|
|
40
|
+
res = await doFetch(`${baseUrl}/auth/user/emailpass`, {
|
|
41
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: init.signal,
|
|
42
|
+
body: JSON.stringify({ email, password }),
|
|
43
|
+
});
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if ((error as { name?: unknown })?.name === 'AbortError' || init.signal?.aborted) throw error;
|
|
46
|
+
throw new SignInError('failed', `Could not reach Medusa at ${baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
|
|
47
|
+
}
|
|
48
|
+
let body: { token?: unknown; location?: string; message?: string; mfa_required?: unknown; verification_required?: unknown } = {};
|
|
49
|
+
let bodyUnparseable = false;
|
|
50
|
+
try {
|
|
51
|
+
const parsed: unknown = await res.json();
|
|
52
|
+
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) body = parsed;
|
|
53
|
+
else bodyUnparseable = true;
|
|
54
|
+
} catch {
|
|
55
|
+
bodyUnparseable = true;
|
|
56
|
+
}
|
|
57
|
+
if (res.status === 401) throw new SignInError('invalid_credentials', body.message ?? 'Invalid email or password');
|
|
58
|
+
if (bodyUnparseable) throw new SignInError('server_error', `Medusa sent an unreadable response (HTTP ${res.status})`, res.status);
|
|
59
|
+
// A location, MFA or verification requirement is a sign-in flow this connector can't do.
|
|
60
|
+
// Never return a token from a body like this, even if one is present.
|
|
61
|
+
if (body.location) throw new SignInError('unsupported', `Medusa wants to continue sign-in at ${body.location}; only email and password are supported`);
|
|
62
|
+
if (body.mfa_required === true) throw new SignInError('unsupported', 'Medusa requires multi-factor authentication, which this connector does not support');
|
|
63
|
+
if (body.verification_required === true) throw new SignInError('unsupported', 'Medusa requires email verification, which this connector does not support');
|
|
64
|
+
if (!res.ok) throw new SignInError('server_error', body.message ?? `Medusa sign-in failed (HTTP ${res.status})`, res.status);
|
|
65
|
+
if (typeof body.token !== 'string') throw new SignInError('server_error', `Medusa sign-in response had no token (HTTP ${res.status})`, res.status);
|
|
66
|
+
const capabilities = await readCapabilities(baseUrl, { Authorization: `Bearer ${body.token}` }, { fetch: doFetch, signal: init.signal });
|
|
67
|
+
return { token: body.token, expiresAt: jwtExpiresAt(body.token), capabilities };
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** Re-reads the store's `order.create` capability (ADR-062) for a restored session, with the connector's own headers. */
|
|
71
|
+
export const medusaCapabilities = (context: SyncContext): Promise<ServerCapabilities | undefined> =>
|
|
72
|
+
readCapabilities(context.baseUrl, context.headers, { signal: context.signal });
|
|
73
|
+
export const medusaSearchCustomers = (context: SyncContext, query: string, options?: { limit?: number }) =>
|
|
74
|
+
searchMedusaCustomers(context.baseUrl, context.headers, query, { ...options, signal: context.signal });
|
|
75
|
+
export const medusaCreateCustomer = (context: SyncContext, input: CustomerInput) =>
|
|
76
|
+
createMedusaCustomer(context.baseUrl, context.headers, input, { signal: context.signal });
|
|
77
|
+
export const medusaGetCustomer = (context: SyncContext, id: string) =>
|
|
78
|
+
getMedusaCustomer(context.baseUrl, context.headers, id, { signal: context.signal });
|
|
79
|
+
|
|
80
|
+
// The JWT from Medusa's emailpass sign-in (POST /auth/user/emailpass) is stored as token.
|
|
81
|
+
// email and password are only sign-in form fields and are never sent as headers.
|
|
82
|
+
export const medusaAdminUserAuth: ConnectorAuth = {
|
|
83
|
+
type: 'Medusa admin user (Bearer JWT)',
|
|
84
|
+
fields: [
|
|
85
|
+
{ key: 'url', label: 'Backend URL', type: 'url', placeholder: 'https://my-medusa-backend.com', required: true },
|
|
86
|
+
{ key: 'email', label: 'Email', type: 'text', required: true },
|
|
87
|
+
{ key: 'password', label: 'Password', type: 'password', required: true },
|
|
88
|
+
],
|
|
89
|
+
getHeaders: (credentials): Record<string, string> => typeof credentials.token === 'string' && credentials.token.length > 0
|
|
90
|
+
? { Authorization: `Bearer ${credentials.token}` } : {},
|
|
91
|
+
signIn: medusaSignIn,
|
|
92
|
+
};
|
|
7
93
|
|
|
8
94
|
/**
|
|
9
|
-
* MedusaJS v2 connector for Tally UI.
|
|
95
|
+
* MedusaJS v2 connector for Tally UI, with a secret API key. Build one per store session, anew on each
|
|
96
|
+
* sign-in or store change: it owns the reconcile feed, whose queued work must never reach another store's database (#307).
|
|
10
97
|
*
|
|
11
98
|
* Connects to Medusa backends via the Admin API.
|
|
12
99
|
* Products are stored in RxDB using a schema that mirrors the Medusa API shape.
|
|
13
100
|
*
|
|
14
101
|
* ```ts
|
|
15
|
-
* import {
|
|
102
|
+
* import { createMedusaConnector } from '@tallyui/connector-medusa';
|
|
16
103
|
* import { ConnectorProvider } from '@tallyui/core';
|
|
17
104
|
*
|
|
18
|
-
*
|
|
105
|
+
* const connector = useMemo(() => createMedusaConnector(), [backendUrl]);
|
|
106
|
+
* <ConnectorProvider connector={connector}>
|
|
19
107
|
* <App />
|
|
20
108
|
* </ConnectorProvider>
|
|
21
109
|
* ```
|
|
22
110
|
*/
|
|
23
|
-
export
|
|
111
|
+
export function createMedusaConnector(): TallyConnector {
|
|
112
|
+
// The id reconcile's corrections reach `products` only through this pull adapter (ADR-060).
|
|
113
|
+
const idFeed = createReconcileFeed({ fetchByIds });
|
|
114
|
+
// fetchByIds asks for at most this many ids per request; the runner budgets a page's refetch by requests.
|
|
115
|
+
const refetchBatchSize = MAX_IDS_PER_REQUEST;
|
|
116
|
+
return {
|
|
117
|
+
...medusaConnectorParts,
|
|
118
|
+
replication: {
|
|
119
|
+
// One replication per collection: the product, variant and id-reconcile
|
|
120
|
+
// feeds share it (ADR-060). The variant feed catches price-only edits,
|
|
121
|
+
// which bump only the variant. reconcile is last so its fetch wins duplicates.
|
|
122
|
+
products: combinePullAdapters({
|
|
123
|
+
products: medusaProductReplication,
|
|
124
|
+
variants: createMedusaVariantFeedReplication(),
|
|
125
|
+
reconcile: idFeed.adapter,
|
|
126
|
+
}, { legacyKey: 'products', batchSize: MEDUSA_PULL_BATCH_SIZE }),
|
|
127
|
+
},
|
|
128
|
+
reconcile: {
|
|
129
|
+
stock: medusaStockReconcile,
|
|
130
|
+
ids: { fetchPages, variantIds, enqueue: idFeed.enqueue, refetchBatchSize },
|
|
131
|
+
prices: { fetchPages: fetchPricePages, fingerprint: priceFingerprint, enqueue: idFeed.enqueue, refetchBatchSize },
|
|
132
|
+
// Re-fetched through the enriched fetchByIds, so the corrected document carries the new calculated prices (D2b).
|
|
133
|
+
calculatedPrices: { fetchPages: fetchCalculatedPricePages, fingerprint: calculatedPriceFingerprint, enqueue: idFeed.enqueue, refetchBatchSize },
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Everything but the reconcile feed and what is wired to it: stateless, so every instance shares it.
|
|
139
|
+
const medusaConnectorParts = {
|
|
24
140
|
id: 'medusa',
|
|
25
141
|
name: 'MedusaJS',
|
|
26
142
|
description: 'Connect to MedusaJS v2 backends via the Admin API',
|
|
27
143
|
icon: undefined, // TODO: Medusa logo
|
|
28
144
|
|
|
29
|
-
auth:
|
|
30
|
-
type: 'Medusa Admin API',
|
|
31
|
-
fields: [
|
|
32
|
-
{
|
|
33
|
-
key: 'url',
|
|
34
|
-
label: 'Backend URL',
|
|
35
|
-
type: 'url',
|
|
36
|
-
placeholder: 'https://my-medusa-backend.com',
|
|
37
|
-
required: true,
|
|
38
|
-
},
|
|
39
|
-
{
|
|
40
|
-
key: 'api_token',
|
|
41
|
-
label: 'API Token',
|
|
42
|
-
type: 'password',
|
|
43
|
-
placeholder: 'Your admin API token',
|
|
44
|
-
required: true,
|
|
45
|
-
},
|
|
46
|
-
],
|
|
47
|
-
getHeaders: (credentials) => ({
|
|
48
|
-
Authorization: `Bearer ${credentials.api_token}`,
|
|
49
|
-
}),
|
|
50
|
-
},
|
|
145
|
+
auth: medusaSecretKeyAuth,
|
|
51
146
|
|
|
52
147
|
schemas: {
|
|
53
148
|
products: medusaProductSchema,
|
|
@@ -61,13 +156,40 @@ export const medusaConnector: TallyConnector = {
|
|
|
61
156
|
products: medusaProductSync,
|
|
62
157
|
},
|
|
63
158
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
}
|
|
159
|
+
storeSettings: medusaStoreSettings,
|
|
160
|
+
|
|
161
|
+
// No capabilities read here: the plugin's routes authenticate users only, so this connector can't send orders through the plugin either.
|
|
162
|
+
} satisfies Omit<TallyConnector, 'replication' | 'reconcile'>;
|
|
163
|
+
|
|
164
|
+
/** Medusa connector using an admin user's Bearer JWT; like createMedusaConnector(), one per store session with its own feed. */
|
|
165
|
+
export const createMedusaAdminUserConnector = (): TallyConnector => ({
|
|
166
|
+
...createMedusaConnector(), auth: medusaAdminUserAuth, capabilities: medusaCapabilities,
|
|
167
|
+
searchCustomers: medusaSearchCustomers, createCustomer: medusaCreateCustomer, getCustomer: medusaGetCustomer,
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* @deprecated One instance for the whole app: a store switch can leak queued reconcile work across stores.
|
|
172
|
+
* Use createMedusaConnector() per store session. Removed in 4.0.
|
|
173
|
+
*/
|
|
174
|
+
export const medusaConnector: TallyConnector = createMedusaConnector();
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* @deprecated One instance for the whole app: a store switch can leak queued reconcile work across stores.
|
|
178
|
+
* Use createMedusaAdminUserConnector() per store session. Removed in 4.0.
|
|
179
|
+
*/
|
|
180
|
+
export const medusaAdminUserConnector: TallyConnector = createMedusaAdminUserConnector();
|
|
68
181
|
|
|
69
182
|
// Re-export pieces for advanced usage
|
|
70
183
|
export { medusaProductSchema } from './schemas/products';
|
|
71
184
|
export { medusaProductTraits } from './traits/product';
|
|
72
185
|
export { medusaProductSync } from './sync/products';
|
|
73
186
|
export { medusaProductReplication } from './replication/products';
|
|
187
|
+
export { createMedusaVariantFeedReplication } from './replication/variant-feed';
|
|
188
|
+
export { medusaStockReconcile } from './reconcile/stock';
|
|
189
|
+
export { medusaStoreSettings } from './store-settings';
|
|
190
|
+
export { searchMedusaCustomers, createMedusaCustomer, getMedusaCustomer, toCustomer } from './customers';
|
|
191
|
+
export { withCalculatedPrices } from './pricing/calculated';
|
|
192
|
+
export { MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS } from './reconcile/calculated-prices';
|
|
193
|
+
export type { MedusaCalculatedPrice, MedusaProductDocument, MedusaVariantDocument } from './schemas/products';
|
|
194
|
+
|
|
195
|
+
export { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { SyncContext } from '@tallyui/core';
|
|
2
|
+
import type { MedusaCalculatedPrice, MedusaProductDocument } from '../schemas/products';
|
|
3
|
+
|
|
4
|
+
/** Store API list limit used here; also the most ids per enrichment request (as `fetchByIds`). */
|
|
5
|
+
export const STORE_PAGE_SIZE = 100;
|
|
6
|
+
|
|
7
|
+
/** Only what pricing needs: the product id and each variant's calculated price. */
|
|
8
|
+
export const STORE_PRICE_FIELDS = 'id,*variants.calculated_price';
|
|
9
|
+
|
|
10
|
+
export type StoreProduct = { id: string; variants?: Array<{ id: string; calculated_price?: MedusaCalculatedPrice | null }> };
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* GET a store API path with the pricing context's publishable key. The admin
|
|
14
|
+
* `context.headers` (its `Authorization`) are never sent to `/store/*`. A
|
|
15
|
+
* non-OK response throws with the status and Medusa's message, with the key
|
|
16
|
+
* scrubbed out of it.
|
|
17
|
+
*/
|
|
18
|
+
export async function storeGet(path: string, context: SyncContext): Promise<{ products?: StoreProduct[]; count: number }> {
|
|
19
|
+
const key = context.pricingContext?.publishable_key ?? '';
|
|
20
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
21
|
+
headers: { 'x-publishable-api-key': key, 'Content-Type': 'application/json' },
|
|
22
|
+
signal: context.signal,
|
|
23
|
+
});
|
|
24
|
+
if (!response.ok) {
|
|
25
|
+
const error = await response.json().catch(() => ({}));
|
|
26
|
+
const message = typeof error?.message === 'string' && key ? error.message.split(key).join('[key]') : error?.message;
|
|
27
|
+
throw new Error(`Medusa store API error: ${response.status}${message ? `: ${message}` : ''}`);
|
|
28
|
+
}
|
|
29
|
+
return response.json();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Fills each variant's `calculated_price` from the store API, priced with
|
|
34
|
+
* `context.pricingContext` (`region_id`, `publishable_key`): what Medusa
|
|
35
|
+
* charges at checkout, sale price lists and their dates included (ADR-060
|
|
36
|
+
* amendment 8, D2b). A variant the store API does not list (a draft, or a
|
|
37
|
+
* product outside the key's sales channel) gets `null`: priced mode, not
|
|
38
|
+
* sellable here. Without a pricing context the documents come back
|
|
39
|
+
* unchanged (base-only mode, no `calculated_price` key). A failed store
|
|
40
|
+
* request throws, so the pull retries and never delivers a half-priced
|
|
41
|
+
* document.
|
|
42
|
+
*/
|
|
43
|
+
export async function withCalculatedPrices<Doc extends MedusaProductDocument>(docs: Doc[], context: SyncContext): Promise<Doc[]> {
|
|
44
|
+
const pricing = context.pricingContext;
|
|
45
|
+
if (!pricing) return docs;
|
|
46
|
+
const byVariant = new Map<string, MedusaCalculatedPrice | null>();
|
|
47
|
+
for (let i = 0; i < docs.length; i += STORE_PAGE_SIZE) {
|
|
48
|
+
const params = new URLSearchParams({ region_id: pricing.region_id ?? '', limit: String(STORE_PAGE_SIZE), fields: STORE_PRICE_FIELDS });
|
|
49
|
+
for (const doc of docs.slice(i, i + STORE_PAGE_SIZE)) params.append('id[]', doc.id);
|
|
50
|
+
const data = await storeGet(`/store/products?${params}`, context);
|
|
51
|
+
for (const product of data.products ?? []) {
|
|
52
|
+
for (const variant of product.variants ?? []) byVariant.set(variant.id, variant.calculated_price ?? null);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return docs.map((doc) => (Array.isArray(doc.variants)
|
|
56
|
+
? { ...doc, variants: doc.variants.map((v) => ({ ...v, calculated_price: byVariant.get(v.id) ?? null })) }
|
|
57
|
+
: doc));
|
|
58
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { SyncContext } from '@tallyui/core';
|
|
2
|
+
import { STORE_PAGE_SIZE, STORE_PRICE_FIELDS, storeGet } from '../pricing/calculated';
|
|
3
|
+
import type { MedusaCalculatedPrice, MedusaProductDocument } from '../schemas/products';
|
|
4
|
+
|
|
5
|
+
/** The calculated-price check's interval: price-list edits and sale start/end bump no timestamp (ADR-060 amendment 8). */
|
|
6
|
+
export const MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS = 30 * 60 * 1000;
|
|
7
|
+
|
|
8
|
+
type Variant = { id: string; calculated_price?: MedusaCalculatedPrice | null };
|
|
9
|
+
|
|
10
|
+
/** Sorted and `|`-joined; a variant with no calculated price contributes `${variantId}:-`. */
|
|
11
|
+
function fingerprintOf(variants: Variant[]): string {
|
|
12
|
+
return variants.map(({ id, calculated_price: c }) => (c
|
|
13
|
+
? `${id}:${c.currency_code}:${c.calculated_amount}:${c.original_amount}:${c.is_calculated_price_tax_inclusive}:${c.is_original_price_tax_inclusive}:${c.calculated_price?.price_list_type ?? ''}`
|
|
14
|
+
: `${id}:-`)).sort().join('|');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Every product the store API lists for the pricing context, with its
|
|
19
|
+
* calculated-price fingerprint, one `/store/products` request per page of
|
|
20
|
+
* 100 (ADR-060 amendment 8, D2b). Without `context.pricingContext` it yields
|
|
21
|
+
* nothing, so the pass is empty and complete. Products the sales channel
|
|
22
|
+
* does not list are not reported; the runner counts them as `unreported`.
|
|
23
|
+
*
|
|
24
|
+
* The app runs it as `reconcile.calculatedPrices` with
|
|
25
|
+
* `startFingerprintReconcile({ …, intervalMs: MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS, maxPages: 1000 })`:
|
|
26
|
+
* the runner's default of 100 pages of 100 products would truncate at 10,000 products.
|
|
27
|
+
*/
|
|
28
|
+
export async function* fetchPages(context: SyncContext): AsyncIterable<Map<string, string>> {
|
|
29
|
+
const pricing = context.pricingContext;
|
|
30
|
+
if (!pricing) return;
|
|
31
|
+
for (let offset = 0, count = 1; offset < count; offset += STORE_PAGE_SIZE) {
|
|
32
|
+
const params = new URLSearchParams({
|
|
33
|
+
region_id: pricing.region_id ?? '', limit: String(STORE_PAGE_SIZE), offset: String(offset), order: 'id', fields: STORE_PRICE_FIELDS,
|
|
34
|
+
});
|
|
35
|
+
const data = await storeGet(`/store/products?${params}`, context);
|
|
36
|
+
count = data.count;
|
|
37
|
+
yield new Map((data.products ?? []).map((p) => [String(p.id), fingerprintOf(p.variants ?? [])]));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The same fingerprint, from a local document's `variants[].calculated_price`. */
|
|
42
|
+
export function fingerprint(doc: MedusaProductDocument): string {
|
|
43
|
+
return fingerprintOf(doc.variants ?? []);
|
|
44
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
|
+
import type { SyncContext } from '@tallyui/core';
|
|
3
|
+
import { MEDUSA_PRODUCT_FIELDS, toDocument } from '../replication/products';
|
|
4
|
+
import { withCalculatedPrices } from '../pricing/calculated';
|
|
5
|
+
import type { MedusaProductDocument } from '../schemas/products';
|
|
6
|
+
|
|
7
|
+
/** Admin API list limit; also the id-listing page size (ADR-060). */
|
|
8
|
+
const PAGE_SIZE = 1000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* At most this many ids per `fetchByIds` request. Medusa ids are about 31
|
|
12
|
+
* characters; 1,000 of them would pass Node's 16 KB header/URL limit.
|
|
13
|
+
*/
|
|
14
|
+
export const MAX_IDS_PER_REQUEST = 100;
|
|
15
|
+
|
|
16
|
+
async function get(path: string, context: SyncContext) {
|
|
17
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
18
|
+
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
19
|
+
signal: context.signal,
|
|
20
|
+
});
|
|
21
|
+
if (!response.ok) {
|
|
22
|
+
const error = await response.json().catch(() => ({}));
|
|
23
|
+
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
|
|
24
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
25
|
+
}
|
|
26
|
+
return response.json();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Every live product id with its live variant ids, one request per page (ADR-060). */
|
|
30
|
+
export async function* fetchPages(context: SyncContext): AsyncIterable<Array<{ id: string; variantIds: string[] }>> {
|
|
31
|
+
for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
|
|
32
|
+
const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), order: 'id', fields: 'id,variants.id' });
|
|
33
|
+
const data = await get(`/admin/products?${params}`, context);
|
|
34
|
+
const products: Array<{ id: string; variants?: Array<{ id: string }> }> = data.products ?? [];
|
|
35
|
+
count = data.count;
|
|
36
|
+
yield products.map((p) => ({ id: String(p.id), variantIds: (p.variants ?? []).map((v) => String(v.id)) }));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The variant ids a local product document lists. */
|
|
41
|
+
export function variantIds(doc: any): string[] {
|
|
42
|
+
return (doc.variants ?? []).map((v: any) => String(v.id));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** `fetchByIds` for `createReconcileFeed`, in the replication feed's document shape. */
|
|
46
|
+
export async function fetchByIds(ids: string[], context: SyncContext): Promise<Record<string, unknown>[]> {
|
|
47
|
+
const results: Record<string, unknown>[] = [];
|
|
48
|
+
for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
|
|
49
|
+
const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
|
|
50
|
+
const params = new URLSearchParams({ fields: MEDUSA_PRODUCT_FIELDS, limit: String(chunk.length) });
|
|
51
|
+
for (const id of chunk) params.append('id[]', id);
|
|
52
|
+
const data = await get(`/admin/products?${params}`, context);
|
|
53
|
+
const products: Array<Record<string, unknown>> = data.products ?? [];
|
|
54
|
+
results.push(...products.map(toDocument));
|
|
55
|
+
}
|
|
56
|
+
// Priced through the store API when the context carries a pricing context (D2b); the variant and reconcile feeds both build here.
|
|
57
|
+
return withCalculatedPrices(results as MedusaProductDocument[], context);
|
|
58
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
|
+
import type { SyncContext } from '@tallyui/core';
|
|
3
|
+
|
|
4
|
+
/** Admin API list limit; also the price-listing page size (ADR-060). */
|
|
5
|
+
const PAGE_SIZE = 1000;
|
|
6
|
+
|
|
7
|
+
/** The nightly base-price backstop's interval (ADR-060 amendment 8). */
|
|
8
|
+
export const MEDUSA_PRICE_RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
type Price = { amount: number; currency_code: string; price_list_id?: string | null };
|
|
11
|
+
type Variant = { id: string; product_id: string; prices?: Price[] };
|
|
12
|
+
|
|
13
|
+
async function get(path: string, context: SyncContext) {
|
|
14
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
15
|
+
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
16
|
+
signal: context.signal,
|
|
17
|
+
});
|
|
18
|
+
if (!response.ok) {
|
|
19
|
+
const error = await response.json().catch(() => ({}));
|
|
20
|
+
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
|
|
21
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
22
|
+
}
|
|
23
|
+
return response.json();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Base prices only (a null `price_list_id`), as `${variantId}:${currencyCode}:${amount}`, sorted and joined. */
|
|
27
|
+
const fingerprintOf = (entries: string[]): string => [...entries].sort().join('|');
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Every product's base-price fingerprint, one `/admin/product-variants`
|
|
31
|
+
* request per page (ADR-060 amendment 8's nightly backstop). The listing is
|
|
32
|
+
* not grouped by product, so each product's variants may land on different
|
|
33
|
+
* pages; a page's yielded entry is always recomputed from every base price
|
|
34
|
+
* seen for that product so far, so the last page that touches a product
|
|
35
|
+
* carries its complete, correct fingerprint. The reconcile runner keeps only
|
|
36
|
+
* the latest entry per id, so earlier, partial entries are harmless.
|
|
37
|
+
*/
|
|
38
|
+
export async function* fetchPages(context: SyncContext): AsyncIterable<Map<string, string>> {
|
|
39
|
+
const byProduct = new Map<string, string[]>();
|
|
40
|
+
for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
|
|
41
|
+
const params = new URLSearchParams({
|
|
42
|
+
limit: String(PAGE_SIZE), offset: String(offset), order: 'id',
|
|
43
|
+
fields: 'id,product_id,prices.amount,prices.currency_code,prices.price_list_id',
|
|
44
|
+
});
|
|
45
|
+
const data = await get(`/admin/product-variants?${params}`, context);
|
|
46
|
+
const variants: Variant[] = data.variants ?? [];
|
|
47
|
+
count = data.count;
|
|
48
|
+
const touched = new Set<string>();
|
|
49
|
+
for (const variant of variants) {
|
|
50
|
+
const productId = String(variant.product_id);
|
|
51
|
+
touched.add(productId);
|
|
52
|
+
const entries = byProduct.get(productId) ?? [];
|
|
53
|
+
byProduct.set(productId, entries);
|
|
54
|
+
for (const price of variant.prices ?? []) {
|
|
55
|
+
if (price.price_list_id) continue;
|
|
56
|
+
entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
yield new Map([...touched].map((id) => [id, fingerprintOf(byProduct.get(id) ?? [])]));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The same fingerprint, computed from a local product document's base prices. Replicated Medusa documents carry only base prices today (ADR-060 amendment 8); any `price_list_id` is still skipped, for consistency. */
|
|
64
|
+
export function fingerprint(doc: any): string {
|
|
65
|
+
const entries: string[] = [];
|
|
66
|
+
for (const variant of doc.variants ?? []) {
|
|
67
|
+
for (const price of variant.prices ?? []) {
|
|
68
|
+
if (price.price_list_id) continue;
|
|
69
|
+
entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return fingerprintOf(entries);
|
|
73
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
|
+
import type { StockReconcileAdapter } from '@tallyui/core';
|
|
3
|
+
|
|
4
|
+
type Level = { stocked_quantity: number; reserved_quantity: number };
|
|
5
|
+
|
|
6
|
+
/** Admin API list limit; about 6 requests for 5,000 inventory items. */
|
|
7
|
+
const PAGE_SIZE = 1000;
|
|
8
|
+
const FIELDS = 'id,location_levels.stocked_quantity,location_levels.reserved_quantity,location_levels.location_id';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Sorted quantity pairs. Local documents carry no location_id, so compare
|
|
12
|
+
* quantities only and a first pass does not rewrite every document.
|
|
13
|
+
*/
|
|
14
|
+
const pairsKey = (levels: Level[] = []) =>
|
|
15
|
+
levels.map((l) => JSON.stringify([l.stocked_quantity, l.reserved_quantity])).sort().join();
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Stock reconciler for Medusa v2 products (ADR-060). Inventory changes never
|
|
19
|
+
* touch the product, so replication misses them. Pages are keyed by
|
|
20
|
+
* inventory item id; each value is its location levels' quantities.
|
|
21
|
+
*/
|
|
22
|
+
export const medusaStockReconcile: StockReconcileAdapter = {
|
|
23
|
+
async *fetchPages(context) {
|
|
24
|
+
for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
|
|
25
|
+
// Offset paging needs a total order, or items can be skipped or repeated between pages.
|
|
26
|
+
const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), fields: FIELDS, order: 'id' });
|
|
27
|
+
const response = await fetch(`${context.baseUrl}/admin/inventory-items?${params}`, {
|
|
28
|
+
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
29
|
+
signal: context.signal,
|
|
30
|
+
});
|
|
31
|
+
if (!response.ok) {
|
|
32
|
+
const error = await response.json().catch(() => ({}));
|
|
33
|
+
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
|
|
34
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
35
|
+
}
|
|
36
|
+
const data = await response.json() as { inventory_items: Array<{ id: string; location_levels?: Level[] }>; count: number };
|
|
37
|
+
count = data.count;
|
|
38
|
+
yield new Map(data.inventory_items.map((item) => [item.id, (item.location_levels ?? [])
|
|
39
|
+
.map(({ stocked_quantity, reserved_quantity }) => ({ stocked_quantity, reserved_quantity }))]));
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
overlay(doc, stock) {
|
|
43
|
+
let changed = false;
|
|
44
|
+
const variants = (doc.variants ?? []).map((variant: any) => {
|
|
45
|
+
let variantChanged = false;
|
|
46
|
+
const inventory_items = (variant.inventory_items ?? []).map((item: any) => {
|
|
47
|
+
const levels = stock.get(item.inventory_item_id) as Level[] | undefined;
|
|
48
|
+
if (!levels || pairsKey(levels) === pairsKey(item.inventory?.location_levels)) return item;
|
|
49
|
+
variantChanged = true;
|
|
50
|
+
return { ...item, inventory: { ...item.inventory, location_levels: levels } };
|
|
51
|
+
});
|
|
52
|
+
if (!variantChanged) return variant;
|
|
53
|
+
changed = true;
|
|
54
|
+
return { ...variant, inventory_items };
|
|
55
|
+
});
|
|
56
|
+
return changed ? { variants } : undefined;
|
|
57
|
+
},
|
|
58
|
+
};
|