From f19fb8872ae168b8dc29086cef2849d783b526c3 Mon Sep 17 00:00:00 2001 From: vyshnav Date: Wed, 9 Oct 2024 16:36:24 +0530 Subject: [PATCH 01/18] fix the form issue --- src/components/common/registration-form.tsx | 757 ++++++++++---------- 1 file changed, 366 insertions(+), 391 deletions(-) diff --git a/src/components/common/registration-form.tsx b/src/components/common/registration-form.tsx index 6ee30b4..4ce64c7 100644 --- a/src/components/common/registration-form.tsx +++ b/src/components/common/registration-form.tsx @@ -6,30 +6,17 @@ import { zodResolver } from "@hookform/resolvers/zod"; import * as z from "zod"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; -import { - Form, - FormControl, - FormDescription, - FormField, - FormItem, - FormLabel, - FormMessage, + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, } from "@/components/ui/form"; -import { - Card, - CardContent, - CardDescription, - CardFooter, - CardHeader, - CardTitle, -} from "@/components/ui/card"; +import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"; import { Label } from "@/components/ui/label"; import { getPrice } from "@/app/actions/get-price"; import { toast } from "sonner"; @@ -44,401 +31,389 @@ import { PaymentLoading } from "../payment/payment-loading"; import { PaymentSuccessfulComponent } from "../payment/payment-successful"; declare global { - interface Window { - Razorpay: any; - } + interface Window { + Razorpay: any; + } } interface ResponseInterface { - orderId?: string; - status: number; - error?: string; + orderId?: string; + status: number; + error?: string; } interface RazorpayResponse { - razorpay_order_id: string; - razorpay_payment_id: string; - razorpay_signature: string; + razorpay_order_id: string; + razorpay_payment_id: string; + razorpay_signature: string; } -export const baseSchema = z.object({ - designation: z.enum(["student", "faculty", "employee"]), - name: z.string().min(2, { message: "Name must be at least 2 characters." }), - email: z.string().email({ message: "Invalid email address." }), - phone: z - .string() - .regex(/^\d{10}$/, { message: "Phone number must be 10 digits." }), - photo: z.string(), - couponCode: z.string().optional(), +const baseSchema = z.object({ + name: z.string().min(1, "Name is required"), + email: z.string().email("Invalid email"), + phone: z.string().min(10, "Phone number must be at least 10 digits"), + photo: z.string().min(1, "Photo is required"), + designation: z.enum(["student", "faculty", "employee"]), }); +const studentSchema = baseSchema.extend({ + usn: z.string().min(1, "USN is required"), + idCard: z.string().min(1, "ID Card is required"), +}); + +const facultyOrEmployeeSchema = baseSchema; + export interface FormDataInterface { - designation: "student" | "faculty" | "employee"; - name: string; - email: string; - phone: string; - photo: string; - idCard?: string; - usn?: string; - amount: string; - couponCode?: string; + designation: "student" | "faculty" | "employee"; + name: string; + email: string; + phone: string; + photo: string; + idCard?: string; + usn?: string; + amount: string; + couponCode?: string; } -export const studentSchema = baseSchema.extend({ - usn: z.string().min(1, { message: "USN is required for students." }), - idCard: z.string(), -}); - export default function RegistrationForm() { - const [step, setStep] = useState(1); - const [pricing, setPricing] = useState({ - basePrice: basePrice, - discountAmount: initialdiscount, - finalPrice: basePrice, - }); - const [isProcessing, setIsProcessing] = useState(false); - const [loading, setLoading] = useState(false); - const [success, setSuccess] = useState(false); + const [step, setStep] = useState(1); + const [pricing, setPricing] = useState({ + basePrice: basePrice, + discountAmount: initialdiscount, + finalPrice: basePrice, + }); + const [isProcessing, setIsProcessing] = useState(false); + const [loading, setLoading] = useState(false); + const [success, setSuccess] = useState(false); - const { data: session } = useSession(); + const { data: session } = useSession(); - const form = useForm< - z.infer - >({ - resolver: zodResolver(baseSchema), - defaultValues: { - designation: "student", - name: "", - email: "", - phone: "", - couponCode: "", - }, - }); + const form = useForm< + z.infer & { + couponCode?: string; + } + >({ + resolver: zodResolver(facultyOrEmployeeSchema), + defaultValues: { + name: "", + email: "", + phone: "", + photo: "", + idCard: "", + usn: "", + designation: "student", + couponCode: "", + }, + }); - // const handleSubmitForm = async () => { - // const data = form.getValues(); - // const resp = await submitForm(data as FormDataInterface); - // }; + // const handleSubmitForm = async () => { + // const data = form.getValues(); + // const resp = await submitForm(data as FormDataInterface); + // }; - const handlePayment = async () => { - setIsProcessing(true); - const couponCode = form.getValues("couponCode"); - try { - const response = await fetch("/api/create-order", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ amount: pricing.finalPrice }), - }); - const data: Promise = response.json(); + const handlePayment = async () => { + setIsProcessing(true); + const couponCode = form.getValues("couponCode"); + try { + const response = await fetch("/api/create-order", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ amount: pricing.finalPrice }), + }); + const data: Promise = response.json(); - const options = { - key: process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID, - amount: pricing.finalPrice * 100, - currency: "INR", - name: "Test Name", - description: "Test Transaction", - order_id: (await data).orderId, - handler: async (response: RazorpayResponse) => { - const resp = await fetch("/api/verify-order", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - orderId: response.razorpay_order_id, - razorpayPaymentId: response.razorpay_payment_id, - razorpaySignature: response.razorpay_signature, - amount: pricing.finalPrice, - }), - }); + const options = { + key: process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID, + amount: pricing.finalPrice * 100, + currency: "INR", + name: "St Joseph Engineering College", + description: "Test Transaction", + order_id: (await data).orderId, + handler: async (response: RazorpayResponse) => { + const resp = await fetch("/api/verify-order", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + orderId: response.razorpay_order_id, + razorpayPaymentId: response.razorpay_payment_id, + razorpaySignature: response.razorpay_signature, + amount: pricing.finalPrice, + }), + }); - const data = await resp.json(); - console.log(data); - if (data.isOk) { - await invalidateCouponCode(couponCode ?? "", session!); - const formResponse = form.getValues(); - await submitForm( - formResponse as FormDataInterface, - pricing.finalPrice - ); - setIsProcessing(false); - setSuccess(true); - } else { - setIsProcessing(false); - alert("Payment failed"); - } - }, - // change to dynamic - notes: { - customerName: form.getValues("name"), - customerEmail: session?.user.email, - customerContact: form.getValues("phone"), - }, - prefill: { - name: form.getValues("name"), - email: session?.user.email, - constact: form.getValues("phone"), - }, - theme: { - color: "#3399cc", - }, - }; - const rzp1 = new window.Razorpay(options); - rzp1.open(); - } catch (error) { - toast.error(`Some error ${error}`); - } - }; + const data = await resp.json(); + console.log(data); + if (data.isOk) { + await invalidateCouponCode(couponCode ?? "", session!); + const formResponse = form.getValues(); + await submitForm(formResponse as FormDataInterface, pricing.finalPrice); + setIsProcessing(false); + setSuccess(true); + } else { + setIsProcessing(false); + alert("Payment failed"); + } + }, + // change to dynamic + notes: { + customerName: form.getValues("name"), + customerEmail: session?.user.email, + customerContact: form.getValues("phone"), + }, + prefill: { + name: form.getValues("name"), + email: session?.user.email, + constact: form.getValues("phone"), + }, + theme: { + color: "#3399cc", + }, + }; + const rzp1 = new window.Razorpay(options); + rzp1.open(); + } catch (error) { + toast.error(`Some error ${error}`); + } + }; - const onSubmit = async ( - values: z.infer< - typeof studentSchema | typeof baseSchema | typeof baseSchema - > - ) => { - await handlePayment(); - // Handle form submission here - }; + const onSubmit = async (values: z.infer) => { + await handlePayment(); + // Handle form submission here + }; - const verifyCoupon = async () => { - const couponCode = form.getValues("couponCode"); - try { - const { basePrice, discountAmount, finalPrice } = await getPrice( - couponCode - ); - setPricing({ basePrice, discountAmount, finalPrice }); - toast.success("Coupon applied successfully"); - } catch (e) { - console.error(e); - const message = getErrorMessage(e); - toast.error(`${message}`); - } - }; + const verifyCoupon = async () => { + const couponCode = form.getValues("couponCode"); + try { + const { basePrice, discountAmount, finalPrice } = await getPrice(couponCode); + setPricing({ basePrice, discountAmount, finalPrice }); + toast.success("Coupon applied successfully"); + } catch (e) { + console.error(e); + const message = getErrorMessage(e); + toast.error(`${message}`); + } + }; - const handleNext = async () => { - let isValid = false; - if (step === 1) { - isValid = await form.trigger(["designation"]); - } else if (step === 2) { - const designation = form.getValues("designation"); - if (designation === "student") { - isValid = await form.trigger([ - "name", - "email", - "phone", - "usn", - "idCard", - "photo", - ]); - } else if (designation === "faculty" || designation === "employee") { - isValid = await form.trigger(["name", "email", "phone", "photo"]); - } - } + const handleNext = async () => { + let isValid = false; + + if (step === 1) { + isValid = await form.trigger(["designation"]); + } else if (step === 2) { + const designation = form.getValues("designation"); + + // Trigger different validations based on the designation + if (designation === "student") { + isValid = await form.trigger(["name", "email", "phone", "usn", "idCard", "photo"]); + } else if (designation === "faculty" || designation === "employee") { + isValid = await form.trigger(["name", "email", "phone", "photo"]); + } + } - if (isValid) { - setStep(step + 1); + if (isValid) { + setStep(step + 1); + } + }; + if (isProcessing) { + return ( +
+ +
+ ); + } + if (success) { + return ( +
+ +
+ ); } - }; - if (isProcessing) { - return ( -
- -
- ); - } - if (success) { - return ( -
- -
- ); - } - return ( - -