@merchi/cart 1.4.84 → 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.
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports["default"] = void 0;
7
+ var _TestOrderNotice = _interopRequireDefault(require("@merchi/invoice/lib/TestOrderNotice"));
7
8
  var _containers = require("../components/containers");
8
9
  var _tabs = require("../utilities/tabs");
9
10
  var _company = require("../utilities/company");
@@ -13,8 +14,10 @@ var _buttons = require("../buttons");
13
14
  var _components = require("../components");
14
15
  var _CartProvider = require("../CartProvider");
15
16
  var _jsxRuntime = require("react/jsx-runtime");
17
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
16
18
  function PanelPaymentSuccess() {
17
19
  var _useCartContext = (0, _CartProvider.useCartContext)(),
20
+ cart = _useCartContext.cart,
18
21
  classNameBtnPrimary = _useCartContext.classNameBtnPrimary,
19
22
  customSuccessMessage = _useCartContext.customSuccessMessage,
20
23
  fetchingCart = _useCartContext.fetchingCart,
@@ -30,20 +33,25 @@ function PanelPaymentSuccess() {
30
33
  children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.CartBody, {
31
34
  children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_containers.CheckoutContainer, {
32
35
  children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_containers.InnerContainer, {
33
- children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("h2", {
34
- children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactFontawesome.FontAwesomeIcon, {
35
- icon: _freeSolidSvgIcons.faCheckCircle
36
- })
37
- }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("h3", {
38
- children: ["Order #", id]
39
- }), /*#__PURE__*/(0, _jsxRuntime.jsx)("h4", {
40
- children: "Payment Received!"
41
- }), customSuccessMessage ? /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
42
- className: "merchi-cart-success-message ",
43
- children: customSuccessMessage
44
- }) : /*#__PURE__*/(0, _jsxRuntime.jsxs)("p", {
45
- className: "merchi-cart-success-message ",
46
- children: ["Your order #", id, " is being processed and you should receive an email from us shortly. If you haven't heard from us within 24 hours please feel free to contact us", email ? " at ".concat(email.emailAddress, ".") : '.']
36
+ children: [invoiceJson.isTest || cart !== null && cart !== void 0 && cart.isTest ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_TestOrderNotice["default"], {
37
+ title: "Test order #".concat(id),
38
+ paymentReceived: unpaid === false
39
+ }) : /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
40
+ children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("h2", {
41
+ children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactFontawesome.FontAwesomeIcon, {
42
+ icon: _freeSolidSvgIcons.faCheckCircle
43
+ })
44
+ }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("h3", {
45
+ children: ["Order #", id]
46
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)("h4", {
47
+ children: "Payment Received!"
48
+ }), customSuccessMessage ? /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
49
+ className: "merchi-cart-success-message ",
50
+ children: customSuccessMessage
51
+ }) : /*#__PURE__*/(0, _jsxRuntime.jsxs)("p", {
52
+ className: "merchi-cart-success-message ",
53
+ children: ["Your order #", id, " is being processed and you should receive an email from us shortly. If you haven't heard from us within 24 hours please feel free to contact us", email ? " at ".concat(email.emailAddress, ".") : '.']
54
+ })]
47
55
  }), !unpaid && /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
48
56
  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_buttons.ButtonInvoiceDownload, {})
49
57
  }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
@@ -0,0 +1,5 @@
1
+ export declare function getCheckoutCartClient(cart: {
2
+ id: number | string;
3
+ token?: string;
4
+ isTest?: boolean;
5
+ }, domainId: number | string | undefined, apiUrl?: string): Promise<any>;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getCheckoutCartClient = getCheckoutCartClient;
7
+ var _sdk = require("@merchi/sdk");
8
+ var _cookie = require("./cookie");
9
+ function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
10
+ function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
11
+ function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
12
+ function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
13
+ function getCheckoutCartClient(_x, _x2, _x3) {
14
+ return _getCheckoutCartClient.apply(this, arguments);
15
+ }
16
+ function _getCheckoutCartClient() {
17
+ _getCheckoutCartClient = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(cart, domainId, apiUrl) {
18
+ var token, cookie;
19
+ return _regenerator().w(function (_context) {
20
+ while (1) switch (_context.n) {
21
+ case 0:
22
+ token = cart.token; // Another tab can replace the cookie while checkout still shows its own cart.
23
+ if (!(!token && domainId)) {
24
+ _context.n = 2;
25
+ break;
26
+ }
27
+ _context.n = 1;
28
+ return (0, _cookie.getCartCookie)(domainId, cart.isTest === true);
29
+ case 1:
30
+ cookie = _context.v;
31
+ if ((cookie === null || cookie === void 0 ? void 0 : cookie[0]) === String(cart.id)) token = cookie[1];
32
+ case 2:
33
+ return _context.a(2, token ? new _sdk.Merchi(undefined, undefined, undefined, token, apiUrl) : undefined);
34
+ }
35
+ }, _callee);
36
+ }));
37
+ return _getCheckoutCartClient.apply(this, arguments);
38
+ }
@@ -1,6 +1,3 @@
1
- export declare const TEST_CHECKOUT_QUERY = "merchi_test_checkout";
2
- export declare const TEST_CHECKOUT_STORAGE_KEY = "merchi_test_checkout";
3
- export declare const TEST_CARD_NUMBER = "4242 4242 4242 4242";
4
- export declare function readTestCheckoutFlag(): boolean;
1
+ export { readTestCheckoutFlag, TEST_CARD_NUMBER, TEST_CHECKOUT_QUERY, TEST_CHECKOUT_STORAGE_KEY } from '@merchi/invoice/lib/testCheckout';
5
2
  export declare function persistTestCheckoutFlag(): boolean;
6
3
  export declare function cartCookieName(domainId: number | string, isTest?: boolean): string;
@@ -3,30 +3,35 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.TEST_CHECKOUT_STORAGE_KEY = exports.TEST_CHECKOUT_QUERY = exports.TEST_CARD_NUMBER = void 0;
6
+ Object.defineProperty(exports, "TEST_CARD_NUMBER", {
7
+ enumerable: true,
8
+ get: function get() {
9
+ return _testCheckout.TEST_CARD_NUMBER;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "TEST_CHECKOUT_QUERY", {
13
+ enumerable: true,
14
+ get: function get() {
15
+ return _testCheckout.TEST_CHECKOUT_QUERY;
16
+ }
17
+ });
18
+ Object.defineProperty(exports, "TEST_CHECKOUT_STORAGE_KEY", {
19
+ enumerable: true,
20
+ get: function get() {
21
+ return _testCheckout.TEST_CHECKOUT_STORAGE_KEY;
22
+ }
23
+ });
7
24
  exports.cartCookieName = cartCookieName;
8
25
  exports.persistTestCheckoutFlag = persistTestCheckoutFlag;
9
- exports.readTestCheckoutFlag = readTestCheckoutFlag;
10
- var TEST_CHECKOUT_QUERY = exports.TEST_CHECKOUT_QUERY = 'merchi_test_checkout';
11
- var TEST_CHECKOUT_STORAGE_KEY = exports.TEST_CHECKOUT_STORAGE_KEY = 'merchi_test_checkout';
12
- var TEST_CARD_NUMBER = exports.TEST_CARD_NUMBER = '4242 4242 4242 4242';
13
- function readTestCheckoutFlag() {
14
- if (typeof window === 'undefined') {
15
- return false;
16
- }
17
- try {
18
- var params = new URLSearchParams(window.location.search);
19
- if (params.get(TEST_CHECKOUT_QUERY) === '1') {
20
- window.localStorage.setItem(TEST_CHECKOUT_STORAGE_KEY, '1');
21
- return true;
22
- }
23
- return window.localStorage.getItem(TEST_CHECKOUT_STORAGE_KEY) === '1';
24
- } catch (_unused) {
25
- return false;
26
+ Object.defineProperty(exports, "readTestCheckoutFlag", {
27
+ enumerable: true,
28
+ get: function get() {
29
+ return _testCheckout.readTestCheckoutFlag;
26
30
  }
27
- }
31
+ });
32
+ var _testCheckout = require("@merchi/invoice/lib/testCheckout");
28
33
  function persistTestCheckoutFlag() {
29
- return readTestCheckoutFlag();
34
+ return (0, _testCheckout.readTestCheckoutFlag)();
30
35
  }
31
36
  function cartCookieName(domainId) {
32
37
  var isTest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@merchi/cart",
3
- "version": "1.4.84",
3
+ "version": "1.4.86",
4
4
  "description": "Merchi's cart",
5
5
  "source": "src/index.ts",
6
6
  "main": "lib/index.js",
@@ -94,7 +94,7 @@
94
94
  "@fortawesome/free-solid-svg-icons": "6.4.2",
95
95
  "@fortawesome/react-fontawesome": "^0.2.0",
96
96
  "@merchi/error-catch": "^0.1.13",
97
- "@merchi/invoice": "^1.3.20",
97
+ "@merchi/invoice": "^1.3.21",
98
98
  "@merchi/product-form": "^1.19.66",
99
99
  "@merchi/product-form-sdk": "^1.0.43",
100
100
  "@merchi/sdk": "^1.42.32",
@@ -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,36 @@
1
+ import * as React from 'react';
2
+ import { renderToStaticMarkup } from 'react-dom/server.node';
3
+ import { useCartContext } from '../CartProvider';
4
+ import PanelPaymentSuccess from './PanelPaymentSuccess';
5
+
6
+ jest.mock('../CartProvider', () => ({ useCartContext: jest.fn() }));
7
+ jest.mock('../components/containers', () => ({
8
+ CheckoutContainer: ({ children }: any) => children,
9
+ InnerContainer: ({ children }: any) => children,
10
+ }));
11
+ jest.mock('../components', () => ({
12
+ CartBody: ({ children }: any) => children,
13
+ CartTabPanel: ({ children }: any) => children,
14
+ }));
15
+ jest.mock('../buttons', () => ({
16
+ Button: ({ children }: any) => <button>{children}</button>,
17
+ ButtonInvoiceDownload: () => <button>Download receipt</button>,
18
+ }));
19
+
20
+ it.each([
21
+ [true, false, true],
22
+ [undefined, true, true],
23
+ [false, false, false],
24
+ ])('labels the confirmation for invoice %s and cart %s', (invoiceTest, cartTest, expectedTest) => {
25
+ (useCartContext as jest.Mock).mockReturnValue({
26
+ cart: { isTest: cartTest },
27
+ invoiceJson: { id: 42, isTest: invoiceTest, unpaid: false },
28
+ customSuccessMessage: 'Our team is preparing your goods.',
29
+ });
30
+ const page = renderToStaticMarkup(<PanelPaymentSuccess />);
31
+ expect(page.includes('Test order #42')).toBe(expectedTest);
32
+ expect(page.includes('Simulated payment received.')).toBe(expectedTest);
33
+ expect(page.includes('Payment Received!')).toBe(!expectedTest);
34
+ expect(page.includes('Our team is preparing your goods.')).toBe(!expectedTest);
35
+ expect(page).toContain('Download receipt');
36
+ });
@@ -1,3 +1,4 @@
1
+ import TestOrderNotice from '@merchi/invoice/lib/TestOrderNotice';
1
2
  import {
2
3
  CheckoutContainer,
3
4
  InnerContainer,
@@ -12,6 +13,7 @@ import { useCartContext } from '../CartProvider';
12
13
 
13
14
  function PanelPaymentSuccess() {
14
15
  const {
16
+ cart,
15
17
  classNameBtnPrimary,
16
18
  customSuccessMessage,
17
19
  fetchingCart,
@@ -26,19 +28,25 @@ function PanelPaymentSuccess() {
26
28
  <CartBody>
27
29
  <CheckoutContainer>
28
30
  <InnerContainer>
29
- <h2><FontAwesomeIcon icon={faCheckCircle} /></h2>
30
- <h3>Order #{id}</h3>
31
- <h4>Payment Received!</h4>
32
- {customSuccessMessage ? (
33
- <p className='merchi-cart-success-message '>
34
- {customSuccessMessage}
35
- </p>
31
+ {invoiceJson.isTest || cart?.isTest ? (
32
+ <TestOrderNotice title={`Test order #${id}`} paymentReceived={unpaid === false} />
36
33
  ) : (
37
- <p className='merchi-cart-success-message '>
38
- Your order #{id} is being processed and you should
39
- receive an email from us shortly. If you haven't heard from us within 24
40
- hours please feel free to contact us{email ? ` at ${email.emailAddress}.` : '.'}
41
- </p>
34
+ <>
35
+ <h2><FontAwesomeIcon icon={faCheckCircle} /></h2>
36
+ <h3>Order #{id}</h3>
37
+ <h4>Payment Received!</h4>
38
+ {customSuccessMessage ? (
39
+ <p className='merchi-cart-success-message '>
40
+ {customSuccessMessage}
41
+ </p>
42
+ ) : (
43
+ <p className='merchi-cart-success-message '>
44
+ Your order #{id} is being processed and you should
45
+ receive an email from us shortly. If you haven't heard from us within 24
46
+ hours please feel free to contact us{email ? ` at ${email.emailAddress}.` : '.'}
47
+ </p>
48
+ )}
49
+ </>
42
50
  )}
43
51
  {!unpaid && <p><ButtonInvoiceDownload /></p>}
44
52
  <p>
@@ -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
+ }
@@ -1,22 +1,5 @@
1
- export const TEST_CHECKOUT_QUERY = 'merchi_test_checkout';
2
- export const TEST_CHECKOUT_STORAGE_KEY = 'merchi_test_checkout';
3
- export const TEST_CARD_NUMBER = '4242 4242 4242 4242';
4
-
5
- export function readTestCheckoutFlag(): boolean {
6
- if (typeof window === 'undefined') {
7
- return false;
8
- }
9
- try {
10
- const params = new URLSearchParams(window.location.search);
11
- if (params.get(TEST_CHECKOUT_QUERY) === '1') {
12
- window.localStorage.setItem(TEST_CHECKOUT_STORAGE_KEY, '1');
13
- return true;
14
- }
15
- return window.localStorage.getItem(TEST_CHECKOUT_STORAGE_KEY) === '1';
16
- } catch {
17
- return false;
18
- }
19
- }
1
+ import { readTestCheckoutFlag } from '@merchi/invoice/lib/testCheckout';
2
+ export { readTestCheckoutFlag, TEST_CARD_NUMBER, TEST_CHECKOUT_QUERY, TEST_CHECKOUT_STORAGE_KEY } from '@merchi/invoice/lib/testCheckout';
20
3
 
21
4
  export function persistTestCheckoutFlag(): boolean {
22
5
  return readTestCheckoutFlag();