-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ebanx-tef.js
432 lines (394 loc) · 11.8 KB
/
ebanx-tef.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
* External dependencies
*/
import React from 'react';
import styled from '@emotion/styled';
import debugFactory from 'debug';
import { sprintf } from '@wordpress/i18n';
import { useI18n } from '@automattic/react-i18n';
import {
Button,
FormStatus,
useLineItems,
useFormStatus,
registerStore,
useSelect,
useDispatch,
} from '@automattic/composite-checkout';
import { camelCase } from 'lodash';
import { useDispatch as useReduxDispatch } from 'react-redux';
/**
* Internal dependencies
*/
import { errorNotice } from 'calypso/state/notices/actions';
import { validatePaymentDetails } from 'calypso/lib/checkout/validation';
import useCountryList from 'calypso/my-sites/checkout/composite-checkout/hooks/use-country-list';
import Field from 'calypso/my-sites/checkout/composite-checkout/components/field';
import {
SummaryLine,
SummaryDetails,
} from 'calypso/my-sites/checkout/composite-checkout/components/summary-details';
import { PaymentMethodLogos } from 'calypso/my-sites/checkout/composite-checkout/components/payment-method-logos';
import { maskField } from 'calypso/lib/checkout';
import CountrySpecificPaymentFields from '../components/country-specific-payment-fields';
const debug = debugFactory( 'composite-checkout:ebanx-tef-payment-method' );
export function createEbanxTefPaymentMethodStore() {
debug( 'creating a new ebanx-tef payment method store' );
const actions = {
changeCustomerName( payload ) {
return { type: 'CUSTOMER_NAME_SET', payload };
},
changeCustomerBank( payload ) {
return { type: 'CUSTOMER_BANK_SET', payload };
},
setFieldValue( key, value ) {
return { type: 'FIELD_VALUE_SET', payload: { key, value } };
},
setFieldError( key, message ) {
return { type: 'FIELD_ERROR_SET', payload: { key, message } };
},
touchAllFields() {
return { type: 'TOUCH_ALL_FIELDS' };
},
};
const selectors = {
getCustomerName( state ) {
return state.customerName;
},
getCustomerBank( state ) {
return state.customerBank;
},
getFields( state ) {
return state.fields;
},
};
const store = registerStore( 'ebanx-tef', {
reducer(
state = {
customerName: { value: '', isTouched: false },
customerBank: { value: '', isTouched: false },
fields: {},
},
action
) {
switch ( action.type ) {
case 'CUSTOMER_NAME_SET':
return { ...state, customerName: { value: action.payload, isTouched: true } };
case 'CUSTOMER_BANK_SET':
return { ...state, customerBank: { value: action.payload, isTouched: true } };
case 'FIELD_VALUE_SET':
return {
...state,
fields: {
...state.fields,
[ action.payload.key ]: {
value: maskField(
action.payload.key,
state.fields[ action.payload.key ],
action.payload.value
),
isTouched: true,
errors: [],
},
},
};
case 'FIELD_ERROR_SET':
return {
...state,
fields: {
...state.fields,
[ action.payload.key ]: {
...state.fields[ action.payload.key ],
errors: [ action.payload.message ],
},
},
};
case 'TOUCH_ALL_FIELDS':
return {
...state,
fields: Object.keys( state.fields ).reduce(
( obj, key ) => ( {
...obj,
[ key ]: {
...state.fields[ key ],
isTouched: true,
},
} ),
{}
),
};
}
return state;
},
actions,
selectors,
} );
return { ...store, actions, selectors };
}
export function createEbanxTefMethod( { store } ) {
return {
id: 'brazil-tef',
label: <EbanxTefLabel />,
activeContent: <EbanxTefFields />,
submitButton: <EbanxTefPayButton store={ store } />,
inactiveContent: <EbanxTefSummary />,
getAriaLabel: () => 'Transferência bancária',
};
}
function EbanxTefFields() {
const { __ } = useI18n();
const fields = useSelect( ( select ) => select( 'ebanx-tef' ).getFields() );
const getField = ( key ) => fields[ key ] || {};
const getFieldValue = ( key ) => getField( key ).value ?? '';
const getErrorMessagesForField = ( key ) => {
const managedValue = getField( key );
if ( managedValue?.isRequired && managedValue?.value === '' ) {
return [ __( 'This field is required.' ) ];
}
return managedValue.errors ?? [];
};
const { setFieldValue } = useDispatch( 'ebanx-tef' );
const customerName = useSelect( ( select ) => select( 'ebanx-tef' ).getCustomerName() );
const customerBank = useSelect( ( select ) => select( 'ebanx-tef' ).getCustomerBank() );
const { changeCustomerName, changeCustomerBank } = useDispatch( 'ebanx-tef' );
const { formStatus } = useFormStatus();
const isDisabled = formStatus !== FormStatus.READY;
const countriesList = useCountryList( [] );
return (
<EbanxTefFormWrapper>
<EbanxTefField
id="ebanx-tef-cardholder-name"
type="Text"
autoComplete="cc-name"
label={ __( 'Your name' ) }
value={ customerName?.value ?? '' }
onChange={ changeCustomerName }
isError={ customerName?.isTouched && customerName?.value.length === 0 }
errorMessage={ __( 'This field is required' ) }
disabled={ isDisabled }
/>
<BankSelector
id="ebanx-tef-bank-selector"
value={ customerBank?.value ?? '' }
onChange={ changeCustomerBank }
label={ __( 'Bank' ) }
isError={ customerBank?.isTouched && customerBank?.value.length === 0 }
errorMessage={ __( 'This field is required' ) }
disabled={ isDisabled }
/>
<div className="ebanx-tef__contact-fields">
<CountrySpecificPaymentFields
countryCode={ 'BR' } // If this payment method is available and the country is not Brazil, we have other problems
countriesList={ countriesList }
getErrorMessage={ getErrorMessagesForField }
getFieldValue={ getFieldValue }
handleFieldChange={ setFieldValue }
disableFields={ isDisabled }
/>
</div>
</EbanxTefFormWrapper>
);
}
function BankSelector( { id, value, onChange, label, isError, errorMessage, disabled } ) {
const { __ } = useI18n();
const bankOptions = getBankOptions( __ );
return (
<SelectWrapper>
<label htmlFor={ id } disabled={ disabled }>
{ label }
</label>
<select
id={ id }
value={ value }
onChange={ ( event ) => onChange( event.target.value ) }
disabled={ disabled }
>
{ bankOptions.map( ( bank ) => (
<BankOption key={ bank.value } value={ bank.value } label={ bank.label } />
) ) }
</select>
<ErrorMessage isError={ isError } errorMessage={ errorMessage } />
</SelectWrapper>
);
}
function BankOption( { value, label } ) {
return <option value={ value }>{ label }</option>;
}
function ErrorMessage( { isError, errorMessage } ) {
if ( isError ) {
return <Description isError={ isError }>{ errorMessage }</Description>;
}
return null;
}
const Description = styled.p`
margin: 8px 0 0;
color: ${ ( props ) =>
props.isError ? props.theme.colors.error : props.theme.colors.textColorLight };
font-style: italic;
font-size: 14px;
`;
const EbanxTefFormWrapper = styled.div`
padding: 16px;
position: relative;
::after {
display: block;
width: calc( 100% - 6px );
height: 1px;
content: '';
background: ${ ( props ) => props.theme.colors.borderColorLight };
position: absolute;
top: 0;
left: 3px;
.rtl & {
right: 3px;
left: auto;
}
}
`;
const EbanxTefField = styled( Field )`
margin-top: 16px;
:first-of-type {
margin-top: 0;
}
`;
const SelectWrapper = styled.div`
margin-top: 16px;
select {
width: 100%;
}
`;
function EbanxTefPayButton( { disabled, onClick, store } ) {
const { __ } = useI18n();
const [ items, total ] = useLineItems();
const { formStatus } = useFormStatus();
const customerName = useSelect( ( select ) => select( 'ebanx-tef' ).getCustomerName() );
const customerBank = useSelect( ( select ) => select( 'ebanx-tef' ).getCustomerBank() );
const fields = useSelect( ( select ) => select( 'ebanx-tef' ).getFields() );
const massagedFields = Object.entries( fields ).reduce(
( accum, [ key, managedValue ] ) => ( { ...accum, [ camelCase( key ) ]: managedValue.value } ),
{}
);
const contactCountryCode = useSelect(
( select ) => select( 'wpcom' )?.getContactInfo().countryCode?.value
);
const reduxDispatch = useReduxDispatch();
return (
<Button
disabled={ disabled }
onClick={ () => {
if ( isFormValid( store, contactCountryCode, __, reduxDispatch ) ) {
debug( 'submitting ebanx-tef payment' );
onClick( 'ebanx-tef', {
...massagedFields,
name: customerName?.value, // this needs to come after massagedFields to prevent it from being overridden
address: massagedFields?.address1,
tefBank: customerBank?.value,
items,
total,
} );
}
} }
buttonType="primary"
isBusy={ FormStatus.SUBMITTING === formStatus }
fullWidth
>
<ButtonContents formStatus={ formStatus } total={ total } />
</Button>
);
}
function ButtonContents( { formStatus, total } ) {
const { __ } = useI18n();
if ( formStatus === FormStatus.SUBMITTING ) {
return __( 'Processing…' );
}
if ( formStatus === FormStatus.READY ) {
/* translators: %s is the total to be paid in localized currency */
return sprintf( __( 'Pay %s' ), total.amount.displayValue );
}
return __( 'Please wait…' );
}
function EbanxTefSummary() {
const customerName = useSelect( ( select ) => select( 'ebanx-tef' ).getCustomerName() );
const customerBank = useSelect( ( select ) => select( 'ebanx-tef' ).getCustomerBank() );
return (
<SummaryDetails>
<SummaryLine>{ customerName?.value }</SummaryLine>
<SummaryLine>{ customerBank?.value }</SummaryLine>
</SummaryDetails>
);
}
function isFormValid( store, contactCountryCode, __, reduxDispatch ) {
// Touch fields so that we show errors
store.dispatch( store.actions.touchAllFields() );
let isValid = true;
const customerName = store.selectors.getCustomerName( store.getState() );
const customerBank = store.selectors.getCustomerBank( store.getState() );
if ( ! customerName?.value.length ) {
// Touch the field so it displays a validation error
store.dispatch( store.actions.changeCustomerName( '' ) );
isValid = false;
}
if ( ! customerBank?.value.length ) {
// Touch the field so it displays a validation error
store.dispatch( store.actions.changeCustomerBank( '' ) );
isValid = false;
}
const rawState = store.selectors.getFields( store.getState() );
const validationResults = validatePaymentDetails(
Object.entries( {
...rawState,
country: { value: contactCountryCode },
name: customerName,
'tef-bank': customerBank,
} ).reduce( ( accum, [ key, managedValue ] ) => {
accum[ key ] = managedValue.value;
return accum;
}, {} ),
'brazil-tef'
);
Object.entries( validationResults.errors ).map( ( [ key, errors ] ) => {
errors.map( ( error ) => {
isValid = false;
store.dispatch( store.actions.setFieldError( key, error ) );
} );
} );
debug( 'ebanx card details validation results: ', validationResults );
if ( validationResults.errors?.country?.length > 0 ) {
const countryErrorMessage = validationResults.errors.country[ 0 ];
reduxDispatch(
errorNotice( countryErrorMessage || __( 'An error occurred during your purchase.' ) )
);
}
return isValid;
}
function EbanxTefLabel() {
return (
<React.Fragment>
<span>{ 'Transferência bancária' }</span>
<PaymentMethodLogos className="ebanx-tef__logo payment-logos">
<EbanxTefLogo />
</PaymentMethodLogos>
</React.Fragment>
);
}
const EbanxTefLogo = styled( EbanxTefLogoImg )`
width: 76px;
`;
function EbanxTefLogoImg( { className } ) {
return (
<img
src="/calypso/images/upgrades/brazil-tef.svg"
alt="Transferência bancária"
className={ className }
/>
);
}
function getBankOptions( __ ) {
const banks = [
{ value: 'banrisul', label: 'Banrisul' },
{ value: 'bradesco', label: 'Bradesco' },
{ value: 'bancodobrasil', label: 'Banco do Brasil' },
{ value: 'itau', label: 'Itaú' },
];
return [ { value: '', label: __( 'Please select your bank.' ) }, ...banks ];
}