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
@@ -3,7 +3,8 @@
import { Receipt } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillExpense = {
id: number
@@ -62,14 +63,14 @@ export function BillExpensesSection({ expenses = [] }: BillExpensesSectionProps)
{expense.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -19,9 +19,10 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { cn } from "@/shared/lib/utils"
import { formatDate, formatCurrency, formatEnum } from "@/shared/utils/formatters"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { useBill } from "./bill-context"
import { Money } from "@/shared/components/money"
function InfoItem({
icon: Icon,
@@ -3,7 +3,8 @@
import { Wrench } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillPart = {
id: number
@@ -62,14 +63,14 @@ export function BillPartsSection({ parts = [] }: BillPartsSectionProps) {
{part.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -17,7 +17,6 @@ import { PaymentMadeForm } from "@/modules/payment-mades/payment-made-form"
import { useBill } from "./bill-context"
import { formatDate } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { toRelation } from "@/shared/lib/utils"
export function BillPaymentsSection() {
const bill = useBill()
@@ -39,8 +38,17 @@ export function BillPaymentsSection() {
{(resourceId) => (
<PaymentMadeForm
initialData={{
amount: bill?.balance_due,
vendor: toRelation(bill?.vendor?.id, getFullName(bill?.vendor as any)),
// API-shape keys so PaymentMadeForm.mapToFormValues
// can pick them up (it reads `payment_made` / `vendor_id`
// / `vendor.*`, not the form-shape fields). bill_id +
// bill_number are required because the bill field is
// hidden when billId is supplied, but the schema still
// demands a populated bill relation.
bill_id: bill?.id,
bill_number: bill?.bill_number,
payment_made: bill?.balance_due,
vendor_id: bill?.vendor?.id,
vendor: bill?.vendor,
payment_for: "bill",
}}
billId={bill?.id}
@@ -77,7 +85,7 @@ export function BillPaymentsSection() {
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{item.vendor?.name || item.vendor_name || "—"}</span>
<span>{item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name || "—"}</span>
</div>
)
},
@@ -3,7 +3,8 @@
import { Briefcase } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillService = {
id: number
@@ -62,14 +63,14 @@ export function BillServicesSection({ services = [] }: BillServicesSectionProps)
{service.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -2,9 +2,10 @@
import { Card, CardContent } from "@/shared/components/ui/card"
import { Separator } from "@/shared/components/ui/separator"
import { formatCurrency, formatEnum } from "@/shared/utils/formatters"
import { formatEnum } from "@/shared/utils/formatters"
import { cn } from "@/shared/lib/utils"
import { useBill } from "./bill-context"
import { Money } from "@/shared/components/money"
export function BillTotalsSummary() {
const bill = useBill()
@@ -46,70 +47,65 @@ export function BillTotalsSummary() {
{parts.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Parts ({parts.length})</span>
<span>{formatCurrency(partsTotal)}</span>
<span>{<Money value={partsTotal} />}</span>
</div>
)}
{services.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Services ({services.length})</span>
<span>{formatCurrency(servicesTotal)}</span>
<span>{<Money value={servicesTotal} />}</span>
</div>
)}
{expenses.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Expenses ({expenses.length})</span>
<span>{formatCurrency(expensesTotal)}</span>
<span>{<Money value={expensesTotal} />}</span>
</div>
)}
<Separator />
<div className="flex justify-between text-sm font-medium">
<span>Subtotal</span>
<span>{formatCurrency(subTotal)}</span>
<span>{<Money value={subTotal} />}</span>
</div>
{discountAmount > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Discount{discount && discount !== "no" ? ` (${formatEnum(discount)})` : ""}</span>
<span className="text-muted-foreground">−{formatCurrency(discountAmount)}</span>
<span className="text-muted-foreground">−{<Money value={discountAmount} />}</span>
</div>
)}
{taxAmount > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Tax{bill.tax?.name ? ` (${bill.tax.name})` : ""}</span>
<span>{formatCurrency(taxAmount)}</span>
<span>{<Money value={taxAmount} />}</span>
</div>
)}
<Separator />
<div className="flex justify-between text-base font-semibold">
<span>Total</span>
<span>{<Money value={total} />}</span>
</div>
{paymentsMade > 0 && (
<div className="flex justify-between text-sm text-muted-foreground">
<span>Amount Paid</span>
<span>– {<Money value={paymentsMade} />}</span>
</div>
)}
<Separator />
<div className={cn(
"flex justify-between rounded-lg px-3 py-2 text-base font-bold bg-muted/50",
"flex justify-between rounded-lg px-3 py-2 text-base font-bold",
balanceDue > 0 ? "bg-primary/10 text-primary" : "bg-green-500/10 text-green-600",
)}>
<span>Total</span>
<span>{formatCurrency(total)}</span>
<span>Balance Due</span>
<span>{<Money value={balanceDue} />}</span>
</div>
{paymentsMade > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Payments Made</span>
<span className="text-emerald-600">−{formatCurrency(paymentsMade)}</span>
</div>
)}
{paymentsMade > 0 && (
<>
<Separator />
<div className={cn(
"flex justify-between rounded-lg px-3 py-2 text-base font-semibold",
balanceDue > 0 ? "text-destructive bg-destructive/5" : "text-emerald-700 bg-emerald-50 dark:bg-emerald-950/20",
)}>
<span>Balance Due</span>
<span>{formatCurrency(balanceDue)}</span>
</div>
</>
)}
</div>
</CardContent>
</Card>
@@ -169,6 +169,7 @@ export function EstimateExpenseItemsSection({ estimateId }: { estimateId: string
onOpenChange={setPickerOpen}
selectionMode="single"
onConfirm={handlePickerConfirm}
searchPlaceholder="Search expense items..."
crudProps={{
routeKey: EXPENSE_ITEM_ROUTES.INDEX,
getClient: (api) => api.expenseItems,
@@ -168,6 +168,7 @@ export function EstimatePartsSection({ estimateId }: { estimateId: string }) {
onOpenChange={setPickerOpen}
selectionMode="single"
onConfirm={handlePickerConfirm}
searchPlaceholder="Search parts by title, SKU, or part number..."
crudProps={{
routeKey: PARTS_ROUTES.INDEX,
getClient: (api) => api.parts,
@@ -181,6 +181,7 @@ export function EstimateServicesSection({ estimateId }: { estimateId: string })
onOpenChange={setPickerOpen}
selectionMode="single"
onConfirm={handlePickerConfirm}
searchPlaceholder="Search services..."
crudProps={{
routeKey: SERVICE_ROUTES.INDEX,
getClient: (api) => api.services,
@@ -2,8 +2,9 @@
import { Card, CardContent } from "@/shared/components/ui/card"
import { Separator } from "@/shared/components/ui/separator"
import { formatCurrency, formatEnum } from "@/shared/utils/formatters"
import { formatEnum } from "@/shared/utils/formatters"
import { useEstimate } from "./estimate-context"
import { Money } from "@/shared/components/money"
export function EstimateTotalsSummary() {
const estimate = useEstimate()
@@ -39,19 +40,19 @@ export function EstimateTotalsSummary() {
{parts.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Parts ({parts.length})</span>
<span>{formatCurrency(lineTotal(parts))}</span>
<span>{<Money value={lineTotal(parts)} />}</span>
</div>
)}
{services.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Services ({services.length})</span>
<span>{formatCurrency(lineTotal(services))}</span>
<span>{<Money value={lineTotal(services)} />}</span>
</div>
)}
{expenses.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Expenses ({expenses.length})</span>
<span>{formatCurrency(lineTotal(expenses))}</span>
<span>{<Money value={lineTotal(expenses)} />}</span>
</div>
)}
<Separator />
@@ -60,7 +61,7 @@ export function EstimateTotalsSummary() {
<div className="flex justify-between text-sm font-medium">
<span>Subtotal</span>
<span>{formatCurrency(subTotal)}</span>
<span>{<Money value={subTotal} />}</span>
</div>
{discount && discount !== "no" && (
@@ -74,7 +75,7 @@ export function EstimateTotalsSummary() {
<div className="flex justify-between text-base font-semibold">
<span>Total</span>
<span>{formatCurrency(displayTotal)}</span>
<span>{<Money value={displayTotal} />}</span>
</div>
</div>
</CardContent>
@@ -58,6 +58,7 @@ export function ExpenseItemsSelectorField<
itemKey="expense_id"
dialogProps={{
title: "Select Expense Items",
searchPlaceholder: "Search expense items...",
crudProps: {
routeKey: EXPENSE_ITEM_ROUTES.INDEX,
getClient: (api) => api.expenseItems,
@@ -20,8 +20,9 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { cn } from "@/shared/lib/utils"
import { formatDate, formatCurrency, formatEnum, formatTaxLabel } from "@/shared/utils/formatters"
import { formatDate, formatEnum, formatTaxLabel } from "@/shared/utils/formatters"
import { useExpense } from "./expense-context"
import { Money } from "@/shared/components/money"
function InfoItem({
icon: Icon,
@@ -30,7 +31,7 @@ function InfoItem({
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value?: string | null
value?: React.ReactNode
}) {
return (
<div className="flex items-start gap-3">
@@ -92,10 +93,10 @@ export function ExpenseGeneralInfo() {
<Card className="flex flex-col gap-1 p-4">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Total</span>
<span className="mt-1 text-lg font-semibold">
{formatCurrency(expense.total ?? 0)}
{<Money value={expense.total ?? 0} />}
</span>
{expense.sub_total != null && expense.sub_total !== expense.total && (
<span className="text-xs text-muted-foreground">Subtotal: {formatCurrency(expense.sub_total)}</span>
<span className="text-xs text-muted-foreground">Subtotal: {<Money value={expense.sub_total} />}</span>
)}
</Card>
@@ -103,7 +104,7 @@ export function ExpenseGeneralInfo() {
<Card className="flex flex-col gap-1 p-4">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Paid</span>
<span className="mt-1 text-lg font-semibold text-green-600 dark:text-green-400">
{formatCurrency(paymentsM ?? 0)}
{<Money value={paymentsM ?? 0} />}
</span>
</Card>
@@ -111,7 +112,7 @@ export function ExpenseGeneralInfo() {
<Card className={cn("flex flex-col gap-1 p-4", (balanceDue ?? 0) > 0 && "border-destructive/50 bg-destructive/5")}>
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Balance Due</span>
<span className={cn("mt-1 text-lg font-semibold", (balanceDue ?? 0) > 0 ? "text-destructive" : "text-green-600 dark:text-green-400")}>
{formatCurrency(balanceDue ?? 0)}
{<Money value={balanceDue ?? 0} />}
</span>
</Card>
</div>
@@ -139,10 +140,10 @@ export function ExpenseGeneralInfo() {
<InfoItem icon={Percent} label="Discount Type" value={formatEnum(expense.discount)} />
)}
{expense.discount_amount_major != null && expense.discount_amount_major > 0 && (
<InfoItem icon={Percent} label="Discount" value={formatCurrency(expense.discount_amount_major)} />
<InfoItem icon={Percent} label="Discount" value={<Money value={expense.discount_amount_major} />} />
)}
{expense.tax_amount != null && expense.tax_amount > 0 && (
<InfoItem icon={Percent} label={taxLabel} value={formatCurrency(expense.tax_amount)} />
<InfoItem icon={Percent} label={taxLabel} value={<Money value={expense.tax_amount} />} />
)}
</div>
</CardContent>
@@ -10,7 +10,7 @@ import {
TableHeader,
TableRow,
} from "@/shared/components/ui/table"
import { formatCurrency } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type ExpenseItem = {
id?: number
@@ -89,8 +89,8 @@ export function ExpenseItemsSection({
{item.description || "—"}
</TableCell>
<TableCell className="text-right text-sm">{qty.toLocaleString()}</TableCell>
<TableCell className="text-right text-sm">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-semibold">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right text-sm">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-semibold">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
@@ -104,25 +104,25 @@ export function ExpenseItemsSection({
{subTotal != null && (
<div className="flex justify-between">
<span className="text-muted-foreground">Subtotal</span>
<span className="font-medium">{formatCurrency(subTotal)}</span>
<span className="font-medium">{<Money value={subTotal} />}</span>
</div>
)}
{discountAmount != null && discountAmount > 0 && discountType !== "no" && (
<div className="flex justify-between text-destructive">
<span>Discount</span>
<span>− {formatCurrency(discountAmount)}</span>
<span>− {<Money value={discountAmount} />}</span>
</div>
)}
{taxAmount != null && taxAmount > 0 && (
<div className="flex justify-between">
<span className="text-muted-foreground">{taxLabel || "Tax"}</span>
<span className="font-medium">{formatCurrency(taxAmount)}</span>
<span className="font-medium">{<Money value={taxAmount} />}</span>
</div>
)}
{total != null && (
<div className="flex justify-between border-t pt-2 text-base font-semibold">
<span>Total</span>
<span>{formatCurrency(total)}</span>
<span>{<Money value={total} />}</span>
</div>
)}
</div>
@@ -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>
)
}
@@ -1,9 +1,12 @@
"use client"
import { useState } from "react"
import { AlertTriangle, Plus, Save, Trash2 } from "lucide-react"
import { useFieldArray } from "react-hook-form"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
import { FieldGroup } from "@/shared/components/ui/field"
import {
@@ -11,6 +14,9 @@ import {
RhfTextField,
RhfTextareaField,
RhfAsyncSelectField,
RhfAutoGenerateField,
RhfSelectField,
type InlineCreateFormProps,
} from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
@@ -34,32 +40,57 @@ export type InventoryAdjustmentFormProps = {
// ── Default values ──
const OPERATION_OPTIONS = [
{ value: "add", label: "Increase" },
{ value: "subtract", label: "Decrease" },
]
const DEFAULT_VALUES: InventoryAdjustmentFormValues = {
reference_number: "",
date: "",
chart_of_account: "",
chart_of_account: undefined,
reason: null,
notes: "",
parts: [{ part: null, quantity: 1, rate: 0 }],
parts: [{ part: null, quantity: 1, operation: "add", rate: 0 }],
}
// ── Mapping helpers ──
function mapToFormValues(data: unknown): InventoryAdjustmentFormValues {
const d = (data as any)?.data ?? data ?? {}
// Laravel serializes the `inventoryAdjustmentParts` relation as
// `inventory_adjustment_parts` in JSON; fall back through the other
// shapes for resilience.
const rawParts: any[] =
(Array.isArray(d.inventory_adjustment_parts) && d.inventory_adjustment_parts)
|| (Array.isArray(d.inventoryAdjustmentParts) && d.inventoryAdjustmentParts)
|| (Array.isArray(d.parts) && d.parts)
|| []
// Backend casts `date` to Carbon → serializes as an ISO string
// ("2026-05-18T00:00:00.000000Z"). HTML <input type="date"> only accepts
// "YYYY-MM-DD", so slice the first 10 chars; pass through plain dates.
const rawDate = d.date ?? ""
const date = typeof rawDate === "string" && rawDate.length >= 10
? rawDate.slice(0, 10)
: ""
return {
reference_number: d.reference_number || "",
date: d.date || "",
chart_of_account: d.chart_of_account || "",
reason: toRelation(d.reason_id, d.reason_name),
date,
chart_of_account: d.chart_of_account != null && d.chart_of_account !== ""
? Number(d.chart_of_account)
: undefined,
reason: toRelation(d.reason_id, d.reason?.title ?? d.reason?.name ?? d.reason_name),
notes: d.notes || "",
parts: Array.isArray(d.parts) && d.parts.length > 0
? d.parts.map((p: any) => ({
part: toRelation(p.part_id, p.part_name),
parts: rawParts.length > 0
? rawParts.map((p: any) => ({
part: toRelation(p.part_id, p.part?.title ?? p.part?.name ?? p.part_name),
quantity: p.quantity ?? 1,
operation: (p.operation === "subtract" ? "subtract" : "add") as "add" | "subtract",
rate: p.rate ?? 0,
}))
: [{ part: null, quantity: 1, rate: 0 }],
: [{ part: null, quantity: 1, operation: "add", rate: 0 }],
}
}
@@ -67,12 +98,13 @@ function mapFormToPayload(values: InventoryAdjustmentFormValues) {
return {
reference_number: values.reference_number || undefined,
date: values.date || undefined,
chart_of_account: values.chart_of_account || undefined,
chart_of_account: values.chart_of_account ?? undefined,
reason_id: toId(values.reason) ? Number(toId(values.reason)) : undefined,
notes: values.notes || undefined,
parts: values.parts.map((p) => ({
part_id: toId(p.part) ? Number(toId(p.part)) : undefined,
quantity: p.quantity,
operation: p.operation,
rate: p.rate,
})),
}
@@ -81,6 +113,52 @@ function mapFormToPayload(values: InventoryAdjustmentFormValues) {
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 }
function ReasonInlineCreateForm({ onSuccess }: InlineCreateFormProps) {
const api = useAuthApi()
const [title, setTitle] = useState("")
const [isSaving, setIsSaving] = useState(false)
const handleSave = async () => {
const trimmed = title.trim()
if (!trimmed) {
toast.error("Reason title is required.")
return
}
setIsSaving(true)
try {
const response = (await api.reasons.create({ title: trimmed } as never)) as any
const created = response?.data ?? response
toast.success("Reason added.")
onSuccess(created?.id ? { value: String(created.id), label: created.title ?? trimmed } : undefined)
} catch {
toast.error("Failed to add reason.")
} finally {
setIsSaving(false)
}
}
return (
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="reason-title">Title</Label>
<Input
id="reason-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="e.g. Stock count correction"
autoFocus
/>
</div>
<div className="flex justify-end">
<Button type="button" onClick={handleSave} disabled={isSaving}>
<Plus className="size-4" />
{isSaving ? "Adding..." : "Add Reason"}
</Button>
</div>
</div>
)
}
// ── Component ──
export function InventoryAdjustmentForm({ resourceId, initialData, onSuccess }: InventoryAdjustmentFormProps) {
@@ -127,20 +205,27 @@ export function InventoryAdjustmentForm({ resourceId, initialData, onSuccess }:
<FieldGroup>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField
<RhfAutoGenerateField
name="reference_number"
label="Reference Number"
placeholder="ADJ-001"
placeholder="ADJ-0001"
table="inventory_adjustments"
autoFetch={!isEditing}
/>
<RhfTextField
name="date"
label="Date"
type="date"
/>
{/* TODO: replace with chart-of-accounts async select once the
module ships. Locked as integer + disabled for now. */}
<RhfTextField
name="chart_of_account"
label="Chart of Account"
placeholder="Account name"
type="number"
placeholder="Account number"
description="Pending chart-of-accounts module — disabled."
disabled
/>
<RhfAsyncSelectField
name="reason"
@@ -149,6 +234,8 @@ export function InventoryAdjustmentForm({ resourceId, initialData, onSuccess }:
queryKey={[REASON_ROUTES.INDEX]}
listFn={() => api.reasons.list()}
mapOption={mapLookupOption}
createLabel="Reason"
createForm={(props) => <ReasonInlineCreateForm {...props} />}
{...STORE_OBJECT}
/>
</div>
@@ -168,7 +255,7 @@ export function InventoryAdjustmentForm({ resourceId, initialData, onSuccess }:
type="button"
variant="outline"
size="sm"
onClick={() => append({ part: null, quantity: 1, rate: 0 })}
onClick={() => append({ part: null, quantity: 1, operation: "add", rate: 0 })}
>
<Plus className="size-4" />
Add Part
@@ -180,15 +267,25 @@ export function InventoryAdjustmentForm({ resourceId, initialData, onSuccess }:
)}
{fields.map((field, index) => (
<div key={field.id} className="grid grid-cols-[1fr_auto_auto_auto] items-end gap-2 rounded-lg border p-3">
<RhfAsyncSelectField
name={`parts.${index}.part`}
label="Part"
placeholder="Select part..."
queryKey={[PARTS_ROUTES.INDEX]}
listFn={() => api.parts.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
<div
key={field.id}
className="grid items-end gap-2 rounded-lg border p-3 grid-cols-[minmax(0,1fr)_9rem_6rem_6rem_auto]"
>
<div className="min-w-0">
<RhfAsyncSelectField
name={`parts.${index}.part`}
label="Part"
placeholder="Select part..."
queryKey={[PARTS_ROUTES.INDEX]}
listFn={() => api.parts.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
</div>
<RhfSelectField
name={`parts.${index}.operation`}
label="Operation"
options={OPERATION_OPTIONS}
/>
<RhfTextField
name={`parts.${index}.quantity`}
@@ -6,14 +6,21 @@ export const relationFieldSchema = z
const partLineSchema = z.object({
part: relationFieldSchema,
quantity: z.coerce.number().min(1, "Quantity must be at least 1"),
quantity: z.coerce.number().int().min(1, "Quantity must be at least 1"),
operation: z.enum(["add", "subtract"]).default("add"),
rate: z.coerce.number().min(0, "Rate must be 0 or more"),
})
export const inventoryAdjustmentFormSchema = z.object({
reference_number: z.string().min(1, "Reference number is required").max(255, "Reference number cannot exceed 255 characters"),
date: z.string().min(1, "Date is required"),
chart_of_account: z.string().optional(),
// TODO: pending chart-of-accounts module. Until then this is a free integer
// that the backend stores as-is; replace with an async select bound to the
// chart-of-accounts API once the module ships.
chart_of_account: z.preprocess(
(v) => (v === "" || v == null ? undefined : v),
z.coerce.number().int("Chart of account must be a whole number").optional(),
),
reason: relationFieldSchema,
notes: z.string().optional(),
parts: z.array(partLineSchema).min(1, "At least one part is required"),
@@ -15,7 +15,8 @@ import {
TableHeader,
TableRow,
} from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type InvoiceExpense = {
id: number
@@ -78,10 +79,10 @@ export function InvoiceExpensesSection({ expenses = [] }: InvoiceExpensesSection
{formatNumber(qty)}
</TableCell>
<TableCell className="text-right">
{formatCurrency(rate)}
{<Money value={rate} />}
</TableCell>
<TableCell className="text-right font-medium">
{formatCurrency(amount)}
{<Money value={amount} />}
</TableCell>
</TableRow>
)
@@ -91,7 +92,7 @@ export function InvoiceExpensesSection({ expenses = [] }: InvoiceExpensesSection
Subtotal
</TableCell>
<TableCell className="text-right">
{formatCurrency(subtotal)}
{<Money value={subtotal} />}
</TableCell>
</TableRow>
</TableBody>
@@ -22,8 +22,9 @@ import {
import { Badge } from "@/shared/components/ui/badge"
import { Separator } from "@/shared/components/ui/separator"
import { cn } from "@/shared/lib/utils"
import { formatDate, formatCurrency, formatEnum, formatNumber } from "@/shared/utils/formatters"
import { formatDate, formatEnum, formatNumber } from "@/shared/utils/formatters"
import { useInvoice } from "./invoice-context"
import { Money } from "@/shared/components/money"
function InfoItem({
icon: Icon,
@@ -140,9 +141,9 @@ export function InvoiceGeneralInfo() {
{/* Total Amount */}
<Card className="flex flex-col gap-1 p-4">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Total Amount</span>
<span className="mt-1 text-lg font-semibold">{formatCurrency(total)}</span>
<span className="mt-1 text-lg font-semibold">{<Money value={total} />}</span>
{paid > 0 && (
<span className="text-xs text-muted-foreground">{formatCurrency(paid)} received</span>
<span className="text-xs text-muted-foreground">{<Money value={paid} />} received</span>
)}
</Card>
@@ -158,7 +159,7 @@ export function InvoiceGeneralInfo() {
balanceDue > 0 && invoice.status !== "paid" && "text-primary",
balanceDue <= 0 && "text-green-600",
)}>
{formatCurrency(balanceDue)}
{<Money value={balanceDue} />}
</span>
{balanceDue <= 0 && (
<span className="text-xs font-medium text-green-600">Fully paid</span>
@@ -15,7 +15,8 @@ import {
TableHeader,
TableRow,
} from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type InvoicePart = {
id: number
@@ -78,10 +79,10 @@ export function InvoicePartsSection({ parts = [] }: InvoicePartsSectionProps) {
{formatNumber(qty)}
</TableCell>
<TableCell className="text-right">
{formatCurrency(rate)}
{<Money value={rate} />}
</TableCell>
<TableCell className="text-right font-medium">
{formatCurrency(amount)}
{<Money value={amount} />}
</TableCell>
</TableRow>
)
@@ -91,7 +92,7 @@ export function InvoicePartsSection({ parts = [] }: InvoicePartsSectionProps) {
Subtotal
</TableCell>
<TableCell className="text-right">
{formatCurrency(subtotal)}
{<Money value={subtotal} />}
</TableCell>
</TableRow>
</TableBody>
@@ -27,25 +27,37 @@ export default function InvoicePaymentsSection() {
<CardContent className='flex justify-between '>
<h2>Payments</h2>
<FormDialog title="Record Payment">
{(resourceId) => (
<PaymentReceivedForm
invoiceId={invoice?.id as string}
invoiceCustomer={
(invoice?.customer as any) ??
((invoice as any)?.customer_id
? {
id: (invoice as any).customer_id,
first_name: (invoice as any).customer_name,
}
: null)
}
invoiceAmount={invoice?.balance_due as any}
resourceId={resourceId}
onSuccess={()=>{router.refresh(); invalidateQuery()}}
/>
)}
{(resourceId) => {
const invoiceJobCard =
(invoice as any)?.jobCard ?? (invoice as any)?.job_card ?? null
const invoiceJobCardId =
invoiceJobCard?.id ?? (invoice as any)?.job_card_id ?? null
const invoiceJobCardTitle =
invoiceJobCard?.title ?? (invoice as any)?.job_card_name ?? null
return (
<PaymentReceivedForm
invoiceId={invoice?.id as string}
invoiceCustomer={
(invoice?.customer as any) ??
((invoice as any)?.customer_id
? {
id: (invoice as any).customer_id,
first_name: (invoice as any).customer_name,
}
: null)
}
invoiceAmount={invoice?.balance_due as any}
defaultJobCard={
invoiceJobCardId != null
? { id: Number(invoiceJobCardId), title: invoiceJobCardTitle }
: null
}
lockJobCard={false}
resourceId={resourceId}
onSuccess={() => { router.refresh(); invalidateQuery() }}
/>
)
}}
</FormDialog>
</CardContent>
@@ -15,7 +15,8 @@ import {
TableHeader,
TableRow,
} from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type InvoiceService = {
id: number
@@ -78,10 +79,10 @@ export function InvoiceServicesSection({ services = [] }: InvoiceServicesSection
{formatNumber(qty)}
</TableCell>
<TableCell className="text-right">
{formatCurrency(rate)}
{<Money value={rate} />}
</TableCell>
<TableCell className="text-right font-medium">
{formatCurrency(amount)}
{<Money value={amount} />}
</TableCell>
</TableRow>
)
@@ -91,7 +92,7 @@ export function InvoiceServicesSection({ services = [] }: InvoiceServicesSection
Subtotal
</TableCell>
<TableCell className="text-right">
{formatCurrency(subtotal)}
{<Money value={subtotal} />}
</TableCell>
</TableRow>
</TableBody>
@@ -1,9 +1,10 @@
"use client"
import { Card, CardContent } from "@/shared/components/ui/card"
import { Separator } from "@/shared/components/ui/separator"
import { formatCurrency, formatEnum } from "@/shared/utils/formatters"
import { formatEnum } from "@/shared/utils/formatters"
import { cn } from "@/shared/lib/utils"
import { useInvoice } from "./invoice-context"
import { Money } from "@/shared/components/money"
export function InvoiceTotalsSummary() {
const invoice = useInvoice()
@@ -41,19 +42,19 @@ export function InvoiceTotalsSummary() {
{parts.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Parts ({parts.length})</span>
<span>{formatCurrency(lineTotal(parts))}</span>
<span>{<Money value={lineTotal(parts)} />}</span>
</div>
)}
{services.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Services ({services.length})</span>
<span>{formatCurrency(lineTotal(services))}</span>
<span>{<Money value={lineTotal(services)} />}</span>
</div>
)}
{expenses.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Expenses ({expenses.length})</span>
<span>{formatCurrency(lineTotal(expenses))}</span>
<span>{<Money value={lineTotal(expenses)} />}</span>
</div>
)}
<Separator />
@@ -62,7 +63,7 @@ export function InvoiceTotalsSummary() {
<div className="flex justify-between text-sm font-medium">
<span>Subtotal</span>
<span>{formatCurrency(subTotal)}</span>
<span>{<Money value={subTotal} />}</span>
</div>
{discount && discount !== "no" && (
@@ -76,13 +77,13 @@ export function InvoiceTotalsSummary() {
<div className="flex justify-between text-base font-semibold">
<span>Total</span>
<span>{formatCurrency(displayTotal)}</span>
<span>{<Money value={displayTotal} />}</span>
</div>
{paid > 0 && (
<div className="flex justify-between text-sm text-muted-foreground">
<span>Amount Received</span>
<span>– {formatCurrency(paid)}</span>
<span>– {<Money value={paid} />}</span>
</div>
)}
@@ -93,7 +94,7 @@ export function InvoiceTotalsSummary() {
balanceDue > 0 ? "bg-primary/10 text-primary" : "bg-green-500/10 text-green-600",
)}>
<span>Balance Due</span>
<span>{formatCurrency(balanceDue)}</span>
<span>{<Money value={balanceDue} />}</span>
</div>
</div>
</CardContent>
@@ -37,6 +37,14 @@ export default function JobCardDropdown({ id }: { id: string }) {
router.push(`/sales/job-cards/${id}/appointments?create=1`)
}
const existingInvoice = (jobCard as any)?.invoices?.[0] as { id: number | string; invoice_number?: string | null } | undefined
const handleOpenExistingInvoice = () => {
if (existingInvoice?.id != null) {
router.push(`/sales/invoice/${existingInvoice.id}`)
}
}
const handleConvertToInvoice = async () => {
const confirmed = await confirm({
title: "Convert to Invoice",
@@ -95,10 +103,17 @@ export default function JobCardDropdown({ id }: { id: string }) {
return (
<div className="flex items-center gap-2">
{jobCard?.status !== "draft" && (
<Button variant="outline" onClick={handleConvertToInvoice} disabled={isConverting}>
{isConverting ? <Loader2 className="size-4 animate-spin" /> : <FileText className="size-4" />}
{isConverting ? "Converting..." : "Convert to Invoice"}
</Button>
existingInvoice ? (
<Button variant="outline" onClick={handleOpenExistingInvoice}>
<FileText className="size-4" />
{existingInvoice.invoice_number ? `Invoice #${existingInvoice.invoice_number}` : "View Invoice"}
</Button>
) : (
<Button variant="outline" onClick={handleConvertToInvoice} disabled={isConverting}>
{isConverting ? <Loader2 className="size-4 animate-spin" /> : <FileText className="size-4" />}
{isConverting ? "Converting..." : "Convert to Invoice"}
</Button>
)
)}
<Button variant="outline" onClick={handleCreateAppointment}>
@@ -133,10 +148,17 @@ export default function JobCardDropdown({ id }: { id: string }) {
Create Appointment
</DropdownMenuItem>
{jobCard?.status !== "draft" && (
<DropdownMenuItem onClick={handleConvertToInvoice} disabled={isConverting}>
<FileText className="size-4" />
{isConverting ? "Converting..." : "Convert to Invoice"}
</DropdownMenuItem>
existingInvoice ? (
<DropdownMenuItem onClick={handleOpenExistingInvoice}>
<FileText className="size-4" />
{existingInvoice.invoice_number ? `Invoice #${existingInvoice.invoice_number}` : "View Invoice"}
</DropdownMenuItem>
) : (
<DropdownMenuItem onClick={handleConvertToInvoice} disabled={isConverting}>
<FileText className="size-4" />
{isConverting ? "Converting..." : "Convert to Invoice"}
</DropdownMenuItem>
)
)}
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
@@ -16,8 +16,9 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/shared/components/ui/collapsible"
import { Button } from "@/shared/components/ui/button"
import { useJobCard } from "./job-card-context"
import { formatDate, formatCurrency } from "@/shared/utils/formatters"
import { formatDate } from "@/shared/utils/formatters"
import { useState } from "react"
import { Money } from "@/shared/components/money"
export default function JobCardPaymentsReceived() {
const jobCard = useJobCard()
@@ -88,7 +89,7 @@ export default function JobCardPaymentsReceived() {
<div className="flex items-center gap-2">
<BadgeDollarSignIcon className="h-4 w-4 text-emerald-600" />
<span className="font-semibold text-emerald-700 dark:text-emerald-400">
{formatCurrency(item.amount_received)}
{<Money value={item.amount_received} />}
</span>
</div>
)
@@ -55,6 +55,7 @@ export function PartsSelectorField<
itemKey="part_id"
dialogProps={{
title: "Select Parts",
searchPlaceholder: "Search parts by title, SKU, or part number...",
crudProps: {
routeKey: PARTS_ROUTES.INDEX,
getClient: (api) => api.parts,
@@ -73,23 +73,30 @@ const DEFAULT_VALUES: PaymentMadeFormValues & { details: Array<{ bill_id?: strin
function mapToFormValues(data: unknown): typeof DEFAULT_VALUES {
const d = (data as any)?.data ?? data ?? {}
// PaymentMade lists carry the linked bill/expense inside details[]; top-level
// bill_id/expense_id only exist on inputs sent from a bill/expense subpage.
const firstDetail = Array.isArray(d.details) ? d.details[0] ?? {} : {}
const billId = d.bill_id ?? firstDetail.bill_id ?? firstDetail.bill?.id
const billNumber = d.bill?.bill_number ?? d.bill_number ?? firstDetail.bill?.bill_number
const expenseId = d.expense_id ?? firstDetail.expense_id ?? firstDetail.expense?.id
// Resolve payment_mode label from nested object (title) or fallback to id
const paymentModeId = d.payment_mode_id ?? d.payment_mode?.id
const paymentModeLabel = d.payment_mode?.title ?? d.payment_mode?.name ?? d.payment_mode_name
return {
bill: toRelation(d.bill_id, d.bill?.bill_number ?? d.bill_number),
vendor: toRelation(d.vendor_id, d.vendor?.company_name ?? d.vendor?.name ?? d.vendor_name),
employee: toRelation(d.employee_id, d.employee?.first_name ? `${d.employee.first_name} ${d.employee.last_name ?? ""}`.trim() : d.employee_name),
bill: toRelation(billId, billNumber),
vendor: toRelation(d.vendor_id ?? d.vendor?.id, d.vendor?.company_name ?? d.vendor?.name ?? d.vendor_name),
employee: toRelation(d.employee_id ?? d.employee?.id, d.employee?.first_name ? `${d.employee.first_name} ${d.employee.last_name ?? ""}`.trim() : d.employee_name),
payment_mode: toRelation(paymentModeId, paymentModeLabel),
payment_for: d.payment_for || "bill",
amount: d.payment_made != null ? Number(d.payment_made) : 0,
payment_for: d.payment_for || (expenseId ? "expense" : "bill"),
amount: d.payment_made != null ? Number(d.payment_made) : firstDetail.amount_paid != null ? Number(firstDetail.amount_paid) : 0,
payment_number: d.payment_number || "",
payment_reference: d.payment_reference || "",
payment_date: d.payment_date || "",
paid_through: d.paid_through || "-",
notes: d.notes || "-",
details: [{ bill_id: d.bill_id, expense_id: d.expense_id, amount_paid: d.amount_paid ?? 0 }],
paid_through: d.paid_through || "",
notes: d.notes || "",
details: [{ bill_id: billId, expense_id: expenseId, amount_paid: firstDetail.amount_paid ?? 0 }],
}
}
@@ -64,7 +64,7 @@ function mapToFormValues(data: unknown): PaymentReceivedFormValues {
customer: toRelation(d.customer_id, d.customer_name),
amount_received: d.amount_received != null ? Number(d.amount_received) : 0,
payment_number: d.payment_number || "",
payment_date: d.payment_date || "",
payment_date: d.payment_date || new Date().toISOString().split("T")[0],
note: d.note || "",
}
}
@@ -2,6 +2,7 @@
import { useState } from "react"
import { FileText } from "lucide-react"
import { useQueryClient } from "@tanstack/react-query"
import { Button } from "@/shared/components/ui/button"
import {
Dialog,
@@ -11,50 +12,53 @@ import {
} from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { BillForm } from "@/modules/bills/bill-form"
import { toRelation } from "@/shared/lib/utils"
import { usePurchaseOrder } from "./purchase-order-context"
import { getFullName } from "@/shared/utils/getFullName"
import { getTodayDate } from "@/shared/lib/utils"
import { BILL_ROUTES } from "@garage/api"
/**
* Maps a Purchase Order data object to a complete BillFormValues shape so that
* useResourceForm's shallow spread (`{ ...defaultValues, ...initialData }`) correctly
* pre-fills all relational and line-item fields.
*/
function mapPOToBillInitialData(po: Record<string, any>) {
// Build an API-shaped seed that BillForm's `mapToFormValues` will consume,
// so the dialog opens with PO fields, vendor/department/job_card relations,
// and line items pre-filled.
function mapPOToBillSeed(po: Record<string, any>) {
return {
// Text fields
title: po.title ?? "",
notes: po.notes ?? "",
bill_date: getTodayDate(),
vendor_id: po.vendor_id,
vendor: po.vendor ? { name: getFullName(po.vendor) } : undefined,
department_id: po.department_id,
department: po.department,
job_card_id: po.job_card_id,
job_card: po.job_card
? { order_number: po.job_card.order_number ?? po.job_card.title }
: undefined,
// Relation fields — must be { value, label } objects for RhfAsyncSelectField
vendor: toRelation(po.vendor_id, getFullName(po.vendor)),
department: toRelation(po.department_id, po.department.name),
job_card: toRelation(po.job_card_id, po.job_card.title ),
// Link bill back to the source PO
purchase_order: toRelation(po.id, po.order_number ?? po.title),
purchase_order_id: po.id,
purchase_order: { order_number: po.order_number ?? po.title },
// Parts pre-filled from PO items
part_items: (po.parts ?? []).map((p: any) => ({
parts: (po.parts ?? []).map((p: any) => ({
part_id: p.part_id ?? p.id,
title: p.part?.title ?? p.title ?? "",
part: { name: p.part?.title ?? p.part?.name ?? p.title ?? "" },
quantity: Number(p.quantity) || 1,
rate: Number(p.rate) || 0,
description: p.description ?? "",
})),
// Services and expenses start empty (PO doesn't have them)
service_items: [],
expense_items: [],
}
}
export function CreateBillFromPOButton() {
const [open, setOpen] = useState(false)
const poContext = usePurchaseOrder()
const queryClient = useQueryClient()
if (!poContext) return null
const initialData = poContext.data ? mapPOToBillInitialData(poContext.data) : undefined
const initialData = poContext.data ? mapPOToBillSeed(poContext.data) : undefined
return (
<>
@@ -71,7 +75,12 @@ export function CreateBillFromPOButton() {
<ScrollArea className="max-h-[75vh] px-1">
<BillForm
initialData={initialData}
onSuccess={() => setOpen(false)}
onSuccess={() => {
// Invalidate bills list so when user lands on the bills
// page the new bill is present without a manual refresh.
queryClient.invalidateQueries({ queryKey: [BILL_ROUTES.INDEX] })
setOpen(false)
}}
/>
</ScrollArea>
</DialogContent>
@@ -6,7 +6,6 @@ import {
Truck,
FileText,
Package,
DollarSign,
} from "lucide-react"
import {
Card,
@@ -24,6 +23,7 @@ import {
TableRow,
TableCell,
} from "@/shared/components/ui/table"
import { Money } from "@/shared/components/money"
type PurchaseOrderPart = {
id?: number
@@ -92,11 +92,6 @@ function formatDate(dateStr?: string | null) {
return new Date(dateStr).toLocaleDateString()
}
function formatCurrency(value?: string | number | null) {
if (value == null) return "—"
return `$${Number(value).toFixed(2)}`
}
export function PurchaseOrderGeneralInfo({ purchaseOrder }: PurchaseOrderGeneralInfoProps) {
const parts = purchaseOrder.parts ?? []
const totalAmount = parts.reduce(
@@ -219,9 +214,8 @@ export function PurchaseOrderGeneralInfo({ purchaseOrder }: PurchaseOrderGeneral
<Package className="size-4" />
Parts ({parts.length})
</span>
<span className="flex items-center gap-2 text-base">
<DollarSign className="size-4" />
Total: {formatCurrency(totalAmount)}
<span className="text-base whitespace-nowrap">
Total: <Money value={totalAmount} />
</span>
</CardTitle>
</CardHeader>
@@ -257,10 +251,10 @@ export function PurchaseOrderGeneralInfo({ purchaseOrder }: PurchaseOrderGeneral
{item.quantity ?? 0}
</TableCell>
<TableCell className="text-right">
{formatCurrency(item.rate)}
{<Money value={item.rate} />}
</TableCell>
<TableCell className="text-right font-medium">
{formatCurrency(amount)}
{<Money value={amount} />}
</TableCell>
</TableRow>
)
@@ -270,7 +264,7 @@ export function PurchaseOrderGeneralInfo({ purchaseOrder }: PurchaseOrderGeneral
Total
</TableCell>
<TableCell className="text-right">
{formatCurrency(totalAmount)}
{<Money value={totalAmount} />}
</TableCell>
</TableRow>
</TableBody>
@@ -55,6 +55,7 @@ export function ServicesSelectorField<
itemKey="service_id"
dialogProps={{
title: "Select Services",
searchPlaceholder: "Search services...",
crudProps: {
routeKey: SERVICE_ROUTES.INDEX,
getClient: (api) => api.services,
+100
View File
@@ -0,0 +1,100 @@
"use client"
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Power, Trash2 } from "lucide-react"
import { confirm } from "@/shared/components/confirm-dialog"
import { toast } from "sonner"
import { useFormDialog } from "@/shared/components/form-dialog"
import { VendorForm } from "./vendor-form"
type VendorActionsProps = {
vendorId: string
isActive?: boolean
}
export function VendorActions({ vendorId, isActive }: VendorActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("vendor-details-edit")
const handleDelete = async () => {
const confirmed = await confirm({
title: "Delete Vendor",
description: "Are you sure you want to delete this vendor? This action cannot be undone.",
confirmLabel: "Delete",
variant: "destructive",
})
if (!confirmed) return
try {
await api.vendors.destroy(vendorId)
toast.success("Vendor deleted successfully.")
router.push("/purchase/vendor")
} catch {
toast.error("Failed to delete vendor.")
}
}
const handleToggleStatus = async () => {
try {
await api.vendors.toggleStatus({ id: Number(vendorId) } as any)
toast.success(isActive ? "Vendor deactivated." : "Vendor activated.")
router.refresh()
} catch {
toast.error("Failed to update vendor status.")
}
}
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Ellipsis className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => editDialog.open(vendorId)}>
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={handleToggleStatus}>
<Power className="size-4" />
{isActive ? "Deactivate" : "Activate"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
<DialogContent className="min-w-xl lg:min-w-2xl">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">Edit Vendor</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<VendorForm
resourceId={editDialog.resourceId}
onSuccess={() => {
editDialog.close()
router.refresh()
}}
/>
</ScrollArea>
</DialogContent>
</Dialog>
</>
)
}
+28
View File
@@ -0,0 +1,28 @@
"use client"
import { createContext, useContext } from "react"
type VendorContextValue = {
id: string
label: string
}
const VendorContext = createContext<VendorContextValue | null>(null)
export function VendorProvider({
vendor,
children,
}: {
vendor: VendorContextValue
children: React.ReactNode
}) {
return (
<VendorContext.Provider value={vendor}>
{children}
</VendorContext.Provider>
)
}
export function useVendor() {
return useContext(VendorContext)
}
+135
View File
@@ -0,0 +1,135 @@
import {
Building2,
CreditCard,
DollarSign,
Globe,
Mail,
Phone,
User,
} 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"
import { Money } from "@/shared/components/money"
type VendorData = {
id?: number
salutation?: string | null
first_name?: string | null
last_name?: string | null
company_name?: string | null
email?: string | null
phone?: string | null
alternate_phone?: string | null
website?: string | null
opening_balance?: number | string | null
credit_limit?: number | string | null
status?: string | null
created_at?: string
updated_at?: string
}
type VendorGeneralInfoProps = {
vendor: VendorData
}
function InfoItem({
icon: Icon,
label,
value,
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value?: React.ReactNode
}) {
const isEmpty = value == null || value === ""
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">
{isEmpty ? <span className="text-muted-foreground">—</span> : value}
</span>
</div>
</div>
)
}
export function VendorGeneralInfo({ vendor }: VendorGeneralInfoProps) {
const fullName = [vendor.salutation, vendor.first_name, vendor.last_name]
.filter(Boolean)
.join(" ")
.trim()
return (
<div className="grid gap-6 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Building2 className="size-4" />
Vendor Information
</CardTitle>
</CardHeader>
<CardContent className="grid gap-4">
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary">{vendor.company_name || fullName || "Unknown vendor"}</Badge>
{vendor.status && (
<Badge variant={vendor.status === "active" ? "default" : "outline"} className="capitalize">
{vendor.status}
</Badge>
)}
</div>
<Separator />
<div className="grid gap-4 sm:grid-cols-2">
<InfoItem icon={Building2} label="Company" value={vendor.company_name} />
<InfoItem icon={User} label="Contact Name" value={fullName} />
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Phone className="size-4" />
Contact Details
</CardTitle>
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<InfoItem icon={Mail} label="Email" value={vendor.email} />
<InfoItem icon={Phone} label="Phone" value={vendor.phone} />
<InfoItem icon={Phone} label="Alternate Phone" value={vendor.alternate_phone} />
<InfoItem icon={Globe} label="Website" value={vendor.website} />
</CardContent>
</Card>
<Card className="md:col-span-2">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<DollarSign className="size-4" />
Financial Details
</CardTitle>
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<InfoItem
icon={DollarSign}
label="Opening Balance"
value={vendor.opening_balance != null ? <Money value={vendor.opening_balance} /> : null}
/>
<InfoItem
icon={CreditCard}
label="Credit Limit"
value={vendor.credit_limit != null ? <Money value={vendor.credit_limit} /> : null}
/>
</CardContent>
</Card>
</div>
)
}