@merchi/cart 1.4.85 → 1.4.86

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.
@@ -3,7 +3,8 @@ import { createRoot, Root } from 'react-dom/client';
3
3
  import { act } from 'react-dom/test-utils';
4
4
 
5
5
  import CartProvider, { useCartContext } from './CartProvider';
6
- import { getCartCookie, setCartCookie } from './utilities/cookie';
6
+ import { ActiveFormShipmentAddressAndNotes } from './forms/FormShipmentAddressAndNotes';
7
+ import { getCartCookie, getCartCookieToken, setCartCookie } from './utilities/cookie';
7
8
  import { cartNeedsSourceUpdate } from './utilities/job_source';
8
9
  import { reportCartFailure, CART_FAILURE_SOURCES } from './utilities/reportFailure';
9
10
  import { tabIdClearCart, tabIdItems } from './utilities/tabs';
@@ -11,18 +12,28 @@ import { tabIdClearCart, tabIdItems } from './utilities/tabs';
11
12
  const mockGet = jest.fn();
12
13
  const mockPost = jest.fn();
13
14
  const mockCreateItem = jest.fn();
15
+ const mockSaveCart = jest.fn();
16
+ const mockShipmentQuotes = jest.fn();
14
17
 
15
18
  jest.mock('@merchi/sdk', () => ({
16
- Merchi: jest.fn().mockImplementation(() => ({
17
- Cart: { get: (...args: unknown[]) => mockGet(...args) },
18
- authenticatedFetch: (...args: unknown[]) => mockPost(...args),
19
+ Merchi: jest.fn().mockImplementation((_session, _client, _invoice, cartToken) => ({
20
+ Cart: Object.assign(jest.fn(() => ({
21
+ fromJson: (cart: { id: number }) => ({
22
+ save: () => mockSaveCart(cart.id, cartToken),
23
+ }),
24
+ })), { get: (...args: unknown[]) => mockGet(...args) }),
25
+ authenticatedFetch: (...args: unknown[]) => cartToken
26
+ ? mockShipmentQuotes(cartToken, ...args)
27
+ : mockPost(...args),
19
28
  })),
20
29
  }));
30
+ jest.mock('./utilities/address', () => ({ makeAddress: jest.fn(), sanitizeAddressFields: jest.fn() }));
21
31
  jest.mock('./utilities/product', () => ({ makeProduct: jest.fn(json => json) }));
22
32
  jest.mock('./utilities/job', () => ({ makeJob: jest.fn(json => json) }));
23
33
  jest.mock('./utilities/cart', () => ({
24
- makeCart: (json: any) => ({
34
+ makeCart: (json: any, _makeDirty?: boolean, cartToken?: string) => ({
25
35
  ...json,
36
+ save: () => mockSaveCart(json.id, cartToken),
26
37
  toFormData: () => new FormData(),
27
38
  fromJson: jest.fn(),
28
39
  toJson: () => ({ id: 99, token: 'new-token', isTest: false }),
@@ -36,7 +47,13 @@ jest.mock('./utilities/cookie', () => ({
36
47
  setCartCookie: jest.fn(),
37
48
  readHandoffCart: jest.fn(),
38
49
  }));
39
- jest.mock('./utilities/local_storage', () => ({ getSavedCheckoutCustomer: () => null }));
50
+ jest.mock('./utilities/local_storage', () => ({
51
+ ...jest.requireActual('./utilities/local_storage'),
52
+ getSavedCheckoutCustomer: () => null,
53
+ saveCheckoutAddress: jest.fn(),
54
+ }));
55
+ jest.mock('./forms/InputsAddress', () => ({ __esModule: true, default: () => null }));
56
+ jest.mock('./components', () => ({ Title: () => null }));
40
57
  jest.mock('./utilities/job_source', () => ({
41
58
  captureAndReadJobSource: () => null,
42
59
  jobSourceFieldsForApi: () => ({}),
@@ -46,7 +63,7 @@ jest.mock('./utilities/job_source', () => ({
46
63
  jest.mock('./utilities/reportFailure', () => ({
47
64
  reportCartFailure: jest.fn(),
48
65
  reportAddCartItemFailure: jest.fn((error, onError) => onError(error)),
49
- CART_FAILURE_SOURCES: { load: 'cart.load', create: 'cart.create' },
66
+ CART_FAILURE_SOURCES: { load: 'cart.load', create: 'cart.create', update: 'cart.update' },
50
67
  }));
51
68
 
52
69
  let context: ReturnType<typeof useCartContext>;
@@ -487,6 +504,92 @@ describe('cart load and replacement failures', () => {
487
504
  expect(context.alert.show).toBe(true);
488
505
  expect(context.alert.message).toBe('The discount could not be applied.');
489
506
  });
507
+
508
+ it('updates the displayed cart when another tab has replaced the cart cookie', async () => {
509
+ mockGet.mockResolvedValue({ toJson: () => ({ id: 42, token: 'visible-token', cartItems: [{ id: 7 }] }) });
510
+ await act(async () => root.render(<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>));
511
+ (getCartCookie as jest.Mock).mockResolvedValue(['99', 'new-token']);
512
+ (getCartCookieToken as jest.Mock).mockResolvedValue('new-token');
513
+ mockSaveCart.mockImplementation((id, token) => token === 'visible-token'
514
+ ? Promise.resolve({ toJson: () => ({ id, token, receiverAddress: { city: 'Melbourne' } }) })
515
+ : Promise.reject(Object.assign(new Error('Authentication required'), { statusCode: 401 })));
516
+ mockShipmentQuotes.mockResolvedValue({ shipmentGroups: [{ id: 1 }] });
517
+
518
+ await act(async () => { await context.updateCartShipmentAddress({ city: 'Melbourne' }); });
519
+
520
+ expect(mockSaveCart).toHaveBeenCalledWith(42, 'visible-token');
521
+ expect(mockShipmentQuotes).toHaveBeenCalledWith('visible-token', '/generate-cart-shipment-quotes/42/', { method: 'GET' });
522
+ expect(context.cart).toMatchObject({ id: 42, receiverAddress: { city: 'Melbourne' }, shipmentGroups: [{ id: 1 }] });
523
+ expect(reportCartFailure).not.toHaveBeenCalled();
524
+ });
525
+
526
+ it('uses the matching checkout cookie when the cart response has no token', async () => {
527
+ await mountSavedCart();
528
+ mockSaveCart.mockResolvedValue({ toJson: () => ({ id: 42 }) });
529
+ mockShipmentQuotes.mockResolvedValue({ shipmentGroups: [] });
530
+
531
+ await act(async () => { await context.updateCartShipmentAddress({ city: 'Melbourne' }); });
532
+
533
+ expect(mockSaveCart).toHaveBeenCalledWith(42, 'saved-token');
534
+ expect(mockShipmentQuotes).toHaveBeenCalledWith('saved-token', '/generate-cart-shipment-quotes/42/', { method: 'GET' });
535
+ });
536
+
537
+ it('refreshes shipment options with the displayed cart token when the cookie changes', async () => {
538
+ mockGet.mockResolvedValue({ toJson: () => ({ id: 42, token: 'visible-token', cartItems: [{ id: 7 }] }) });
539
+ await act(async () => root.render(<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>));
540
+ (getCartCookie as jest.Mock).mockResolvedValue(['99', 'new-token']);
541
+ mockShipmentQuotes.mockResolvedValue({ shipmentGroups: [{ id: 1 }] });
542
+
543
+ await act(async () => { await context.getCartShipmentOptions?.(); });
544
+
545
+ expect(mockShipmentQuotes).toHaveBeenCalledWith('visible-token', '/generate-cart-shipment-quotes/42/', { method: 'GET' });
546
+ expect(context.cart).toMatchObject({ id: 42, cartItems: [{ id: 7 }], shipmentGroups: [{ id: 1 }] });
547
+ });
548
+
549
+ it('keeps the cart intact when only a different cart’s token is available', async () => {
550
+ await mountSavedCart();
551
+ (getCartCookie as jest.Mock).mockResolvedValue(['99', 'new-token']);
552
+ (getCartCookieToken as jest.Mock).mockResolvedValue('new-token');
553
+ mockSaveCart.mockRejectedValue(Object.assign(new Error('Authentication required'), { statusCode: 401 }));
554
+
555
+ await act(async () => { await context.updateCartShipmentAddress({ city: 'Melbourne' }); });
556
+
557
+ expect(mockSaveCart).not.toHaveBeenCalled();
558
+ expect(mockPost).not.toHaveBeenCalled();
559
+ expect(mockShipmentQuotes).not.toHaveBeenCalled();
560
+ expect(context.cart.id).toBe(42);
561
+ expect(context.alert.message).toContain('Reload checkout');
562
+ });
563
+
564
+ it.each(['visible-token', undefined])(
565
+ 'submits the displayed checkout cart after another tab replaces its cookie (%s)',
566
+ async token => {
567
+ mockGet.mockResolvedValue({ toJson: () => ({ id: 42, token, cartItems: [{ id: 7 }] }) });
568
+ await act(async () => root.render(
569
+ <CartProvider domainId={5} createCartAndCookie={() => {}}>
570
+ <Probe />
571
+ <ActiveFormShipmentAddressAndNotes />
572
+ </CartProvider>,
573
+ ));
574
+ (getCartCookie as jest.Mock).mockResolvedValue(['99', 'new-token']);
575
+ (getCartCookieToken as jest.Mock).mockResolvedValue('new-token');
576
+ mockSaveCart.mockImplementation((id, cartToken) => cartToken === 'visible-token'
577
+ ? Promise.resolve({ toJson: () => ({ id, token: cartToken }) })
578
+ : Promise.reject(Object.assign(new Error('Authentication required'), { statusCode: 401 })));
579
+
580
+ const form = container.querySelector('form')!;
581
+ await act(async () => form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })));
582
+
583
+ if (token) {
584
+ expect(mockSaveCart).toHaveBeenCalledTimes(1);
585
+ expect(mockSaveCart).toHaveBeenCalledWith(42, token);
586
+ } else {
587
+ expect(mockSaveCart).not.toHaveBeenCalled();
588
+ expect(context.alert.message).toContain('Reload checkout');
589
+ }
590
+ expect(context.cart.id).toBe(42);
591
+ },
592
+ );
490
593
  it.each([
491
594
  new TypeError('Failed to fetch'),
492
595
  { statusCode: 503, message: 'Service unavailable' },
@@ -24,6 +24,7 @@ import { persistTestCheckoutFlag, readTestCheckoutFlag } from './utilities/test_
24
24
  import { reportAddCartItemFailure, reportCartFailure, CART_FAILURE_SOURCES } from './utilities/reportFailure';
25
25
  import { isAutomatedClient } from './utilities/automatedClient';
26
26
  import { canReplaceMissingCart } from './utilities/cartLoadFailure';
27
+ import { getCheckoutCartClient } from './utilities/checkoutCartClient';
27
28
  import {
28
29
  appendJobSourceToFormData,
29
30
  captureAndReadJobSource,
@@ -794,28 +795,32 @@ const CartProvider = ({
794
795
 
795
796
  const [fetchingShipmentGroups, setFetchingShipmentGroups] = useState(false);
796
797
  async function updateCartShipmentAddress(address: any) {
797
- // Updates the receiver address on cart and fetches new shipment quotes
798
- const token = await getCartCookieToken((domainId as string | number));
799
- const addressFields = sanitizeAddressFields(address);
800
- const receiverAddress = makeAddress(addressFields, true);
801
- let cartEnt = makeCart(cart, false, token);
798
+ const cartId = cart?.id;
799
+ if (!cartId || cart.invoice?.unpaid === false) return;
800
+
802
801
  setFetchingShipmentGroups(true);
803
802
  try {
804
- cartEnt.receiverAddress = receiverAddress;
805
- cartEnt = await cartEnt.save({embed: cartEmbed});
806
- const cartJson = cartEnt.toJson();
803
+ const shipmentApi = await getCheckoutCartClient(cart, domainId, merchi.backendUri);
804
+ if (!shipmentApi) {
805
+ alertError('Unable to verify this cart. Reload checkout and try again.');
806
+ return;
807
+ }
808
+
809
+ const addressFields = sanitizeAddressFields(address);
810
+ const cartEnt = new shipmentApi.Cart().fromJson(cart);
811
+ cartEnt.receiverAddress = makeAddress(addressFields, true);
812
+ const savedCart = await cartEnt.save({embed: cartEmbed});
813
+ const cartJson = savedCart.toJson();
807
814
  saveCheckoutAddress(domainId, addressFields);
808
- const query: Array<any> = [];
809
- query.push(['cart_token', cart.token]);
810
- const cartWithShipmentGroups = await merchi.authenticatedFetch(
811
- `/generate-cart-shipment-quotes/${cart.id}/`,
812
- {method: 'GET', query}
815
+ const cartWithShipmentGroups = await shipmentApi.authenticatedFetch(
816
+ `/generate-cart-shipment-quotes/${cartId}/`,
817
+ {method: 'GET'}
813
818
  );
814
819
 
815
- setCart({
820
+ setCart((current: any) => current?.id === cartId ? {
816
821
  ...cartJson,
817
822
  shipmentGroups: cartWithShipmentGroups.shipmentGroups || []
818
- });
823
+ } : current);
819
824
  } catch (e: any) {
820
825
  reportCartFailure(e, CART_FAILURE_SOURCES.update);
821
826
  alertError(e.errorMessage || e.message || 'Unable to set address');
@@ -825,18 +830,24 @@ const CartProvider = ({
825
830
  }
826
831
 
827
832
  async function getCartShipmentOptions() {
833
+ const cartId = cart?.id;
834
+ if (!cartId) return;
835
+
828
836
  setFetchingShipmentGroups(true);
829
837
  try {
830
- const query: Array<any> = [];
831
- query.push(['cart_token', cart.token]);
832
- const cartWithGroups = await merchi.authenticatedFetch(
833
- `/generate-cart-shipment-quotes/${cart.id}/`,
834
- {method: 'GET', query}
838
+ const shipmentApi = await getCheckoutCartClient(cart, domainId, merchi.backendUri);
839
+ if (!shipmentApi) {
840
+ alertError('Unable to verify this cart. Reload checkout and try again.');
841
+ return;
842
+ }
843
+ const cartWithGroups = await shipmentApi.authenticatedFetch(
844
+ `/generate-cart-shipment-quotes/${cartId}/`,
845
+ {method: 'GET'}
835
846
  );
836
- setCart({
837
- ...cart,
847
+ setCart((current: any) => current?.id === cartId ? {
848
+ ...current,
838
849
  shipmentGroups: cartWithGroups.shipmentGroups || []
839
- });
850
+ } : current);
840
851
  } catch (e: any) {
841
852
  reportCartFailure(e, CART_FAILURE_SOURCES.shipping);
842
853
  alertError(e.errorMessage || e.message || 'Unable to fetch shipment options');
@@ -6,12 +6,11 @@ import {
6
6
  checkoutShipmentHydrationAction,
7
7
  shipmentFormId,
8
8
  } from "../utilities/shipment";
9
+ import { getCheckoutCartClient } from "../utilities/checkoutCartClient";
9
10
  import { faMapMarkerAlt } from "@fortawesome/free-solid-svg-icons";
10
11
  import { useCartContext } from "../CartProvider";
11
12
  import { useEffect, useRef, useState } from "react";
12
- import { getCartCookieToken } from "../utilities/cookie";
13
13
  import { makeAddress, sanitizeAddressFields } from "../utilities/address";
14
- import { makeCart } from "../utilities/cart";
15
14
  import { cartEmbed } from "../utilities/helpers";
16
15
  import { tabIdCheckout } from "../utilities/tabs";
17
16
  import {
@@ -128,6 +127,12 @@ export function ActiveFormShipmentAddressAndNotes() {
128
127
  const receiverNotes = cart?.receiverNotes || saved.receiverNotes || "";
129
128
  const [addressFieldsOpen, setAddressFieldsOpen] = useState(false);
130
129
  const hydratedShipmentOptionsRef = useRef(false);
130
+ const currentCartId = useRef(cart?.id);
131
+
132
+ useEffect(() => {
133
+ currentCartId.current = cart?.id;
134
+ return () => { currentCartId.current = undefined; };
135
+ }, [cart?.id]);
131
136
 
132
137
  useEffect(() => {
133
138
  if (hydratedShipmentOptionsRef.current || !cart?.id) return;
@@ -156,19 +161,29 @@ export function ActiveFormShipmentAddressAndNotes() {
156
161
  ]);
157
162
 
158
163
  async function saveCartShipmentAddressAndGoToNextTab(values: any) {
164
+ const cartId = cart?.id;
165
+ if (!cartId || cart.invoice?.unpaid === false) return;
166
+
159
167
  const { receiverAddress: address, receiverNotes } = values;
160
168
  setLoadingTotals(true);
161
169
  try {
162
- const cartToken = await getCartCookieToken(domainId as number);
170
+ const shipmentApi = await getCheckoutCartClient(cart, domainId);
171
+ if (!shipmentApi) {
172
+ alertError("Unable to verify this cart. Reload checkout and try again.");
173
+ return;
174
+ }
163
175
  // Never PATCH an existing Address via cart token — create a fresh embed.
164
176
  const addressFields = sanitizeAddressFields(address);
165
177
  const receiverAddress = makeAddress(addressFields, true);
166
- const cartEnt = makeCart(cart, false, cartToken);
178
+ const cartEnt = new shipmentApi.Cart().fromJson(cart);
167
179
  cartEnt.receiverAddress = receiverAddress;
168
180
  cartEnt.receiverNotes = receiverNotes;
169
- await cartEnt.save({ embed: cartEmbed });
181
+ const savedCart = await cartEnt.save({ embed: cartEmbed });
182
+ if (currentCartId.current !== cartId) return;
183
+
170
184
  saveCheckoutAddress(domainId, addressFields, receiverNotes);
171
- setCart(cartEnt.toJson());
185
+ const cartJson = savedCart.toJson();
186
+ setCart((current: any) => current?.id === cartId ? cartJson : current);
172
187
  setActiveTabAndEditDisabled({
173
188
  tabId: tabIdCheckout,
174
189
  tabIndexToSet: 2,
@@ -0,0 +1,16 @@
1
+ import { Merchi } from '@merchi/sdk';
2
+ import { getCartCookie } from './cookie';
3
+
4
+ export async function getCheckoutCartClient(
5
+ cart: { id: number | string; token?: string; isTest?: boolean },
6
+ domainId: number | string | undefined,
7
+ apiUrl?: string,
8
+ ) {
9
+ let token = cart.token;
10
+ // Another tab can replace the cookie while checkout still shows its own cart.
11
+ if (!token && domainId) {
12
+ const cookie = await getCartCookie(domainId, cart.isTest === true);
13
+ if (cookie?.[0] === String(cart.id)) token = cookie[1];
14
+ }
15
+ return token ? new Merchi(undefined, undefined, undefined, token, apiUrl) : undefined;
16
+ }