-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathindex.jsx
More file actions
311 lines (279 loc) · 11.9 KB
/
Copy pathindex.jsx
File metadata and controls
311 lines (279 loc) · 11.9 KB
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
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import React, {useEffect, useState} from 'react'
import {
Alert,
AlertIcon,
Box,
Button,
Container,
Grid,
GridItem,
Stack
} from '@salesforce/retail-react-app/app/components/shared/ui'
import {FormattedMessage, useIntl} from 'react-intl'
import {useForm} from 'react-hook-form'
import {
useAuthHelper,
AuthHelpers,
useShopperBasketsMutation,
useShopperOrdersMutation
} from '@salesforce/commerce-sdk-react'
import {useToast} from '@salesforce/retail-react-app/app/hooks/use-toast'
import useNavigation from '@salesforce/retail-react-app/app/hooks/use-navigation'
import {useCheckout} from '@salesforce/retail-react-app/app/pages/checkout-container/util/checkout-context'
import ContactInfo from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-contact-info'
import PickupAddress from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-pickup-address'
import ShippingAddress from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-shipping-address'
import ShippingOptions from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-shipping-options'
import Payment from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-payment'
import OrderSummary from '@salesforce/retail-react-app/app/components/order-summary'
import {useCurrentBasket} from '@salesforce/retail-react-app/app/hooks/use-current-basket'
import {
API_ERROR_MESSAGE,
STORE_LOCATOR_IS_ENABLED
} from '@salesforce/retail-react-app/app/constants'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
import {
getPaymentInstrumentCardType,
getMaskCreditCardNumber
} from '@salesforce/retail-react-app/app/utils/cc-utils'
import {generatePassword} from '@salesforce/retail-react-app/app/utils/password-utils'
const CheckoutOneClick = () => {
const {formatMessage} = useIntl()
const navigate = useNavigation()
const {step} = useCheckout()
const [error] = useState()
const showToast = useToast()
const [isLoading, setIsLoading] = useState(false)
const [enableUserRegistration, setEnableUserRegistration] = useState(false)
const {data: basket} = useCurrentBasket()
const {passwordless = {}, social = {}} = getConfig().app.login || {}
const idps = social?.idps
const isSocialEnabled = !!social?.enabled
const isPasswordlessEnabled = !!passwordless?.enabled
// Only enable BOPIS functionality if the feature toggle is on
const isPickupOrder = STORE_LOCATOR_IS_ENABLED
? basket?.shipments[0]?.shippingMethod?.c_storePickupEnabled === true
: false
const selectedShippingAddress = basket?.shipments && basket?.shipments[0]?.shippingAddress
const selectedBillingAddress = basket?.billingAddress
const appliedPayment = basket?.paymentInstruments && basket?.paymentInstruments[0]
const {mutateAsync: addPaymentInstrumentToBasket} = useShopperBasketsMutation(
'addPaymentInstrumentToBasket'
)
const {mutateAsync: updateBillingAddressForBasket} = useShopperBasketsMutation(
'updateBillingAddressForBasket'
)
const {mutateAsync: createOrder} = useShopperOrdersMutation('createOrder')
const {mutateAsync: register} = useAuthHelper(AuthHelpers.Register)
const showError = (message) => {
showToast({
title: message || formatMessage(API_ERROR_MESSAGE),
status: 'error'
})
}
// Form for payment method
const paymentMethodForm = useForm()
// Form for billing address
const billingAddressForm = useForm({
mode: 'onChange',
shouldUnregister: false,
defaultValues: {...selectedBillingAddress}
})
const onPaymentSubmit = async (formValue) => {
// The form gives us the expiration date as `MM/YY` - so we need to split it into
// month and year to submit them as individual fields.
const [expirationMonth, expirationYear] = formValue.expiry.split('/')
const paymentInstrument = {
paymentMethodId: 'CREDIT_CARD',
paymentCard: {
holder: formValue.holder,
maskedNumber: getMaskCreditCardNumber(formValue.number),
cardType: getPaymentInstrumentCardType(formValue.cardType),
expirationMonth: parseInt(expirationMonth),
expirationYear: parseInt(`20${expirationYear}`)
}
}
return addPaymentInstrumentToBasket({
parameters: {basketId: basket?.basketId},
body: paymentInstrument
})
}
const onBillingSubmit = async () => {
const isFormValid = await billingAddressForm.trigger()
if (!isFormValid) {
return
}
// For one-click checkout, billing same as shipping by default
const billingSameAsShipping = !isPickupOrder
const billingAddress = billingSameAsShipping
? selectedShippingAddress
: billingAddressForm.getValues()
// Using destructuring to remove properties from the object...
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {addressId, creationDate, lastModified, preferred, ...address} = billingAddress
return await updateBillingAddressForBasket({
body: address,
parameters: {basketId: basket.basketId}
})
}
const submitOrder = async () => {
const registerUser = async (data) => {
try {
const body = {
customer: {
firstName: data.firstName,
lastName: data.lastName,
email: data.email,
login: data.email,
phoneHome: data.phoneHome
},
password: generatePassword()
}
await register(body)
showToast({
variant: 'subtle',
title: `${formatMessage(
{
defaultMessage: 'Welcome {name},',
id: 'auth_modal.info.welcome_user'
},
{
name: data.firstName || ''
}
)}`,
description: `${formatMessage({
defaultMessage: "You're now signed in.",
id: 'auth_modal.description.now_signed_in'
})}`,
status: 'success',
position: 'top-right',
isClosable: true
})
} catch (error) {
let message = formatMessage(API_ERROR_MESSAGE)
if (error.response) {
const json = await error.response.json()
if (/the login is already in use/i.test(json.detail)) {
message = formatMessage({
id: 'checkout_confirmation.message.already_has_account',
defaultMessage: 'This email already has an account.'
})
}
}
showError(message)
}
}
setIsLoading(true)
try {
const order = await createOrder({
body: {basketId: basket.basketId}
})
if (enableUserRegistration) {
await registerUser({
firstName: order.billingAddress.firstName,
lastName: order.billingAddress.lastName,
email: order.customerInfo.email,
phoneHome: order.billingAddress.phone
})
}
navigate(`/checkout/confirmation/${order.orderNo}`)
} catch (error) {
const message = formatMessage({
id: 'checkout.message.generic_error',
defaultMessage: 'An unexpected error occurred during checkout.'
})
showError(message)
} finally {
setIsLoading(false)
}
}
const onPlaceOrder = paymentMethodForm.handleSubmit(async (paymentFormValues) => {
try {
if (!appliedPayment) {
await onPaymentSubmit(paymentFormValues)
}
// If successful `onBillingSubmit` returns the updated basket. If the form was invalid on
// submit, `undefined` is returned.
const updatedBasket = await onBillingSubmit()
if (updatedBasket) {
await submitOrder()
}
} catch (error) {
showError()
}
})
useEffect(() => {
if (error || step === 4) {
window.scrollTo({top: 0})
}
}, [error, step])
return (
<Box background="gray.50" flex="1">
<Container
data-testid="sf-checkout-container"
maxWidth="container.xl"
py={{base: 7, lg: 16}}
px={{base: 0, lg: 8}}
>
<Grid templateColumns={{base: '1fr', lg: '66% 1fr'}} gap={{base: 10, xl: 20}}>
<GridItem>
<Stack spacing={4}>
{error && (
<Alert status="error" variant="left-accent">
<AlertIcon />
{error}
</Alert>
)}
<ContactInfo
isSocialEnabled={isSocialEnabled}
isPasswordlessEnabled={isPasswordlessEnabled}
idps={idps}
/>
{isPickupOrder ? <PickupAddress /> : <ShippingAddress />}
{!isPickupOrder && <ShippingOptions />}
<Payment
enableUserRegistration={enableUserRegistration}
setEnableUserRegistration={setEnableUserRegistration}
paymentMethodForm={paymentMethodForm}
billingAddressForm={billingAddressForm}
/>
{/* Place Order Button */}
<Box display="flex" bottom="0" px={4} pt={6} pb={11}>
<Container variant="form">
<Button
w="full"
onClick={onPlaceOrder}
isLoading={isLoading}
data-testid="place-order-button"
size="lg"
px={8}
minW="200px"
>
<FormattedMessage
defaultMessage="Place Order"
id="checkout_payment.button.place_order"
/>
</Button>
</Container>
</Box>
</Stack>
</GridItem>
<GridItem py={6} px={[4, 4, 4, 0]}>
<OrderSummary
basket={basket}
showTaxEstimationForm={false}
showCartItems={true}
/>
</GridItem>
</Grid>
</Container>
</Box>
)
}
export default CheckoutOneClick