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