-
Notifications
You must be signed in to change notification settings - Fork 288
/
CheckoutActions.js
353 lines (311 loc) · 11.2 KB
/
CheckoutActions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/* eslint-disable react/no-multi-comp */
import React, { Fragment, Component } from "react";
import PropTypes from "prop-types";
import { isEqual } from "lodash";
import styled from "styled-components";
import Actions from "@reactioncommerce/components/CheckoutActions/v1";
import ShippingAddressCheckoutAction from "@reactioncommerce/components/ShippingAddressCheckoutAction/v1";
import FulfillmentOptionsCheckoutAction from "@reactioncommerce/components/FulfillmentOptionsCheckoutAction/v1";
import PaymentsCheckoutAction from "@reactioncommerce/components/PaymentsCheckoutAction/v1";
import FinalReviewCheckoutAction from "@reactioncommerce/components/FinalReviewCheckoutAction/v1";
import { addTypographyStyles } from "@reactioncommerce/components/utils";
import withAddressValidation from "containers/address/withAddressValidation";
import Dialog from "@material-ui/core/Dialog";
import PageLoading from "components/PageLoading";
import Router from "translations/i18nRouter";
import calculateRemainderDue from "lib/utils/calculateRemainderDue";
import { placeOrderMutation } from "../../hooks/orders/placeOrder.gql";
const MessageDiv = styled.div`
${addTypographyStyles("NoPaymentMethodsMessage", "bodyText")}
`;
const NoPaymentMethodsMessage = () => <MessageDiv>No payment methods available</MessageDiv>;
NoPaymentMethodsMessage.renderComplete = () => "";
class CheckoutActions extends Component {
static propTypes = {
addressValidation: PropTypes.func.isRequired,
addressValidationResults: PropTypes.object,
apolloClient: PropTypes.shape({
mutate: PropTypes.func.isRequired
}),
cart: PropTypes.shape({
account: PropTypes.object,
checkout: PropTypes.object,
email: PropTypes.string,
items: PropTypes.array
}).isRequired,
cartStore: PropTypes.object,
checkoutMutations: PropTypes.shape({
onSetFulfillmentOption: PropTypes.func.isRequired,
onSetShippingAddress: PropTypes.func.isRequired
}),
clearAuthenticatedUsersCart: PropTypes.func.isRequired,
orderEmailAddress: PropTypes.string.isRequired,
paymentMethods: PropTypes.array
};
state = {
actionAlerts: {
1: null,
2: null,
3: null,
4: null
},
hasPaymentError: false,
isPlacingOrder: false
};
componentDidUpdate({ addressValidationResults: prevAddressValidationResults }) {
const { addressValidationResults } = this.props;
if (
addressValidationResults &&
prevAddressValidationResults &&
!isEqual(addressValidationResults, prevAddressValidationResults)
) {
this.handleValidationErrors();
}
}
componentWillUnmount() {
this._isMounted = false;
}
buildData = ({ step, action }) => ({
action,
payment_method: this.paymentMethod, // eslint-disable-line camelcase
shipping_method: this.shippingMethod, // eslint-disable-line camelcase
step
});
get shippingMethod() {
const { checkout: { fulfillmentGroups } } = this.props.cart;
const { selectedFulfillmentOption } = fulfillmentGroups[0];
return selectedFulfillmentOption ? selectedFulfillmentOption.fulfillmentMethod.displayName : null;
}
get paymentMethod() {
const [firstPayment] = this.props.cartStore.checkoutPayments;
return firstPayment ? firstPayment.payment.method : null;
}
setShippingAddress = async (address) => {
const { checkoutMutations: { onSetShippingAddress } } = this.props;
delete address.isValid;
const { data, error } = await onSetShippingAddress(address);
if (data && !error && this._isMounted) {
this.setState({
actionAlerts: {
1: {}
}
});
}
};
handleValidationErrors() {
const { addressValidationResults } = this.props;
const { validationErrors } = addressValidationResults || [];
const shippingAlert =
validationErrors && validationErrors.length ? {
alertType: validationErrors[0].type,
title: validationErrors[0].summary,
message: validationErrors[0].details
} : null;
this.setState({ actionAlerts: { 1: shippingAlert } });
}
setShippingMethod = async (shippingMethod) => {
const { checkoutMutations: { onSetFulfillmentOption } } = this.props;
const { checkout: { fulfillmentGroups } } = this.props.cart;
const fulfillmentOption = {
fulfillmentGroupId: fulfillmentGroups[0]._id,
fulfillmentMethodId: shippingMethod.selectedFulfillmentOption.fulfillmentMethod._id
};
await onSetFulfillmentOption(fulfillmentOption);
};
handlePaymentSubmit = (paymentInput) => {
this.props.cartStore.addCheckoutPayment(paymentInput);
this.setState({
hasPaymentError: false,
actionAlerts: {
3: {}
}
});
};
handlePaymentsReset = () => {
this.props.cartStore.resetCheckoutPayments();
}
buildOrder = async () => {
const { cart, cartStore, orderEmailAddress } = this.props;
const cartId = cartStore.hasAccountCart ? cartStore.accountCartId : cartStore.anonymousCartId;
const { checkout } = cart;
const fulfillmentGroups = checkout.fulfillmentGroups.map((group) => {
const { data } = group;
const { selectedFulfillmentOption } = group;
const items = cart.items.map((item) => ({
addedAt: item.addedAt,
price: item.price.amount,
productConfiguration: item.productConfiguration,
quantity: item.quantity
}));
return {
data,
items,
selectedFulfillmentMethodId: selectedFulfillmentOption.fulfillmentMethod._id,
shopId: group.shop._id,
totalPrice: checkout.summary.total.amount,
type: group.type
};
});
const order = {
cartId,
currencyCode: checkout.summary.total.currency.code,
email: orderEmailAddress,
fulfillmentGroups,
shopId: cart.shop._id
};
return this.setState({ isPlacingOrder: true }, () => this.placeOrder(order));
};
placeOrder = async (order) => {
const { cartStore, clearAuthenticatedUsersCart, apolloClient } = this.props;
// Payments can have `null` amount to mean "remaining".
let remainingAmountDue = order.fulfillmentGroups.reduce((sum, group) => sum + group.totalPrice, 0);
const payments = cartStore.checkoutPayments.map(({ payment }) => {
const amount = payment.amount ? Math.min(payment.amount, remainingAmountDue) : remainingAmountDue;
remainingAmountDue -= amount;
return { ...payment, amount };
});
try {
const { data } = await apolloClient.mutate({
mutation: placeOrderMutation,
variables: {
input: {
order,
payments
}
}
});
// Placing the order was successful, so we should clear the
// anonymous cart credentials from cookie since it will be
// deleted on the server.
cartStore.clearAnonymousCartCredentials();
clearAuthenticatedUsersCart();
// Also destroy the collected and cached payment input
cartStore.resetCheckoutPayments();
const { placeOrder: { orders, token } } = data;
// Send user to order confirmation page
Router.push(`/checkout/order?orderId=${orders[0].referenceId}${token ? `&token=${token}` : ""}`);
} catch (error) {
if (this._isMounted) {
this.setState({
hasPaymentError: true,
isPlacingOrder: false,
actionAlerts: {
3: {
alertType: "error",
title: "Payment method failed",
message: error.toString().replace("Error: GraphQL error:", "")
}
}
});
}
}
};
renderPlacingOrderOverlay = () => {
const { isPlacingOrder } = this.state;
return (
<Dialog fullScreen disableBackdropClick={true} disableEscapeKeyDown={true} open={isPlacingOrder}>
<PageLoading delay={0} message="Placing your order..." />
</Dialog>
);
};
render() {
const {
addressValidation,
addressValidationResults,
cart,
cartStore,
paymentMethods
} = this.props;
const { checkout: { fulfillmentGroups, summary }, items } = cart;
const { actionAlerts, hasPaymentError } = this.state;
const [fulfillmentGroup] = fulfillmentGroups;
// Order summary
const { fulfillmentTotal, itemTotal, surchargeTotal, taxTotal, total } = summary;
const checkoutSummary = {
displayShipping: fulfillmentTotal && fulfillmentTotal.displayAmount,
displaySubtotal: itemTotal.displayAmount,
displaySurcharge: surchargeTotal.displayAmount,
displayTotal: total.displayAmount,
displayTax: taxTotal && taxTotal.displayAmount,
items
};
const addresses = fulfillmentGroups.reduce((list, group) => {
if (group.shippingAddress) list.push(group.shippingAddress);
return list;
}, []);
const payments = cartStore.checkoutPayments.slice();
const remainingAmountDue = calculateRemainderDue(payments, total.amount);
let PaymentComponent = PaymentsCheckoutAction;
if (!Array.isArray(paymentMethods) || paymentMethods.length === 0) {
PaymentComponent = NoPaymentMethodsMessage;
}
const actions = [
{
id: "1",
activeLabel: "Enter a shipping address",
completeLabel: "Shipping address",
incompleteLabel: "Shipping address",
status: fulfillmentGroup.type !== "shipping" || fulfillmentGroup.shippingAddress ? "complete" : "incomplete",
component: ShippingAddressCheckoutAction,
onSubmit: this.setShippingAddress,
props: {
addressValidationResults,
alert: actionAlerts["1"],
fulfillmentGroup,
onAddressValidation: addressValidation
}
},
{
id: "2",
activeLabel: "Choose a shipping method",
completeLabel: "Shipping method",
incompleteLabel: "Shipping method",
status: fulfillmentGroup.selectedFulfillmentOption ? "complete" : "incomplete",
component: FulfillmentOptionsCheckoutAction,
onSubmit: this.setShippingMethod,
props: {
alert: actionAlerts["2"],
fulfillmentGroup
}
},
{
id: "3",
activeLabel: "Enter payment information",
completeLabel: "Payment information",
incompleteLabel: "Payment information",
status: remainingAmountDue === 0 && !hasPaymentError ? "complete" : "incomplete",
component: PaymentComponent,
onSubmit: this.handlePaymentSubmit,
props: {
addresses,
alert: actionAlerts["3"],
onReset: this.handlePaymentsReset,
payments,
paymentMethods,
remainingAmountDue
}
},
{
id: "4",
activeLabel: "Review and place order",
completeLabel: "Review and place order",
incompleteLabel: "Review and place order",
status: "incomplete",
component: FinalReviewCheckoutAction,
onSubmit: this.buildOrder,
props: {
alert: actionAlerts["4"],
checkoutSummary,
productURLPath: "/api/detectLanguage/product/"
}
}
];
return (
<Fragment>
{this.renderPlacingOrderOverlay()}
<Actions actions={actions} />
</Fragment>
);
}
}
export default withAddressValidation(CheckoutActions);