1 import type { ChangeEvent } from 'react';
2 import { useState } from 'react';
4 import { c } from 'ttag';
6 import { Button } from '@proton/atoms';
7 import SettingsParagraph from '@proton/components/containers/account/SettingsParagraph';
8 import SettingsSection from '@proton/components/containers/account/SettingsSection';
9 import { useLoading } from '@proton/hooks';
10 import { onSessionMigrationPaymentsVersion } from '@proton/payments';
11 import { buyCredit, validateCredit } from '@proton/shared/lib/api/payments';
12 import { requiredValidator } from '@proton/shared/lib/helpers/formValidators';
14 import { InputFieldTwo, useFormErrors } from '../../components';
15 import { useApi, useEventManager, useNotifications, useSubscription, useUser } from '../../hooks';
17 const GiftCodeSection = () => {
18 const [value, setValue] = useState('');
19 const { validator, reset, onFormSubmit } = useFormErrors();
20 const [loading, withLoading] = useLoading();
22 const { call } = useEventManager();
23 const { createNotification } = useNotifications();
24 const [user] = useUser();
25 const [subscription] = useSubscription();
27 const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => {
28 setValue(target.value.replace(/\s|\t/g, '').toUpperCase());
31 const submit = async () => {
32 const paymentsVersion = onSessionMigrationPaymentsVersion(user, subscription);
34 await api(validateCredit({ GiftCode: value }, paymentsVersion));
35 await api(buyCredit({ GiftCode: value, Amount: 0 }, paymentsVersion));
39 createNotification({ text: c('Success').t`Gift code applied` });
45 {c('Info').t`If you have a gift code, enter it below to apply your discount.`}
48 <label htmlFor="gift-code-input" className="sr-only">
49 {c('Label').t`Gift code`}
53 className="gift-code_container flex flex-nowrap flex-column md:flex-row gap-2 md:gap-4"
57 withLoading(submit());
64 error={validator([requiredValidator(value)])}
65 placeholder={c('Placeholder').t`Add gift code`}
66 onChange={handleChange}
68 <div className="shrink-0">
69 <Button color="norm" type="submit" data-testid="submitCodeBtn" loading={loading}>
70 {c('Action').t`Submit`}
78 export default GiftCodeSection;