"use client" import { AlertTriangle, Plus } from "lucide-react" import { Button } from "@/shared/components/ui/button" import { Alert, AlertTitle } from "@/shared/components/ui/alert" import { FieldGroup } from "@/shared/components/ui/field" import { Rhform, RhfTextField, RhfTextareaField, } from "@/shared/components/form" import { toast } from "sonner" import { useAuthApi } from "@/shared/useApi" import { useFormMutation } from "@/shared/hooks/use-form-mutation" import { useForm } from "react-hook-form" import { zodResolver } from "@hookform/resolvers/zod" import { z } from "zod" const schema = z.object({ period_start: z.string().min(1, "Required"), period_end: z.string().min(1, "Required"), reference: z.string().max(50).optional(), note: z.string().max(2000).optional(), }) type PayrollRunFormValues = z.infer function firstOfMonth() { const d = new Date() return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().slice(0, 10) } function lastOfMonth() { const d = new Date() return new Date(d.getFullYear(), d.getMonth() + 1, 0).toISOString().slice(0, 10) } export type PayrollRunFormProps = { onSuccess?: (runId?: string) => void } export function PayrollRunForm({ onSuccess }: PayrollRunFormProps) { const api = useAuthApi() const form = useForm({ resolver: zodResolver(schema), defaultValues: { period_start: firstOfMonth(), period_end: lastOfMonth(), reference: "", note: "", }, }) const { mutate, error, isPending } = useFormMutation(form, { mutationFn: (values: PayrollRunFormValues) => { const payload = { period_start: values.period_start, period_end: values.period_end, reference: values.reference || undefined, note: values.note || undefined, } const promise = api.payroll.create(payload) toast.promise(promise, { loading: "Creating run + generating entries...", success: "Payroll run created", error: "Failed to create run", }) return promise }, onSuccess: (res: any) => { const runId = res?.data?.id ?? res?.id form.reset() onSuccess?.(runId ? String(runId) : undefined) }, }) return ( mutate(values)}> {error && ( Failed to create payroll run {error.message} )}
) }