@tallyui/connector-shopify 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Kilmurray and TallyUI contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.d.ts CHANGED
@@ -37,9 +37,9 @@ type ShopifyProductCheckpoint = {
37
37
  /**
38
38
  * Replication adapter for Shopify products.
39
39
  *
40
- * Implements pull (cursor-based pagination via Link header, filtered by
41
- * updated_at_min) and push (PUT to update individual products via Admin
42
- * REST API). Designed for use with RxDB's replicateRxCollection.
40
+ * Pull-only (cursor-based pagination via Link header, filtered by
41
+ * updated_at_min) for RxDB's replicateRxCollection. Catalogue data is
42
+ * server-owned; the POS never writes products.
43
43
  */
44
44
  declare const shopifyProductReplication: ReplicationAdapter<any, ShopifyProductCheckpoint>;
45
45
 
package/dist/index.js CHANGED
@@ -83,10 +83,37 @@ var shopifyProductSchema = {
83
83
  };
84
84
 
85
85
  // src/traits/product.ts
86
+ import { moneyFromMajor } from "@tallyui/core";
87
+ function productStock(variants) {
88
+ if (!variants.length) return { status: "unknown" };
89
+ const status = variants.some((stock) => stock.status === "in_stock") ? "in_stock" : variants.some((stock) => stock.status === "backorder") ? "backorder" : variants.every((stock) => stock.status === "out_of_stock") ? "out_of_stock" : "unknown";
90
+ const quantity = variants.every((stock) => stock.quantity != null) ? variants.reduce((sum, stock) => sum + stock.quantity, 0) : void 0;
91
+ return quantity === void 0 ? { status } : { status, quantity };
92
+ }
86
93
  var shopifyProductTraits = {
87
94
  getId: (doc) => String(doc.id),
88
95
  getName: (doc) => doc.title ?? "",
89
96
  getSku: (doc) => doc.variants?.[0]?.sku || void 0,
97
+ getPrices: (doc, context) => {
98
+ const variant = doc.variants?.[0];
99
+ if (!variant) return [];
100
+ const currency = context?.currency ?? "XXX";
101
+ const price = moneyFromMajor(variant.price, currency);
102
+ const compareAt = moneyFromMajor(variant.compare_at_price, currency);
103
+ if (!price) return [];
104
+ if (compareAt && compareAt.amount > price.amount) {
105
+ return [{ ...compareAt, kind: "base" }, { ...price, kind: "sale" }];
106
+ }
107
+ return [{ ...price, kind: "base" }];
108
+ },
109
+ getStock: (doc) => productStock((doc.variants ?? []).map((variant) => {
110
+ if (!variant) return { status: "unknown" };
111
+ if (variant.inventory_management == null) return { status: "in_stock" };
112
+ const quantity = variant.inventory_quantity ?? void 0;
113
+ if (quantity == null) return { status: "unknown" };
114
+ if (quantity > 0) return { status: "in_stock", quantity };
115
+ return { status: variant.inventory_policy === "continue" ? "backorder" : "out_of_stock", quantity };
116
+ })),
90
117
  getPrice: (doc) => doc.variants?.[0]?.price || void 0,
91
118
  getRegularPrice: (doc) => {
92
119
  const variant = doc.variants?.[0];
@@ -120,6 +147,8 @@ var shopifyProductTraits = {
120
147
  },
121
148
  getStockQuantity: (doc) => doc.variants?.[0]?.inventory_quantity ?? null,
122
149
  hasVariants: (doc) => (doc.variants?.length ?? 0) > 1,
150
+ isSellable: (doc) => doc.status === void 0 || doc.status === "active",
151
+ getVariantCount: (doc) => doc.variants?.length ?? 1,
123
152
  getType: (doc) => doc.product_type || "simple",
124
153
  getBarcode: (doc) => doc.variants?.[0]?.barcode || void 0,
125
154
  getCategoryNames: (doc) => {
@@ -229,38 +258,6 @@ var shopifyProductReplication = {
229
258
  const checkpoint = allProducts.length > 0 ? { updated_at: allProducts[allProducts.length - 1].updated_at } : lastCheckpoint ?? { updated_at: "" };
230
259
  return { documents, checkpoint };
231
260
  }
232
- },
233
- push: {
234
- async handler(changeRows, context) {
235
- const conflicts = [];
236
- for (const row of changeRows) {
237
- const doc = row.newDocumentState;
238
- try {
239
- const response = await fetch(
240
- `${context.baseUrl}/admin/api/2024-01/products/${doc.id}.json`,
241
- {
242
- method: "PUT",
243
- headers: {
244
- ...context.headers,
245
- "Content-Type": "application/json"
246
- },
247
- body: JSON.stringify({ product: doc }),
248
- signal: context.signal
249
- }
250
- );
251
- if (!response.ok) {
252
- if (row.assumedMasterState) {
253
- conflicts.push({ ...row.assumedMasterState, _deleted: false });
254
- }
255
- }
256
- } catch {
257
- if (row.assumedMasterState) {
258
- conflicts.push({ ...row.assumedMasterState, _deleted: false });
259
- }
260
- }
261
- }
262
- return conflicts;
263
- }
264
261
  }
265
262
  };
266
263
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/connector-shopify",
3
- "version": "1.0.0",
3
+ "version": "3.0.0-next.0",
4
4
  "type": "module",
5
5
  "description": "Shopify connector for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -15,14 +15,20 @@
15
15
  },
16
16
  "files": [
17
17
  "dist",
18
- "src"
18
+ "src",
19
+ "!src/**/*.test.ts"
19
20
  ],
20
21
  "license": "MIT",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/TallyUI/tallyui.git",
25
+ "directory": "connectors/shopify"
26
+ },
21
27
  "peerDependencies": {
22
- "@tallyui/core": "0.2.0"
28
+ "@tallyui/core": "^3.0.0-next.0"
23
29
  },
24
30
  "devDependencies": {
25
- "rxdb": "16.21.1"
31
+ "rxdb": "17.5.0"
26
32
  },
27
33
  "scripts": {
28
34
  "build": "tsup",
@@ -24,9 +24,9 @@ function normalizeId(product: any) {
24
24
  /**
25
25
  * Replication adapter for Shopify products.
26
26
  *
27
- * Implements pull (cursor-based pagination via Link header, filtered by
28
- * updated_at_min) and push (PUT to update individual products via Admin
29
- * REST API). Designed for use with RxDB's replicateRxCollection.
27
+ * Pull-only (cursor-based pagination via Link header, filtered by
28
+ * updated_at_min) for RxDB's replicateRxCollection. Catalogue data is
29
+ * server-owned; the POS never writes products.
30
30
  */
31
31
  export const shopifyProductReplication: ReplicationAdapter<any, ShopifyProductCheckpoint> = {
32
32
  pull: {
@@ -71,41 +71,4 @@ export const shopifyProductReplication: ReplicationAdapter<any, ShopifyProductCh
71
71
  return { documents, checkpoint };
72
72
  },
73
73
  },
74
-
75
- push: {
76
- async handler(changeRows, context) {
77
- const conflicts: any[] = [];
78
-
79
- for (const row of changeRows) {
80
- const doc = row.newDocumentState as any;
81
-
82
- try {
83
- const response = await fetch(
84
- `${context.baseUrl}/admin/api/2024-01/products/${doc.id}.json`,
85
- {
86
- method: 'PUT',
87
- headers: {
88
- ...context.headers,
89
- 'Content-Type': 'application/json',
90
- },
91
- body: JSON.stringify({ product: doc }),
92
- signal: context.signal,
93
- },
94
- );
95
-
96
- if (!response.ok) {
97
- if (row.assumedMasterState) {
98
- conflicts.push({ ...row.assumedMasterState, _deleted: false });
99
- }
100
- }
101
- } catch {
102
- if (row.assumedMasterState) {
103
- conflicts.push({ ...row.assumedMasterState, _deleted: false });
104
- }
105
- }
106
- }
107
-
108
- return conflicts;
109
- },
110
- },
111
74
  };
@@ -1,4 +1,15 @@
1
- import type { ProductTraits } from '@tallyui/core';
1
+ import { moneyFromMajor } from '@tallyui/core';
2
+ import type { ProductPrice, ProductTraits, StockLevel } from '@tallyui/core';
3
+
4
+ function productStock(variants: StockLevel[]): StockLevel {
5
+ if (!variants.length) return { status: 'unknown' };
6
+ const status = variants.some((stock) => stock.status === 'in_stock') ? 'in_stock'
7
+ : variants.some((stock) => stock.status === 'backorder') ? 'backorder'
8
+ : variants.every((stock) => stock.status === 'out_of_stock') ? 'out_of_stock' : 'unknown';
9
+ const quantity = variants.every((stock) => stock.quantity != null)
10
+ ? variants.reduce((sum, stock) => sum + stock.quantity!, 0) : undefined;
11
+ return quantity === undefined ? { status } : { status, quantity };
12
+ }
2
13
 
3
14
  /**
4
15
  * Shopify product trait implementations.
@@ -18,6 +29,31 @@ export const shopifyProductTraits: ProductTraits = {
18
29
 
19
30
  getSku: (doc) => doc.variants?.[0]?.sku || undefined,
20
31
 
32
+ getPrices: (doc, context) => {
33
+ const variant = doc.variants?.[0];
34
+ if (!variant) return [];
35
+ // REST variant prices are decimal strings in the shop currency.
36
+ const currency = context?.currency ?? 'XXX';
37
+ const price = moneyFromMajor(variant.price, currency);
38
+ const compareAt = moneyFromMajor(variant.compare_at_price, currency);
39
+ if (!price) return [];
40
+ // compare_at_price above price means `price` is a sale price.
41
+ if (compareAt && compareAt.amount > price.amount) {
42
+ return [{ ...compareAt, kind: 'base' }, { ...price, kind: 'sale' }] as ProductPrice[];
43
+ }
44
+ return [{ ...price, kind: 'base' }];
45
+ },
46
+
47
+ getStock: (doc) => productStock((doc.variants ?? []).map((variant: any): StockLevel => {
48
+ if (!variant) return { status: 'unknown' };
49
+ if (variant.inventory_management == null) return { status: 'in_stock' };
50
+ const quantity = variant.inventory_quantity ?? undefined;
51
+ if (quantity == null) return { status: 'unknown' };
52
+ if (quantity > 0) return { status: 'in_stock', quantity };
53
+ // inventory_policy 'continue' allows overselling.
54
+ return { status: variant.inventory_policy === 'continue' ? 'backorder' : 'out_of_stock', quantity };
55
+ })),
56
+
21
57
  getPrice: (doc) => doc.variants?.[0]?.price || undefined,
22
58
 
23
59
  getRegularPrice: (doc) => {
@@ -74,6 +110,10 @@ export const shopifyProductTraits: ProductTraits = {
74
110
 
75
111
  hasVariants: (doc) => (doc.variants?.length ?? 0) > 1,
76
112
 
113
+ isSellable: (doc) => doc.status === undefined || doc.status === 'active',
114
+
115
+ getVariantCount: (doc) => doc.variants?.length ?? 1,
116
+
77
117
  getType: (doc) => doc.product_type || 'simple',
78
118
 
79
119
  getBarcode: (doc) => doc.variants?.[0]?.barcode || undefined,
@@ -1,275 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { shopifyProductTraits } from '../traits/product';
3
-
4
- /**
5
- * Realistic Shopify product document, shaped like the Admin REST API response.
6
- */
7
- const fullProduct = {
8
- id: 7429873610823,
9
- title: 'Espresso Machine Pro',
10
- body_html: '<p>High-end espresso machine with dual boilers.</p>',
11
- vendor: 'BrewCraft',
12
- product_type: 'Equipment',
13
- handle: 'espresso-machine-pro',
14
- status: 'active',
15
- tags: 'coffee, equipment, pro-series',
16
- variants: [
17
- {
18
- id: 42304918372615,
19
- title: 'Silver',
20
- price: '599.99',
21
- compare_at_price: null,
22
- sku: 'ESP-PRO-SLV',
23
- barcode: '1234567890123',
24
- inventory_policy: 'deny',
25
- inventory_management: 'shopify',
26
- inventory_quantity: 15,
27
- option1: 'Silver',
28
- },
29
- {
30
- id: 42304918372616,
31
- title: 'Matte Black',
32
- price: '649.99',
33
- compare_at_price: '699.99',
34
- sku: 'ESP-PRO-BLK',
35
- barcode: '1234567890124',
36
- inventory_policy: 'deny',
37
- inventory_management: 'shopify',
38
- inventory_quantity: 3,
39
- option1: 'Matte Black',
40
- },
41
- ],
42
- options: [
43
- { id: 1, name: 'Color', position: 1, values: ['Silver', 'Matte Black'] },
44
- ],
45
- images: [
46
- { id: 1, src: 'https://cdn.shopify.com/espresso-front.jpg', alt: 'Front', position: 1 },
47
- { id: 2, src: 'https://cdn.shopify.com/espresso-black.jpg', alt: 'Black', position: 2 },
48
- ],
49
- image: {
50
- id: 1,
51
- src: 'https://cdn.shopify.com/espresso-front.jpg',
52
- alt: 'Front',
53
- },
54
- };
55
-
56
- /**
57
- * Single-variant product (no meaningful options).
58
- */
59
- const simpleProduct = {
60
- id: 7429873610824,
61
- title: 'Coffee Mug',
62
- body_html: '<p>A simple ceramic mug.</p>',
63
- product_type: '',
64
- status: 'active',
65
- tags: '',
66
- variants: [
67
- {
68
- id: 42304918372617,
69
- title: 'Default Title',
70
- price: '14.99',
71
- compare_at_price: null,
72
- sku: 'MUG-001',
73
- barcode: null,
74
- inventory_policy: 'deny',
75
- inventory_management: null, // not tracking inventory
76
- inventory_quantity: 0,
77
- },
78
- ],
79
- options: [
80
- { id: 1, name: 'Title', position: 1, values: ['Default Title'] },
81
- ],
82
- images: [],
83
- image: null,
84
- };
85
-
86
- /**
87
- * Product with an active sale (compare_at_price > price).
88
- */
89
- const saleProduct = {
90
- ...fullProduct,
91
- id: 7429873610825,
92
- variants: [
93
- {
94
- ...fullProduct.variants[0],
95
- price: '499.99',
96
- compare_at_price: '599.99',
97
- },
98
- ],
99
- };
100
-
101
- const minimalProduct = {
102
- id: 9999,
103
- };
104
-
105
- describe('Shopify product traits', () => {
106
- describe('getId', () => {
107
- it('returns the product id as a string', () => {
108
- expect(shopifyProductTraits.getId(fullProduct)).toBe('7429873610823');
109
- });
110
- });
111
-
112
- describe('getName', () => {
113
- it('returns the title', () => {
114
- expect(shopifyProductTraits.getName(fullProduct)).toBe('Espresso Machine Pro');
115
- });
116
-
117
- it('returns empty string for missing title', () => {
118
- expect(shopifyProductTraits.getName(minimalProduct)).toBe('');
119
- });
120
- });
121
-
122
- describe('getSku', () => {
123
- it('returns SKU from first variant', () => {
124
- expect(shopifyProductTraits.getSku(fullProduct)).toBe('ESP-PRO-SLV');
125
- });
126
-
127
- it('returns undefined when no variants', () => {
128
- expect(shopifyProductTraits.getSku(minimalProduct)).toBeUndefined();
129
- });
130
- });
131
-
132
- describe('getPrice', () => {
133
- it('returns price string from first variant', () => {
134
- expect(shopifyProductTraits.getPrice(fullProduct)).toBe('599.99');
135
- });
136
-
137
- it('returns undefined when no variants', () => {
138
- expect(shopifyProductTraits.getPrice(minimalProduct)).toBeUndefined();
139
- });
140
- });
141
-
142
- describe('getRegularPrice / getSalePrice / isOnSale', () => {
143
- it('regular price falls back to current price when no compare_at', () => {
144
- expect(shopifyProductTraits.getRegularPrice(fullProduct)).toBe('599.99');
145
- });
146
-
147
- it('not on sale when compare_at_price is null', () => {
148
- expect(shopifyProductTraits.isOnSale(fullProduct)).toBe(false);
149
- expect(shopifyProductTraits.getSalePrice(fullProduct)).toBeUndefined();
150
- });
151
-
152
- it('detects sale when compare_at_price > price', () => {
153
- expect(shopifyProductTraits.isOnSale(saleProduct)).toBe(true);
154
- expect(shopifyProductTraits.getSalePrice(saleProduct)).toBe('499.99');
155
- expect(shopifyProductTraits.getRegularPrice(saleProduct)).toBe('599.99');
156
- });
157
- });
158
-
159
- describe('getImageUrl / getImageUrls', () => {
160
- it('returns the primary image src via image shortcut', () => {
161
- expect(shopifyProductTraits.getImageUrl(fullProduct)).toBe(
162
- 'https://cdn.shopify.com/espresso-front.jpg'
163
- );
164
- });
165
-
166
- it('returns all image URLs', () => {
167
- expect(shopifyProductTraits.getImageUrls(fullProduct)).toEqual([
168
- 'https://cdn.shopify.com/espresso-front.jpg',
169
- 'https://cdn.shopify.com/espresso-black.jpg',
170
- ]);
171
- });
172
-
173
- it('returns undefined / empty for product with no images', () => {
174
- expect(shopifyProductTraits.getImageUrl(simpleProduct)).toBeUndefined();
175
- expect(shopifyProductTraits.getImageUrls(simpleProduct)).toEqual([]);
176
- });
177
- });
178
-
179
- describe('getDescription', () => {
180
- it('returns body_html', () => {
181
- expect(shopifyProductTraits.getDescription(fullProduct)).toBe(
182
- '<p>High-end espresso machine with dual boilers.</p>'
183
- );
184
- });
185
-
186
- it('returns undefined when missing', () => {
187
- expect(shopifyProductTraits.getDescription(minimalProduct)).toBeUndefined();
188
- });
189
- });
190
-
191
- describe('getStockStatus', () => {
192
- it('returns instock for product with quantity', () => {
193
- expect(shopifyProductTraits.getStockStatus(fullProduct)).toBe('instock');
194
- });
195
-
196
- it('returns instock when inventory_management is null (not tracked)', () => {
197
- expect(shopifyProductTraits.getStockStatus(simpleProduct)).toBe('instock');
198
- });
199
-
200
- it('returns outofstock when tracked and quantity is 0', () => {
201
- const outOfStock = {
202
- ...fullProduct,
203
- variants: [{
204
- ...fullProduct.variants[0],
205
- inventory_quantity: 0,
206
- }],
207
- };
208
- expect(shopifyProductTraits.getStockStatus(outOfStock)).toBe('outofstock');
209
- });
210
-
211
- it('returns onbackorder when inventory_policy is continue', () => {
212
- const backorder = {
213
- ...fullProduct,
214
- variants: [{
215
- ...fullProduct.variants[0],
216
- inventory_policy: 'continue',
217
- inventory_quantity: 0,
218
- }],
219
- };
220
- expect(shopifyProductTraits.getStockStatus(backorder)).toBe('onbackorder');
221
- });
222
-
223
- it('returns unknown when no variants', () => {
224
- expect(shopifyProductTraits.getStockStatus(minimalProduct)).toBe('unknown');
225
- });
226
- });
227
-
228
- describe('getStockQuantity', () => {
229
- it('returns quantity from first variant', () => {
230
- expect(shopifyProductTraits.getStockQuantity(fullProduct)).toBe(15);
231
- });
232
-
233
- it('returns null when no variants', () => {
234
- expect(shopifyProductTraits.getStockQuantity(minimalProduct)).toBeNull();
235
- });
236
- });
237
-
238
- describe('hasVariants / getType', () => {
239
- it('multi-variant product has variants', () => {
240
- expect(shopifyProductTraits.hasVariants(fullProduct)).toBe(true);
241
- });
242
-
243
- it('single-variant product has no variants', () => {
244
- expect(shopifyProductTraits.hasVariants(simpleProduct)).toBe(false);
245
- });
246
-
247
- it('returns product_type', () => {
248
- expect(shopifyProductTraits.getType(fullProduct)).toBe('Equipment');
249
- });
250
-
251
- it('defaults to simple when product_type is empty', () => {
252
- expect(shopifyProductTraits.getType(simpleProduct)).toBe('simple');
253
- });
254
- });
255
-
256
- describe('getBarcode', () => {
257
- it('returns barcode from first variant', () => {
258
- expect(shopifyProductTraits.getBarcode(fullProduct)).toBe('1234567890123');
259
- });
260
-
261
- it('returns undefined when barcode is null', () => {
262
- expect(shopifyProductTraits.getBarcode(simpleProduct)).toBeUndefined();
263
- });
264
- });
265
-
266
- describe('getCategoryNames', () => {
267
- it('returns product_type as category', () => {
268
- expect(shopifyProductTraits.getCategoryNames(fullProduct)).toEqual(['Equipment']);
269
- });
270
-
271
- it('returns empty array when product_type is empty', () => {
272
- expect(shopifyProductTraits.getCategoryNames(simpleProduct)).toEqual([]);
273
- });
274
- });
275
- });
@@ -1,206 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import type { SyncContext } from '@tallyui/core';
3
-
4
- import { shopifyProductReplication } from './products';
5
-
6
- const context: SyncContext = {
7
- connectorId: 'shopify',
8
- baseUrl: 'https://my-store.myshopify.com',
9
- headers: { 'X-Shopify-Access-Token': 'shpat_test_token' },
10
- };
11
-
12
- describe('shopifyProductReplication.pull.handler', () => {
13
- beforeEach(() => {
14
- vi.restoreAllMocks();
15
- });
16
-
17
- it('fetches products from initial checkpoint (undefined)', async () => {
18
- const mockProducts = [
19
- { id: 1001, title: 'Widget', updated_at: '2026-01-01T00:00:00Z' },
20
- { id: 1002, title: 'Gadget', updated_at: '2026-01-02T00:00:00Z' },
21
- ];
22
-
23
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
24
- new Response(JSON.stringify({ products: mockProducts }), {
25
- status: 200,
26
- headers: { 'Content-Type': 'application/json' },
27
- }),
28
- );
29
-
30
- const result = await shopifyProductReplication.pull.handler(undefined, 100, context);
31
-
32
- expect(result.documents).toHaveLength(2);
33
- expect(result.documents[0]._deleted).toBe(false);
34
- expect(result.documents[0].id).toBe('1001');
35
- expect(result.documents[1].id).toBe('1002');
36
- expect(result.checkpoint).toEqual({
37
- updated_at: '2026-01-02T00:00:00Z',
38
- });
39
- });
40
-
41
- it('passes updated_at_min when checkpoint is provided', async () => {
42
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
43
- new Response(JSON.stringify({ products: [] }), {
44
- status: 200,
45
- headers: { 'Content-Type': 'application/json' },
46
- }),
47
- );
48
-
49
- const checkpoint = { updated_at: '2026-01-01T00:00:00Z' };
50
- const result = await shopifyProductReplication.pull.handler(checkpoint, 100, context);
51
-
52
- expect(result.documents).toHaveLength(0);
53
-
54
- const calledUrl = (globalThis.fetch as any).mock.calls[0][0];
55
- expect(calledUrl).toContain('updated_at_min=2026-01-01T00%3A00%3A00Z');
56
- });
57
-
58
- it('follows cursor-based pagination via Link header', async () => {
59
- const page1 = [
60
- { id: 1001, title: 'Widget', updated_at: '2026-01-01T00:00:00Z' },
61
- ];
62
- const page2 = [
63
- { id: 1002, title: 'Gadget', updated_at: '2026-01-02T00:00:00Z' },
64
- ];
65
-
66
- vi.spyOn(globalThis, 'fetch')
67
- .mockResolvedValueOnce(
68
- new Response(JSON.stringify({ products: page1 }), {
69
- status: 200,
70
- headers: {
71
- 'Content-Type': 'application/json',
72
- Link: '<https://my-store.myshopify.com/admin/api/2024-01/products.json?page_info=abc123&limit=1>; rel="next"',
73
- },
74
- }),
75
- )
76
- .mockResolvedValueOnce(
77
- new Response(JSON.stringify({ products: page2 }), {
78
- status: 200,
79
- headers: { 'Content-Type': 'application/json' },
80
- }),
81
- );
82
-
83
- const result = await shopifyProductReplication.pull.handler(undefined, 1, context);
84
-
85
- expect(result.documents).toHaveLength(2);
86
- expect(result.checkpoint).toEqual({
87
- updated_at: '2026-01-02T00:00:00Z',
88
- });
89
- expect(globalThis.fetch).toHaveBeenCalledTimes(2);
90
- });
91
-
92
- it('throws on non-OK response', async () => {
93
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
94
- new Response('Internal Server Error', { status: 500 }),
95
- );
96
-
97
- await expect(
98
- shopifyProductReplication.pull.handler(undefined, 100, context),
99
- ).rejects.toThrow('Shopify API error: 500');
100
- });
101
-
102
- it('returns lastCheckpoint when no products are returned', async () => {
103
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
104
- new Response(JSON.stringify({ products: [] }), {
105
- status: 200,
106
- headers: { 'Content-Type': 'application/json' },
107
- }),
108
- );
109
-
110
- const checkpoint = { updated_at: '2026-01-01T00:00:00Z' };
111
- const result = await shopifyProductReplication.pull.handler(checkpoint, 100, context);
112
-
113
- expect(result.checkpoint).toEqual(checkpoint);
114
- });
115
-
116
- it('normalizes numeric IDs to strings', async () => {
117
- const mockProducts = [
118
- { id: 9999, title: 'Numeric ID', updated_at: '2026-03-01T00:00:00Z' },
119
- ];
120
-
121
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
122
- new Response(JSON.stringify({ products: mockProducts }), {
123
- status: 200,
124
- headers: { 'Content-Type': 'application/json' },
125
- }),
126
- );
127
-
128
- const result = await shopifyProductReplication.pull.handler(undefined, 100, context);
129
-
130
- expect(result.documents[0].id).toBe('9999');
131
- });
132
- });
133
-
134
- describe('shopifyProductReplication.push.handler', () => {
135
- beforeEach(() => {
136
- vi.restoreAllMocks();
137
- });
138
-
139
- it('sends PUT for updates with product wrapper', async () => {
140
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
141
- new Response(JSON.stringify({}), { status: 200 }),
142
- );
143
-
144
- const conflicts = await shopifyProductReplication.push!.handler(
145
- [{
146
- newDocumentState: { id: '1001', title: 'Updated', _deleted: false } as any,
147
- assumedMasterState: { id: '1001', title: 'Old', _deleted: false } as any,
148
- }],
149
- context,
150
- );
151
-
152
- expect(conflicts).toHaveLength(0);
153
- const [url, opts] = (globalThis.fetch as any).mock.calls[0];
154
- expect(url).toContain('/admin/api/2024-01/products/1001.json');
155
- expect(opts.method).toBe('PUT');
156
- const body = JSON.parse(opts.body);
157
- expect(body.product).toBeDefined();
158
- expect(body.product.title).toBe('Updated');
159
- });
160
-
161
- it('returns conflicts on server error', async () => {
162
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
163
- new Response('conflict', { status: 409 }),
164
- );
165
-
166
- const conflicts = await shopifyProductReplication.push!.handler(
167
- [{
168
- newDocumentState: { id: '1001', title: 'Updated', _deleted: false } as any,
169
- assumedMasterState: { id: '1001', title: 'Server Version', _deleted: false } as any,
170
- }],
171
- context,
172
- );
173
-
174
- expect(conflicts).toHaveLength(1);
175
- expect(conflicts[0].title).toBe('Server Version');
176
- });
177
-
178
- it('returns conflicts on network failure', async () => {
179
- vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new Error('Network error'));
180
-
181
- const conflicts = await shopifyProductReplication.push!.handler(
182
- [{
183
- newDocumentState: { id: '1001', title: 'Updated', _deleted: false } as any,
184
- assumedMasterState: { id: '1001', title: 'Server Version', _deleted: false } as any,
185
- }],
186
- context,
187
- );
188
-
189
- expect(conflicts).toHaveLength(1);
190
- });
191
-
192
- it('does not return conflict when assumedMasterState is absent', async () => {
193
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
194
- new Response('error', { status: 500 }),
195
- );
196
-
197
- const conflicts = await shopifyProductReplication.push!.handler(
198
- [{
199
- newDocumentState: { id: '1001', title: 'New Product', _deleted: false } as any,
200
- }],
201
- context,
202
- );
203
-
204
- expect(conflicts).toHaveLength(0);
205
- });
206
- });