All files / src/app/(auth)/signup SignUpForm.tsx

92% Statements 23/25
87.5% Branches 7/8
100% Functions 2/2
92% Lines 23/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2221x                                                         1x 64x 64x 64x 64x       64x                             64x 4x           4x 4x           2x 1x             1x 1x           1x 1x           1x               2x   2x     2x               64x   64x                                                                                                                                                                                                                            
'use client';
 
import { useMutation } from '@apollo/client/react';
import {
  Button,
  Checkbox,
  Container,
  Group,
  Paper,
  PasswordInput,
  Text,
  TextInput,
  Title,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
import { useTranslations } from 'next-intl';
import type { FC } from 'react';
import { useState } from 'react';
import { CREATE_USER } from '@/lib/graphql/mutations';
import { isFormSubmitDisabled, signUpValidationSchema } from '@/lib/validation';
import { zodResolver } from '@/lib/validation/zodResolver';
import PrivacyPolicyLink from '../../../components/PrivacyPolicyLink';
import { AUTH_ROUTES } from '../../../types/routes';
import type { CreateUserData, CreateUserVars } from './types';
 
const SignUpForm: FC = () => {
  const translate = useTranslations();
  const router = useRouter();
  const [isLoggingIn, setIsLoggingIn] = useState(false);
  const [createUser, { loading }] = useMutation<CreateUserData, CreateUserVars>(
    CREATE_USER,
  );
 
  const form = useForm({
    mode: 'uncontrolled',
    initialValues: {
      firstName: '',
      lastName: '',
      userName: '',
      email: '',
      password: '',
      confirmPassword: '',
      privacyAccepted: false as boolean,
    },
    validate: zodResolver(signUpValidationSchema),
    validateInputOnBlur: true,
  });
 
  const handleSignUp = async (values: typeof form.values) => {
    try {
      const {
        privacyAccepted: _,
        password,
        email,
        ...userRegisterInput
      } = values;
      const { data } = await createUser({
        variables: {
          userRegisterInput: { ...userRegisterInput, password, email },
        },
      });
 
      if (data?.createUser?.success) {
        notifications.show({
          title: translate('response.success'),
          message: translate('auth.accountCreatedSuccess'),
          color: 'green',
        });
 
        // Automatically log in the user
        setIsLoggingIn(true);
        const result = await signIn('credentials', {
          email,
          password,
          redirect: false,
        });
 
        if (result?.ok) {
          notifications.show({
            title: translate('response.success'),
            message: translate('auth.loginSuccess'),
            color: 'green',
          });
          // Keep loading state active until navigation completes
          router.push('/');
        } else E{
          // Registration succeeded but login failed, redirect to login page
          setIsLoggingIn(false);
          router.push(AUTH_ROUTES.LOGIN);
        }
      }
    } catch (error) {
      setIsLoggingIn(false);
      const message =
        error instanceof Error
          ? error.message
          : translate('response.unknownError');
      notifications.show({
        title: translate('response.error'),
        message: message,
        color: 'red',
      });
    }
  };
 
  const isSubmitDisabled = isFormSubmitDisabled(form, loading, isLoggingIn);
 
  return (
    <Container maw={520} my={40} id="sign-up-page">
      <Title ta="center" c="var(--mantine-color-gray-8)">
        {translate('auth.createAccount')}
      </Title>
      <Group mt={5} justify="center" align="center">
        <Text c="dimmed" size="sm" ta="center">
          {translate('auth.alreadyHaveAnAccount')}
        </Text>
        <Button
          variant="transparent"
          size="sm"
          component={Link}
          href={AUTH_ROUTES.LOGIN}
          data-testid="login-link"
        >
          {translate('auth.login')}
        </Button>
      </Group>
 
      <Paper
        component="form"
        withBorder
        shadow="md"
        p={30}
        mt={30}
        radius="md"
        onSubmit={form.onSubmit(handleSignUp)}
      >
        <TextInput
          required
          id="first-name"
          placeholder={translate('user.firstName')}
          label={translate('user.firstName')}
          key={form.key('firstName')}
          {...form.getInputProps('firstName')}
        />
        <TextInput
          required
          id="last-name"
          placeholder={translate('user.lastName')}
          mt="md"
          label={translate('user.lastName')}
          key={form.key('lastName')}
          {...form.getInputProps('lastName')}
        />
        <TextInput
          required
          id="user-name"
          placeholder={translate('user.userName')}
          mt="md"
          label={translate('user.userName')}
          key={form.key('userName')}
          {...form.getInputProps('userName')}
        />
        <TextInput
          label={translate('user.email')}
          placeholder={translate('auth.emailPlaceholder')}
          required
          mt="md"
          id="email"
          key={form.key('email')}
          {...form.getInputProps('email')}
        />
        <PasswordInput
          placeholder={translate('user.password')}
          required
          mt="md"
          id="password"
          label={translate('user.password')}
          key={form.key('password')}
          {...form.getInputProps('password')}
        />
        <PasswordInput
          placeholder={translate('user.confirmPassword')}
          required
          mt="md"
          id="confirm-password"
          label={translate('user.confirmPassword')}
          key={form.key('confirmPassword')}
          {...form.getInputProps('confirmPassword')}
        />
 
        <Checkbox
          data-testid="privacy-accepted"
          size="md"
          label={<PrivacyPolicyLink />}
          mt="xl"
          key={form.key('privacyAccepted')}
          {...form.getInputProps('privacyAccepted', { type: 'checkbox' })}
        />
 
        <Button
          id="submit-button"
          data-testid="submit-button"
          fullWidth
          mt="xl"
          type="submit"
          disabled={isSubmitDisabled}
          loading={loading || isLoggingIn}
          loaderProps={{ type: 'dots' }}
        >
          {translate('auth.createAnAccountButton')}
        </Button>
      </Paper>
    </Container>
  );
};
 
export default SignUpForm;