@tallyui/connector-medusa 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/connector-medusa",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "description": "MedusaJS v2 connector for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -15,13 +15,22 @@
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.2.0"
30
+ "@tallyui/core": "2.0.0"
23
31
  },
24
32
  "devDependencies": {
33
+ "@tallyui/database": "2.0.0",
25
34
  "rxdb": "16.21.1"
26
35
  },
27
36
  "scripts": {
@@ -0,0 +1,40 @@
1
+ import { 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 `order.create` contract capability (ADR-062), with the
8
+ * connector's usual injectable `fetch`. A 2xx with a valid list gives its
9
+ * max; a 2xx with the field missing/malformed, a non-JSON body, or a 404
10
+ * both mean an old plugin and give `{ orderCreate: 1 }`. A network failure,
11
+ * a 5xx or any other non-2xx that isn't 404/401 is unknown and gives
12
+ * `undefined`, never 1. A 401 means rejected/expired credentials and throws.
13
+ */
14
+ export async function readCapabilities(
15
+ baseUrl: string,
16
+ headers: Record<string, string>,
17
+ init: { fetch?: typeof fetch; signal?: AbortSignal } = {},
18
+ ): Promise<ServerCapabilities | undefined> {
19
+ const doFetch = init.fetch ?? fetch;
20
+ let res: Response;
21
+ try {
22
+ res = await doFetch(`${baseUrl}${CAPABILITIES_PATH}`, { method: 'GET', headers, signal: init.signal });
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ if (res.status === 401) throw new SignInError('invalid_credentials', `Medusa rejected the credentials reading capabilities (HTTP 401)`);
27
+ if (res.status === 404) return { orderCreate: 1 };
28
+ if (!res.ok) return undefined;
29
+ let body: unknown;
30
+ try {
31
+ body = await res.json();
32
+ } catch {
33
+ return { orderCreate: 1 };
34
+ }
35
+ const contracts = (body as { contracts?: Record<string, unknown> } | null)?.contracts?.['order.create'];
36
+ const valid = Array.isArray(contracts)
37
+ ? contracts.filter((v): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v > 0)
38
+ : [];
39
+ return { orderCreate: valid.length > 0 ? Math.max(...valid) : 1 };
40
+ }
package/src/index.ts CHANGED
@@ -1,9 +1,91 @@
1
- import type { TallyConnector } from '@tallyui/core';
1
+ import { combinePullAdapters, createReconcileFeed, SignInError, type ConnectorAuth, type ServerCapabilities, type SyncContext, type TallyConnector } from '@tallyui/core';
2
2
 
3
+ import { readCapabilities } from './capabilities';
3
4
  import { medusaProductSchema } from './schemas/products';
4
5
  import { medusaProductTraits } from './traits/product';
5
6
  import { medusaProductSync } from './sync/products';
6
7
  import { medusaProductReplication } from './replication/products';
8
+ import { createMedusaVariantFeedReplication } from './replication/variant-feed';
9
+ import { medusaStockReconcile } from './reconcile/stock';
10
+ import { fetchByIds, fetchPages, variantIds } from './reconcile/ids';
11
+ import { fetchPages as fetchPricePages, fingerprint as priceFingerprint } from './reconcile/prices';
12
+ import { fetchPages as fetchCalculatedPricePages, fingerprint as calculatedPriceFingerprint } from './reconcile/calculated-prices';
13
+ import { medusaStoreSettings } from './store-settings';
14
+
15
+ // The id reconcile's corrections reach `products` only through this pull adapter (ADR-060).
16
+ const idFeed = createReconcileFeed({ fetchByIds });
17
+
18
+ export const medusaSecretKeyAuth: ConnectorAuth = {
19
+ type: 'Medusa Admin API',
20
+ fields: [
21
+ { key: 'url', label: 'Backend URL', type: 'url', placeholder: 'https://my-medusa-backend.com', required: true },
22
+ { key: 'api_token', label: 'Secret API Key', type: 'password', placeholder: 'sk_...', required: true },
23
+ ],
24
+ // Medusa v2 only accepts secret API keys over HTTP Basic auth, with the
25
+ // key as the username and an empty password. Bearer is for user JWTs.
26
+ getHeaders: (credentials) => ({ Authorization: `Basic ${btoa(`${credentials.api_token}:`)}` }),
27
+ };
28
+
29
+ // Reads exp from a JWT payload without verifying it: for display and refresh timing only.
30
+ const jwtExpiresAt = (token: string): string | undefined => {
31
+ try {
32
+ const part = token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/');
33
+ const { exp } = JSON.parse(atob(part.padEnd(Math.ceil(part.length / 4) * 4, '=')));
34
+ return typeof exp === 'number' ? new Date(exp * 1000).toISOString() : undefined;
35
+ } catch { return undefined; }
36
+ };
37
+
38
+ export const medusaSignIn: NonNullable<ConnectorAuth['signIn']> = async (baseUrl, { email, password }, init = {}) => {
39
+ const doFetch = init.fetch ?? fetch;
40
+ let res: Response;
41
+ try {
42
+ res = await doFetch(`${baseUrl}/auth/user/emailpass`, {
43
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: init.signal,
44
+ body: JSON.stringify({ email, password }),
45
+ });
46
+ } catch (error) {
47
+ if ((error as { name?: unknown })?.name === 'AbortError' || init.signal?.aborted) throw error;
48
+ throw new SignInError('failed', `Could not reach Medusa at ${baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
49
+ }
50
+ let body: { token?: unknown; location?: string; message?: string; mfa_required?: unknown; verification_required?: unknown } = {};
51
+ let bodyUnparseable = false;
52
+ try {
53
+ const parsed: unknown = await res.json();
54
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) body = parsed;
55
+ else bodyUnparseable = true;
56
+ } catch {
57
+ bodyUnparseable = true;
58
+ }
59
+ if (res.status === 401) throw new SignInError('invalid_credentials', body.message ?? 'Invalid email or password');
60
+ if (bodyUnparseable) throw new SignInError('server_error', `Medusa sent an unreadable response (HTTP ${res.status})`, res.status);
61
+ // A location, MFA or verification requirement is a sign-in flow this connector can't do.
62
+ // Never return a token from a body like this, even if one is present.
63
+ if (body.location) throw new SignInError('unsupported', `Medusa wants to continue sign-in at ${body.location}; only email and password are supported`);
64
+ if (body.mfa_required === true) throw new SignInError('unsupported', 'Medusa requires multi-factor authentication, which this connector does not support');
65
+ if (body.verification_required === true) throw new SignInError('unsupported', 'Medusa requires email verification, which this connector does not support');
66
+ if (!res.ok) throw new SignInError('server_error', body.message ?? `Medusa sign-in failed (HTTP ${res.status})`, res.status);
67
+ if (typeof body.token !== 'string') throw new SignInError('server_error', `Medusa sign-in response had no token (HTTP ${res.status})`, res.status);
68
+ const capabilities = await readCapabilities(baseUrl, { Authorization: `Bearer ${body.token}` }, { fetch: doFetch, signal: init.signal });
69
+ return { token: body.token, expiresAt: jwtExpiresAt(body.token), capabilities };
70
+ };
71
+
72
+ /** Re-reads the store's `order.create` capability (ADR-062) for a restored session, with the connector's own headers. */
73
+ export const medusaCapabilities = (context: SyncContext): Promise<ServerCapabilities | undefined> =>
74
+ readCapabilities(context.baseUrl, context.headers, { signal: context.signal });
75
+
76
+ // The JWT from Medusa's emailpass sign-in (POST /auth/user/emailpass) is stored as token.
77
+ // email and password are only sign-in form fields and are never sent as headers.
78
+ export const medusaAdminUserAuth: ConnectorAuth = {
79
+ type: 'Medusa admin user (Bearer JWT)',
80
+ fields: [
81
+ { key: 'url', label: 'Backend URL', type: 'url', placeholder: 'https://my-medusa-backend.com', required: true },
82
+ { key: 'email', label: 'Email', type: 'text', required: true },
83
+ { key: 'password', label: 'Password', type: 'password', required: true },
84
+ ],
85
+ getHeaders: (credentials): Record<string, string> => typeof credentials.token === 'string' && credentials.token.length > 0
86
+ ? { Authorization: `Bearer ${credentials.token}` } : {},
87
+ signIn: medusaSignIn,
88
+ };
7
89
 
8
90
  /**
9
91
  * MedusaJS v2 connector for Tally UI.
@@ -26,28 +108,7 @@ export const medusaConnector: TallyConnector = {
26
108
  description: 'Connect to MedusaJS v2 backends via the Admin API',
27
109
  icon: undefined, // TODO: Medusa logo
28
110
 
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
- },
111
+ auth: medusaSecretKeyAuth,
51
112
 
52
113
  schemas: {
53
114
  products: medusaProductSchema,
@@ -62,12 +123,40 @@ export const medusaConnector: TallyConnector = {
62
123
  },
63
124
 
64
125
  replication: {
65
- products: medusaProductReplication,
126
+ // One replication per collection: the product, variant and id-reconcile
127
+ // feeds share it (ADR-060). The variant feed catches price-only edits,
128
+ // which bump only the variant. reconcile is last so its fetch wins duplicates.
129
+ products: combinePullAdapters({
130
+ products: medusaProductReplication,
131
+ variants: createMedusaVariantFeedReplication(),
132
+ reconcile: idFeed.adapter,
133
+ }, { legacyKey: 'products' }),
134
+ },
135
+
136
+ reconcile: {
137
+ stock: medusaStockReconcile,
138
+ ids: { fetchPages, variantIds, enqueue: idFeed.enqueue },
139
+ prices: { fetchPages: fetchPricePages, fingerprint: priceFingerprint, enqueue: idFeed.enqueue },
140
+ // Re-fetched through the enriched fetchByIds, so the corrected document carries the new calculated prices (D2b).
141
+ calculatedPrices: { fetchPages: fetchCalculatedPricePages, fingerprint: calculatedPriceFingerprint, enqueue: idFeed.enqueue },
66
142
  },
143
+
144
+ storeSettings: medusaStoreSettings,
145
+
146
+ // No capabilities read here: the plugin's routes authenticate users only, so this connector can't send orders through the plugin either.
67
147
  };
68
148
 
149
+ /** Medusa connector using an admin user's Bearer JWT. */
150
+ export const medusaAdminUserConnector: TallyConnector = { ...medusaConnector, auth: medusaAdminUserAuth, capabilities: medusaCapabilities };
151
+
69
152
  // Re-export pieces for advanced usage
70
153
  export { medusaProductSchema } from './schemas/products';
71
154
  export { medusaProductTraits } from './traits/product';
72
155
  export { medusaProductSync } from './sync/products';
73
156
  export { medusaProductReplication } from './replication/products';
157
+ export { createMedusaVariantFeedReplication } from './replication/variant-feed';
158
+ export { medusaStockReconcile } from './reconcile/stock';
159
+ export { medusaStoreSettings } from './store-settings';
160
+ export { withCalculatedPrices } from './pricing/calculated';
161
+ export { MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS } from './reconcile/calculated-prices';
162
+ export type { MedusaCalculatedPrice, MedusaProductDocument, MedusaVariantDocument } from './schemas/products';
@@ -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,56 @@
1
+ import type { SyncContext } from '@tallyui/core';
2
+ import { MEDUSA_PRODUCT_FIELDS, toDocument } from '../replication/products';
3
+ import { withCalculatedPrices } from '../pricing/calculated';
4
+ import type { MedusaProductDocument } from '../schemas/products';
5
+
6
+ /** Admin API list limit; also the id-listing page size (ADR-060). */
7
+ const PAGE_SIZE = 1000;
8
+
9
+ /**
10
+ * At most this many ids per `fetchByIds` request. Medusa ids are about 31
11
+ * characters; 1,000 of them would pass Node's 16 KB header/URL limit.
12
+ */
13
+ const MAX_IDS_PER_REQUEST = 100;
14
+
15
+ async function get(path: string, context: SyncContext) {
16
+ const response = await fetch(`${context.baseUrl}${path}`, {
17
+ headers: { ...context.headers, 'Content-Type': 'application/json' },
18
+ signal: context.signal,
19
+ });
20
+ if (!response.ok) {
21
+ const error = await response.json().catch(() => ({}));
22
+ throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
23
+ }
24
+ return response.json();
25
+ }
26
+
27
+ /** Every live product id with its live variant ids, one request per page (ADR-060). */
28
+ export async function* fetchPages(context: SyncContext): AsyncIterable<Array<{ id: string; variantIds: string[] }>> {
29
+ for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
30
+ const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), order: 'id', fields: 'id,variants.id' });
31
+ const data = await get(`/admin/products?${params}`, context);
32
+ const products: Array<{ id: string; variants?: Array<{ id: string }> }> = data.products ?? [];
33
+ count = data.count;
34
+ yield products.map((p) => ({ id: String(p.id), variantIds: (p.variants ?? []).map((v) => String(v.id)) }));
35
+ }
36
+ }
37
+
38
+ /** The variant ids a local product document lists. */
39
+ export function variantIds(doc: any): string[] {
40
+ return (doc.variants ?? []).map((v: any) => String(v.id));
41
+ }
42
+
43
+ /** `fetchByIds` for `createReconcileFeed`, in the replication feed's document shape. */
44
+ export async function fetchByIds(ids: string[], context: SyncContext): Promise<Record<string, unknown>[]> {
45
+ const results: Record<string, unknown>[] = [];
46
+ for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
47
+ const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
48
+ const params = new URLSearchParams({ fields: MEDUSA_PRODUCT_FIELDS, limit: String(chunk.length) });
49
+ for (const id of chunk) params.append('id[]', id);
50
+ const data = await get(`/admin/products?${params}`, context);
51
+ const products: Array<Record<string, unknown>> = data.products ?? [];
52
+ results.push(...products.map(toDocument));
53
+ }
54
+ // Priced through the store API when the context carries a pricing context (D2b); the variant and reconcile feeds both build here.
55
+ return withCalculatedPrices(results as MedusaProductDocument[], context);
56
+ }
@@ -0,0 +1,71 @@
1
+ import type { SyncContext } from '@tallyui/core';
2
+
3
+ /** Admin API list limit; also the price-listing page size (ADR-060). */
4
+ const PAGE_SIZE = 1000;
5
+
6
+ /** The nightly base-price backstop's interval (ADR-060 amendment 8). */
7
+ export const MEDUSA_PRICE_RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1000;
8
+
9
+ type Price = { amount: number; currency_code: string; price_list_id?: string | null };
10
+ type Variant = { id: string; product_id: string; prices?: Price[] };
11
+
12
+ async function get(path: string, context: SyncContext) {
13
+ const response = await fetch(`${context.baseUrl}${path}`, {
14
+ headers: { ...context.headers, 'Content-Type': 'application/json' },
15
+ signal: context.signal,
16
+ });
17
+ if (!response.ok) {
18
+ const error = await response.json().catch(() => ({}));
19
+ throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
20
+ }
21
+ return response.json();
22
+ }
23
+
24
+ /** Base prices only (a null `price_list_id`), as `${variantId}:${currencyCode}:${amount}`, sorted and joined. */
25
+ const fingerprintOf = (entries: string[]): string => [...entries].sort().join('|');
26
+
27
+ /**
28
+ * Every product's base-price fingerprint, one `/admin/product-variants`
29
+ * request per page (ADR-060 amendment 8's nightly backstop). The listing is
30
+ * not grouped by product, so each product's variants may land on different
31
+ * pages; a page's yielded entry is always recomputed from every base price
32
+ * seen for that product so far, so the last page that touches a product
33
+ * carries its complete, correct fingerprint. The reconcile runner keeps only
34
+ * the latest entry per id, so earlier, partial entries are harmless.
35
+ */
36
+ export async function* fetchPages(context: SyncContext): AsyncIterable<Map<string, string>> {
37
+ const byProduct = new Map<string, string[]>();
38
+ for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
39
+ const params = new URLSearchParams({
40
+ limit: String(PAGE_SIZE), offset: String(offset), order: 'id',
41
+ fields: 'id,product_id,prices.amount,prices.currency_code,prices.price_list_id',
42
+ });
43
+ const data = await get(`/admin/product-variants?${params}`, context);
44
+ const variants: Variant[] = data.variants ?? [];
45
+ count = data.count;
46
+ const touched = new Set<string>();
47
+ for (const variant of variants) {
48
+ const productId = String(variant.product_id);
49
+ touched.add(productId);
50
+ const entries = byProduct.get(productId) ?? [];
51
+ byProduct.set(productId, entries);
52
+ for (const price of variant.prices ?? []) {
53
+ if (price.price_list_id) continue;
54
+ entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
55
+ }
56
+ }
57
+ yield new Map([...touched].map((id) => [id, fingerprintOf(byProduct.get(id) ?? [])]));
58
+ }
59
+ }
60
+
61
+ /** 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. */
62
+ export function fingerprint(doc: any): string {
63
+ const entries: string[] = [];
64
+ for (const variant of doc.variants ?? []) {
65
+ for (const price of variant.prices ?? []) {
66
+ if (price.price_list_id) continue;
67
+ entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
68
+ }
69
+ }
70
+ return fingerprintOf(entries);
71
+ }
@@ -0,0 +1,56 @@
1
+ import type { StockReconcileAdapter } from '@tallyui/core';
2
+
3
+ type Level = { stocked_quantity: number; reserved_quantity: number };
4
+
5
+ /** Admin API list limit; about 6 requests for 5,000 inventory items. */
6
+ const PAGE_SIZE = 1000;
7
+ const FIELDS = 'id,location_levels.stocked_quantity,location_levels.reserved_quantity,location_levels.location_id';
8
+
9
+ /**
10
+ * Sorted quantity pairs. Local documents carry no location_id, so compare
11
+ * quantities only and a first pass does not rewrite every document.
12
+ */
13
+ const pairsKey = (levels: Level[] = []) =>
14
+ levels.map((l) => JSON.stringify([l.stocked_quantity, l.reserved_quantity])).sort().join();
15
+
16
+ /**
17
+ * Stock reconciler for Medusa v2 products (ADR-060). Inventory changes never
18
+ * touch the product, so replication misses them. Pages are keyed by
19
+ * inventory item id; each value is its location levels' quantities.
20
+ */
21
+ export const medusaStockReconcile: StockReconcileAdapter = {
22
+ async *fetchPages(context) {
23
+ for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
24
+ // Offset paging needs a total order, or items can be skipped or repeated between pages.
25
+ const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), fields: FIELDS, order: 'id' });
26
+ const response = await fetch(`${context.baseUrl}/admin/inventory-items?${params}`, {
27
+ headers: { ...context.headers, 'Content-Type': 'application/json' },
28
+ signal: context.signal,
29
+ });
30
+ if (!response.ok) {
31
+ const error = await response.json().catch(() => ({}));
32
+ throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
33
+ }
34
+ const data = await response.json() as { inventory_items: Array<{ id: string; location_levels?: Level[] }>; count: number };
35
+ count = data.count;
36
+ yield new Map(data.inventory_items.map((item) => [item.id, (item.location_levels ?? [])
37
+ .map(({ stocked_quantity, reserved_quantity }) => ({ stocked_quantity, reserved_quantity }))]));
38
+ }
39
+ },
40
+ overlay(doc, stock) {
41
+ let changed = false;
42
+ const variants = (doc.variants ?? []).map((variant: any) => {
43
+ let variantChanged = false;
44
+ const inventory_items = (variant.inventory_items ?? []).map((item: any) => {
45
+ const levels = stock.get(item.inventory_item_id) as Level[] | undefined;
46
+ if (!levels || pairsKey(levels) === pairsKey(item.inventory?.location_levels)) return item;
47
+ variantChanged = true;
48
+ return { ...item, inventory: { ...item.inventory, location_levels: levels } };
49
+ });
50
+ if (!variantChanged) return variant;
51
+ changed = true;
52
+ return { ...variant, inventory_items };
53
+ });
54
+ return changed ? { variants } : undefined;
55
+ },
56
+ };