updates
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
"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,
|
||||
RhfCheckboxField,
|
||||
RhfAsyncSelectField,
|
||||
RhfAsyncMultiSelectField,
|
||||
} 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 {
|
||||
estimateFormSchema,
|
||||
type EstimateFormValues,
|
||||
} from "./estimate.schema"
|
||||
import { ESTIMATE_ROUTES, CUSTOMER_ROUTES, VEHICLE_ROUTES, DEPARTMENT_ROUTES, LABEL_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type EstimateFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: Partial<EstimateFormValues>
|
||||
onSuccess?: () => void
|
||||
defaultVehicleId?: string | null
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: EstimateFormValues = {
|
||||
title: "",
|
||||
customer: null,
|
||||
vehicle: null,
|
||||
department: null,
|
||||
estimate_number: "",
|
||||
date: "",
|
||||
has_insurance: false,
|
||||
remarks: "",
|
||||
labels: [],
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): EstimateFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
|
||||
return {
|
||||
title: d.title || "",
|
||||
customer: toRelation(d.customer_id, d.customer_name),
|
||||
vehicle: toRelation(d.vehicle_id, d.vehicle_name),
|
||||
department: toRelation(d.department_id, d.department_name),
|
||||
estimate_number: d.estimate_number || "",
|
||||
date: d.date || "",
|
||||
has_insurance: d.has_insurance ?? false,
|
||||
remarks: Array.isArray(d.remarks) ? d.remarks.join("\n") : d.remarks || "",
|
||||
labels: Array.isArray(d.labels)
|
||||
? d.labels.map((l: any) => ({ value: String(l.id), label: l.name }))
|
||||
: [],
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: EstimateFormValues) {
|
||||
return {
|
||||
title: values.title,
|
||||
customer_id: toId(values.customer),
|
||||
vehicle_id: toId(values.vehicle),
|
||||
department_id: toId(values.department),
|
||||
estimate_number: values.estimate_number || undefined,
|
||||
date: values.date || undefined,
|
||||
has_insurance: values.has_insurance,
|
||||
remarks: values.remarks
|
||||
? values.remarks.split("\n").filter(Boolean)
|
||||
: [],
|
||||
label_ids: values.labels.map((l) => Number(l.value)),
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared mapOption for async selects ──
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.name,
|
||||
})
|
||||
|
||||
const mapCustomerOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: [item.first_name, item.last_name].filter(Boolean).join(" "),
|
||||
})
|
||||
|
||||
const mapVehicleOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: [item.year, item.make_name, item.model_name].filter(Boolean).join(" "),
|
||||
})
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function EstimateForm({ resourceId, initialData, onSuccess }: EstimateFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<EstimateFormValues, any>({
|
||||
schema: estimateFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
queryKey: [ESTIMATE_ROUTES.BY_ID, resourceId],
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: EstimateFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = (isEditing && resourceId
|
||||
? api.estimates.update(resourceId, payload)
|
||||
: api.estimates.create(payload)) as Promise<any>
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating estimate..." : "Creating estimate...",
|
||||
success: isEditing ? "Estimate updated successfully" : "Estimate created successfully",
|
||||
error: isEditing ? "Failed to update estimate" : "Failed to create estimate",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update estimate" : "Failed to create estimate"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextField name="title" label="Title" placeholder="Estimate title" required />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="estimate_number" label="Estimate Number" placeholder="EST-001" />
|
||||
<RhfTextField name="date" label="Date" type="date" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="customer"
|
||||
label="Customer"
|
||||
placeholder="Select customer"
|
||||
queryKey={[CUSTOMER_ROUTES.INDEX]}
|
||||
listFn={() => api.customers.list()}
|
||||
mapOption={mapCustomerOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle"
|
||||
label="Vehicle"
|
||||
placeholder="Select vehicle"
|
||||
queryKey={[VEHICLE_ROUTES.INDEX]}
|
||||
listFn={() => api.vehicles.list()}
|
||||
mapOption={mapVehicleOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="department"
|
||||
label="Department"
|
||||
placeholder="Select department"
|
||||
queryKey={[DEPARTMENT_ROUTES.INDEX]}
|
||||
listFn={() => api.departments.list()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncMultiSelectField
|
||||
name="labels"
|
||||
label="Labels"
|
||||
placeholder="Select labels"
|
||||
multiple
|
||||
queryKey={[LABEL_ROUTES.INDEX]}
|
||||
listFn={() => api.labels.list()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<RhfCheckboxField name="has_insurance" label="Has Insurance" />
|
||||
|
||||
<RhfTextareaField name="remarks" label="Remarks" placeholder="Enter remarks (one per line)" rows={3} />
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
{isEditing ? <Save /> : <Plus />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Estimate" : "Create Estimate")}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const estimateFormSchema = z.object({
|
||||
// ── Required fields ──
|
||||
title: z.string().min(1, "Title is required"),
|
||||
|
||||
// ── Relations ──
|
||||
customer: relationFieldSchema,
|
||||
vehicle: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
|
||||
// ── Optional fields ──
|
||||
estimate_number: z.string().optional(),
|
||||
date: z.string().optional(),
|
||||
has_insurance: z.boolean().default(false),
|
||||
remarks: z.string().optional(),
|
||||
|
||||
// ── Multi-select relations ──
|
||||
labels: z
|
||||
.array(z.object({ value: z.string(), label: z.string() }))
|
||||
.default([]),
|
||||
})
|
||||
|
||||
type EstimateFormValues = z.infer<typeof estimateFormSchema>
|
||||
|
||||
export { estimateFormSchema, relationFieldSchema }
|
||||
export type { EstimateFormValues }
|
||||
@@ -0,0 +1,209 @@
|
||||
"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,
|
||||
RhfSelectField,
|
||||
RhfAsyncSelectField,
|
||||
RhfTextareaField,
|
||||
} 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 {
|
||||
expenseFormSchema,
|
||||
type ExpenseFormValues,
|
||||
} from "./expense.schema"
|
||||
import { EXPENSE_ROUTES, JOB_CARD_ROUTES, VENDOR_ROUTES, DEPARTMENT_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: "open", label: "Open" },
|
||||
{ value: "paid", label: "Paid" },
|
||||
]
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type ExpenseFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: ExpenseFormValues = {
|
||||
job_card: null,
|
||||
category: null,
|
||||
vendor: null,
|
||||
department: null,
|
||||
title: "",
|
||||
invoice_number: "",
|
||||
expense_date: "",
|
||||
notes: "",
|
||||
status: "open",
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): ExpenseFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
|
||||
return {
|
||||
job_card: toRelation(d.job_card_id, d.job_card_name),
|
||||
category: toRelation(d.category_id, d.category_name),
|
||||
vendor: toRelation(d.vendor_id, d.vendor_name),
|
||||
department: toRelation(d.department_id, d.department_name),
|
||||
title: d.title || "",
|
||||
invoice_number: d.invoice_number || "",
|
||||
expense_date: d.expense_date || "",
|
||||
notes: d.notes || "",
|
||||
status: d.status || "open",
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: ExpenseFormValues) {
|
||||
return {
|
||||
job_card_id: toId(values.job_card),
|
||||
category_id: toId(values.category),
|
||||
vendor_id: toId(values.vendor),
|
||||
department_id: toId(values.department),
|
||||
title: values.title,
|
||||
invoice_number: values.invoice_number || undefined,
|
||||
expense_date: values.expense_date || undefined,
|
||||
notes: values.notes || undefined,
|
||||
status: values.status || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared mapOption for async selects ──
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.name,
|
||||
})
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function ExpenseForm({ resourceId, initialData, onSuccess }: ExpenseFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<ExpenseFormValues, any>({
|
||||
schema: expenseFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: ExpenseFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = isEditing && resourceId
|
||||
? api.expenses.update(resourceId, payload)
|
||||
: api.expenses.create(payload)
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating expense..." : "Creating expense...",
|
||||
success: isEditing ? "Expense updated successfully" : "Expense created successfully",
|
||||
error: isEditing ? "Failed to update expense" : "Failed to create expense",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update expense" : "Failed to create expense"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextField name="title" label="Title" placeholder="Enter expense title" required />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfSelectField
|
||||
name="status"
|
||||
label="Status"
|
||||
placeholder="Select status"
|
||||
options={STATUS_OPTIONS}
|
||||
/>
|
||||
<RhfTextField name="expense_date" label="Expense Date" placeholder="YYYY-MM-DD" type="date" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="vendor"
|
||||
label="Vendor"
|
||||
placeholder="Select vendor"
|
||||
queryKey={[VENDOR_ROUTES.INDEX]}
|
||||
listFn={() => api.vendors.list()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="department"
|
||||
label="Department"
|
||||
placeholder="Select department"
|
||||
queryKey={[DEPARTMENT_ROUTES.INDEX]}
|
||||
listFn={() => api.departments.list()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="job_card"
|
||||
label="Job Card"
|
||||
placeholder="Select job card"
|
||||
queryKey={[JOB_CARD_ROUTES.INDEX]}
|
||||
listFn={() => api.jobCards.list()}
|
||||
mapOption={(item: any) => ({ value: String(item.id), label: item.job_card_number || item.name || `#${item.id}` })}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="category"
|
||||
label="Category"
|
||||
placeholder="Select category"
|
||||
queryKey={[EXPENSE_ROUTES.ITEMS]}
|
||||
listFn={() => api.expenses.listItems()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<RhfTextField name="invoice_number" label="Invoice Number" placeholder="INV-001" />
|
||||
|
||||
<RhfTextareaField name="notes" label="Notes" rows={3} />
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
{isEditing ? <Save /> : <Plus />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Expense" : "Create Expense")}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const expenseFormSchema = z.object({
|
||||
// ── Relations ──
|
||||
job_card: relationFieldSchema,
|
||||
category: relationFieldSchema,
|
||||
vendor: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
|
||||
// ── Basic info ──
|
||||
title: z.string().min(1, "Title is required"),
|
||||
invoice_number: z.string().optional(),
|
||||
expense_date: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
})
|
||||
|
||||
type ExpenseFormValues = z.infer<typeof expenseFormSchema>
|
||||
|
||||
export { expenseFormSchema, relationFieldSchema }
|
||||
export type { ExpenseFormValues }
|
||||
@@ -0,0 +1,68 @@
|
||||
"use client"
|
||||
|
||||
import { CalendarCheck, CalendarX, Eye, Ban } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
export function AppointmentsSummaryCard({ data }: Props) {
|
||||
const totals = data.appointments_summary?.totals
|
||||
|
||||
const stats = [
|
||||
{
|
||||
label: "Completed",
|
||||
value: totals?.completed?.text ?? "0 Appt.",
|
||||
icon: CalendarCheck,
|
||||
color: "text-emerald-600",
|
||||
bg: "bg-emerald-500/10",
|
||||
},
|
||||
{
|
||||
label: "No Shows",
|
||||
value: totals?.no_shows?.text ?? "0 Appt.",
|
||||
icon: Eye,
|
||||
color: "text-amber-600",
|
||||
bg: "bg-amber-500/10",
|
||||
},
|
||||
{
|
||||
label: "No-Show Rate",
|
||||
value: totals?.no_shows_rate?.text ?? "0%",
|
||||
icon: Ban,
|
||||
color: "text-red-600",
|
||||
bg: "bg-red-500/10",
|
||||
},
|
||||
{
|
||||
label: "Cancelled",
|
||||
value: totals?.cancelled?.text ?? "0 Appt.",
|
||||
icon: CalendarX,
|
||||
color: "text-slate-600",
|
||||
bg: "bg-slate-500/10",
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Appointments Summary</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{stats.map((stat) => (
|
||||
<div
|
||||
key={stat.label}
|
||||
className="flex items-center gap-3 rounded-lg border p-3"
|
||||
>
|
||||
<div className={`rounded-md p-2 ${stat.bg}`}>
|
||||
<stat.icon className={`h-4 w-4 ${stat.color}`} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{stat.value}</p>
|
||||
<p className="text-xs text-muted-foreground">{stat.label}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client"
|
||||
|
||||
import { Users, Building2, Truck, Shield } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
export function CustomersTotalsCard({ data }: Props) {
|
||||
const customers = data.customers_totals
|
||||
|
||||
const stats = [
|
||||
{ label: "Individuals", value: customers?.individuals ?? 0, icon: Users, color: "text-sky-600", bg: "bg-sky-500/10" },
|
||||
{ label: "Companies", value: customers?.companies ?? 0, icon: Building2, color: "text-indigo-600", bg: "bg-indigo-500/10" },
|
||||
{ label: "Fleets", value: customers?.fleets ?? 0, icon: Truck, color: "text-teal-600", bg: "bg-teal-500/10" },
|
||||
{ label: "Insurers", value: customers?.insurers ?? 0, icon: Shield, color: "text-rose-600", bg: "bg-rose-500/10" },
|
||||
]
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-sm font-medium">Customers</CardTitle>
|
||||
<span className="text-2xl font-bold">{customers?.total_customers ?? 0}</span>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{stats.map((stat) => (
|
||||
<div key={stat.label} className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={`rounded-md p-1.5 ${stat.bg}`}>
|
||||
<stat.icon className={`h-3.5 w-3.5 ${stat.color}`} />
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">{stat.label}</span>
|
||||
</div>
|
||||
<span className="text-sm font-semibold">{stat.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client"
|
||||
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { useDashboardData } from "./use-dashboard-data"
|
||||
import { FinancialTotalsCards } from "./financial-totals-cards"
|
||||
import { IncomeExpenseChart } from "./income-expense-chart"
|
||||
import { FinancialSummaryChart } from "./financial-summary-chart"
|
||||
import { WorkOrdersStatusCard } from "./work-orders-status-card"
|
||||
import { AppointmentsSummaryCard } from "./appointments-summary-card"
|
||||
import { UpcomingAppointmentsCard } from "./upcoming-appointments-card"
|
||||
import { ItemsTotalsCard } from "./items-totals-card"
|
||||
import { CustomersTotalsCard } from "./customers-totals-card"
|
||||
import { SalesPurchaseCards } from "./sales-purchase-cards"
|
||||
import { VehicleStatsCards } from "./vehicle-stats-cards"
|
||||
|
||||
export function DashboardContent() {
|
||||
const { data, isLoading, isError, error } = useDashboardData()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-24">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-24 text-muted-foreground">
|
||||
<p className="text-lg font-medium">Failed to load dashboard</p>
|
||||
<p className="text-sm">{error?.message ?? "An unexpected error occurred"}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Financial Overview */}
|
||||
<FinancialTotalsCards data={data} />
|
||||
|
||||
{/* Charts Row */}
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<IncomeExpenseChart data={data} />
|
||||
<FinancialSummaryChart data={data} />
|
||||
</div>
|
||||
|
||||
{/* Work Orders + Appointments */}
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<WorkOrdersStatusCard data={data} />
|
||||
<AppointmentsSummaryCard data={data} />
|
||||
</div>
|
||||
|
||||
{/* Upcoming Appointments */}
|
||||
<UpcomingAppointmentsCard data={data} />
|
||||
|
||||
{/* Sales & Purchase Documents */}
|
||||
<SalesPurchaseCards data={data} />
|
||||
|
||||
{/* Quick Stats Row */}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<ItemsTotalsCard data={data} />
|
||||
<CustomersTotalsCard data={data} />
|
||||
</div>
|
||||
|
||||
{/* Vehicle Statistics */}
|
||||
<VehicleStatsCards data={data} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
"use client"
|
||||
|
||||
import { Bar, BarChart, XAxis, YAxis, CartesianGrid } from "recharts"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
type ChartConfig,
|
||||
} from "@/shared/components/ui/chart"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
const chartConfig = {
|
||||
amount: {
|
||||
label: "Amount",
|
||||
color: "var(--color-blue-500, #3b82f6)",
|
||||
},
|
||||
} satisfies ChartConfig
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
export function FinancialSummaryChart({ data }: Props) {
|
||||
const summary = data.financial_summary
|
||||
const currency = summary?.currency ?? ""
|
||||
|
||||
const chartData = (summary?.chart ?? []).map((item) => ({
|
||||
label: item.label ?? "",
|
||||
amount: item.amount ?? 0,
|
||||
count: item.count ?? 0,
|
||||
}))
|
||||
|
||||
const colors = ["#3b82f6", "#f59e0b", "#ef4444"]
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Financial Summary</CardTitle>
|
||||
<CardDescription>
|
||||
Invoices, expenses & bills breakdown ({currency})
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ChartContainer config={chartConfig} className="h-75 w-full">
|
||||
<BarChart data={chartData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
|
||||
<XAxis dataKey="label" tickLine={false} axisLine={false} />
|
||||
<YAxis tickLine={false} axisLine={false} tickFormatter={(v: number) => v.toLocaleString()} />
|
||||
<ChartTooltip
|
||||
content={
|
||||
<ChartTooltipContent
|
||||
formatter={(value, _name, item) => (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{currency} {Number(value).toLocaleString()}</span>
|
||||
<span className="text-muted-foreground">{item.payload.count} document(s)</span>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="amount"
|
||||
radius={[6, 6, 0, 0]}
|
||||
fill="var(--color-amount)"
|
||||
barSize={48}
|
||||
>
|
||||
{chartData.map((_entry, index) => (
|
||||
<rect key={index} fill={colors[index % colors.length]} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
DollarSign,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
ArrowUpRight,
|
||||
ArrowDownRight,
|
||||
} from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
export function FinancialTotalsCards({ data }: Props) {
|
||||
const totals = data.totals
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Card className="relative overflow-hidden">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
Total Income
|
||||
</CardTitle>
|
||||
<div className="rounded-md bg-emerald-500/10 p-2">
|
||||
<TrendingUp className="h-4 w-4 text-emerald-600" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold text-emerald-600">
|
||||
{totals?.total_income_text ?? `${totals?.currency ?? ""} 0.00`}
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<ArrowUpRight className="h-3 w-3 text-emerald-500" />
|
||||
Income this period
|
||||
</div>
|
||||
</CardContent>
|
||||
<div className="absolute -bottom-4 -right-4 h-24 w-24 rounded-full bg-emerald-500/5" />
|
||||
</Card>
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
Total Expenses
|
||||
</CardTitle>
|
||||
<div className="rounded-md bg-red-500/10 p-2">
|
||||
<TrendingDown className="h-4 w-4 text-red-600" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold text-red-600">
|
||||
{totals?.total_expense_text ?? `${totals?.currency ?? ""} 0.00`}
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<ArrowDownRight className="h-3 w-3 text-red-500" />
|
||||
Expenses this period
|
||||
</div>
|
||||
</CardContent>
|
||||
<div className="absolute -bottom-4 -right-4 h-24 w-24 rounded-full bg-red-500/5" />
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
"use client"
|
||||
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
CartesianGrid,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
type ChartConfig,
|
||||
} from "@/shared/components/ui/chart"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
const chartConfig = {
|
||||
income: {
|
||||
label: "Income",
|
||||
color: "var(--color-emerald-500, #10b981)",
|
||||
},
|
||||
expense: {
|
||||
label: "Expense",
|
||||
color: "var(--color-red-500, #ef4444)",
|
||||
},
|
||||
} satisfies ChartConfig
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
export function IncomeExpenseChart({ data }: Props) {
|
||||
const series = data.chart?.series ?? []
|
||||
const currency = data.chart?.currency ?? ""
|
||||
|
||||
const chartData = series.map((item) => ({
|
||||
date: item.date ?? "",
|
||||
income: item.income ?? 0,
|
||||
expense: item.expense ?? 0,
|
||||
}))
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Income vs Expenses</CardTitle>
|
||||
<CardDescription>
|
||||
Financial trend over the selected period ({currency})
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ChartContainer config={chartConfig} className="h-75 w-full">
|
||||
<AreaChart data={chartData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id="fillIncome" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="var(--color-income)" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="var(--color-income)" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
<linearGradient id="fillExpense" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="var(--color-expense)" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="var(--color-expense)" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickFormatter={(value: string) => {
|
||||
const date = new Date(value)
|
||||
return date.toLocaleDateString("en-US", { month: "short", day: "numeric" })
|
||||
}}
|
||||
/>
|
||||
<YAxis tickLine={false} axisLine={false} tickFormatter={(v: number) => `${v.toLocaleString()}`} />
|
||||
<ChartTooltip
|
||||
content={
|
||||
<ChartTooltipContent
|
||||
labelFormatter={(value) => {
|
||||
return new Date(value).toLocaleDateString("en-US", {
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
})
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="income"
|
||||
stroke="var(--color-income)"
|
||||
fill="url(#fillIncome)"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="expense"
|
||||
stroke="var(--color-expense)"
|
||||
fill="url(#fillExpense)"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ChartContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client"
|
||||
|
||||
import { Package, Wrench, Layers } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
export function ItemsTotalsCard({ data }: Props) {
|
||||
const items = data.items_totals
|
||||
|
||||
const stats = [
|
||||
{ label: "Parts", value: items?.parts ?? 0, icon: Package, color: "text-blue-600", bg: "bg-blue-500/10" },
|
||||
{ label: "Services", value: items?.services ?? 0, icon: Wrench, color: "text-violet-600", bg: "bg-violet-500/10" },
|
||||
{ label: "Service Groups", value: items?.service_groups ?? 0, icon: Layers, color: "text-amber-600", bg: "bg-amber-500/10" },
|
||||
]
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-sm font-medium">Items</CardTitle>
|
||||
<span className="text-2xl font-bold">{items?.total_items ?? 0}</span>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{stats.map((stat) => (
|
||||
<div key={stat.label} className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={`rounded-md p-1.5 ${stat.bg}`}>
|
||||
<stat.icon className={`h-3.5 w-3.5 ${stat.color}`} />
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">{stat.label}</span>
|
||||
</div>
|
||||
<span className="text-sm font-semibold">{stat.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client"
|
||||
|
||||
import { FileText, FileSearch, Receipt, ShoppingCart } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
export function SalesPurchaseCards({ data }: Props) {
|
||||
const sales = data.sales_totals
|
||||
const purchase = data.purchase_totals
|
||||
|
||||
const salesStats = [
|
||||
{ label: "Inspections", value: sales?.inspections ?? 0, icon: FileSearch },
|
||||
{ label: "Estimates", value: sales?.estimates ?? 0, icon: FileText },
|
||||
{ label: "Invoices", value: sales?.invoices ?? 0, icon: Receipt },
|
||||
]
|
||||
|
||||
const purchaseStats = [
|
||||
{ label: "Purchase Orders", value: purchase?.purchase_orders ?? 0, icon: ShoppingCart },
|
||||
{ label: "Bills", value: purchase?.bills ?? 0, icon: Receipt },
|
||||
{ label: "Expenses", value: purchase?.expenses ?? 0, icon: FileText },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-sm font-medium">Sales Documents</CardTitle>
|
||||
<span className="text-2xl font-bold text-emerald-600">
|
||||
{sales?.total_sales_documents ?? 0}
|
||||
</span>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{salesStats.map((stat) => (
|
||||
<div
|
||||
key={stat.label}
|
||||
className="flex flex-col items-center gap-1 rounded-lg border p-3 text-center"
|
||||
>
|
||||
<stat.icon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg font-bold">{stat.value}</span>
|
||||
<span className="text-[11px] text-muted-foreground leading-tight">
|
||||
{stat.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-sm font-medium">Purchase Documents</CardTitle>
|
||||
<span className="text-2xl font-bold text-blue-600">
|
||||
{purchase?.total_purchase_documents ?? 0}
|
||||
</span>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{purchaseStats.map((stat) => (
|
||||
<div
|
||||
key={stat.label}
|
||||
className="flex flex-col items-center gap-1 rounded-lg border p-3 text-center"
|
||||
>
|
||||
<stat.icon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg font-bold">{stat.value}</span>
|
||||
<span className="text-[11px] text-muted-foreground leading-tight">
|
||||
{stat.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
"use client"
|
||||
|
||||
import { Calendar, Clock } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
const statusBadge: Record<string, string> = {
|
||||
confirmed: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300",
|
||||
pending: "bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300",
|
||||
cancelled: "bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300",
|
||||
}
|
||||
|
||||
type AppointmentDetail = NonNullable<NonNullable<NonNullable<DashboardData["upcoming_appointments"]>["today"]>["details"]>[number]
|
||||
|
||||
function AppointmentRow({ appt }: { appt: AppointmentDetail }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between rounded-lg border p-3 transition-colors hover:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="rounded-md bg-primary/10 p-2">
|
||||
<Calendar className="h-4 w-4 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{appt.title}</p>
|
||||
{appt.notes && (
|
||||
<p className="text-xs text-muted-foreground line-clamp-1">{appt.notes}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Clock className="h-3 w-3" />
|
||||
{appt.from_time?.slice(0, 5)} - {appt.to_time?.slice(0, 5)}
|
||||
</div>
|
||||
<Badge variant="secondary" className={statusBadge[appt.status ?? ""] ?? ""}>
|
||||
{appt.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyState() {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
|
||||
<Calendar className="h-8 w-8 mb-2 opacity-50" />
|
||||
<p className="text-sm">No appointments</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function UpcomingAppointmentsCard({ data }: Props) {
|
||||
const upcoming = data.upcoming_appointments
|
||||
|
||||
const tabs = [
|
||||
{ key: "today", label: "Today", data: upcoming?.today },
|
||||
{ key: "tomorrow", label: "Tomorrow", data: upcoming?.tomorrow },
|
||||
{ key: "this_week", label: "This Week", data: upcoming?.this_week },
|
||||
{ key: "next_week", label: "Next Week", data: upcoming?.next_week },
|
||||
]
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Upcoming Appointments</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Tabs defaultValue="today">
|
||||
<TabsList className="w-full">
|
||||
{tabs.map((tab) => (
|
||||
<TabsTrigger key={tab.key} value={tab.key} className="flex-1 text-xs">
|
||||
{tab.label}
|
||||
<Badge variant="secondary" className="ml-1.5 h-5 px-1.5 text-[10px]">
|
||||
{tab.data?.count ?? 0}
|
||||
</Badge>
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
|
||||
{tabs.map((tab) => (
|
||||
<TabsContent key={tab.key} value={tab.key} className="space-y-2 mt-3">
|
||||
{(tab.data?.details as AppointmentDetail[] | undefined)?.length ? (
|
||||
(tab.data?.details as AppointmentDetail[]).map((appt) => (
|
||||
<AppointmentRow key={appt.id} appt={appt} />
|
||||
))
|
||||
) : (
|
||||
<EmptyState />
|
||||
)}
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import type { HomeDashboardResponse } from "@garage/api"
|
||||
|
||||
export type DashboardData = HomeDashboardResponse
|
||||
|
||||
export function useDashboardData() {
|
||||
const api = useAuthApi()
|
||||
|
||||
return useQuery<DashboardData>({
|
||||
queryKey: ["home", "dashboard"],
|
||||
queryFn: () => api.home.dashboard(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
"use client"
|
||||
|
||||
import { Car } from "lucide-react"
|
||||
import { Bar, BarChart, XAxis, YAxis, CartesianGrid, Cell } from "recharts"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
type ChartConfig,
|
||||
} from "@/shared/components/ui/chart"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
const chartConfig = {
|
||||
vehicles_count: {
|
||||
label: "Vehicles",
|
||||
color: "var(--color-blue-500, #3b82f6)",
|
||||
},
|
||||
} satisfies ChartConfig
|
||||
|
||||
const COLORS = ["#3b82f6", "#8b5cf6", "#06b6d4", "#f59e0b", "#ef4444", "#10b981", "#ec4899", "#6366f1"]
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
export function VehicleStatsCards({ data }: Props) {
|
||||
const bodyTypes = data.body_types_vehicle_totals ?? []
|
||||
const makes = data.make_model_vehicle_totals?.makes ?? []
|
||||
|
||||
const bodyData = bodyTypes.map((bt) => ({
|
||||
name: bt.body_type ?? "Unknown",
|
||||
vehicles_count: bt.vehicles_count ?? 0,
|
||||
}))
|
||||
|
||||
const makeData = makes.map((m) => ({
|
||||
name: m.make ?? "Unknown",
|
||||
vehicles_count: m.vehicles_count ?? 0,
|
||||
}))
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Car className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<CardTitle>Vehicles by Body Type</CardTitle>
|
||||
<CardDescription>Distribution across body types</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{bodyData.length > 0 ? (
|
||||
<ChartContainer config={chartConfig} className="h-55 w-full">
|
||||
<BarChart data={bodyData} layout="vertical" margin={{ top: 0, right: 10, left: 0, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" horizontal={false} />
|
||||
<XAxis type="number" tickLine={false} axisLine={false} />
|
||||
<YAxis type="category" dataKey="name" tickLine={false} axisLine={false} width={80} />
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Bar dataKey="vehicles_count" radius={[0, 6, 6, 0]} barSize={24}>
|
||||
{bodyData.map((_entry, index) => (
|
||||
<Cell key={index} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground text-center py-8">No vehicle data</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Car className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<CardTitle>Vehicles by Make</CardTitle>
|
||||
<CardDescription>Top vehicle manufacturers</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{makeData.length > 0 ? (
|
||||
<ChartContainer config={chartConfig} className="h-55 w-full">
|
||||
<BarChart data={makeData} layout="vertical" margin={{ top: 0, right: 10, left: 0, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" horizontal={false} />
|
||||
<XAxis type="number" tickLine={false} axisLine={false} />
|
||||
<YAxis type="category" dataKey="name" tickLine={false} axisLine={false} width={80} />
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Bar dataKey="vehicles_count" radius={[0, 6, 6, 0]} barSize={24}>
|
||||
{makeData.map((_entry, index) => (
|
||||
<Cell key={index} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ChartContainer>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground text-center py-8">No vehicle data</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client"
|
||||
|
||||
import { ClipboardList } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Progress } from "@/shared/components/ui/progress"
|
||||
import type { DashboardData } from "./use-dashboard-data"
|
||||
|
||||
type Props = { data: DashboardData }
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
draft: "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300",
|
||||
check_in: "bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300",
|
||||
in_progress: "bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300",
|
||||
completed: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-300",
|
||||
cancelled: "bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300",
|
||||
invoiced: "bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300",
|
||||
}
|
||||
|
||||
export function WorkOrdersStatusCard({ data }: Props) {
|
||||
const workOrders = data.work_orders_status
|
||||
const cards = workOrders?.cards ?? []
|
||||
const totals = workOrders?.totals
|
||||
const totalOrders = totals?.orders ?? 0
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ClipboardList className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle>Work Orders</CardTitle>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-2xl font-bold">{totals?.orders_text ?? "0 Orders"}</p>
|
||||
<p className="text-xs text-muted-foreground">{totals?.amount_text ?? ""}</p>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{cards.map((card) => {
|
||||
const percentage = totalOrders > 0 ? ((card.count ?? 0) / totalOrders) * 100 : 0
|
||||
return (
|
||||
<div key={card.status} className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={statusColors[card.status ?? ""] ?? ""}
|
||||
>
|
||||
{card.label}
|
||||
</Badge>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{card.orders_text}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-sm font-medium">{card.amount_text}</span>
|
||||
</div>
|
||||
<Progress value={percentage} className="h-1.5" />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{cards.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
No work orders this period
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
|
||||
|
||||
type InvoiceActionsProps = {
|
||||
invoiceId: string
|
||||
}
|
||||
|
||||
export function InvoiceActions({ invoiceId }: InvoiceActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/sales/invoice/${invoiceId}/edit`)
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
await api.invoices.destroy(invoiceId)
|
||||
router.push("/sales/invoice")
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Ellipsis className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<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 InvoiceContextValue = {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const InvoiceContext = createContext<InvoiceContextValue | null>(null)
|
||||
|
||||
export function InvoiceProvider({
|
||||
invoice,
|
||||
children,
|
||||
}: {
|
||||
invoice: InvoiceContextValue
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<InvoiceContext.Provider value={invoice}>
|
||||
{children}
|
||||
</InvoiceContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useInvoice() {
|
||||
return useContext(InvoiceContext)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"use client"
|
||||
|
||||
import { z } from "zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Plus } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { FieldGroup } from "@/shared/components/ui/field"
|
||||
import { Rhform, RhfTextField, RhfCheckboxField } from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
|
||||
const schema = z.object({
|
||||
document_number: z.string().min(1, "Document number is required"),
|
||||
show_in_invoice: z.boolean(),
|
||||
show_in_estimate: z.boolean(),
|
||||
show_in_statement: z.boolean(),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
type InvoiceDocumentFormProps = {
|
||||
invoiceId: string
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function InvoiceDocumentForm({ invoiceId, onSuccess }: InvoiceDocumentFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
document_number: "",
|
||||
show_in_invoice: true,
|
||||
show_in_estimate: false,
|
||||
show_in_statement: false,
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = async (values: FormValues) => {
|
||||
try {
|
||||
await api.invoices.createDocument({
|
||||
invoice_id: Number(invoiceId),
|
||||
document_number: values.document_number,
|
||||
show_in_invoice: values.show_in_invoice,
|
||||
show_in_estimate: values.show_in_estimate,
|
||||
show_in_statement: values.show_in_statement,
|
||||
})
|
||||
toast.success("Document created")
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
} catch {
|
||||
toast.error("Failed to create document")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
<RhfTextField
|
||||
name="document_number"
|
||||
label="Document Number"
|
||||
placeholder="e.g. DOC-001"
|
||||
required
|
||||
/>
|
||||
<RhfCheckboxField name="show_in_invoice" label="Show in Invoice" />
|
||||
<RhfCheckboxField name="show_in_estimate" label="Show in Estimate" />
|
||||
<RhfCheckboxField name="show_in_statement" label="Show in Statement" />
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
<Plus />
|
||||
{form.formState.isSubmitting ? "Creating..." : "Create Document"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
"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,
|
||||
RhfSelectField,
|
||||
RhfTextareaField,
|
||||
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 {
|
||||
invoiceFormSchema,
|
||||
type InvoiceFormValues,
|
||||
} from "./invoice.schema"
|
||||
import { INVOICE_ROUTES, CUSTOMER_ROUTES, VEHICLE_ROUTES, DEPARTMENT_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: "draft", label: "Draft" },
|
||||
{ value: "open", label: "Open" },
|
||||
{ value: "paid", label: "Paid" },
|
||||
{ value: "overdue", label: "Overdue" },
|
||||
{ value: "void", label: "Void" },
|
||||
]
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type InvoiceFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: InvoiceFormValues = {
|
||||
subject: "",
|
||||
customer: null,
|
||||
vehicle: null,
|
||||
department: null,
|
||||
invoice_number: "",
|
||||
invoice_date: "",
|
||||
due_date: "",
|
||||
status: "draft",
|
||||
notes: "",
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): InvoiceFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
|
||||
return {
|
||||
subject: d.subject || "",
|
||||
customer: toRelation(d.customer_id, d.customer_name),
|
||||
vehicle: toRelation(d.vehicle_id, d.vehicle_name),
|
||||
department: toRelation(d.department_id, d.department_name),
|
||||
invoice_number: d.invoice_number || "",
|
||||
invoice_date: d.invoice_date || "",
|
||||
due_date: d.due_date || "",
|
||||
status: d.status || "draft",
|
||||
notes: d.notes || "",
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: InvoiceFormValues) {
|
||||
return {
|
||||
subject: values.subject,
|
||||
customer_id: toId(values.customer),
|
||||
vehicle_id: toId(values.vehicle),
|
||||
department_id: toId(values.department),
|
||||
invoice_number: values.invoice_number || undefined,
|
||||
invoice_date: values.invoice_date || undefined,
|
||||
due_date: values.due_date || undefined,
|
||||
status: values.status || undefined,
|
||||
notes: values.notes || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared mapOption for async selects ──
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.name,
|
||||
})
|
||||
|
||||
const mapCustomerOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: [item.first_name, item.last_name].filter(Boolean).join(" "),
|
||||
})
|
||||
|
||||
const mapVehicleOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: [item.year, item.make_name, item.model_name].filter(Boolean).join(" "),
|
||||
})
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function InvoiceForm({ resourceId, initialData, onSuccess }: InvoiceFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<InvoiceFormValues, any>({
|
||||
schema: invoiceFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
queryKey: [INVOICE_ROUTES.BY_ID, resourceId],
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: InvoiceFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = (isEditing && resourceId
|
||||
? api.invoices.update(resourceId, payload)
|
||||
: api.invoices.create(payload)) as Promise<any>
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating invoice..." : "Creating invoice...",
|
||||
success: isEditing ? "Invoice updated successfully" : "Invoice created successfully",
|
||||
error: isEditing ? "Failed to update invoice" : "Failed to create invoice",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update invoice" : "Failed to create invoice"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextField name="subject" label="Subject" placeholder="Invoice subject" required />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="invoice_number" label="Invoice Number" placeholder="INV-0001" />
|
||||
<RhfSelectField
|
||||
name="status"
|
||||
label="Status"
|
||||
placeholder="Select status"
|
||||
options={STATUS_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="invoice_date" label="Invoice Date" type="date" />
|
||||
<RhfTextField name="due_date" label="Due Date" type="date" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="customer"
|
||||
label="Customer"
|
||||
placeholder="Select customer"
|
||||
queryKey={[CUSTOMER_ROUTES.INDEX]}
|
||||
listFn={() => api.customers.list()}
|
||||
mapOption={mapCustomerOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle"
|
||||
label="Vehicle"
|
||||
placeholder="Select vehicle"
|
||||
queryKey={[VEHICLE_ROUTES.INDEX]}
|
||||
listFn={() => api.vehicles.list()}
|
||||
mapOption={mapVehicleOption}
|
||||
{...STORE_OBJECT}
|
||||
|
||||
/>
|
||||
</div>
|
||||
|
||||
<RhfAsyncSelectField
|
||||
name="department"
|
||||
label="Department"
|
||||
placeholder="Select department"
|
||||
queryKey={[DEPARTMENT_ROUTES.INDEX]}
|
||||
listFn={() => api.departments.list()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
|
||||
<RhfTextareaField name="notes" label="Notes" placeholder="Additional notes" rows={3} />
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
{isEditing ? <Save /> : <Plus />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Invoice" : "Create Invoice")}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import {
|
||||
FileText,
|
||||
Calendar,
|
||||
Hash,
|
||||
Users,
|
||||
Car,
|
||||
Building2,
|
||||
CircleDollarSign,
|
||||
Clock,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
|
||||
type InvoiceData = {
|
||||
id?: number
|
||||
subject?: string
|
||||
invoice_number?: string
|
||||
invoice_date?: string
|
||||
due_date?: string
|
||||
status?: string
|
||||
notes?: string
|
||||
customer_name?: string
|
||||
customer_id?: number
|
||||
vehicle_name?: string
|
||||
vehicle_id?: number
|
||||
department_name?: string
|
||||
department_id?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
type InvoiceGeneralInfoProps = {
|
||||
invoice: InvoiceData
|
||||
}
|
||||
|
||||
function InfoItem({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value?: string | 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 || <span className="text-muted-foreground">—</span>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const statusColorMap: Record<string, string> = {
|
||||
draft: "secondary",
|
||||
open: "default",
|
||||
paid: "default",
|
||||
overdue: "destructive",
|
||||
void: "outline",
|
||||
}
|
||||
|
||||
export function InvoiceGeneralInfo({ invoice }: InvoiceGeneralInfoProps) {
|
||||
return (
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Invoice Details */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<FileText className="size-4" />
|
||||
Invoice Details
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{invoice.subject && (
|
||||
<Badge variant="secondary">{invoice.subject}</Badge>
|
||||
)}
|
||||
{invoice.status && (
|
||||
<Badge variant={statusColorMap[invoice.status] as any ?? "outline"}>
|
||||
{invoice.status.charAt(0).toUpperCase() + invoice.status.slice(1)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Hash}
|
||||
label="Invoice Number"
|
||||
value={invoice.invoice_number}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Calendar}
|
||||
label="Invoice Date"
|
||||
value={invoice.invoice_date}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Calendar}
|
||||
label="Due Date"
|
||||
value={invoice.due_date}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Clock}
|
||||
label="Created"
|
||||
value={invoice.created_at ? new Date(invoice.created_at).toLocaleDateString() : null}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Relations */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<CircleDollarSign className="size-4" />
|
||||
Related Information
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Users}
|
||||
label="Customer"
|
||||
value={invoice.customer_name}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Car}
|
||||
label="Vehicle"
|
||||
value={invoice.vehicle_name}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Building2}
|
||||
label="Department"
|
||||
value={invoice.department_name}
|
||||
/>
|
||||
</div>
|
||||
{invoice.notes && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">Notes</span>
|
||||
<p className="text-sm">{invoice.notes}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
"use client"
|
||||
|
||||
import { z } from "zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Plus } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { FieldGroup } from "@/shared/components/ui/field"
|
||||
import { Rhform, RhfTextareaField } from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
|
||||
const schema = z.object({
|
||||
note: z.string().min(1, "Note is required"),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
type InvoiceNoteFormProps = {
|
||||
invoiceId: string
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function InvoiceNoteForm({ invoiceId, onSuccess }: InvoiceNoteFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { note: "" },
|
||||
})
|
||||
|
||||
const handleSubmit = async (values: FormValues) => {
|
||||
try {
|
||||
await api.invoices.createNote({
|
||||
invoice_id: Number(invoiceId),
|
||||
note: values.note,
|
||||
})
|
||||
toast.success("Note created")
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
} catch {
|
||||
toast.error("Failed to create note")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
<RhfTextareaField
|
||||
name="note"
|
||||
label="Note"
|
||||
placeholder="Enter a note..."
|
||||
rows={4}
|
||||
required
|
||||
/>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
<Plus />
|
||||
{form.formState.isSubmitting ? "Creating..." : "Add Note"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const invoiceFormSchema = z.object({
|
||||
// ── Required fields ──
|
||||
subject: z.string().min(1, "Subject is required"),
|
||||
|
||||
// ── Relations ──
|
||||
customer: relationFieldSchema,
|
||||
vehicle: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
|
||||
// ── Optional fields ──
|
||||
invoice_number: z.string().optional(),
|
||||
invoice_date: z.string().optional(),
|
||||
due_date: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
})
|
||||
|
||||
type InvoiceFormValues = z.infer<typeof invoiceFormSchema>
|
||||
|
||||
export { invoiceFormSchema, relationFieldSchema }
|
||||
export type { InvoiceFormValues }
|
||||
@@ -0,0 +1,289 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useRef } from "react"
|
||||
import { useMutation, useQuery } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
ComboboxContent,
|
||||
ComboboxList,
|
||||
ComboboxItem,
|
||||
ComboboxEmpty,
|
||||
} from "@/shared/components/ui/combobox"
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/shared/components/ui/popover"
|
||||
import { Calendar } from "@/shared/components/ui/calendar"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { toast } from "sonner"
|
||||
import { Ellipsis, Pencil, Trash2, CalendarIcon, UserCog, UserCheck, Loader2 } from "lucide-react"
|
||||
import { format } from "date-fns"
|
||||
import { EMPLOYEE_ROUTES } from "@garage/api"
|
||||
|
||||
type JobCardActionsProps = {
|
||||
jobCardId: string
|
||||
}
|
||||
|
||||
type Employee = {
|
||||
id: number
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
name?: string
|
||||
}
|
||||
|
||||
function getEmployeeName(emp: Employee) {
|
||||
return emp.name || [emp.first_name, emp.last_name].filter(Boolean).join(" ") || `Employee #${emp.id}`
|
||||
}
|
||||
|
||||
// ── Employee Picker Dialog ──
|
||||
|
||||
type EmployeePickerDialogProps = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
title: string
|
||||
description: string
|
||||
employees: Employee[]
|
||||
loading: boolean
|
||||
isPending: boolean
|
||||
onSelect: (employeeId: number) => void
|
||||
}
|
||||
|
||||
function EmployeePickerDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
employees,
|
||||
loading,
|
||||
isPending,
|
||||
onSelect,
|
||||
}: EmployeePickerDialogProps) {
|
||||
const anchorRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const handleSelect = (emp: Employee | null) => {
|
||||
if (!emp) return
|
||||
onSelect(emp.id)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div ref={anchorRef}>
|
||||
<Combobox
|
||||
value={null}
|
||||
onValueChange={handleSelect}
|
||||
disabled={isPending}
|
||||
>
|
||||
<ComboboxInput
|
||||
placeholder="Search employees..."
|
||||
showClear={false}
|
||||
/>
|
||||
<ComboboxContent anchor={anchorRef}>
|
||||
<ComboboxList>
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{!loading &&
|
||||
employees.map((emp) => (
|
||||
<ComboboxItem key={emp.id} value={emp}>
|
||||
{getEmployeeName(emp)}
|
||||
</ComboboxItem>
|
||||
))}
|
||||
{!loading && employees.length === 0 && (
|
||||
<ComboboxEmpty>No employees found</ComboboxEmpty>
|
||||
)}
|
||||
</ComboboxList>
|
||||
</ComboboxContent>
|
||||
</Combobox>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Main Component ──
|
||||
|
||||
export function JobCardActions({ jobCardId }: JobCardActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
const [datePickerOpen, setDatePickerOpen] = useState(false)
|
||||
const [serviceWriterDialogOpen, setServiceWriterDialogOpen] = useState(false)
|
||||
const [salesPersonDialogOpen, setSalesPersonDialogOpen] = useState(false)
|
||||
|
||||
const { data: employeesData, isLoading: employeesLoading } = useQuery({
|
||||
queryKey: [EMPLOYEE_ROUTES.INDEX],
|
||||
queryFn: () => api.employees.list(),
|
||||
})
|
||||
|
||||
const employees: Employee[] = (employeesData as any)?.data ?? []
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/sales/job-cards/${jobCardId}/edit`)
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Job Card",
|
||||
description: "Are you sure you want to delete this job card? This action cannot be undone.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (confirmed) {
|
||||
const promise = api.jobCards.destroy(jobCardId)
|
||||
toast.promise(promise, {
|
||||
loading: "Deleting job card...",
|
||||
success: "Job card deleted successfully",
|
||||
error: "Failed to delete job card",
|
||||
})
|
||||
await promise
|
||||
router.push("/sales/job-cards")
|
||||
}
|
||||
}
|
||||
|
||||
const changeDateMutation = useMutation({
|
||||
mutationFn: (date: Date) => {
|
||||
const order_date = format(date, "yyyy-MM-dd")
|
||||
const promise = api.jobCards.changeDate(jobCardId, { order_date })
|
||||
toast.promise(promise, {
|
||||
loading: "Updating date...",
|
||||
success: "Date updated successfully",
|
||||
error: "Failed to update date",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
setDatePickerOpen(false)
|
||||
router.refresh()
|
||||
},
|
||||
})
|
||||
|
||||
const changeServiceWriterMutation = useMutation({
|
||||
mutationFn: (employeeId: number) => {
|
||||
const promise = api.jobCards.changeServiceWriter(jobCardId, { service_writer_id: employeeId })
|
||||
toast.promise(promise, {
|
||||
loading: "Updating service writer...",
|
||||
success: "Service writer updated successfully",
|
||||
error: "Failed to update service writer",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
setServiceWriterDialogOpen(false)
|
||||
router.refresh()
|
||||
},
|
||||
})
|
||||
|
||||
const changeSalesPersonMutation = useMutation({
|
||||
mutationFn: (employeeId: number) => {
|
||||
const promise = api.jobCards.changeSalesPerson(jobCardId, { sales_person_id: employeeId })
|
||||
toast.promise(promise, {
|
||||
loading: "Updating sales person...",
|
||||
success: "Sales person updated successfully",
|
||||
error: "Failed to update sales person",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
setSalesPersonDialogOpen(false)
|
||||
router.refresh()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Popover open={datePickerOpen} onOpenChange={setDatePickerOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<CalendarIcon className="size-4" />
|
||||
<span className="hidden sm:inline">Change Date</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="end">
|
||||
<Calendar
|
||||
mode="single"
|
||||
onSelect={(date) => {
|
||||
if (date) changeDateMutation.mutate(date)
|
||||
}}
|
||||
disabled={changeDateMutation.isPending}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<Button variant="outline" size="sm" onClick={() => setServiceWriterDialogOpen(true)}>
|
||||
<UserCog className="size-4" />
|
||||
<span className="hidden sm:inline">Service Writer</span>
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" size="sm" onClick={() => setSalesPersonDialogOpen(true)}>
|
||||
<UserCheck className="size-4" />
|
||||
<span className="hidden sm:inline">Sales Person</span>
|
||||
</Button>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Ellipsis className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<EmployeePickerDialog
|
||||
open={serviceWriterDialogOpen}
|
||||
onOpenChange={setServiceWriterDialogOpen}
|
||||
title="Change Service Writer"
|
||||
description="Search and select an employee to assign as service writer."
|
||||
employees={employees}
|
||||
loading={employeesLoading}
|
||||
isPending={changeServiceWriterMutation.isPending}
|
||||
onSelect={(id) => changeServiceWriterMutation.mutate(id)}
|
||||
/>
|
||||
|
||||
<EmployeePickerDialog
|
||||
open={salesPersonDialogOpen}
|
||||
onOpenChange={setSalesPersonDialogOpen}
|
||||
title="Change Sales Person"
|
||||
description="Search and select an employee to assign as sales person."
|
||||
employees={employees}
|
||||
loading={employeesLoading}
|
||||
isPending={changeSalesPersonMutation.isPending}
|
||||
onSelect={(id) => changeSalesPersonMutation.mutate(id)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useContext, useState, useCallback } from "react"
|
||||
import type { JobCardStatus } from "./job-card.schema"
|
||||
|
||||
type JobCardContextValue = {
|
||||
id: string
|
||||
label: string
|
||||
status: JobCardStatus
|
||||
setStatus: (status: JobCardStatus) => void
|
||||
}
|
||||
|
||||
const JobCardContext = createContext<JobCardContextValue | null>(null)
|
||||
|
||||
export function JobCardProvider({
|
||||
jobCard,
|
||||
children,
|
||||
}: {
|
||||
jobCard: { id: string; label: string; status: JobCardStatus }
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const [status, setStatusState] = useState<JobCardStatus>(jobCard.status)
|
||||
|
||||
const setStatus = useCallback((newStatus: JobCardStatus) => {
|
||||
setStatusState(newStatus)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<JobCardContext.Provider value={{ id: jobCard.id, label: jobCard.label, status, setStatus }}>
|
||||
{children}
|
||||
</JobCardContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useJobCard() {
|
||||
return useContext(JobCardContext)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
"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,
|
||||
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 {
|
||||
jobCardFormSchema,
|
||||
type JobCardFormValues,
|
||||
TAX_INCLUSIVE_OPTIONS,
|
||||
DISCOUNT_TYPE_OPTIONS,
|
||||
DISCOUNT_AT_OPTIONS,
|
||||
} from "./job-card.schema"
|
||||
import { JOB_CARD_ROUTES, CUSTOMER_ROUTES, VEHICLE_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type JobCardFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: JobCardFormValues = {
|
||||
title: "",
|
||||
customer: null,
|
||||
vehicle: null,
|
||||
status: "draft",
|
||||
tax_inclusive: "Tax Inclusive",
|
||||
discount_type: "no",
|
||||
discount_at: "inclusive_of_tax",
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): JobCardFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
|
||||
return {
|
||||
title: d.title || "",
|
||||
customer: toRelation(d.customer_id, d.customer_name),
|
||||
vehicle: toRelation(d.vehicle_id, d.vehicle_name),
|
||||
status: d.status || "draft",
|
||||
tax_inclusive: d.tax_inclusive || "Tax Inclusive",
|
||||
discount_type: d.discount_type || "no",
|
||||
discount_at: d.discount_at || "inclusive_of_tax",
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: JobCardFormValues) {
|
||||
return {
|
||||
title: values.title,
|
||||
customer_id: toId(values.customer),
|
||||
vehicle_id: toId(values.vehicle),
|
||||
status: values.status || undefined,
|
||||
tax_inclusive: values.tax_inclusive || undefined,
|
||||
discount_type: values.discount_type || undefined,
|
||||
discount_at: values.discount_at || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared mapOption for async selects ──
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.name,
|
||||
})
|
||||
|
||||
const mapCustomerOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: [item.first_name, item.last_name].filter(Boolean).join(" "),
|
||||
})
|
||||
|
||||
const mapVehicleOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: [item.year, item.make_name, item.model_name].filter(Boolean).join(" "),
|
||||
})
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function JobCardForm({ resourceId, initialData, onSuccess }: JobCardFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<JobCardFormValues, any>({
|
||||
schema: jobCardFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
queryKey: [JOB_CARD_ROUTES.BY_ID, resourceId],
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: JobCardFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = (isEditing && resourceId
|
||||
? api.jobCards.update(resourceId, payload)
|
||||
: api.jobCards.create(payload)) as Promise<any>
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating job card..." : "Creating job card...",
|
||||
success: isEditing ? "Job card updated successfully" : "Job card created successfully",
|
||||
error: isEditing ? "Failed to update job card" : "Failed to create job card",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update job card" : "Failed to create job card"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextField name="title" label="Title" placeholder="Job Card 001" required />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="customer"
|
||||
label="Customer"
|
||||
placeholder="Select customer"
|
||||
queryKey={[CUSTOMER_ROUTES.INDEX]}
|
||||
listFn={() => api.customers.list()}
|
||||
mapOption={mapCustomerOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle"
|
||||
label="Vehicle"
|
||||
placeholder="Select vehicle"
|
||||
queryKey={[VEHICLE_ROUTES.INDEX]}
|
||||
listFn={() => api.vehicles.list()}
|
||||
mapOption={mapVehicleOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<RhfSelectField
|
||||
name="tax_inclusive"
|
||||
label="Tax"
|
||||
placeholder="Select tax type"
|
||||
options={TAX_INCLUSIVE_OPTIONS}
|
||||
/>
|
||||
<RhfSelectField
|
||||
name="discount_type"
|
||||
label="Discount Type"
|
||||
placeholder="Select discount type"
|
||||
options={DISCOUNT_TYPE_OPTIONS}
|
||||
/>
|
||||
<RhfSelectField
|
||||
name="discount_at"
|
||||
label="Discount At"
|
||||
placeholder="Select discount at"
|
||||
options={DISCOUNT_AT_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
{isEditing ? <Save /> : <Plus />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Job Card" : "Create Job Card")}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import {
|
||||
ClipboardList,
|
||||
Calendar,
|
||||
Hash,
|
||||
Users,
|
||||
Car,
|
||||
Building2,
|
||||
Gauge,
|
||||
Clock,
|
||||
UserCheck,
|
||||
Briefcase,
|
||||
Receipt,
|
||||
DollarSign,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
|
||||
type JobCardData = {
|
||||
id?: number
|
||||
title?: string
|
||||
status?: string
|
||||
check_in_date?: string
|
||||
km_in?: number
|
||||
tax_inclusive?: string
|
||||
discount_type?: string
|
||||
discount_at?: string
|
||||
customer_id?: number
|
||||
customer_name?: string
|
||||
vehicle_id?: number
|
||||
vehicle_name?: string
|
||||
department_id?: number
|
||||
department_name?: string
|
||||
sales_person_id?: number
|
||||
sales_person_name?: string
|
||||
service_writer_id?: number
|
||||
service_writer_name?: string
|
||||
purchase_orders_count?: number
|
||||
bills_count?: number
|
||||
expenses_count?: number
|
||||
tasks_count?: number
|
||||
appointments_count?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
type JobCardGeneralInfoProps = {
|
||||
jobCard: JobCardData
|
||||
}
|
||||
|
||||
function InfoItem({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value?: string | 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 || <span className="text-muted-foreground">—</span>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const statusColorMap: Record<string, string> = {
|
||||
draft: "secondary",
|
||||
check_in: "default",
|
||||
in_progress: "default",
|
||||
completed: "default",
|
||||
invoiced: "outline",
|
||||
cancelled: "destructive",
|
||||
}
|
||||
|
||||
export function JobCardGeneralInfo({ jobCard }: JobCardGeneralInfoProps) {
|
||||
const formatStatus = (status?: string) => {
|
||||
if (!status) return null
|
||||
return status
|
||||
.split("_")
|
||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Job Card Details */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<ClipboardList className="size-4" />
|
||||
Job Card Details
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{jobCard.title && (
|
||||
<Badge variant="secondary">{jobCard.title}</Badge>
|
||||
)}
|
||||
{jobCard.status && (
|
||||
<Badge variant={statusColorMap[jobCard.status] as any ?? "outline"}>
|
||||
{formatStatus(jobCard.status)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Calendar}
|
||||
label="Check-in Date"
|
||||
value={jobCard.check_in_date}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Gauge}
|
||||
label="KM In"
|
||||
value={jobCard.km_in ? Number(jobCard.km_in).toLocaleString() : null}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Clock}
|
||||
label="Created"
|
||||
value={jobCard.created_at ? new Date(jobCard.created_at).toLocaleDateString() : null}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Clock}
|
||||
label="Updated"
|
||||
value={jobCard.updated_at ? new Date(jobCard.updated_at).toLocaleDateString() : null}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Related Information */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Users className="size-4" />
|
||||
Related Information
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Users}
|
||||
label="Customer"
|
||||
value={jobCard.customer_name}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Car}
|
||||
label="Vehicle"
|
||||
value={jobCard.vehicle_name}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Building2}
|
||||
label="Department"
|
||||
value={jobCard.department_name}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Briefcase}
|
||||
label="Sales Person"
|
||||
value={jobCard.sales_person_name}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={UserCheck}
|
||||
label="Service Writer"
|
||||
value={jobCard.service_writer_name}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Tax & Discount Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<DollarSign className="size-4" />
|
||||
Tax & Discount Settings
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Receipt}
|
||||
label="Tax Inclusive"
|
||||
value={jobCard.tax_inclusive}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={DollarSign}
|
||||
label="Discount Type"
|
||||
value={formatStatus(jobCard.discount_type)}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={DollarSign}
|
||||
label="Discount At"
|
||||
value={formatStatus(jobCard.discount_at)}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Counts */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Hash className="size-4" />
|
||||
Related Counts
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Receipt}
|
||||
label="Purchase Orders"
|
||||
value={String(jobCard.purchase_orders_count ?? 0)}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Receipt}
|
||||
label="Bills"
|
||||
value={String(jobCard.bills_count ?? 0)}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={DollarSign}
|
||||
label="Expenses"
|
||||
value={String(jobCard.expenses_count ?? 0)}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={ClipboardList}
|
||||
label="Tasks"
|
||||
value={String(jobCard.tasks_count ?? 0)}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Calendar}
|
||||
label="Appointments"
|
||||
value={String(jobCard.appointments_count ?? 0)}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client"
|
||||
|
||||
import { z } from "zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Plus } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { FieldGroup } from "@/shared/components/ui/field"
|
||||
import { Rhform, RhfTextareaField } from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
|
||||
const schema = z.object({
|
||||
recommendation: z.string().min(1, "Recommendation is required"),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
type JobCardRecommendationFormProps = {
|
||||
jobCardId: string
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function JobCardRecommendationForm({ jobCardId, onSuccess }: JobCardRecommendationFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { recommendation: "" },
|
||||
})
|
||||
|
||||
const handleSubmit = async (values: FormValues) => {
|
||||
try {
|
||||
await api.jobCards.addShopRecommendation(jobCardId, {
|
||||
recommendation: values.recommendation,
|
||||
})
|
||||
toast.success("Shop recommendation added")
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
} catch {
|
||||
toast.error("Failed to add shop recommendation")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
<RhfTextareaField
|
||||
name="recommendation"
|
||||
label="Shop Recommendation"
|
||||
placeholder="Enter shop recommendation..."
|
||||
rows={4}
|
||||
required
|
||||
/>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
<Plus />
|
||||
{form.formState.isSubmitting ? "Adding..." : "Add Recommendation"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client"
|
||||
|
||||
import { z } from "zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Plus } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { FieldGroup } from "@/shared/components/ui/field"
|
||||
import { Rhform, RhfTextareaField } from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
|
||||
const schema = z.object({
|
||||
remark: z.string().min(1, "Remark is required"),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
type JobCardRemarkFormProps = {
|
||||
jobCardId: string
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function JobCardRemarkForm({ jobCardId, onSuccess }: JobCardRemarkFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { remark: "" },
|
||||
})
|
||||
|
||||
const handleSubmit = async (values: FormValues) => {
|
||||
try {
|
||||
await api.jobCards.addCustomerRemark(jobCardId, {
|
||||
remark: values.remark,
|
||||
})
|
||||
toast.success("Customer remark added")
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
} catch {
|
||||
toast.error("Failed to add customer remark")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
<RhfTextareaField
|
||||
name="remark"
|
||||
label="Customer Remark"
|
||||
placeholder="Enter customer remark..."
|
||||
rows={4}
|
||||
required
|
||||
/>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
<Plus />
|
||||
{form.formState.isSubmitting ? "Adding..." : "Add Remark"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"use client"
|
||||
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { toast } from "sonner"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useJobCard } from "./job-card-context"
|
||||
import { JOB_CARD_STATUSES, type JobCardStatus } from "./job-card.schema"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/shared/components/ui/tooltip"
|
||||
import {
|
||||
CircleDot,
|
||||
LogIn,
|
||||
Loader,
|
||||
Pause,
|
||||
PackageCheck,
|
||||
CheckCircle2,
|
||||
} from "lucide-react"
|
||||
|
||||
// ── Status icon mapping ──
|
||||
|
||||
const STATUS_ICONS: Record<JobCardStatus, React.ComponentType<{ className?: string }>> = {
|
||||
draft: CircleDot,
|
||||
check_in: LogIn,
|
||||
in_progress: Loader,
|
||||
on_hold: Pause,
|
||||
ready_to_deliver: PackageCheck,
|
||||
delivered: CheckCircle2,
|
||||
}
|
||||
|
||||
// ── Component ──
|
||||
|
||||
type JobCardStatusStepperProps = {
|
||||
jobCardId: string
|
||||
}
|
||||
|
||||
export function JobCardStatusStepper({ jobCardId }: JobCardStatusStepperProps) {
|
||||
const api = useAuthApi()
|
||||
const jobCard = useJobCard()
|
||||
const currentStatus = jobCard?.status ?? "draft"
|
||||
|
||||
const currentIndex = JOB_CARD_STATUSES.findIndex((s) => s.value === currentStatus)
|
||||
|
||||
const { mutate, isPending, variables } = useMutation({
|
||||
mutationFn: async (status: JobCardStatus) => {
|
||||
const promise = api.jobCards.changeStatus(jobCardId, { status })
|
||||
toast.promise(promise, {
|
||||
loading: "Updating status...",
|
||||
success: "Status updated successfully",
|
||||
error: "Failed to update status",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: (_data, status) => {
|
||||
jobCard?.setStatus(status)
|
||||
},
|
||||
})
|
||||
|
||||
const handleClick = (status: JobCardStatus, index: number) => {
|
||||
if (isPending) return
|
||||
if (status === currentStatus) return
|
||||
mutate(status)
|
||||
}
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className="flex items-center gap-0 overflow-x-auto">
|
||||
{JOB_CARD_STATUSES.map((step, index) => {
|
||||
const Icon = STATUS_ICONS[step.value]
|
||||
const isActive = step.value === currentStatus
|
||||
const isCompleted = index < currentIndex
|
||||
const isTransitioning = isPending && variables === step.value
|
||||
const isClickable = !isPending && step.value !== currentStatus
|
||||
|
||||
return (
|
||||
<div key={step.value} className="flex items-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleClick(step.value, index)}
|
||||
disabled={!isClickable}
|
||||
className={cn(
|
||||
"relative flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-all",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
isActive && "bg-primary text-primary-foreground shadow-sm",
|
||||
isCompleted && !isActive && "bg-primary/10 text-primary hover:bg-primary/20",
|
||||
!isActive && !isCompleted && "bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground",
|
||||
isTransitioning && "animate-pulse",
|
||||
!isClickable && !isActive && "opacity-60",
|
||||
isClickable && "cursor-pointer",
|
||||
)}
|
||||
>
|
||||
<Icon className={cn(
|
||||
"size-4 shrink-0",
|
||||
isTransitioning && "animate-spin"
|
||||
)} />
|
||||
<span className="hidden whitespace-nowrap sm:inline">{step.label}</span>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{isActive ? `Current: ${step.label}` : `Change to ${step.label}`}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{/* Connector line */}
|
||||
{index < JOB_CARD_STATUSES.length - 1 && (
|
||||
<div
|
||||
className={cn(
|
||||
"mx-1 h-0.5 w-4 shrink-0 transition-colors",
|
||||
index < currentIndex ? "bg-primary/40" : "bg-border"
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
// ── Job Card Statuses ──
|
||||
|
||||
export const JOB_CARD_STATUSES = [
|
||||
{ value: "draft", label: "Draft" },
|
||||
{ value: "check_in", label: "Check In" },
|
||||
{ value: "in_progress", label: "In Progress" },
|
||||
{ value: "on_hold", label: "On Hold" },
|
||||
{ value: "ready_to_deliver", label: "Ready to Deliver" },
|
||||
{ value: "delivered", label: "Delivered" },
|
||||
] as const
|
||||
|
||||
export type JobCardStatus = (typeof JOB_CARD_STATUSES)[number]["value"]
|
||||
|
||||
const TAX_INCLUSIVE_OPTIONS = [
|
||||
{ value: "Tax Inclusive", label: "Tax Inclusive" },
|
||||
{ value: "Tax Exclusive", label: "Tax Exclusive" },
|
||||
]
|
||||
|
||||
const DISCOUNT_TYPE_OPTIONS = [
|
||||
{ value: "no", label: "No Discount" },
|
||||
{ value: "transaction_level", label: "Transaction Level" },
|
||||
]
|
||||
|
||||
const DISCOUNT_AT_OPTIONS = [
|
||||
{ value: "inclusive_of_tax", label: "Inclusive of Tax" },
|
||||
{ value: "exclusive_of_tax", label: "Exclusive of Tax" },
|
||||
]
|
||||
|
||||
const jobCardFormSchema = z.object({
|
||||
// ── Required fields ──
|
||||
title: z.string().min(1, "Title is required"),
|
||||
|
||||
// ── Relations ──
|
||||
customer: relationFieldSchema,
|
||||
vehicle: relationFieldSchema,
|
||||
|
||||
// ── Settings ──
|
||||
status: z.string().optional(),
|
||||
tax_inclusive: z.string().optional(),
|
||||
discount_type: z.string().optional(),
|
||||
discount_at: z.string().optional(),
|
||||
})
|
||||
|
||||
type JobCardFormValues = z.infer<typeof jobCardFormSchema>
|
||||
|
||||
export { jobCardFormSchema, relationFieldSchema, TAX_INCLUSIVE_OPTIONS, DISCOUNT_TYPE_OPTIONS, DISCOUNT_AT_OPTIONS }
|
||||
export type { JobCardFormValues }
|
||||
@@ -0,0 +1,201 @@
|
||||
"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,
|
||||
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 {
|
||||
paymentReceivedFormSchema,
|
||||
type PaymentReceivedFormValues,
|
||||
} from "./payment-received.schema"
|
||||
import { PAYMENT_ROUTES, CUSTOMER_ROUTES, JOB_CARD_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type PaymentReceivedFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: PaymentReceivedFormValues = {
|
||||
job_card: null,
|
||||
payment_mode: null,
|
||||
customer: null,
|
||||
amount_received: "",
|
||||
payment_number: "",
|
||||
payment_date: "",
|
||||
note: "",
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): PaymentReceivedFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
|
||||
return {
|
||||
job_card: toRelation(d.job_card_id, d.job_card_name),
|
||||
payment_mode: toRelation(d.payment_mode_id, d.payment_mode_name),
|
||||
customer: toRelation(d.customer_id, d.customer_name),
|
||||
amount_received: d.amount_received ? String(d.amount_received) : "",
|
||||
payment_number: d.payment_number || "",
|
||||
payment_date: d.payment_date || "",
|
||||
note: d.note || "",
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: PaymentReceivedFormValues) {
|
||||
return {
|
||||
job_card_id: toId(values.job_card),
|
||||
payment_mode_id: toId(values.payment_mode),
|
||||
customer_id: toId(values.customer),
|
||||
amount_received: values.amount_received,
|
||||
payment_number: values.payment_number || undefined,
|
||||
payment_date: values.payment_date,
|
||||
note: values.note || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared mapOption for async selects ──
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.name || item.title,
|
||||
})
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function PaymentReceivedForm({ resourceId, initialData, onSuccess }: PaymentReceivedFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<PaymentReceivedFormValues, any>({
|
||||
schema: paymentReceivedFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: PaymentReceivedFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = isEditing && resourceId
|
||||
? api.payments.updateReceived(resourceId, payload as any)
|
||||
: api.payments.createReceived(payload as any)
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating payment..." : "Recording payment...",
|
||||
success: isEditing ? "Payment updated successfully" : "Payment recorded successfully",
|
||||
error: isEditing ? "Failed to update payment" : "Failed to record payment",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update payment" : "Failed to record payment"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="customer"
|
||||
label="Customer"
|
||||
placeholder="Select customer"
|
||||
queryKey={[CUSTOMER_ROUTES.INDEX]}
|
||||
listFn={() => api.customers.list()}
|
||||
mapOption={(item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.first_name
|
||||
? `${item.first_name} ${item.last_name || ""}`.trim()
|
||||
: item.name || `#${item.id}`,
|
||||
})}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="job_card"
|
||||
label="Job Card"
|
||||
placeholder="Select job card"
|
||||
queryKey={[JOB_CARD_ROUTES.INDEX]}
|
||||
listFn={() => api.jobCards.list()}
|
||||
mapOption={(item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.job_card_number || item.name || `#${item.id}`,
|
||||
})}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField
|
||||
name="amount_received"
|
||||
label="Amount Received"
|
||||
placeholder="0.00"
|
||||
type="number"
|
||||
required
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="payment_mode"
|
||||
label="Payment Mode"
|
||||
placeholder="Select payment mode"
|
||||
queryKey={[PAYMENT_ROUTES.MODES]}
|
||||
listFn={() => api.payments.listModes()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField
|
||||
name="payment_number"
|
||||
label="Payment Number"
|
||||
placeholder="PAY-001"
|
||||
/>
|
||||
<RhfTextField
|
||||
name="payment_date"
|
||||
label="Payment Date"
|
||||
type="date"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<RhfTextareaField name="note" label="Note" rows={3} placeholder="Add any notes about this payment..." />
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
{isEditing ? <Save /> : <Plus />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Recording...")
|
||||
: (isEditing ? "Update Payment" : "Record Payment")}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const paymentReceivedFormSchema = z.object({
|
||||
// ── Relations ──
|
||||
job_card: relationFieldSchema,
|
||||
payment_mode: relationFieldSchema,
|
||||
customer: relationFieldSchema,
|
||||
|
||||
// ── Payment info ──
|
||||
amount_received: z.string().min(1, "Amount is required"),
|
||||
payment_number: z.string().optional(),
|
||||
payment_date: z.string().min(1, "Payment date is required"),
|
||||
note: z.string().optional(),
|
||||
})
|
||||
|
||||
type PaymentReceivedFormValues = z.infer<typeof paymentReceivedFormSchema>
|
||||
|
||||
export { paymentReceivedFormSchema, relationFieldSchema }
|
||||
export type { PaymentReceivedFormValues }
|
||||
@@ -0,0 +1,97 @@
|
||||
"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,
|
||||
} 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 { holidayYearFormSchema, type HolidayYearFormValues } from "./holiday-year.schema"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type HolidayYearFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: HolidayYearFormValues = {
|
||||
year: new Date().getFullYear(),
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): HolidayYearFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
return {
|
||||
year: d.year ?? new Date().getFullYear(),
|
||||
}
|
||||
}
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function HolidayYearForm({ resourceId, initialData, onSuccess }: HolidayYearFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form } = useResourceForm<HolidayYearFormValues, any>({
|
||||
schema: holidayYearFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId: null,
|
||||
initialData,
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: HolidayYearFormValues) => {
|
||||
const promise = api.holidayYears.create({ year: values.year })
|
||||
toast.promise(promise, {
|
||||
loading: "Creating holiday year...",
|
||||
success: "Holiday year created successfully",
|
||||
error: "Failed to create holiday year",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>Failed to create holiday year</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextField
|
||||
name="year"
|
||||
label="Year"
|
||||
placeholder="e.g. 2026"
|
||||
type="number"
|
||||
required
|
||||
/>
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
<Plus />
|
||||
{isPending ? "Creating..." : "Create Holiday Year"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const holidayYearFormSchema = z.object({
|
||||
year: z.coerce.number().min(1900, "Year is required").max(2100, "Invalid year"),
|
||||
})
|
||||
|
||||
export type HolidayYearFormValues = z.infer<typeof holidayYearFormSchema>
|
||||
@@ -0,0 +1,139 @@
|
||||
"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,
|
||||
RhfCheckboxField,
|
||||
} 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 { taxFormSchema, type TaxFormValues } from "./tax.schema"
|
||||
import { TAX_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type TaxFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: TaxFormValues = {
|
||||
title: "",
|
||||
note: "",
|
||||
rate: 0,
|
||||
is_default: false,
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): TaxFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
return {
|
||||
title: d.title ?? "",
|
||||
note: d.note ?? "",
|
||||
rate: d.rate ? Number(d.rate) : 0,
|
||||
is_default: d.is_default ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: TaxFormValues) {
|
||||
return {
|
||||
title: values.title,
|
||||
note: values.note || undefined,
|
||||
rate: values.rate,
|
||||
is_default: values.is_default,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function TaxForm({ resourceId, initialData, onSuccess }: TaxFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<TaxFormValues, any>({
|
||||
schema: taxFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
queryKey: [TAX_ROUTES.BY_ID, resourceId],
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: TaxFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = isEditing && resourceId
|
||||
? api.taxes.update(resourceId, payload)
|
||||
: api.taxes.create(payload)
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating tax..." : "Creating tax...",
|
||||
success: isEditing ? "Tax updated successfully" : "Tax created successfully",
|
||||
error: isEditing ? "Failed to update tax" : "Failed to create tax",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update tax" : "Failed to create tax"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextField
|
||||
name="title"
|
||||
label="Title"
|
||||
placeholder="e.g. VAT"
|
||||
required
|
||||
/>
|
||||
<RhfTextField
|
||||
name="rate"
|
||||
label="Rate (%)"
|
||||
placeholder="e.g. 18"
|
||||
type="number"
|
||||
required
|
||||
/>
|
||||
<RhfTextareaField
|
||||
name="note"
|
||||
label="Note"
|
||||
placeholder="Optional description"
|
||||
rows={3}
|
||||
/>
|
||||
<RhfCheckboxField
|
||||
name="is_default"
|
||||
label="Set as default"
|
||||
/>
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
{isEditing ? <Save /> : <Plus />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Tax" : "Create Tax")}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const taxFormSchema = z.object({
|
||||
title: z.string().min(1, "Title is required"),
|
||||
note: z.string().optional(),
|
||||
rate: z.coerce.number().min(0, "Rate must be 0 or more"),
|
||||
is_default: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export type TaxFormValues = z.infer<typeof taxFormSchema>
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client"
|
||||
|
||||
import { z } from "zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Plus } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { FieldGroup } from "@/shared/components/ui/field"
|
||||
import { Rhform, RhfTextField, type InlineCreateFormProps } from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
|
||||
const schema = z.object({
|
||||
title: z.string().min(1, "Title is required"),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
export function DocumentTypeInlineForm({ onSuccess }: InlineCreateFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { title: "" },
|
||||
})
|
||||
|
||||
const handleSubmit = async (values: FormValues) => {
|
||||
try {
|
||||
const result = await api.vehicleDocuments.createDocumentType({ title: values.title })
|
||||
toast.success("Document type created")
|
||||
form.reset()
|
||||
const item = (result as any)?.data ?? result
|
||||
onSuccess({ value: String(item.id), label: item.title ?? item.name ?? String(item.id) })
|
||||
} catch {
|
||||
toast.error("Failed to create document type")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
<RhfTextField
|
||||
name="title"
|
||||
label="Title"
|
||||
placeholder="e.g. Registration Certificate"
|
||||
required
|
||||
/>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
<Plus />
|
||||
{form.formState.isSubmitting ? "Creating..." : "Create Document Type"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"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 } 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 { mileageFormSchema, type MileageFormValues } from "./mileage.schema"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type MileageFormProps = {
|
||||
vehicleId: string
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: MileageFormValues = {
|
||||
mileage: 0,
|
||||
date: "",
|
||||
time: "",
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): MileageFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
return {
|
||||
mileage: d.mileage ?? 0,
|
||||
date: d.date || "",
|
||||
time: d.time || "",
|
||||
}
|
||||
}
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function MileageForm({ vehicleId, resourceId, initialData, onSuccess }: MileageFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<MileageFormValues, any>({
|
||||
schema: mileageFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: MileageFormValues) => {
|
||||
const payload = { mileage: values.mileage, date: values.date, time: values.time }
|
||||
const promise = isEditing && resourceId
|
||||
? api.vehicleDocuments.updateMileage(resourceId, payload as any)
|
||||
: api.vehicleDocuments.createMileage({ vehicle_id: Number(vehicleId), ...payload } as any)
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating mileage..." : "Adding mileage...",
|
||||
success: isEditing ? "Mileage updated successfully" : "Mileage added successfully",
|
||||
error: isEditing ? "Failed to update mileage" : "Failed to add mileage",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update mileage" : "Failed to add mileage"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfTextField
|
||||
name="mileage"
|
||||
label="Mileage"
|
||||
placeholder="e.g. 50000"
|
||||
type="number"
|
||||
required
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField
|
||||
name="date"
|
||||
label="Date"
|
||||
type="date"
|
||||
required
|
||||
/>
|
||||
<RhfTextField
|
||||
name="time"
|
||||
label="Time"
|
||||
type="time"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={isPending} className="w-full">
|
||||
{isPending ? null : isEditing ? <Save /> : <Plus />}
|
||||
{isPending ? "Saving..." : isEditing ? "Update Mileage" : "Add Mileage"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const mileageFormSchema = z.object({
|
||||
mileage: z.coerce.number({ message: "Mileage is required" }).min(0, "Mileage must be 0 or greater"),
|
||||
date: z.string().min(1, "Date is required"),
|
||||
time: z.string().min(1, "Time is required"),
|
||||
})
|
||||
|
||||
export type MileageFormValues = z.infer<typeof mileageFormSchema>
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
|
||||
|
||||
type VehicleActionsProps = {
|
||||
vehicleId: string
|
||||
}
|
||||
|
||||
export function VehicleActions({ vehicleId }: VehicleActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/sales/vehicles/${vehicleId}/edit`)
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
await api.vehicles.destroy(vehicleId)
|
||||
router.push("/sales/vehicles")
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Ellipsis className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useContext } from "react"
|
||||
|
||||
type VehicleContextValue = {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const VehicleContext = createContext<VehicleContextValue | null>(null)
|
||||
|
||||
export function VehicleProvider({ vehicle, children }: { vehicle: VehicleContextValue; children: React.ReactNode }) {
|
||||
return <VehicleContext.Provider value={vehicle}>{children}</VehicleContext.Provider>
|
||||
}
|
||||
|
||||
export function useVehicle() {
|
||||
return useContext(VehicleContext)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
"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,
|
||||
RhfTextareaField,
|
||||
RhfAsyncSelectField,
|
||||
RhfDocumentField,
|
||||
} from "@/shared/components/form"
|
||||
import { DocumentTypeInlineForm } from "./inline-forms/document-type-inline-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 { vehicleDocumentFormSchema, type VehicleDocumentFormValues } from "./vehicle-document.schema"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type VehicleDocumentFormProps = {
|
||||
vehicleId: string
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: VehicleDocumentFormValues = {
|
||||
document_type: null,
|
||||
file: null,
|
||||
note: "",
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.name ?? item.title ?? String(item.id),
|
||||
})
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
function mapToFormValues(data: unknown): VehicleDocumentFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
|
||||
return {
|
||||
document_type: toRelation(d.document_type_id, d.document_type?.name ?? d.document_type?.title),
|
||||
file: null,
|
||||
note: d.note || "",
|
||||
}
|
||||
}
|
||||
|
||||
function mapToPayload(values: VehicleDocumentFormValues, vehicleId: string) {
|
||||
return {
|
||||
vehicle_id: Number(vehicleId),
|
||||
document_type_id: toId(values.document_type),
|
||||
file: values.file instanceof File ? values.file : undefined,
|
||||
note: values.note || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function VehicleDocumentForm({ vehicleId, resourceId, initialData, onSuccess }: VehicleDocumentFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<VehicleDocumentFormValues, any>({
|
||||
schema: vehicleDocumentFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: VehicleDocumentFormValues) => {
|
||||
const payload = mapToPayload(values, vehicleId)
|
||||
const promise = isEditing && resourceId
|
||||
? api.vehicleDocuments.updateDocument(resourceId, payload)
|
||||
: api.vehicleDocuments.createDocument(payload)
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating document..." : "Uploading document...",
|
||||
success: isEditing ? "Document updated successfully" : "Document uploaded successfully",
|
||||
error: isEditing ? "Failed to update document" : "Failed to upload document",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update document" : "Failed to upload document"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<RhfAsyncSelectField
|
||||
name="document_type"
|
||||
label="Document Type"
|
||||
placeholder="Select document type"
|
||||
queryKey={["document-types"]}
|
||||
listFn={() => api.vehicleDocuments.listDocumentTypes()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <DocumentTypeInlineForm {...props} />}
|
||||
createLabel="Document Type"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
|
||||
<RhfDocumentField
|
||||
name="file"
|
||||
label="Document File"
|
||||
required
|
||||
/>
|
||||
|
||||
<RhfTextareaField
|
||||
name="note"
|
||||
label="Note"
|
||||
placeholder="Optional notes about this document"
|
||||
/>
|
||||
|
||||
<Button type="submit" disabled={isPending} className="w-full">
|
||||
{isPending ? null : isEditing ? <Save /> : <Plus />}
|
||||
{isPending ? "Saving..." : isEditing ? "Update Document" : "Upload Document"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const relationFieldSchema = z.object({ value: z.string(), label: z.string() }).nullable()
|
||||
|
||||
export const vehicleDocumentFormSchema = z.object({
|
||||
document_type: relationFieldSchema,
|
||||
file: z.instanceof(File, { message: "File is required" }).nullable(),
|
||||
note: z.string().optional(),
|
||||
})
|
||||
|
||||
export type VehicleDocumentFormValues = z.infer<typeof vehicleDocumentFormSchema>
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
RhfTextField,
|
||||
RhfTextareaField,
|
||||
RhfAsyncSelectField,
|
||||
RhfImageField,
|
||||
} from "@/shared/components/form"
|
||||
import { ShopTypeInlineForm } from "./inline-forms/shop-type-inline-form"
|
||||
import { BodyTypeInlineForm } from "./inline-forms/body-type-inline-form"
|
||||
@@ -52,6 +53,7 @@ const DEFAULT_VALUES: VehicleFormValues = {
|
||||
mileage: "",
|
||||
owners_number: "",
|
||||
note: "",
|
||||
image: null,
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
@@ -83,10 +85,11 @@ function mapToFormValues(data: unknown): VehicleFormValues {
|
||||
mileage: d.mileage || "",
|
||||
owners_number: d.owners_number || "",
|
||||
note: d.note || "",
|
||||
image: null,
|
||||
}
|
||||
}
|
||||
|
||||
function mapCreatePayload(values: VehicleFormValues) {
|
||||
function mapToPayload(values: VehicleFormValues) {
|
||||
return {
|
||||
shop_type_id: toId(values.shop_type),
|
||||
vehicle_body_type_id: toId(values.vehicle_body_type),
|
||||
@@ -104,13 +107,7 @@ function mapCreatePayload(values: VehicleFormValues) {
|
||||
mileage: values.mileage || undefined,
|
||||
owners_number: values.owners_number || undefined,
|
||||
note: values.note || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function mapUpdatePayload(values: VehicleFormValues) {
|
||||
return {
|
||||
mileage: values.mileage || undefined,
|
||||
license_plate: values.license_plate || undefined,
|
||||
image: values.image instanceof File ? values.image : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,9 +126,10 @@ export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormP
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: VehicleFormValues) => {
|
||||
const payload = mapToPayload(values)
|
||||
const promise = isEditing && resourceId
|
||||
? api.vehicles.update(resourceId, mapUpdatePayload(values))
|
||||
: api.vehicles.create(mapCreatePayload(values))
|
||||
? api.vehicles.update(resourceId, payload)
|
||||
: api.vehicles.create(payload)
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating vehicle..." : "Creating vehicle...",
|
||||
success: isEditing ? "Vehicle updated successfully" : "Vehicle created successfully",
|
||||
@@ -158,102 +156,97 @@ export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormP
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
{!isEditing && (
|
||||
<>
|
||||
{/* Vehicle identity */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<RhfTextField name="make" label="Make" placeholder="e.g. Toyota" required />
|
||||
<RhfTextField name="model" label="Model" placeholder="e.g. Camry" required />
|
||||
<RhfTextField name="year" label="Year" placeholder="e.g. 2024" required />
|
||||
</div>
|
||||
{/* Vehicle identity */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<RhfTextField name="make" label="Make" placeholder="e.g. Toyota" required />
|
||||
<RhfTextField name="model" label="Model" placeholder="e.g. Camry" required />
|
||||
<RhfTextField name="year" label="Year" placeholder="e.g. 2024" required />
|
||||
</div>
|
||||
|
||||
<RhfTextField name="sub_model" label="Sub Model" placeholder="e.g. LE" />
|
||||
<RhfTextField name="sub_model" label="Sub Model" placeholder="e.g. LE" />
|
||||
|
||||
{/* Associations */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="shop_type"
|
||||
label="Shop Type"
|
||||
placeholder="Select shop type"
|
||||
queryKey={["shop-types"]}
|
||||
listFn={() => api.shopTypes.list()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <ShopTypeInlineForm {...props} />}
|
||||
createLabel="Shop Type"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle_body_type"
|
||||
label="Body Type"
|
||||
placeholder="Select body type"
|
||||
queryKey={["vehicle-body-types"]}
|
||||
listFn={() => api.vehicleAttributes.listBodyTypes()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <BodyTypeInlineForm {...props} />}
|
||||
createLabel="Body Type"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
{/* Associations */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="shop_type"
|
||||
label="Shop Type"
|
||||
placeholder="Select shop type"
|
||||
queryKey={["shop-types"]}
|
||||
listFn={() => api.shopTypes.list()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <ShopTypeInlineForm {...props} />}
|
||||
createLabel="Shop Type"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle_body_type"
|
||||
label="Body Type"
|
||||
placeholder="Select body type"
|
||||
queryKey={["vehicle-body-types"]}
|
||||
listFn={() => api.vehicleAttributes.listBodyTypes()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <BodyTypeInlineForm {...props} />}
|
||||
createLabel="Body Type"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle_fuel_type"
|
||||
label="Fuel Type"
|
||||
placeholder="Select fuel type"
|
||||
queryKey={["vehicle-fuel-types"]}
|
||||
listFn={() => api.vehicleAttributes.listFuelTypes()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <FuelTypeInlineForm {...props} />}
|
||||
createLabel="Fuel Type"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle_transmission"
|
||||
label="Transmission"
|
||||
placeholder="Select transmission"
|
||||
queryKey={["vehicle-transmissions"]}
|
||||
listFn={() => api.vehicleAttributes.listTransmissions()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <TransmissionInlineForm {...props} />}
|
||||
createLabel="Transmission"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle_fuel_type"
|
||||
label="Fuel Type"
|
||||
placeholder="Select fuel type"
|
||||
queryKey={["vehicle-fuel-types"]}
|
||||
listFn={() => api.vehicleAttributes.listFuelTypes()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <FuelTypeInlineForm {...props} />}
|
||||
createLabel="Fuel Type"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle_transmission"
|
||||
label="Transmission"
|
||||
placeholder="Select transmission"
|
||||
queryKey={["vehicle-transmissions"]}
|
||||
listFn={() => api.vehicleAttributes.listTransmissions()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <TransmissionInlineForm {...props} />}
|
||||
createLabel="Transmission"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle_color"
|
||||
label="Color"
|
||||
placeholder="Select color"
|
||||
queryKey={["vehicle-colors"]}
|
||||
listFn={() => api.vehicleAttributes.listColors()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <ColorInlineForm {...props} />}
|
||||
createLabel="Color"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfTextField name="vin_number" label="VIN Number" placeholder="e.g. 1HGBH41JXMN109186" />
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="vehicle_color"
|
||||
label="Color"
|
||||
placeholder="Select color"
|
||||
queryKey={["vehicle-colors"]}
|
||||
listFn={() => api.vehicleAttributes.listColors()}
|
||||
mapOption={mapLookupOption}
|
||||
createForm={(props) => <ColorInlineForm {...props} />}
|
||||
createLabel="Color"
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfTextField name="vin_number" label="VIN Number" placeholder="e.g. 1HGBH41JXMN109186" />
|
||||
</div>
|
||||
|
||||
{/* Technical specs */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="engine_size" label="Engine Size" placeholder="e.g. 2.5L" />
|
||||
<RhfTextField name="drivetrain" label="Drivetrain" placeholder="e.g. FWD" />
|
||||
</div>
|
||||
{/* Technical specs */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="engine_size" label="Engine Size" placeholder="e.g. 2.5L" />
|
||||
<RhfTextField name="drivetrain" label="Drivetrain" placeholder="e.g. FWD" />
|
||||
</div>
|
||||
|
||||
<RhfTextField name="owners_number" label="Number of Owners" placeholder="e.g. 1" />
|
||||
</>
|
||||
)}
|
||||
<RhfTextField name="owners_number" label="Number of Owners" placeholder="e.g. 1" />
|
||||
|
||||
{/* Editable in both create and update */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="license_plate" label="License Plate" placeholder="e.g. ABC-123" />
|
||||
<RhfTextField name="mileage" label="Mileage" placeholder="e.g. 10000" />
|
||||
</div>
|
||||
|
||||
{!isEditing && (
|
||||
<RhfTextareaField name="note" label="Notes" rows={3} />
|
||||
)}
|
||||
<RhfImageField name="image" label="Image" />
|
||||
|
||||
<RhfTextareaField name="note" label="Notes" rows={3} />
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
{isEditing ? <Save /> : <Plus />}
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import {
|
||||
Car,
|
||||
Calendar,
|
||||
Gauge,
|
||||
Fuel,
|
||||
Cog,
|
||||
Palette,
|
||||
Hash,
|
||||
FileText,
|
||||
Users,
|
||||
Shield,
|
||||
Wrench,
|
||||
CircleDot,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
|
||||
type VehicleData = {
|
||||
id?: number
|
||||
make?: string
|
||||
model?: string
|
||||
year?: string
|
||||
sub_model?: string
|
||||
license_plate?: string
|
||||
vin_number?: string
|
||||
engine_number?: string | null
|
||||
engine_size?: string
|
||||
drivetrain?: string
|
||||
mileage?: string
|
||||
owners_number?: string
|
||||
front_tire_size?: string | null
|
||||
rear_tire_size?: string | null
|
||||
note?: string
|
||||
image_url?: string | null
|
||||
reg_date?: string | null
|
||||
mfg_date?: string | null
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
shop_type?: { id?: number; title?: string }
|
||||
vehicle_body_type?: { id?: number; title?: string }
|
||||
vehicle_fuel_type?: { id?: number; title?: string }
|
||||
vehicle_transmission?: { id?: number; title?: string }
|
||||
vehicle_color?: { id?: number; title?: string; code?: string }
|
||||
}
|
||||
|
||||
type VehicleGeneralInfoProps = {
|
||||
vehicle: VehicleData
|
||||
}
|
||||
|
||||
function InfoItem({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value?: string | 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 || <span className="text-muted-foreground">—</span>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function VehicleGeneralInfo({ vehicle }: VehicleGeneralInfoProps) {
|
||||
return (
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Vehicle Identity */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Car className="size-4" />
|
||||
Vehicle Identity
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary">
|
||||
{[vehicle.make, vehicle.model].filter(Boolean).join(" ") || "Unknown"}
|
||||
</Badge>
|
||||
{vehicle.year && <Badge variant="outline">{vehicle.year}</Badge>}
|
||||
{vehicle.sub_model && (
|
||||
<Badge variant="outline">{vehicle.sub_model}</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Hash}
|
||||
label="License Plate"
|
||||
value={vehicle.license_plate}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Shield}
|
||||
label="VIN Number"
|
||||
value={vehicle.vin_number}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={FileText}
|
||||
label="Engine Number"
|
||||
value={vehicle.engine_number}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Users}
|
||||
label="Number of Owners"
|
||||
value={vehicle.owners_number}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Technical Specifications */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Wrench className="size-4" />
|
||||
Technical Specifications
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{vehicle.vehicle_body_type?.title && (
|
||||
<Badge variant="secondary">{vehicle.vehicle_body_type.title}</Badge>
|
||||
)}
|
||||
{vehicle.vehicle_transmission?.title && (
|
||||
<Badge variant="outline">{vehicle.vehicle_transmission.title}</Badge>
|
||||
)}
|
||||
{vehicle.vehicle_fuel_type?.title && (
|
||||
<Badge variant="outline">{vehicle.vehicle_fuel_type.title}</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Cog}
|
||||
label="Engine Size"
|
||||
value={vehicle.engine_size}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={CircleDot}
|
||||
label="Drivetrain"
|
||||
value={vehicle.drivetrain}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Gauge}
|
||||
label="Mileage"
|
||||
value={vehicle.mileage ? `${Number(vehicle.mileage).toLocaleString()} km` : null}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Fuel}
|
||||
label="Fuel Type"
|
||||
value={vehicle.vehicle_fuel_type?.title}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Appearance & Shop */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Palette className="size-4" />
|
||||
Appearance
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Palette}
|
||||
label="Color"
|
||||
value={vehicle.vehicle_color?.title}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Wrench}
|
||||
label="Shop Type"
|
||||
value={vehicle.shop_type?.title}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={CircleDot}
|
||||
label="Front Tire Size"
|
||||
value={vehicle.front_tire_size}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={CircleDot}
|
||||
label="Rear Tire Size"
|
||||
value={vehicle.rear_tire_size}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Dates & Notes */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Calendar className="size-4" />
|
||||
Dates & Notes
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Calendar}
|
||||
label="Registration Date"
|
||||
value={vehicle.reg_date ? new Date(vehicle.reg_date).toLocaleDateString() : null}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Calendar}
|
||||
label="Manufacturing Date"
|
||||
value={vehicle.mfg_date ? new Date(vehicle.mfg_date).toLocaleDateString() : null}
|
||||
/>
|
||||
</div>
|
||||
{vehicle.note && (
|
||||
<>
|
||||
<Separator />
|
||||
<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">
|
||||
<FileText className="size-4" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-xs text-muted-foreground">Note</span>
|
||||
<p className="text-sm whitespace-pre-wrap">{vehicle.note}</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -30,6 +30,9 @@ export const vehicleFormSchema = z.object({
|
||||
|
||||
// ── Notes ──
|
||||
note: z.string().optional(),
|
||||
|
||||
// ── Image ──
|
||||
image: z.any().optional(),
|
||||
})
|
||||
|
||||
export type VehicleFormValues = z.infer<typeof vehicleFormSchema>
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
"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,
|
||||
} 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 {
|
||||
vendorFormSchema,
|
||||
type VendorFormValues,
|
||||
} from "./vendor.schema"
|
||||
import { VENDOR_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type VendorFormProps = {
|
||||
resourceId?: string | null
|
||||
initialData?: unknown
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: VendorFormValues = {
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
company_name: "",
|
||||
email: "",
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): VendorFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
|
||||
return {
|
||||
first_name: d.first_name || "",
|
||||
last_name: d.last_name || "",
|
||||
company_name: d.company_name || "",
|
||||
email: d.email || "",
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: VendorFormValues) {
|
||||
return {
|
||||
first_name: values.first_name,
|
||||
last_name: values.last_name || undefined,
|
||||
company_name: values.company_name || undefined,
|
||||
email: values.email || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Component ──
|
||||
|
||||
export function VendorForm({ resourceId, initialData, onSuccess }: VendorFormProps) {
|
||||
const api = useAuthApi()
|
||||
|
||||
const { form, isEditing } = useResourceForm<VendorFormValues, any>({
|
||||
schema: vendorFormSchema,
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
resourceId,
|
||||
initialData,
|
||||
mapToFormValues,
|
||||
})
|
||||
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: VendorFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = isEditing && resourceId
|
||||
? api.vendors.update(resourceId, payload)
|
||||
: api.vendors.create(payload)
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating vendor..." : "Creating vendor...",
|
||||
success: isEditing ? "Vendor updated successfully" : "Vendor created successfully",
|
||||
error: isEditing ? "Failed to update vendor" : "Failed to create vendor",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
<Alert variant="destructive" className="mb-4">
|
||||
<AlertTriangle className="me-2 h-4 w-4" />
|
||||
<AlertTitle>
|
||||
{isEditing ? "Failed to update vendor" : "Failed to create vendor"}
|
||||
</AlertTitle>
|
||||
{error.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="first_name" label="First Name" placeholder="John" required />
|
||||
<RhfTextField name="last_name" label="Last Name" placeholder="Doe" />
|
||||
</div>
|
||||
|
||||
<RhfTextField name="company_name" label="Company Name" placeholder="Acme Supplies" />
|
||||
<RhfTextField name="email" label="Email" placeholder="vendor@example.com" type="email" />
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
{isEditing ? <Save /> : <Plus />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Vendor" : "Create Vendor")}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</Rhform>
|
||||
)
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const vendorFormSchema = z.object({
|
||||
first_name: z.string().min(1, "First name is required"),
|
||||
last_name: z.string().optional(),
|
||||
company_name: z.string().optional(),
|
||||
email: z
|
||||
.union([z.string().email("Enter a valid email address"), z.literal("")])
|
||||
.optional(),
|
||||
})
|
||||
|
||||
type VendorFormValues = z.infer<typeof vendorFormSchema>
|
||||
|
||||
export { vendorFormSchema }
|
||||
export type { VendorFormValues }
|
||||
Reference in New Issue
Block a user