Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use graphql to add item to cart #1987

Merged
merged 19 commits into from
Dec 11, 2019
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -172,43 +172,59 @@ describe('createCart', () => {
});

describe('addItemToCart', () => {
const payload = { item: 'ITEM', quantity: 1 };
const payload = {
item: { sku: 'ITEM' },
productType: 'SimpleProduct',
quantity: 1,
addSimpleProductToCart: jest.fn().mockResolvedValue(),
addConfigurableProductToCart: jest.fn().mockResolvedValue()
};

test('it returns a thunk', () => {
expect(addItemToCart()).toBeInstanceOf(Function);
});

test('its thunk returns undefined', async () => {
const result = await addItemToCart()(...thunkArgs);
const result = await addItemToCart(payload)(...thunkArgs);

expect(result).toBeUndefined();
});

// test('addItemToCart thunk dispatches actions on success', async () => {
// const payload = { item: 'ITEM', quantity: 1 };
// const cartItem = 'CART_ITEM';

// request.mockResolvedValueOnce(cartItem);
// await addItemToCart(payload)(...thunkArgs);

// expect(dispatch).toHaveBeenNthCalledWith(
// 1,
// actions.addItem.request(payload)
// );
// expect(dispatch).toHaveBeenNthCalledWith(2, expect.any(Function));
// expect(dispatch).toHaveBeenNthCalledWith(3, expect.any(Function));
// expect(dispatch).toHaveBeenNthCalledWith(
// 4,
// actions.addItem.receive({ cartItem, ...payload })
// );
// expect(dispatch).toHaveBeenCalledTimes(4);
// });
test('it uses the simple product mutation for simple product type', async () => {
await addItemToCart({
...payload,
productType: 'SimpleProduct'
})(...thunkArgs);

test('its thunk dispatches actions on success', async () => {
// Test setup.
const cartItem = 'CART_ITEM';
request.mockResolvedValueOnce(cartItem);
expect(payload.addSimpleProductToCart).toHaveBeenCalledTimes(1);
});

test('it uses the configurable product mutation for configurable product type', async () => {
await addItemToCart({
...payload,
productType: 'ConfigurableProduct'
})(...thunkArgs);

expect(payload.addConfigurableProductToCart).toHaveBeenCalledTimes(1);
});

test('it dispatches an error for an invalid product type', async () => {
await addItemToCart({
...payload,
productType: 'INVALID'
})(...thunkArgs);

expect(payload.addConfigurableProductToCart).toHaveBeenCalledTimes(0);
expect(payload.addSimpleProductToCart).toHaveBeenCalledTimes(0);
expect(dispatch).toHaveBeenNthCalledWith(
2,
actions.addItem.receive(
new Error('Unsupported product type. Cannot add to cart.')
)
);
});

test('its thunk dispatches actions on success', async () => {
// Call the function.
await addItemToCart(payload)(...thunkArgs);

Expand All @@ -225,47 +241,22 @@ describe('addItemToCart', () => {
expect(dispatch).toHaveBeenNthCalledWith(4, actions.addItem.receive());
});

// test('it calls writeImageToCache', async () => {
// writeImageToCache.mockImplementationOnce(() => {});

// await updateItemInCart(payload)(...thunkArgs);

// expect(writeImageToCache).toHaveBeenCalled();
// });

test('its thunk dispatches special failure if cartId is not present', async () => {
getState.mockImplementationOnce(() => ({
cart: {
/* Purposefully no cartId here */
},
user: { isSignedIn: false }
}));

const error = new Error('Missing required information: cartId');
error.noCartId = true;

await addItemToCart(payload)(...thunkArgs);

expect(dispatch).toHaveBeenNthCalledWith(
1,
actions.addItem.request(payload)
);
expect(dispatch).toHaveBeenNthCalledWith(
2,
actions.addItem.receive(error)
);
// createCart
expect(dispatch).toHaveBeenNthCalledWith(3, expect.any(Function));
});

test('its thunk tries to recreate a cart on 404 failure', async () => {
test('its thunk tries to recreate a cart on non-network, invalid cart failure', async () => {
const error = new Error('ERROR');
error.response = {
status: 404
};
request.mockRejectedValueOnce(error);
error.networkError = false;
error.graphQLErrors = [
{
message: 'Could not find a cart'
}
];

await addItemToCart(payload)(...thunkArgs);
const customPayload = {
...payload,
addSimpleProductToCart: jest.fn().mockRejectedValueOnce(error)
};
await addItemToCart({
...customPayload
})(...thunkArgs);

expect(dispatch).toHaveBeenCalledTimes(9);

Expand All @@ -275,7 +266,7 @@ describe('addItemToCart', () => {

expect(dispatch).toHaveBeenNthCalledWith(
1,
actions.addItem.request(payload)
actions.addItem.request(customPayload)
);
expect(dispatch).toHaveBeenNthCalledWith(
2,
Expand All @@ -293,7 +284,7 @@ describe('addItemToCart', () => {
*/
expect(dispatch).toHaveBeenNthCalledWith(
6,
actions.addItem.request(payload)
actions.addItem.request(customPayload)
);
// getCartDetails
expect(dispatch).toHaveBeenNthCalledWith(7, expect.any(Function));
Expand All @@ -302,21 +293,6 @@ describe('addItemToCart', () => {
// addItem.receive
expect(dispatch).toHaveBeenNthCalledWith(9, actions.addItem.receive());
});

test('its thunk uses the appropriate endpoint when user is signed in', async () => {
getState.mockImplementationOnce(() => ({
cart: { cartId: 'SOME_CART_ID', details: { id: 'HASH_ID' } },
user: { isSignedIn: true }
}));

await addItemToCart(payload)(...thunkArgs);

const authedEndpoint = '/rest/V1/carts/mine/items';
expect(request).toHaveBeenCalledWith(authedEndpoint, {
method: 'POST',
body: expect.any(String)
});
});
});

describe('removeItemFromCart', () => {
Expand Down Expand Up @@ -878,7 +854,7 @@ describe('writeImageToCache', () => {
media_gallery_entries: []
};

await addItemToCart(emptyImages);
await writeImageToCache(emptyImages);

expect(mockGetItem).not.toHaveBeenCalled();
});
Expand Down
60 changes: 29 additions & 31 deletions packages/peregrine/lib/store/actions/cart/asyncActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,39 +52,28 @@ export const createCart = payload =>
};

export const addItemToCart = (payload = {}) => {
const { item, fetchCartId } = payload;
const { addItemMutation, fetchCartId, item, quantity, parentSku } = payload;

const writingImageToCache = writeImageToCache(item);

return async function thunk(dispatch, getState) {
await writingImageToCache;
dispatch(actions.addItem.request(payload));

try {
const { cart, user } = getState();
const { isSignedIn } = user;
let cartEndpoint;

if (!isSignedIn) {
const { cartId } = cart;

if (!cartId) {
const missingCartIdError = new Error(
'Missing required information: cartId'
);
missingCartIdError.noCartId = true;
throw missingCartIdError;
}
const { cart } = getState();
const { cartId } = cart;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this can be null after an order is placed, and a subsequent add calls this with a null cartId.

@tjwiebell suggested two options, but I think it may be better to figure out why the cart is deleted but never re-created after order. It should definitely be created every time the cartId is deleted.


cartEndpoint = `/rest/V1/guest-carts/${cartId}/items`;
} else {
cartEndpoint = '/rest/V1/carts/mine/items';
}
const variables = {
cartId,
parentSku,
product: item,
quantity,
sku: item.sku
};

const quoteId = getQuoteIdForRest(cart, user);
const cartItem = toRESTCartItem(quoteId, payload);
await request(cartEndpoint, {
method: 'POST',
body: JSON.stringify({ cartItem })
await addItemMutation({
variables
});

// 2019-02-07 Moved these dispatches to the success clause of
Expand All @@ -100,12 +89,12 @@ export const addItemToCart = (payload = {}) => {
await dispatch(toggleDrawer('cart'));
dispatch(actions.addItem.receive());
} catch (error) {
const { response, noCartId } = error;

dispatch(actions.addItem.receive(error));

// check if the cart has expired
if (noCartId || (response && response.status === 404)) {
const shouldRetry = !error.networkError && isInvalidCart(error);

// Only retry if the cart is invalid
if (shouldRetry) {
// Delete the cached ID from local storage and Redux.
// In contrast to the save, make sure storage deletion is
// complete before dispatching the error--you don't want an
Expand Down Expand Up @@ -209,8 +198,7 @@ export const updateItemInCart = (payload = {}) => {
// Add the updated item to that cart.
await dispatch(
addItemToCart({
...payload,
fetchCartId
...payload
sirugh marked this conversation as resolved.
Show resolved Hide resolved
})
);
}
Expand Down Expand Up @@ -376,7 +364,7 @@ export const getCartDetails = (payload = {}) => {
// TODO: If we don't have the image in cache we should probably try
// to find it some other way otherwise we have no image to display
// in the cart and will have to fall back to a placeholder.
if (imageCache && Array.isArray(items) && items.length) {
if (Array.isArray(items) && items.length) {
const validTotals = totals && totals.items;
items.forEach(item => {
item.image = item.image || imageCache[item.sku] || {};
Expand Down Expand Up @@ -542,3 +530,13 @@ export function getQuoteIdForRest(cart, user) {
return cart.cartId;
}
}

// Returns true if the cart is invalid.
function isInvalidCart(error) {
return !!(
error.graphQLErrors &&
error.graphQLErrors.find(err =>
err.message.includes('Could not find a cart')
)
);
}
47 changes: 43 additions & 4 deletions packages/peregrine/lib/talons/MiniCart/useCartOptions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { useCallback, useMemo, useState } from 'react';
import { useMutation } from '@apollo/react-hooks';

import { useCartContext } from '@magento/peregrine/lib/context/cart';

import { appendOptionsToPayload } from '../../util/appendOptionsToPayload';
import { findMatchingProductOptionValue } from '../../util/productVariants';
import { isProductConfigurable } from '../../util/isProductConfigurable';
Expand All @@ -18,10 +22,29 @@ const isItemMissingOptions = (cartItem, configItem, numSelections) => {
};

export const useCartOptions = props => {
const { cartItem, configItem, endEditItem, updateCart } = props;
const {
addConfigurableProductToCartMutation,
addSimpleProductToCartMutation,
cartItem,
configItem,
createCartMutation,
endEditItem
} = props;

const { name, price, qty } = cartItem;

const [, { updateItemInCart }] = useCartContext();

const [addConfigurableProductToCart] = useMutation(
addConfigurableProductToCartMutation
);

const [addSimpleProductToCart] = useMutation(
addSimpleProductToCartMutation
);

const [fetchCartId] = useMutation(createCartMutation);

const initialOptionSelections = useMemo(() => {
const result = new Map();

Expand Down Expand Up @@ -68,7 +91,7 @@ export const useCartOptions = props => {
[optionSelections]
);

const handleUpdate = useCallback(() => {
const handleUpdate = useCallback(async () => {
const payload = {
item: configItem,
productType: configItem.__typename,
Expand All @@ -80,8 +103,24 @@ export const useCartOptions = props => {
appendOptionsToPayload(payload, optionSelections);
}

updateCart(payload);
}, [cartItem, configItem, quantity, optionSelections, updateCart]);
await updateItemInCart({
...payload,
addConfigurableProductToCart,
addSimpleProductToCart,
fetchCartId
});
endEditItem();
}, [
configItem,
quantity,
cartItem.item_id,
optionSelections,
updateItemInCart,
addConfigurableProductToCart,
addSimpleProductToCart,
fetchCartId,
endEditItem
]);

const handleValueChange = useCallback(
value => {
Expand Down
Loading