updates
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
"use client"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, Trash2, CheckCircle, Unlink } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
|
||||
type AppointmentActionsProps = {
|
||||
appointmentId: string
|
||||
currentStatus?: string
|
||||
jobCardId?: number | null
|
||||
}
|
||||
|
||||
export function AppointmentActions({ appointmentId, currentStatus, jobCardId }: AppointmentActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
const queryClient = useQueryClient()
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/calendar/appointment/${appointmentId}/edit`)
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await api.appointments.destroy(appointmentId)
|
||||
toast.success("Appointment deleted.")
|
||||
router.push("/calendar/appointment/list")
|
||||
} catch {
|
||||
toast.error("Failed to delete appointment.")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleChangeStatus = async (status: string) => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await api.appointments.changeStatus(appointmentId, { status } as any)
|
||||
toast.success(`Status updated to "${status}".`)
|
||||
queryClient.invalidateQueries({ queryKey: [APPOINTMENT_ROUTES.INDEX] })
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast.error("Failed to update status.")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUnlinkJobCard = async () => {
|
||||
if (!jobCardId) return
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await api.appointments.unlinkJobCard(appointmentId, {} as any)
|
||||
toast.success("Job card unlinked.")
|
||||
queryClient.invalidateQueries({ queryKey: [APPOINTMENT_ROUTES.INDEX] })
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast.error("Failed to unlink job card.")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" disabled={isLoading}>
|
||||
<Ellipsis className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
{currentStatus !== "confirmed" && (
|
||||
<DropdownMenuItem onClick={() => handleChangeStatus("confirmed")}>
|
||||
<CheckCircle className="size-4" />
|
||||
Confirm
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{currentStatus !== "completed" && (
|
||||
<DropdownMenuItem onClick={() => handleChangeStatus("completed")}>
|
||||
<CheckCircle className="size-4" />
|
||||
Mark Completed
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{currentStatus !== "cancelled" && (
|
||||
<DropdownMenuItem onClick={() => handleChangeStatus("cancelled")}>
|
||||
<CheckCircle className="size-4" />
|
||||
Cancel
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{jobCardId && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleUnlinkJobCard}>
|
||||
<Unlink className="size-4" />
|
||||
Unlink Job Card
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useContext } from "react"
|
||||
|
||||
type AppointmentContextValue = {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const AppointmentContext = createContext<AppointmentContextValue | null>(null)
|
||||
|
||||
export function AppointmentProvider({
|
||||
appointment,
|
||||
children,
|
||||
}: {
|
||||
appointment: AppointmentContextValue
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<AppointmentContext.Provider value={appointment}>
|
||||
{children}
|
||||
</AppointmentContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAppointment() {
|
||||
return useContext(AppointmentContext)
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
"use client"
|
||||
|
||||
import { AlertTriangle, Plus, Save } 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,
|
||||
RhfSelectField,
|
||||
RhfAsyncSelectField,
|
||||
} from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useResourceForm } from "@/shared/hooks/use-resource-form"
|
||||
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
|
||||
import { toRelation, toId } from "@/shared/lib/utils"
|
||||
|
||||
import {
|
||||
appointmentFormSchema,
|
||||
type AppointmentFormValues,
|
||||
APPOINTMENT_STATUS_OPTIONS,
|
||||
} from "./appointment.schema"
|
||||
import { RhfVehicleSelectField } from "@/modules/vehicles/rhf-vehicle-select-field"
|
||||
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
|
||||
import { RhfEmployeeSelectField } from "@/modules/employees/rhf-employee-select-field"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type AppointmentFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: AppointmentFormValues = {
|
||||
title: "",
|
||||
date: "",
|
||||
from_time: "",
|
||||
to_time: "",
|
||||
customer: null,
|
||||
vehicle: null,
|
||||
service_writer: null,
|
||||
technician: null,
|
||||
department: null,
|
||||
job_card: null,
|
||||
notes: "",
|
||||
status: "requested",
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): AppointmentFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
|
||||
return {
|
||||
title: d.title || "",
|
||||
date: d.date || "",
|
||||
from_time: d.from_time || "",
|
||||
to_time: d.to_time || "",
|
||||
customer: toRelation(d.customer_id, d.customer_name),
|
||||
vehicle: toRelation(d.vehicle_id, d.vehicle_name),
|
||||
service_writer: toRelation(d.service_writer_id, d.service_writer_name),
|
||||
technician: toRelation(d.technician_id, d.technician_name),
|
||||
department: toRelation(d.department_id, d.department_name),
|
||||
job_card: toRelation(d.job_card_id, d.job_card_title),
|
||||
notes: d.notes || "",
|
||||
status: d.status || "requested",
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: AppointmentFormValues) {
|
||||
return {
|
||||
title: values.title,
|
||||
date: values.date,
|
||||
from_time: values.from_time,
|
||||
to_time: values.to_time,
|
||||
customer_id: toId(values.customer),
|
||||
vehicle_id: toId(values.vehicle),
|
||||
service_writer_id: toId(values.service_writer),
|
||||
technician_id: toId(values.technician),
|
||||
department_id: toId(values.department),
|
||||
job_card_id: toId(values.job_card),
|
||||
notes: values.notes || undefined,
|
||||
status: values.status || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared helpers ──
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.name ?? item.title ?? String(item.id),
|
||||
})
|
||||
|
||||
const mapJobCardOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.title || `Job Card #${item.id}`,
|
||||
})
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function AppointmentForm({ resourceId, initialData, onSuccess }: AppointmentFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<AppointmentFormValues>({
|
||||
schema: appointmentFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, isPending, error } = useFormMutation(form, {
|
||||
mutationFn: (values: AppointmentFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = (isEditing && resourceId
|
||||
? api.appointments.update(resourceId, payload as any)
|
||||
: api.appointments.create(payload as any)) as Promise<any>
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating appointment..." : "Creating appointment...",
|
||||
success: isEditing ? "Appointment updated." : "Appointment created.",
|
||||
error: isEditing ? "Failed to update appointment." : "Failed to create appointment.",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)} className="space-y-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="size-4" />
|
||||
<AlertTitle>{error.message}</AlertTitle>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextField name="title" label="Title" placeholder="e.g. Oil Change Appointment" required />
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<RhfTextField name="date" label="Date" placeholder="YYYY-MM-DD" type="date" />
|
||||
<RhfSelectField
|
||||
name="status"
|
||||
label="Status"
|
||||
options={APPOINTMENT_STATUS_OPTIONS}
|
||||
placeholder="Select status"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<RhfTextField name="from_time" label="From Time" placeholder="HH:MM" type="time" />
|
||||
<RhfTextField name="to_time" label="To Time" placeholder="HH:MM" type="time" />
|
||||
</div>
|
||||
</FieldGroup>
|
||||
|
||||
<FieldGroup>
|
||||
<RhfCustomerSelectField name="customer" />
|
||||
<RhfVehicleSelectField name="vehicle" />
|
||||
</FieldGroup>
|
||||
|
||||
<FieldGroup>
|
||||
<RhfEmployeeSelectField name="service_writer" label="Service Writer" />
|
||||
<RhfEmployeeSelectField name="technician" label="Technician" />
|
||||
<RhfAsyncSelectField
|
||||
name="department"
|
||||
label="Department"
|
||||
placeholder="Select department..."
|
||||
queryKey={["departments-lookup"]}
|
||||
listFn={() => api.departments.list()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</FieldGroup>
|
||||
|
||||
<FieldGroup>
|
||||
<RhfAsyncSelectField
|
||||
name="job_card"
|
||||
label="Job Card (optional)"
|
||||
placeholder="Select job card..."
|
||||
queryKey={["job-cards-lookup"]}
|
||||
listFn={() => api.jobCards.list()}
|
||||
mapOption={mapJobCardOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</FieldGroup>
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextareaField name="notes" label="Notes" placeholder="Additional notes..." />
|
||||
</FieldGroup>
|
||||
|
||||
<Button type="submit" disabled={isPending} className="w-full">
|
||||
{isEditing ? <Save className="size-4" /> : <Plus className="size-4" />}
|
||||
{isPending
|
||||
? (isEditing ? "Saving..." : "Creating...")
|
||||
: (isEditing ? "Save Changes" : "Create Appointment")}
|
||||
</Button>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import {
|
||||
CalendarCheck2,
|
||||
Clock,
|
||||
User,
|
||||
Car,
|
||||
Users,
|
||||
Wrench,
|
||||
Building2,
|
||||
FileText,
|
||||
ClipboardList,
|
||||
Info,
|
||||
ExternalLink,
|
||||
} from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
|
||||
type AppointmentData = {
|
||||
id?: number
|
||||
job_card_id?: number
|
||||
title?: string
|
||||
date?: string
|
||||
from_time?: string
|
||||
to_time?: string
|
||||
customer_id?: number
|
||||
vehicle_id?: number
|
||||
service_writer_id?: number
|
||||
technician_id?: number
|
||||
department_id?: number
|
||||
notes?: string
|
||||
status?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
type AppointmentGeneralInfoProps = {
|
||||
appointment: AppointmentData
|
||||
}
|
||||
|
||||
function InfoItem({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value?: string | number | null
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">
|
||||
<Icon className="size-4" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
<span className="text-sm font-medium">
|
||||
{value != null && value !== "" ? String(value) : <span className="text-muted-foreground">—</span>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
requested: "bg-yellow-100 text-yellow-800",
|
||||
confirmed: "bg-blue-100 text-blue-800",
|
||||
in_progress: "bg-purple-100 text-purple-800",
|
||||
completed: "bg-green-100 text-green-800",
|
||||
cancelled: "bg-red-100 text-red-800",
|
||||
}
|
||||
|
||||
export function AppointmentGeneralInfo({ appointment }: AppointmentGeneralInfoProps) {
|
||||
const statusClass = appointment.status
|
||||
? (STATUS_COLORS[appointment.status] ?? "bg-gray-100 text-gray-800")
|
||||
: "bg-gray-100 text-gray-800"
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 md:grid-cols-2 p-6">
|
||||
{/* Appointment Details */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<CalendarCheck2 className="size-4" />
|
||||
Appointment Details
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
{appointment.status && (
|
||||
<Badge className={statusClass}>
|
||||
{appointment.status.replace("_", " ")}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem icon={Info} label="Title" value={appointment.title} />
|
||||
<InfoItem icon={CalendarCheck2} label="Date" value={appointment.date} />
|
||||
<InfoItem icon={Clock} label="From Time" value={appointment.from_time} />
|
||||
<InfoItem icon={Clock} label="To Time" value={appointment.to_time} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Customer & Vehicle */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<User className="size-4" />
|
||||
Customer & Vehicle
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem icon={User} label="Customer ID" value={appointment.customer_id} />
|
||||
<InfoItem icon={Car} label="Vehicle ID" value={appointment.vehicle_id} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Assignment */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Users className="size-4" />
|
||||
Assignment
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem icon={Users} label="Service Writer ID" value={appointment.service_writer_id} />
|
||||
<InfoItem icon={Wrench} label="Technician ID" value={appointment.technician_id} />
|
||||
<InfoItem icon={Building2} label="Department ID" value={appointment.department_id} />
|
||||
</div>
|
||||
{appointment.job_card_id && (
|
||||
<div className="pt-2">
|
||||
<span className="text-xs text-muted-foreground mb-1 block">Job Card</span>
|
||||
<Button asChild variant="outline" size="sm" className="gap-1.5">
|
||||
<Link href={`/sales/job-cards/${appointment.job_card_id}`}>
|
||||
<ClipboardList className="size-3.5" />
|
||||
Job Card #{appointment.job_card_id}
|
||||
<ExternalLink className="size-3.5" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Notes */}
|
||||
{appointment.notes && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<FileText className="size-4" />
|
||||
Notes
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground whitespace-pre-line">{appointment.notes}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const APPOINTMENT_STATUS_OPTIONS = [
|
||||
{ value: "requested", label: "Requested" },
|
||||
{ value: "confirmed", label: "Confirmed" },
|
||||
{ value: "in_progress", label: "In Progress" },
|
||||
{ value: "completed", label: "Completed" },
|
||||
{ value: "cancelled", label: "Cancelled" },
|
||||
]
|
||||
|
||||
const appointmentFormSchema = z.object({
|
||||
title: z.string().min(1, "Title is required"),
|
||||
date: z.string().min(1, "Date is required"),
|
||||
from_time: z.string().min(1, "Start time is required"),
|
||||
to_time: z.string().min(1, "End time is required"),
|
||||
customer: relationFieldSchema,
|
||||
vehicle: relationFieldSchema,
|
||||
service_writer: relationFieldSchema,
|
||||
technician: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
job_card: relationFieldSchema,
|
||||
notes: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
})
|
||||
|
||||
type AppointmentFormValues = z.infer<typeof appointmentFormSchema>
|
||||
|
||||
export { appointmentFormSchema, relationFieldSchema, APPOINTMENT_STATUS_OPTIONS }
|
||||
export type { AppointmentFormValues }
|
||||
Reference in New Issue
Block a user