feat: implement signup and verification basic functionality with forms and actions

This commit is contained in:
arraysid
2025-05-23 01:15:12 +07:00
parent e13e5b4de2
commit 01da8339f4
18 changed files with 638 additions and 4 deletions
@@ -8,6 +8,8 @@ import {
} from '../_validation/signin-validation';
export async function SigninAction(request: SignInValidationType) {
console.log(request);
const validRequest = signInValidationSchema.parse(request);
const { data } = await fetchPostSignin(validRequest);
@@ -0,0 +1,15 @@
'use server';
import { z } from 'zod';
import { fetchPostSignin } from '../_http/fetch-post-signup';
import { signupValidationSchema } from '../_validation/signup-validation';
export async function SignupAction(
request: z.infer<typeof signupValidationSchema>
) {
const validRequest = signupValidationSchema.parse(request);
const data = await fetchPostSignin({ ...validRequest });
return data;
}
@@ -0,0 +1,267 @@
'use client';
import {
Button,
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
Input,
} from '@components/atoms';
import { zodResolver } from '@hookform/resolvers/zod';
import { Turnstile } from '@marsidev/react-turnstile';
import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { LuLoader } from 'react-icons/lu';
import { z } from 'zod';
import { SignupAction } from '../_actions/signup-action';
import {
signupValidationSchema,
stepOneSignupValidationSchema,
stepTwoSignupValidationSchema,
} from '../_validation/signup-validation';
export function SignupForm() {
const router = useRouter();
const [step, setStep] = useState(1);
const [stepOneData, setStepOneData] = useState<z.infer<
typeof stepOneSignupValidationSchema
> | null>(null);
const { mutate, isPending, error } = useMutation({
mutationFn: async (data: z.infer<typeof signupValidationSchema>) => {
const result = await SignupAction(data);
return {
...result,
email: data.email,
};
},
onSuccess: ({ email }) => {
router.push(`/verification?ref=${email}`);
},
onError: () => {
secondForm.reset();
},
});
const firstForm = useForm<z.infer<typeof stepOneSignupValidationSchema>>({
resolver: zodResolver(stepOneSignupValidationSchema),
defaultValues: {
email: '',
fullname: '',
password: '',
confirm_password: '',
},
});
const secondForm = useForm<z.infer<typeof stepTwoSignupValidationSchema>>({
resolver: zodResolver(stepTwoSignupValidationSchema),
defaultValues: {
phone_number: '',
referral_code: '',
referred_by: '',
student_type: '',
token: '',
},
});
const handleFirstSubmit = (
values: z.infer<typeof stepOneSignupValidationSchema>
) => {
setStepOneData(values);
setStep(2);
};
const handleSecondSubmit = (
values: z.infer<typeof stepTwoSignupValidationSchema>
) => {
if (stepOneData) {
mutate({ ...stepOneData, ...values });
}
};
return (
<>
{step === 1 && (
<Form {...firstForm}>
<form
onSubmit={firstForm.handleSubmit(handleFirstSubmit)}
className="space-y-4"
>
<FormField
control={firstForm.control}
name="fullname"
render={({ field }) => (
<FormItem>
<FormLabel>Full Name</FormLabel>
<FormControl>
<Input placeholder="Nama Lengkap" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={firstForm.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="emailmu@mail.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={firstForm.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" placeholder="••••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={firstForm.control}
name="confirm_password"
render={({ field }) => (
<FormItem>
<FormLabel>Confirm Password</FormLabel>
<FormControl>
<Input type="password" placeholder="••••••••" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
type="submit"
className="w-full bg-[#5fbaef] hover:bg-[#22a5f1]"
>
Selanjutnya
</Button>
</form>
</Form>
)}
{step === 2 && (
<Form {...secondForm}>
<form
onSubmit={secondForm.handleSubmit(handleSecondSubmit)}
className="space-y-4"
>
{error && (
<div className="p-2 text-xs bg-red-50 border border-red-200 text-red-800 rounded-sm">
{(error as Error).message}
</div>
)}
<FormField
control={secondForm.control}
name="phone_number"
render={({ field }) => (
<FormItem>
<FormLabel>Nomor Telepon</FormLabel>
<FormControl>
<Input placeholder="081234567890" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex gap-x-4">
<FormField
control={secondForm.control}
name="referral_code"
render={({ field }) => (
<FormItem>
<FormLabel>Kode Referral</FormLabel>
<FormControl>
<Input placeholder="ABCD" maxLength={4} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={secondForm.control}
name="referred_by"
render={({ field }) => (
<FormItem>
<FormLabel>Referrer</FormLabel>
<FormControl>
<Input placeholder="Referral ID" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={secondForm.control}
name="student_type"
render={({ field }) => (
<FormItem>
<FormLabel>Status</FormLabel>
<FormControl>
<Input placeholder="e.g., Undergraduate" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Turnstile
siteKey="1x00000000000000000000AA"
onSuccess={(token) => secondForm.setValue('token', token)}
options={{
theme: 'light',
size: 'flexible',
language: 'id',
}}
/>
<div className="flex justify-between">
<Button
type="button"
variant="secondary"
onClick={() => setStep(1)}
>
Kembali
</Button>
<Button
type="submit"
disabled={isPending || !secondForm.watch('token')}
className="flex items-center gap-2 hover:bg-[#5fbaef] bg-[#22a5f1]"
>
{isPending ? (
<LuLoader className="h-5 w-5 animate-spin" />
) : (
'Daftar'
)}
</Button>
</div>
</form>
</Form>
)}
</>
);
}
@@ -0,0 +1,34 @@
import { fetcher } from '@/lib/openapi';
import { SignupValidationSchema } from '../_validation/signup-validation';
export async function fetchPostSignin({
email,
password,
fullname,
phone_number,
student_type,
referral_code,
referred_by,
}: SignupValidationSchema) {
const { data, error, response } = await fetcher.POST('/v1/auth/register', {
body: {
email,
password,
fullname,
phone_number,
student_type,
referral_code,
referred_by,
},
});
if (error) {
throw new Error(error.message);
}
if (!response.ok) {
throw new Error('Someting went wrong, please try again later');
}
return data;
}
@@ -0,0 +1,76 @@
import { z } from 'zod';
export const stepOneSignupValidationSchema = z
.object({
email: z
.string({
required_error: 'Email tidak boleh kosong',
invalid_type_error: 'Email harus berupa string',
})
.min(1, 'Email tidak boleh kosong')
.email('Email harus valid'),
fullname: z
.string({
required_error: 'Nama tidak boleh kosong',
invalid_type_error: 'Nama harus berupa string',
})
.min(1, 'Nama tidak boleh kosong')
.max(50, 'Nama tidak boleh lebih dari 50 karakter'),
password: z
.string({
required_error: 'Password tidak boleh kosong',
invalid_type_error: 'Password harus berupa string',
})
.min(1, 'Password tidak boleh kosong')
.min(8, 'Password harus lebih dari 8 karakter')
.max(50, 'Password tidak boleh lebih dari 50 karakter')
.regex(
/(?=.*[A-Z])/,
'Password harus mengandung setidaknya satu huruf kapital'
)
.regex(
/(?=.*[a-z])/,
'Password harus mengandung setidaknya satu huruf kecil'
)
.regex(/(?=.*\d)/, 'Password harus mengandung setidaknya satu angka')
.regex(
/(?=.*[!@#$%^&*()_\-+={}[\]|\\:;"'<>,.?/~`])/,
'Password harus mengandung setidaknya satu karakter spesial'
),
confirm_password: z
.string({
required_error: 'Konfirmasi password tidak boleh kosong',
})
.min(1, 'Konfirmasi password tidak boleh kosong')
.max(50, 'Konfirmasi password tidak boleh lebih dari 50 karakter'),
})
.refine((data) => data.password === data.confirm_password, {
message: 'Password dan Konfirmasi Password harus sama',
path: ['confirm_password'],
});
export const stepTwoSignupValidationSchema = z.object({
phone_number: z
.string({
required_error: 'Nomor telepon tidak boleh kosong',
invalid_type_error: 'Nomor telepon harus berupa string',
})
.min(10, 'Nomor telepon tidak boleh kurang dari 10 karakter')
.max(15, 'Nomor telepon tidak boleh lebih dari 15 karakter')
.regex(/^\d+$/, 'Nomor telepon hanya boleh berisi angka'),
referral_code: z
.string()
.max(4, 'Kode referral tidak boleh lebih dari 4 karakter')
.optional(),
referred_by: z
.string()
.max(50, 'Kode referral tidak boleh lebih dari 50 karakter')
.optional(),
student_type: z.string(),
token: z.string(),
});
export const signupValidationSchema = stepOneSignupValidationSchema.and(
stepTwoSignupValidationSchema
);
export type SignupValidationSchema = z.infer<typeof signupValidationSchema>
@@ -1,4 +1,5 @@
import { LogoSimple } from '../../_components/logo';
import { SignupForm } from './_components/signup-form';
export default function Page() {
return (
@@ -10,6 +11,8 @@ export default function Page() {
Buat akunmu sekarang
</p>
</div>
<SignupForm />
</>
);
}
@@ -0,0 +1,15 @@
'use server';
import { fetcher } from '@/lib/openapi';
export async function resendOTPAction(email: string) {
const data = await fetcher.POST('/v1/auth/send-otp', {
body: {
email,
},
});
console.log(data);
return data;
}
@@ -0,0 +1,15 @@
'use server';
import { fetchPostVerifyEmail } from '../_http/fetch-post-verify-email';
import {
type VerifyEmailValidationType,
verifyEmailSchema,
} from '../_validation/verify-email-validation';
export async function verifyEmailAction(request: VerifyEmailValidationType) {
const validRequest = verifyEmailSchema.parse(request);
const data = await fetchPostVerifyEmail(validRequest);
return data;
}
@@ -0,0 +1,16 @@
'use client';
import { Button } from '@components/atoms';
import { usePostResendOTP } from '../_hooks/use-post-resend-otp';
export function ButtonResendOTP({ email }: { email: string }) {
const { mutate } = usePostResendOTP();
const handleResendOTP = () => mutate(email);
return (
<Button onClick={handleResendOTP} className="w-full -mt-2">
Kirim Ulang Kode OTP
</Button>
);
}
@@ -0,0 +1,80 @@
'use client';
import {
Button,
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
Input,
} from '@components/atoms';
import { LuLoader } from 'react-icons/lu';
import { useFormVerifyEmail } from '../_hooks/use-form-verify-email';
import { usePostVerifyEmail } from '../_hooks/use-post-verify-email';
import { type VerifyEmailValidationType } from '../_validation/verify-email-validation';
import { ButtonResendOTP } from './button-resend-otp';
export function VerifyEmailForm() {
const form = useFormVerifyEmail();
const { mutate, isPending, error } = usePostVerifyEmail(form);
const onSubmit = (values: VerifyEmailValidationType) => {
mutate(values);
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{error && (
<div className="p-2 text-xs bg-red-50 border border-red-200 text-red-800 rounded-sm">
{(error as Error).message}
</div>
)}
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="emailmu@mail.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="otp"
render={({ field }) => (
<FormItem>
<FormLabel>OTP</FormLabel>
<FormControl>
<Input placeholder="123456" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
type="submit"
disabled={isPending}
className="w-full hover:bg-[#5fbaef] bg-[#22a5f1] font-bold"
>
{isPending ? (
<LuLoader className="h-5 w-5 animate-spin" />
) : (
'Verifikasi'
)}
</Button>
</form>
<ButtonResendOTP email={form.watch('email')} />
</Form>
);
}
@@ -0,0 +1,20 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { useSearchParams } from 'next/navigation';
import { useForm } from 'react-hook-form';
import {
verifyEmailSchema,
type VerifyEmailValidationType,
} from '../_validation/verify-email-validation';
export function useFormVerifyEmail() {
const searchParams = useSearchParams();
const email = searchParams.get('ref');
return useForm<VerifyEmailValidationType>({
resolver: zodResolver(verifyEmailSchema),
defaultValues: {
email: email ?? '',
otp: '',
},
});
}
@@ -0,0 +1,12 @@
import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { resendOTPAction } from '../_actions/resend-otp-action';
export function usePostResendOTP() {
const router = useRouter();
return useMutation({
mutationFn: resendOTPAction,
onSuccess: () => router.replace('/verification?success=true'),
});
}
@@ -0,0 +1,20 @@
import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { verifyEmailAction } from '../_actions/verify-email-action';
import { useFormVerifyEmail } from './use-form-verify-email';
export function usePostVerifyEmail(
form: ReturnType<typeof useFormVerifyEmail>
) {
const router = useRouter();
return useMutation({
mutationFn: verifyEmailAction,
onSuccess: () => {
router.push('/feedback');
},
onError: () => {
form.resetField('otp');
},
});
}
@@ -0,0 +1,31 @@
import { fetcher } from '@/lib/openapi';
import { VerifyEmailValidationType } from '../_validation/verify-email-validation';
export async function fetchPostVerifyEmail({
email,
otp,
}: VerifyEmailValidationType) {
const formattedOTP = parseInt(otp);
const { data, error, response } = await fetcher.POST(
'/v1/auth/verify-email',
{
body: {
email,
otp: formattedOTP,
},
}
);
if (error) {
throw new Error(error.message);
}
if (!response.ok) {
throw new Error('Something went wrong, please try again later');
}
console.log(data);
return data;
}
@@ -0,0 +1,10 @@
import { z } from 'zod';
export const verifyEmailSchema = z.object({
email: z.string().email({ message: 'Format email tidak valid' }),
otp: z
.string()
.min(6, { message: 'OTP harus terdiri dari 6 digit' })
.max(6, { message: 'OTP harus terdiri dari 6 digit' }),
});
export type VerifyEmailValidationType = z.infer<typeof verifyEmailSchema>;
@@ -0,0 +1,18 @@
import { LogoSimple } from '../../_components/logo';
import { VerifyEmailForm } from './_components/verify-email-form';
export default function Page() {
return (
<>
<div className="flex flex-col items-center gap-4">
<LogoSimple />
<p className="text-muted-foreground text-center text-sm sm:text-base">
Verifikasi akun mu sekarang
</p>
</div>
<VerifyEmailForm />
</>
);
}
@@ -3,8 +3,8 @@ import Link from 'next/link';
export function DesktopNavigation() {
return (
<nav className="hidden md:flex items-center gap-8">
<Link href="/about" className="text-sm font-medium relative group">
<span className="transition-colors hover:text-primary">About</span>
<Link href="/" className="text-sm font-medium relative group">
<span className="transition-colors hover:text-primary">Home</span>
<span className="absolute -bottom-1 left-0 w-0 h-0.5 bg-primary transition-all duration-300 group-hover:w-full"></span>
</Link>
<Link href="/events" className="text-sm font-medium relative group">
@@ -5,10 +5,10 @@ export function MobileNavigation() {
<div className="md:hidden border-t bg-background/95 backdrop-blur-md">
<nav className="container flex flex-col py-4 text-center">
<Link
href="/about"
href="/"
className="py-3 text-sm font-medium border-b border-border/50"
>
About
Home
</Link>
<Link
href="/events"