Merge branch 'fix/back-front-validation-alignment' into dev

This commit is contained in:
humam kerdiah 2026-05-18 13:31:05 +04:00
commit 5570527e69
151 changed files with 6116 additions and 1258 deletions

View File

@ -0,0 +1,13 @@
{
"permissions": {
"allow": [
"Bash(pnpm --version)",
"Bash(grep -E \"\\\\.\\(tsx?|jsx?\\)$\")",
"Bash(grep -E \"\\\\.\\(tsx?\\)$\")"
]
},
"enabledMcpjsonServers": [
"code-review-graph"
],
"enableAllProjectMcpServers": true
}

2
.env.prod Normal file
View File

@ -0,0 +1,2 @@
NIXPACKS_NODE_VERSION=22
NEXT_PUBLIC_API_URL=http://reparee.test

View File

@ -5,11 +5,11 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { AppointmentForm } from "@/modules/appointments/appointment-form"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon, ExternalLinkIcon } from "lucide-react"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { RelationLink } from "@/shared/components/relation-link"
const STATUS_COLORS: Record<string, string> = {
requested: "bg-yellow-100 text-yellow-800",
@ -26,6 +26,9 @@ export default function AppointmentsPage() {
<ResourcePage<AppointmentsClient>
pageTitle="Appointments"
routeKey={APPOINTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search appointments..."
statusFilter={{ statuses: AppointmentStatus }}
getClient={(api) => api.appointments}
onRowClick={(row) => router.push(`/calendar/appointment/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@ -86,22 +89,14 @@ export default function AppointmentsPage() {
id: "job_card",
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
cell: ({ row }) => {
const jobCardId = (row.original as any).job_card_id
if (!jobCardId) return <span className="text-muted-foreground"></span>
const item = row.original as any
const jobCardId = item.job_card_id ?? item.job_card?.id
return (
<Button
variant="outline"
size="sm"
className="h-7 gap-1.5"
onClick={(e) => {
e.stopPropagation()
router.push(`/sales/job-cards/${jobCardId}`)
}}
>
<ClipboardListIcon className="size-3" />
#{jobCardId}
<ExternalLinkIcon className="size-3" />
</Button>
<RelationLink
href={jobCardId ? `/sales/job-cards/${jobCardId}` : null}
icon={ClipboardListIcon}
label={item.job_card?.title || (jobCardId ? `#${jobCardId}` : null)}
/>
)
},
},

View File

@ -201,15 +201,20 @@ export default function InventoryAdjustmentsPage() {
<ResourcePage<InventoryAdjustmentsClient>
pageTitle="Inventory Adjustments"
routeKey={INVENTORY_ADJUSTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search adjustments..."
getClient={(api) => api.inventoryAdjustments}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Inventory Adjustment">
{(resourceId) => (
<FormDialog
title="Inventory Adjustment"
classNames={{ dialogContent: "lg:min-w-4xl" }}
>
{(resourceId, { close }) => (
<InventoryAdjustmentForm
resourceId={resourceId}
initialData={selectedItem}
onSuccess={invalidateQuery}
onSuccess={() => { invalidateQuery(); close() }}
/>
)}
</FormDialog>

View File

@ -12,15 +12,20 @@ export default function ExpenseItemPage() {
<ResourcePage<ExpenseItemsClient>
pageTitle="Expense Items"
routeKey={EXPENSE_ITEM_ROUTES.INDEX}
searchable
searchPlaceholder="Search expense items..."
getClient={(api) => api.expenseItems}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Expense Item">
{(resourceId) => (
{(resourceId, { close }) => (
<ExpenseItemForm
resourceId={resourceId}
initialData={selectedItem}
onSuccess={invalidateQuery}
onSuccess={() => {
invalidateQuery()
close()
}}
/>
)}
</FormDialog>

View File

@ -17,6 +17,8 @@ export default function PartsPage() {
<ResourcePage<PartsClient>
pageTitle="Parts"
routeKey={PARTS_ROUTES.INDEX}
searchable
searchPlaceholder="Search parts..."
getClient={(api) => api.parts}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@ -24,6 +26,7 @@ export default function PartsPage() {
<ImportDataButton
onImport={(file) => api.parts.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Parts"
/>
<ExportDataButton
onExport={(filters) => api.parts.exportData(filters)}

View File

@ -13,6 +13,8 @@ export default function ServiceGroupPage() {
<ResourcePage<ServiceGroupsClient>
pageTitle="Service Groups"
routeKey={SERVICE_GROUP_ROUTES.INDEX}
searchable
searchPlaceholder="Search service groups..."
getClient={(api) => api.serviceGroups}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -17,6 +17,8 @@ export default function ServicesPage() {
<ResourcePage<ServicesClient>
pageTitle="Services"
routeKey={SERVICE_ROUTES.INDEX}
searchable
searchPlaceholder="Search services..."
getClient={(api) => api.services}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@ -24,6 +26,7 @@ export default function ServicesPage() {
<ImportDataButton
onImport={(file) => api.services.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Services"
/>
<ExportDataButton
onExport={(filters) => api.services.exportData(filters)}

View File

@ -14,6 +14,9 @@ export default function EmployeesPage() {
<ResourcePage<EmployeesClient>
pageTitle="Employees"
routeKey={EMPLOYEE_ROUTES.INDEX}
searchable
searchPlaceholder="Search employees..."
statusFilter={{ statuses: ["active", "inactive"] }}
getClient={(api) => api.employees}
onRowClick={(row) => router.push(`/productivity/employees/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({

View File

@ -12,6 +12,8 @@ export default function HolidayYearsPage() {
<ResourcePage<HolidayYearsClient>
pageTitle="Holiday Years"
routeKey={HOLIDAY_YEAR_ROUTES.INDEX}
searchable
searchPlaceholder="Search holidays..."
getClient={(api) => api.holidayYears}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -13,6 +13,8 @@ export default function ShopCalendarsPage() {
<ResourcePage<ShopCalendarsClient>
pageTitle="Shop Calendars"
routeKey={SHOP_CALENDAR_ROUTES.INDEX}
searchable
searchPlaceholder="Search shop calendars..."
getClient={(api) => api.shopCalendars}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -13,6 +13,8 @@ export default function ShopTimingsPage() {
<ResourcePage<ShopTimingsClient>
pageTitle="Shop Timings"
routeKey={SHOP_TIMING_ROUTES.INDEX}
searchable
searchPlaceholder="Search shop timings..."
getClient={(api) => api.shopTimings}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -4,13 +4,16 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { TaskForm } from "@/modules/tasks/task-form"
import { TASK_ROUTES } from "@garage/api"
import { TASK_ROUTES, TaskStatus } from "@garage/api"
import type { TasksClient } from "@garage/api"
export default function TasksPage() {
return (
<ResourcePage<TasksClient>
routeKey={TASK_ROUTES.INDEX}
searchable
searchPlaceholder="Search tasks..."
statusFilter={{ statuses: TaskStatus }}
getClient={(api) => api.tasks}
headerProps={({ selectedItem, invalidateQuery }) => ({
title: "Tasks",

View File

@ -3,6 +3,7 @@ import { getServerApi } from '@garage/api/server'
import { BillActions } from '@/modules/bills/bill-actions'
import { BillProvider, type BillResponse } from '@/modules/bills/bill-context'
import BillStatusBadge from '@/modules/bills/bill-status-badge'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import { ReceiptIcon } from 'lucide-react'
import React from 'react'
@ -26,6 +27,7 @@ export default async function BillDetailLayout(props: {
actions={
<div className="flex space-x-2 items-center">
<BillStatusBadge bill={{id, status:data?.status}} />
<ShareDocumentButton type="bill" id={id} />
<BillActions billId={id} />
</div>
}

View File

@ -6,9 +6,13 @@ import { Badge } from "@/shared/components/ui/badge"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { BillForm } from "@/modules/bills/bill-form"
import { BILL_ROUTES } from "@garage/api"
import { BILL_ROUTES, BillStatus } from "@garage/api"
import type { BillsClient } from "@garage/api"
import { formatDate } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2 } from "lucide-react"
export default function BillsPage() {
const router = useRouter()
@ -17,6 +21,9 @@ export default function BillsPage() {
<ResourcePage<BillsClient>
pageTitle="Bills"
routeKey={BILL_ROUTES.INDEX}
searchable
searchPlaceholder="Search bills..."
statusFilter={{ statuses: BillStatus }}
getClient={(api) => api.bills}
onRowClick={(row) => router.push(`/purchase/bill/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@ -41,12 +48,18 @@ export default function BillsPage() {
{
accessorKey: "total",
header: ({ column }) => <ColumnHeader column={column} title="Total" />,
cell: ({ row }) => (row.original as any).total || "—",
cell: ({ row }) => {
const v = (row.original as any).total
return v != null && v !== "" ? <Money value={v} /> : "—"
},
},
{
accessorKey: "balance_due",
header: ({ column }) => <ColumnHeader column={column} title="Balance Due" />,
cell: ({ row }) => (row.original as any).balance_due || "—",
cell: ({ row }) => {
const v = (row.original as any).balance_due
return v != null && v !== "" ? <Money value={v} /> : "—"
},
},
{
accessorKey: "title",
@ -55,7 +68,16 @@ export default function BillsPage() {
{
accessorKey: "vendor",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor?.name || "—",
cell: ({ row }) => {
const vendor = (row.original as any).vendor
return (
<RelationLink
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
icon={Building2}
label={vendor?.company_name || getFullName(vendor)}
/>
)
},
},
{
accessorKey: "bill_date",

View File

@ -5,10 +5,14 @@ import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { ExpenseForm } from "@/modules/expenses/expense-form"
import { Badge } from "@/shared/components/ui/badge"
import { EXPENSE_ROUTES } from "@garage/api"
import { EXPENSE_ROUTES, ExpenseStatus } from "@garage/api"
import type { ExpensesClient } from "@garage/api"
import { useRouter } from "next/navigation"
import { formatCurrency, formatDate, formatEnum } from "@/shared/utils/formatters"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2 } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
export default function ExpensesPage() {
const router = useRouter()
@ -16,6 +20,9 @@ export default function ExpensesPage() {
<ResourcePage<ExpensesClient>
pageTitle="Expenses"
routeKey={EXPENSE_ROUTES.INDEX}
searchable
searchPlaceholder="Search expenses..."
statusFilter={{ statuses: ExpenseStatus }}
getClient={(api) => api.expenses}
onRowClick={(row)=>router.push(`/purchase/expense/${row.id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@ -49,7 +56,13 @@ export default function ExpensesPage() {
header: () => "Vendor",
cell: ({ row }) => {
const vendor = (row.original as any).vendor
return vendor?.company_name || vendor?.name || "—"
return (
<RelationLink
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
icon={Building2}
label={vendor?.company_name || getFullName(vendor) || vendor?.name}
/>
)
},
},
{
@ -60,12 +73,12 @@ export default function ExpensesPage() {
{
accessorKey: "total",
header: () => "Total",
cell: ({ row }) => formatCurrency((row.original as any).total ?? 0),
cell: ({ row }) => <Money value={(row.original as any).total ?? 0} />,
},
{
accessorKey: "balance_due",
header: () => "Balance Due",
cell: ({ row }) => formatCurrency((row.original as any).balance_due ?? 0),
cell: ({ row }) => <Money value={(row.original as any).balance_due ?? 0} />,
},
{
accessorKey: "status",

View File

@ -32,8 +32,11 @@ import {
} from "@/shared/components/ui/dialog"
import { confirm } from "@/shared/components/confirm-dialog"
import { useAuthApi } from "@/shared/useApi"
import { getFullName } from "@/shared/utils/getFullName"
import { PAYMENT_MADE_ROUTES } from "@garage/api"
import type { PaymentMadesClient } from "@garage/api"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2 } from "lucide-react"
// ── Attachment helpers ──
@ -208,10 +211,13 @@ function AttachmentsDialog({
type PaymentMadeItem = {
id: number
payment_number?: string
vendor?: { id?: number | string; company_name?: string | null; first_name?: string | null; last_name?: string | null; name?: string | null } | null
vendor_name?: string
employee?: { id?: number | string; first_name?: string | null; last_name?: string | null; name?: string | null } | null
employee_name?: string
payment_for?: string
payment_made?: string | number
payment_mode?: { name?: string | null; title?: string | null } | null
payment_mode_name?: string
payment_date?: string
paid_through?: string
@ -230,14 +236,20 @@ export default function PaymentsMadePage() {
<ResourcePage<PaymentMadesClient>
pageTitle="Payments Made"
routeKey={PAYMENT_MADE_ROUTES.INDEX}
searchable
searchPlaceholder="Search payments..."
getClient={(api) => api.paymentMades}
headerProps={({ invalidateQuery }) => ({
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Record Payment">
{(resourceId) => (
{(resourceId, { close }) => (
<PaymentMadeForm
resourceId={resourceId}
onSuccess={invalidateQuery}
initialData={selectedItem}
onSuccess={() => {
invalidateQuery()
close()
}}
/>
)}
</FormDialog>
@ -262,11 +274,27 @@ export default function PaymentsMadePage() {
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => {
const item = row.original as unknown as PaymentMadeItem
const isVendor =
item.vendor?.company_name ||
getFullName(item.vendor) ||
item.vendor?.name ||
item.vendor_name
const label =
isVendor ||
getFullName(item.employee) ||
item.employee?.name ||
item.employee_name
const href = isVendor && item.vendor?.id
? `/purchase/vendor/${item.vendor.id}`
: item.employee?.id
? `/productivity/employees/${item.employee.id}`
: null
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{item.vendor_name || "—"}</span>
</div>
<RelationLink
href={href}
icon={isVendor ? Building2 : UserIcon}
label={label}
/>
)
},
},
@ -309,10 +337,15 @@ export default function PaymentsMadePage() {
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
cell: ({ row }) => {
const item = row.original as unknown as PaymentMadeItem
const label =
item.payment_mode?.name ||
item.payment_mode?.title ||
item.payment_mode_name ||
"—"
return (
<div className="flex items-center gap-2">
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
<span className="capitalize">{item.payment_mode_name || "—"}</span>
<span className="capitalize">{label}</span>
</div>
)
},

View File

@ -3,6 +3,7 @@ import { getServerApi } from '@garage/api/server'
import { PurchaseOrderActions } from '@/modules/purchase-orders/purchase-order-actions'
import { PurchaseOrderProvider } from '@/modules/purchase-orders/purchase-order-context'
import { CreateBillFromPOButton } from '@/modules/purchase-orders/create-bill-from-po-button'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import { ClipboardList } from 'lucide-react'
import React from 'react'
@ -30,6 +31,7 @@ export default async function layout(props: {
actions={
<div className="flex items-center gap-2">
<CreateBillFromPOButton />
<ShareDocumentButton type="purchase_order" id={id} />
<PurchaseOrderActions purchaseOrderId={id} />
</div>
}

View File

@ -7,6 +7,9 @@ import FormDialog from "@/shared/components/form-dialog"
import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form"
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
import type { PurchaseOrdersClient } from "@garage/api"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2 } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
export default function PurchaseOrdersPage() {
const router = useRouter()
@ -15,6 +18,8 @@ export default function PurchaseOrdersPage() {
<ResourcePage<PurchaseOrdersClient>
pageTitle="Purchase Orders"
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
searchable
searchPlaceholder="Search purchase orders..."
getClient={(api) => api.purchaseOrders}
onRowClick={(row) => router.push(`/purchase/purchase-order/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@ -43,7 +48,16 @@ export default function PurchaseOrdersPage() {
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "order_date",

View File

@ -5,14 +5,20 @@ import { Badge } from "@/shared/components/ui/badge"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { VendorCreditForm } from "@/modules/vendor-credits/vendor-credit-form"
import { VENDOR_CREDIT_ROUTES } from "@garage/api"
import { VENDOR_CREDIT_ROUTES, VendorCreditStatus } from "@garage/api"
import type { VendorCreditsClient } from "@garage/api"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, FileTextIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
export default function VendorCreditsPage() {
return (
<ResourcePage<VendorCreditsClient>
pageTitle="Vendor Credits"
routeKey={VENDOR_CREDIT_ROUTES.INDEX}
searchable
searchPlaceholder="Search vendor credits..."
statusFilter={{ statuses: VendorCreditStatus }}
getClient={(api) => api.vendorCredits}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@ -35,12 +41,30 @@ export default function VendorCreditsPage() {
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "bill_number",
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
cell: ({ row }) => (row.original as any).bill_number || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.bill?.id ? `/purchase/bill/${item.bill.id}` : null}
icon={FileTextIcon}
label={item.bill?.bill_number || item.bill_number}
/>
)
},
},
{
accessorKey: "vendor_credit_date",

View File

@ -0,0 +1,37 @@
import { DashboardDetailsPage } from "@/base/components/layout/dashboard"
import { getServerApi } from "@garage/api/server"
import { VendorActions } from "@/modules/vendors/vendor-actions"
import { VendorProvider } from "@/modules/vendors/vendor-context"
import React from "react"
export default async function layout(props: {
params: Promise<{ id: string }>
children: React.ReactNode
}) {
const { id } = await props.params
const api = await getServerApi()
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
const vendor = response?.data
const company = vendor?.company_name as string | undefined
const fullName = [vendor?.first_name, vendor?.last_name].filter(Boolean).join(" ").trim()
const title = company || fullName || "Vendor Details"
const isActive = vendor?.is_active ?? vendor?.status === "active"
return (
<VendorProvider vendor={{ id, label: title }}>
<DashboardDetailsPage
className="p-0 lg:p-0"
title={title}
description={vendor?.email ?? vendor?.phone ?? undefined}
backHref="/purchase/vendor"
actions={<VendorActions vendorId={id} isActive={Boolean(isActive)} />}
tabs={[
{ href: `/purchase/vendor/${id}`, label: "Details" },
]}
>
{props.children}
</DashboardDetailsPage>
</VendorProvider>
)
}

View File

@ -0,0 +1,17 @@
import { getServerApi } from "@garage/api/server"
import { VendorGeneralInfo } from "@/modules/vendors/vendor-general-info"
export default async function VendorDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params
const api = await getServerApi()
// The OpenAPI schema doesn't yet describe GET /api/vendors/{id} (only PUT/DELETE),
// so cast through `any` here until the schema is regenerated.
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
const vendor = response?.data
if (!vendor) {
return <div className="text-muted-foreground p-6">Vendor not found.</div>
}
return <VendorGeneralInfo vendor={vendor} />
}

View File

@ -1,18 +1,28 @@
"use client"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Power } from "lucide-react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { Badge } from "@/shared/components/ui/badge"
import { VendorForm } from "@/modules/vendors/vendor-form"
import { useAuthApi } from "@/shared/useApi"
import { VENDOR_ROUTES } from "@garage/api"
import type { VendorsClient } from "@garage/api"
export default function VendorsPage() {
const router = useRouter()
const api = useAuthApi()
return (
<ResourcePage<VendorsClient>
pageTitle="Vendors"
routeKey={VENDOR_ROUTES.INDEX}
searchable
searchPlaceholder="Search vendors..."
getClient={(api) => api.vendors}
onRowClick={(row) => router.push(`/purchase/vendor/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Vendor">
@ -46,6 +56,18 @@ export default function VendorsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Email" />,
cell: ({ row }) => (row.original as any).email || "—",
},
{
accessorKey: "is_active",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const isActive = Boolean((row.original as any).is_active)
return (
<Badge variant={isActive ? "default" : "outline"}>
{isActive ? "Active" : "Inactive"}
</Badge>
)
},
},
{
accessorKey: "created_at",
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
@ -54,7 +76,26 @@ export default function VendorsPage() {
return val ? new Date(val).toLocaleDateString() : "—"
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => {
const isActive = Boolean((row as any).is_active)
return [
{
label: isActive ? "Deactivate" : "Activate",
icon: Power,
onClick: async () => {
try {
await api.vendors.toggleStatus({ id: Number((row as any).id) } as any)
toast.success(isActive ? "Vendor deactivated." : "Vendor activated.")
router.refresh()
} catch {
toast.error("Failed to update vendor status.")
}
},
},
]
},
}),
]}
/>
)

View File

@ -5,7 +5,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { CreditNoteForm } from "@/modules/credit-notes/credit-note-form"
import { CREDIT_NOTE_ROUTES } from "@garage/api"
import { CREDIT_NOTE_ROUTES, CreditNoteStatus } from "@garage/api"
import type { CreditNotesClient } from "@garage/api"
type CreditNoteItem = {
@ -25,6 +25,9 @@ export default function CreditNotesPage() {
<ResourcePage<CreditNotesClient>
pageTitle="Credit Notes"
routeKey={CREDIT_NOTE_ROUTES.INDEX}
searchable
searchPlaceholder="Search credit notes..."
statusFilter={{ statuses: CreditNoteStatus }}
getClient={(api) => api.creditNotes}
onRowClick={(row) => router.push(`/sales/credit-notes/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({

View File

@ -32,6 +32,8 @@ export default function CustomerVehiclesPage({ params }: { params: Promise<{ id:
)}
pageTitle="Customer Vehicles"
routeKey={VEHICLE_ROUTES.INDEX}
searchable
searchPlaceholder="Search vehicles..."
getClient={(api) => api.vehicles}
extraParams={{ customer_id: customerId }}
header={null}

View File

@ -6,7 +6,6 @@ import { ColumnHeader } from '@/shared/data-view/table-view'
import FormDialog from '@/shared/components/form-dialog'
import { ImportDataButton } from '@/shared/components/import-data-button'
import { ExportDataButton } from '@/shared/components/export-data-button'
import { DownloadSampleButton } from '@/shared/components/download-sample-button'
import { useAuthApi } from '@/shared/useApi'
import { CustomerForm } from '@/modules/customers/customer-form'
import { CUSTOMER_ROUTES } from '@garage/api'
@ -20,18 +19,19 @@ export default function CustomersPage() {
<ResourcePage<CustomersClient>
pageTitle='Customers'
routeKey={CUSTOMER_ROUTES.INDEX}
searchable
searchPlaceholder="Search customers..."
getClient={(api) => api.customers}
onRowClick={(row) => router.push(`/sales/customers/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<div className='flex items-center gap-2'>
<DownloadSampleButton
onDownload={() => api.customers.downloadImportSample()}
fileName='customers-import-sample'
/>
<ImportDataButton
onImport={(file) => api.customers.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Customers"
onDownloadSample={() => api.customers.downloadImportSample()}
sampleFileName='customers-import-sample'
/>
<ExportDataButton
onExport={(filters) => api.customers.exportData(filters)}

View File

@ -4,6 +4,7 @@ import { EstimateActions } from '@/modules/estimates/estimate-actions'
import { EstimateProvider } from '@/modules/estimates/estimate-context'
import { CreateInvoiceFromEstimateButton } from '@/modules/estimates/create-invoice-from-estimate-button'
import { CreateJobCardFromEstimateButton } from '@/modules/estimates/create-job-card-from-estimate-button'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import { FileTextIcon } from 'lucide-react'
import React from 'react'
import { formatDate } from '@/shared/utils/formatters'
@ -40,6 +41,7 @@ export default async function layout(props: {
<div className="flex items-center gap-2">
<CreateInvoiceFromEstimateButton />
<CreateJobCardFromEstimateButton />
<ShareDocumentButton type="estimate" id={id} />
<EstimateActions estimateId={id} />
</div>
}

View File

@ -1,5 +1,6 @@
"use client"
import { useRouter } from 'next/navigation'
import { ResourcePage } from '@/shared/data-view/resource-page'
import { ColumnHeader } from '@/shared/data-view/table-view'
import FormDialog from '@/shared/components/form-dialog'
@ -7,18 +8,22 @@ import { EstimateForm } from '@/modules/estimates/estimate-form'
import { ESTIMATE_ROUTES } from '@garage/api'
import type { EstimatesClient } from '@garage/api'
import { Car, FileTextIcon, UserIcon } from 'lucide-react'
import { Button } from '@/shared/components/ui/button'
import Link from 'next/link'
import { formatDate } from '@/shared/utils/formatters'
import { getVehicleLabel } from '@/modules/vehicles/utils/getVehicleLabel'
import { getFullName } from '@/shared/utils/getFullName'
import { RelationLink } from '@/shared/components/relation-link'
export default function EstimatesPage() {
const router = useRouter()
return (
<ResourcePage<EstimatesClient>
pageTitle="Estimates"
routeKey={ESTIMATE_ROUTES.INDEX}
searchable
searchPlaceholder="Search estimates..."
getClient={(api) => api.estimates}
onRowClick={(row) => router.push(`/sales/estimates/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Estimate">
@ -39,7 +44,7 @@ export default function EstimatesPage() {
const item = row.original
return (
<div className="flex items-center gap-2">
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline">
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline" onClick={(e) => e.stopPropagation()}>
<FileTextIcon className="text-muted-foreground h-4 w-4" />
<span>{item.title}</span>
</Link>
@ -55,26 +60,30 @@ export default function EstimatesPage() {
accessorKey: "customer_name",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item:any = row.original
const item: any = row.original
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{getFullName(item.customer) || "—"}</span>
</div>
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getFullName(item.customer)}
/>
)
}
},
},
{
accessorKey: "vehicle",
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const item :any= row.original
return <Button variant="outline" asChild size="sm">
<Link href={`/sales/vehicles/${item.vehicle?.id}`}>
<Car/> {getVehicleLabel(item.vehicle as any) || "—"}
</Link>
</Button>
}
const item: any = row.original
return (
<RelationLink
href={item.vehicle?.id ? `/sales/vehicles/${item.vehicle.id}` : null}
icon={Car}
label={getVehicleLabel(item.vehicle as any)}
meta={item.vehicle?.license_plate}
/>
)
},
},
{
accessorKey: "date",

View File

@ -2,6 +2,7 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
import { getServerApi } from '@garage/api/server'
import { InspectionActions } from '@/modules/inspections/inspection-actions'
import { InspectionProvider } from '@/modules/inspections/inspection-context'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import React from 'react'
export default async function layout(props: {
@ -23,7 +24,12 @@ export default async function layout(props: {
title={title}
description={orderNumber ? `Order: ${orderNumber}` : undefined}
backHref="/sales/inspections"
actions={<InspectionActions inspectionId={id} status={status} />}
actions={
<div className="flex items-center gap-2">
<ShareDocumentButton type="inspection" id={id} />
<InspectionActions inspectionId={id} status={status} />
</div>
}
tabs={[
{
href: `/sales/inspections/${id}`,

View File

@ -1,5 +1,6 @@
import { getServerApi } from '@garage/api/server'
import { InspectionGeneralInfo } from '@/modules/inspections/inspection-general-info'
import { InspectionDetailHeader } from '@/modules/inspections/inspection-detail-header'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
export default async function page(props: { params: Promise<{ id: string }> }) {
@ -11,8 +12,11 @@ export default async function page(props: { params: Promise<{ id: string }> }) {
return <div className="text-muted-foreground">Inspection not found.</div>
}
const data = inspection.data as { title?: string }
return (
<DashboardPage header={null}>
<InspectionDetailHeader inspectionId={id} title={data.title} />
<InspectionGeneralInfo inspection={inspection.data} />
</DashboardPage>
)

View File

@ -1,46 +1,125 @@
"use client"
import { useState } from "react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { InspectionForm } from "@/modules/inspections/inspection-form"
import { INSPECTION_ROUTES } from "@garage/api"
import { InspectionFromTemplateForm } from "@/modules/inspections/inspection-from-template-form"
import { InspectionRowActions } from "@/modules/inspections/inspection-row-actions"
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 { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
import type { InspectionsClient } from "@garage/api"
import Link from "next/link"
import { Car, ClipboardList, ListChecks, UserIcon } from "lucide-react"
import { useRouter } from "next/navigation"
import { RelationLink } from "@/shared/components/relation-link"
import { getFullName } from "@/shared/utils/getFullName"
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
const STATUS_BADGE_CLASS: Record<string, string> = {
in_progress: "bg-amber-100 text-amber-800",
completed: "bg-emerald-100 text-emerald-800",
cancelled: "bg-rose-100 text-rose-800",
}
const STATUS_LABEL: Record<string, string> = {
in_progress: "In Progress",
completed: "Completed",
cancelled: "Cancelled",
}
export default function InspectionsPage() {
const router = useRouter()
const [fromTemplateOpen, setFromTemplateOpen] = useState(false)
return (
<ResourcePage<InspectionsClient>
pageTitle="Inspections"
routeKey={INSPECTION_ROUTES.INDEX}
searchable
searchPlaceholder="Search inspections..."
statusFilter={{ statuses: InspectionStatus }}
getClient={(api) => api.inspections}
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Inspection">
{(resourceId) => (
<InspectionForm
resourceId={resourceId}
initialData={selectedItem}
onSuccess={invalidateQuery}
/>
)}
</FormDialog>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" asChild>
<Link href="/settings/inspection-templates">
<ListChecks className="size-4" />
Manage templates
</Link>
</Button>
<Button size="sm" variant="default" onClick={() => setFromTemplateOpen(true)}>
<ClipboardList className="size-4" />
New from template
</Button>
<FormDialog title="Inspection" classNames={{ trigger: "" }}>
{(resourceId) => (
<InspectionForm
resourceId={resourceId}
initialData={selectedItem}
onSuccess={invalidateQuery}
/>
)}
</FormDialog>
<Dialog open={fromTemplateOpen} onOpenChange={setFromTemplateOpen}>
<DialogContent className="min-w-2xl">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">
New inspection from template
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<InspectionFromTemplateForm
onSuccess={(id) => {
setFromTemplateOpen(false)
invalidateQuery()
if (id) router.push(`/sales/inspections/${id}/checkpoints`)
}}
/>
</ScrollArea>
</DialogContent>
</Dialog>
</div>
),
})}
columns={({ actionsColumn }) => [
columns={({ openEdit, deleteItem }) => [
{
accessorKey: "title",
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
cell: ({ row }) => {
const r = row.original as any
return (
<div className="flex flex-col">
<span className="font-medium">{r.title ?? "—"}</span>
{r.order_number && (
<span className="text-xs text-muted-foreground">{r.order_number}</span>
)}
</div>
)
},
},
{
accessorKey: "customer",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const c = (row.original as any).customer
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
return (
<RelationLink
href={c?.id ? `/sales/customers/${c.id}` : null}
icon={UserIcon}
label={getFullName(c)}
/>
)
},
},
{
@ -48,27 +127,51 @@ export default function InspectionsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const v = (row.original as any).vehicle
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
return (
<RelationLink
href={v?.id ? `/sales/vehicles/${v.id}` : null}
icon={Car}
label={getVehicleLabel(v as any)}
meta={v?.license_plate}
/>
)
},
},
{
accessorKey: "inspection_category",
header: ({ column }) => <ColumnHeader column={column} title="Category" />,
cell: ({ row }) => (row.original as any).inspection_category?.name ?? "—",
cell: ({ row }) => {
const ic = (row.original as any).inspection_category
return ic?.inspection_name ?? ic?.name ?? "—"
},
},
{
accessorKey: "status",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const status = (row.original as any).status
const status = (row.original as any).status as string | undefined
if (!status) return "—"
const cls = STATUS_BADGE_CLASS[status] ?? "bg-gray-100 text-gray-700"
return (
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
{status ?? "—"}
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>
{STATUS_LABEL[status] ?? status}
</span>
)
},
},
actionsColumn(),
{
id: "actions",
header: () => <span className="sr-only">Actions</span>,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
<InspectionRowActions
inspection={row.original as any}
onEdit={() => openEdit(row.original as any)}
onDelete={() => deleteItem(String((row.original as any).id))}
/>
),
},
]}
/>
)

View File

@ -5,6 +5,7 @@ import { InvoiceProvider } from '@/modules/invoices/invoice-context'
import { ReceiptIcon } from 'lucide-react'
import React from 'react'
import InvoiceStatusBadge from '@/modules/invoices/invoice-status-badge'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
export default async function InvoiceDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
const { id } = await props.params
@ -24,6 +25,7 @@ export default async function InvoiceDetailLayout(props: { params: Promise<{ id:
<div className="flex space-x-2 items-center">
<InvoiceStatusBadge invoice={{id, status:data?.status}} />
<ShareDocumentButton type="invoice" id={id} />
<InvoiceActions invoiceId={id} />
</div>
}

View File

@ -1,14 +1,17 @@
"use client"
import { Car, UserIcon } from "lucide-react"
import { useRouter } from "next/navigation"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { InvoiceForm } from "@/modules/invoices/invoice-form"
import { Badge } from "@/shared/components/ui/badge"
import { formatCurrency, formatDate, formatEnum } from "@/shared/utils/formatters"
import { INVOICE_ROUTES } from "@garage/api"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { INVOICE_ROUTES, InvoiceStatus } from "@garage/api"
import type { InvoicesClient } from "@garage/api"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
type InvoiceItem = {
id: number
@ -23,6 +26,7 @@ type InvoiceItem = {
total?: number | string
balance_due?: number | string
customer?: {
id?: number | string
first_name?: string
last_name?: string
company_name?: string
@ -82,6 +86,9 @@ export default function InvoicesPage() {
<ResourcePage<InvoicesClient>
pageTitle="Invoices"
routeKey={INVOICE_ROUTES.INDEX}
searchable
searchPlaceholder="Search invoices..."
statusFilter={{ statuses: InvoiceStatus }}
getClient={(api) => api.invoices}
onRowClick={(row) => router.push(`/sales/invoice/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@ -133,15 +140,13 @@ export default function InvoicesPage() {
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item = row.original as unknown as InvoiceItem
const customerLabel = getCustomerLabel(item)
return (
<div className="min-w-[190px]">
<p className="font-medium leading-none">{customerLabel}</p>
<p className="mt-1 text-xs text-muted-foreground">
{item.customer?.phone || item.customer?.company_name || "—"}
</p>
</div>
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getCustomerLabel(item)}
meta={item.customer?.phone}
/>
)
},
},
@ -150,14 +155,14 @@ export default function InvoicesPage() {
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const item = row.original as unknown as InvoiceItem
const vehicleId = (item.vehicle as any)?.id
return (
<div className="min-w-[220px]">
<p className="font-medium leading-none">{getVehicleLabel(item)}</p>
<p className="mt-1 text-xs text-muted-foreground">
{item.vehicle?.license_plate || "—"}
</p>
</div>
<RelationLink
href={vehicleId ? `/sales/vehicles/${vehicleId}` : null}
icon={Car}
label={getVehicleLabel(item)}
meta={item.vehicle?.license_plate}
/>
)
},
},
@ -224,10 +229,10 @@ export default function InvoicesPage() {
return (
<div className="min-w-[150px]">
<p className="font-medium leading-none">
Total: {formatCurrency(item.total ?? 0)}
Total: {<Money value={item.total ?? 0} />}
</p>
<p className="mt-1 text-xs text-muted-foreground">
Due: {formatCurrency(item.balance_due ?? 0)}
Due: {<Money value={item.balance_due ?? 0} />}
</p>
</div>
)

View File

@ -7,11 +7,13 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { AppointmentForm } from "@/modules/appointments/appointment-form"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, ClockIcon } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { getFullName } from "@/shared/utils/getFullName"
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
const STATUS_COLORS: Record<string, string> = {
requested: "bg-yellow-100 text-yellow-800",
@ -42,13 +44,34 @@ export default function JobCardAppointmentsPage({
router.replace(`${pathname}?${params.toString()}`)
}, [pathname, router, searchParams])
const defaultJobCard = jobCard
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
const jc = jobCard as any
const defaultJobCard = jc
? { value: String(jc.id), label: jc.label || jc.title || `Job Card` }
: null
const appointmentDefaults = jc
? {
job_card_id: jc.id,
job_card_title: jc.title || `Job Card #${jc.id}`,
customer_id: jc.customer?.id,
customer_name: getFullName(jc.customer),
vehicle_id: jc.vehicle?.id,
vehicle_name: getVehicleLabel(jc.vehicle),
service_writer_id: jc.service_writer?.id,
service_writer_name: getFullName(jc.service_writer),
technician_id: jc.primary_technician?.id,
technician_name: getFullName(jc.primary_technician),
department_id: jc.department?.id,
department_name: jc.department?.name,
}
: { job_card: defaultJobCard }
return (
<ResourcePage<AppointmentsClient>
routeKey={APPOINTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search appointments..."
statusFilter={{ statuses: AppointmentStatus }}
getClient={(api) => api.appointments}
extraParams={{ job_card_id: jobCardId }}
header={null}
@ -59,8 +82,8 @@ export default function JobCardAppointmentsPage({
{(resourceId) => (
<AppointmentForm
resourceId={resourceId}
initialData={selectedItem ?? { job_card: defaultJobCard }}
onSuccess={() => { closeDialog(); invalidateQuery() }}
initialData={selectedItem ?? appointmentDefaults}
onSuccess={() => { closeDialog(); invalidateQuery(); router.refresh() }}
/>
)}
</FormDialog>

View File

@ -10,7 +10,7 @@ import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import { JOB_CARD_ROUTES } from "@garage/api"
import { ApiError, JOB_CARD_ROUTES } from "@garage/api"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { CONSTANTS } from "@/config/constants"
@ -22,6 +22,62 @@ function getFileIcon(mimeType?: string) {
return FileIcon
}
const ALLOWED_HINT = "Allowed: images, PDF, Office docs, audio, video."
function describeAttachmentError(rawMessage: string, filename: string): string {
const msg = rawMessage.toLowerCase()
if (msg.includes("must be a file of type") || msg.includes("mimes")) {
return `${filename}: unsupported file type. ${ALLOWED_HINT}`
}
if (msg.includes("may not be greater") || msg.includes("max")) {
return `${filename}: exceeds 5 MB limit.`
}
if (msg.includes("must be a file")) {
return `${filename}: invalid file.`
}
return `${filename}: ${rawMessage}`
}
function showUploadError(err: unknown, files: File[]) {
if (!(err instanceof ApiError)) {
toast.error("Failed to upload attachment(s)")
return
}
const validation = err.validationErrors
if (!validation || Object.keys(validation).length === 0) {
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
return
}
const messages: string[] = []
for (const [key, msgs] of Object.entries(validation)) {
const firstMsg = Array.isArray(msgs) ? msgs[0] : String(msgs)
if (!firstMsg) continue
const match = key.match(/^attachments\.(\d+)$/)
if (match) {
const idx = Number(match[1])
const filename = files[idx]?.name ?? `File #${idx + 1}`
messages.push(describeAttachmentError(firstMsg, filename))
} else if (key === "attachments") {
messages.push(firstMsg)
} else {
messages.push(firstMsg)
}
}
if (messages.length === 0) {
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
return
}
const shown = messages.slice(0, 3)
const extra = messages.length - shown.length
shown.forEach((m) => toast.error(m))
if (extra > 0) toast.error(`...and ${extra} more`)
}
export default function JobCardAttachmentsPage() {
const { id: jobCardId } = useParams<{ id: string }>()
const api = useAuthApi()
@ -66,18 +122,19 @@ export default function JobCardAttachmentsPage() {
const files = e.target.files
if (!files || files.length === 0) return
const fileList = Array.from(files)
setIsUploading(true)
const promise = api.jobCards.addAttachment(jobCardId, Array.from(files))
toast.promise(promise, {
loading: "Uploading attachment(s)...",
success: "Attachment(s) uploaded successfully",
error: "Failed to upload attachment(s)",
})
const loadingToast = toast.loading("Uploading attachment(s)...")
try {
await promise
await api.jobCards.addAttachment(jobCardId, fileList)
toast.dismiss(loadingToast)
toast.success("Attachment(s) uploaded successfully")
queryClient.invalidateQueries({ queryKey })
startRefreshTransition(() => router.refresh())
} catch (err) {
toast.dismiss(loadingToast)
showUploadError(err, fileList)
} finally {
setIsUploading(false)
if (fileInputRef.current) {

View File

@ -6,9 +6,12 @@ import { Badge } from "@/shared/components/ui/badge"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { BillForm } from "@/modules/bills/bill-form"
import { BILL_ROUTES } from "@garage/api"
import { BILL_ROUTES, BillStatus } from "@garage/api"
import type { BillsClient } from "@garage/api"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, FileTextIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
export default function JobCardBillsPage({
params,
@ -25,6 +28,9 @@ export default function JobCardBillsPage({
return (
<ResourcePage<BillsClient>
routeKey={BILL_ROUTES.INDEX}
searchable
searchPlaceholder="Search bills..."
statusFilter={{ statuses: BillStatus }}
getClient={(api) => api.bills}
extraParams={{ job_card_id: jobCardId }}
header={null}
@ -46,7 +52,16 @@ export default function JobCardBillsPage({
{
accessorKey: "bill_number",
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
cell: ({ row }) => (row.original as any).bill_number || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.id ? `/purchase/bill/${item.id}` : null}
icon={FileTextIcon}
label={item.bill_number}
/>
)
},
},
{
accessorKey: "title",
@ -55,7 +70,16 @@ export default function JobCardBillsPage({
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "bill_date",

View File

@ -44,6 +44,7 @@ export default function JobCardExpenseItemsPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getExpenseItems(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []

View File

@ -4,10 +4,14 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { InspectionForm } from "@/modules/inspections/inspection-form"
import { INSPECTION_ROUTES } from "@garage/api"
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
import type { InspectionsClient } from "@garage/api"
import { useRouter } from "next/navigation"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { RelationLink } from "@/shared/components/relation-link"
import { Car, UserIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
export default function InspectionsPage() {
const router = useRouter()
@ -17,6 +21,9 @@ export default function InspectionsPage() {
pageTitle="Inspections"
extraParams={{job_card_id: jobCard?.id}}
routeKey={INSPECTION_ROUTES.INDEX}
searchable
searchPlaceholder="Search inspections..."
statusFilter={{ statuses: InspectionStatus }}
getClient={(api) => api.inspections}
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@ -42,7 +49,13 @@ export default function InspectionsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const c = (row.original as any).customer
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
return (
<RelationLink
href={c?.id ? `/sales/customers/${c.id}` : null}
icon={UserIcon}
label={getFullName(c)}
/>
)
},
},
{
@ -50,7 +63,14 @@ export default function InspectionsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const v = (row.original as any).vehicle
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
return (
<RelationLink
href={v?.id ? `/sales/vehicles/${v.id}` : null}
icon={Car}
label={getVehicleLabel(v as any)}
meta={v?.license_plate}
/>
)
},
},
{

View File

@ -16,7 +16,7 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
const title = jobCard?.title || 'Job Card Details'
const status = jobCard?.status || 'draft'
const docs = jobCard?.documents
const attachmentsCount = jobCard?.attachment_files?.length ?? jobCard?.documents?.length ?? 0
return (
<JobCardProvider jobCard={{ ...jobCard }}>
@ -55,7 +55,7 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
// TODO: Needs refactor from API side then refactor in frontend
{
href: `/sales/job-cards/${id}/attachments`,
label: `Attachments (${docs?.length || 0})`
label: `Attachments (${attachmentsCount})`
},
{

View File

@ -1,21 +1,10 @@
import { getServerApi } from '@garage/api/server'
import { JobCardGeneralInfo } from '@/modules/job-cards/job-card-general-info'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
import type { JobCardShowData } from '@garage/api'
export default async function JobCardDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params
const api = await getServerApi()
const response = await api.jobCards.show(id)
const data = response.data
if (!data) {
return <div className="text-muted-foreground">Job card not found.</div>
}
export default async function JobCardDetailPage() {
return (
<DashboardPage header={null}>
<JobCardGeneralInfo jobCard={data} />
<JobCardGeneralInfo />
</DashboardPage>
)
}

View File

@ -44,6 +44,7 @@ export default function JobCardPartsPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getParts(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []

View File

@ -8,6 +8,9 @@ import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
import type { PurchaseOrdersClient } from "@garage/api"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, FileTextIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
export default function JobCardPurchaseOrdersPage({
params,
@ -24,6 +27,8 @@ export default function JobCardPurchaseOrdersPage({
return (
<ResourcePage<PurchaseOrdersClient>
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
searchable
searchPlaceholder="Search purchase orders..."
getClient={(api) => api.purchaseOrders}
extraParams={{ job_card_id: jobCardId }}
header={null}
@ -46,7 +51,16 @@ export default function JobCardPurchaseOrdersPage({
{
accessorKey: "order_number",
header: ({ column }) => <ColumnHeader column={column} title="Order #" />,
cell: ({ row }) => (row.original as any).order_number || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.id ? `/purchase/purchase-order/${item.id}` : null}
icon={FileTextIcon}
label={item.order_number}
/>
)
},
},
{
accessorKey: "title",
@ -55,7 +69,16 @@ export default function JobCardPurchaseOrdersPage({
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "order_date",

View File

@ -46,6 +46,7 @@ export default function JobCardServicesPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getServices(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []

View File

@ -5,7 +5,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { TaskForm } from "@/modules/tasks/task-form"
import { TASK_ROUTES } from "@garage/api"
import { TASK_ROUTES, TaskStatus } from "@garage/api"
import type { TasksClient } from "@garage/api"
import { Badge } from "@/shared/components/ui/badge"
import { useJobCard } from "@/modules/job-cards/job-card-context"
@ -26,6 +26,9 @@ export default function JobCardTasksPage({
return (
<ResourcePage<TasksClient>
routeKey={TASK_ROUTES.INDEX}
searchable
searchPlaceholder="Search tasks..."
statusFilter={{ statuses: TaskStatus }}
getClient={(api) => api.tasks}
extraParams={{ job_card_id: jobCardId }}
header={null}

View File

@ -6,12 +6,9 @@ import FormDialog from '@/shared/components/form-dialog'
import { JobCardForm } from '@/modules/job-cards/job-card-form'
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
import type { JobCardsClient } from '@garage/api'
import { Tabs, TabsList, TabsTrigger } from '@/shared/components/ui/tabs'
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
import { ClipboardListIcon } from 'lucide-react'
import { Badge } from '@/shared/components/ui/badge'
import { Input } from '@/shared/components/ui/input'
import { useRouter } from 'next/navigation'
import { useState, useEffect, useMemo } from 'react'
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
import { useFilterParams } from '@/shared/hooks/use-filter-params'
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
@ -37,30 +34,17 @@ const statusColorMap: Record<string, string> = {
export default function JobCardsPage() {
const router = useRouter()
const [searchInput, setSearchInput] = useState("")
const [search, setSearch] = useState("")
const [statusFilter, setStatusFilter] = useState<string>("check_in")
const filter = useFilterParams(jobCardFilterConfig)
useEffect(() => {
const timer = setTimeout(() => setSearch(searchInput), 400)
return () => clearTimeout(timer)
}, [searchInput])
const extraParams = useMemo(() => {
const params: Record<string, unknown> = { ...filter.appliedParams }
if (search) params.search = search
if (statusFilter !== "all") params.status = statusFilter
return params
}, [filter.appliedParams, search, statusFilter])
return (
<>
<ResourcePage<JobCardsClient>
routeKey={JOB_CARD_ROUTES.INDEX}
getClient={(api) => api.jobCards}
extraParams={extraParams}
searchable
searchPlaceholder="Search job cards..."
statusFilter={{ statuses: JobCardStatus }}
extraParams={filter.appliedParams}
onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
title: "Job Cards",
@ -135,30 +119,6 @@ export default function JobCardsPage() {
},
actionsColumn(),
]}
tableHeader={
<div className="flex justify-between">
<Tabs value={statusFilter} onValueChange={setStatusFilter}>
<TabsList variant="line">
<TabsTrigger value="all">All</TabsTrigger>
{JobCardStatus.map((status) => (
<TabsTrigger key={status} value={status}>
{formatEnum(status)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<div className="relative w-64">
<SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search job cards..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="pl-8"
/>
</div>
</div>
}
/>
<FilterDrawer

View File

@ -14,6 +14,7 @@ import {
ClipboardListIcon,
} from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { RelationLink } from "@/shared/components/relation-link"
type PaymentReceivedItem = {
id: number
@ -33,6 +34,8 @@ export default function PaymentReceivedPage() {
return (
<ResourcePage<{ list(query?: any): Promise<any>; destroy(id: string): Promise<any> }>
routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
searchable
searchPlaceholder="Search payments..."
getClient={(api) => ({
list: (query?: any) => api.paymentReceived.list(query),
destroy: (id: string) => api.paymentReceived.destroy(id),
@ -67,12 +70,14 @@ export default function PaymentReceivedPage() {
accessorKey: "customer",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item:any = row.original as unknown as PaymentReceivedItem
const item: any = row.original as unknown as PaymentReceivedItem
const customer = item.customer
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{getFullName(item.customer) || "—"}</span>
</div>
<RelationLink
href={customer?.id ? `/sales/customers/${customer.id}` : null}
icon={UserIcon}
label={getFullName(customer) || item.customer_name}
/>
)
},
},
@ -80,13 +85,14 @@ export default function PaymentReceivedPage() {
accessorKey: "job_card",
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
cell: ({ row }) => {
const item:any = row.original as unknown as PaymentReceivedItem
const label = item.job_card?.title
const item: any = row.original as unknown as PaymentReceivedItem
const jobCard = item.job_card
return (
<div className="flex items-center gap-2">
<ClipboardListIcon className="h-4 w-4 text-muted-foreground" />
<span>{label || "—"}</span>
</div>
<RelationLink
href={jobCard?.id ? `/sales/job-cards/${jobCard.id}` : null}
icon={ClipboardListIcon}
label={jobCard?.title || item.job_card_name}
/>
)
},
},

View File

@ -8,8 +8,10 @@ import FormDialog from '@/shared/components/form-dialog'
import { EstimateForm } from '@/modules/estimates/estimate-form'
import { ESTIMATE_ROUTES } from '@garage/api'
import type { EstimatesClient } from '@garage/api'
import { FileTextIcon } from 'lucide-react'
import { FileTextIcon, UserIcon } from 'lucide-react'
import { useVehicle } from '@/modules/vehicles/vehicle-context'
import { RelationLink } from '@/shared/components/relation-link'
import { getFullName } from '@/shared/utils/getFullName'
export default function VehicleEstimatesPage({ params }: { params: Promise<{ id: string }> }) {
const { id: vehicleId } = use(params)
@ -37,6 +39,8 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
}
pageTitle="Vehicle Estimates"
routeKey={ESTIMATE_ROUTES.INDEX}
searchable
searchPlaceholder="Search estimates..."
getClient={(api) => api.estimates}
extraParams={{ vehicle_id: vehicleId }}
header={
@ -63,6 +67,16 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
{
accessorKey: "customer_name",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getFullName(item.customer) || item.customer_name}
/>
)
},
},
{
accessorKey: "date",

View File

@ -7,14 +7,14 @@ import type { ColumnDef } from '@tanstack/react-table'
import FormDialog from '@/shared/components/form-dialog'
import { ImportDataButton } from '@/shared/components/import-data-button'
import { ExportDataButton } from '@/shared/components/export-data-button'
import { DownloadSampleButton } from '@/shared/components/download-sample-button'
import { useAuthApi } from '@/shared/useApi'
import type { CrudResourceColumnHelpers, ResourceItem } from '@/shared/data-view/resource-page'
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
import { VEHICLE_ROUTES } from '@garage/api'
import type { VehiclesClient } from '@garage/api'
import { CarIcon } from 'lucide-react'
import { CarIcon, UserIcon } from 'lucide-react'
import { getFullName } from '@/shared/utils/getFullName'
import { RelationLink } from '@/shared/components/relation-link'
export default function VehiclesPage() {
const router = useRouter()
@ -23,18 +23,19 @@ export default function VehiclesPage() {
<ResourcePage<VehiclesClient>
pageTitle="Vehicles"
routeKey={VEHICLE_ROUTES.INDEX}
searchable
searchPlaceholder="Search vehicles..."
getClient={(api) => api.vehicles}
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<div className='flex items-center gap-2'>
<DownloadSampleButton
onDownload={() => api.vehicles.downloadImportSample()}
fileName='vehicles-import-sample'
/>
<ImportDataButton
onImport={(file) => api.vehicles.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Vehicles"
onDownloadSample={() => api.vehicles.downloadImportSample()}
sampleFileName='vehicles-import-sample'
/>
<ExportDataButton
onExport={(filters) => api.vehicles.exportData(filters)}
@ -80,8 +81,14 @@ export default function VehiclesPage() {
accessorKey: "customers",
header: ({ column }: any) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }: any) => {
const val = (row.original as any).customers?.[0]
return getFullName(val)
const customer = (row.original as any).customers?.[0]
return (
<RelationLink
href={customer?.id ? `/sales/customers/${customer.id}` : null}
icon={UserIcon}
label={getFullName(customer)}
/>
)
},
} as any,
{

View File

@ -55,6 +55,8 @@ export default function DepartmentsPage() {
<ResourcePage<DepartmentsClient>
pageTitle="Departments"
routeKey={DEPARTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search departments..."
getClient={(api) => api.departments}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -0,0 +1,264 @@
"use client"
import { useCallback, useEffect, useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Pencil, Plus, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Textarea } from "@/shared/components/ui/textarea"
import { Switch } from "@/shared/components/ui/switch"
import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import { prompt } from "@/shared/components/prompt-dialog"
import { TemplateCheckpointEditDialog } from "@/modules/inspections/template-checkpoint-edit-dialog"
import type {
InspectionTemplate,
InspectionTemplateSection,
InspectionTemplateCheckPoint,
InspectionSeverity,
} from "@garage/api"
const SEVERITY_BADGE: Record<InspectionSeverity, { label: string; cls: string }> = {
good: { label: "Good", cls: "bg-emerald-100 text-emerald-800" },
attention: { label: "Attention", cls: "bg-amber-100 text-amber-800" },
critical: { label: "Critical", cls: "bg-rose-100 text-rose-800" },
na: { label: "N/A", cls: "bg-slate-100 text-slate-700" },
not_inspected: { label: "Not inspected", cls: "bg-gray-100 text-gray-700" },
}
const RECORD_TYPE_LABEL: Record<string, string> = {
capture_photo: "Photo",
record_video: "Video",
record_audio: "Audio",
record_conditions: "0100",
wire_frame: "Wireframe",
none: "No media",
}
export default function InspectionTemplateEditorPage() {
const params = useParams<{ id: string }>()
const id = params.id
const api = useAuthApi()
const [template, setTemplate] = useState<InspectionTemplate | null>(null)
const [loading, setLoading] = useState(true)
const [editing, setEditing] = useState<{
section: InspectionTemplateSection
checkpoint: InspectionTemplateCheckPoint | null
} | null>(null)
const load = useCallback(async () => {
setLoading(true)
try {
const res = await api.inspectionTemplates.show(id)
setTemplate(res.data)
} catch (e: any) {
toast.error(e?.message ?? "Failed to load template")
} finally {
setLoading(false)
}
}, [id])
useEffect(() => { load() }, [load])
const updateMeta = async (partial: Partial<InspectionTemplate>) => {
if (!template) return
try {
const res = await api.inspectionTemplates.update(template.id, partial)
setTemplate(res.data)
} catch (e: any) {
toast.error(e?.message ?? "Failed to save")
}
}
const addSection = async () => {
if (!template) return
const name = await prompt({
title: "New section",
label: "Section name",
placeholder: "e.g. Brakes",
confirmLabel: "Add section",
})
if (!name) return
const nextOrder = (template.sections?.length ?? 0) + 1
try {
await api.inspectionTemplates.createSection(template.id, { name, sort_order: nextOrder })
await load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to add section")
}
}
const deleteSection = async (section: InspectionTemplateSection) => {
if (!template) return
const confirmed = await confirm({
title: `Delete section "${section.name}"?`,
description: "This will remove the section and all its checkpoints.",
confirmLabel: "Delete",
variant: "destructive",
})
if (!confirmed) return
try {
await api.inspectionTemplates.destroySection(template.id, section.id)
await load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to delete section")
}
}
const renameSection = async (section: InspectionTemplateSection, name: string) => {
if (!template || name === section.name) return
try {
await api.inspectionTemplates.updateSection(template.id, section.id, { name })
await load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to rename section")
}
}
const deleteCheckpoint = async (section: InspectionTemplateSection, cp: InspectionTemplateCheckPoint, e: React.MouseEvent) => {
e.stopPropagation()
if (!template) return
const confirmed = await confirm({
title: `Delete "${cp.name}"?`,
description: "This checkpoint will be removed from the template.",
confirmLabel: "Delete",
variant: "destructive",
})
if (!confirmed) return
try {
await api.inspectionTemplates.destroyCheckpoint(template.id, section.id, cp.id)
await load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to delete checkpoint")
}
}
if (loading) return <div className="p-6 text-muted-foreground">Loading</div>
if (!template) return <div className="p-6 text-muted-foreground">Template not found</div>
return (
<div className="p-6 space-y-6 max-w-4xl">
<div className="flex items-center gap-2">
<Link href="/settings/inspection-templates">
<Button variant="ghost" size="sm"><ChevronLeft className="size-4 mr-1" /> Back</Button>
</Link>
</div>
<div className="rounded border p-4 space-y-3">
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<label className="text-xs text-muted-foreground">Name</label>
<Input
defaultValue={template.name}
onBlur={(e) => e.currentTarget.value !== template.name && updateMeta({ name: e.currentTarget.value })}
/>
</div>
<div className="flex items-center gap-3 mt-5">
<Switch
checked={template.is_active}
onCheckedChange={(checked) => updateMeta({ is_active: checked })}
/>
<span className="text-sm">{template.is_active ? "Active" : "Inactive"}</span>
</div>
</div>
<div>
<label className="text-xs text-muted-foreground">Description</label>
<Textarea
defaultValue={template.description ?? ""}
rows={2}
onBlur={(e) => e.currentTarget.value !== (template.description ?? "") && updateMeta({ description: e.currentTarget.value })}
/>
</div>
</div>
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Sections & Checkpoints</h2>
<Button onClick={addSection} size="sm"><Plus className="size-4 mr-1" /> Add section</Button>
</div>
<div className="space-y-4">
{(template.sections ?? []).length === 0 && (
<div className="rounded border-dashed border p-6 text-center text-sm text-muted-foreground">
No sections yet. Add one to start building the checklist.
</div>
)}
{(template.sections ?? []).map((section) => (
<div key={section.id} className="rounded border">
<div className="flex items-center gap-2 px-3 py-2 bg-muted/40">
<Input
defaultValue={section.name}
onBlur={(e) => renameSection(section, e.currentTarget.value)}
className="max-w-md h-8"
/>
<span className="text-xs text-muted-foreground">
{(section.check_points ?? []).length} checkpoint{(section.check_points ?? []).length === 1 ? "" : "s"}
</span>
<div className="ml-auto flex items-center gap-1">
<Button size="sm" variant="ghost" onClick={() => setEditing({ section, checkpoint: null })}>
<Plus className="size-4 mr-1" /> Checkpoint
</Button>
<Button size="sm" variant="ghost" onClick={() => deleteSection(section)}>
<Trash2 className="size-4 text-red-600" />
</Button>
</div>
</div>
<div className="divide-y">
{(section.check_points ?? []).length === 0 && (
<div className="p-3 text-sm text-muted-foreground">No checkpoints in this section.</div>
)}
{(section.check_points ?? []).map((cp) => {
const sev = SEVERITY_BADGE[cp.severity_default] ?? SEVERITY_BADGE.not_inspected
return (
<button
type="button"
key={cp.id}
onClick={() => setEditing({ section, checkpoint: cp })}
className="w-full text-left flex items-center gap-3 px-3 py-2 hover:bg-muted/30 transition"
>
<span className="text-xs text-muted-foreground w-6 text-right">
{cp.sort_order}
</span>
<span className="flex-1 min-w-0 truncate text-sm font-medium">
{cp.name}
</span>
<span className="text-xs text-muted-foreground hidden sm:inline-block">
{RECORD_TYPE_LABEL[cp.record_type] ?? cp.record_type}
</span>
<span className={`text-xs rounded-full px-2 py-0.5 ${sev.cls}`}>
{sev.label}
</span>
<Pencil className="size-3.5 text-muted-foreground" />
<button
type="button"
onClick={(e) => deleteCheckpoint(section, cp, e)}
className="text-red-600 hover:text-red-700"
aria-label="Delete checkpoint"
>
<Trash2 className="size-4" />
</button>
</button>
)
})}
</div>
</div>
))}
</div>
{editing && (
<TemplateCheckpointEditDialog
open={!!editing}
onOpenChange={(o) => { if (!o) setEditing(null) }}
templateId={template.id}
sectionId={editing.section.id}
checkpoint={editing.checkpoint}
nextSortOrder={(editing.section.check_points?.length ?? 0) + 1}
onSaved={load}
/>
)}
</div>
)
}

View File

@ -0,0 +1,157 @@
"use client"
import { useEffect, useState } from "react"
import Link from "next/link"
import { Copy, Pencil, Plus, Trash2 } from "lucide-react"
import { toast } from "sonner"
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"
import type { InspectionTemplate } from "@garage/api"
export default function InspectionTemplatesPage() {
const api = useAuthApi()
const [items, setItems] = useState<InspectionTemplate[]>([])
const [search, setSearch] = useState("")
const [loading, setLoading] = useState(true)
const [creating, setCreating] = useState(false)
const [newName, setNewName] = useState("")
const load = async () => {
setLoading(true)
try {
const res = await api.inspectionTemplates.list(search ? { search } : undefined)
setItems(res.data ?? [])
} catch (e: any) {
toast.error(e?.message ?? "Failed to load templates")
} finally {
setLoading(false)
}
}
useEffect(() => {
load()
}, [])
const handleCreate = async () => {
if (!newName.trim()) return
try {
await api.inspectionTemplates.create({ name: newName.trim(), is_active: true })
setNewName("")
setCreating(false)
toast.success("Template created")
load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to create template")
}
}
const handleDuplicate = async (id: number) => {
try {
await api.inspectionTemplates.duplicate(id)
toast.success("Template duplicated")
load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to duplicate template")
}
}
const handleDelete = async (id: number, name: string) => {
const confirmed = await confirm({
title: `Delete "${name}"?`,
description: "This will remove the template and all its sections / checkpoints.",
confirmLabel: "Delete",
variant: "destructive",
})
if (!confirmed) return
try {
await api.inspectionTemplates.destroy(id)
toast.success("Template deleted")
load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to delete template")
}
}
return (
<div className="p-6 space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-2xl font-semibold">Inspection Templates</h1>
<div className="flex items-center gap-2">
<Input
placeholder="Search…"
value={search}
onChange={(e) => setSearch(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && load()}
className="w-56"
/>
<Button onClick={() => setCreating((c) => !c)}>
<Plus className="size-4 mr-1" /> New template
</Button>
</div>
</div>
{creating && (
<div className="flex items-center gap-2 rounded border p-3">
<Input
autoFocus
placeholder="Template name (e.g. Annual Safety)"
value={newName}
onChange={(e) => setNewName(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleCreate()}
className="max-w-md"
/>
<Button onClick={handleCreate}>Create</Button>
<Button variant="ghost" onClick={() => { setCreating(false); setNewName("") }}>Cancel</Button>
</div>
)}
<div className="rounded border">
<table className="w-full text-sm">
<thead className="bg-muted">
<tr>
<th className="text-left p-3">Name</th>
<th className="text-left p-3">Sections</th>
<th className="text-left p-3">Checkpoints</th>
<th className="text-left p-3">Status</th>
<th className="text-right p-3">Actions</th>
</tr>
</thead>
<tbody>
{loading && (
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">Loading</td></tr>
)}
{!loading && items.length === 0 && (
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">No templates yet</td></tr>
)}
{!loading && items.map((t) => {
const sectionCount = t.sections?.length ?? 0
const cpCount = (t.sections ?? []).reduce((sum, s) => sum + (s.check_points?.length ?? 0), 0)
return (
<tr key={t.id} className="border-t hover:bg-muted/40">
<td className="p-3 font-medium">{t.name}</td>
<td className="p-3">{sectionCount}</td>
<td className="p-3">{cpCount}</td>
<td className="p-3">
<span className={`inline-block rounded-full px-2 py-0.5 text-xs ${t.is_active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"}`}>
{t.is_active ? "Active" : "Inactive"}
</span>
</td>
<td className="p-3 text-right space-x-1">
<Link href={`/settings/inspection-templates/${t.id}`}>
<Button size="sm" variant="ghost"><Pencil className="size-4" /></Button>
</Link>
<Button size="sm" variant="ghost" onClick={() => handleDuplicate(t.id)}><Copy className="size-4" /></Button>
<Button size="sm" variant="ghost" onClick={() => handleDelete(t.id, t.name)}><Trash2 className="size-4 text-red-600" /></Button>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
)
}

View File

@ -12,6 +12,8 @@ export default function InsuranceTypesPage() {
<ResourcePage<InsuranceTypesClient>
pageTitle="Insurance Types"
routeKey={INSURANCE_TYPE_ROUTES.INDEX}
searchable
searchPlaceholder="Search insurance types..."
getClient={(api) => api.insuranceTypes}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -12,6 +12,8 @@ export default function MakeAndModelsPage() {
<ResourcePage<MakeAndModelsClient>
pageTitle="Make & Models"
routeKey={MAKE_AND_MODEL_ROUTES.INDEX}
searchable
searchPlaceholder="Search makes & models..."
getClient={(api) => api.makeAndModels}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -13,6 +13,8 @@ export default function ShopTypesPage() {
<ResourcePage<ShopTypesClient>
pageTitle="Shop Types"
routeKey={SHOP_TYPE_ROUTES.INDEX}
searchable
searchPlaceholder="Search shop types..."
getClient={(api) => api.shopTypes}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -55,6 +55,8 @@ export default function TaxesPage() {
<ResourcePage<TaxesClient>
pageTitle="Tax & Rates"
routeKey={TAX_ROUTES.INDEX}
searchable
searchPlaceholder="Search tax rates..."
getClient={(api) => api.taxes}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (

View File

@ -0,0 +1,444 @@
"use client"
import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import {
AlertCircle,
Calendar,
Car,
CheckCircle2,
ChevronRight,
ClipboardList,
Gauge,
Loader2,
Printer,
ShieldAlert,
ShieldCheck,
User,
} from "lucide-react"
type Severity = "good" | "attention" | "critical" | "na" | "not_inspected"
type Photo = { id: number; url: string | null; caption?: string | null }
type CheckPoint = {
name: string
description?: string | null
severity: Severity
technician_notes?: string | null
condition_rate?: number | null
photos?: Photo[]
}
type Section = { name: string; items: CheckPoint[] }
type PublicInspection = {
title?: string
order_number?: string
date?: string
time?: string
status?: string
odometer?: number | null
note?: string | null
description?: string | null
customer?: { name?: string } | null
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string; vin?: string } | null
technician?: { name?: string } | null
department?: string | null
template?: string | null
totals: { good: number; attention: number; critical: number; na: number; not_inspected: number; considered: number; all: number }
score: number | null
sections: Section[]
share_expires_at?: string | null
}
const SEVERITY_LABEL: Record<Severity, string> = {
good: "Good",
attention: "Attention",
critical: "Critical",
na: "N/A",
not_inspected: "Not Inspected",
}
const SEVERITY_DOT_BG: Record<Severity, string> = {
good: "bg-emerald-500",
attention: "bg-amber-500",
critical: "bg-rose-500",
na: "bg-slate-400",
not_inspected: "bg-gray-300",
}
const SEVERITY_PILL: Record<Severity, string> = {
good: "bg-emerald-50 text-emerald-700 border-emerald-200",
attention: "bg-amber-50 text-amber-800 border-amber-200",
critical: "bg-rose-50 text-rose-700 border-rose-200",
na: "bg-slate-50 text-slate-700 border-slate-200",
not_inspected: "bg-gray-50 text-gray-600 border-gray-200",
}
const SEVERITY_BORDER: Record<Severity, string> = {
good: "border-l-emerald-500",
attention: "border-l-amber-500",
critical: "border-l-rose-500",
na: "border-l-slate-400",
not_inspected: "border-l-gray-300",
}
function ScoreRing({ score }: { score: number | null }) {
if (score === null) {
return (
<div className="size-32 rounded-full border-4 border-dashed border-muted-foreground/30 flex items-center justify-center text-xs text-muted-foreground">
Not scored
</div>
)
}
const color =
score >= 80 ? "text-emerald-600" : score >= 50 ? "text-amber-600" : "text-rose-600"
const stroke =
score >= 80 ? "stroke-emerald-500" : score >= 50 ? "stroke-amber-500" : "stroke-rose-500"
const r = 56
const c = 2 * Math.PI * r
const offset = c - (score / 100) * c
return (
<div className="relative size-32 shrink-0">
<svg viewBox="0 0 128 128" className="size-32 -rotate-90">
<circle cx="64" cy="64" r={r} className="fill-none stroke-muted" strokeWidth="10" />
<circle
cx="64"
cy="64"
r={r}
className={`fill-none ${stroke} transition-[stroke-dashoffset]`}
strokeWidth="10"
strokeLinecap="round"
strokeDasharray={c}
strokeDashoffset={offset}
/>
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center">
<div className={`text-3xl font-bold leading-none ${color}`}>{score}</div>
<div className="text-[10px] uppercase tracking-wider text-muted-foreground mt-1">
Health
</div>
</div>
</div>
)
}
export default function PublicInspectionPage() {
const params = useParams<{ token: string }>()
const token = params.token
const [data, setData] = useState<PublicInspection | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
const [lightbox, setLightbox] = useState<Photo | null>(null)
useEffect(() => {
const base = process.env.NEXT_PUBLIC_API_URL ?? ""
fetch(`${base.replace(/\/$/, "")}/api/public/inspections/${token}`, {
headers: { Accept: "application/json", "X-Lang": "en" },
})
.then(async (res) => {
if (!res.ok) {
const body = await res.json().catch(() => ({} as any))
throw new Error(body.message ?? `Failed (HTTP ${res.status})`)
}
return res.json()
})
.then((json: { data: PublicInspection }) => setData(json.data))
.catch((e: Error) => setError(e.message))
.finally(() => setLoading(false))
}, [token])
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100">
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="size-4 animate-spin" /> Loading inspection
</div>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-6">
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
<AlertCircle className="size-12 mx-auto text-rose-500" />
<h1 className="text-lg font-semibold">Can't open this inspection</h1>
<p className="text-sm text-muted-foreground">{error}</p>
</div>
</div>
)
}
if (!data) return null
const vehicleLine = data.vehicle
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
: "—"
const criticalCount = data.totals.critical
const attentionCount = data.totals.attention
const headlineStatus =
criticalCount > 0
? { Icon: ShieldAlert, color: "text-rose-600", bg: "bg-rose-50", label: `${criticalCount} critical issue${criticalCount === 1 ? "" : "s"} found` }
: attentionCount > 0
? { Icon: AlertCircle, color: "text-amber-600", bg: "bg-amber-50", label: `${attentionCount} item${attentionCount === 1 ? "" : "s"} need attention` }
: { Icon: ShieldCheck, color: "text-emerald-600", bg: "bg-emerald-50", label: "No issues found" }
return (
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
{/* Print is handled by downloading the backend-generated PDF
(see the Print button), so this page no longer needs print CSS. */}
{/* Print bar */}
<div className="no-print bg-white/80 backdrop-blur border-b sticky top-0 z-10">
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-3 flex items-center justify-between">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<ClipboardList className="size-4" />
<span className="font-medium text-foreground">Inspection report</span>
</div>
<a
href={`${(process.env.NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, "")}/api/public/inspections/${token}/print`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm border bg-white hover:bg-muted/40 transition"
>
<Printer className="size-3.5" /> Print PDF
</a>
</div>
</div>
<div className="max-w-3xl mx-auto p-4 sm:p-6 space-y-5">
{/* Hero card */}
<div className="rounded-2xl bg-white shadow-sm border overflow-hidden">
<div className="p-6 sm:p-8">
<div className="flex items-start justify-between gap-6 flex-wrap">
<div className="min-w-0 flex-1">
<div className="text-xs uppercase tracking-wider text-muted-foreground">
Vehicle inspection report
</div>
<h1 className="mt-1 text-2xl sm:text-3xl font-bold tracking-tight">{data.title ?? "Inspection"}</h1>
{data.order_number && (
<div className="text-sm text-muted-foreground font-mono mt-1">#{data.order_number}</div>
)}
<div className={`mt-4 inline-flex items-center gap-2 rounded-full ${headlineStatus.bg} px-4 py-1.5`}>
<headlineStatus.Icon className={`size-4 ${headlineStatus.color}`} />
<span className={`text-sm font-medium ${headlineStatus.color}`}>
{headlineStatus.label}
</span>
</div>
</div>
<ScoreRing score={data.score} />
</div>
</div>
<div className="border-t bg-gray-50/60 px-6 sm:px-8 py-4">
<div className="info-grid grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm">
<InfoCell icon={User} label="Customer" value={data.customer?.name ?? "—"} />
<InfoCell icon={Car} label="Vehicle" value={vehicleLine} subtitle={data.vehicle?.license_plate ?? undefined} />
<InfoCell icon={Calendar} label="Inspected" value={data.date ?? "—"} subtitle={data.time ?? undefined} />
<InfoCell icon={Gauge} label="Odometer" value={data.odometer != null ? `${Number(data.odometer).toLocaleString()} km` : "—"} />
</div>
</div>
</div>
{/* Severity summary */}
<div className="totals-grid grid grid-cols-2 sm:grid-cols-5 gap-2 pb-avoid">
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
<div
key={s}
className={`rounded-xl border px-3 py-3 text-center ${SEVERITY_PILL[s]}`}
>
<div className="text-xl font-bold leading-none tabular-nums">{data.totals[s]}</div>
<div className="text-[11px] font-medium mt-1.5">{SEVERITY_LABEL[s]}</div>
</div>
))}
</div>
{/* Sections */}
{data.sections.length === 0 ? (
<div className="rounded-2xl bg-white border p-8 text-center text-sm text-muted-foreground">
This inspection has no recorded checkpoints yet.
</div>
) : (
data.sections.map((section) => (
<section key={section.name} className="rounded-2xl bg-white shadow-sm border overflow-hidden">
<header className="px-5 sm:px-6 py-3 border-b flex items-center justify-between bg-gray-50/60">
<h2 className="font-semibold text-sm sm:text-base">{section.name}</h2>
<span className="text-xs text-muted-foreground">
{section.items.length} {section.items.length === 1 ? "item" : "items"}
</span>
</header>
<ul className="divide-y">
{section.items.map((cp, i) => (
<li
key={i}
className={`cp-row pb-avoid px-5 sm:px-6 py-4 border-l-4 ${SEVERITY_BORDER[cp.severity]}`}
>
{/* Head: dot + name + severity pill (pill stays inline next to name) */}
<div className="cp-head flex items-center gap-2">
<span className={`size-2 rounded-full ${SEVERITY_DOT_BG[cp.severity]} shrink-0`} />
<span className="font-medium text-sm flex-1 min-w-0 truncate">{cp.name}</span>
<span className={`cp-pill inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium shrink-0 ${SEVERITY_PILL[cp.severity]}`}>
{SEVERITY_LABEL[cp.severity]}
</span>
</div>
<div className="cp-body ms-4">
{cp.description && (
<p className="text-xs text-muted-foreground mt-1">{cp.description}</p>
)}
{cp.technician_notes && (
<p className="mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-foreground/80 italic border-l-2 border-muted-foreground/30">
"{cp.technician_notes}"
</p>
)}
{cp.condition_rate != null && (
<div className="mt-2">
<div className="h-1.5 bg-muted rounded-full overflow-hidden">
<div
className={`h-full transition-all ${cp.severity === "critical" ? "bg-rose-500" : cp.severity === "attention" ? "bg-amber-500" : "bg-emerald-500"}`}
style={{ width: `${cp.condition_rate}%` }}
/>
</div>
<div className="text-[11px] text-muted-foreground mt-0.5 tabular-nums">{cp.condition_rate}%</div>
</div>
)}
{cp.photos && cp.photos.length > 0 && (
<div className="photo-grid mt-3 grid grid-cols-3 sm:grid-cols-4 gap-2">
{cp.photos.map((p) => (
p.url ? (
<button
type="button"
key={p.id}
onClick={() => setLightbox(p)}
className="group relative rounded-lg overflow-hidden border bg-muted aspect-square focus:outline-none focus:ring-2 focus:ring-primary/40"
aria-label="View photo"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={p.url}
alt={p.caption ?? ""}
className="block w-full h-full object-cover transition group-hover:scale-105"
/>
</button>
) : null
))}
</div>
)}
</div>
</li>
))}
</ul>
</section>
))
)}
{(data.note || data.description) && (
<section className="rounded-2xl bg-white shadow-sm border p-5 sm:p-6">
<h2 className="font-semibold text-sm mb-3 flex items-center gap-2">
<ChevronRight className="size-4 text-muted-foreground" />
Additional notes from your technician
</h2>
{data.note && <p className="text-sm leading-relaxed">{data.note}</p>}
{data.description && (
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">{data.description}</p>
)}
</section>
)}
{/* Technician footer */}
{data.technician?.name && (
<div className="rounded-2xl bg-white shadow-sm border px-5 sm:px-6 py-4 flex items-center justify-between gap-3 flex-wrap">
<div className="flex items-center gap-3">
<div className="size-10 rounded-full bg-gradient-to-br from-blue-500 to-blue-600 text-white flex items-center justify-center font-semibold text-sm">
{data.technician.name
.split(" ")
.map((p) => p[0])
.filter(Boolean)
.slice(0, 2)
.join("")}
</div>
<div>
<div className="text-xs text-muted-foreground">Inspected by</div>
<div className="font-medium text-sm">{data.technician.name}</div>
</div>
</div>
{data.department && (
<span className="text-xs text-muted-foreground">{data.department}</span>
)}
{data.template && (
<span className="text-xs rounded-full border px-3 py-1 bg-muted/30">
{data.template}
</span>
)}
</div>
)}
<footer className="text-center text-xs text-muted-foreground py-6 no-print">
{data.share_expires_at && (
<div>Link valid until {new Date(data.share_expires_at).toLocaleDateString()}</div>
)}
</footer>
</div>
{/* Lightbox */}
{lightbox && lightbox.url && (
<div
className="no-print fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
onClick={() => setLightbox(null)}
role="dialog"
aria-modal
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={lightbox.url}
alt={lightbox.caption ?? ""}
className="max-w-full max-h-[88vh] object-contain shadow-2xl"
onClick={(e) => e.stopPropagation()}
/>
<button
type="button"
onClick={() => setLightbox(null)}
className="absolute top-4 right-4 rounded-full bg-white/10 hover:bg-white/20 text-white size-9 inline-flex items-center justify-center"
aria-label="Close"
>
×
</button>
{lightbox.caption && (
<div className="absolute bottom-4 inset-x-0 text-center text-white/90 text-sm px-4">
{lightbox.caption}
</div>
)}
</div>
)}
</div>
)
}
function InfoCell({
icon: Icon,
label,
value,
subtitle,
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value: string
subtitle?: string
}) {
return (
<div className="flex items-start gap-2 min-w-0">
<Icon className="size-4 mt-0.5 text-muted-foreground shrink-0" />
<div className="min-w-0">
<div className="text-[11px] uppercase tracking-wide text-muted-foreground">{label}</div>
<div className="font-medium truncate">{value}</div>
{subtitle && (
<div className="text-xs text-muted-foreground font-mono truncate">{subtitle}</div>
)}
</div>
</div>
)
}

View File

@ -1,10 +1,12 @@
import { Geist_Mono, Inter } from "next/font/google"
import NextTopLoader from "nextjs-toploader"
import { QueryProvider } from "@/shared/components/query-provider"
import { ThemeProvider } from "@/shared/components/theme-provider"
import { Toaster } from "@/shared/components/ui/sonner"
import { ConfirmDialog } from "@/shared/components/confirm-dialog"
import { PromptDialog } from "@/shared/components/prompt-dialog"
import { NuqsAdapter } from "nuqs/adapters/next/app"
import { cn } from "@/shared/lib/utils"
import './globals.css'
@ -33,11 +35,13 @@ export default function RootLayout({
className={cn("antialiased", fontMono.variable, "font-sans", inter.variable)}
>
<body>
<NextTopLoader color="var(--primary)" height={3} showSpinner={false} />
<NuqsAdapter>
<ThemeProvider>
<QueryProvider>{children}</QueryProvider>
<Toaster />
<ConfirmDialog />
<PromptDialog />
</ThemeProvider>
</NuqsAdapter>
</body>

View File

@ -141,9 +141,20 @@ export function AppSidebar({ navGroups, logo, user, ...props }: AppSidebarProps)
)
}
function isPathActive(pathname: string, href: string): boolean {
if (href === '/') return pathname === '/'
return pathname === href || pathname.startsWith(href + '/')
}
function isItemActive(pathname: string, item: { href: string; matchPath?: string; isActive?: boolean }): boolean {
if (item.isActive !== undefined) return item.isActive
if (item.matchPath) return isPathActive(pathname, item.matchPath)
return isPathActive(pathname, item.href)
}
function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
const pathname = usePathname()
const isActive = item.isActive ?? pathname === item.href
const isActive = isItemActive(pathname, item)
return (
<SidebarMenuItem>
@ -169,8 +180,8 @@ function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: bool
function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
const pathname = usePathname()
const isChildActive = item.items?.some((sub) => pathname === sub.href)
const isActive = item.isActive ?? (pathname === item.href || isChildActive === true)
const isChildActive = item.items?.some((sub) => isItemActive(pathname, sub))
const isActive = item.isActive ?? (isItemActive(pathname, item) || isChildActive === true)
// Collapsed sidebar → flyout dropdown with sub-items
if (isCollapsed) {
@ -210,7 +221,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
</DropdownMenuLabel>
<DropdownMenuSeparator />
{item.items?.map((sub) => {
const isSubActive = sub.isActive ?? pathname === sub.href
const isSubActive = isItemActive(pathname, sub)
return (
<DropdownMenuItem key={sub.href} asChild>
<Link
@ -272,7 +283,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
<CollapsibleContent className="overflow-hidden py-2 data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up">
<SidebarMenuSub>
{item.items?.map((sub) => {
const isSubActive = sub.isActive ?? pathname === sub.href
const isSubActive = isItemActive(pathname, sub)
return (
<SidebarMenuSubItem key={sub.href}>
<SidebarMenuSubButton asChild isActive={isSubActive} className="dashboard-nav-sub-item my-0.5">

View File

@ -68,14 +68,22 @@ export default function DashboardDetailsPageLayout({
</Button>
)}
{(avatarSrc || avatarFallback) && (
<a rel="preload" target="_blank" href={avatarSrc} >
<Avatar className="size-14">
{avatarSrc && <AvatarImage src={avatarSrc} alt={title} />}
<AvatarFallback>
{avatarFallback ?? title.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
</a>
avatarSrc ? (
<a target="_blank" rel="noopener noreferrer" href={avatarSrc}>
<Avatar className="size-14">
<AvatarImage src={avatarSrc} alt={title} />
<AvatarFallback>
{avatarFallback ?? title.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
</a>
) : (
<Avatar className="size-14">
<AvatarFallback>
{avatarFallback ?? title.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
)
)}
{!avatarSrc && !avatarFallback && icon && (
<div className="flex items-center justify-center size-10 rounded-full bg-muted text-muted-foreground">
@ -109,6 +117,7 @@ export default function DashboardDetailsPageLayout({
<Link
key={tab.href}
href={tab.href}
prefetch
className={cn(
"relative inline-flex items-center justify-center px-3 py-2 text-sm font-medium whitespace-nowrap transition-colors",
"text-muted-foreground hover:text-foreground",

View File

@ -6,6 +6,12 @@ export type NavItem = {
href: string
icon?: ReactNode
isActive?: boolean
/**
* Optional prefix used to decide active state when the link target
* differs from the page's URL pattern (e.g. `/calendar/appointment/list`
* is the link, but the item should stay active on `/calendar/appointment/{id}`).
*/
matchPath?: string
badge?: string | number
items?: NavSubItem[]
}
@ -15,6 +21,7 @@ export type NavSubItem = {
href: string
icon?: ReactNode
isActive?: boolean
matchPath?: string
}
export type NavGroup = {

View File

@ -76,7 +76,7 @@ export const navGroups: NavGroup[] = [
icon: <CalendarIcon />,
items: [
// { title: "Work Schedule", href: "/calendar/work-schedule/list", icon: <Clock3Icon /> },
{ title: "Appointments", href: "/calendar/appointment/list", icon: <CalendarCheck2Icon /> },
{ title: "Appointments", href: "/calendar/appointment/list", matchPath: "/calendar/appointment", icon: <CalendarCheck2Icon /> },
],
},
{
@ -176,7 +176,8 @@ export const navGroups: NavGroup[] = [
{ title: "Insurance Types", href: "/settings/insurance-types", icon: <ShieldIcon /> },
{ title: "Tax & Rates", href: "/settings/tax-rates", icon: <ReceiptTextIcon /> },
{ title: "Make & Models", href: "/settings/make-and-models", icon: <CarIcon /> },
{ title: "Configurations", href: "/settings/configurations/preferences/sales", icon: <SettingsIcon /> },
{ title: "Inspection Templates", href: "/settings/inspection-templates", icon: <ClipboardListIcon /> },
{ title: "Configurations", href: "/settings/configurations/preferences/sales", matchPath: "/settings/configurations", icon: <SettingsIcon /> },
// { title: "Templates", href: "/settings/templates", icon: <ClipboardListIcon /> },
// { title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> },
// { title: "Master", href: "/settings/master/body-type", icon: <ListIcon /> },

View File

@ -11,9 +11,11 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { Ellipsis, Pencil, Trash2, Share2 } from "lucide-react"
import { useState } from "react"
import { useFormDialog } from "@/shared/components/form-dialog"
import { BillForm } from "./bill-form"
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"
type BillActionsProps = {
billId: string
@ -23,6 +25,7 @@ export function BillActions({ billId }: BillActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("bill-details-edit")
const [shareOpen, setShareOpen] = useState(false)
const handleDelete = async () => {
await api.bills.destroy(billId)
@ -42,6 +45,10 @@ export function BillActions({ billId }: BillActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-4" />
Share
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
@ -49,6 +56,8 @@ export function BillActions({ billId }: BillActionsProps) {
</DropdownMenuContent>
</DropdownMenu>
<ShareDocumentDialog type="bill" id={billId} open={shareOpen} onOpenChange={setShareOpen} />
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
<DialogContent className="min-w-xl lg:min-w-4xl">
<DialogHeader>

View File

@ -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>

View File

@ -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,

View File

@ -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>

View File

@ -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>
)
},

View File

@ -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>

View File

@ -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>

View File

@ -1,7 +1,7 @@
"use client"
import { useState } from "react"
import { ClipboardList } from "lucide-react"
import { ClipboardList, Loader2 } from "lucide-react"
import { useRouter } from "next/navigation"
import { ApiError } from "@garage/api"
import { Button } from "@/shared/components/ui/button"
@ -30,34 +30,37 @@ export function CreateJobCardFromEstimateButton() {
if (!confirmed) return
setIsConverting(true)
const promise = api.estimates.convertToJobCard(estimateId, {})
toast.promise(promise, {
loading: "Generating job card...",
success: "Estimate converted to job card successfully",
error: (error: unknown) =>
error instanceof ApiError && error.status === 409
? "A job card already exists for this estimate."
: "Failed to convert estimate to job card",
})
try {
const response = await api.estimates.convertToJobCard(estimateId, {})
const response = await promise
const jobCardId = response?.data?.id
toast.success("Estimate converted to job card successfully")
if (jobCardId) {
router.push(`/sales/job-cards/${jobCardId}`)
return
}
} catch (error) {
if (error instanceof ApiError && error.status === 409) {
const jobCardId = (error.payload?.data as { job_card_id?: number } | undefined)?.job_card_id
toast.info("A job card already exists for this estimate.")
if (jobCardId) {
router.push(`/sales/job-cards/${jobCardId}`)
return
}
}
toast.error("Failed to convert estimate to job card")
} finally {
setIsConverting(false)
}
setIsConverting(false)
}
return (
<Button variant="outline" size="sm" onClick={handleConvert} disabled={isConverting}>
<ClipboardList className="me-2 size-4" />
{isConverting ? <Loader2 className="me-2 size-4 animate-spin" /> : <ClipboardList className="me-2 size-4" />}
{isConverting ? "Generating..." : "Generate Job Card"}
</Button>
)

View File

@ -24,7 +24,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/shared/components/ui/select"
import { Ellipsis, Pencil, Trash2, ShieldCheck, Check, X, Printer } from "lucide-react"
import { Ellipsis, Pencil, Trash2, ShieldCheck, Check, X, Printer, Share2 } from "lucide-react"
import { useState } from "react"
import { useMutation, useQuery } from "@tanstack/react-query"
import { toast } from "sonner"
@ -34,6 +34,7 @@ import { DatePickerField, TimePickerField } from "@/shared/components/form"
import { cn } from "@/shared/lib/utils"
import { EmployeeCombobox, type EmployeeOption } from "../employees/employee-combobox"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"
type EstimateActionsProps = {
estimateId: string
@ -135,6 +136,7 @@ export function EstimateActions({ estimateId }: EstimateActionsProps) {
const { print, isPrinting } = useDocumentPrint()
const [editOpen, setEditOpen] = useState(false)
const [authOpen, setAuthOpen] = useState(false)
const [shareOpen, setShareOpen] = useState(false)
const [itemStatuses, setItemStatuses] = useState<Record<string, string>>({})
const [authMethod, setAuthMethod] = useState("in_person")
const [employee, setEmployee] = useState<EmployeeOption | null>(null)
@ -224,6 +226,10 @@ export function EstimateActions({ estimateId }: EstimateActionsProps) {
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-4" />
Share
</DropdownMenuItem>
<DropdownMenuItem onClick={openAuthDialog}>
<ShieldCheck className="size-4" />
Store Authorisation
@ -235,6 +241,8 @@ export function EstimateActions({ estimateId }: EstimateActionsProps) {
</DropdownMenuContent>
</DropdownMenu>
<ShareDocumentDialog type="estimate" id={estimateId} open={shareOpen} onOpenChange={setShareOpen} />
{/* Edit Dialog */}
<Dialog open={editOpen} onOpenChange={setEditOpen}>
<DialogContent className="min-w-xl">

View File

@ -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,

View File

@ -63,24 +63,48 @@ const DEFAULT_VALUES: EstimateFormValues = {
// ── Mapping helpers ──
function customerLabel(c: any): string | undefined {
if (!c) return undefined
const name = [c.first_name, c.last_name].filter(Boolean).join(" ").trim()
return c.company_name || name || undefined
}
function vehicleLabel(v: any): string | undefined {
if (!v) return undefined
const core = [v.make, v.model, v.sub_model].filter(Boolean).join(" ")
const suffix = [v.year, v.license_plate].filter(Boolean).join(" - ")
if (core && suffix) return `${core} (${suffix})`
return core || suffix || undefined
}
function mapToFormValues(data: unknown): EstimateFormValues {
const d = (data as any)?.data ?? data ?? {}
return {
title: d.title || "",
customer: toRelation(d.customer_id, d.customer_name),
vehicle: toRelation(d.vehicle_id, d.vehicle_name),
department: toRelation(d.department_id, d.department_name),
insurance_type: toRelation(d.insurance_type_id, d.insurance_type_title ?? d.insurance_type_name ?? d.insurance_type?.title),
customer: toRelation(
d.customer_id ?? d.customer?.id,
d.customer_name ?? customerLabel(d.customer),
),
vehicle: toRelation(
d.vehicle_id ?? d.vehicle?.id,
d.vehicle_name ?? vehicleLabel(d.vehicle),
),
department: toRelation(
d.department_id ?? d.department?.id,
d.department_name ?? d.department?.name ?? d.department?.title,
),
insurance_type: toRelation(
d.insurance_type_id ?? d.insurance_type?.id,
d.insurance_type_title ?? d.insurance_type_name ?? d.insurance_type?.title ?? d.insurance_type?.name,
),
insurer: toRelation(
d.insurer_id,
d.insurer_name
?? [d.insurer?.first_name, d.insurer?.last_name].filter(Boolean).join(" ")
?? d.insurer?.company_name,
d.insurer_id ?? d.insurer?.id,
d.insurer_name ?? customerLabel(d.insurer),
),
service_writer: toRelation(
d.service_writer_id,
d.service_writer_name ?? [d.service_writer?.first_name, d.service_writer?.last_name].filter(Boolean).join(" "),
d.service_writer_id ?? d.service_writer?.id,
d.service_writer_name ?? customerLabel(d.service_writer),
),
estimate_number: d.estimate_number || "",
date: d.date ? d.date.split("T")[0] : "",
@ -140,12 +164,13 @@ const DISCOUNT_OPTIONS = DiscountType.map((value) => ({
export function EstimateForm({ resourceId, initialData, onSuccess }: EstimateFormProps) {
const api = useAuthApi()
const { form, isEditing } = useResourceForm<EstimateFormValues, any>({
const { form, isEditing, invalidate } = useResourceForm<EstimateFormValues, any>({
schema: estimateFormSchema,
defaultValues: DEFAULT_VALUES,
resourceId,
initialData,
queryKey: [ESTIMATE_ROUTES.BY_ID, resourceId],
initialize: (id) => api.estimates.show(id),
mapToFormValues,
})
@ -163,7 +188,7 @@ export function EstimateForm({ resourceId, initialData, onSuccess }: EstimateFor
return promise
},
onSuccess: () => {
form.reset()
if (!isEditing) form.reset()
onSuccess?.()
},
})

View File

@ -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,

View File

@ -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,

View File

@ -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>

View File

@ -27,9 +27,9 @@ import {
INVENTORY_CATEGORY_ROUTES,
INVENTORY_ROUTES,
DEPARTMENT_ROUTES,
VENDOR_ROUTES,
} from "@garage/api"
import { InventoryCategoryCrudDialog } from "./inventory-category-crud-dialog"
import { RhfVendorSelectField } from "@/modules/vendors/rhf-vendor-select-field"
// ── Constants ──
@ -84,15 +84,26 @@ function mapToFormValues(data: unknown): ExpenseItemFormValues {
sku: d.sku || "",
item_code: d.item_code || "",
description: d.description || "",
category: toRelation(d.category_id, d.category_title ?? d.category_name),
unit_type: toRelation(d.unit_type_id, d.unit_type_title ?? d.unit_type_name),
department: toRelation(d.department_id, d.department_name ?? d.department_title),
category: toRelation(
d.category_id ?? d.category?.id,
d.category_title ?? d.category_name ?? d.category?.title ?? d.category?.name,
),
unit_type: toRelation(
d.unit_type_id ?? d.unit_type?.id,
d.unit_type_title ?? d.unit_type_name ?? d.unit_type?.title ?? d.unit_type?.name,
),
department: toRelation(
d.department_id ?? d.department?.id,
d.department_name ?? d.department_title ?? d.department?.name ?? d.department?.title,
),
purchase_information: d.purchase_information ?? true,
purchase_price: d.purchase_price ?? undefined,
purchase_chart_of_account: d.purchase_chart_of_account || "",
purchase_preferred_vendor: toRelation(
d.purchase_preferred_vendor_id,
d.purchase_preferred_vendor_name,
d.purchase_preferred_vendor_id ?? d.purchase_preferred_vendor?.id,
d.purchase_preferred_vendor_name
?? d.purchase_preferred_vendor?.company_name
?? [d.purchase_preferred_vendor?.first_name, d.purchase_preferred_vendor?.last_name].filter(Boolean).join(" "),
),
sales_information: d.sales_information ?? false,
selling_price: d.selling_price ?? undefined,
@ -127,7 +138,7 @@ function mapFormToPayload(values: ExpenseItemFormValues) {
export function ExpenseItemForm({ resourceId, initialData, onSuccess }: ExpenseItemFormProps) {
const api = useAuthApi()
const { form, isEditing } = useResourceForm<ExpenseItemFormValues, any>({
const { form, isEditing, invalidate } = useResourceForm<ExpenseItemFormValues, any>({
schema: expenseItemFormSchema,
defaultValues: DEFAULT_VALUES,
resourceId,
@ -150,7 +161,7 @@ export function ExpenseItemForm({ resourceId, initialData, onSuccess }: ExpenseI
return promise
},
onSuccess: () => {
form.reset()
if (!isEditing) form.reset()
onSuccess?.()
},
})
@ -247,7 +258,7 @@ export function ExpenseItemForm({ resourceId, initialData, onSuccess }: ExpenseI
</div>
{/* Purchase Information */}
{/* <RhfCheckboxField
<RhfCheckboxField
name="purchase_information"
label="Purchase Information"
/>
@ -259,22 +270,21 @@ export function ExpenseItemForm({ resourceId, initialData, onSuccess }: ExpenseI
placeholder="0.00"
type="number"
/>
{/* TODO(phase-2): wire Purchase Chart of Account to the chart-of-accounts module (currently disabled, marked "Coming soon"). */}
<RhfTextField
name="purchase_chart_of_account"
label="Purchase Chart of Account"
placeholder="e.g. Expenses"
description="Coming soon"
disabled
/>
</div>
<RhfAsyncSelectField
<RhfVendorSelectField
name="purchase_preferred_vendor"
label="Preferred Vendor"
placeholder="Select vendor"
queryKey={[VENDOR_ROUTES.INDEX]}
listFn={() => api.vendors.list()}
mapOption={(item: any) => ({ value: String(item.id), label: item.name ?? String(item.id) })}
{...STORE_OBJECT}
/> */}
/>
{/* Sales Information */}
{/* <RhfCheckboxField

View File

@ -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,

View File

@ -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>

View File

@ -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>

View File

@ -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>
)
}

View File

@ -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>
)
}

View File

@ -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")
}
}

View File

@ -12,11 +12,13 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2, Play, CheckCircle2, Printer } from "lucide-react"
import { Ellipsis, Pencil, Trash2, Play, CheckCircle2, Printer, Share2 } from "lucide-react"
import { useState } from "react"
import { toast } from "sonner"
import { useFormDialog } from "@/shared/components/form-dialog"
import { InspectionForm } from "./inspection-form"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"
type InspectionActionsProps = {
inspectionId: string
@ -34,6 +36,7 @@ export function InspectionActions({ inspectionId, status, onStatusChange }: Insp
const router = useRouter()
const editDialog = useFormDialog("inspection-details-edit")
const { print, isPrinting } = useDocumentPrint()
const [shareOpen, setShareOpen] = useState(false)
const handleDelete = async () => {
const promise = api.inspections.destroy(inspectionId)
@ -79,6 +82,10 @@ export function InspectionActions({ inspectionId, status, onStatusChange }: Insp
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-4" />
Share
</DropdownMenuItem>
{transition && (
<DropdownMenuItem onClick={() => handleStatusChange(transition.next)}>
<transition.icon className="size-4" />
@ -93,6 +100,8 @@ export function InspectionActions({ inspectionId, status, onStatusChange }: Insp
</DropdownMenuContent>
</DropdownMenu>
<ShareDocumentDialog type="inspection" id={inspectionId} open={shareOpen} onOpenChange={setShareOpen} />
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
<DialogContent className="min-w-xl lg:min-w-4xl">
<DialogHeader>

View File

@ -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>
)
}

View File

@ -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">

View File

@ -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>
)
}

View File

@ -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>
)
}

View File

@ -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>
)
}

View File

@ -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(),
})

View File

@ -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>
)
}

View File

@ -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 (0100)" },
{ 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>
)
}

View File

@ -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`}

View File

@ -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"),

View File

@ -1,5 +1,6 @@
"use client"
import { useState } from "react"
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
@ -9,8 +10,9 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Printer, Trash2 } from "lucide-react"
import { Ellipsis, Printer, Share2, Trash2 } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"
type InvoiceActionsProps = {
invoiceId: string
@ -20,6 +22,7 @@ export function InvoiceActions({ invoiceId }: InvoiceActionsProps) {
const api = useAuthApi()
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
const [shareOpen, setShareOpen] = useState(false)
const handleDelete = async () => {
await api.invoices.destroy(invoiceId)
@ -39,12 +42,18 @@ export function InvoiceActions({ invoiceId }: InvoiceActionsProps) {
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-4" />
Share
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<ShareDocumentDialog type="invoice" id={invoiceId} open={shareOpen} onOpenChange={setShareOpen} />
</>
)
}

View File

@ -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>

View File

@ -251,12 +251,13 @@ function TransactionDiscountField() {
export function InvoiceForm({ resourceId, initialData, onSuccess }: InvoiceFormProps) {
const api = useAuthApi()
const { form, isEditing } = useResourceForm<InvoiceFormValues, any>({
const { form, isEditing, invalidate } = useResourceForm<InvoiceFormValues, any>({
schema: invoiceFormSchema,
defaultValues: DEFAULT_VALUES,
resourceId,
initialData,
queryKey: [INVOICE_ROUTES.BY_ID, resourceId],
initialize: (id) => api.invoices.show(id),
mapToFormValues,
})
@ -277,7 +278,7 @@ export function InvoiceForm({ resourceId, initialData, onSuccess }: InvoiceFormP
return promise
},
onSuccess: () => {
form.reset()
if (!isEditing) form.reset()
onSuccess?.()
},
})

View File

@ -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>

View File

@ -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>

View File

@ -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>

Some files were not shown because too many files have changed in this diff Show More