Skip to content

Commit

Permalink
Partial Feature: PayID into PayTo component branch (#3069)
Browse files Browse the repository at this point in the history
* adds PayTo component shell

* payto segmented controller

* add support to second description

* adds email and refactor identifier to enum

* adds pay input fields, starts validation

* fix validator

* splits PhoneInput and passes state to PayTo

* tests and PR comments

* fix tests
  • Loading branch information
m1aw authored Jan 10, 2025
1 parent 03ef141 commit df83f04
Show file tree
Hide file tree
Showing 35 changed files with 1,015 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ function AchInput(props: ACHInputProps) {
props.onChange({ data, isValid, storePaymentMethod });
}, [data, valid, errors, storePaymentMethod]);

console.log('ach props 2', props);

return (
<div className="adyen-checkout__ach">
<FormInstruction />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useState, useRef } from 'preact/hooks';
import { useCoreContext } from '../../../../core/Context/CoreProvider';
import { MBWayInputProps } from './types';
import './MBWayInput.scss';
import PhoneInput from '../../../internal/PhoneInput';
import PhoneInputForm from '../../../internal/PhoneInput';
import LoadingWrapper from '../../../internal/LoadingWrapper';
import usePhonePrefixes from '../../../internal/PhoneInput/usePhonePrefixes';

Expand All @@ -28,7 +28,7 @@ function MBWayInput(props: MBWayInputProps) {
return (
<LoadingWrapper status={prefixLoadingStatus}>
<div className="adyen-checkout__mb-way">
<PhoneInput {...props} items={phonePrefixes} ref={phoneInputRef} onChange={onChange} data={props.data} />
<PhoneInputForm {...props} items={phonePrefixes} ref={phoneInputRef} onChange={onChange} data={props.data} />

{props.showPayButton && props.payButton({ status, label: i18n.get('confirmPurchase') })}
</div>
Expand Down
72 changes: 72 additions & 0 deletions packages/lib/src/components/PayTo/PayTo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { render, screen } from '@testing-library/preact';
import PayTo from './PayTo';
import userEvent from '@testing-library/user-event';
import getDataset from '../../core/Services/get-dataset';

jest.mock('../../core/Services/get-dataset');
(getDataset as jest.Mock).mockImplementation(
jest.fn(() => {
return Promise.resolve([{ id: 'AUS', prefix: '+61' }]);
})
);

describe('PayTo', () => {
let onSubmitMock;
let user;

beforeEach(() => {
onSubmitMock = jest.fn();
user = userEvent.setup();
});

test('should render payment and show PayID page', async () => {
const payTo = new PayTo(global.core, {
i18n: global.i18n,
loadingContext: 'test',
modules: { resources: global.resources }
});

render(payTo.render());
expect(await screen.findByText(/Enter the PayID and account details that are connected to your Payto account./i)).toBeTruthy();
expect(await screen.findByLabelText(/Prefix/i)).toBeTruthy();
expect(await screen.findByLabelText(/Mobile number/i)).toBeTruthy();
expect(await screen.findByLabelText(/First name/i)).toBeTruthy();
expect(await screen.findByLabelText(/Last name/i)).toBeTruthy();
});

test('should render continue button', async () => {
const payTo = new PayTo(global.core, {
onSubmit: onSubmitMock,
i18n: global.i18n,
loadingContext: 'test',
modules: { resources: global.resources }
});

render(payTo.render());
const button = await screen.findByRole('button', { name: 'Confirm purchase' });

// check if button actually triggers submit
await user.click(button);
expect(onSubmitMock).toHaveBeenCalledTimes(0);

//TODO check validation fails
});

test('should change to different identifier when selected', async () => {
const payTo = new PayTo(global.core, {
onSubmit: onSubmitMock,
i18n: global.i18n,
loadingContext: 'test',
modules: { resources: global.resources },
showPayButton: false
});

render(payTo.render());

await user.click(screen.queryByRole('button', { name: 'Mobile' }));
await user.click(screen.queryByRole('option', { name: /Email/i }));

expect(screen.queryByLabelText(/Prefix/i)).toBeFalsy();
expect(screen.getByLabelText(/Email/i)).toBeTruthy();
});
});
135 changes: 135 additions & 0 deletions packages/lib/src/components/PayTo/PayTo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { h } from 'preact';
import UIElement from '../internal/UIElement/UIElement';
import { CoreProvider } from '../../core/Context/CoreProvider';
import Await from '../../components/internal/Await';
import SRPanelProvider from '../../core/Errors/SRPanelProvider';

/*
Types (previously in their own file)
*/
import { UIElementProps } from '../internal/UIElement/types';
import { TxVariants } from '../tx-variants';
import PayToInput from './components/PayToInput';
import { PayIdFormData } from './components/PayIDInput';
import { PayToIdentifierEnum } from './components/IdentifierSelector';

export interface PayToConfiguration extends UIElementProps {
paymentData?: any;
data?: PayToData;
placeholders?: any; //TODO
}

export interface PayToData extends PayIdFormData {
shopperAccountIdentifier: string;
}

/*
Await Config (previously in its own file)
*/
const COUNTDOWN_MINUTES = 15; // min
const THROTTLE_TIME = 60000; // ms
const THROTTLE_INTERVAL = 10000; // ms

const config = {
COUNTDOWN_MINUTES,
THROTTLE_TIME,
THROTTLE_INTERVAL,
showCountdownTimer: false
};

const getAccountIdentifier = (state: PayToData) => {
switch (state.selectedIdentifier) {
case PayToIdentifierEnum.email:
return state.email;
case PayToIdentifierEnum.abn:
return state.abn;
case PayToIdentifierEnum.orgid:
return state.orgid;
case PayToIdentifierEnum.phone:
return `${state.phonePrefix}-${state.phoneNumber}`;
}
};
/**
*
*/
export class PayToElement extends UIElement<PayToConfiguration> {
public static type = TxVariants.payto;

protected static defaultProps = {
placeholders: {}
};

formatProps(props) {
return {
...props,
data: {
...props.data,
phonePrefix: props.data?.phonePrefix || '+61' // use AUS as default value
}
};
}

/**
* Formats the component data output
*/
formatData() {
return {
paymentMethod: {
type: PayToElement.type,
shopperAccountIdentifier: getAccountIdentifier(this.state.data)
}
};
}

get isValid(): boolean {
return !!this.state.isValid;
}

get displayName(): string {
return this.props.name;
}

render() {
if (this.props.paymentData) {
return (
<CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>
<SRPanelProvider srPanel={this.props.modules.srPanel}>
<Await
ref={ref => {
this.componentRef = ref;
}}
clientKey={this.props.clientKey}
paymentData={this.props.paymentData}
onError={this.props.onError}
onComplete={this.onComplete}
brandLogo={this.icon}
type={this.constructor['type']}
messageText={this.props.i18n.get('ancv.confirmPayment')}
awaitText={this.props.i18n.get('await.waitForConfirmation')}
showCountdownTimer={config.showCountdownTimer}
throttleTime={config.THROTTLE_TIME}
throttleInterval={config.THROTTLE_INTERVAL}
onActionHandled={this.onActionHandled}
/>
</SRPanelProvider>
</CoreProvider>
);
}

return (
<CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>
<PayToInput
data={this.props.data}
placeholders={this.props.placeholders}
setComponentRef={this.setComponentRef}
onSubmit={this.submit}
onChange={this.setState}
payButton={this.payButton}
showPayButton={this.props.showPayButton}
/>
</CoreProvider>
);
}
}

export default PayToElement;
17 changes: 17 additions & 0 deletions packages/lib/src/components/PayTo/components/BSBInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { h } from 'preact';

export default function BSBInput() {
// const { i18n } = useCoreContext();

// TODO type this
// const { handleChangeFor, triggerValidation, data, valid, errors } = useForm<any>({
// schema: ['beneficiaryId']
// });
//
// const [status, setStatus] = useState<string>('ready');

// this.setStatus = setStatus;
// this.showValidation = triggerValidation;

return <p>BSBInput.tsx</p>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { h } from 'preact';
import Select from '../../internal/FormFields/Select';
import { SelectTargetObject } from '../../internal/FormFields/Select/types';
import Field from '../../internal/FormFields/Field';
import { useCoreContext } from '../../../core/Context/CoreProvider';
import Language from '../../../language';
import { createEnumChecker } from '../../../core/utils';

export enum PayToIdentifierEnum {
phone = 'phone',
email = 'email',
abn = 'abn',
orgid = 'orgid'
}

const payToIdentifierEnumCheck = createEnumChecker(PayToIdentifierEnum);

export type PayToPayIDInputIdentifierValues = keyof typeof PayToIdentifierEnum;

type PayIdOptionsType = { id: PayToPayIDInputIdentifierValues; nameKey: string }[];

export const PAYID_IDENTIFIER_OPTIONS: PayIdOptionsType = [
{
id: PayToIdentifierEnum.phone,
nameKey: 'payto.payid.option.phone'
},
{
id: PayToIdentifierEnum.email,
nameKey: 'payto.payid.option.email'
},
{
id: PayToIdentifierEnum.abn,
nameKey: 'payto.payid.option.abn'
},
{
id: PayToIdentifierEnum.orgid,
nameKey: 'payto.payid.option.orgid'
}
];

interface IdentifierSelectorProps {
classNameModifiers?: string[];
selectedIdentifier: PayToPayIDInputIdentifierValues;
onSelectedIdentifier: (value: PayToPayIDInputIdentifierValues) => void;
}

const loadI18nForOptions = (i18n: Language, options: PayIdOptionsType) =>
options.map(option => ({
id: option.id,
name: i18n.get(option.nameKey)
}));

export default function IdentifierSelector({ selectedIdentifier, onSelectedIdentifier, classNameModifiers }: IdentifierSelectorProps) {
const { i18n } = useCoreContext();

const hydratedOptions = loadI18nForOptions(i18n, PAYID_IDENTIFIER_OPTIONS);

// TODO this probably can by a bit tidier, clean up some of these types
// maybe make Select type generic
const onChange = (e: { target: SelectTargetObject }) => {
// TODO clean this
const valueStr = e.target.value + '';

if (payToIdentifierEnumCheck(valueStr)) {
onSelectedIdentifier(valueStr);
}
};

return (
<Field
className={''}
name={'payid-identifier'}
useLabelElement={true}
label={i18n.get('payto.payid.label.identifier')}
showContextualElement={false}
classNameModifiers={classNameModifiers}
>
<Select filterable={false} items={hydratedOptions} selectedValue={selectedIdentifier} onChange={onChange} name={'payid-identifier'} />
</Field>
);
}
10 changes: 10 additions & 0 deletions packages/lib/src/components/PayTo/components/PayIDInput.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
@import 'styles/variable-generator';

.adyen-checkout__fieldset--payto__payid_input {
margin-top: token(spacer-070);

.adyen-checkout__fieldset__fields {
margin-top: token(spacer-070);
gap: 0 token(spacer-060);
}
}
Loading

0 comments on commit df83f04

Please sign in to comment.