@tapcart/mobile-components 0.16.0 → 0.16.2

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.
Files changed (25) hide show
  1. package/dist/components/hooks/use-nosto-recommendation.d.ts +4 -0
  2. package/dist/components/hooks/use-nosto-recommendation.d.ts.map +1 -1
  3. package/dist/components/hooks/use-nosto-recommendation.js +116 -23
  4. package/dist/components/hooks/use-nosto-recommendation.queries.d.ts +0 -1
  5. package/dist/components/hooks/use-nosto-recommendation.queries.d.ts.map +1 -1
  6. package/dist/components/hooks/use-nosto-recommendation.queries.js +0 -3
  7. package/dist/components/hooks/use-nosto-recommendation.test.js +168 -171
  8. package/dist/components/hooks/use-order-details.d.ts +23 -0
  9. package/dist/components/hooks/use-order-details.d.ts.map +1 -1
  10. package/dist/components/hooks/use-order-details.js +59 -11
  11. package/dist/components/hooks/use-products.d.ts.map +1 -1
  12. package/dist/components/hooks/use-products.js +24 -4
  13. package/dist/components/hooks/use-products.test.d.ts +2 -0
  14. package/dist/components/hooks/use-products.test.d.ts.map +1 -0
  15. package/dist/components/hooks/use-products.test.js +129 -0
  16. package/dist/components/libs/cache/ProductsLocalStorage.d.ts.map +1 -1
  17. package/dist/components/libs/cache/ProductsLocalStorage.js +32 -0
  18. package/dist/components/libs/cache/ProductsLocalStorage.test.d.ts +2 -0
  19. package/dist/components/libs/cache/ProductsLocalStorage.test.d.ts.map +1 -0
  20. package/dist/components/libs/cache/ProductsLocalStorage.test.js +110 -0
  21. package/dist/components/ui/drawer.d.ts +3 -2
  22. package/dist/components/ui/drawer.d.ts.map +1 -1
  23. package/dist/components/ui/drawer.js +3 -3
  24. package/dist/tests/use-order-details.test.js +84 -1
  25. package/package.json +1 -1
@@ -14,13 +14,13 @@ import { useProducts } from "./use-products";
14
14
  jest.mock("./use-products", () => ({
15
15
  useProducts: jest.fn(),
16
16
  }));
17
- // Mock fetch for GraphQL queries
17
+ // Mock fetch for GraphQL queries. `newSession` is intentionally NOT handled:
18
+ // after TICKET-5763 nothing may ever mint a session, so a newSession request
19
+ // would be a bug — fail loudly if one is ever issued.
18
20
  global.fetch = jest.fn((url, options) => {
19
21
  const body = JSON.parse(options === null || options === void 0 ? void 0 : options.body);
20
22
  if (body.query.includes("newSession")) {
21
- return Promise.resolve({
22
- json: () => Promise.resolve({ data: { newSession: "mockSessionId" } }),
23
- });
23
+ return Promise.reject(new Error("newSession must never be called (TICKET-5763)"));
24
24
  }
25
25
  if (body.query.includes("GetFrontPageRecommendations")) {
26
26
  return Promise.resolve({
@@ -93,6 +93,31 @@ global.fetch = jest.fn((url, options) => {
93
93
  }
94
94
  return Promise.reject(new Error("Unknown query"));
95
95
  });
96
+ // Asserts the invariant that must hold for EVERY test: no request ever asks
97
+ // Nosto to mint a new session.
98
+ const expectNoNewSessionCall = () => {
99
+ const calls = global.fetch.mock.calls;
100
+ const mintedSession = calls.some(([, options]) => {
101
+ const raw = options === null || options === void 0 ? void 0 : options.body;
102
+ return typeof raw === "string" && raw.includes("newSession");
103
+ });
104
+ expect(mintedSession).toBe(false);
105
+ };
106
+ const setCidCookie = (value) => {
107
+ document.cookie = `2c.cId=${value}`;
108
+ };
109
+ const clearCookies = () => {
110
+ document.cookie = "2c.cId=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
111
+ };
112
+ const recentSession = (sessionId) => ({
113
+ sessionId,
114
+ lastSessionEventTimestamp: Date.now(),
115
+ });
116
+ const flush = () => __awaiter(void 0, void 0, void 0, function* () {
117
+ yield act(() => __awaiter(void 0, void 0, void 0, function* () {
118
+ yield new Promise((resolve) => setTimeout(resolve, 0));
119
+ }));
120
+ });
96
121
  describe("useNostoRecommendations", () => {
97
122
  const mockIntegrations = [
98
123
  {
@@ -104,233 +129,218 @@ describe("useNostoRecommendations", () => {
104
129
  const mockBaseURL = "http://mockbaseurl.com";
105
130
  beforeEach(() => {
106
131
  jest.clearAllMocks();
132
+ clearCookies();
107
133
  useProducts.mockReturnValue({
108
134
  products: [{ id: "1", name: "Product 1" }],
109
135
  isLoading: false,
110
136
  error: null,
111
137
  });
112
138
  });
113
- it("should return front page recommendations if productIds is empty and slotId is provided", () => __awaiter(void 0, void 0, void 0, function* () {
114
- const slotId = "mockSlotId";
115
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, slotId, "US", undefined, undefined, undefined));
116
- // Initial state check
139
+ afterEach(() => {
140
+ // Invariant across every path: never mint a Nosto session.
141
+ expectNoNewSessionCall();
142
+ clearCookies();
143
+ });
144
+ it("uses the passed-in session for front page recommendations", () => __awaiter(void 0, void 0, void 0, function* () {
145
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "mockSlotId", "US", undefined, undefined, undefined, undefined, undefined, recentSession("passed-session")));
117
146
  expect(result.current.isLoading).toBe(true);
118
- // Wait for all promises with act
119
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
120
- yield new Promise((resolve) => setTimeout(resolve, 0));
121
- }));
122
- // Check final state
147
+ yield flush();
123
148
  expect(result.current.isLoading).toBe(false);
124
149
  expect(result.current.error).toBe(null);
150
+ // Native session was used -> personalization surfaced as "session".
151
+ expect(result.current.personalization).toBe("session");
125
152
  expect(useProducts).toHaveBeenCalledWith({
126
153
  productIds: ["front-page-id-1"],
127
154
  baseURL: mockBaseURL,
128
155
  productHandles: [],
129
- queryVariables: {
130
- appId: undefined,
131
- country: "US",
132
- },
156
+ queryVariables: { appId: undefined, country: "US" },
133
157
  mock: false,
134
158
  });
135
159
  }));
136
- it("should return best sellers recommendations if productIds is empty and slotId is not provided", () => __awaiter(void 0, void 0, void 0, function* () {
137
- const slotId = "";
138
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, slotId, "US", undefined, undefined));
139
- // Initial state check
160
+ it("falls back to the 2c.cId cookie when no session is passed (front page)", () => __awaiter(void 0, void 0, void 0, function* () {
161
+ setCidCookie("cookie-cid");
162
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "mockSlotId", "US"));
140
163
  expect(result.current.isLoading).toBe(true);
141
- // Wait for all promises with act
142
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
143
- yield new Promise((resolve) => setTimeout(resolve, 0));
144
- }));
145
- // Check final state
164
+ yield flush();
146
165
  expect(result.current.isLoading).toBe(false);
147
- expect(result.current.error).toBe(null);
166
+ // Cookie-derived session resolves, so the personalized front page query runs.
167
+ expect(result.current.personalization).toBe("cookie");
148
168
  expect(useProducts).toHaveBeenCalledWith({
149
- productIds: ["best-seller-1"],
169
+ productIds: ["front-page-id-1"],
150
170
  baseURL: mockBaseURL,
151
171
  productHandles: [],
152
- queryVariables: {
153
- appId: undefined,
154
- country: "US",
155
- },
172
+ queryVariables: { appId: undefined, country: "US" },
156
173
  mock: false,
157
174
  });
158
175
  }));
159
- it("should return best sellers recommendations if productIds is not empty, Best Sellers is the recommendation type and slotId is not provided", () => __awaiter(void 0, void 0, void 0, function* () {
160
- const slotId = "";
161
- const productIds = ["mockProductId"];
162
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, slotId, "US", NostoRecommendationsType.BEST_SELLERS, productIds));
163
- // Initial state check
176
+ it("falls back to bestSellers on the front page when there is no session and no cookie", () => __awaiter(void 0, void 0, void 0, function* () {
177
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "mockSlotId", "US"));
164
178
  expect(result.current.isLoading).toBe(true);
165
- // Wait for all promises with act
166
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
167
- yield new Promise((resolve) => setTimeout(resolve, 0));
168
- }));
169
- // Check final state
179
+ yield flush();
170
180
  expect(result.current.isLoading).toBe(false);
171
- expect(result.current.error).toBe(null);
181
+ // No identity available -> personalization "none".
182
+ expect(result.current.personalization).toBe("none");
183
+ // No session-based query fired; bestSellers fallback engaged.
172
184
  expect(useProducts).toHaveBeenCalledWith({
173
185
  productIds: ["best-seller-1"],
174
186
  baseURL: mockBaseURL,
175
187
  productHandles: [],
176
- queryVariables: {
177
- appId: undefined,
178
- country: "US",
179
- },
188
+ queryVariables: { appId: undefined, country: "US" },
180
189
  mock: false,
181
190
  });
182
191
  }));
183
- it("should return default front page recommendations if slotId is provided but layoutType is not", () => __awaiter(void 0, void 0, void 0, function* () {
184
- const slotId = "mockSlotId";
185
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, slotId, "US"));
186
- // Initial state check
192
+ it("upgrades from bestSellers to personalized once a late 2c.cId cookie appears", () => __awaiter(void 0, void 0, void 0, function* () {
193
+ // The WebView Nosto SDK mints the cookie asynchronously, so a carousel can
194
+ // mount before it exists. The bounded poll must pick up the late cookie and
195
+ // re-resolve from the bestSellers fallback to the personalized front page.
196
+ jest.useFakeTimers();
197
+ try {
198
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "mockSlotId", "US"));
199
+ // No cookie at mount -> "none" + bestSellers fallback.
200
+ yield act(() => __awaiter(void 0, void 0, void 0, function* () {
201
+ yield jest.advanceTimersByTimeAsync(0);
202
+ }));
203
+ expect(result.current.personalization).toBe("none");
204
+ expect(useProducts).toHaveBeenLastCalledWith(expect.objectContaining({ productIds: ["best-seller-1"] }));
205
+ // Cookie minted after mount; the 250ms poll picks it up and refetches.
206
+ setCidCookie("late-cookie-cid");
207
+ yield act(() => __awaiter(void 0, void 0, void 0, function* () {
208
+ yield jest.advanceTimersByTimeAsync(250);
209
+ }));
210
+ expect(result.current.personalization).toBe("cookie");
211
+ expect(useProducts).toHaveBeenLastCalledWith(expect.objectContaining({ productIds: ["front-page-id-1"] }));
212
+ }
213
+ finally {
214
+ jest.useRealTimers();
215
+ }
216
+ }));
217
+ it("returns best sellers when productIds is empty and slotId is not provided", () => __awaiter(void 0, void 0, void 0, function* () {
218
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US"));
187
219
  expect(result.current.isLoading).toBe(true);
188
- // Wait for all promises with act
189
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
190
- yield new Promise((resolve) => setTimeout(resolve, 0));
191
- }));
192
- // Check final state
220
+ yield flush();
193
221
  expect(result.current.isLoading).toBe(false);
194
222
  expect(result.current.error).toBe(null);
195
223
  expect(useProducts).toHaveBeenCalledWith({
196
- productIds: ["front-page-id-1"],
224
+ productIds: ["best-seller-1"],
197
225
  baseURL: mockBaseURL,
198
226
  productHandles: [],
199
- queryVariables: {
200
- appId: undefined,
201
- country: "US",
202
- },
227
+ queryVariables: { appId: undefined, country: "US" },
203
228
  mock: false,
204
229
  });
205
230
  }));
206
- it("should return the correct recommendations for best sellers", () => __awaiter(void 0, void 0, void 0, function* () {
207
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.BEST_SELLERS, undefined, undefined));
208
- // Initial state check
231
+ it("returns best sellers when BEST_SELLERS type and productIds are provided but no slotId", () => __awaiter(void 0, void 0, void 0, function* () {
232
+ // Stable reference so the hook's effect deps don't change across renders.
233
+ const productIds = ["mockProductId"];
234
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.BEST_SELLERS, productIds));
209
235
  expect(result.current.isLoading).toBe(true);
210
- // Wait for all promises with act
211
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
212
- yield new Promise((resolve) => setTimeout(resolve, 0));
213
- }));
214
- // Check final state
236
+ yield flush();
215
237
  expect(result.current.isLoading).toBe(false);
216
- expect(result.current.error).toBe(null);
217
238
  expect(useProducts).toHaveBeenCalledWith({
218
239
  productIds: ["best-seller-1"],
219
240
  baseURL: mockBaseURL,
220
241
  productHandles: [],
221
- queryVariables: {
222
- appId: undefined,
223
- country: "US",
224
- },
242
+ queryVariables: { appId: undefined, country: "US" },
225
243
  mock: false,
226
244
  });
227
245
  }));
228
- it("should return the related recommendations when only productIds and a recommendation type are provided on a non-home layout", () => __awaiter(void 0, void 0, void 0, function* () {
246
+ it("returns product page recommendations when a session, productIds and slotId are provided", () => __awaiter(void 0, void 0, void 0, function* () {
229
247
  const productIds = ["mockProductId"];
230
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_TOGETHER, productIds, undefined));
231
- // Initial state check
248
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "mockSlotId", "US", NostoRecommendationsType.VIEWED_TOGETHER, productIds, undefined, undefined, undefined, recentSession("passed-session")));
232
249
  expect(result.current.isLoading).toBe(true);
233
- // Wait for all promises with act
234
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
235
- yield new Promise((resolve) => setTimeout(resolve, 0));
236
- }));
237
- // Check final state
250
+ yield flush();
251
+ expect(result.current.isLoading).toBe(false);
252
+ expect(useProducts).toHaveBeenCalledWith({
253
+ productIds: ["product-page-id-1"],
254
+ baseURL: mockBaseURL,
255
+ productHandles: [],
256
+ queryVariables: { appId: undefined, country: "US" },
257
+ mock: false,
258
+ });
259
+ }));
260
+ it("returns the related products PDP fallback (no slotId, non-category type)", () => __awaiter(void 0, void 0, void 0, function* () {
261
+ const productIds = ["mockProductId"];
262
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_TOGETHER, productIds));
263
+ expect(result.current.isLoading).toBe(true);
264
+ yield flush();
238
265
  expect(result.current.isLoading).toBe(false);
239
- expect(result.current.error).toBe(null);
240
266
  expect(useProducts).toHaveBeenCalledWith({
241
267
  productIds: ["related-1"],
242
268
  baseURL: mockBaseURL,
243
269
  productHandles: [],
244
- queryVariables: {
245
- appId: undefined,
246
- country: "US",
247
- },
270
+ queryVariables: { appId: undefined, country: "US" },
248
271
  mock: false,
249
272
  });
250
273
  }));
251
- it("should return the correct recommendations when productIds and slotIds are provided", () => __awaiter(void 0, void 0, void 0, function* () {
252
- const slotId = "mockSlotId";
274
+ it("returns the category PDP fallback when a session is available and type is VIEWED_CATEGORY", () => __awaiter(void 0, void 0, void 0, function* () {
253
275
  const productIds = ["mockProductId"];
254
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, slotId, "US", NostoRecommendationsType.VIEWED_TOGETHER, productIds, undefined));
255
- // Initial state check
276
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_CATEGORY, productIds, undefined, undefined, undefined, recentSession("passed-session")));
256
277
  expect(result.current.isLoading).toBe(true);
257
- // Wait for all promises with act
258
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
259
- yield new Promise((resolve) => setTimeout(resolve, 0));
260
- }));
261
- // Check final state
278
+ yield flush();
262
279
  expect(result.current.isLoading).toBe(false);
263
- expect(result.current.error).toBe(null);
264
280
  expect(useProducts).toHaveBeenCalledWith({
265
- productIds: ["product-page-id-1"],
281
+ productIds: ["category-page-id-1"],
266
282
  baseURL: mockBaseURL,
267
283
  productHandles: [],
268
- queryVariables: {
269
- appId: undefined,
270
- country: "US",
271
- },
284
+ queryVariables: { appId: undefined, country: "US" },
272
285
  mock: false,
273
286
  });
274
287
  }));
275
- it("should return the related products fallback recommendations when productIds are provided and no slotId and a type other than viewed_category and best_sellers is provided", () => __awaiter(void 0, void 0, void 0, function* () {
288
+ it("falls back to bestSellers for a VIEWED_CATEGORY PDP when there is no session", () => __awaiter(void 0, void 0, void 0, function* () {
276
289
  const productIds = ["mockProductId"];
277
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_TOGETHER, productIds, undefined));
278
- // Initial state check
290
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_CATEGORY, productIds));
279
291
  expect(result.current.isLoading).toBe(true);
280
- // Wait for all promises with act
281
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
282
- yield new Promise((resolve) => setTimeout(resolve, 0));
283
- }));
284
- // Check final state
292
+ yield flush();
285
293
  expect(result.current.isLoading).toBe(false);
286
- expect(result.current.error).toBe(null);
287
294
  expect(useProducts).toHaveBeenCalledWith({
288
- productIds: ["related-1"],
295
+ productIds: ["best-seller-1"],
289
296
  baseURL: mockBaseURL,
290
297
  productHandles: [],
291
- queryVariables: {
292
- appId: undefined,
293
- country: "US",
294
- },
298
+ queryVariables: { appId: undefined, country: "US" },
295
299
  mock: false,
296
300
  });
297
301
  }));
298
- it("should return the category fallback recommendations when no slotId, productIds are provided and a recommendation type of viewed_category is provided", () => __awaiter(void 0, void 0, void 0, function* () {
302
+ it("serves bestSellers (not an error) for a VIEWED_CATEGORY PDP when the cId cookie is malformed", () => __awaiter(void 0, void 0, void 0, function* () {
303
+ // A bad percent-encoding makes decodeURIComponent throw; the shared reader
304
+ // must return null (never the raw value) so this routes into the designed
305
+ // bestSellers fallback instead of escaping into the hook's error state.
306
+ document.cookie = "2c.cId=%";
299
307
  const productIds = ["mockProductId"];
300
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_CATEGORY, productIds, undefined));
301
- // Initial state check
308
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_CATEGORY, productIds));
302
309
  expect(result.current.isLoading).toBe(true);
303
- // Wait for all promises with act
304
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
305
- yield new Promise((resolve) => setTimeout(resolve, 0));
306
- }));
307
- // Check final state
310
+ yield flush();
308
311
  expect(result.current.isLoading).toBe(false);
309
312
  expect(result.current.error).toBe(null);
313
+ expect(result.current.personalization).toBe("none");
310
314
  expect(useProducts).toHaveBeenCalledWith({
311
- productIds: ["category-page-id-1"],
315
+ productIds: ["best-seller-1"],
312
316
  baseURL: mockBaseURL,
313
317
  productHandles: [],
314
- queryVariables: {
315
- appId: undefined,
316
- country: "US",
317
- },
318
+ queryVariables: { appId: undefined, country: "US" },
318
319
  mock: false,
319
320
  });
320
321
  }));
321
- it("should handle loading state", () => __awaiter(void 0, void 0, void 0, function* () {
322
+ it("defaults to best sellers if productIds are empty but a non-BestSellers type is used", () => __awaiter(void 0, void 0, void 0, function* () {
323
+ const productIds = [];
324
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_TOGETHER, productIds));
325
+ expect(result.current.isLoading).toBe(true);
326
+ yield flush();
327
+ expect(result.current.isLoading).toBe(false);
328
+ expect(useProducts).toHaveBeenCalledWith({
329
+ productIds: ["best-seller-1"],
330
+ baseURL: mockBaseURL,
331
+ productHandles: [],
332
+ queryVariables: { appId: undefined, country: "US" },
333
+ mock: false,
334
+ });
335
+ }));
336
+ it("handles loading state", () => __awaiter(void 0, void 0, void 0, function* () {
322
337
  const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US"));
323
- // Check initial loading state
324
338
  expect(result.current.isLoading).toBe(true);
325
- // Wait for all state updates to complete
326
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
327
- yield new Promise((resolve) => setTimeout(resolve, 0));
328
- }));
329
- // Verify loading has finished
339
+ yield flush();
330
340
  expect(result.current.isLoading).toBe(false);
331
341
  expect(result.current.error).toBe(null);
332
342
  }));
333
- it("should handle error state", () => __awaiter(void 0, void 0, void 0, function* () {
343
+ it("handles error state", () => __awaiter(void 0, void 0, void 0, function* () {
334
344
  const mockError = () => "Failed to fetch products";
335
345
  useProducts.mockReturnValue({
336
346
  products: [],
@@ -338,58 +348,45 @@ describe("useNostoRecommendations", () => {
338
348
  error: mockError,
339
349
  });
340
350
  const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL));
341
- // Initial state check
342
351
  expect(result.current.isLoading).toBe(true);
343
- // Wait for all promises and state updates to resolve
344
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
345
- yield new Promise((resolve) => setTimeout(resolve, 0));
346
- }));
347
- // Verify final error state
352
+ yield flush();
348
353
  expect(result.current.isLoading).toBe(false);
349
354
  expect(result.current.error).toBe(mockError);
350
355
  expect(result.current.recommendations).toEqual([]);
351
356
  }));
352
- it("should default to best sellers if productIds are empty but a recommendation type other than Best Sellers is used", () => __awaiter(void 0, void 0, void 0, function* () {
353
- const productIds = [];
354
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.VIEWED_TOGETHER, productIds, undefined));
355
- // Initial state check
357
+ it("returns an empty array if skip is true", () => __awaiter(void 0, void 0, void 0, function* () {
358
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.BEST_SELLERS, undefined, true));
356
359
  expect(result.current.isLoading).toBe(true);
357
- // Wait for all promises with act
358
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
359
- yield new Promise((resolve) => setTimeout(resolve, 0));
360
- }));
361
- // Check final state
360
+ yield flush();
362
361
  expect(result.current.isLoading).toBe(false);
363
- expect(result.current.error).toBe(null);
364
362
  expect(useProducts).toHaveBeenCalledWith({
365
- productIds: ["best-seller-1"],
363
+ productIds: [],
366
364
  baseURL: mockBaseURL,
367
365
  productHandles: [],
368
- queryVariables: {
369
- appId: undefined,
370
- country: "US",
371
- },
366
+ queryVariables: { appId: undefined, country: "US" },
372
367
  mock: false,
373
368
  });
369
+ // skip must short-circuit before any Nosto request and before any
370
+ // bestSellers fallback resolves — the empty-productIds call above always
371
+ // matches on first render, so these guard against a broken skip.
372
+ expect(global.fetch).not.toHaveBeenCalled();
373
+ expect(useProducts).not.toHaveBeenCalledWith(expect.objectContaining({ productIds: ["best-seller-1"] }));
374
374
  }));
375
- it("should return an empty array if skip is true", () => __awaiter(void 0, void 0, void 0, function* () {
376
- const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "", "US", NostoRecommendationsType.BEST_SELLERS, undefined, true));
377
- // Initial state check
375
+ it("ignores an expired session and falls back without minting a new one", () => __awaiter(void 0, void 0, void 0, function* () {
376
+ const staleSession = {
377
+ sessionId: "stale-session",
378
+ lastSessionEventTimestamp: Date.now() - 60 * 60 * 1000, // 1h ago
379
+ };
380
+ const { result } = renderHook(() => useNostoRecommendations(mockIntegrations, mockBaseURL, "mockSlotId", "US", undefined, undefined, undefined, undefined, undefined, staleSession));
378
381
  expect(result.current.isLoading).toBe(true);
379
- // Wait for all promises with act
380
- yield act(() => __awaiter(void 0, void 0, void 0, function* () {
381
- yield new Promise((resolve) => setTimeout(resolve, 0));
382
- }));
383
- // Check final state
382
+ yield flush();
384
383
  expect(result.current.isLoading).toBe(false);
384
+ // Expired session is dropped by the hook -> null sessionId -> bestSellers.
385
385
  expect(useProducts).toHaveBeenCalledWith({
386
- productIds: [],
386
+ productIds: ["best-seller-1"],
387
387
  baseURL: mockBaseURL,
388
388
  productHandles: [],
389
- queryVariables: {
390
- appId: undefined,
391
- country: "US",
392
- },
389
+ queryVariables: { appId: undefined, country: "US" },
393
390
  mock: false,
394
391
  });
395
392
  }));
@@ -9,6 +9,29 @@ type UseOrderDetailsProps = {
9
9
  type UseProductsReturn = {
10
10
  orderDetails: Record<string, any>;
11
11
  };
12
+ /**
13
+ * Effective (post-edit) quantity for an order line item, correct across BOTH
14
+ * Shopify order APIs the app consumes:
15
+ *
16
+ * - Storefront API exposes `currentQuantity` (ordered minus removed); it is 0
17
+ * for a line removed via Order Editing. Authoritative when present.
18
+ * - New Customer Account API has NO `currentQuantity`. There the only
19
+ * per-line signal is `refundableQuantity` (= quantity − refunded), which is
20
+ * also driven down to the post-edit count by an Order Editing removal
21
+ * (verified against real prod data: a removed line has refundableQuantity 0
22
+ * with no refund record). We trust it ONLY when the order was `edited` AND
23
+ * has no refund activity — because a refund/return ALSO lowers
24
+ * `refundableQuantity`, and `edited` is sticky, so on an edited-then-refunded
25
+ * order we cannot tell an edit-removal from a return. In that case we fall
26
+ * back to the ordered `quantity` (show the item) rather than risk hiding a
27
+ * line the customer actually bought / returned, or blanking a fully-refunded
28
+ * order. Trade-off: an item removed via an edit that DID issue a refund is
29
+ * not hidden (needs a per-line signal the API doesn't expose).
30
+ *
31
+ * Exported so blocks (PurchaseOverview, OrderHistory, OrderStatus) that build
32
+ * their own order objects from raw `customer.orders` share one implementation.
33
+ */
34
+ export declare const getEffectiveLineQuantity: (order: Record<string, any>, lineItem: Record<string, any>) => number;
12
35
  export declare const transformOrderDetails: (order: Record<string, any>) => {
13
36
  orderDetails: Record<string, any>;
14
37
  checkoutData: Record<string, any>;
@@ -1 +1 @@
1
- {"version":3,"file":"use-order-details.d.ts","sourceRoot":"","sources":["../../../components/hooks/use-order-details.ts"],"names":[],"mappings":"AAKA,KAAK,oBAAoB,GAAG;IAC1B,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC9B,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,OAAO,CAAA;CACf,CAAA;AAED,KAAK,iBAAiB,GAAG;IACvB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAClC,CAAA;AA0LD,eAAO,MAAM,qBAAqB,UACzB,OAAO,MAAM,EAAE,GAAG,CAAC;kBACT,OAAO,MAAM,EAAE,GAAG,CAAC;kBAAgB,OAAO,MAAM,EAAE,GAAG,CAAC;CAmOxE,CAAA;AAED,wBAAgB,eAAe,CAAC,EAC9B,SAAS,EACT,MAAM,EACN,KAAK,EACL,QAAQ,EACR,OAAO,EACP,IAAY,GACb,EAAE,oBAAoB,GAAG,iBAAiB,CAiE1C"}
1
+ {"version":3,"file":"use-order-details.d.ts","sourceRoot":"","sources":["../../../components/hooks/use-order-details.ts"],"names":[],"mappings":"AAKA,KAAK,oBAAoB,GAAG;IAC1B,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC9B,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,OAAO,CAAA;CACf,CAAA;AAED,KAAK,iBAAiB,GAAG;IACvB,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAClC,CAAA;AAwMD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,wBAAwB,UAC5B,OAAO,MAAM,EAAE,GAAG,CAAC,YAChB,OAAO,MAAM,EAAE,GAAG,CAAC,KAC5B,MAUF,CAAA;AAED,eAAO,MAAM,qBAAqB,UACzB,OAAO,MAAM,EAAE,GAAG,CAAC;kBACT,OAAO,MAAM,EAAE,GAAG,CAAC;kBAAgB,OAAO,MAAM,EAAE,GAAG,CAAC;CAoOxE,CAAA;AAED,wBAAgB,eAAe,CAAC,EAC9B,SAAS,EACT,MAAM,EACN,KAAK,EACL,QAAQ,EACR,OAAO,EACP,IAAY,GACb,EAAE,oBAAoB,GAAG,iBAAiB,CAiE1C"}
@@ -138,6 +138,54 @@ const updateLineDetails = (line, product) => {
138
138
  line.sellingPlan = (_k = (_j = product.sellingPlanAllocation) === null || _j === void 0 ? void 0 : _j.sellingPlan) === null || _k === void 0 ? void 0 : _k.name;
139
139
  line.variantName = (_l = product.variant) === null || _l === void 0 ? void 0 : _l.title;
140
140
  };
141
+ /**
142
+ * True when an order has any refund/return activity. Used to keep the
143
+ * Customer-Account-API `refundableQuantity` heuristic (below) away from orders
144
+ * whose `refundableQuantity` was lowered by a refund rather than an order edit.
145
+ */
146
+ const hasRefundActivity = (order) => {
147
+ var _a, _b, _c;
148
+ if (Array.isArray(order === null || order === void 0 ? void 0 : order.refunds) && order.refunds.length > 0)
149
+ return true;
150
+ const refunded = (_c = (_b = (_a = order === null || order === void 0 ? void 0 : order.totalRefunded) === null || _a === void 0 ? void 0 : _a.amount) !== null && _b !== void 0 ? _b : order === null || order === void 0 ? void 0 : order.totalRefunded) !== null && _c !== void 0 ? _c : order === null || order === void 0 ? void 0 : order.totalRefund;
151
+ if (refunded != null && parseFloat(String(refunded)) > 0)
152
+ return true;
153
+ const status = String((order === null || order === void 0 ? void 0 : order.financialStatus) || "").toUpperCase();
154
+ return status.includes("REFUND"); // REFUNDED / PARTIALLY_REFUNDED
155
+ };
156
+ /**
157
+ * Effective (post-edit) quantity for an order line item, correct across BOTH
158
+ * Shopify order APIs the app consumes:
159
+ *
160
+ * - Storefront API exposes `currentQuantity` (ordered minus removed); it is 0
161
+ * for a line removed via Order Editing. Authoritative when present.
162
+ * - New Customer Account API has NO `currentQuantity`. There the only
163
+ * per-line signal is `refundableQuantity` (= quantity − refunded), which is
164
+ * also driven down to the post-edit count by an Order Editing removal
165
+ * (verified against real prod data: a removed line has refundableQuantity 0
166
+ * with no refund record). We trust it ONLY when the order was `edited` AND
167
+ * has no refund activity — because a refund/return ALSO lowers
168
+ * `refundableQuantity`, and `edited` is sticky, so on an edited-then-refunded
169
+ * order we cannot tell an edit-removal from a return. In that case we fall
170
+ * back to the ordered `quantity` (show the item) rather than risk hiding a
171
+ * line the customer actually bought / returned, or blanking a fully-refunded
172
+ * order. Trade-off: an item removed via an edit that DID issue a refund is
173
+ * not hidden (needs a per-line signal the API doesn't expose).
174
+ *
175
+ * Exported so blocks (PurchaseOverview, OrderHistory, OrderStatus) that build
176
+ * their own order objects from raw `customer.orders` share one implementation.
177
+ */
178
+ export const getEffectiveLineQuantity = (order, lineItem) => {
179
+ var _a;
180
+ if (lineItem.currentQuantity != null)
181
+ return lineItem.currentQuantity;
182
+ if ((order === null || order === void 0 ? void 0 : order.edited) === true &&
183
+ lineItem.refundableQuantity != null &&
184
+ !hasRefundActivity(order)) {
185
+ return lineItem.refundableQuantity;
186
+ }
187
+ return (_a = lineItem.quantity) !== null && _a !== void 0 ? _a : 1;
188
+ };
141
189
  export const transformOrderDetails = (order) => {
142
190
  var _a;
143
191
  // Helper function to safely parse amounts
@@ -148,12 +196,12 @@ export const transformOrderDetails = (order) => {
148
196
  return parseFloat(amount) || 0;
149
197
  return 0;
150
198
  };
151
- // Shopify Order Editing sets currentQuantity to 0 for removed/refunded
152
- // line items those must not be shown to the customer
153
- const activeLineItems = (order.lineItems || []).filter((lineItem) => { var _a, _b; return ((_b = (_a = lineItem.currentQuantity) !== null && _a !== void 0 ? _a : lineItem.quantity) !== null && _b !== void 0 ? _b : 1) > 0; });
199
+ const effectiveQuantity = (lineItem) => getEffectiveLineQuantity(order, lineItem);
200
+ // Line items removed via Order Editing must not be shown to the customer
201
+ const activeLineItems = (order.lineItems || []).filter((lineItem) => effectiveQuantity(lineItem) > 0);
154
202
  // Transform line items to cart lines
155
203
  const cartLines = activeLineItems.map((lineItem) => {
156
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
204
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
157
205
  const variant = lineItem.variant || {};
158
206
  const product = variant.product || {};
159
207
  return {
@@ -188,13 +236,13 @@ export const transformOrderDetails = (order) => {
188
236
  productId: ((_k = variant.product) === null || _k === void 0 ? void 0 : _k.id) || lineItem.productId,
189
237
  merchandiseId: variant.id || lineItem.merchandiseId,
190
238
  title: lineItem.title || product.title || "Unknown Product",
191
- quantity: (_m = (_l = lineItem.currentQuantity) !== null && _l !== void 0 ? _l : lineItem.quantity) !== null && _m !== void 0 ? _m : 1,
239
+ quantity: effectiveQuantity(lineItem),
192
240
  uniqueId: crypto.randomUUID(),
193
241
  vendor: product.vendor || lineItem.vendor || "Unknown",
194
242
  compareAtPrice: {
195
- amount: parseAmount(((_o = lineItem.originalTotalPrice) === null || _o === void 0 ? void 0 : _o.amount) || ((_p = lineItem.compareAtPrice) === null || _p === void 0 ? void 0 : _p.amount)),
196
- currencyCode: ((_q = lineItem.originalTotalPrice) === null || _q === void 0 ? void 0 : _q.currencyCode) ||
197
- ((_r = lineItem.compareAtPrice) === null || _r === void 0 ? void 0 : _r.currencyCode) ||
243
+ amount: parseAmount(((_l = lineItem.originalTotalPrice) === null || _l === void 0 ? void 0 : _l.amount) || ((_m = lineItem.compareAtPrice) === null || _m === void 0 ? void 0 : _m.amount)),
244
+ currencyCode: ((_o = lineItem.originalTotalPrice) === null || _o === void 0 ? void 0 : _o.currencyCode) ||
245
+ ((_p = lineItem.compareAtPrice) === null || _p === void 0 ? void 0 : _p.currencyCode) ||
198
246
  order.currency ||
199
247
  "USD",
200
248
  },
@@ -265,7 +313,7 @@ export const transformOrderDetails = (order) => {
265
313
  })),
266
314
  subtotalPrice: wrapMoney(subtotal, currencyCode),
267
315
  lineItems: activeLineItems.map((lineItem) => {
268
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
316
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
269
317
  const variant = lineItem.variant || {};
270
318
  const product = variant.product || {};
271
319
  const currencyCode = ((_a = lineItem.discountedTotalPrice) === null || _a === void 0 ? void 0 : _a.currencyCode) ||
@@ -315,9 +363,9 @@ export const transformOrderDetails = (order) => {
315
363
  discountApplication: allocation.discountApplication || {},
316
364
  });
317
365
  }),
318
- quantity: (_t = (_s = lineItem.currentQuantity) !== null && _s !== void 0 ? _s : lineItem.quantity) !== null && _t !== void 0 ? _t : 1,
366
+ quantity: effectiveQuantity(lineItem),
319
367
  title: lineItem.title || product.title,
320
- id: ((_u = variant.id) === null || _u === void 0 ? void 0 : _u.split("/").pop()) || ((_v = lineItem.variantId) === null || _v === void 0 ? void 0 : _v.split("/").pop()),
368
+ id: ((_s = variant.id) === null || _s === void 0 ? void 0 : _s.split("/").pop()) || ((_t = lineItem.variantId) === null || _t === void 0 ? void 0 : _t.split("/").pop()),
321
369
  };
322
370
  }),
323
371
  totalPrice: wrapMoney(total, currencyCode),