@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.
@@ -1,15 +1,116 @@
1
- import type { ProductTraits } from '@tallyui/core';
1
+ import { minorUnitDigits, moneyToMajor, resolvePrice } from '@tallyui/core';
2
+ import type { ProductPrice, ProductTraits, StockLevel } from '@tallyui/core';
3
+ import type { MedusaCalculatedPrice, MedusaProductDocument, MedusaVariantDocument } from '../schemas/products';
4
+
5
+ function productStock(variants: StockLevel[]): StockLevel {
6
+ if (!variants.length) return { status: 'unknown' };
7
+ const status = variants.some((stock) => stock.status === 'in_stock') ? 'in_stock'
8
+ : variants.some((stock) => stock.status === 'backorder') ? 'backorder'
9
+ : variants.every((stock) => stock.status === 'out_of_stock') ? 'out_of_stock' : 'unknown';
10
+ const quantity = variants.every((stock) => stock.quantity != null)
11
+ ? variants.reduce((sum, stock) => sum + stock.quantity!, 0) : undefined;
12
+ return quantity === undefined ? { status } : { status, quantity };
13
+ }
14
+
15
+ /**
16
+ * Units a Medusa variant can sell now.
17
+ *
18
+ * The Store API computes `inventory_quantity`; the Admin API does not, so
19
+ * otherwise sum available stock (stocked minus reserved) across locations
20
+ * for each inventory item, divided by the units the variant needs of it,
21
+ * and take the scarcest item. Null when neither is present.
22
+ */
23
+ function variantQuantity(variant: any): number | null {
24
+ if (variant?.inventory_quantity != null) return variant.inventory_quantity;
25
+ const items: any[] = variant?.inventory_items ?? [];
26
+ const known = items.filter((item) => item?.inventory?.location_levels);
27
+ if (!known.length) return null;
28
+ return Math.min(
29
+ ...known.map((item) => {
30
+ const available = item.inventory.location_levels.reduce(
31
+ (sum: number, level: any) =>
32
+ sum + Number(level?.stocked_quantity ?? 0) - Number(level?.reserved_quantity ?? 0),
33
+ 0,
34
+ );
35
+ return Math.floor(available / Number(item.required_quantity || 1));
36
+ }),
37
+ );
38
+ }
39
+
40
+ // Medusa v2 amounts are major units (12 = €12.00), not cents.
41
+ const toMinor = (amount: unknown, currency: string) =>
42
+ Math.round(Number(amount) * 10 ** minorUnitDigits(currency));
43
+
44
+ const taxFlag = (flag: unknown) => (typeof flag === 'boolean' ? { taxInclusive: flag } : {});
45
+
46
+ /**
47
+ * Priced mode (D2b): the store API's calculated price, in the pricing
48
+ * context's currency, is what Medusa charges. `null` (not sold in this
49
+ * channel or region) gives no price. A sale list adds a sale entry below the
50
+ * original price; an override list replaces the base price.
51
+ */
52
+ function calculatedPrices(calc: MedusaCalculatedPrice | null): ProductPrice[] {
53
+ if (!calc?.currency_code || calc.original_amount == null || calc.calculated_amount == null) return [];
54
+ const currency = calc.currency_code.toUpperCase();
55
+ const type = calc.calculated_price?.price_list_type;
56
+ if (type === 'override') {
57
+ return [{ amount: toMinor(calc.calculated_amount, currency), currency, kind: 'base', ...taxFlag(calc.is_calculated_price_tax_inclusive) }];
58
+ }
59
+ const prices: ProductPrice[] = [{ amount: toMinor(calc.original_amount, currency), currency, kind: 'base', ...taxFlag(calc.is_original_price_tax_inclusive) }];
60
+ if (type === 'sale' && calc.calculated_amount < calc.original_amount) {
61
+ prices.push({ amount: toMinor(calc.calculated_amount, currency), currency, kind: 'sale', ...taxFlag(calc.is_calculated_price_tax_inclusive) });
62
+ }
63
+ return prices;
64
+ }
65
+
66
+ function variantPrices(variant: MedusaVariantDocument | undefined): ProductPrice[] {
67
+ if (!variant) return [];
68
+ // Priced mode never falls back to the admin prices.
69
+ if (variant.calculated_price !== undefined) return calculatedPrices(variant.calculated_price);
70
+ const prices: ProductPrice[] = [];
71
+ const seen = new Set<string>();
72
+
73
+ // Base-only mode. Base prices: the variant's own prices, first per currency, skipping
74
+ // price-list overrides.
75
+ for (const price of variant.prices ?? []) {
76
+ if (price?.price_list_id || price?.amount == null || !price.currency_code) continue;
77
+ const currency = String(price.currency_code).toUpperCase();
78
+ if (seen.has(currency)) continue;
79
+ seen.add(currency);
80
+ prices.push({ amount: toMinor(price.amount, currency), currency, kind: 'base' });
81
+ }
82
+ return prices;
83
+ }
84
+
85
+ /** Priced mode: the store API has priced this document (any variant carries `calculated_price`, even `null`). */
86
+ const isPriced = (doc: MedusaProductDocument) => (doc.variants ?? []).some((v) => v.calculated_price !== undefined);
87
+
88
+ /** Priced mode: what `getPrices` plus `resolvePrice` give, the current or the base ('was' when a sale applies), as a major-unit string. */
89
+ function pricedMajor(doc: MedusaProductDocument, which: 'current' | 'base'): string | undefined {
90
+ const resolved = resolvePrice(variantPrices(doc.variants?.[0]));
91
+ const money = which === 'base' ? resolved?.was ?? resolved?.current : resolved?.current;
92
+ return money ? moneyToMajor(money).toFixed(2) : undefined;
93
+ }
94
+
95
+ function variantStock(variant: any): StockLevel {
96
+ if (!variant) return { status: 'unknown' };
97
+ if (variant.manage_inventory === false) return { status: 'in_stock' };
98
+ const quantity = variantQuantity(variant);
99
+ if (quantity == null) return { status: 'unknown' };
100
+ if (quantity > 0) return { status: 'in_stock', quantity };
101
+ return { status: variant.allow_backorder ? 'backorder' : 'out_of_stock', quantity };
102
+ }
2
103
 
3
104
  /**
4
105
  * Medusa v2 product trait implementations.
5
106
  *
6
107
  * Key mapping differences from WooCommerce:
7
108
  * - Product name is `title` (not `name`)
8
- * - Price lives on `variants[0].prices[0].amount` (cents, integer)
109
+ * - Price lives on `variants[0].prices[0].amount` (major units: 12 = 12.00)
9
110
  * - Images use `url` (not `src`)
10
111
  * - SKU/barcode live on variants, not the product
11
112
  * - Categories use `name`, tags use `value`
12
- * - Stock is per-variant via `inventory_quantity`
113
+ * - Stock is per-variant: `inventory_quantity` (Store API) or inventory levels (Admin API)
13
114
  */
14
115
  export const medusaProductTraits: ProductTraits = {
15
116
  getId: (doc) => doc.id,
@@ -21,20 +122,36 @@ export const medusaProductTraits: ProductTraits = {
21
122
  return doc.variants?.[0]?.sku || undefined;
22
123
  },
23
124
 
125
+ getPrices: (doc) => variantPrices(doc.variants?.[0]),
126
+
127
+ getStock: (doc) => productStock((doc.variants ?? []).map(variantStock)),
128
+
129
+ getVariants: (doc) => (doc.variants ?? []).map((v: any) => ({
130
+ id: v.id,
131
+ title: v.title ?? undefined,
132
+ sku: v.sku || undefined,
133
+ barcode: v.barcode || v.ean || v.upc || undefined,
134
+ prices: variantPrices(v),
135
+ stock: variantStock(v),
136
+ })),
137
+
138
+ // getPrice, getRegularPrice and getSalePrice: deprecated; use `getPrices`. In priced mode the
139
+ // first two give what `getPrices` resolves to, never the admin prices.
24
140
  getPrice: (doc) => {
25
- // Medusa stores prices as integers in smallest currency unit (cents)
141
+ if (isPriced(doc)) return pricedMajor(doc, 'current');
142
+ // Medusa v2 amounts are already major units (not cents).
26
143
  const amount = doc.variants?.[0]?.prices?.[0]?.amount;
27
144
  if (amount == null) return undefined;
28
- // Convert cents to decimal string (assumes 2 decimal places)
29
- return (amount / 100).toFixed(2);
145
+ return Number(amount).toFixed(2);
30
146
  },
31
147
 
32
148
  getRegularPrice: (doc) => {
149
+ if (isPriced(doc)) return pricedMajor(doc, 'base');
33
150
  // Medusa doesn't have a separate regular/sale price on the product level
34
151
  // The pricing engine handles this via price lists
35
152
  const amount = doc.variants?.[0]?.prices?.[0]?.amount;
36
153
  if (amount == null) return undefined;
37
- return (amount / 100).toFixed(2);
154
+ return Number(amount).toFixed(2);
38
155
  },
39
156
 
40
157
  getSalePrice: () => {
@@ -70,19 +187,26 @@ export const medusaProductTraits: ProductTraits = {
70
187
  if (variant.manage_inventory === false) return 'instock';
71
188
  if (variant.allow_backorder) return 'onbackorder';
72
189
 
73
- const qty = variant.inventory_quantity;
190
+ const qty = variantQuantity(variant);
74
191
  if (qty == null) return 'unknown';
75
192
  return qty > 0 ? 'instock' : 'outofstock';
76
193
  },
77
194
 
78
195
  getStockQuantity: (doc) => {
79
- return doc.variants?.[0]?.inventory_quantity ?? null;
196
+ return variantQuantity(doc.variants?.[0]);
80
197
  },
81
198
 
82
199
  hasVariants: (doc) => {
83
200
  return (doc.variants?.length ?? 0) > 1;
84
201
  },
85
202
 
203
+ // In priced mode, a product with no variant that yields a price (a null calculated price, or null
204
+ // amounts) is not sold in this channel or region.
205
+ isSellable: (doc: MedusaProductDocument) => (doc.status === undefined || doc.status === 'published')
206
+ && (!isPriced(doc) || doc.variants!.some((v) => variantPrices(v).length > 0)),
207
+
208
+ getVariantCount: (doc) => doc.variants?.length ?? 1,
209
+
86
210
  getType: (doc) => {
87
211
  // Medusa doesn't have product types like WooCommerce
88
212
  // A gift card is the closest equivalent to a "type"
@@ -1,260 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { medusaProductTraits } from '../traits/product';
3
-
4
- /**
5
- * Realistic MedusaJS v2 product document, shaped like the Admin API response.
6
- */
7
- const fullProduct = {
8
- id: 'prod_01H8X3K4M2N5P7Q9R1S3T5V7',
9
- title: 'Commercial Espresso Machine',
10
- handle: 'commercial-espresso-machine',
11
- status: 'published',
12
- description: 'High-end commercial espresso machine with dual boilers.',
13
- thumbnail: 'https://cdn.example/thumb-espresso.jpg',
14
- is_giftcard: false,
15
- images: [
16
- { id: 'img_01', url: 'https://cdn.example/espresso-full.jpg' },
17
- { id: 'img_02', url: 'https://cdn.example/espresso-back.jpg' },
18
- ],
19
- categories: [
20
- { id: 'pcat_01', name: 'Equipment' },
21
- { id: 'pcat_02', name: 'Café Gear' },
22
- ],
23
- variants: [
24
- {
25
- id: 'var_01H',
26
- sku: 'MED-ESP-001',
27
- barcode: '9876543210001',
28
- ean: null,
29
- upc: null,
30
- inventory_quantity: 8,
31
- manage_inventory: true,
32
- allow_backorder: false,
33
- prices: [
34
- { currency_code: 'usd', amount: 89900 },
35
- { currency_code: 'eur', amount: 82500 },
36
- ],
37
- },
38
- ],
39
- };
40
-
41
- const multiVariantProduct = {
42
- ...fullProduct,
43
- id: 'prod_multi',
44
- variants: [
45
- {
46
- id: 'var_01',
47
- sku: 'MED-ESP-S',
48
- barcode: null,
49
- ean: '4006381333931',
50
- upc: null,
51
- inventory_quantity: 3,
52
- manage_inventory: true,
53
- allow_backorder: false,
54
- prices: [{ currency_code: 'usd', amount: 89900 }],
55
- },
56
- {
57
- id: 'var_02',
58
- sku: 'MED-ESP-L',
59
- barcode: null,
60
- ean: null,
61
- upc: '036000291452',
62
- inventory_quantity: 0,
63
- manage_inventory: true,
64
- allow_backorder: true,
65
- prices: [{ currency_code: 'usd', amount: 109900 }],
66
- },
67
- ],
68
- };
69
-
70
- const giftcardProduct = {
71
- ...fullProduct,
72
- id: 'prod_gc',
73
- is_giftcard: true,
74
- variants: [
75
- {
76
- id: 'var_gc',
77
- sku: 'GC-50',
78
- barcode: null,
79
- ean: null,
80
- upc: null,
81
- inventory_quantity: null,
82
- manage_inventory: false,
83
- allow_backorder: false,
84
- prices: [{ currency_code: 'usd', amount: 5000 }],
85
- },
86
- ],
87
- };
88
-
89
- const minimalProduct = {
90
- id: 'prod_empty',
91
- };
92
-
93
- describe('Medusa product traits', () => {
94
- describe('getId', () => {
95
- it('returns the product id', () => {
96
- expect(medusaProductTraits.getId(fullProduct)).toBe('prod_01H8X3K4M2N5P7Q9R1S3T5V7');
97
- });
98
- });
99
-
100
- describe('getName', () => {
101
- it('returns the title (not name)', () => {
102
- expect(medusaProductTraits.getName(fullProduct)).toBe('Commercial Espresso Machine');
103
- });
104
-
105
- it('returns empty string for missing title', () => {
106
- expect(medusaProductTraits.getName(minimalProduct)).toBe('');
107
- });
108
- });
109
-
110
- describe('getSku', () => {
111
- it('reads SKU from the first variant', () => {
112
- expect(medusaProductTraits.getSku(fullProduct)).toBe('MED-ESP-001');
113
- });
114
-
115
- it('returns undefined when no variants', () => {
116
- expect(medusaProductTraits.getSku(minimalProduct)).toBeUndefined();
117
- });
118
- });
119
-
120
- describe('getPrice', () => {
121
- it('converts cents to decimal string', () => {
122
- expect(medusaProductTraits.getPrice(fullProduct)).toBe('899.00');
123
- });
124
-
125
- it('returns undefined when no variants/prices', () => {
126
- expect(medusaProductTraits.getPrice(minimalProduct)).toBeUndefined();
127
- });
128
- });
129
-
130
- describe('getRegularPrice / getSalePrice / isOnSale', () => {
131
- it('regular price matches price (Medusa uses price lists, not product-level sales)', () => {
132
- expect(medusaProductTraits.getRegularPrice(fullProduct)).toBe('899.00');
133
- });
134
-
135
- it('sale price is always undefined (handled by price lists)', () => {
136
- expect(medusaProductTraits.getSalePrice(fullProduct)).toBeUndefined();
137
- });
138
-
139
- it('isOnSale is always false (no product-level sale flag)', () => {
140
- expect(medusaProductTraits.isOnSale(fullProduct)).toBe(false);
141
- });
142
- });
143
-
144
- describe('getImageUrl / getImageUrls', () => {
145
- it('prefers thumbnail over images[0].url', () => {
146
- expect(medusaProductTraits.getImageUrl(fullProduct)).toBe('https://cdn.example/thumb-espresso.jpg');
147
- });
148
-
149
- it('falls back to images[0].url when no thumbnail', () => {
150
- const noThumb = { ...fullProduct, thumbnail: null };
151
- expect(medusaProductTraits.getImageUrl(noThumb)).toBe('https://cdn.example/espresso-full.jpg');
152
- });
153
-
154
- it('returns all URLs (thumbnail + images, deduplicated)', () => {
155
- const urls = medusaProductTraits.getImageUrls(fullProduct);
156
- expect(urls).toContain('https://cdn.example/thumb-espresso.jpg');
157
- expect(urls).toContain('https://cdn.example/espresso-full.jpg');
158
- expect(urls).toContain('https://cdn.example/espresso-back.jpg');
159
- });
160
-
161
- it('returns undefined / empty for missing images', () => {
162
- expect(medusaProductTraits.getImageUrl(minimalProduct)).toBeUndefined();
163
- expect(medusaProductTraits.getImageUrls(minimalProduct)).toEqual([]);
164
- });
165
- });
166
-
167
- describe('getDescription', () => {
168
- it('returns the description', () => {
169
- expect(medusaProductTraits.getDescription(fullProduct)).toBe(
170
- 'High-end commercial espresso machine with dual boilers.'
171
- );
172
- });
173
-
174
- it('returns undefined when missing', () => {
175
- expect(medusaProductTraits.getDescription(minimalProduct)).toBeUndefined();
176
- });
177
- });
178
-
179
- describe('getStockStatus', () => {
180
- it('returns instock when quantity > 0', () => {
181
- expect(medusaProductTraits.getStockStatus(fullProduct)).toBe('instock');
182
- });
183
-
184
- it('returns outofstock when quantity is 0 and no backorder', () => {
185
- const outOfStock = {
186
- ...fullProduct,
187
- variants: [{ ...fullProduct.variants[0], inventory_quantity: 0 }],
188
- };
189
- expect(medusaProductTraits.getStockStatus(outOfStock)).toBe('outofstock');
190
- });
191
-
192
- it('returns onbackorder when allow_backorder is true', () => {
193
- expect(medusaProductTraits.getStockStatus(multiVariantProduct)).toBe('instock');
194
- });
195
-
196
- it('returns instock when manage_inventory is false', () => {
197
- expect(medusaProductTraits.getStockStatus(giftcardProduct)).toBe('instock');
198
- });
199
-
200
- it('returns unknown when no variants', () => {
201
- expect(medusaProductTraits.getStockStatus(minimalProduct)).toBe('unknown');
202
- });
203
- });
204
-
205
- describe('getStockQuantity', () => {
206
- it('returns the first variant quantity', () => {
207
- expect(medusaProductTraits.getStockQuantity(fullProduct)).toBe(8);
208
- });
209
-
210
- it('returns null when no variants', () => {
211
- expect(medusaProductTraits.getStockQuantity(minimalProduct)).toBeNull();
212
- });
213
- });
214
-
215
- describe('hasVariants / getType', () => {
216
- it('single variant = no variants', () => {
217
- expect(medusaProductTraits.hasVariants(fullProduct)).toBe(false);
218
- });
219
-
220
- it('multiple variants detected', () => {
221
- expect(medusaProductTraits.hasVariants(multiVariantProduct)).toBe(true);
222
- });
223
-
224
- it('simple type for single variant', () => {
225
- expect(medusaProductTraits.getType(fullProduct)).toBe('simple');
226
- });
227
-
228
- it('variable type for multiple variants', () => {
229
- expect(medusaProductTraits.getType(multiVariantProduct)).toBe('variable');
230
- });
231
-
232
- it('giftcard type detected', () => {
233
- expect(medusaProductTraits.getType(giftcardProduct)).toBe('giftcard');
234
- });
235
- });
236
-
237
- describe('getBarcode', () => {
238
- it('returns barcode from first variant', () => {
239
- expect(medusaProductTraits.getBarcode(fullProduct)).toBe('9876543210001');
240
- });
241
-
242
- it('falls back to EAN', () => {
243
- expect(medusaProductTraits.getBarcode(multiVariantProduct)).toBe('4006381333931');
244
- });
245
-
246
- it('returns undefined when no barcode fields', () => {
247
- expect(medusaProductTraits.getBarcode(minimalProduct)).toBeUndefined();
248
- });
249
- });
250
-
251
- describe('getCategoryNames', () => {
252
- it('returns category name strings', () => {
253
- expect(medusaProductTraits.getCategoryNames(fullProduct)).toEqual(['Equipment', 'Café Gear']);
254
- });
255
-
256
- it('returns empty array when no categories', () => {
257
- expect(medusaProductTraits.getCategoryNames(minimalProduct)).toEqual([]);
258
- });
259
- });
260
- });
@@ -1,169 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import type { SyncContext } from '@tallyui/core';
3
-
4
- import { medusaProductReplication } from './products';
5
-
6
- const context: SyncContext = {
7
- connectorId: 'medusa',
8
- baseUrl: 'https://my-medusa-backend.com',
9
- headers: { Authorization: 'Bearer test_token' },
10
- };
11
-
12
- describe('medusaProductReplication.pull.handler', () => {
13
- beforeEach(() => {
14
- vi.restoreAllMocks();
15
- });
16
-
17
- it('fetches products from initial checkpoint (undefined)', async () => {
18
- const mockProducts = [
19
- { id: 'prod_01', title: 'Widget', updated_at: '2026-01-01T00:00:00Z' },
20
- { id: 'prod_02', title: 'Gadget', updated_at: '2026-01-02T00:00:00Z' },
21
- ];
22
-
23
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
24
- new Response(JSON.stringify({ products: mockProducts }), { status: 200 }),
25
- );
26
-
27
- const result = await medusaProductReplication.pull.handler(undefined, 100, context);
28
-
29
- expect(result.documents).toHaveLength(2);
30
- expect(result.documents[0]._deleted).toBe(false);
31
- expect(result.checkpoint).toEqual({
32
- offset: 0,
33
- updated_at: '2026-01-02T00:00:00Z',
34
- });
35
-
36
- const calledUrl = (globalThis.fetch as any).mock.calls[0][0];
37
- expect(calledUrl).toContain('offset=0');
38
- expect(calledUrl).toContain('limit=100');
39
- expect(calledUrl).toContain('fields=');
40
- });
41
-
42
- it('passes updated_at filter and offset from checkpoint', async () => {
43
- const mockProducts = [
44
- { id: 'prod_03', title: 'Thingamajig', updated_at: '2026-02-01T00:00:00Z' },
45
- ];
46
-
47
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
48
- new Response(JSON.stringify({ products: mockProducts }), { status: 200 }),
49
- );
50
-
51
- const checkpoint = { offset: 50, updated_at: '2026-01-15T00:00:00Z' };
52
- const result = await medusaProductReplication.pull.handler(checkpoint, 100, context);
53
-
54
- const calledUrl = (globalThis.fetch as any).mock.calls[0][0];
55
- expect(calledUrl).toContain('offset=50');
56
- expect(calledUrl).toContain('updated_at%5Bgte%5D=2026-01-15T00%3A00%3A00Z');
57
-
58
- // Batch smaller than batchSize resets offset to 0
59
- expect(result.checkpoint.offset).toBe(0);
60
- });
61
-
62
- it('advances offset when batch equals batchSize', async () => {
63
- const mockProducts = Array.from({ length: 25 }, (_, i) => ({
64
- id: `prod_${i}`,
65
- title: `Product ${i}`,
66
- updated_at: '2026-01-01T00:00:00Z',
67
- }));
68
-
69
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
70
- new Response(JSON.stringify({ products: mockProducts }), { status: 200 }),
71
- );
72
-
73
- const result = await medusaProductReplication.pull.handler(undefined, 25, context);
74
-
75
- expect(result.checkpoint.offset).toBe(25);
76
- });
77
-
78
- it('throws on non-OK response', async () => {
79
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
80
- new Response('Internal Server Error', { status: 500 }),
81
- );
82
-
83
- await expect(
84
- medusaProductReplication.pull.handler(undefined, 100, context),
85
- ).rejects.toThrow('Medusa API error: 500');
86
- });
87
-
88
- it('returns lastCheckpoint when no products are returned', async () => {
89
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
90
- new Response(JSON.stringify({ products: [] }), { status: 200 }),
91
- );
92
-
93
- const checkpoint = { offset: 0, updated_at: '2026-01-01T00:00:00Z' };
94
- const result = await medusaProductReplication.pull.handler(checkpoint, 100, context);
95
-
96
- expect(result.checkpoint).toEqual(checkpoint);
97
- });
98
- });
99
-
100
- describe('medusaProductReplication.push.handler', () => {
101
- beforeEach(() => {
102
- vi.restoreAllMocks();
103
- });
104
-
105
- it('sends POST for updates', async () => {
106
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
107
- new Response(JSON.stringify({}), { status: 200 }),
108
- );
109
-
110
- const conflicts = await medusaProductReplication.push!.handler(
111
- [{
112
- newDocumentState: { id: 'prod_01', title: 'Updated', _deleted: false } as any,
113
- assumedMasterState: { id: 'prod_01', title: 'Old', _deleted: false } as any,
114
- }],
115
- context,
116
- );
117
-
118
- expect(conflicts).toHaveLength(0);
119
- const [url, opts] = (globalThis.fetch as any).mock.calls[0];
120
- expect(url).toContain('/admin/products/prod_01');
121
- expect(opts.method).toBe('POST');
122
- });
123
-
124
- it('returns conflicts on server error', async () => {
125
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
126
- new Response('conflict', { status: 409 }),
127
- );
128
-
129
- const conflicts = await medusaProductReplication.push!.handler(
130
- [{
131
- newDocumentState: { id: 'prod_01', title: 'Updated', _deleted: false } as any,
132
- assumedMasterState: { id: 'prod_01', title: 'Server Version', _deleted: false } as any,
133
- }],
134
- context,
135
- );
136
-
137
- expect(conflicts).toHaveLength(1);
138
- expect(conflicts[0].title).toBe('Server Version');
139
- });
140
-
141
- it('returns conflicts on network failure', async () => {
142
- vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new Error('Network error'));
143
-
144
- const conflicts = await medusaProductReplication.push!.handler(
145
- [{
146
- newDocumentState: { id: 'prod_01', title: 'Updated', _deleted: false } as any,
147
- assumedMasterState: { id: 'prod_01', title: 'Server Version', _deleted: false } as any,
148
- }],
149
- context,
150
- );
151
-
152
- expect(conflicts).toHaveLength(1);
153
- });
154
-
155
- it('does not return conflict when assumedMasterState is absent', async () => {
156
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
157
- new Response('error', { status: 500 }),
158
- );
159
-
160
- const conflicts = await medusaProductReplication.push!.handler(
161
- [{
162
- newDocumentState: { id: 'prod_01', title: 'New Product', _deleted: false } as any,
163
- }],
164
- context,
165
- );
166
-
167
- expect(conflicts).toHaveLength(0);
168
- });
169
- });