@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
|
@@ -1,31 +1,97 @@
|
|
|
1
|
+
import { compareIds, ConnectorUnauthorizedError } from '@tallyui/core';
|
|
1
2
|
import type { ReplicationAdapter } from '@tallyui/core';
|
|
2
3
|
|
|
4
|
+
import { medusaProductSchema, type MedusaProductDocument } from '../schemas/products';
|
|
5
|
+
import { withCalculatedPrices } from '../pricing/calculated';
|
|
6
|
+
|
|
7
|
+
/** Top-level fields the RxDB schema declares; RxDB rejects any others. */
|
|
8
|
+
const SCHEMA_FIELDS = Object.keys(medusaProductSchema.properties);
|
|
9
|
+
|
|
10
|
+
/** Keeps only schema fields, so new Medusa API fields never fail validation. Also used by the id reconcile's `fetchByIds`, for an identical document shape. Sorts `variants` by id (a stable copy; the input is not mutated), since Medusa does not guarantee variant order. */
|
|
11
|
+
export function toDocument(product: Record<string, unknown>) {
|
|
12
|
+
const doc: Record<string, unknown> = {};
|
|
13
|
+
for (const field of SCHEMA_FIELDS) {
|
|
14
|
+
if (product[field] !== undefined) doc[field] = product[field];
|
|
15
|
+
}
|
|
16
|
+
if (Array.isArray(doc.variants)) {
|
|
17
|
+
doc.variants = [...doc.variants].sort((a: any, b: any) => compareIds(a.id, b.id));
|
|
18
|
+
}
|
|
19
|
+
return doc;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* A pass pages through every product with updated_at >= `updated_at`, in id
|
|
24
|
+
* order, `offset` rows in. The pass-start mark becomes the next lower bound.
|
|
25
|
+
*/
|
|
3
26
|
export type MedusaProductCheckpoint = {
|
|
4
27
|
offset: number;
|
|
5
28
|
updated_at: string;
|
|
29
|
+
pass_max?: string;
|
|
30
|
+
pass_mark?: string;
|
|
31
|
+
pass_count?: number;
|
|
6
32
|
};
|
|
7
33
|
|
|
8
|
-
|
|
9
|
-
|
|
34
|
+
// The Admin API does not compute variants.inventory_quantity (only the Store
|
|
35
|
+
// API does), so fetch the inventory levels the traits sum instead.
|
|
36
|
+
export const MEDUSA_PRODUCT_FIELDS = [
|
|
37
|
+
'*variants',
|
|
38
|
+
'*variants.prices',
|
|
39
|
+
'+variants.inventory_items.required_quantity',
|
|
40
|
+
'+variants.inventory_items.inventory.location_levels.stocked_quantity',
|
|
41
|
+
'+variants.inventory_items.inventory.location_levels.reserved_quantity',
|
|
42
|
+
'*images',
|
|
43
|
+
'*categories',
|
|
44
|
+
'*tags',
|
|
45
|
+
'*options',
|
|
46
|
+
'*options.values',
|
|
47
|
+
].join(',');
|
|
48
|
+
|
|
49
|
+
// A first sync of about 2,000 products took 21 sequential pages at RxDB's default 100
|
|
50
|
+
// (perf spike, 2026-09-28). 500 is within the 1,000 Admin API list limit;
|
|
51
|
+
// tune it against a real store.
|
|
52
|
+
export const MEDUSA_PULL_BATCH_SIZE = 500;
|
|
10
53
|
|
|
11
54
|
/**
|
|
12
55
|
* Replication adapter for Medusa v2 products.
|
|
13
56
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
57
|
+
* Pull-only (id-ordered offset pages within an updated_at window) for RxDB's
|
|
58
|
+
* replicateRxCollection. Catalogue data is server-owned; the POS never
|
|
59
|
+
* writes products.
|
|
17
60
|
*/
|
|
18
61
|
export const medusaProductReplication: ReplicationAdapter<any, MedusaProductCheckpoint> = {
|
|
19
62
|
pull: {
|
|
20
63
|
async handler(lastCheckpoint, batchSize, context) {
|
|
64
|
+
const offset = lastCheckpoint?.offset ?? 0;
|
|
65
|
+
let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? '';
|
|
66
|
+
if (offset === 0 && lastCheckpoint?.pass_mark === undefined) {
|
|
67
|
+
const markResponse = await fetch(
|
|
68
|
+
`${context.baseUrl}/admin/products?limit=1&order=-updated_at&fields=id,updated_at`,
|
|
69
|
+
{ headers: { ...context.headers, 'Content-Type': 'application/json' }, signal: context.signal },
|
|
70
|
+
);
|
|
71
|
+
if (!markResponse.ok) {
|
|
72
|
+
const error = await markResponse.json().catch(() => ({}));
|
|
73
|
+
if (markResponse.status === 401 || markResponse.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ''}`, markResponse.status);
|
|
74
|
+
throw new Error(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
75
|
+
}
|
|
76
|
+
const markData = await markResponse.json();
|
|
77
|
+
passMark = markData.products?.[0]?.updated_at ?? passMark;
|
|
78
|
+
if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
|
|
79
|
+
return { documents: [], checkpoint: lastCheckpoint };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
21
82
|
const params = new URLSearchParams({
|
|
22
83
|
limit: String(batchSize),
|
|
23
84
|
offset: String(lastCheckpoint?.offset ?? 0),
|
|
24
85
|
fields: MEDUSA_PRODUCT_FIELDS,
|
|
86
|
+
// Offsets need a total order. Many products share an updated_at
|
|
87
|
+
// (bulk writes), and Medusa sorts by one field only, so page by the
|
|
88
|
+
// unique id within the fixed updated_at window.
|
|
89
|
+
order: 'id',
|
|
25
90
|
});
|
|
26
91
|
|
|
27
92
|
if (lastCheckpoint?.updated_at) {
|
|
28
|
-
|
|
93
|
+
// Medusa 2.21 honours only the operator form; `updated_at[gte]` is silently dropped.
|
|
94
|
+
params.set('updated_at[$gte]', lastCheckpoint.updated_at);
|
|
29
95
|
}
|
|
30
96
|
|
|
31
97
|
const response = await fetch(
|
|
@@ -40,63 +106,33 @@ export const medusaProductReplication: ReplicationAdapter<any, MedusaProductChec
|
|
|
40
106
|
);
|
|
41
107
|
|
|
42
108
|
if (!response.ok) {
|
|
43
|
-
|
|
109
|
+
const error = await response.json().catch(() => ({}));
|
|
110
|
+
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
|
|
111
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
44
112
|
}
|
|
45
113
|
|
|
46
114
|
const data = await response.json();
|
|
47
115
|
const products: any[] = data.products ?? [];
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
116
|
+
if (offset > 0 && (products.length === 0 || data.count < (lastCheckpoint?.pass_count ?? data.count))) {
|
|
117
|
+
return medusaProductReplication.pull.handler({
|
|
118
|
+
offset: 0, updated_at: lastCheckpoint?.updated_at ?? '', pass_mark: passMark,
|
|
119
|
+
}, batchSize, context);
|
|
120
|
+
}
|
|
121
|
+
// Priced through the store API when the context carries a pricing context (D2b).
|
|
122
|
+
const priced = await withCalculatedPrices(products.map(toDocument) as MedusaProductDocument[], context);
|
|
123
|
+
const documents = priced.map((doc) => ({ ...doc, _deleted: false }));
|
|
54
124
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
125
|
+
// RxDB merges checkpoints, so clear pass state explicitly at completion.
|
|
126
|
+
const checkpoint: MedusaProductCheckpoint = offset + products.length >= data.count
|
|
127
|
+
? { offset: 0, updated_at: passMark, pass_mark: undefined, pass_count: undefined }
|
|
128
|
+
: {
|
|
129
|
+
offset: offset + products.length,
|
|
130
|
+
updated_at: lastCheckpoint?.updated_at ?? '',
|
|
131
|
+
pass_mark: passMark,
|
|
132
|
+
pass_count: offset === 0 ? data.count : lastCheckpoint?.pass_count ?? data.count,
|
|
133
|
+
};
|
|
61
134
|
|
|
62
135
|
return { documents, checkpoint };
|
|
63
136
|
},
|
|
64
137
|
},
|
|
65
|
-
|
|
66
|
-
push: {
|
|
67
|
-
async handler(changeRows, context) {
|
|
68
|
-
const conflicts: any[] = [];
|
|
69
|
-
|
|
70
|
-
for (const row of changeRows) {
|
|
71
|
-
const doc = row.newDocumentState as any;
|
|
72
|
-
|
|
73
|
-
try {
|
|
74
|
-
const response = await fetch(
|
|
75
|
-
`${context.baseUrl}/admin/products/${doc.id}`,
|
|
76
|
-
{
|
|
77
|
-
method: 'POST',
|
|
78
|
-
headers: {
|
|
79
|
-
...context.headers,
|
|
80
|
-
'Content-Type': 'application/json',
|
|
81
|
-
},
|
|
82
|
-
body: JSON.stringify(doc),
|
|
83
|
-
signal: context.signal,
|
|
84
|
-
},
|
|
85
|
-
);
|
|
86
|
-
|
|
87
|
-
if (!response.ok) {
|
|
88
|
-
if (row.assumedMasterState) {
|
|
89
|
-
conflicts.push({ ...row.assumedMasterState, _deleted: false });
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
} catch {
|
|
93
|
-
if (row.assumedMasterState) {
|
|
94
|
-
conflicts.push({ ...row.assumedMasterState, _deleted: false });
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
return conflicts;
|
|
100
|
-
},
|
|
101
|
-
},
|
|
102
138
|
};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
|
+
import type { ReplicationAdapter, SyncContext } from '@tallyui/core';
|
|
3
|
+
import { fetchByIds } from '../reconcile/ids';
|
|
4
|
+
import { MEDUSA_PRODUCT_FIELDS, toDocument, type MedusaProductCheckpoint } from './products';
|
|
5
|
+
import { withCalculatedPrices } from '../pricing/calculated';
|
|
6
|
+
import type { MedusaProductDocument } from '../schemas/products';
|
|
7
|
+
|
|
8
|
+
/** Admin API list limit (ADR-060); the default variant page size. */
|
|
9
|
+
const MAX_LIMIT = 1000;
|
|
10
|
+
/** The newest variant's `updated_at`: each pass's mark, and a fresh install's seed. */
|
|
11
|
+
const MARK_PATH = '/admin/product-variants?limit=1&order=-updated_at&fields=id,updated_at';
|
|
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
|
+
/**
|
|
27
|
+
* Variant feed for Medusa products (ADR-060, amendment 8).
|
|
28
|
+
*
|
|
29
|
+
* On Medusa 2.21 a price-only edit bumps the variant's `updated_at` but not
|
|
30
|
+
* the product's, through both the admin's batch route and the single-variant
|
|
31
|
+
* route, so the product feed never sees it. This pull adapter pages changed
|
|
32
|
+
* variants with the same pass and offset design as `medusaProductReplication`
|
|
33
|
+
* and re-delivers their parent products, re-fetched with the id reconcile's
|
|
34
|
+
* `fetchByIds` in the same document shape, into the `products` collection.
|
|
35
|
+
* It runs as a sub-adapter of the connector's combined `replication.products`
|
|
36
|
+
* adapter (`combinePullAdapters`), not as its own replication. Parents that
|
|
37
|
+
* no longer exist are skipped; deletions are the id reconcile's job.
|
|
38
|
+
*
|
|
39
|
+
* On a fresh install `seedCheckpoint` starts the cursor at the variant mark,
|
|
40
|
+
* read before the product feed's first pass, so the catalogue downloads once.
|
|
41
|
+
* An upgrade (a stored product checkpoint, none for this feed) is not seeded:
|
|
42
|
+
* its first pass re-delivers every product that has variants, once. That is
|
|
43
|
+
* deliberate: it heals any price change the product feed missed before this
|
|
44
|
+
* feed existed.
|
|
45
|
+
*
|
|
46
|
+
* `variantPageSize` (the variant page `limit`) is for tests and tuning.
|
|
47
|
+
*/
|
|
48
|
+
export const createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT): ReplicationAdapter<any, MedusaProductCheckpoint> => ({
|
|
49
|
+
pull: {
|
|
50
|
+
// The next call's unchanged-mark check then ends at one mark read, unless
|
|
51
|
+
// a variant changed since.
|
|
52
|
+
async seedCheckpoint(context) {
|
|
53
|
+
const markData = await get(MARK_PATH, context);
|
|
54
|
+
return { offset: 0, updated_at: markData.variants?.[0]?.updated_at ?? '', pass_mark: undefined, pass_count: undefined };
|
|
55
|
+
},
|
|
56
|
+
async handler(lastCheckpoint, batchSize, context) {
|
|
57
|
+
let offset = lastCheckpoint?.offset ?? 0;
|
|
58
|
+
let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? '';
|
|
59
|
+
let passCount = lastCheckpoint?.pass_count;
|
|
60
|
+
if (offset === 0 && lastCheckpoint?.pass_mark === undefined) {
|
|
61
|
+
const markData = await get(MARK_PATH, context);
|
|
62
|
+
passMark = markData.variants?.[0]?.updated_at ?? passMark;
|
|
63
|
+
if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
|
|
64
|
+
return { documents: [], checkpoint: lastCheckpoint };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const page = (from: number): Promise<{ variants?: Array<{ product_id: string }>; count: number }> => {
|
|
68
|
+
// Offsets need a total order, so page by the unique id within the fixed updated_at window.
|
|
69
|
+
const params = new URLSearchParams({ limit: String(variantPageSize), offset: String(from), order: 'id', fields: 'id,product_id' });
|
|
70
|
+
// Medusa 2.21 honours only the operator form; `updated_at[gte]` is silently dropped.
|
|
71
|
+
// The columns are timestamptz and `$gte` includes ties, as in the product feed.
|
|
72
|
+
if (lastCheckpoint?.updated_at) params.set('updated_at[$gte]', lastCheckpoint.updated_at);
|
|
73
|
+
return get(`/admin/product-variants?${params}`, context);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// RxDB stops pulling on a page shorter than batchSize, so keep reading
|
|
77
|
+
// variant pages until enough parents are delivered or the pass ends.
|
|
78
|
+
// Count delivered documents, not parent ids, as Vendure's feed does, so
|
|
79
|
+
// deleted parents (skipped) never cut a call short mid-pass.
|
|
80
|
+
const seen = new Set<string>();
|
|
81
|
+
const documents: Record<string, unknown>[] = [];
|
|
82
|
+
let complete = false;
|
|
83
|
+
while (!complete && documents.length < batchSize) {
|
|
84
|
+
let data = await page(offset);
|
|
85
|
+
if (offset > 0 && (!data.variants?.length || data.count < (passCount ?? data.count))) {
|
|
86
|
+
offset = 0; // Rows vanished mid-pass: restart; re-reads are harmless, skips are not.
|
|
87
|
+
data = await page(0);
|
|
88
|
+
}
|
|
89
|
+
const variants = data.variants ?? [];
|
|
90
|
+
if (offset === 0) passCount = data.count;
|
|
91
|
+
const parentIds = [...new Set(variants.map((v) => String(v.product_id)))].filter((id) => !seen.has(id));
|
|
92
|
+
parentIds.forEach((id) => seen.add(id));
|
|
93
|
+
if (parentIds.length) {
|
|
94
|
+
documents.push(...(await fetchByIds(parentIds, context)).map((doc) => ({ ...doc, _deleted: false })));
|
|
95
|
+
}
|
|
96
|
+
offset += variants.length;
|
|
97
|
+
complete = offset >= data.count || !variants.length;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Keep the lower bound fixed while paging by id; advance it only at pass end.
|
|
101
|
+
// RxDB merges checkpoints, so explicitly clear pass state at completion.
|
|
102
|
+
const checkpoint: MedusaProductCheckpoint = complete
|
|
103
|
+
? { offset: 0, updated_at: passMark, pass_mark: undefined, pass_count: undefined }
|
|
104
|
+
: { offset, updated_at: lastCheckpoint?.updated_at ?? '', pass_mark: passMark, pass_count: passCount };
|
|
105
|
+
// RxDB saves no checkpoint from an empty page. If this call's variant
|
|
106
|
+
// pages mapped to no live parents but the cursor moved, the cursor would
|
|
107
|
+
// stick mid-pass and a later change below it would be lost. Carry the
|
|
108
|
+
// checkpoint on one current product; re-delivering it is harmless.
|
|
109
|
+
const moved = (['offset', 'updated_at', 'pass_mark', 'pass_count'] as const)
|
|
110
|
+
.some((key) => checkpoint[key] !== lastCheckpoint?.[key]);
|
|
111
|
+
if (!documents.length && moved) {
|
|
112
|
+
const carrier = await get(`/admin/products?${new URLSearchParams({ limit: '1', fields: MEDUSA_PRODUCT_FIELDS })}`, context);
|
|
113
|
+
const priced = await withCalculatedPrices((carrier.products ?? []).map(toDocument) as MedusaProductDocument[], context);
|
|
114
|
+
documents.push(...priced.map((doc) => ({ ...doc, _deleted: false })));
|
|
115
|
+
}
|
|
116
|
+
return { documents, checkpoint };
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
});
|
package/src/schemas/products.ts
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
import type { RxJsonSchema } from 'rxdb';
|
|
2
2
|
|
|
3
|
+
/** A store API variant's `calculated_price`: the fields the connector reads. Amounts are major units. */
|
|
4
|
+
export interface MedusaCalculatedPrice {
|
|
5
|
+
calculated_amount: number | null;
|
|
6
|
+
original_amount: number | null;
|
|
7
|
+
currency_code: string;
|
|
8
|
+
is_calculated_price_tax_inclusive: boolean;
|
|
9
|
+
is_original_price_tax_inclusive: boolean;
|
|
10
|
+
calculated_price?: { price_list_id?: string | null; price_list_type?: string | null };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A stored variant. `calculated_price`: an object when priced, `null` when not sold here, undefined in base-only mode. */
|
|
14
|
+
export interface MedusaVariantDocument {
|
|
15
|
+
id: string;
|
|
16
|
+
prices?: Array<{ amount: number; currency_code: string; price_list_id?: string | null }>;
|
|
17
|
+
calculated_price?: MedusaCalculatedPrice | null;
|
|
18
|
+
[field: string]: unknown;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A stored product; typed for the fields the pricing code reads. */
|
|
22
|
+
export interface MedusaProductDocument {
|
|
23
|
+
id: string;
|
|
24
|
+
status?: string;
|
|
25
|
+
variants?: MedusaVariantDocument[];
|
|
26
|
+
[field: string]: unknown;
|
|
27
|
+
}
|
|
28
|
+
|
|
3
29
|
/**
|
|
4
30
|
* MedusaJS v2 Product RxDB schema.
|
|
5
31
|
* Mirrors the Medusa Admin API product shape.
|
|
@@ -15,7 +41,8 @@ import type { RxJsonSchema } from 'rxdb';
|
|
|
15
41
|
*/
|
|
16
42
|
export const medusaProductSchema: RxJsonSchema<any> = {
|
|
17
43
|
title: 'Medusa Product',
|
|
18
|
-
|
|
44
|
+
// 1: declares `variants[].calculated_price` (backlog 44). A bump drops and resyncs (ConnectorSchemas).
|
|
45
|
+
version: 1,
|
|
19
46
|
type: 'object',
|
|
20
47
|
primaryKey: 'id',
|
|
21
48
|
properties: {
|
|
@@ -26,8 +53,10 @@ export const medusaProductSchema: RxJsonSchema<any> = {
|
|
|
26
53
|
title: {
|
|
27
54
|
type: 'string',
|
|
28
55
|
},
|
|
56
|
+
// Indexed fields must be required strings with a maxLength (RxDB SC34).
|
|
29
57
|
handle: {
|
|
30
58
|
type: 'string',
|
|
59
|
+
maxLength: 255,
|
|
31
60
|
},
|
|
32
61
|
subtitle: {
|
|
33
62
|
type: ['string', 'null'],
|
|
@@ -39,6 +68,7 @@ export const medusaProductSchema: RxJsonSchema<any> = {
|
|
|
39
68
|
type: 'string',
|
|
40
69
|
enum: ['draft', 'proposed', 'published', 'rejected'],
|
|
41
70
|
default: 'draft',
|
|
71
|
+
maxLength: 20,
|
|
42
72
|
},
|
|
43
73
|
thumbnail: {
|
|
44
74
|
type: ['string', 'null'],
|
|
@@ -168,6 +198,7 @@ export const medusaProductSchema: RxJsonSchema<any> = {
|
|
|
168
198
|
},
|
|
169
199
|
},
|
|
170
200
|
},
|
|
201
|
+
// Admin base prices.
|
|
171
202
|
prices: {
|
|
172
203
|
type: 'array',
|
|
173
204
|
items: {
|
|
@@ -181,6 +212,27 @@ export const medusaProductSchema: RxJsonSchema<any> = {
|
|
|
181
212
|
},
|
|
182
213
|
},
|
|
183
214
|
},
|
|
215
|
+
// The store API's price (D2b), as `MedusaCalculatedPrice`: an object in priced mode,
|
|
216
|
+
// `null` when the sales channel or region does not sell the variant, and absent in
|
|
217
|
+
// base-only mode, with no pricing context. No `additionalProperties: false`: the store
|
|
218
|
+
// API sends more fields (`id`, `original_price`) and can add others.
|
|
219
|
+
calculated_price: {
|
|
220
|
+
type: ['object', 'null'],
|
|
221
|
+
properties: {
|
|
222
|
+
calculated_amount: { type: ['number', 'null'] },
|
|
223
|
+
original_amount: { type: ['number', 'null'] },
|
|
224
|
+
currency_code: { type: 'string' },
|
|
225
|
+
is_calculated_price_tax_inclusive: { type: ['boolean', 'null'] },
|
|
226
|
+
is_original_price_tax_inclusive: { type: ['boolean', 'null'] },
|
|
227
|
+
calculated_price: {
|
|
228
|
+
type: 'object',
|
|
229
|
+
properties: {
|
|
230
|
+
price_list_id: { type: ['string', 'null'] },
|
|
231
|
+
price_list_type: { type: ['string', 'null'] },
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
},
|
|
184
236
|
},
|
|
185
237
|
},
|
|
186
238
|
},
|
|
@@ -192,5 +244,5 @@ export const medusaProductSchema: RxJsonSchema<any> = {
|
|
|
192
244
|
},
|
|
193
245
|
},
|
|
194
246
|
indexes: ['handle', 'status'],
|
|
195
|
-
required: ['id'],
|
|
247
|
+
required: ['id', 'handle', 'status'],
|
|
196
248
|
};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError, StoreSettingsError } from '@tallyui/core';
|
|
2
|
+
import type { StoreSettings, StoreSettingsChoice, SyncContext } from '@tallyui/core';
|
|
3
|
+
|
|
4
|
+
type Store = { id: string; default_region_id: string | null };
|
|
5
|
+
type Country = { iso_2: string };
|
|
6
|
+
type Region = { id: string; name: string; currency_code: string; countries?: Country[] };
|
|
7
|
+
type PricePreference = { attribute: string; value: string; is_tax_inclusive: boolean };
|
|
8
|
+
type SalesChannel = { id: string; name: string };
|
|
9
|
+
type ApiKey = { id: string; title: string; token: string; revoked_at: string | null; sales_channels?: SalesChannel[] };
|
|
10
|
+
type TaxRate = { rate: number | null; is_default: boolean; rules?: unknown[] };
|
|
11
|
+
type TaxRegion = { country_code: string; province_code: string | null; tax_rates?: TaxRate[] };
|
|
12
|
+
|
|
13
|
+
/** Except for 401/403 (`ConnectorUnauthorizedError`), a non-OK response becomes `StoreSettingsError('failed')`, carrying the HTTP status and Medusa's own `message`. */
|
|
14
|
+
async function get(context: SyncContext, path: string): Promise<any> {
|
|
15
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
16
|
+
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
17
|
+
signal: context.signal,
|
|
18
|
+
});
|
|
19
|
+
if (!response.ok) {
|
|
20
|
+
const body = await response.json().catch(() => ({}));
|
|
21
|
+
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ''}`, response.status);
|
|
22
|
+
throw new StoreSettingsError('failed', `Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ''}`);
|
|
23
|
+
}
|
|
24
|
+
return response.json();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function resolveRegion(regions: Region[], store: Store | undefined, choice?: StoreSettingsChoice): Region {
|
|
28
|
+
const region =
|
|
29
|
+
(choice?.region && regions.find((r) => r.id === choice.region)) ||
|
|
30
|
+
(store?.default_region_id && regions.find((r) => r.id === store.default_region_id)) ||
|
|
31
|
+
(regions.length === 1 ? regions[0] : undefined);
|
|
32
|
+
// A chosen region that no longer resolves falls through the same ladder, and ends here too: choice_required, never failed.
|
|
33
|
+
if (!region) throw new StoreSettingsError('choice_required', 'Medusa has more than one region; choose one', { regions: regions.map((r) => ({ id: r.id, name: r.name })) });
|
|
34
|
+
return region;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// A cashier-facing name, never the key's own token: its sales channel names (blank ones don't
|
|
38
|
+
// count), joined in order; a key with none falls back to its (developer-facing) title.
|
|
39
|
+
function channelName(key: ApiKey): string {
|
|
40
|
+
const names = (key.sales_channels ?? []).map((c) => c.name).filter((name) => name?.trim());
|
|
41
|
+
return names.length > 0 ? names.join(', ') : key.title;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Reads the store's currency, tax inclusivity and location tax rate, and the
|
|
46
|
+
* publishable-key channel, from Medusa's admin API only (TV4b). Read-only
|
|
47
|
+
* (ADR-048). Region, then country, then channel: the first ambiguity that
|
|
48
|
+
* needs a choice reports every choice known at that point, so the app asks
|
|
49
|
+
* once.
|
|
50
|
+
*/
|
|
51
|
+
export const medusaStoreSettings = async (context: SyncContext, choice?: StoreSettingsChoice): Promise<StoreSettings> => {
|
|
52
|
+
const [storeRes, regionsRes, pricePrefRes, apiKeysRes] = await Promise.all([
|
|
53
|
+
get(context, '/admin/stores?fields=id,default_region_id'),
|
|
54
|
+
get(context, '/admin/regions?limit=1000&fields=id,name,currency_code,*countries'),
|
|
55
|
+
get(context, '/admin/price-preferences?limit=1000'),
|
|
56
|
+
get(context, '/admin/api-keys?type=publishable&limit=1000&fields=id,title,token,revoked_at,sales_channels.id,sales_channels.name'),
|
|
57
|
+
]);
|
|
58
|
+
|
|
59
|
+
const region = resolveRegion(regionsRes.regions ?? [], storeRes.stores?.[0], choice);
|
|
60
|
+
|
|
61
|
+
const pricePreferences: PricePreference[] = pricePrefRes.price_preferences ?? [];
|
|
62
|
+
const pref =
|
|
63
|
+
pricePreferences.find((p) => p.attribute === 'region_id' && p.value === region.id) ??
|
|
64
|
+
pricePreferences.find((p) => p.attribute === 'currency_code' && p.value === region.currency_code);
|
|
65
|
+
const pricesIncludeTax = pref?.is_tax_inclusive ?? false;
|
|
66
|
+
|
|
67
|
+
const countries = region.countries ?? [];
|
|
68
|
+
const chosenCountry = choice?.country?.toLowerCase();
|
|
69
|
+
// A chosen country outside the region is a mismatch, never silently replaced: the tax rate would differ from what the server charges.
|
|
70
|
+
const countryCode = chosenCountry ? countries.find((c) => c.iso_2.toLowerCase() === chosenCountry)?.iso_2 : countries.length === 1 ? countries[0]!.iso_2 : undefined;
|
|
71
|
+
|
|
72
|
+
// Once the country is known, its tax region tells us the rate; ambiguity is reported below either way.
|
|
73
|
+
let taxRegions: TaxRegion[] = [];
|
|
74
|
+
if (countryCode !== undefined) {
|
|
75
|
+
const taxRegionsRes = await get(context, `/admin/tax-regions?country_code=${encodeURIComponent(countryCode)}&limit=1000&fields=id,country_code,province_code,*tax_rates`);
|
|
76
|
+
taxRegions = taxRegionsRes.tax_regions ?? [];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const apiKeys: ApiKey[] = apiKeysRes.api_keys ?? [];
|
|
80
|
+
const availableKeys = apiKeys.filter((k) => !k.revoked_at);
|
|
81
|
+
// No publishable key at all is a store misconfiguration, not a choice the app can offer.
|
|
82
|
+
if (availableKeys.length === 0) throw new StoreSettingsError('failed', 'Medusa has no publishable API key; create one in the admin');
|
|
83
|
+
const channelKey =
|
|
84
|
+
(choice?.channel && availableKeys.find((k) => k.id === choice.channel)) ||
|
|
85
|
+
(availableKeys.length === 1 ? availableKeys[0] : undefined);
|
|
86
|
+
|
|
87
|
+
if (countryCode === undefined || !channelKey) {
|
|
88
|
+
const message = chosenCountry && countryCode === undefined ? "the chosen country isn't in this region; choose a country" : 'Medusa needs a country and/or sales channel choice';
|
|
89
|
+
throw new StoreSettingsError('choice_required', message, {
|
|
90
|
+
countries: countries.map((c) => c.iso_2.toLowerCase()),
|
|
91
|
+
channels: availableKeys.map((k) => ({ id: k.id, name: channelName(k) })),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The country's own tax region (province_code null); a province-level one is not the store's rate.
|
|
96
|
+
const countryTaxRegion = taxRegions.find((tr) => tr.province_code === null);
|
|
97
|
+
// A rate with rules is a product/customer-specific override, not a tax class, and is never the default.
|
|
98
|
+
const eligibleRates = (countryTaxRegion?.tax_rates ?? []).filter((r) => !r.rules || r.rules.length === 0);
|
|
99
|
+
const defaultRate = eligibleRates.find((r) => r.is_default);
|
|
100
|
+
// No tax region, or no default rate: Medusa's system provider adds no tax line, so default is 0 — never a silent guess.
|
|
101
|
+
const taxRatesPpm = { default: defaultRate?.rate != null ? Math.round(defaultRate.rate * 10_000) : 0 };
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
currency: region.currency_code.toUpperCase(),
|
|
105
|
+
pricesIncludeTax,
|
|
106
|
+
taxRatesPpm,
|
|
107
|
+
// The publishable key is a public credential, as storefronts embed it, so it may sit here.
|
|
108
|
+
// It never appears in an error message, `choices`, or console output — only in this context.
|
|
109
|
+
pricingContext: {
|
|
110
|
+
region_id: region.id,
|
|
111
|
+
currency_code: region.currency_code.toLowerCase(),
|
|
112
|
+
publishable_key: channelKey.token,
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
};
|
package/src/sync/products.ts
CHANGED
|
@@ -74,7 +74,8 @@ export const medusaProductSync: CollectionSync = {
|
|
|
74
74
|
|
|
75
75
|
async fetchModifiedAfter(date: string, context: SyncContext): Promise<any[]> {
|
|
76
76
|
const response = await fetch(
|
|
77
|
-
|
|
77
|
+
// Medusa 2.21 honours only the operator form; `updated_at[gte]` is silently dropped.
|
|
78
|
+
`${context.baseUrl}/admin/products?updated_at[$gte]=${date}&limit=100&fields=*variants,*variants.prices,*images,*categories,*tags,*options,*options.values`,
|
|
78
79
|
{
|
|
79
80
|
headers: {
|
|
80
81
|
...context.headers,
|