filters , order inspections , inventory items , credit notes

This commit is contained in:
2026-04-08 14:38:16 +03:00
parent 90c84a0bda
commit bb02b77be2
33 changed files with 2552 additions and 145 deletions
@@ -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 CreditNoteActionsProps = {
creditNoteId: string
}
export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
const api = useAuthApi()
const router = useRouter()
const handleEdit = () => {
router.push(`/sales/credit-notes/${creditNoteId}/edit`)
}
const handleDelete = async () => {
await api.creditNotes.destroy(creditNoteId)
router.push("/sales/credit-notes")
}
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 CreditNoteContextValue = {
id: string
label: string
}
const CreditNoteContext = createContext<CreditNoteContextValue | null>(null)
export function CreditNoteProvider({
creditNote,
children,
}: {
creditNote: CreditNoteContextValue
children: React.ReactNode
}) {
return (
<CreditNoteContext.Provider value={creditNote}>
{children}
</CreditNoteContext.Provider>
)
}
export function useCreditNote() {
return useContext(CreditNoteContext)
}
@@ -0,0 +1,70 @@
"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 } from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
const schema = z.object({
attachments: z.instanceof(FileList).refine((files) => files.length > 0, "At least one file is required"),
})
type FormValues = z.infer<typeof schema>
type CreditNoteDocumentFormProps = {
creditNoteId: string
onSuccess?: () => void
}
export function CreditNoteDocumentForm({ creditNoteId, onSuccess }: CreditNoteDocumentFormProps) {
const api = useAuthApi()
const form = useForm<FormValues>({
resolver: zodResolver(schema),
})
const handleSubmit = async (values: FormValues) => {
try {
const formData = new FormData()
Array.from(values.attachments).forEach((file) => {
formData.append("attachments[]", file)
})
await api.creditNotes.addAttachment(creditNoteId, formData)
toast.success("Attachment uploaded")
form.reset()
onSuccess?.()
} catch {
toast.error("Failed to upload attachment")
}
}
return (
<Rhform form={form} onSubmit={handleSubmit}>
<FieldGroup>
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium">Attachments</label>
<input
type="file"
multiple
className="text-sm"
{...form.register("attachments")}
/>
{form.formState.errors.attachments && (
<p className="text-xs text-destructive">
{form.formState.errors.attachments.message as string}
</p>
)}
</div>
<Button type="submit" disabled={form.formState.isSubmitting}>
<Plus />
{form.formState.isSubmitting ? "Uploading..." : "Upload Attachment"}
</Button>
</FieldGroup>
</Rhform>
)
}
@@ -0,0 +1,182 @@
"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 {
creditNoteFormSchema,
type CreditNoteFormValues,
} from "./credit-note.schema"
import { CREDIT_NOTE_ROUTES, DEPARTMENT_ROUTES } from "@garage/api"
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
// ── 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 }
// ── Constants ──
const STATUS_OPTIONS = [
{ value: "draft", label: "Draft" },
{ value: "open", label: "Open" },
{ value: "applied", label: "Applied" },
{ value: "void", label: "Void" },
]
// ── Props ──
export type CreditNoteFormProps = {
resourceId?: string | null
initialData?: unknown
onSuccess?: () => void
}
// ── Default values ──
const DEFAULT_VALUES: CreditNoteFormValues = {
subject: "",
customer: null,
department: null,
date: "",
status: "draft",
notes: "",
}
// ── Mapping helpers ──
function mapToFormValues(data: unknown): CreditNoteFormValues {
const d = (data as any)?.data ?? data ?? {}
return {
subject: d.subject || "",
customer: toRelation(d.customer_id, d.customer_name),
department: toRelation(d.department_id, d.department_name),
date: d.date || "",
status: d.status || "draft",
notes: d.notes || "",
}
}
function mapFormToPayload(values: CreditNoteFormValues) {
return {
subject: values.subject,
customer_id: toId(values.customer),
department_id: toId(values.department),
date: values.date || undefined,
status: values.status,
notes: values.notes || undefined,
}
}
// ── Component ──
export function CreditNoteForm({ resourceId, initialData, onSuccess }: CreditNoteFormProps) {
const api = useAuthApi()
const { form, isEditing } = useResourceForm<CreditNoteFormValues>({
schema: creditNoteFormSchema,
defaultValues: DEFAULT_VALUES,
resourceId: resourceId ?? null,
initialData,
queryKey: [CREDIT_NOTE_ROUTES.BY_ID, resourceId],
initialize: (id) => api.creditNotes.show(id),
mapToFormValues,
})
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: CreditNoteFormValues) => {
const payload = mapFormToPayload(values)
const promise = (isEditing && resourceId
? api.creditNotes.update(resourceId, payload)
: api.creditNotes.create(payload)) as Promise<any>
toast.promise(promise, {
loading: isEditing ? "Updating credit note..." : "Creating credit note...",
success: isEditing ? "Credit note updated successfully" : "Credit note created successfully",
error: isEditing ? "Failed to update credit note" : "Failed to create credit note",
})
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 credit note" : "Failed to create credit note"}
</AlertTitle>
{error.message}
</Alert>
)}
<FieldGroup>
<RhfTextField name="subject" label="Subject" placeholder="Credit note subject" required />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfCustomerSelectField name="customer" label="Customer" />
<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">
<RhfTextField name="date" label="Date" type="date" />
<RhfSelectField
name="status"
label="Status"
options={STATUS_OPTIONS}
/>
</div>
<RhfTextareaField name="notes" label="Notes" placeholder="Additional notes..." rows={3} />
<Button type="submit" variant="default" disabled={isPending}>
{isEditing ? (
<>
<Save className="me-2 size-4" />
{isPending ? "Saving..." : "Save Changes"}
</>
) : (
<>
<Plus className="me-2 size-4" />
{isPending ? "Creating..." : "Create Credit Note"}
</>
)}
</Button>
</FieldGroup>
</Rhform>
)
}
@@ -0,0 +1,146 @@
import {
FileText,
Calendar,
Hash,
Users,
Building2,
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 CreditNoteData = {
id?: number
subject?: string
credit_invoice?: string
date?: string
status?: string
notes?: string
customer_id?: number
customer_name?: string
department_name?: string
department_id?: number
invoice_id?: number
created_at?: string
updated_at?: string
}
type CreditNoteGeneralInfoProps = {
creditNote: CreditNoteData
}
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",
applied: "default",
void: "outline",
}
export function CreditNoteGeneralInfo({ creditNote }: CreditNoteGeneralInfoProps) {
return (
<div className="grid gap-6 md:grid-cols-2">
{/* Credit Note Details */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FileText className="size-4" />
Credit Note Details
</CardTitle>
</CardHeader>
<CardContent className="grid gap-4">
<div className="flex flex-wrap items-center gap-2">
{creditNote.subject && (
<Badge variant="secondary">{creditNote.subject}</Badge>
)}
{creditNote.status && (
<Badge variant={statusColorMap[creditNote.status] as any ?? "outline"}>
{creditNote.status.charAt(0).toUpperCase() + creditNote.status.slice(1)}
</Badge>
)}
</div>
<Separator />
<div className="grid gap-4 sm:grid-cols-2">
<InfoItem
icon={Hash}
label="Credit Note #"
value={creditNote.credit_invoice}
/>
<InfoItem
icon={Calendar}
label="Date"
value={creditNote.date}
/>
<InfoItem
icon={Clock}
label="Created"
value={creditNote.created_at ? new Date(creditNote.created_at).toLocaleDateString() : null}
/>
</div>
</CardContent>
</Card>
{/* Relations */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Users className="size-4" />
Related Info
</CardTitle>
</CardHeader>
<CardContent className="grid gap-4">
<div className="grid gap-4">
<InfoItem
icon={Users}
label="Customer"
value={creditNote.customer_name}
/>
<InfoItem
icon={Building2}
label="Department"
value={creditNote.department_name}
/>
</div>
{creditNote.notes && (
<>
<Separator />
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">Notes</span>
<p className="text-sm">{creditNote.notes}</p>
</div>
</>
)}
</CardContent>
</Card>
</div>
)
}
@@ -0,0 +1,60 @@
"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 CreditNoteNoteFormProps = {
creditNoteId: string
onSuccess?: () => void
}
export function CreditNoteNoteForm({ creditNoteId, onSuccess }: CreditNoteNoteFormProps) {
const api = useAuthApi()
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: { note: "" },
})
const handleSubmit = async (values: FormValues) => {
try {
await api.creditNotes.addInternalNote(creditNoteId, { note: values.note })
toast.success("Note added")
form.reset()
onSuccess?.()
} catch {
toast.error("Failed to add 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 ? "Adding..." : "Add Note"}
</Button>
</FieldGroup>
</Rhform>
)
}
@@ -0,0 +1,24 @@
import { z } from "zod"
const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
const creditNoteFormSchema = z.object({
// ── Required fields ──
subject: z.string().min(1, "Subject is required"),
// ── Relations ──
customer: relationFieldSchema,
department: relationFieldSchema,
// ── Optional fields ──
date: z.string().optional(),
status: z.string().optional(),
notes: z.string().optional(),
})
type CreditNoteFormValues = z.infer<typeof creditNoteFormSchema>
export { creditNoteFormSchema, relationFieldSchema }
export type { CreditNoteFormValues }
@@ -0,0 +1,206 @@
"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,
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 { toRelation, toId } from "@/shared/lib/utils"
import { expenseItemFormSchema, type ExpenseItemFormValues } from "./expense-item.schema"
import { EXPENSE_ITEM_ROUTES, INVENTORY_CATEGORY_ROUTES } from "@garage/api"
import { InventoryCategoryCrudDialog } from "./inventory-category-crud-dialog"
// ── Constants ──
const ITEM_TYPE_OPTIONS = [
{ value: "Expense", label: "Expense" },
]
const mapLookupOption = (item: any) => ({
value: String(item.id),
label: item.title ?? item.name ?? String(item.id),
})
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
// ── Props ──
export type ExpenseItemFormProps = {
resourceId?: string | null
initialData?: unknown
onSuccess?: () => void
}
// ── Default values ──
const DEFAULT_VALUES: ExpenseItemFormValues = {
item_type: "Expense",
item_name: "",
category: null,
purchase_price: undefined,
purchase_chart_of_account: "",
purchase_information: true,
is_active: true,
}
// ── Mapping helpers ──
function mapToFormValues(data: unknown): ExpenseItemFormValues {
const d = (data as any)?.data ?? data ?? {}
return {
item_type: d.item_type || "Expense",
item_name: d.item_name || "",
category: toRelation(d.category_id, d.category_title ?? d.category_name),
purchase_price: d.purchase_price ?? undefined,
purchase_chart_of_account: d.purchase_chart_of_account || "",
purchase_information: d.purchase_information ?? true,
is_active: d.is_active ?? true,
}
}
function mapFormToPayload(values: ExpenseItemFormValues) {
return {
item_type: values.item_type,
item_name: values.item_name,
category_id: toId(values.category),
purchase_price: values.purchase_price,
purchase_chart_of_account: values.purchase_chart_of_account || undefined,
purchase_information: values.purchase_information,
is_active: values.is_active,
}
}
// ── Component ──
export function ExpenseItemForm({ resourceId, initialData, onSuccess }: ExpenseItemFormProps) {
const api = useAuthApi()
const { form, isEditing } = useResourceForm<ExpenseItemFormValues, any>({
schema: expenseItemFormSchema,
defaultValues: DEFAULT_VALUES,
resourceId,
initialData,
initialize: (id) => api.expenseItems.show(id),
queryKey: [EXPENSE_ITEM_ROUTES.BY_ID, resourceId],
mapToFormValues,
})
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: ExpenseItemFormValues) => {
const promise = isEditing && resourceId
? api.expenseItems.update(resourceId, mapFormToPayload(values))
: api.expenseItems.create(mapFormToPayload(values))
toast.promise(promise, {
loading: isEditing ? "Updating expense item..." : "Creating expense item...",
success: isEditing ? "Expense item updated successfully" : "Expense item created successfully",
error: isEditing ? "Failed to update expense item" : "Failed to create expense item",
})
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 item" : "Failed to create expense item"}
</AlertTitle>
{error.message}
</Alert>
)}
<FieldGroup>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfSelectField
name="item_type"
label="Item Type"
options={ITEM_TYPE_OPTIONS}
required
/>
<RhfTextField
name="item_name"
label="Item Name"
placeholder="e.g. Office Supplies"
required
/>
</div>
<div>
<div className="mb-1 flex items-center justify-between">
<span className="text-sm font-medium">Category</span>
<InventoryCategoryCrudDialog />
</div>
<RhfAsyncSelectField
name="category"
label=""
placeholder="Select category"
queryKey={[INVENTORY_CATEGORY_ROUTES.INDEX]}
listFn={() => api.inventoryCategories.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField
name="purchase_price"
label="Purchase Price"
placeholder="0.00"
type="number"
/>
<RhfTextField
name="purchase_chart_of_account"
label="Purchase Chart of Account"
placeholder="e.g. Expenses"
/>
</div>
<div className="flex flex-col gap-3">
<RhfCheckboxField
name="purchase_information"
label="Purchase Information"
/>
<RhfCheckboxField
name="is_active"
label="Active"
/>
</div>
</FieldGroup>
<div className="mt-6 flex justify-end">
<Button type="submit" disabled={isPending}>
{isEditing ? (
<>
<Save className="me-2 h-4 w-4" />
{isPending ? "Saving..." : "Save Changes"}
</>
) : (
<>
<Plus className="me-2 h-4 w-4" />
{isPending ? "Creating..." : "Create Expense Item"}
</>
)}
</Button>
</div>
</Rhform>
)
}
@@ -0,0 +1,17 @@
import { z } from "zod"
export const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
export const expenseItemFormSchema = z.object({
item_type: z.string().min(1, "Item type is required"),
item_name: z.string().min(1, "Item name is required"),
category: relationFieldSchema,
purchase_price: z.coerce.number().min(0).optional(),
purchase_chart_of_account: z.string().optional(),
purchase_information: z.boolean().default(true),
is_active: z.boolean().default(true),
})
export type ExpenseItemFormValues = z.infer<typeof expenseItemFormSchema>
@@ -0,0 +1,33 @@
"use client"
import { CrudDialog } from "@/shared/components/crud-dialog"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { useAuthApi } from "@/shared/useApi"
import { INVENTORY_CATEGORY_ROUTES } from "@garage/api"
import { InventoryCategoryForm } from "./inventory-category-form"
export function InventoryCategoryCrudDialog() {
const api = useAuthApi()
return (
<CrudDialog
title="Inventory Category"
queryKey={[INVENTORY_CATEGORY_ROUTES.INDEX]}
getClient={() => api.inventoryCategories}
resourceLabel="inventory category"
columns={() => [
{
accessorKey: "title",
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
},
]}
renderForm={({ resourceId, initialData, onSuccess }) => (
<InventoryCategoryForm
resourceId={resourceId}
initialData={initialData}
onSuccess={onSuccess}
/>
)}
/>
)
}
@@ -0,0 +1,80 @@
"use client"
import { z } from "zod"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Plus, Save } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
import { FieldGroup } from "@/shared/components/ui/field"
import { Rhform, RhfTextField } from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { useEffect } from "react"
const inventoryCategorySchema = z.object({
title: z.string().min(1, "Title is required"),
})
type InventoryCategoryFormValues = z.infer<typeof inventoryCategorySchema>
type InventoryCategoryFormProps = {
resourceId?: string | null
initialData?: any
onSuccess?: () => void
}
export function InventoryCategoryForm({ resourceId, initialData, onSuccess }: InventoryCategoryFormProps) {
const api = useAuthApi()
const isEditing = !!resourceId
const form = useForm<InventoryCategoryFormValues>({
resolver: zodResolver(inventoryCategorySchema),
defaultValues: { title: "" },
})
useEffect(() => {
if (initialData) {
const d = initialData?.data ?? initialData
form.reset({ title: d.title ?? "" })
}
}, [initialData, form])
const handleSubmit = async (values: InventoryCategoryFormValues) => {
try {
const promise = isEditing
? api.inventoryCategories.update(resourceId!, { title: values.title })
: api.inventoryCategories.create({ title: values.title })
toast.promise(promise, {
loading: isEditing ? "Updating..." : "Creating...",
success: isEditing ? "Updated successfully" : "Created successfully",
error: isEditing ? "Failed to update" : "Failed to create",
})
await promise
form.reset()
onSuccess?.()
} catch {
// toast already shown
}
}
return (
<Rhform form={form} onSubmit={handleSubmit}>
<FieldGroup>
<RhfTextField
name="title"
label="Title"
placeholder="e.g. Engine Parts"
required
/>
<Button type="submit" disabled={form.formState.isSubmitting}>
{isEditing ? <Save className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
{form.formState.isSubmitting
? (isEditing ? "Updating..." : "Creating...")
: (isEditing ? "Update" : "Create")}
</Button>
</FieldGroup>
</Rhform>
)
}
@@ -8,7 +8,11 @@ import { FieldGroup } from "@/shared/components/ui/field"
import {
Rhform,
RhfTextField,
RhfTextareaField,
RhfSelectField,
RhfAsyncSelectField,
RhfDateField,
RhfTimeField,
} from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
@@ -25,6 +29,9 @@ import {
import {
INSPECTION_ROUTES,
DEPARTMENT_ROUTES,
JOB_CARD_ROUTES,
InspectionStatus,
RateType,
} from "@garage/api"
import { RhfVehicleSelectField } from "@/modules/vehicles/rhf-vehicle-select-field"
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
@@ -46,10 +53,22 @@ const DEFAULT_VALUES: InspectionFormValues = {
department: null,
inspection_category: null,
employee: null,
job_card: null,
labor_rate: null,
title: "",
order_number: "",
date: "",
time: "",
status: "in_progress",
note: "",
description: "",
rate_type: "flat_rate",
quantity: 1,
rate: 0,
working_hours: 0,
labor_hours: 0,
tax: "",
chart_of_account: "",
}
// ── Mapping helpers ──
@@ -63,10 +82,26 @@ function mapToFormValues(data: unknown): InspectionFormValues {
department: toRelation(d.department_id, d.department?.name),
inspection_category: toRelation(d.inspection_category_id, d.inspection_category?.name),
employee: toRelation(d.employee_id, d.employee?.first_name ? `${d.employee.first_name} ${d.employee.last_name ?? ""}`.trim() : undefined),
job_card: d.job_card_id
? { value: String(d.job_card_id), label: d.job_card?.title ?? d.job_card?.order_number ?? String(d.job_card_id) }
: null,
labor_rate: d.labor_rate_id
? { value: String(d.labor_rate_id), label: d.labor_rate?.title ?? String(d.labor_rate_id) }
: null,
title: d.title ?? "",
order_number: d.order_number ?? "",
date: d.date ?? "",
date: d.date ? d.date.split("T")[0] : "",
time: d.time ?? "",
status: d.status ?? "in_progress",
note: d.note ?? "",
description: d.description ?? "",
rate_type: d.rate_type ?? "flat_rate",
quantity: d.quantity != null ? Number(d.quantity) : 1,
rate: d.rate != null ? Number(d.rate) : 0,
working_hours: d.working_hours != null ? Number(d.working_hours) : 0,
labor_hours: d.labor_hours != null ? Number(d.labor_hours) : 0,
tax: d.tax ?? "",
chart_of_account: d.chart_of_account ?? "",
}
}
@@ -77,14 +112,36 @@ function mapFormToPayload(values: InspectionFormValues) {
department_id: toId(values.department),
inspection_category_id: toId(values.inspection_category),
employee_id: toId(values.employee),
job_card_id: toId(values.job_card) ?? null,
labor_rate_id: values.labor_rate ? Number(values.labor_rate.value) : undefined,
title: values.title,
order_number: values.order_number || undefined,
date: values.date || undefined,
time: values.time || undefined,
status: values.status || undefined,
note: values.note || undefined,
description: values.description || undefined,
rate_type: values.rate_type || undefined,
quantity: values.quantity ?? undefined,
rate: values.rate ?? undefined,
working_hours: values.working_hours ?? undefined,
labor_hours: values.labor_hours ?? undefined,
tax: values.tax || undefined,
chart_of_account: values.chart_of_account || undefined,
}
}
// ── Shared mapOption for async selects ──
// ── Select options ──
const STATUS_OPTIONS = InspectionStatus.map((v) => ({
value: v,
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
}))
const RATE_TYPE_OPTIONS = RateType.map((v) => ({
value: v,
label: v === "flat_rate" ? "Flat Rate" : "Hourly",
}))
const mapLookupOption = (item: any) => ({
value: String(item.id),
@@ -171,15 +228,74 @@ export function InspectionForm({ resourceId, initialData, onSuccess }: Inspectio
/>
</div>
<RhfEmployeeSelectField name="employee" />
<RhfTextField name="order_number" label="Order Number" placeholder="e.g. ORD-001" />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfEmployeeSelectField name="employee" />
<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.title ?? item.order_number ?? String(item.id),
})}
{...STORE_OBJECT}
/>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="date" label="Date" placeholder="YYYY-MM-DD" type="date" />
<RhfTextField name="time" label="Time" placeholder="HH:MM:SS" type="time" step={1} />
<RhfSelectField
name="status"
label="Status"
placeholder="Select status"
options={STATUS_OPTIONS}
/>
<RhfTextField name="order_number" label="Order Number" placeholder="e.g. ORD-001" />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfDateField name="date" label="Date" />
<RhfTimeField name="time" label="Time" withSeconds />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfSelectField
name="rate_type"
label="Rate Type"
placeholder="Select rate type"
options={RATE_TYPE_OPTIONS}
/>
<RhfAsyncSelectField
name="labor_rate"
label="Labor Rate"
placeholder="Select labor rate"
queryKey={["labor-rates"]}
listFn={() => api.inventory.listLaborRates()}
mapOption={(item: any) => ({
value: String(item.id),
label: item.title ?? String(item.id),
})}
{...STORE_OBJECT}
/>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<RhfTextField name="quantity" label="Quantity" type="number" placeholder="1" />
<RhfTextField name="rate" label="Rate" type="number" placeholder="0.00" />
<RhfTextField name="tax" label="Tax" placeholder="e.g. 5%" />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="working_hours" label="Working Hours" type="number" placeholder="0" />
<RhfTextField name="labor_hours" label="Labor Hours" type="number" placeholder="0" />
</div>
<RhfTextField name="chart_of_account" label="Chart of Account" placeholder="e.g. COA-123" />
<RhfTextareaField name="note" label="Note" placeholder="Internal notes..." />
<RhfTextareaField name="description" label="Description" placeholder="Full description..." />
<Button type="submit" variant="default" disabled={isPending}>
{isEditing ? <Save /> : <Plus />}
{isPending
@@ -10,10 +10,22 @@ const inspectionFormSchema = z.object({
department: relationFieldSchema,
inspection_category: relationFieldSchema,
employee: relationFieldSchema,
job_card: relationFieldSchema.optional(),
labor_rate: relationFieldSchema.optional(),
title: z.string().min(1, "Title is required"),
order_number: z.string().optional(),
date: z.string().optional(),
time: z.string().optional(),
status: z.string().optional(),
note: z.string().optional(),
description: z.string().optional(),
rate_type: z.string().optional(),
quantity: z.coerce.number().min(0).optional(),
rate: z.coerce.number().min(0).optional(),
working_hours: z.coerce.number().min(0).optional(),
labor_hours: z.coerce.number().min(0).optional(),
tax: z.string().optional(),
chart_of_account: z.string().optional(),
})
type InspectionFormValues = z.infer<typeof inspectionFormSchema>
@@ -0,0 +1,282 @@
"use client"
import { z } from "zod"
import { parseAsInteger, parseAsString, parseAsBoolean } from "nuqs"
import { toRelation, toId, type RelationFieldValue } from "@/shared/lib/utils"
import {
RhfAsyncSelectField,
RhfDateField,
RhfCheckboxField,
RhfSelectField,
} from "@/shared/components/form"
import { useAuthApi } from "@/shared/useApi"
import {
CUSTOMER_ROUTES,
EMPLOYEE_ROUTES,
DEPARTMENT_ROUTES,
VEHICLE_ROUTES,
LABEL_ROUTES,
INSURANCE_TYPE_ROUTES,
JobCardStatus,
} from "@garage/api"
import { formatEnum } from "@/shared/utils/formatters"
import { Separator } from "@/shared/components/ui/separator"
import type { UseFilterParamsOptions } from "@/shared/hooks/use-filter-params"
// ── Schema ──
const relationField = z.object({ value: z.string(), label: z.string() }).nullable().optional()
const jobCardFilterSchema = z.object({
customer_id: relationField,
insurer_id: relationField,
vehicle_id: relationField,
department_id: relationField,
sales_person_id: relationField,
primary_technician_id: relationField,
service_writer_id: relationField,
label_ids: z.string().optional(),
check_in_date: z.string().optional(),
check_out_date: z.string().optional(),
delivery_date: z.string().optional(),
start_date: z.string().optional(),
end_date: z.string().optional(),
convert_invoice: z.boolean().optional(),
has_start_or_delivery_date: z.boolean().optional(),
has_start_date: z.boolean().optional(),
has_delivery_date: z.boolean().optional(),
has_both_dates: z.boolean().optional(),
})
type JobCardFilterValues = z.infer<typeof jobCardFilterSchema>
// ── Defaults ──
const defaultValues: JobCardFilterValues = {
customer_id: null,
insurer_id: null,
vehicle_id: null,
department_id: null,
sales_person_id: null,
primary_technician_id: null,
service_writer_id: null,
label_ids: "",
check_in_date: "",
check_out_date: "",
delivery_date: "",
start_date: "",
end_date: "",
convert_invoice: false,
has_start_or_delivery_date: false,
has_start_date: false,
has_delivery_date: false,
has_both_dates: false,
}
// ── nuqs Parsers ──
const paramsParsers = {
customer_id: parseAsInteger,
insurer_id: parseAsInteger,
vehicle_id: parseAsInteger,
department_id: parseAsInteger,
sales_person_id: parseAsInteger,
primary_technician_id: parseAsInteger,
service_writer_id: parseAsInteger,
label_ids: parseAsString,
check_in_date: parseAsString,
check_out_date: parseAsString,
delivery_date: parseAsString,
start_date: parseAsString,
end_date: parseAsString,
convert_invoice: parseAsBoolean,
has_start_or_delivery_date: parseAsBoolean,
has_start_date: parseAsBoolean,
has_delivery_date: parseAsBoolean,
has_both_dates: parseAsBoolean,
}
// ── Mappers ──
function mapParamsToFormValues(params: Record<string, any>): Partial<JobCardFilterValues> {
return {
customer_id: params.customer_id ? toRelation(params.customer_id) : null,
insurer_id: params.insurer_id ? toRelation(params.insurer_id) : null,
vehicle_id: params.vehicle_id ? toRelation(params.vehicle_id) : null,
department_id: params.department_id ? toRelation(params.department_id) : null,
sales_person_id: params.sales_person_id ? toRelation(params.sales_person_id) : null,
primary_technician_id: params.primary_technician_id ? toRelation(params.primary_technician_id) : null,
service_writer_id: params.service_writer_id ? toRelation(params.service_writer_id) : null,
label_ids: params.label_ids ?? "",
check_in_date: params.check_in_date ?? "",
check_out_date: params.check_out_date ?? "",
delivery_date: params.delivery_date ?? "",
start_date: params.start_date ?? "",
end_date: params.end_date ?? "",
convert_invoice: params.convert_invoice ?? false,
has_start_or_delivery_date: params.has_start_or_delivery_date ?? false,
has_start_date: params.has_start_date ?? false,
has_delivery_date: params.has_delivery_date ?? false,
has_both_dates: params.has_both_dates ?? false,
}
}
function mapFormValuesToParams(values: JobCardFilterValues): Record<string, any> {
return {
customer_id: toId(values.customer_id as RelationFieldValue) ?? null,
insurer_id: toId(values.insurer_id as RelationFieldValue) ?? null,
vehicle_id: toId(values.vehicle_id as RelationFieldValue) ?? null,
department_id: toId(values.department_id as RelationFieldValue) ?? null,
sales_person_id: toId(values.sales_person_id as RelationFieldValue) ?? null,
primary_technician_id: toId(values.primary_technician_id as RelationFieldValue) ?? null,
service_writer_id: toId(values.service_writer_id as RelationFieldValue) ?? null,
label_ids: values.label_ids || null,
check_in_date: values.check_in_date || null,
check_out_date: values.check_out_date || null,
delivery_date: values.delivery_date || null,
start_date: values.start_date || null,
end_date: values.end_date || null,
convert_invoice: values.convert_invoice || null,
has_start_or_delivery_date: values.has_start_or_delivery_date || null,
has_start_date: values.has_start_date || null,
has_delivery_date: values.has_delivery_date || null,
has_both_dates: values.has_both_dates || null,
}
}
// ── Filter Config (for useFilterParams) ──
export const jobCardFilterConfig: UseFilterParamsOptions<JobCardFilterValues> = {
schema: jobCardFilterSchema,
defaultValues,
paramsParsers,
mapParamsToFormValues,
mapFormValuesToParams,
}
// ── Filter Fields Component ──
function SectionLabel({ children }: { children: React.ReactNode }) {
return <p className="text-sm font-medium text-muted-foreground pt-2">{children}</p>
}
export function JobCardFilterFields() {
const api = useAuthApi()
const employeeMapOption = (item: any) => ({
value: String(item.id),
label: [item.first_name, item.last_name].filter(Boolean).join(" ") || `Employee #${item.id}`,
})
const customerMapOption = (item: any) => {
const name = [item.first_name, item.last_name].filter(Boolean).join(" ")
return {
value: String(item.id),
label: name || item.company_name || `Customer #${item.id}`,
}
}
const vehicleMapOption = (item: any) => ({
value: String(item.id),
label: [item.year, item.make, item.model].filter(Boolean).join(" ") || `Vehicle #${item.id}`,
})
return (
<>
{/* ── Relations ── */}
<SectionLabel>Relations</SectionLabel>
<RhfAsyncSelectField
name="customer_id"
label="Customer"
queryKey={[CUSTOMER_ROUTES.INDEX]}
listFn={() => api.customers.list({ per_page: 100 })}
mapOption={customerMapOption}
placeholder="All customers"
/>
<RhfAsyncSelectField
name="vehicle_id"
label="Vehicle"
queryKey={[VEHICLE_ROUTES.INDEX]}
listFn={() => api.vehicles.list({ per_page: 100 })}
mapOption={vehicleMapOption}
placeholder="All vehicles"
/>
<RhfAsyncSelectField
name="insurer_id"
label="Insurance Type"
queryKey={[INSURANCE_TYPE_ROUTES.INDEX]}
listFn={() => api.insuranceTypes.list({ per_page: 100 })}
mapOption={(item: any) => ({ value: String(item.id), label: item.title ?? item.name ?? `#${item.id}` })}
placeholder="All insurers"
/>
<RhfAsyncSelectField
name="department_id"
label="Department"
queryKey={[DEPARTMENT_ROUTES.INDEX]}
listFn={() => api.departments.list({ per_page: 100 })}
mapOption={(item: any) => ({ value: String(item.id), label: item.title ?? item.name ?? `#${item.id}` })}
placeholder="All departments"
/>
<Separator />
<SectionLabel>Assigned Staff</SectionLabel>
<RhfAsyncSelectField
name="sales_person_id"
label="Sales Person"
queryKey={[EMPLOYEE_ROUTES.INDEX, "sales_person"]}
listFn={() => api.employees.list({ per_page: 100 })}
mapOption={employeeMapOption}
placeholder="All sales persons"
/>
<RhfAsyncSelectField
name="primary_technician_id"
label="Primary Technician"
queryKey={[EMPLOYEE_ROUTES.INDEX, "technician"]}
listFn={() => api.employees.list({ per_page: 100 })}
mapOption={employeeMapOption}
placeholder="All technicians"
/>
<RhfAsyncSelectField
name="service_writer_id"
label="Service Writer"
queryKey={[EMPLOYEE_ROUTES.INDEX, "service_writer"]}
listFn={() => api.employees.list({ per_page: 100 })}
mapOption={employeeMapOption}
placeholder="All service writers"
/>
{/* ── Dates ── */}
<Separator />
<SectionLabel>Dates</SectionLabel>
<div className="grid grid-cols-2 gap-3">
<RhfDateField name="check_in_date" label="Check-in Date" />
<RhfDateField name="check_out_date" label="Check-out Date" />
</div>
<RhfDateField name="delivery_date" label="Delivery Date" />
<div className="grid grid-cols-2 gap-3">
<RhfDateField name="start_date" label="Start Date" />
<RhfDateField name="end_date" label="End Date" />
</div>
{/* ── Flags ── */}
<Separator />
<SectionLabel>Flags</SectionLabel>
<RhfCheckboxField name="convert_invoice" label="Convert to Invoice" />
<RhfCheckboxField name="has_start_or_delivery_date" label="Has Start or Delivery Date" />
<RhfCheckboxField name="has_start_date" label="Has Start Date" />
<RhfCheckboxField name="has_delivery_date" label="Has Delivery Date" />
<RhfCheckboxField name="has_both_dates" label="Has Both Dates" />
</>
)
}