feat: add template checkpoint edit dialog and vendor management components

- Implemented TemplateCheckpointEditDialog for creating and editing inspection checkpoints.
- Added VendorActions component for managing vendor actions including edit, activate/deactivate, and delete.
- Created VendorContext for managing vendor state across components.
- Developed VendorGeneralInfo component to display detailed vendor information.
- Introduced AedSymbol and Money components for consistent currency representation.
- Added PromptDialog for user input prompts throughout the application.
- Implemented RelationLink component for unified related-data display in CRUD tables.
- Created InspectionTemplatesClient for API interactions related to inspection templates.
This commit is contained in:
2026-05-18 12:08:42 +04:00
parent 54d11f01b4
commit 4bfd8c84a9
111 changed files with 5002 additions and 1047 deletions
@@ -0,0 +1,524 @@
"use client"
import { useEffect, useRef, useState } from "react"
import { toast } from "sonner"
import {
AlertTriangle,
Camera,
ChevronLeft,
ChevronRight,
CheckCircle2,
Image as ImageIcon,
Loader2,
Mic,
StickyNote,
Trash2,
Video,
X,
} from "lucide-react"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { Alert, AlertDescription, AlertTitle } from "@/shared/components/ui/alert"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Textarea } from "@/shared/components/ui/textarea"
import { Label } from "@/shared/components/ui/label"
import { useAuthApi } from "@/shared/useApi"
import { CheckpointMediaLightbox, type LightboxItem } from "@/modules/inspections/checkpoint-media-lightbox"
export type Severity = "good" | "attention" | "critical" | "na" | "not_inspected"
export type RecordType = "capture_photo" | "record_video" | "record_audio" | "record_conditions" | "wire_frame" | "none"
export type CheckpointMedia = {
id: number
url: string | null
media_type: "photo" | "video" | "audio" | "document"
sort_order: number
caption?: string | null
}
export type Checkpoint = {
id: number
name: string
description?: string | null
severity?: Severity | null
status?: string | null
technician_notes?: string | null
section_name?: string | null
record_type?: RecordType | null
condition_rate?: number | null
media?: CheckpointMedia[]
attachments?: CheckpointMedia[]
}
const SEVERITY: { value: Severity; label: string; cls: string }[] = [
{ value: "good", label: "Good", cls: "bg-emerald-100 text-emerald-800 hover:bg-emerald-200 border-emerald-200" },
{ value: "attention", label: "Attention", cls: "bg-amber-100 text-amber-800 hover:bg-amber-200 border-amber-200" },
{ value: "critical", label: "Critical", cls: "bg-rose-100 text-rose-800 hover:bg-rose-200 border-rose-200" },
{ value: "na", label: "N/A", cls: "bg-slate-100 text-slate-700 hover:bg-slate-200 border-slate-200" },
]
/** A checkpoint is "complete" once severity is set AND the required recording (if any) is captured. */
export function isCheckpointComplete(cp: Checkpoint): boolean {
const sev = (cp.severity as Severity) ?? "not_inspected"
if (sev === "not_inspected") return false
if (sev === "na") return true
const rt = (cp.record_type as RecordType) ?? "none"
const items = cp.attachments ?? cp.media ?? []
if (rt === "capture_photo") return items.some((m) => m.media_type === "photo")
if (rt === "record_video") return items.some((m) => m.media_type === "video")
if (rt === "record_audio") return items.some((m) => m.media_type === "audio")
if (rt === "record_conditions") return cp.condition_rate != null
return true
}
type Props = {
open: boolean
onOpenChange: (o: boolean) => void
/** Full ordered list of checkpoints (typically section-flattened from the page). */
checkpoints: Checkpoint[]
/** Index into `checkpoints`. null = dialog closed. */
activeIndex: number | null
onIndexChange: (i: number) => void
onSaved: () => void
/** Optimistic patch back to the parent so the row updates instantly. */
onPatch?: (checkpointId: number, patch: Partial<Checkpoint>) => void
}
export function CheckpointFillDialog({
open,
onOpenChange,
checkpoints,
activeIndex,
onIndexChange,
onSaved,
onPatch,
}: Props) {
const api = useAuthApi()
const photoInputRef = useRef<HTMLInputElement>(null)
const videoInputRef = useRef<HTMLInputElement>(null)
const audioInputRef = useRef<HTMLInputElement>(null)
// Local state — seeded only when the active checkpoint changes
// (not on every parent refetch, so unsaved notes don't get clobbered).
const [severity, setSeverity] = useState<Severity>("not_inspected")
const [notes, setNotes] = useState("")
const [conditionRate, setConditionRate] = useState<number>(50)
const [media, setMedia] = useState<CheckpointMedia[]>([])
const [savingNote, setSavingNote] = useState(false)
const [savingCondition, setSavingCondition] = useState(false)
const [uploading, setUploading] = useState(false)
const [lightbox, setLightbox] = useState<LightboxItem | null>(null)
const checkpoint = activeIndex != null ? checkpoints[activeIndex] : null
const checkpointId = checkpoint?.id ?? null
// Reseed only when the *checkpoint identity* changes (open or step nav).
useEffect(() => {
if (checkpoint) {
setSeverity((checkpoint.severity as Severity) ?? "not_inspected")
setNotes(checkpoint.technician_notes ?? "")
setConditionRate(checkpoint.condition_rate ?? 50)
setMedia(checkpoint.attachments ?? checkpoint.media ?? [])
}
// Intentionally only depends on the id — not on the whole prop object.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [checkpointId, open])
if (!checkpoint) return null
const recordType = (checkpoint.record_type as RecordType) ?? "none"
const skipsMedia = severity === "na" || recordType === "none" || recordType === "wire_frame"
const needsSeverity = severity === "not_inspected"
const needsPhoto = !skipsMedia && recordType === "capture_photo" && !media.some((m) => m.media_type === "photo")
const needsVideo = !skipsMedia && recordType === "record_video" && !media.some((m) => m.media_type === "video")
const needsAudio = !skipsMedia && recordType === "record_audio" && !media.some((m) => m.media_type === "audio")
const needsCondition = !skipsMedia && recordType === "record_conditions" && checkpoint.condition_rate == null
const allDone = !needsSeverity && !needsPhoto && !needsVideo && !needsAudio && !needsCondition
const hasUnsavedNote = notes !== (checkpoint.technician_notes ?? "")
const isFirst = activeIndex === 0
const isLast = activeIndex === checkpoints.length - 1
// All field saves rely on the optimistic `onPatch` to keep the parent
// page in sync. We intentionally do NOT call `onSaved()` here, because a
// full inspection refetch on every chip click was causing the dialog tree
// to re-render in a way that flickered the modal closed/open. `onSaved`
// is reserved for the explicit page-level "load" callsite (initial mount
// + nav). The server is authoritative — if anything ever diverges, the
// user can reopen the dialog or refresh.
const updateSeverity = async (s: Severity) => {
setSeverity(s)
onPatch?.(checkpoint.id, { severity: s })
try {
await api.inspections.updateCheckpoint(String(checkpoint.id), { severity: s } as any)
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to save finding")
}
}
const saveNotes = async () => {
if (!hasUnsavedNote) return
setSavingNote(true)
try {
await api.inspections.updateCheckpoint(String(checkpoint.id), { technician_notes: notes } as any)
onPatch?.(checkpoint.id, { technician_notes: notes })
toast.success("Note saved")
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to save note")
} finally {
setSavingNote(false)
}
}
const saveCondition = async (v: number) => {
setConditionRate(v)
onPatch?.(checkpoint.id, { condition_rate: v })
setSavingCondition(true)
try {
await api.inspections.updateCheckpoint(String(checkpoint.id), { condition_rate: v } as any)
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to save condition")
} finally {
setSavingCondition(false)
}
}
const handleFiles = async (filesList: FileList | null) => {
if (!filesList || filesList.length === 0) return
const files = Array.from(filesList).slice(0, 10)
setUploading(true)
try {
const res = await api.inspections.uploadCheckpointAttachments(checkpoint.id, files)
const added = (res.data as any[]) ?? []
const nextMedia = [...media, ...added]
setMedia(nextMedia)
onPatch?.(checkpoint.id, { attachments: nextMedia, media: nextMedia } as any)
toast.success("Saved")
} catch (e: any) {
toast.error(e?.payload?.message ?? "Upload failed")
} finally {
setUploading(false)
if (photoInputRef.current) photoInputRef.current.value = ""
if (videoInputRef.current) videoInputRef.current.value = ""
if (audioInputRef.current) audioInputRef.current.value = ""
}
}
const deleteAttachment = async (mediaId: number) => {
try {
await api.inspections.destroyCheckpointAttachment(checkpoint.id, mediaId)
const nextMedia = media.filter((x) => x.id !== mediaId)
setMedia(nextMedia)
onPatch?.(checkpoint.id, { attachments: nextMedia, media: nextMedia } as any)
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to remove")
}
}
const goNext = async () => {
// Belt-and-suspenders — the button is also `disabled={!allDone}`.
if (!allDone) return
if (hasUnsavedNote) await saveNotes()
if (isLast) {
onOpenChange(false)
} else if (activeIndex != null) {
onIndexChange(activeIndex + 1)
}
}
const goPrev = async () => {
if (hasUnsavedNote) await saveNotes()
if (activeIndex != null && activeIndex > 0) onIndexChange(activeIndex - 1)
}
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<div className="flex items-center justify-between gap-2">
<div className="min-w-0">
<DialogTitle className="flex items-center gap-2">
<span className="truncate">{checkpoint.name}</span>
{allDone && <CheckCircle2 className="size-4 text-emerald-600 shrink-0" />}
</DialogTitle>
{checkpoint.section_name && (
<DialogDescription>
{checkpoint.section_name} · {(activeIndex ?? 0) + 1} of {checkpoints.length}
</DialogDescription>
)}
</div>
</div>
</DialogHeader>
{!allDone && (
<Alert variant="default" className="border-amber-200 bg-amber-50/60">
<AlertTriangle className="text-amber-700" />
<AlertTitle className="text-amber-900">Still required</AlertTitle>
<AlertDescription className="text-amber-900/90">
<ul className="list-disc list-inside space-y-0.5">
{needsSeverity && <li>Pick a finding</li>}
{needsPhoto && <li>Add at least one photo</li>}
{needsVideo && <li>Add at least one video</li>}
{needsAudio && <li>Add at least one audio recording</li>}
{needsCondition && <li>Set the condition rating</li>}
</ul>
</AlertDescription>
</Alert>
)}
<div className="space-y-5">
{/* Finding */}
<div>
<div className="mb-2 flex items-center justify-between">
<Label className="flex items-center gap-2">
Finding <Badge variant="secondary" className="text-[10px]">required</Badge>
</Label>
{!needsSeverity && <CheckCircle2 className="size-4 text-emerald-600" />}
</div>
<div className="flex flex-wrap gap-2">
{SEVERITY.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => updateSeverity(opt.value)}
className={`rounded-full px-4 py-1.5 text-sm font-medium border transition ${opt.cls} ${
severity === opt.value ? "ring-2 ring-offset-1 ring-foreground/30" : "opacity-70 hover:opacity-100"
}`}
>
{opt.label}
</button>
))}
</div>
</div>
{/* Condition rating */}
{recordType === "record_conditions" && severity !== "na" && (
<div>
<div className="mb-2 flex items-center justify-between">
<Label className="flex items-center gap-2">
Condition rating <Badge variant="secondary" className="text-[10px]">required</Badge>
</Label>
{!needsCondition && <CheckCircle2 className="size-4 text-emerald-600" />}
</div>
<div className="flex items-center gap-3">
<input
type="range"
min={0}
max={100}
step={5}
value={conditionRate}
onChange={(e) => setConditionRate(Number(e.target.value))}
onMouseUp={(e) => saveCondition(Number((e.target as HTMLInputElement).value))}
onTouchEnd={(e) => saveCondition(Number((e.target as HTMLInputElement).value))}
className="flex-1 accent-foreground"
disabled={savingCondition}
/>
<span className="w-12 text-right text-sm tabular-nums font-medium">{conditionRate}%</span>
</div>
<p className="text-xs text-muted-foreground mt-1">0 = worn / broken · 100 = like new.</p>
</div>
)}
{/* Media — only the relevant kind for this record_type */}
{!skipsMedia && (
<MediaSection
recordType={recordType}
media={media}
uploading={uploading}
required={needsPhoto || needsVideo || needsAudio}
satisfied={
(recordType === "capture_photo" && !needsPhoto) ||
(recordType === "record_video" && !needsVideo) ||
(recordType === "record_audio" && !needsAudio)
}
onPick={(kind) => {
if (kind === "photo") photoInputRef.current?.click()
else if (kind === "video") videoInputRef.current?.click()
else audioInputRef.current?.click()
}}
onDelete={deleteAttachment}
onPreview={(item) => setLightbox(item)}
/>
)}
<input ref={photoInputRef} type="file" accept="image/*" capture="environment" multiple onChange={(e) => handleFiles(e.target.files)} className="hidden" />
<input ref={videoInputRef} type="file" accept="video/*" capture="environment" multiple onChange={(e) => handleFiles(e.target.files)} className="hidden" />
<input ref={audioInputRef} type="file" accept="audio/*" capture multiple onChange={(e) => handleFiles(e.target.files)} className="hidden" />
{/* Notes */}
<div>
<div className="mb-2 flex items-center justify-between">
<Label htmlFor="cp-notes" className="flex items-center gap-2">
<StickyNote className="size-3.5" /> Technician notes
<Badge variant="outline" className="text-[10px]">optional</Badge>
</Label>
{hasUnsavedNote && (
<span className="text-[11px] text-amber-700">Unsaved</span>
)}
</div>
<Textarea
id="cp-notes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={3}
placeholder="e.g. Pads at 3mm, suggest replacement before next service"
/>
<div className="mt-2 flex justify-end">
<Button
type="button"
size="sm"
variant={hasUnsavedNote ? "default" : "outline"}
onClick={saveNotes}
disabled={savingNote || !hasUnsavedNote}
>
{savingNote ? "Saving…" : "Update note"}
</Button>
</div>
</div>
</div>
<DialogFooter className="!justify-between items-center gap-2 flex-wrap">
<Button variant="ghost" size="sm" onClick={() => onOpenChange(false)}>
<X className="size-4" /> Close
</Button>
<div className="flex flex-col items-end gap-1">
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={goPrev} disabled={isFirst}>
<ChevronLeft className="size-4" /> Previous
</Button>
<Button
size="sm"
onClick={goNext}
disabled={!allDone}
title={!allDone ? "Complete the required fields to continue" : undefined}
>
{isLast ? "Done" : (hasUnsavedNote ? "Save & next" : "Next")}
{!isLast && <ChevronRight className="size-4" />}
</Button>
</div>
{!allDone && (
<span className="text-[11px] text-muted-foreground">
Complete the required fields to continue.
</span>
)}
</div>
</DialogFooter>
</DialogContent>
</Dialog>
<CheckpointMediaLightbox
open={!!lightbox}
onOpenChange={(o) => { if (!o) setLightbox(null) }}
item={lightbox}
/>
</>
)
}
function MediaSection({
recordType,
media,
uploading,
required,
satisfied,
onPick,
onDelete,
onPreview,
}: {
recordType: RecordType
media: CheckpointMedia[]
uploading: boolean
required: boolean
satisfied: boolean
onPick: (kind: "photo" | "video" | "audio") => void
onDelete: (id: number) => void
onPreview: (item: LightboxItem) => void
}) {
let label = "Recording"
let icon = <Camera className="size-3.5" />
let cta = "Take / pick file"
let kind: "photo" | "video" | "audio" = "photo"
if (recordType === "capture_photo") { label = "Photo"; cta = "Take or pick photo"; icon = <Camera className="size-3.5" />; kind = "photo" }
if (recordType === "record_video") { label = "Video"; cta = "Record or pick video"; icon = <Video className="size-3.5" />; kind = "video" }
if (recordType === "record_audio") { label = "Audio"; cta = "Record or pick audio"; icon = <Mic className="size-3.5" />; kind = "audio" }
const matching = media.filter((m) => {
if (recordType === "capture_photo") return m.media_type === "photo"
if (recordType === "record_video") return m.media_type === "video"
if (recordType === "record_audio") return m.media_type === "audio"
return true
})
return (
<div>
<div className="mb-2 flex items-center justify-between">
<Label className="flex items-center gap-2">
{label}
{required && <Badge variant="secondary" className="text-[10px]">required</Badge>}
{satisfied && <CheckCircle2 className="size-4 text-emerald-600" />}
</Label>
<Button type="button" size="sm" variant="outline" onClick={() => onPick(kind)} disabled={uploading}>
{uploading ? <Loader2 className="size-3.5 animate-spin" /> : icon}
{uploading ? "Uploading…" : cta}
</Button>
</div>
{matching.length === 0 ? (
<div className="rounded-md border border-dashed bg-muted/40 p-6 text-center text-xs text-muted-foreground flex flex-col items-center gap-1.5">
<ImageIcon className="size-5" />
{required ? `Tap the button above to add a ${label.toLowerCase()}` : `No ${label.toLowerCase()} yet`}
</div>
) : (
<div className={kind === "audio" ? "space-y-2" : "grid grid-cols-3 sm:grid-cols-4 gap-2"}>
{matching.map((m) => (
<div key={m.id} className="relative group rounded-md overflow-hidden border bg-muted">
<button
type="button"
onClick={() => onPreview(m as LightboxItem)}
className="block w-full"
>
{m.media_type === "photo" && m.url && (
// eslint-disable-next-line @next/next/no-img-element
<img src={m.url} alt={m.caption ?? ""} className="block w-full aspect-square object-cover" />
)}
{m.media_type === "video" && m.url && (
<div className="relative w-full aspect-square">
<video src={m.url} className="block w-full h-full object-cover" />
<div className="absolute inset-0 flex items-center justify-center bg-black/30 text-white">
<Video className="size-6" />
</div>
</div>
)}
{m.media_type === "audio" && m.url && (
<div className="p-2 w-full">
<audio src={m.url} controls className="w-full" />
</div>
)}
</button>
<Badge variant="secondary" className="absolute top-1 left-1 text-[9px] capitalize">{m.media_type}</Badge>
<button
type="button"
onClick={() => onDelete(m.id)}
className="absolute top-1 right-1 rounded-full bg-foreground/80 text-background p-1 opacity-0 group-hover:opacity-100 transition"
aria-label="Remove"
>
<Trash2 className="size-3" />
</button>
</div>
))}
</div>
)}
</div>
)
}
@@ -0,0 +1,59 @@
"use client"
import { Dialog, DialogContent } from "@/shared/components/ui/dialog"
export type LightboxItem = {
id: number
url: string | null
media_type: "photo" | "video" | "audio" | "document"
caption?: string | null
}
export function CheckpointMediaLightbox({
open,
onOpenChange,
item,
}: {
open: boolean
onOpenChange: (o: boolean) => void
item: LightboxItem | null
}) {
if (!item) return null
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-3xl p-0 bg-black/95 border-0">
<div className="flex items-center justify-center min-h-[60vh] max-h-[85vh] p-4">
{item.media_type === "photo" && item.url && (
// eslint-disable-next-line @next/next/no-img-element
<img
src={item.url}
alt={item.caption ?? ""}
className="max-w-full max-h-[80vh] object-contain"
/>
)}
{item.media_type === "video" && item.url && (
<video src={item.url} controls autoPlay className="max-w-full max-h-[80vh]" />
)}
{item.media_type === "audio" && item.url && (
<audio src={item.url} controls className="w-full" />
)}
{item.media_type === "document" && item.url && (
<a
href={item.url}
target="_blank"
rel="noopener noreferrer"
className="text-white underline"
>
Open document
</a>
)}
</div>
{item.caption && (
<div className="bg-black/80 text-white text-sm px-4 py-2 text-center">
{item.caption}
</div>
)}
</DialogContent>
</Dialog>
)
}
@@ -27,14 +27,21 @@ export function InspectionCategoryInlineForm({ onSuccess }: InlineCreateFormProp
const handleSubmit = async (values: FormValues) => {
try {
const result = await api.inspections.createCategory({
title: values.inspection_name,
inspection_name: values.inspection_name,
} as any)
toast.success("Inspection category created")
form.reset()
const item = (result as any)?.data ?? result
onSuccess({ value: String(item.id), label: item.name ?? values.inspection_name })
} catch {
toast.error("Failed to create inspection category")
onSuccess({
value: String(item.id),
label: item.inspection_name ?? values.inspection_name,
})
} catch (e: any) {
const errors = e?.payload?.errors
const firstError = errors && typeof errors === "object"
? (Object.values(errors)[0] as string[])?.[0]
: null
toast.error(firstError ?? e?.message ?? "Failed to create inspection category")
}
}
@@ -0,0 +1,43 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { ClipboardList, Printer, Share2 } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
/**
* Client island for the inspection detail page header — exposes the Share
* dialog and a quick link to the technician's checkpoints page without
* pulling the entire page out of the server-component tree.
*/
export function InspectionDetailHeader({
inspectionId,
title,
}: {
inspectionId: number | string
title?: string
}) {
const [shareOpen, setShareOpen] = useState(false)
return (
<div className="flex items-center justify-between flex-wrap gap-2 mb-3">
<div className="min-w-0">
<div className="text-xs text-muted-foreground uppercase tracking-wide">Inspection</div>
<h1 className="text-xl sm:text-2xl font-bold truncate">{title ?? "Inspection"}</h1>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" asChild>
<Link href={`/sales/inspections/${inspectionId}/checkpoints`}>
<ClipboardList className="size-4" /> Checkpoints
</Link>
</Button>
<Button variant="default" size="sm" onClick={() => setShareOpen(true)}>
<Share2 className="size-4" /> Share with customer
</Button>
</div>
<InspectionShareDialog open={shareOpen} onOpenChange={setShareOpen} inspectionId={inspectionId} />
</div>
)
}
@@ -1,5 +1,7 @@
"use client"
import { useEffect, useRef } from "react"
import { useFormContext, useWatch } from "react-hook-form"
import { AlertTriangle, Plus, Save } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
@@ -30,6 +32,7 @@ import {
INSPECTION_ROUTES,
DEPARTMENT_ROUTES,
JOB_CARD_ROUTES,
TAX_ROUTES,
InspectionStatus,
RateType,
} from "@garage/api"
@@ -67,7 +70,7 @@ const DEFAULT_VALUES: InspectionFormValues = {
rate: 0,
working_hours: 0,
labor_hours: 0,
tax: "",
tax: null,
chart_of_account: "",
}
@@ -100,7 +103,14 @@ function mapToFormValues(data: unknown): InspectionFormValues {
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 ?? "",
tax: d.tax_id
? {
value: String(d.tax_id),
label: d.tax?.title
? `${d.tax.title}${d.tax?.rate != null ? ` (${d.tax.rate}%)` : ""}`
: `#${d.tax_id}`,
}
: null,
chart_of_account: d.chart_of_account ?? "",
}
}
@@ -126,7 +136,7 @@ function mapFormToPayload(values: InspectionFormValues) {
rate: values.rate ?? undefined,
working_hours: values.working_hours ?? undefined,
labor_hours: values.labor_hours ?? undefined,
tax: values.tax || undefined,
tax_id: values.tax?.value ? Number(values.tax.value) : undefined,
chart_of_account: values.chart_of_account || undefined,
}
}
@@ -150,6 +160,37 @@ const mapLookupOption = (item: any) => ({
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
// ── Customer-scoped vehicle picker ──
// Watches the `customer` field. When it changes, clears the `vehicle` selection so a stale
// vehicle from a previous customer doesn't get submitted. While no customer is picked, the
// vehicle field is disabled — picking a vehicle without a customer makes no garage sense.
function CustomerScopedVehicleField() {
const { setValue, control, getValues } = useFormContext<InspectionFormValues>()
const customer = useWatch({ control, name: "customer" })
const customerId = customer?.value ?? null
const lastCustomerIdRef = useRef<string | null>(customerId)
useEffect(() => {
if (lastCustomerIdRef.current !== customerId) {
const currentVehicle = getValues("vehicle")
if (currentVehicle) {
setValue("vehicle", null, { shouldDirty: true, shouldValidate: false })
}
lastCustomerIdRef.current = customerId
}
}, [customerId, setValue, getValues])
return (
<RhfVehicleSelectField
name="vehicle"
customer_id={customerId}
disabled={!customerId}
placeholder={customerId ? "Search this customer's vehicles…" : "Select a customer first"}
/>
)
}
// ── Component ──
export function InspectionForm({ resourceId, initialData, onSuccess }: InspectionFormProps) {
@@ -200,7 +241,7 @@ export function InspectionForm({ resourceId, initialData, onSuccess }: Inspectio
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfCustomerSelectField name="customer" />
<RhfVehicleSelectField name="vehicle" />
<CustomerScopedVehicleField />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
@@ -221,7 +262,10 @@ export function InspectionForm({ resourceId, initialData, onSuccess }: Inspectio
placeholder="Select category"
queryKey={[INSPECTION_ROUTES.CATEGORIES]}
listFn={() => api.inspections.listCategories()}
mapOption={mapLookupOption}
mapOption={(item: any) => ({
value: String(item.id),
label: item.inspection_name ?? item.name ?? item.title ?? `#${item.id}`,
})}
createForm={(props) => <InspectionCategoryInlineForm {...props} />}
createLabel="Inspection Category"
{...STORE_OBJECT}
@@ -283,7 +327,20 @@ export function InspectionForm({ resourceId, initialData, onSuccess }: Inspectio
<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%" />
<RhfAsyncSelectField
name="tax"
label="Tax"
placeholder="Select tax rate"
queryKey={[TAX_ROUTES.INDEX]}
listFn={() => api.taxes.list()}
mapOption={(item: any) => ({
value: String(item.id),
label: item.title
? `${item.title}${item.rate != null ? ` (${item.rate}%)` : ""}`
: `#${item.id}`,
})}
{...STORE_OBJECT}
/>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
@@ -0,0 +1,262 @@
"use client"
import { useEffect, useState } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { toast } from "sonner"
import { ClipboardList, Plus } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
import { FieldGroup } from "@/shared/components/ui/field"
import {
Rhform,
RhfTextField,
RhfTextareaField,
RhfDateField,
RhfTimeField,
} from "@/shared/components/form"
import { useAuthApi } from "@/shared/useApi"
import type { InspectionTemplate } from "@garage/api"
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
import { RhfVehicleSelectField } from "@/modules/vehicles/rhf-vehicle-select-field"
import { RhfEmployeeSelectField } from "@/modules/employees/rhf-employee-select-field"
import { RhfAsyncSelectField } from "@/shared/components/form"
import { DEPARTMENT_ROUTES } from "@garage/api"
import { useFormContext, useWatch } from "react-hook-form"
import { useEffect as useReactEffect, useRef } from "react"
const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
const schema = z.object({
customer: relationFieldSchema.refine((v) => !!v?.value, "Customer is required"),
vehicle: relationFieldSchema.refine((v) => !!v?.value, "Vehicle is required"),
department: relationFieldSchema.refine((v) => !!v?.value, "Department is required"),
employee: relationFieldSchema.refine((v) => !!v?.value, "Employee is required"),
title: z.string().min(1, "Title is required").max(100),
order_number: z.string().min(1, "Order number is required").max(100),
date: z.string().min(1, "Date is required"),
time: z.string().min(1, "Time is required"),
odometer: z.coerce.number().int().min(0).optional().or(z.literal("")).transform(v => v === "" ? undefined : v),
note: z.string().optional(),
})
type FormValues = z.infer<typeof schema>
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
const mapLookupOption = (item: any) => ({ value: String(item.id), label: item.name ?? item.title ?? String(item.id) })
// Scope vehicle picker to selected customer
function CustomerScopedVehicleField() {
const { setValue, control, getValues } = useFormContext<FormValues>()
const customer = useWatch({ control, name: "customer" })
const customerId = customer?.value ?? null
const lastRef = useRef<string | null>(customerId)
useReactEffect(() => {
if (lastRef.current !== customerId) {
if (getValues("vehicle")) {
setValue("vehicle", null, { shouldDirty: true, shouldValidate: false })
}
lastRef.current = customerId
}
}, [customerId, setValue, getValues])
return (
<RhfVehicleSelectField
name="vehicle"
customer_id={customerId}
disabled={!customerId}
placeholder={customerId ? "Search this customer's vehicles…" : "Select a customer first"}
/>
)
}
export function InspectionFromTemplateForm({ onSuccess }: { onSuccess?: (inspectionId: number) => void }) {
const api = useAuthApi()
const [step, setStep] = useState<"pick-template" | "fill-details">("pick-template")
const [templates, setTemplates] = useState<InspectionTemplate[]>([])
const [selectedTemplate, setSelectedTemplate] = useState<InspectionTemplate | null>(null)
const [loadingTemplates, setLoadingTemplates] = useState(true)
const form = useForm<FormValues>({
resolver: zodResolver(schema) as any,
defaultValues: {
customer: null,
vehicle: null,
department: null,
employee: null,
title: "",
order_number: "",
date: new Date().toISOString().slice(0, 10),
time: new Date().toTimeString().slice(0, 8),
odometer: undefined,
note: "",
},
})
useEffect(() => {
let cancelled = false
setLoadingTemplates(true)
api.inspectionTemplates.list({ is_active: true }).then((res) => {
if (!cancelled) {
setTemplates(res.data ?? [])
setLoadingTemplates(false)
}
}).catch((e: any) => {
if (!cancelled) {
toast.error(e?.message ?? "Failed to load templates")
setLoadingTemplates(false)
}
})
return () => { cancelled = true }
}, [])
const pickTemplate = (t: InspectionTemplate) => {
setSelectedTemplate(t)
form.setValue("title", t.name)
setStep("fill-details")
}
const handleSubmit = async (values: FormValues) => {
if (!selectedTemplate) return
try {
const res = await api.inspections.createFromTemplate({
template_id: selectedTemplate.id,
title: values.title,
customer_id: values.customer!.value,
vehicle_id: values.vehicle!.value,
department_id: values.department!.value,
employee_id: values.employee!.value,
order_number: values.order_number,
date: values.date,
time: values.time,
odometer: values.odometer as any,
note: values.note || undefined,
})
const created = (res as any)?.data
toast.success("Inspection created with checkpoints from template")
onSuccess?.(created?.id)
} catch (e: any) {
const errors = e?.payload?.errors
const firstError = errors && typeof errors === "object"
? (Object.values(errors)[0] as string[])?.[0]
: null
toast.error(firstError ?? e?.message ?? "Failed to create inspection")
}
}
if (step === "pick-template") {
return (
<div className="space-y-3">
<div>
<h3 className="text-sm font-medium">Choose an inspection template</h3>
<p className="text-xs text-muted-foreground">
The selected template's sections and checkpoints will be cloned onto the new inspection.
</p>
</div>
{loadingTemplates && (
<div className="rounded border-dashed border p-6 text-center text-sm text-muted-foreground">Loading templates…</div>
)}
{!loadingTemplates && templates.length === 0 && (
<div className="rounded border-dashed border p-6 text-center text-sm text-muted-foreground">
No active templates. Create one under Settings → Inspection Templates.
</div>
)}
{!loadingTemplates && templates.length > 0 && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-[60vh] overflow-y-auto">
{templates.map((t) => {
const sectionCount = t.sections?.length ?? 0
const cpCount = (t.sections ?? []).reduce((s, sec) => s + (sec.check_points?.length ?? 0), 0)
const empty = cpCount === 0
return (
<button
type="button"
key={t.id}
onClick={() => !empty && pickTemplate(t)}
disabled={empty}
title={empty ? "This template has no checkpoints yet — add some in Settings → Inspection Templates" : undefined}
className={`rounded border p-3 text-left transition ${
empty
? "opacity-50 cursor-not-allowed border-dashed"
: "hover:border-primary hover:bg-primary/5"
}`}
>
<div className="flex items-start gap-2">
<ClipboardList className="size-4 mt-0.5 text-muted-foreground" />
<div className="flex-1 min-w-0">
<div className="font-medium text-sm flex items-center gap-2">
{t.name}
{empty && (
<span className="text-[10px] uppercase tracking-wide bg-amber-100 text-amber-800 px-1.5 py-0.5 rounded">
Empty
</span>
)}
</div>
{t.description && (
<div className="text-xs text-muted-foreground line-clamp-2 mt-0.5">
{t.description}
</div>
)}
<div className="text-xs text-muted-foreground mt-1">
{sectionCount} sections · {cpCount} checkpoints
</div>
</div>
</div>
</button>
)
})}
</div>
)}
</div>
)
}
return (
<Rhform form={form} onSubmit={handleSubmit}>
<div className="flex items-center justify-between mb-3">
<div className="text-sm">
<span className="text-muted-foreground">Template:</span>{" "}
<span className="font-medium">{selectedTemplate?.name}</span>
</div>
<Button type="button" variant="ghost" size="sm" onClick={() => setStep("pick-template")}>
Change template
</Button>
</div>
<FieldGroup>
<RhfTextField name="title" label="Title" placeholder="e.g. Pre-purchase" required />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfCustomerSelectField name="customer" />
<CustomerScopedVehicleField />
</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}
/>
<RhfEmployeeSelectField name="employee" />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<RhfTextField name="order_number" label="Order number" placeholder="e.g. ORD-001" required />
<RhfDateField name="date" label="Date" />
<RhfTimeField name="time" label="Time" withSeconds />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="odometer" label="Odometer" type="number" placeholder="km" />
</div>
<RhfTextareaField name="note" label="Note" placeholder="Internal notes…" />
<Button type="submit" variant="default" disabled={form.formState.isSubmitting}>
<Plus className="size-4" />
{form.formState.isSubmitting ? "Creating…" : "Create inspection"}
</Button>
</FieldGroup>
</Rhform>
)
}
@@ -0,0 +1,164 @@
"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import {
CheckCircle2,
ClipboardList,
Eye,
MoreHorizontal,
Pencil,
PlayCircle,
Share2,
Trash2,
XCircle,
} from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
import { INSPECTION_ROUTES } from "@garage/api"
type InspectionStatus = "in_progress" | "completed" | "cancelled"
type InspectionRow = {
id: number | string
status?: InspectionStatus | string
}
export function InspectionRowActions({
inspection,
onEdit,
onDelete,
}: {
inspection: InspectionRow
onEdit: () => void
onDelete: () => Promise<unknown>
}) {
const router = useRouter()
const api = useAuthApi()
const queryClient = useQueryClient()
const [shareOpen, setShareOpen] = useState(false)
const inspectionId = String(inspection.id)
const status = inspection.status as InspectionStatus | undefined
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: [INSPECTION_ROUTES.INDEX] })
queryClient.invalidateQueries({ queryKey: [INSPECTION_ROUTES.BY_ID, inspectionId] })
}
const changeStatus = async (next: InspectionStatus, label: string) => {
try {
await api.inspections.changeStatus({
id: Number(inspectionId),
status: next,
} as any)
toast.success(label)
invalidate()
} catch (e: any) {
// Surface backend validation / permission errors verbatim so the user
// (and we) can see what actually failed.
const errors = e?.payload?.errors
const firstFieldError = errors && typeof errors === "object"
? (Object.values(errors)[0] as string[])?.[0]
: null
const msg =
firstFieldError ??
e?.payload?.message ??
e?.message ??
`Failed: ${label}`
toast.error(msg)
// eslint-disable-next-line no-console
console.error("changeStatus failed", { inspectionId, next, error: e })
}
}
const handleDelete = async (e: React.MouseEvent) => {
e.stopPropagation()
const confirmed = await confirm({
title: "Delete this inspection?",
description: "This will remove the inspection and all its checkpoints. This cannot be undone.",
confirmLabel: "Delete",
variant: "destructive",
})
if (confirmed) {
try {
await onDelete()
toast.success("Inspection deleted")
} catch (err: any) {
toast.error(err?.payload?.message ?? err?.message ?? "Failed to delete inspection")
}
}
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
onClick={(e) => e.stopPropagation()}
>
<MoreHorizontal className="size-4" />
<span className="sr-only">Inspection actions</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
<DropdownMenuItem onClick={() => router.push(`/sales/inspections/${inspectionId}`)}>
<Eye className="size-3.5 text-muted-foreground" /> View detail
</DropdownMenuItem>
<DropdownMenuItem onClick={() => router.push(`/sales/inspections/${inspectionId}/checkpoints`)}>
<ClipboardList className="size-3.5 text-muted-foreground" /> Open checkpoints
</DropdownMenuItem>
<DropdownMenuItem onClick={onEdit}>
<Pencil className="size-3.5 text-muted-foreground" /> Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-3.5 text-muted-foreground" /> Share with customer
</DropdownMenuItem>
<DropdownMenuSeparator />
{status === "cancelled" || status === "completed" ? (
<DropdownMenuItem onClick={() => changeStatus("in_progress", "Reopened — back to in progress")}>
<PlayCircle className="size-3.5 text-amber-600" /> Reopen as in progress
</DropdownMenuItem>
) : (
<DropdownMenuItem onClick={() => changeStatus("completed", "Inspection marked completed")}>
<CheckCircle2 className="size-3.5 text-emerald-600" /> Mark completed
</DropdownMenuItem>
)}
{status !== "cancelled" && (
<DropdownMenuItem onClick={() => changeStatus("cancelled", "Inspection cancelled")}>
<XCircle className="size-3.5 text-rose-600" /> Cancel
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-3.5" /> Delete
</DropdownMenuItem>
</DropdownMenuContent>
<InspectionShareDialog
open={shareOpen}
onOpenChange={setShareOpen}
inspectionId={inspectionId}
/>
</DropdownMenu>
)
}
@@ -0,0 +1,139 @@
"use client"
import { useEffect, useState } from "react"
import { toast } from "sonner"
import { Check, Copy, ExternalLink, Link2, XCircle } from "lucide-react"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
export function InspectionShareDialog({
open,
onOpenChange,
inspectionId,
}: {
open: boolean
onOpenChange: (o: boolean) => void
inspectionId: number | string
}) {
const api = useAuthApi()
const [loading, setLoading] = useState(false)
const [shareUrl, setShareUrl] = useState<string | null>(null)
const [expiresAt, setExpiresAt] = useState<string | null>(null)
const [copied, setCopied] = useState(false)
const generate = async () => {
setLoading(true)
try {
const res = await api.inspections.share(inspectionId)
setShareUrl(res.data.share_url)
setExpiresAt(res.data.share_expires_at)
} catch (e: any) {
toast.error(e?.payload?.message ?? e?.message ?? "Failed to generate share link")
onOpenChange(false)
} finally {
setLoading(false)
}
}
useEffect(() => {
if (open && !shareUrl) generate()
if (!open) {
setShareUrl(null)
setExpiresAt(null)
setCopied(false)
}
}, [open])
const copy = async () => {
if (!shareUrl) return
try {
await navigator.clipboard.writeText(shareUrl)
setCopied(true)
toast.success("Link copied")
setTimeout(() => setCopied(false), 2000)
} catch {
toast.error("Copy failed — select the field and press Cmd/Ctrl+C")
}
}
const revoke = async () => {
const ok = await confirm({
title: "Revoke this share link?",
description: "The customer will no longer be able to view the report.",
confirmLabel: "Revoke",
variant: "destructive",
})
if (!ok) return
try {
await api.inspections.revokeShare(inspectionId)
toast.success("Share link revoked")
onOpenChange(false)
} catch (e: any) {
toast.error(e?.payload?.message ?? e?.message ?? "Failed to revoke")
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Link2 className="size-4" /> Share inspection with customer
</DialogTitle>
<DialogDescription>
Anyone with this link can view the inspection report. No login required.
</DialogDescription>
</DialogHeader>
{loading && (
<div className="py-6 text-center text-sm text-muted-foreground">Generating link…</div>
)}
{shareUrl && (
<div className="space-y-3">
<div className="flex items-center gap-2">
<Input value={shareUrl} readOnly className="font-mono text-xs" />
<Button type="button" size="sm" onClick={copy}>
{copied ? <Check className="size-4" /> : <Copy className="size-4" />}
{copied ? "Copied" : "Copy"}
</Button>
</div>
{expiresAt && (
<p className="text-xs text-muted-foreground">
Expires on {new Date(expiresAt).toLocaleDateString()}.
</p>
)}
<div className="flex items-center justify-between text-xs">
<a
href={shareUrl}
target="_blank"
rel="noopener noreferrer"
className="text-primary inline-flex items-center gap-1 hover:underline"
>
<ExternalLink className="size-3.5" /> Open preview in new tab
</a>
</div>
</div>
)}
<DialogFooter className="flex justify-between gap-2 sm:justify-between">
<Button variant="ghost" size="sm" onClick={revoke} disabled={!shareUrl}>
<XCircle className="size-4 text-rose-600" /> Revoke link
</Button>
<Button variant="outline" onClick={() => onOpenChange(false)}>Done</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -24,7 +24,7 @@ const inspectionFormSchema = z.object({
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(),
tax: relationFieldSchema.optional(),
chart_of_account: z.string().optional(),
})
@@ -0,0 +1,119 @@
"use client"
import { useEffect, useRef, useState } from "react"
import { Eraser, Save } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
type Props = {
label: string
existingUrl?: string | null
onSave: (dataUrl: string) => Promise<void> | void
saving?: boolean
}
/**
* Minimal in-house signature pad — uses <canvas> + pointer events.
* Works with mouse, touch, and stylus on any device. No external dep.
*/
export function SignaturePad({ label, existingUrl, onSave, saving }: Props) {
const canvasRef = useRef<HTMLCanvasElement>(null)
const drawingRef = useRef(false)
const lastPointRef = useRef<{ x: number; y: number } | null>(null)
const [hasDrawn, setHasDrawn] = useState(false)
const getCtx = () => {
const c = canvasRef.current
if (!c) return null
const ctx = c.getContext("2d")
if (!ctx) return null
ctx.lineWidth = 2.2
ctx.lineCap = "round"
ctx.lineJoin = "round"
ctx.strokeStyle = "#111"
return ctx
}
useEffect(() => {
// Size the canvas to its CSS size while keeping crisp lines on HiDPI screens.
const c = canvasRef.current
if (!c) return
const dpr = window.devicePixelRatio || 1
const rect = c.getBoundingClientRect()
c.width = Math.round(rect.width * dpr)
c.height = Math.round(rect.height * dpr)
const ctx = c.getContext("2d")
ctx?.scale(dpr, dpr)
}, [])
const pointFromEvent = (e: React.PointerEvent<HTMLCanvasElement>) => {
const rect = (e.target as HTMLCanvasElement).getBoundingClientRect()
return { x: e.clientX - rect.left, y: e.clientY - rect.top }
}
const handleDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
e.preventDefault()
;(e.target as HTMLCanvasElement).setPointerCapture(e.pointerId)
drawingRef.current = true
lastPointRef.current = pointFromEvent(e)
}
const handleMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!drawingRef.current) return
const ctx = getCtx()
if (!ctx || !lastPointRef.current) return
const p = pointFromEvent(e)
ctx.beginPath()
ctx.moveTo(lastPointRef.current.x, lastPointRef.current.y)
ctx.lineTo(p.x, p.y)
ctx.stroke()
lastPointRef.current = p
setHasDrawn(true)
}
const handleUp = () => {
drawingRef.current = false
lastPointRef.current = null
}
const clear = () => {
const c = canvasRef.current
const ctx = getCtx()
if (!c || !ctx) return
ctx.clearRect(0, 0, c.width, c.height)
setHasDrawn(false)
}
const submit = async () => {
if (!canvasRef.current || !hasDrawn) return
const dataUrl = canvasRef.current.toDataURL("image/png")
await onSave(dataUrl)
}
return (
<div className="rounded border bg-white">
<div className="flex items-center justify-between px-3 py-2 border-b bg-muted/30">
<span className="text-sm font-medium">{label}</span>
<div className="flex items-center gap-1">
<Button type="button" variant="ghost" size="sm" onClick={clear} disabled={saving}>
<Eraser className="size-3.5" /> Clear
</Button>
<Button type="button" size="sm" onClick={submit} disabled={!hasDrawn || saving}>
<Save className="size-3.5" /> {saving ? "Saving…" : "Save"}
</Button>
</div>
</div>
{existingUrl && !hasDrawn && (
<div className="px-3 pt-2 text-xs text-muted-foreground">
Previously signed:
<img src={existingUrl} alt="" className="block max-h-20 mt-1" />
</div>
)}
<canvas
ref={canvasRef}
className="block w-full h-32 touch-none bg-white"
onPointerDown={handleDown}
onPointerMove={handleMove}
onPointerUp={handleUp}
onPointerCancel={handleUp}
/>
</div>
)
}
@@ -0,0 +1,219 @@
"use client"
import { useEffect, useState } from "react"
import { toast } from "sonner"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Textarea } from "@/shared/components/ui/textarea"
import { Label } from "@/shared/components/ui/label"
import { useAuthApi } from "@/shared/useApi"
import type {
InspectionSeverity,
InspectionTemplateCheckPoint,
InspectionTemplateCheckPointRecordType,
} from "@garage/api"
const RECORD_TYPE_OPTIONS: { value: InspectionTemplateCheckPointRecordType; label: string }[] = [
{ value: "none", label: "No media" },
{ value: "capture_photo", label: "Capture photo" },
{ value: "record_video", label: "Record video" },
{ value: "record_audio", label: "Record audio" },
{ value: "record_conditions", label: "Condition rating (0–100)" },
{ value: "wire_frame", label: "Wireframe diagram" },
]
const SEVERITY_OPTIONS: { value: InspectionSeverity; label: string; cls: string }[] = [
{ value: "not_inspected", label: "Not inspected", cls: "bg-gray-100 text-gray-700" },
{ value: "good", label: "Good", cls: "bg-emerald-100 text-emerald-800" },
{ value: "attention", label: "Needs attention", cls: "bg-amber-100 text-amber-800" },
{ value: "critical", label: "Critical", cls: "bg-rose-100 text-rose-800" },
{ value: "na", label: "Not applicable", cls: "bg-slate-100 text-slate-700" },
]
export type CheckpointDraft = {
name: string
description: string
record_type: InspectionTemplateCheckPointRecordType
severity_default: InspectionSeverity
sort_order: number
}
export function TemplateCheckpointEditDialog({
open,
onOpenChange,
templateId,
sectionId,
checkpoint,
nextSortOrder,
onSaved,
}: {
open: boolean
onOpenChange: (open: boolean) => void
templateId: number
sectionId: number
/** When set, edit this checkpoint. When null, create new. */
checkpoint: InspectionTemplateCheckPoint | null
nextSortOrder?: number
onSaved: () => void
}) {
const api = useAuthApi()
const isEdit = !!checkpoint
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [recordType, setRecordType] = useState<InspectionTemplateCheckPointRecordType>("capture_photo")
const [severity, setSeverity] = useState<InspectionSeverity>("not_inspected")
const [sortOrder, setSortOrder] = useState<number>(1)
const [saving, setSaving] = useState(false)
useEffect(() => {
if (!open) return
if (checkpoint) {
setName(checkpoint.name)
setDescription(checkpoint.description ?? "")
setRecordType(checkpoint.record_type)
setSeverity(checkpoint.severity_default)
setSortOrder(checkpoint.sort_order)
} else {
setName("")
setDescription("")
setRecordType("capture_photo")
setSeverity("not_inspected")
setSortOrder(nextSortOrder ?? 1)
}
}, [open, checkpoint, nextSortOrder])
const submit = async () => {
if (!name.trim()) {
toast.error("Name is required")
return
}
setSaving(true)
try {
const payload = {
name: name.trim(),
description: description.trim() || undefined,
record_type: recordType,
severity_default: severity,
sort_order: sortOrder,
}
if (isEdit && checkpoint) {
await api.inspectionTemplates.updateCheckpoint(templateId, sectionId, checkpoint.id, payload)
toast.success("Checkpoint updated")
} else {
await api.inspectionTemplates.createCheckpoint(templateId, sectionId, payload)
toast.success("Checkpoint added")
}
onSaved()
onOpenChange(false)
} catch (e: any) {
const errors = e?.payload?.errors
const firstError = errors && typeof errors === "object"
? (Object.values(errors)[0] as string[])?.[0]
: null
toast.error(firstError ?? e?.message ?? (isEdit ? "Failed to update checkpoint" : "Failed to add checkpoint"))
} finally {
setSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{isEdit ? "Edit checkpoint" : "Add checkpoint"}</DialogTitle>
<DialogDescription>
Define what the technician will check and how the finding is recorded.
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="grid gap-1.5">
<Label htmlFor="cp-name">Name</Label>
<Input
id="cp-name"
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Front-left brake pad thickness"
/>
</div>
<div className="grid gap-1.5">
<Label htmlFor="cp-description">Description (optional)</Label>
<Textarea
id="cp-description"
value={description}
rows={2}
onChange={(e) => setDescription(e.target.value)}
placeholder="Brief guidance for the technician"
/>
</div>
<div className="grid gap-1.5">
<Label>How it's recorded</Label>
<div className="grid grid-cols-2 gap-1.5">
{RECORD_TYPE_OPTIONS.map((opt) => (
<button
type="button"
key={opt.value}
onClick={() => setRecordType(opt.value)}
className={`rounded border px-2 py-1.5 text-xs text-left transition ${
recordType === opt.value ? "border-primary bg-primary/5 text-foreground" : "text-muted-foreground hover:border-foreground/30"
}`}
>
{opt.label}
</button>
))}
</div>
</div>
<div className="grid gap-1.5">
<Label>Default severity (when not yet inspected)</Label>
<div className="flex flex-wrap gap-1.5">
{SEVERITY_OPTIONS.map((opt) => (
<button
type="button"
key={opt.value}
onClick={() => setSeverity(opt.value)}
className={`rounded-full px-3 py-1 text-xs font-medium transition border ${
severity === opt.value ? "border-primary ring-1 ring-primary " + opt.cls : opt.cls + " border-transparent opacity-70 hover:opacity-100"
}`}
>
{opt.label}
</button>
))}
</div>
</div>
<div className="grid gap-1.5 max-w-[160px]">
<Label htmlFor="cp-order">Sort order</Label>
<Input
id="cp-order"
type="number"
min={0}
value={sortOrder}
onChange={(e) => setSortOrder(parseInt(e.target.value || "0", 10))}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>Cancel</Button>
<Button onClick={submit} disabled={saving || !name.trim()}>
{saving ? "Saving…" : isEdit ? "Save changes" : "Add checkpoint"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}