Skip to content
New issue

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

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

Already on GitHub? # to your account

Refactor checkout workflow to set shipping address/get shipping methods with graphql #2018

Merged
merged 6 commits into from
Dec 18, 2019
Merged
Show file tree
Hide file tree
Changes from 4 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 @@ -8,7 +8,6 @@ import actions from '../actions';
import {
beginCheckout,
formatAddress,
getShippingMethods,
resetCheckout,
submitBillingAddress,
submitShippingAddress,
Expand Down Expand Up @@ -89,14 +88,12 @@ describe('beginCheckout', () => {
fetchCartId
})(...thunkArgs);

expect(dispatch).toHaveBeenCalledTimes(3);
expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, actions.reset());
expect(dispatch).toHaveBeenNthCalledWith(
2,
actions.begin(expect.any(Object))
);
// TODO: test fails but "Compared values have no visual difference."
// expect(dispatch).toHaveBeenNthCalledWith(2, cartActions.getShippingMethods());
});
});

Expand Down Expand Up @@ -128,68 +125,6 @@ describe('resetCheckout', () => {
});
});

describe('getShippingMethods', () => {
test('getShippingMethods() returns a thunk', () => {
expect(
getShippingMethods({
fetchCartId
})
).toBeInstanceOf(Function);
});

test('getShippingMethods thunk returns undefined', async () => {
const result = await getShippingMethods({
fetchCartId
})(...thunkArgs);

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

test('getShippingMethods thunk dispatches actions on success', async () => {
// Mock the estimate-shipping-methods response.
const MOCK_RESPONSE = [];
request.mockResolvedValueOnce(MOCK_RESPONSE);

await getShippingMethods({
fetchCartId
})(...thunkArgs);

expect(dispatch).toHaveBeenNthCalledWith(
1,
actions.getShippingMethods.request('CART_ID')
);
expect(dispatch).toHaveBeenNthCalledWith(
2,
actions.getShippingMethods.receive(MOCK_RESPONSE)
);
expect(dispatch).toHaveBeenCalledTimes(2);
});

test('getShippingMethods thunk dispatches actions on failure', async () => {
// Mock the estimate-shipping-methods response.
const error = new Error('ERROR');
request.mockRejectedValueOnce(error);

await getShippingMethods({
fetchCartId
})(...thunkArgs);

expect(dispatch).toHaveBeenNthCalledWith(
1,
actions.getShippingMethods.request('CART_ID')
);
expect(dispatch).toHaveBeenNthCalledWith(
2,
actions.getShippingMethods.receive(error)
);
expect(dispatch).toHaveBeenCalledTimes(2);
});

test('its thunk uses the proper endpoint when the user is signed in', async () => {
// TODO
});
});

describe('submitPaymentMethodAndBillingAddress', () => {
const payload = {
countries,
Expand Down Expand Up @@ -299,7 +234,26 @@ describe('submitBillingAddress', () => {
});

describe('submitShippingAddress', () => {
const payload = { type: 'shippingAddress', countries, formValues: address };
const addressData = ['SomeAddressData'];
const payload = {
countries,
formValues: address,
setGuestEmail: jest.fn().mockResolvedValue(),
setShippingAddressOnCart: jest.fn().mockResolvedValue({
data: {
setShippingAddressesOnCart: {
cart: {
shipping_addresses: [
{
available_shipping_methods: addressData
}
]
}
}
}
}),
type: 'shippingAddress'
};

test('submitShippingAddress() returns a thunk', () => {
expect(submitShippingAddress()).toBeInstanceOf(Function);
Expand All @@ -314,15 +268,19 @@ describe('submitShippingAddress', () => {
test('submitShippingAddress thunk dispatches actions on success', async () => {
await submitShippingAddress(payload)(...thunkArgs);

expect(dispatch).toHaveBeenCalledTimes(3);
expect(dispatch).toHaveBeenNthCalledWith(
1,
actions.shippingAddress.submit()
);
expect(dispatch).toHaveBeenNthCalledWith(
2,
actions.getShippingMethods.receive(addressData)
);
expect(dispatch).toHaveBeenNthCalledWith(
3,
actions.shippingAddress.accept(address)
);
expect(dispatch).toHaveBeenCalledTimes(2);
});

test('submitShippingAddress thunk saves to storage on success', async () => {
Expand Down Expand Up @@ -542,11 +500,15 @@ describe('submitOrder', () => {
expect(dispatch).toHaveBeenNthCalledWith(4, expect.any(Function));
expect(dispatch).toHaveBeenNthCalledWith(5, actions.order.accept());

expect(mockRemoveItem).toHaveBeenCalledTimes(4);
expect(mockRemoveItem).toHaveBeenCalledTimes(5);
expect(mockRemoveItem).toHaveBeenNthCalledWith(1, 'billing_address');
expect(mockRemoveItem).toHaveBeenNthCalledWith(2, 'paymentMethod');
expect(mockRemoveItem).toHaveBeenNthCalledWith(3, 'shipping_address');
expect(mockRemoveItem).toHaveBeenNthCalledWith(4, 'shippingMethod');
expect(mockRemoveItem).toHaveBeenNthCalledWith(
5,
'availableShippingMethods'
);
});

test('submitOrder thunk dispatches actions and clears local storage on success when addresses are different', async () => {
Expand Down Expand Up @@ -591,11 +553,15 @@ describe('submitOrder', () => {
expect(dispatch).toHaveBeenNthCalledWith(4, expect.any(Function));
expect(dispatch).toHaveBeenNthCalledWith(5, actions.order.accept());

expect(mockRemoveItem).toHaveBeenCalledTimes(4);
expect(mockRemoveItem).toHaveBeenCalledTimes(5);
expect(mockRemoveItem).toHaveBeenNthCalledWith(1, 'billing_address');
expect(mockRemoveItem).toHaveBeenNthCalledWith(2, 'paymentMethod');
expect(mockRemoveItem).toHaveBeenNthCalledWith(3, 'shipping_address');
expect(mockRemoveItem).toHaveBeenNthCalledWith(4, 'shippingMethod');
expect(mockRemoveItem).toHaveBeenNthCalledWith(
5,
'availableShippingMethods'
);
});

test('submitOrder thunk dispatches actions on failure', async () => {
Expand Down
151 changes: 78 additions & 73 deletions packages/peregrine/lib/store/actions/checkout/asyncActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,30 @@ import actions from './actions';
const { request } = Magento2;
const storage = new BrowserPersistence();

export const beginCheckout = payload =>
export const beginCheckout = () =>
async function thunk(dispatch) {
const { fetchCartId } = payload;
// Before we begin, reset the state of checkout to clear out stale data.
dispatch(actions.reset());

const storedBillingAddress = storage.getItem('billing_address');
const storedPaymentMethod = storage.getItem('paymentMethod');
const storedShippingAddress = storage.getItem('shipping_address');
const storedShippingMethod = storage.getItem('shippingMethod');
const storedAvailableShippingMethods = await retreiveAvailableShippingMethods();
const storedBillingAddress = await retrieveBillingAddress();
const storedPaymentMethod = await retrievePaymentMethod();
const storedShippingAddress = await retrieveShippingAddress();
const storedShippingMethod = await retrieveShippingMethod();

dispatch(
actions.begin({
availableShippingMethods: storedAvailableShippingMethods || [],
billingAddress: storedBillingAddress,
paymentCode: storedPaymentMethod && storedPaymentMethod.code,
paymentData: storedPaymentMethod && storedPaymentMethod.data,
shippingAddress: storedShippingAddress,
shippingAddress: storedShippingAddress || {},
shippingMethod:
storedShippingMethod && storedShippingMethod.carrier_code,
shippingTitle:
storedShippingMethod && storedShippingMethod.carrier_title
})
);
dispatch(
getShippingMethods({
fetchCartId
})
);
};

export const cancelCheckout = () =>
Expand All @@ -53,61 +49,6 @@ export const resetReceipt = () =>
await dispatch(actions.receipt.reset());
};

export const getShippingMethods = payload => {
return async function thunk(dispatch, getState) {
const { fetchCartId } = payload;
const { cart, user } = getState();
const { cartId } = cart;

try {
// if there isn't a cart, create one then retry this operation
if (!cartId) {
await dispatch(
createCart({
fetchCartId
})
);
return thunk(...arguments);
}

dispatch(actions.getShippingMethods.request(cartId));

const guestEndpoint = `/rest/V1/guest-carts/${cartId}/estimate-shipping-methods`;
const authedEndpoint =
'/rest/V1/carts/mine/estimate-shipping-methods';
const endpoint = user.isSignedIn ? authedEndpoint : guestEndpoint;

const response = await request(endpoint, {
method: 'POST',
body: JSON.stringify({
address: {
country_id: 'US',
postcode: null
}
})
});

dispatch(actions.getShippingMethods.receive(response));
} catch (error) {
const { response } = error;

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

// check if the guest cart has expired
if (response && response.status === 404) {
// if so, clear it out, get a new one and retry.
await dispatch(removeCart());
await dispatch(
createCart({
fetchCartId
})
);
return thunk(...arguments);
}
}
};
};

export const submitPaymentMethodAndBillingAddress = payload =>
async function thunk(dispatch) {
const { countries, formValues } = payload;
Expand Down Expand Up @@ -170,23 +111,74 @@ export const submitPaymentMethod = payload =>
}
};

export const submitShippingAddress = payload =>
export const submitShippingAddress = (payload = {}) =>
async function thunk(dispatch, getState) {
dispatch(actions.shippingAddress.submit());

const { cart } = getState();
const {
formValues,
countries,
setGuestEmail,
setShippingAddressOnCart
} = payload;

const { cart, user } = getState();

const { cartId } = cart;
if (!cartId) {
throw new Error('Missing required information: cartId');
}

try {
const address = formatAddress(
payload.formValues,
payload.countries
);
const address = formatAddress(formValues, countries);

if (!user.isSignedIn) {
if (!formValues.email) {
throw new Error('Missing required information: email');
}
await setGuestEmail({
variables: {
cartId,
email: formValues.email
}
});
}

const {
firstname,
lastname,
street,
city,
region_code,
postcode,
telephone,
country_id
} = address;

const { data } = await setShippingAddressOnCart({
variables: {
cartId,
firstname,
lastname,
street,
city,
region_code,
postcode,
telephone,
country_id
}
});
// We can get the shipping methods immediately after setting the
// address. Grab it from the response and put it in the store.
const shippingMethods =
data.setShippingAddressesOnCart.cart.shipping_addresses[0]
.available_shipping_methods;

// On success, save to local storage.
await saveAvailableShippingMethods(shippingMethods);
await saveShippingAddress(address);

dispatch(actions.getShippingMethods.receive(shippingMethods));
dispatch(actions.shippingAddress.accept(address));
} catch (error) {
dispatch(actions.shippingAddress.reject(error));
Expand Down Expand Up @@ -351,6 +343,18 @@ export const formatAddress = (address = {}, countries = []) => {
};
};

async function clearAvailableShippingMethods() {
return storage.removeItem('availableShippingMethods');
}

async function retreiveAvailableShippingMethods() {
return storage.getItem('availableShippingMethods');
}

async function saveAvailableShippingMethods(methods) {
return storage.setItem('availableShippingMethods', methods);
}

async function clearBillingAddress() {
return storage.removeItem('billing_address');
}
Expand Down Expand Up @@ -404,4 +408,5 @@ export const clearCheckoutDataFromStorage = async () => {
await clearPaymentMethod();
await clearShippingAddress();
await clearShippingMethod();
await clearAvailableShippingMethods();
};
2 changes: 1 addition & 1 deletion packages/peregrine/lib/store/reducers/checkout.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const initialState = {
receipt: {
order: {}
},
shippingAddress: null,
shippingAddress: {},
shippingAddressError: null,
shippingMethod: '',
shippingMethodError: null,
Expand Down
Loading