-
Notifications
You must be signed in to change notification settings - Fork 69
/
checkout-page-save-user.js
392 lines (350 loc) · 10.5 KB
/
checkout-page-save-user.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/* eslint-disable max-len */
/* global jQuery */
/**
* External dependencies
*/
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { useDispatch, useSelect } from '@wordpress/data';
import { ValidationInputError } from '@woocommerce/blocks-checkout'; // eslint-disable-line import/no-unresolved
import {
VALIDATION_STORE_KEY,
CHECKOUT_STORE_KEY,
} from '@woocommerce/block-data'; // eslint-disable-line import/no-unresolved
/**
* Internal dependencies
*/
import PhoneNumberInput from 'settings/phone-input';
import { getConfig } from 'utils/checkout';
import { buildAjaxURL } from 'utils/express-checkout';
import AdditionalInformation from './additional-information';
import Agreement from './agreement';
import Container from './container';
import useWooPayUser from '../hooks/use-woopay-user';
import request from '../../../checkout/utils/request';
import useSelectedPaymentMethod from '../hooks/use-selected-payment-method';
import { recordUserEvent } from 'tracks';
import './style.scss';
const CheckoutPageSaveUser = ( { isBlocksCheckout } ) => {
const errorId = 'invalid-woopay-phone-number';
const { setValidationErrors, clearValidationError } = useDispatch(
VALIDATION_STORE_KEY
);
const [ isSaveDetailsChecked, setIsSaveDetailsChecked ] = useState(
window.woopayCheckout?.PRE_CHECK_SAVE_MY_INFO || false
);
const [ phoneNumber, setPhoneNumber ] = useState( '' );
const [ isPhoneValid, onPhoneValidationChange ] = useState( null );
const [ userDataSent, setUserDataSent ] = useState( false );
const isPhoneNumberTouched = useRef( false );
const checkoutIsProcessing = useSelect( ( select ) =>
select( CHECKOUT_STORE_KEY ).isProcessing()
);
const isBillingSameAsShipping = useSelect( ( select ) =>
select( CHECKOUT_STORE_KEY ).getUseShippingAsBilling()
);
const isRegisteredUser = useWooPayUser();
const { isWCPayChosen, isNewPaymentTokenChosen } = useSelectedPaymentMethod(
isBlocksCheckout
);
const viewportWidth = window.document.documentElement.clientWidth;
const viewportHeight = window.document.documentElement.clientHeight;
useEffect( () => {
if ( ! isBlocksCheckout ) {
return;
}
const rememberMe = document.querySelector( '#remember-me' );
if ( ! rememberMe ) {
return;
}
if ( checkoutIsProcessing ) {
rememberMe.classList.add(
'wc-block-components-checkout-step--disabled'
);
rememberMe.setAttribute( 'disabled', 'disabled' );
return;
}
rememberMe.classList.remove(
'wc-block-components-checkout-step--disabled'
);
rememberMe.removeAttribute( 'disabled', 'disabled' );
}, [ checkoutIsProcessing, isBlocksCheckout ] );
const getPhoneFieldValue = useCallback( () => {
let phoneFieldValue = '';
if ( isBlocksCheckout ) {
phoneFieldValue =
document.getElementById( 'phone' )?.value ||
document.getElementById( 'billing-phone' )?.value ||
document.getElementById( 'shipping-phone' )?.value ||
'';
} else {
// for classic checkout.
phoneFieldValue =
document.getElementById( 'billing_phone' )?.value || '';
}
// Take out any non-digit characters, except +.
phoneFieldValue = phoneFieldValue.replace( /[^\d+]*/g, '' );
if ( ! phoneFieldValue.startsWith( '+' ) ) {
phoneFieldValue = '+1' + phoneFieldValue;
}
return phoneFieldValue;
}, [ isBlocksCheckout ] );
const sendExtensionData = useCallback(
( shouldClearData = false ) => {
const data = shouldClearData
? { empty: 1 }
: {
save_user_in_woopay: isSaveDetailsChecked ? 1 : 0,
woopay_source_url:
wcSettings?.storePages?.checkout?.permalink,
woopay_is_blocks: 1,
woopay_viewport: `${ viewportWidth }x${ viewportHeight }`,
woopay_user_phone_field: {
full: phoneNumber,
},
};
request(
buildAjaxURL(
getConfig( 'wcAjaxUrl' ),
'set_woopay_phone_number'
),
{
_ajax_nonce: getConfig( 'woopaySessionNonce' ),
...data,
}
).then( () => {
setUserDataSent( ! shouldClearData );
} );
},
[ isSaveDetailsChecked, phoneNumber, viewportWidth, viewportHeight ]
);
const handleCountryDropdownClick = useCallback( () => {
recordUserEvent( 'checkout_woopay_save_my_info_country_click' );
}, [] );
const handleCheckboxClick = ( e ) => {
const isChecked = e.target.checked;
if ( isChecked ) {
setPhoneNumber( getPhoneFieldValue() );
} else {
setPhoneNumber( '' );
if ( isBlocksCheckout ) {
sendExtensionData( true );
}
}
setIsSaveDetailsChecked( isChecked );
recordUserEvent( 'checkout_save_my_info_click', {
status: isChecked ? 'checked' : 'unchecked',
} );
};
useEffect( () => {
// Record Tracks event when the mobile number is entered.
if ( isPhoneValid ) {
recordUserEvent( 'checkout_woopay_save_my_info_mobile_enter' );
}
}, [ isPhoneValid ] );
useEffect( () => {
const checkoutForm = jQuery( 'form.woocommerce-checkout' );
checkoutForm.on( 'checkout_place_order', function () {
jQuery( '#validate-error-invalid-woopay-phone-number' ).show();
} );
}, [] );
useEffect( () => {
if ( ! isSaveDetailsChecked ) {
clearValidationError( errorId );
if ( isPhoneValid !== null ) {
onPhoneValidationChange( null );
}
return;
}
if ( isSaveDetailsChecked && isPhoneValid ) {
clearValidationError( errorId );
// Set extension data if checkbox is selected and phone number is valid in blocks checkout.
if ( isBlocksCheckout ) {
sendExtensionData( false );
}
return;
}
if ( isSaveDetailsChecked && ! isPhoneValid ) {
setValidationErrors( {
[ errorId ]: {
message: __(
'Please enter a valid mobile phone number.',
'woocommerce-payments'
),
// Hides errors when the number has not been typed yet but shows when trying to place the order.
hidden: isPhoneValid === null,
},
} );
}
}, [
clearValidationError,
isBlocksCheckout,
isPhoneValid,
isSaveDetailsChecked,
sendExtensionData,
setValidationErrors,
] );
// In classic checkout the saved tokens are under WCPay, so we need to check if new token is selected or not,
// under WCPay. For blocks checkout considering isWCPayChosen is enough.
const isWCPayWithNewTokenChosen = isBlocksCheckout
? isWCPayChosen
: isWCPayChosen && isNewPaymentTokenChosen;
const updatePhoneNumber = useCallback( () => {
if ( isPhoneNumberTouched.current ) {
return;
}
setPhoneNumber( getPhoneFieldValue() );
}, [ setPhoneNumber, getPhoneFieldValue, isPhoneNumberTouched ] );
useEffect( () => {
updatePhoneNumber();
}, [ updatePhoneNumber ] );
// Update the WooPay phone number on the phone field blur event.
useEffect( () => {
if ( ! isBlocksCheckout ) {
document
.querySelector( '#billing_phone' )
?.addEventListener( 'blur', updatePhoneNumber );
return;
}
updatePhoneNumber();
if ( isBillingSameAsShipping ) {
document
.querySelector( '#billing-phone' )
?.removeEventListener( 'blur', updatePhoneNumber );
document
.querySelector( '#shipping-phone' )
?.addEventListener( 'blur', updatePhoneNumber );
return;
}
document
.querySelector( '#shipping-phone' )
?.removeEventListener( 'blur', updatePhoneNumber );
document
.querySelector( '#billing-phone' )
?.addEventListener( 'blur', updatePhoneNumber );
}, [
isBillingSameAsShipping,
updatePhoneNumber,
isPhoneNumberTouched,
getPhoneFieldValue,
isBlocksCheckout,
] );
if (
! getConfig( 'forceNetworkSavedCards' ) ||
! isWCPayWithNewTokenChosen ||
isRegisteredUser
) {
// Clicking the place order button sets the extension data in backend. If user changes the payment method
// due to an error, we need to clear the extension data in backend.
if ( isBlocksCheckout && userDataSent ) {
sendExtensionData( true );
}
clearValidationError( errorId );
return null;
}
return (
<Container isBlocksCheckout={ isBlocksCheckout }>
<div className="save-details">
<div className="save-details-header">
<div
className={
isBlocksCheckout
? 'wc-block-components-checkbox'
: ''
}
>
<label htmlFor="save_user_in_woopay">
<input
type="checkbox"
checked={ isSaveDetailsChecked }
onChange={ handleCheckboxClick }
name="save_user_in_woopay"
id="save_user_in_woopay"
value="true"
className={ `save-details-checkbox without-margin-right ${
isBlocksCheckout
? 'wc-block-components-checkbox__input'
: ''
}` }
aria-checked={ isSaveDetailsChecked }
/>
{ isBlocksCheckout && (
<svg
className="wc-block-components-checkbox__mark"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 20"
>
<path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" />
</svg>
) }
<span className="wc-block-components-checkbox__label">
{ __(
'Securely save my information for 1-click checkout',
'woocommerce-payments'
) }
</span>
</label>
</div>
</div>
{ isSaveDetailsChecked && (
<div
className="save-details-form form-row"
data-testid="save-user-form"
>
<input
type="hidden"
name="woopay_source_url"
value={
wcSettings?.storePages?.checkout?.permalink
}
/>
<input
type="hidden"
name="woopay_viewport"
value={ `${ viewportWidth }x${ viewportHeight }` }
/>
<div className={ isPhoneValid ? '' : 'has-error' }>
<PhoneNumberInput
value={ phoneNumber }
onValueChange={ setPhoneNumber }
onValidationChange={ onPhoneValidationChange }
onCountryDropdownClick={
handleCountryDropdownClick
}
onClick={ () =>
( isPhoneNumberTouched.current = true )
}
inputProps={ {
name:
'woopay_user_phone_field[no-country-code]',
} }
isBlocksCheckout={ isBlocksCheckout }
/>
</div>
{ isBlocksCheckout && (
<ValidationInputError
elementId={ errorId }
propertyName={ errorId }
/>
) }
{ ! isBlocksCheckout && ! isPhoneValid && (
<p
id="validate-error-invalid-woopay-phone-number"
hidden={ isPhoneValid !== false }
>
{ __(
'Please enter a valid mobile phone number.',
'woocommerce-payments'
) }
</p>
) }
<AdditionalInformation />
<Agreement />
</div>
) }
</div>
</Container>
);
};
export default CheckoutPageSaveUser;