Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4bfd8c84a9 | ||
|
|
54d11f01b4 | ||
|
|
fcbba6247d | ||
|
|
05b55b5721 | ||
|
|
6b356d2855 | ||
|
|
cc7dc1bd17 | ||
|
|
349a458c3c | ||
|
|
25c3125894 | ||
|
|
4b51ffe457 | ||
|
|
b0361fcbfb | ||
|
|
38565298fc | ||
|
|
dd32658500 | ||
|
|
c7eb23dd3f | ||
|
|
4faafe6667 | ||
|
|
1fda8d8d7b | ||
|
|
cdd1cbc31a |
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(pnpm --version)",
|
||||
"Bash(grep -E \"\\\\.\\(tsx?|jsx?\\)$\")",
|
||||
"Bash(grep -E \"\\\\.\\(tsx?\\)$\")"
|
||||
]
|
||||
},
|
||||
"enabledMcpjsonServers": [
|
||||
"code-review-graph"
|
||||
],
|
||||
"enableAllProjectMcpServers": true
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
NIXPACKS_NODE_VERSION=22
|
||||
NEXT_PUBLIC_API_URL=http://reparee.test
|
||||
@@ -74,6 +74,7 @@ Create `apps/dashboard/modules/<feature>/<feature>-form.tsx`:
|
||||
5. Use `useFormMutation()` for submit with automatic validation error mapping
|
||||
6. Render with `Rhform` + `RhfTextField` / `RhfSelectField` / `RhfAsyncSelectField` etc.
|
||||
7. Include error alert, submit button with loading/edit states
|
||||
8. For every required schema/backend field, pass `required` to the rendered form field component so required UI indicators and consistency are preserved
|
||||
|
||||
### Step 5: Create Page Component
|
||||
|
||||
@@ -181,6 +182,19 @@ const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) =
|
||||
| `RhfDateField` | Date picker — see date-time-pickers skill |
|
||||
| `RhfTimeField` | Time picker — see date-time-pickers skill |
|
||||
|
||||
### Required Prop Rule (Important)
|
||||
|
||||
When a field is required by schema or backend validation, always pass the `required` prop on the matching form component.
|
||||
|
||||
- Applies to all controls that support it, including custom selectors (for example `RhfCustomerSelectField`, `RhfVehicleSelectField`) and standard fields (`RhfTextField`, `RhfSelectField`, etc.)
|
||||
- Do not rely on schema-only required validation; keep UI required indicator (`*`) in sync with validation requirements
|
||||
|
||||
```tsx
|
||||
<RhfTextField name="title" label="Title" required />
|
||||
<RhfCustomerSelectField name="customer" required />
|
||||
<RhfVehicleSelectField name="vehicle" required customer_id={customer?.value} />
|
||||
```
|
||||
|
||||
### Imports Cheat Sheet
|
||||
|
||||
```tsx
|
||||
|
||||
@@ -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)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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: (
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { DashboardHeader } from "@/base/components/layout/dashboard";
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page";
|
||||
import { DashboardContent } from "@/modules/home/dashboard-content";
|
||||
import { DashboardFiltersToolbar } from "@/modules/home/dashboard-filters-toolbar";
|
||||
|
||||
export default function page() {
|
||||
return (
|
||||
<DashboardPage headerProps={{title: "Dashboard"}} >
|
||||
<DashboardPage headerProps={{ title: "Dashboard", actions: <DashboardFiltersToolbar /> }} >
|
||||
<DashboardContent />
|
||||
</DashboardPage>
|
||||
)
|
||||
|
||||
@@ -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 }) => ({
|
||||
|
||||
@@ -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: (
|
||||
|
||||
@@ -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: (
|
||||
|
||||
@@ -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: (
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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>
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -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>
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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} />
|
||||
}
|
||||
+42
-1
@@ -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.")
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -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 }) => ({
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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>
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,589 +1,458 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState, useRef, useCallback } from "react"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useParams } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
Plus,
|
||||
Ellipsis,
|
||||
Pencil,
|
||||
Trash2,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
XCircle,
|
||||
MinusCircle,
|
||||
CircleDot,
|
||||
Paperclip,
|
||||
FileUp,
|
||||
FileText,
|
||||
FileImage,
|
||||
File,
|
||||
X,
|
||||
Car,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
CircleCheck,
|
||||
FileSignature,
|
||||
Gauge,
|
||||
Image as ImageIcon,
|
||||
Loader2,
|
||||
Share2,
|
||||
StickyNote,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
import { INSPECTION_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Types ──
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Progress } from "@/shared/components/ui/progress"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import {
|
||||
CheckpointFillDialog,
|
||||
isCheckpointComplete,
|
||||
type Checkpoint,
|
||||
type Severity,
|
||||
} from "@/modules/inspections/checkpoint-fill-dialog"
|
||||
import { SignaturePad } from "@/modules/inspections/signature-pad"
|
||||
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
|
||||
|
||||
type CheckpointItem = {
|
||||
type Inspection = {
|
||||
id: number
|
||||
inspection_id?: number
|
||||
name?: string
|
||||
description?: string
|
||||
record_type?: string
|
||||
condition_rate?: number
|
||||
file?: string
|
||||
status?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
title: string
|
||||
order_number?: string | null
|
||||
status?: string | null
|
||||
odometer?: number | null
|
||||
template?: { id: number; name: string } | null
|
||||
customer?: { first_name?: string; last_name?: string } | null
|
||||
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string } | null
|
||||
check_points: Checkpoint[]
|
||||
technician_signature_url?: string | null
|
||||
customer_signature_url?: string | null
|
||||
}
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
const CHECKPOINT_STATUSES = [
|
||||
{ value: "passed", label: "Passed", icon: CheckCircle2, color: "bg-green-100 text-green-800" },
|
||||
{ value: "need_attention", label: "Need Attention", icon: AlertTriangle, color: "bg-yellow-100 text-yellow-800" },
|
||||
{ value: "failed", label: "Failed", icon: XCircle, color: "bg-red-100 text-red-800" },
|
||||
{ value: "not_applicable", label: "Not Applicable", icon: MinusCircle, color: "bg-gray-100 text-gray-800" },
|
||||
{ value: "not_inspected", label: "Not Inspected", icon: CircleDot, color: "bg-blue-100 text-blue-800" },
|
||||
] as const
|
||||
|
||||
const RECORD_TYPES = [
|
||||
{ value: "record_conditions", label: "Record Conditions" },
|
||||
{ value: "record_audio", label: "Record Audio" },
|
||||
{ value: "record_video", label: "Record Video" },
|
||||
{ value: "capture_photo", label: "Capture Photo" },
|
||||
] as const
|
||||
|
||||
function formatStatus(status?: string) {
|
||||
if (!status) return "Not Inspected"
|
||||
return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
|
||||
const SEVERITY_DOT: Record<Severity, string> = {
|
||||
good: "bg-emerald-500 shadow-emerald-500/30",
|
||||
attention: "bg-amber-500 shadow-amber-500/30",
|
||||
critical: "bg-rose-500 shadow-rose-500/30",
|
||||
na: "bg-slate-400 shadow-slate-400/30",
|
||||
not_inspected: "bg-muted shadow-none",
|
||||
}
|
||||
const SEVERITY_LABEL: Record<Severity, string> = {
|
||||
good: "Good",
|
||||
attention: "Attention",
|
||||
critical: "Critical",
|
||||
na: "N/A",
|
||||
not_inspected: "Not inspected",
|
||||
}
|
||||
const SEVERITY_BADGE: Record<Severity, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
good: "default",
|
||||
attention: "secondary",
|
||||
critical: "destructive",
|
||||
na: "outline",
|
||||
not_inspected: "outline",
|
||||
}
|
||||
|
||||
function getStatusConfig(status?: string) {
|
||||
return CHECKPOINT_STATUSES.find((s) => s.value === status) || CHECKPOINT_STATUSES[4]
|
||||
function groupBySection(cps: Checkpoint[]) {
|
||||
const map = new Map<string, Checkpoint[]>()
|
||||
for (const cp of cps) {
|
||||
const key = cp.section_name || "Other"
|
||||
if (!map.has(key)) map.set(key, [])
|
||||
map.get(key)!.push(cp)
|
||||
}
|
||||
return Array.from(map.entries()).map(([name, items]) => ({ name, items }))
|
||||
}
|
||||
|
||||
// ── Checkpoint Form Dialog ──
|
||||
|
||||
function CheckpointFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
inspectionId,
|
||||
checkpoint,
|
||||
onSuccess,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
inspectionId: string
|
||||
checkpoint?: CheckpointItem | null
|
||||
onSuccess: () => void
|
||||
}) {
|
||||
export default function InspectionCheckpointsPage() {
|
||||
const params = useParams<{ id: string }>()
|
||||
const id = params.id
|
||||
const api = useAuthApi()
|
||||
const [name, setName] = useState(checkpoint?.name ?? "")
|
||||
const [description, setDescription] = useState(checkpoint?.description ?? "")
|
||||
const [recordType, setRecordType] = useState(checkpoint?.record_type ?? "record_conditions")
|
||||
const [isPending, setIsPending] = useState(false)
|
||||
|
||||
const isEditing = !!checkpoint
|
||||
const [data, setData] = useState<Inspection | null>(null)
|
||||
const [initialLoad, setInitialLoad] = useState(true)
|
||||
const [refetching, setRefetching] = useState(false)
|
||||
const [activeIndex, setActiveIndex] = useState<number | null>(null)
|
||||
const [shareOpen, setShareOpen] = useState(false)
|
||||
const [mode, setMode] = useState<"all" | "wizard">("all")
|
||||
const [wizardSectionIdx, setWizardSectionIdx] = useState(0)
|
||||
const [signing, setSigning] = useState<{ who: "technician" | "customer" } | null>(null)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!name.trim()) {
|
||||
toast.error("Name is required")
|
||||
return
|
||||
}
|
||||
setIsPending(true)
|
||||
const load = useCallback(async () => {
|
||||
const isFirst = !data
|
||||
if (isFirst) setInitialLoad(true)
|
||||
else setRefetching(true)
|
||||
try {
|
||||
const payload = {
|
||||
inspection_id: Number(inspectionId),
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
record_type: recordType,
|
||||
const res = await api.inspections.showOne(id)
|
||||
setData(res.data as Inspection)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to load inspection")
|
||||
} finally {
|
||||
setInitialLoad(false)
|
||||
setRefetching(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id])
|
||||
|
||||
const patchCheckpoint = useCallback((checkpointId: number, patch: Partial<Checkpoint>) => {
|
||||
setData((prev) => {
|
||||
if (!prev) return prev
|
||||
return {
|
||||
...prev,
|
||||
check_points: prev.check_points.map((c) =>
|
||||
c.id === checkpointId ? { ...c, ...patch } : c
|
||||
),
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const sections = useMemo(() => data ? groupBySection(data.check_points ?? []) : [], [data])
|
||||
const flatCheckpoints = useMemo(() => sections.flatMap((s) => s.items), [sections])
|
||||
|
||||
const totals = useMemo(() => {
|
||||
const t = { good: 0, attention: 0, critical: 0, na: 0, not_inspected: 0 }
|
||||
for (const cp of data?.check_points ?? []) {
|
||||
const s = (cp.severity as Severity) ?? "not_inspected"
|
||||
t[s]++
|
||||
}
|
||||
return t
|
||||
}, [data])
|
||||
|
||||
const setSeverity = async (cp: Checkpoint, severity: Severity) => {
|
||||
patchCheckpoint(cp.id, { severity })
|
||||
try {
|
||||
await api.inspections.updateCheckpoint(String(cp.id), { severity } as any)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to save")
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
if (isEditing) {
|
||||
const promise = api.inspections.updateCheckpoint(String(checkpoint.id), payload)
|
||||
toast.promise(promise, {
|
||||
loading: "Updating checkpoint...",
|
||||
success: "Checkpoint updated",
|
||||
error: "Failed to update checkpoint",
|
||||
})
|
||||
await promise
|
||||
} else {
|
||||
const promise = api.inspections.createCheckpoint(payload)
|
||||
toast.promise(promise, {
|
||||
loading: "Creating checkpoint...",
|
||||
success: "Checkpoint created",
|
||||
error: "Failed to create checkpoint",
|
||||
})
|
||||
await promise
|
||||
}
|
||||
onSuccess()
|
||||
onOpenChange(false)
|
||||
const handleSign = async (who: "technician" | "customer", dataUrl: string) => {
|
||||
setSigning({ who })
|
||||
try {
|
||||
await api.inspections.sign(id, who, dataUrl)
|
||||
toast.success(who === "technician" ? "Technician signature saved" : "Customer signature saved")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to save signature")
|
||||
} finally {
|
||||
setIsPending(false)
|
||||
setSigning(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (initialLoad) {
|
||||
return (
|
||||
<div className="min-h-[60vh] flex items-center justify-center">
|
||||
<div className="flex items-center gap-2 text-muted-foreground text-sm">
|
||||
<Loader2 className="size-4 animate-spin" /> Loading inspection…
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!data) return <div className="p-6 text-muted-foreground">Inspection not found</div>
|
||||
|
||||
const vehicleLine = data.vehicle
|
||||
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
|
||||
: "—"
|
||||
const customerName = data.customer ? `${data.customer.first_name ?? ""} ${data.customer.last_name ?? ""}`.trim() : "—"
|
||||
const totalCount = data.check_points.length
|
||||
const inspectedCount = totalCount - totals.not_inspected
|
||||
const progress = totalCount > 0 ? Math.round((inspectedCount / totalCount) * 100) : 0
|
||||
|
||||
const wizardSection = sections[wizardSectionIdx]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditing ? "Edit Checkpoint" : "Add Checkpoint"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="grid gap-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-name">Name *</Label>
|
||||
<Input
|
||||
id="cp-name"
|
||||
placeholder="e.g. Engine Oil Level"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<div className="max-w-5xl mx-auto p-3 sm:p-6 space-y-4">
|
||||
{/* Header */}
|
||||
<Card>
|
||||
<CardHeader className="gap-3">
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<Link href={`/sales/inspections/${id}`}>
|
||||
<Button variant="ghost" size="sm" className="-ms-2">
|
||||
<ChevronLeft className="size-4" /> Back to inspection
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="flex items-center gap-2">
|
||||
{refetching && <Loader2 className="size-3.5 animate-spin text-muted-foreground" />}
|
||||
<Button variant="outline" size="sm" onClick={() => setShareOpen(true)}>
|
||||
<Share2 className="size-4" /> Share with customer
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-description">Description</Label>
|
||||
<Textarea
|
||||
id="cp-description"
|
||||
placeholder="Check oil level and condition"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-record-type">Record Type</Label>
|
||||
<Select value={recordType} onValueChange={setRecordType}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{RECORD_TYPES.map((rt) => (
|
||||
<SelectItem key={rt.value} value={rt.value}>
|
||||
{rt.label}
|
||||
</SelectItem>
|
||||
<Separator />
|
||||
<div className="flex items-start justify-between gap-4 flex-wrap">
|
||||
<div className="min-w-0">
|
||||
<CardDescription className="uppercase tracking-wide text-[11px]">Inspection</CardDescription>
|
||||
<CardTitle className="text-2xl">{data.title}</CardTitle>
|
||||
<div className="flex items-center gap-4 mt-2 text-sm text-muted-foreground flex-wrap">
|
||||
<span className="inline-flex items-center gap-1.5"><User className="size-3.5" /> {customerName}</span>
|
||||
<span className="inline-flex items-center gap-1.5"><Car className="size-3.5" /> {vehicleLine}</span>
|
||||
{data.vehicle?.license_plate && (
|
||||
<Badge variant="outline" className="font-mono">{data.vehicle.license_plate}</Badge>
|
||||
)}
|
||||
{data.odometer != null && (
|
||||
<span className="inline-flex items-center gap-1.5"><Gauge className="size-3.5" /> {Number(data.odometer).toLocaleString()} km</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="gap-3">
|
||||
{/* Progress */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>Progress</span>
|
||||
<span className="tabular-nums">{inspectedCount} / {totalCount} ({progress}%)</span>
|
||||
</div>
|
||||
<Progress value={progress} className="h-2" />
|
||||
</div>
|
||||
|
||||
{/* Severity tally */}
|
||||
<div className="flex items-center gap-2 flex-wrap mt-3">
|
||||
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
|
||||
<Badge key={s} variant={SEVERITY_BADGE[s]} className="gap-1.5">
|
||||
<span className={`size-1.5 rounded-full ${SEVERITY_DOT[s].split(" ")[0]}`} />
|
||||
{totals[s]} {SEVERITY_LABEL[s]}
|
||||
</Badge>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isEditing ? <Pencil className="size-4" /> : <Plus className="size-4" />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Checkpoint" : "Create Checkpoint")}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Attachments Dialog ──
|
||||
|
||||
function getFileIcon(url: string) {
|
||||
const ext = url.split(".").pop()?.toLowerCase()
|
||||
if (["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")) return FileImage
|
||||
if (ext === "pdf") return FileText
|
||||
return File
|
||||
}
|
||||
|
||||
function getFileName(url: string) {
|
||||
try {
|
||||
return decodeURIComponent(url.split("/").pop() ?? "Attachment")
|
||||
} catch {
|
||||
return url.split("/").pop() ?? "Attachment"
|
||||
}
|
||||
}
|
||||
|
||||
function isImageUrl(url: string) {
|
||||
const ext = url.split(".").pop()?.toLowerCase()
|
||||
return ["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")
|
||||
}
|
||||
|
||||
function CheckpointAttachmentsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
checkpoint,
|
||||
onSuccess,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
checkpoint: CheckpointItem | null
|
||||
onSuccess: () => void
|
||||
}) {
|
||||
const api = useAuthApi()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
|
||||
const handleUpload = useCallback(async (file: globalThis.File) => {
|
||||
if (!checkpoint) return
|
||||
setIsUploading(true)
|
||||
try {
|
||||
const promise = api.inspections.uploadCheckpointMedia(
|
||||
String(checkpoint.id),
|
||||
{ file },
|
||||
)
|
||||
toast.promise(promise, {
|
||||
loading: "Uploading attachment...",
|
||||
success: "Attachment uploaded",
|
||||
error: "Failed to upload attachment",
|
||||
})
|
||||
await promise
|
||||
onSuccess()
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
if (fileInputRef.current) fileInputRef.current.value = ""
|
||||
}
|
||||
}, [api, checkpoint, onSuccess])
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (!checkpoint) return
|
||||
const promise = api.inspections.deleteCheckpointMedia(String(checkpoint.id))
|
||||
toast.promise(promise, {
|
||||
loading: "Removing attachment...",
|
||||
success: "Attachment removed",
|
||||
error: "Failed to remove attachment",
|
||||
})
|
||||
await promise
|
||||
onSuccess()
|
||||
}, [api, checkpoint, onSuccess])
|
||||
|
||||
const hasFile = !!checkpoint?.file
|
||||
const FileIcon = checkpoint?.file ? getFileIcon(checkpoint.file) : File
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Attachments — {checkpoint?.name}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Current attachment */}
|
||||
{hasFile ? (
|
||||
<div className="rounded-lg border p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0 ">
|
||||
{isImageUrl(checkpoint.file!) ? (
|
||||
<img
|
||||
src={checkpoint.file!}
|
||||
alt="Checkpoint attachment"
|
||||
className="size-12 rounded-md object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-md bg-muted">
|
||||
<FileIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex flex-col gap-0.5 max-w-48">
|
||||
<a
|
||||
href={checkpoint.file!}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="truncate text-sm font-medium text-primary hover:underline"
|
||||
>
|
||||
{getFileName(checkpoint.file!)}
|
||||
</a>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Current attachment
|
||||
{/* Legend */}
|
||||
<div className="mt-3 rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground flex items-center gap-3 flex-wrap">
|
||||
<span className="font-medium text-foreground">Tap a dot to mark:</span>
|
||||
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => (
|
||||
<span key={s} className="inline-flex items-center gap-1.5">
|
||||
<span className={`size-3 rounded-full ${SEVERITY_DOT[s].split(" ")[0]} shadow-md`} />
|
||||
{SEVERITY_LABEL[s]}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="shrink-0 text-destructive hover:text-destructive"
|
||||
onClick={handleDelete}
|
||||
title="Remove attachment"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-muted-foreground">
|
||||
<Paperclip className="size-8" />
|
||||
<span className="text-sm">No attachments yet</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Mode tabs */}
|
||||
{totalCount > 0 && (
|
||||
<Tabs value={mode} onValueChange={(v) => setMode(v as any)} className="w-full">
|
||||
<TabsList className="w-full sm:w-auto">
|
||||
<TabsTrigger value="all">All sections</TabsTrigger>
|
||||
<TabsTrigger value="wizard">Wizard</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
{/* Upload area */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.txt,audio/*,video/*"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleUpload(file)
|
||||
}}
|
||||
/>
|
||||
{/* Sections */}
|
||||
{totalCount === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-10 text-center">
|
||||
<CircleCheck className="size-8 mx-auto text-muted-foreground/60 mb-3" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This inspection has no checkpoints yet. It was probably created from an empty template.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : mode === "all" ? (
|
||||
sections.map((section) => (
|
||||
<Card key={section.name}>
|
||||
<CardHeader className="py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">{section.name}</CardTitle>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
{section.items.filter(isCheckpointComplete).length} / {section.items.length} done
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<ul className="divide-y">
|
||||
{section.items.map((cp) => (
|
||||
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
wizardSection && (() => {
|
||||
const pendingItems = wizardSection.items.filter((cp) => !isCheckpointComplete(cp))
|
||||
const sectionDone = pendingItems.length === 0
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="py-3 gap-1">
|
||||
<div className="flex items-center justify-between flex-wrap gap-2">
|
||||
<CardTitle className="text-base">{wizardSection.name}</CardTitle>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
Section {wizardSectionIdx + 1} / {sections.length}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<ul className="divide-y">
|
||||
{wizardSection.items.map((cp) => (
|
||||
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
<div className="px-4 py-3 border-t bg-muted/30 space-y-2">
|
||||
{!sectionDone && (
|
||||
<div className="flex items-start gap-2 text-xs text-amber-900">
|
||||
<AlertTriangle className="size-3.5 mt-0.5 shrink-0 text-amber-600" />
|
||||
<div>
|
||||
<span className="font-medium">{pendingItems.length} pending.</span>{' '}
|
||||
Each checkpoint needs a finding and its required recording before you can move on.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
disabled={isUploading}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<FileUp className="size-4" />
|
||||
{isUploading
|
||||
? "Uploading..."
|
||||
: hasFile
|
||||
? "Replace Attachment"
|
||||
: "Add Attachment"}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Main Page ──
|
||||
|
||||
export default function InspectionCheckpointsPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: inspectionId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [editingCheckpoint, setEditingCheckpoint] = useState<CheckpointItem | null>(null)
|
||||
const [attachmentsCheckpoint, setAttachmentsCheckpoint] = useState<CheckpointItem | null>(null)
|
||||
|
||||
const queryKey = [INSPECTION_ROUTES.CHECKPOINTS, inspectionId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.inspections.listCheckpoints({ inspection_id: inspectionId } as never),
|
||||
})
|
||||
|
||||
const invalidate = () => {
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}
|
||||
|
||||
// ── Status change mutation ──
|
||||
const changeStatusMutation = useMutation({
|
||||
mutationFn: ({ checkpointId, status }: { checkpointId: number; status: string }) =>
|
||||
api.inspections.changeCheckpointStatus({
|
||||
inspection_id: Number(inspectionId),
|
||||
inspection_check_point_id: String(checkpointId),
|
||||
name: "", // required by API type but server uses checkpoint id from context
|
||||
record_type: "record_conditions",
|
||||
status,
|
||||
} as never),
|
||||
onSuccess: () => invalidate(),
|
||||
})
|
||||
|
||||
// ── Delete checkpoint mutation ──
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (checkpointId: string) => api.inspections.destroyCheckpoint(checkpointId),
|
||||
onSuccess: () => {
|
||||
toast.success("Checkpoint deleted")
|
||||
invalidate()
|
||||
},
|
||||
onError: () => toast.error("Failed to delete checkpoint"),
|
||||
})
|
||||
|
||||
const handleEdit = (checkpoint: CheckpointItem) => {
|
||||
setEditingCheckpoint(checkpoint)
|
||||
setFormOpen(true)
|
||||
}
|
||||
|
||||
const handleAdd = () => {
|
||||
setEditingCheckpoint(null)
|
||||
setFormOpen(true)
|
||||
}
|
||||
|
||||
const handleStatusChange = (checkpointId: number, status: string) => {
|
||||
const promise = changeStatusMutation.mutateAsync({ checkpointId, status, })
|
||||
toast.promise(promise, {
|
||||
loading: "Updating status...",
|
||||
success: `Status changed to ${formatStatus(status)}`,
|
||||
error: "Failed to update status",
|
||||
})
|
||||
}
|
||||
|
||||
const checkpoints = (data as any)?.data ?? []
|
||||
const meta = (data as any)?.meta
|
||||
|
||||
const pagination = {
|
||||
page: meta?.current_page ?? 1,
|
||||
pageSize: meta?.per_page ?? 15,
|
||||
pageCount: meta?.last_page ?? 1,
|
||||
total: meta?.total ?? 0,
|
||||
}
|
||||
|
||||
const columns = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="font-medium">{item.name}</span>
|
||||
{item.description && (
|
||||
<span className="text-xs text-muted-foreground">{item.description}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "record_type",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Record Type" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
const rt = RECORD_TYPES.find((r) => r.value === item.record_type)
|
||||
return rt?.label ?? item.record_type ?? "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
const config = getStatusConfig(item.status)
|
||||
return (
|
||||
<Badge className={config.color}>
|
||||
<config.icon className="mr-1 size-3" />
|
||||
{formatStatus(item.status)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "condition_rate",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Condition" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return item.condition_rate != null ? `${item.condition_rate}/10` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: () => <span className="text-xs">Attachments</span>,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5"
|
||||
onClick={() => setAttachmentsCheckpoint(item)}
|
||||
disabled={wizardSectionIdx === 0}
|
||||
onClick={() => setWizardSectionIdx((i) => Math.max(0, i - 1))}
|
||||
>
|
||||
<Paperclip className="size-3.5" />
|
||||
{item.file ? (
|
||||
<Badge variant="secondary" className="px-1.5 py-0 text-xs">1</Badge>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">0</span>
|
||||
)}
|
||||
<ChevronLeft className="size-4" /> Previous
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<Ellipsis className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{CHECKPOINT_STATUSES.map((s) => (
|
||||
<DropdownMenuItem
|
||||
key={s.value}
|
||||
onClick={() => handleStatusChange(item.id, s.value)}
|
||||
disabled={item.status === s.value}
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={wizardSectionIdx >= sections.length - 1 || !sectionDone}
|
||||
onClick={() => setWizardSectionIdx((i) => Math.min(sections.length - 1, i + 1))}
|
||||
>
|
||||
<s.icon className="size-4" />
|
||||
{s.label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => handleEdit(item)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => deleteMutation.mutate(String(item.id))}
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<h3 className="text-lg font-semibold">Checkpoints</h3>
|
||||
<Button onClick={handleAdd} size="sm">
|
||||
<Plus className="size-4" />
|
||||
Add Checkpoint
|
||||
Next <ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={checkpoints}
|
||||
pagination={pagination}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
})()
|
||||
)}
|
||||
|
||||
{/* Signatures */}
|
||||
{totalCount > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="py-3 flex-row items-center gap-2">
|
||||
<FileSignature className="size-4 text-muted-foreground" />
|
||||
<CardTitle className="text-base">Sign-off</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="gap-3 grid grid-cols-1 md:grid-cols-2">
|
||||
<SignaturePad
|
||||
label="Technician signature"
|
||||
existingUrl={data.technician_signature_url}
|
||||
saving={signing?.who === "technician"}
|
||||
onSave={(d) => handleSign("technician", d)}
|
||||
/>
|
||||
<CheckpointFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={(open) => {
|
||||
setFormOpen(open)
|
||||
if (!open) setEditingCheckpoint(null)
|
||||
}}
|
||||
inspectionId={inspectionId}
|
||||
checkpoint={editingCheckpoint}
|
||||
onSuccess={invalidate}
|
||||
<SignaturePad
|
||||
label="Customer signature"
|
||||
existingUrl={data.customer_signature_url}
|
||||
saving={signing?.who === "customer"}
|
||||
onSave={(d) => handleSign("customer", d)}
|
||||
/>
|
||||
<CheckpointAttachmentsDialog
|
||||
open={!!attachmentsCheckpoint}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setAttachmentsCheckpoint(null)
|
||||
}}
|
||||
checkpoint={attachmentsCheckpoint}
|
||||
onSuccess={invalidate}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<CheckpointFillDialog
|
||||
open={activeIndex !== null}
|
||||
onOpenChange={(o) => { if (!o) setActiveIndex(null) }}
|
||||
checkpoints={flatCheckpoints}
|
||||
activeIndex={activeIndex}
|
||||
onIndexChange={setActiveIndex}
|
||||
onSaved={load}
|
||||
onPatch={patchCheckpoint}
|
||||
/>
|
||||
</DashboardPage>
|
||||
|
||||
<InspectionShareDialog
|
||||
open={shareOpen}
|
||||
onOpenChange={setShareOpen}
|
||||
inspectionId={id}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CheckpointRow({
|
||||
cp,
|
||||
onSeverity,
|
||||
onOpen,
|
||||
}: {
|
||||
cp: Checkpoint
|
||||
onSeverity: (cp: Checkpoint, s: Severity) => void
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const current = (cp.severity as Severity) ?? "not_inspected"
|
||||
const attachments = cp.attachments ?? cp.media ?? []
|
||||
const photoCount = attachments.filter((m) => m.media_type === "photo").length
|
||||
const complete = isCheckpointComplete(cp)
|
||||
return (
|
||||
<li
|
||||
className={`px-3 sm:px-4 py-3 transition-colors hover:bg-muted/30 ${!complete ? "bg-amber-50/40" : ""}`}
|
||||
>
|
||||
<div className="flex items-start gap-3 flex-wrap sm:flex-nowrap">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex-1 min-w-0 text-left group"
|
||||
>
|
||||
<div className="font-medium text-sm flex items-center gap-2">
|
||||
<span className="group-hover:text-primary transition">{cp.name}</span>
|
||||
{!complete && (
|
||||
<Badge variant="secondary" className="text-[10px] uppercase tracking-wide">
|
||||
Pending
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{cp.technician_notes && (
|
||||
<div className="flex items-start gap-1 text-xs text-muted-foreground mt-1">
|
||||
<StickyNote className="size-3 mt-0.5 shrink-0" />
|
||||
<span className="italic line-clamp-1">{cp.technician_notes}</span>
|
||||
</div>
|
||||
)}
|
||||
{photoCount > 0 && (
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
|
||||
<ImageIcon className="size-3" /> {photoCount} photo{photoCount === 1 ? "" : "s"}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
<div className="flex gap-2 justify-end shrink-0 w-full sm:w-auto">
|
||||
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => {
|
||||
const active = current === s
|
||||
return (
|
||||
<button
|
||||
key={s}
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); onSeverity(cp, s) }}
|
||||
aria-label={SEVERITY_LABEL[s]}
|
||||
title={SEVERITY_LABEL[s]}
|
||||
className={`size-10 sm:size-9 rounded-full transition shadow-md ${SEVERITY_DOT[s]} ${active ? "ring-2 ring-offset-2 ring-foreground/40 scale-105" : "opacity-60 hover:opacity-100"}`}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
|
||||
@@ -1,25 +1,68 @@
|
||||
"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">
|
||||
<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}
|
||||
@@ -28,19 +71,55 @@ export default function InspectionsPage() {
|
||||
/>
|
||||
)}
|
||||
</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))}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -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
|
||||
@@ -16,7 +17,6 @@ export default async function InvoiceDetailLayout(props: { params: Promise<{ id:
|
||||
return (
|
||||
<InvoiceProvider invoice={data}>
|
||||
<DashboardDetailsPage
|
||||
className='p-0 lg:p-0'
|
||||
title={title}
|
||||
description={data?.invoice_number ? `Invoice #: ${data.invoice_number}` : undefined}
|
||||
icon={<ReceiptIcon className="size-5" />}
|
||||
@@ -25,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>
|
||||
}
|
||||
|
||||
@@ -1,22 +1,82 @@
|
||||
"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 { INVOICE_ROUTES } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
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
|
||||
subject?: string
|
||||
invoice_title?: string
|
||||
invoice_number?: string
|
||||
customer_name?: string
|
||||
status?: string
|
||||
invoice_date?: string
|
||||
due_date?: string
|
||||
created_at?: string
|
||||
total?: number | string
|
||||
balance_due?: number | string
|
||||
customer?: {
|
||||
id?: number | string
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
company_name?: string
|
||||
phone?: string
|
||||
} | null
|
||||
vehicle?: {
|
||||
make?: string
|
||||
model?: string
|
||||
sub_model?: string
|
||||
year?: number | string
|
||||
license_plate?: string
|
||||
} | null
|
||||
}
|
||||
|
||||
function getCustomerLabel(item: InvoiceItem): string {
|
||||
const firstName = item.customer?.first_name?.trim()
|
||||
const lastName = item.customer?.last_name?.trim()
|
||||
const fullName = [firstName, lastName].filter(Boolean).join(" ").trim()
|
||||
|
||||
return fullName || item.customer_name || item.customer?.company_name || "—"
|
||||
}
|
||||
|
||||
function getVehicleLabel(item: InvoiceItem): string {
|
||||
const vehicle = item.vehicle
|
||||
if (!vehicle) return "—"
|
||||
|
||||
const core = [vehicle.make, vehicle.model, vehicle.sub_model].filter(Boolean).join(" ")
|
||||
const suffix = [vehicle.year, vehicle.license_plate].filter(Boolean).join(" • ")
|
||||
|
||||
if (core && suffix) return `${core} (${suffix})`
|
||||
return core || suffix || "—"
|
||||
}
|
||||
|
||||
function getDueMeta(dueDate?: string) {
|
||||
if (!dueDate) return { text: "No due date", tone: "muted" as const }
|
||||
|
||||
const due = new Date(dueDate)
|
||||
if (isNaN(due.getTime())) return { text: "Invalid due date", tone: "muted" as const }
|
||||
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
due.setHours(0, 0, 0, 0)
|
||||
|
||||
const days = Math.ceil((due.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
|
||||
|
||||
if (days < 0) return { text: `${Math.abs(days)} day(s) overdue`, tone: "danger" as const }
|
||||
if (days === 0) return { text: "Due today", tone: "warning" as const }
|
||||
if (days <= 3) return { text: `Due in ${days} day(s)`, tone: "warning" as const }
|
||||
|
||||
return { text: `Due in ${days} day(s)`, tone: "ok" as const }
|
||||
}
|
||||
|
||||
export default function InvoicesPage() {
|
||||
@@ -26,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 }) => ({
|
||||
@@ -44,15 +107,64 @@ export default function InvoicesPage() {
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "subject",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Subject" />,
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const title = item.subject || item.invoice_title || "Untitled invoice"
|
||||
|
||||
return (
|
||||
<div className="min-w-[220px]">
|
||||
<p className="font-medium leading-none">{title}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{item.invoice_number || "No invoice number"}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "invoice_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice #" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
|
||||
return (
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{item.invoice_number || "—"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getCustomerLabel(item)}
|
||||
meta={item.customer?.phone}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vehicle",
|
||||
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 (
|
||||
<RelationLink
|
||||
href={vehicleId ? `/sales/vehicles/${vehicleId}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(item)}
|
||||
meta={item.vehicle?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
@@ -60,27 +172,71 @@ export default function InvoicesPage() {
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const status = item.status
|
||||
const colorMap: Record<string, string> = {
|
||||
draft: "text-muted-foreground",
|
||||
open: "text-blue-600",
|
||||
paid: "text-green-600",
|
||||
overdue: "text-red-600",
|
||||
void: "text-gray-400",
|
||||
const classMap: Record<string, string> = {
|
||||
draft: "bg-slate-100 text-slate-700",
|
||||
open: "bg-blue-100 text-blue-700",
|
||||
paid: "bg-emerald-100 text-emerald-700",
|
||||
over_due: "bg-red-100 text-red-700",
|
||||
un_paid: "bg-orange-100 text-orange-700",
|
||||
partially_paid: "bg-amber-100 text-amber-700",
|
||||
void: "bg-zinc-100 text-zinc-700",
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={colorMap[status ?? ""] ?? ""}>
|
||||
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
|
||||
</span>
|
||||
<Badge variant="outline" className={classMap[status ?? ""] ?? ""}>
|
||||
{formatEnum(status) || "—"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "invoice_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice Date" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
return formatDate(item.invoice_date)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "due_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Due Date" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const dueMeta = getDueMeta(item.due_date)
|
||||
const toneClassMap = {
|
||||
danger: "text-red-600",
|
||||
warning: "text-amber-600",
|
||||
ok: "text-emerald-600",
|
||||
muted: "text-muted-foreground",
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p className="font-medium leading-none">{formatDate(item.due_date)}</p>
|
||||
<p className={`mt-1 text-xs ${toneClassMap[dueMeta.tone]}`}>
|
||||
{dueMeta.text}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "amounts",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Amounts" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
|
||||
return (
|
||||
<div className="min-w-[150px]">
|
||||
<p className="font-medium leading-none">
|
||||
Total: {<Money value={item.total ?? 0} />}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Due: {<Money value={item.balance_due ?? 0} />}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 ?? []
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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})`
|
||||
},
|
||||
|
||||
{
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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 ?? []
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 ?? []
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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,37 +34,24 @@ 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",
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<FilterTrigger onClick={filter.open} activeFilterCount={filter.activeFilterCount} />
|
||||
<FormDialog classNames={{ dialogContent: 'min-w-6xl' }} title="Job Card" >
|
||||
<FormDialog classNames={{ dialogContent: 'xl:min-w-6xl' }} title="Job Card" >
|
||||
{(resourceId, {close}) => (
|
||||
<JobCardForm
|
||||
resourceId={resourceId}
|
||||
@@ -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
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useParams } from "next/navigation"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { useState } from "react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { Download, ExternalLink, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
@@ -19,10 +19,27 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { VehicleDocumentForm } from "@/modules/vehicles/vehicle-document-form"
|
||||
import { formatDate, formatDateTime } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
type VehicleDocument = {
|
||||
id: number
|
||||
name: string
|
||||
document_number?: string
|
||||
document_type_id?: number
|
||||
document_type?: {
|
||||
id?: number
|
||||
name?: string
|
||||
} | null
|
||||
customer_id?: number
|
||||
customer?: {
|
||||
id?: number
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
name?: string
|
||||
} | null
|
||||
document_expire?: string
|
||||
document_file?: string
|
||||
document_file_url?: string | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -54,7 +71,7 @@ export default function VehicleDocumentsPage() {
|
||||
const handleDelete = async (doc: VehicleDocument) => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Document",
|
||||
description: `Are you sure you want to delete "${doc.name}"?`,
|
||||
description: `Are you sure you want to delete "${doc.document_number || `Document #${doc.id}`}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
@@ -65,16 +82,74 @@ export default function VehicleDocumentsPage() {
|
||||
|
||||
const columns: ColumnDef<VehicleDocument>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
accessorKey: "document_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Document Number" />,
|
||||
cell: ({ getValue, row }) => {
|
||||
const number = getValue<string>()
|
||||
const fallbackName = row.original.document_file?.split("/").pop()
|
||||
return number || fallbackName || `Document #${row.original.id}`
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "document_type_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Document Type" />,
|
||||
cell: ({ row, getValue }) => {
|
||||
const typeName = row.original.document_type?.name
|
||||
const value = getValue<number | undefined>()
|
||||
return typeName || (value ? `#${value}` : "—")
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row, getValue }) => {
|
||||
const name = getFullName(row.original.customer as any) || row.original.customer?.name
|
||||
const value = getValue<number | undefined>()
|
||||
return name || (value ? `#${value}` : "—")
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "document_expire",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry Date" />,
|
||||
cell: ({ getValue }) => formatDate(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "file",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="File" />,
|
||||
cell: ({ row }) => {
|
||||
const url = row.original.document_file_url
|
||||
if (!url) return "No file"
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-primary underline"
|
||||
title="Open document"
|
||||
>
|
||||
<ExternalLink className="size-3.5" />
|
||||
Open
|
||||
</a>
|
||||
<a
|
||||
href={url}
|
||||
download
|
||||
className="inline-flex items-center gap-1 text-primary underline"
|
||||
title="Download document"
|
||||
>
|
||||
<Download className="size-3.5" />
|
||||
Download
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Uploaded At" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -83,7 +158,10 @@ export default function VehicleDocumentsPage() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleDelete(row.original)
|
||||
}}
|
||||
title="Delete document"
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
@@ -93,6 +171,15 @@ export default function VehicleDocumentsPage() {
|
||||
},
|
||||
]
|
||||
|
||||
const handleRowClick = (doc: VehicleDocument) => {
|
||||
if (doc.document_file_url) {
|
||||
window.open(doc.document_file_url, "_blank", "noopener,noreferrer")
|
||||
return
|
||||
}
|
||||
|
||||
toast.info("This document has no file to open.")
|
||||
}
|
||||
|
||||
const documents = (data as any)?.data ?? []
|
||||
const meta = (data as any)?.meta
|
||||
|
||||
@@ -105,21 +192,25 @@ export default function VehicleDocumentsPage() {
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center justify-end">
|
||||
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
slots={{
|
||||
actions: <div className="flex items-center justify-end">
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Upload Document
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
}}
|
||||
columns={columns}
|
||||
data={documents}
|
||||
pagination={pagination}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
onChange={() => { }}
|
||||
onRowClick={handleRowClick}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -13,7 +13,6 @@ export default async function layout(props: { params: Promise<{ id: string }>, c
|
||||
return (
|
||||
<>
|
||||
<DashboardDetailsPage
|
||||
className='p-0 lg:p-0'
|
||||
avatarSrc={vehicle.data?.image_url || ""}
|
||||
// avatarSrc={vehicle.data?.image_url || ""}
|
||||
title={title}
|
||||
|
||||
@@ -25,11 +25,23 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { MileageForm } from "@/modules/vehicles/mileage-form"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { formatDate, formatDateTime } from "@/shared/utils/formatters"
|
||||
|
||||
type MileageRecord = {
|
||||
id: number
|
||||
name: string
|
||||
vehicle_id?: number
|
||||
miles?: number | null
|
||||
fuel_level?: number | null
|
||||
date?: string | null
|
||||
time?: string | null
|
||||
note?: string | null
|
||||
vehicle?: {
|
||||
id?: number
|
||||
make?: string | null
|
||||
model?: string | null
|
||||
year?: number | null
|
||||
license_plate?: string | null
|
||||
} | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -64,9 +76,10 @@ export default function VehicleMileagePage() {
|
||||
})
|
||||
|
||||
const handleDelete = async (record: MileageRecord) => {
|
||||
const label = record.miles != null ? `${record.miles} mi` : `Record #${record.id}`
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Mileage Record",
|
||||
description: `Are you sure you want to delete this mileage record?`,
|
||||
description: `Are you sure you want to delete ${label}?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
@@ -87,16 +100,59 @@ export default function VehicleMileagePage() {
|
||||
|
||||
const columns: ColumnDef<MileageRecord>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Mileage" />,
|
||||
accessorKey: "miles",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Miles" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<number | null | undefined>()
|
||||
return value == null ? "—" : value.toLocaleString()
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "fuel_level",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Fuel Level" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<number | null | undefined>()
|
||||
return value == null ? "—" : `${value}%`
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ getValue }) => formatDate(getValue<string | null | undefined>()),
|
||||
},
|
||||
{
|
||||
accessorKey: "time",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Time" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<string | null | undefined>()
|
||||
if (!value) return "—"
|
||||
if (value.includes("T")) {
|
||||
const timePart = value.split("T")[1]
|
||||
return timePart ? timePart.slice(0, 5) : "—"
|
||||
}
|
||||
return value.slice(0, 5)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "note",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Note" />,
|
||||
cell: ({ getValue }) => getValue<string | null | undefined>() || "—",
|
||||
},
|
||||
{
|
||||
id: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const vehicle = row.original.vehicle
|
||||
if (!vehicle) return "—"
|
||||
const details = [vehicle.make, vehicle.model, vehicle.year].filter(Boolean).join(" ")
|
||||
return details || vehicle.license_plate || "—"
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Recorded At" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -142,31 +198,25 @@ export default function VehicleMileagePage() {
|
||||
<div className="flex flex-col gap-4">
|
||||
|
||||
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: 'Mileage',
|
||||
actions: (
|
||||
<Button onClick={handleCreate}>
|
||||
<Plus className="size-4" />
|
||||
Add Mileage
|
||||
</Button>
|
||||
),
|
||||
}}
|
||||
>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
slots={{
|
||||
actions: <Button onClick={handleCreate}>
|
||||
<Plus className="size-4" />
|
||||
Add Mileage
|
||||
</Button>
|
||||
}}
|
||||
columns={columns}
|
||||
data={records}
|
||||
pagination={pagination}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
onChange={() => { }}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</DashboardPage>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="min-w-md">
|
||||
|
||||
@@ -129,20 +129,28 @@ export default function VehicleOwnersPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardPage headerProps={{
|
||||
title: "Owners",
|
||||
actions: (
|
||||
<Button className="w-full" size={'lg'} onClick={() => setLinkDialogOpen(true)}>
|
||||
<Plus />
|
||||
Add Owner
|
||||
</Button>
|
||||
),
|
||||
}}>
|
||||
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
|
||||
|
||||
<DataTable
|
||||
slots={{
|
||||
actions:
|
||||
<div className="flex justify-end">
|
||||
|
||||
<Button size={'lg'} onClick={() => setLinkDialogOpen(true)}>
|
||||
<Plus />
|
||||
Add Owner
|
||||
</Button>
|
||||
</div>,
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
columns={columns}
|
||||
data={owners}
|
||||
pagination={pagination}
|
||||
@@ -163,7 +171,6 @@ export default function VehicleOwnersPage() {
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</DashboardPage >
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,15 +3,18 @@
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
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()
|
||||
@@ -20,24 +23,25 @@ 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)}
|
||||
fileName='vehicles'
|
||||
/>
|
||||
<FormDialog title="Vehicle">
|
||||
<FormDialog title="Vehicle" classNames={{ dialogContent: 'lg:min-w-4xl' }}>
|
||||
{(resourceId) => (
|
||||
<VehicleForm
|
||||
resourceId={resourceId}
|
||||
@@ -49,9 +53,11 @@ export default function VehiclesPage() {
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
id: "name",
|
||||
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as any
|
||||
@@ -71,6 +77,20 @@ export default function VehiclesPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customers",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }: any) => {
|
||||
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,
|
||||
{
|
||||
accessorKey: "year",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Year" />,
|
||||
@@ -109,14 +129,7 @@ export default function VehiclesPage() {
|
||||
return val != null ? `${Number(val).toLocaleString()} mi` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).created_at
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -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: (
|
||||
|
||||
@@ -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: "0–100",
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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: (
|
||||
|
||||
@@ -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: (
|
||||
|
||||
@@ -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: (
|
||||
|
||||
@@ -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: (
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -68,14 +68,22 @@ export default function DashboardDetailsPageLayout({
|
||||
</Button>
|
||||
)}
|
||||
{(avatarSrc || avatarFallback) && (
|
||||
<a rel="preload" target="_blank" href={avatarSrc} >
|
||||
avatarSrc ? (
|
||||
<a target="_blank" rel="noopener noreferrer" href={avatarSrc}>
|
||||
<Avatar className="size-14">
|
||||
{avatarSrc && <AvatarImage src={avatarSrc} alt={title} />}
|
||||
<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",
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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 /> },
|
||||
|
||||
@@ -4,6 +4,8 @@ import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -15,6 +17,8 @@ import { Ellipsis, Pencil, Trash2, CheckCircle, Unlink } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "./appointment-form"
|
||||
|
||||
type AppointmentActionsProps = {
|
||||
appointmentId: string
|
||||
@@ -27,10 +31,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
const router = useRouter()
|
||||
const queryClient = useQueryClient()
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/calendar/appointment/${appointmentId}/edit`)
|
||||
}
|
||||
const editDialog = useFormDialog("appointment-details-edit")
|
||||
|
||||
const handleDelete = async () => {
|
||||
setIsLoading(true)
|
||||
@@ -75,6 +76,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" disabled={isLoading}>
|
||||
@@ -82,7 +84,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<DropdownMenuItem onClick={() => editDialog.open(appointmentId)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
@@ -120,5 +122,22 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
|
||||
<DialogContent className="min-w-xl lg:min-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">Edit Appointment</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<AppointmentForm
|
||||
resourceId={editDialog.resourceId}
|
||||
onSuccess={() => {
|
||||
editDialog.close()
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -10,20 +10,30 @@ const APPOINTMENT_STATUS_OPTIONS = AppointmentStatus.map((v) => ({
|
||||
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
}))
|
||||
|
||||
const appointmentFormSchema = z.object({
|
||||
title: z.string().min(1, "Title is required"),
|
||||
const appointmentFormSchema = z
|
||||
.object({
|
||||
title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
|
||||
date: z.string().min(1, "Date is required"),
|
||||
from_time: z.string().min(1, "Start time is required"),
|
||||
to_time: z.string().min(1, "End time is required"),
|
||||
customer: relationFieldSchema,
|
||||
vehicle: relationFieldSchema,
|
||||
service_writer: relationFieldSchema,
|
||||
service_writer: relationFieldSchema.refine((val) => !!val?.value, "Service writer is required"),
|
||||
technician: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
job_card: relationFieldSchema,
|
||||
notes: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
})
|
||||
})
|
||||
.superRefine((val, ctx) => {
|
||||
if (val.from_time && val.to_time && val.to_time <= val.from_time) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["to_time"],
|
||||
message: "End time must be after start time",
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
type AppointmentFormValues = z.infer<typeof appointmentFormSchema>
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { z } from "zod"
|
||||
|
||||
const loginFormSchema = z.object({
|
||||
email: z.string().trim().email("Enter a valid email address"),
|
||||
password: z.string().min(8, "Password must be at least 8 characters"),
|
||||
password: z.string().min(6, "Password must be at least 6 characters"),
|
||||
})
|
||||
|
||||
type LoginFormValues = z.infer<typeof loginFormSchema>
|
||||
|
||||
@@ -3,13 +3,19 @@
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, 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
|
||||
@@ -18,10 +24,8 @@ type BillActionsProps = {
|
||||
export function BillActions({ billId }: BillActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/purchase/bill/${billId}/edit`)
|
||||
}
|
||||
const editDialog = useFormDialog("bill-details-edit")
|
||||
const [shareOpen, setShareOpen] = useState(false)
|
||||
|
||||
const handleDelete = async () => {
|
||||
await api.bills.destroy(billId)
|
||||
@@ -29,6 +33,7 @@ export function BillActions({ billId }: BillActionsProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
@@ -36,15 +41,39 @@ export function BillActions({ billId }: BillActionsProps) {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<DropdownMenuItem onClick={() => editDialog.open(billId)}>
|
||||
<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
|
||||
</DropdownMenuItem>
|
||||
</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>
|
||||
<DialogTitle className="text-2xl font-bold">Edit Bill</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<BillForm
|
||||
resourceId={editDialog.resourceId}
|
||||
onSuccess={() => {
|
||||
editDialog.close()
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -61,6 +61,7 @@ const DEFAULT_VALUES: BillFormValues = {
|
||||
discount: "no",
|
||||
discount_amount: undefined,
|
||||
notes: "",
|
||||
label_ids: [],
|
||||
part_items: [],
|
||||
service_items: [],
|
||||
expense_items: [],
|
||||
@@ -102,6 +103,7 @@ function mapToFormValues(data: unknown): BillFormValues {
|
||||
discount: d.discount_type || "no",
|
||||
discount_amount: d.discount_amount != null ? Number(d.discount_amount) : undefined,
|
||||
notes: d.notes || "",
|
||||
label_ids: Array.isArray(d.label_ids) ? d.label_ids.map((id: any) => Number(id)).filter((id: number) => Number.isFinite(id)) : [],
|
||||
part_items: (d.parts ?? []).map((p: any) => ({
|
||||
part_id: p.part_id ?? p.id,
|
||||
title: p.part?.name ?? p.part_name ?? p.title ?? "",
|
||||
@@ -146,6 +148,7 @@ function mapFormToPayload(values: BillFormValues) {
|
||||
discount_type: values.discount || undefined,
|
||||
discount_amount: values.discount === "transaction_level" ? (values.discount_amount ?? 0) : undefined,
|
||||
notes: values.notes || undefined,
|
||||
label_ids: values.label_ids?.length ? values.label_ids : undefined,
|
||||
part_items: (values.part_items ?? []).map((item) => ({
|
||||
part_id: item.part_id,
|
||||
quantity: item.quantity,
|
||||
@@ -276,7 +279,7 @@ export function BillForm({ resourceId, initialData, onSuccess }: BillFormProps)
|
||||
<CardContent>
|
||||
<FieldGroup>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-1">
|
||||
<RhfDateField name="bill_date" label="Bill Date" />
|
||||
<RhfDateField name="bill_date" label="Bill Date" required />
|
||||
<RhfDateField name="bill_due_date" label="Due Date" />
|
||||
</div>
|
||||
|
||||
|
||||
@@ -19,9 +19,10 @@ import {
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import { formatDate, formatCurrency, formatEnum } from "@/shared/utils/formatters"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { useBill } from "./bill-context"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
function InfoItem({
|
||||
icon: Icon,
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { Wrench } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
|
||||
import { formatNumber } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
type BillPart = {
|
||||
id: number
|
||||
@@ -62,14 +63,14 @@ export function BillPartsSection({ parts = [] }: BillPartsSectionProps) {
|
||||
{part.description || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
|
||||
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
|
||||
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
@@ -17,7 +17,6 @@ import { PaymentMadeForm } from "@/modules/payment-mades/payment-made-form"
|
||||
import { useBill } from "./bill-context"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { toRelation } from "@/shared/lib/utils"
|
||||
|
||||
export function BillPaymentsSection() {
|
||||
const bill = useBill()
|
||||
@@ -39,10 +38,18 @@ export function BillPaymentsSection() {
|
||||
{(resourceId) => (
|
||||
<PaymentMadeForm
|
||||
initialData={{
|
||||
anount: bill?.balance_due,
|
||||
vendor: toRelation(bill?.vendor?.id, getFullName(bill?.vendor as any)),
|
||||
payment_made: bill?.balance_due != null ? String(bill.balance_due) : undefined,
|
||||
|
||||
// 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}
|
||||
resourceId={resourceId}
|
||||
@@ -78,7 +85,7 @@ export function BillPaymentsSection() {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{item.vendor?.name || item.vendor_name || "—"}</span>
|
||||
<span>{item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name || "—"}</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { Briefcase } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
|
||||
import { formatNumber } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
type BillService = {
|
||||
id: number
|
||||
@@ -62,14 +63,14 @@ export function BillServicesSection({ services = [] }: BillServicesSectionProps)
|
||||
{service.description || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
|
||||
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
|
||||
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import { formatCurrency, formatEnum } from "@/shared/utils/formatters"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import { useBill } from "./bill-context"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
export function BillTotalsSummary() {
|
||||
const bill = useBill()
|
||||
@@ -46,70 +47,65 @@ export function BillTotalsSummary() {
|
||||
{parts.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Parts ({parts.length})</span>
|
||||
<span>{formatCurrency(partsTotal)}</span>
|
||||
<span>{<Money value={partsTotal} />}</span>
|
||||
</div>
|
||||
)}
|
||||
{services.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Services ({services.length})</span>
|
||||
<span>{formatCurrency(servicesTotal)}</span>
|
||||
<span>{<Money value={servicesTotal} />}</span>
|
||||
</div>
|
||||
)}
|
||||
{expenses.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Expenses ({expenses.length})</span>
|
||||
<span>{formatCurrency(expensesTotal)}</span>
|
||||
<span>{<Money value={expensesTotal} />}</span>
|
||||
</div>
|
||||
)}
|
||||
<Separator />
|
||||
|
||||
<div className="flex justify-between text-sm font-medium">
|
||||
<span>Subtotal</span>
|
||||
<span>{formatCurrency(subTotal)}</span>
|
||||
<span>{<Money value={subTotal} />}</span>
|
||||
</div>
|
||||
|
||||
{discountAmount > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Discount{discount && discount !== "no" ? ` (${formatEnum(discount)})` : ""}</span>
|
||||
<span className="text-muted-foreground">−{formatCurrency(discountAmount)}</span>
|
||||
<span className="text-muted-foreground">−{<Money value={discountAmount} />}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{taxAmount > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Tax{bill.tax?.name ? ` (${bill.tax.name})` : ""}</span>
|
||||
<span>{formatCurrency(taxAmount)}</span>
|
||||
<span>{<Money value={taxAmount} />}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className={cn(
|
||||
"flex justify-between rounded-lg px-3 py-2 text-base font-bold bg-muted/50",
|
||||
)}>
|
||||
<div className="flex justify-between text-base font-semibold">
|
||||
<span>Total</span>
|
||||
<span>{formatCurrency(total)}</span>
|
||||
<span>{<Money value={total} />}</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 className="flex justify-between text-sm text-muted-foreground">
|
||||
<span>Amount Paid</span>
|
||||
<span>– {<Money value={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",
|
||||
"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>Balance Due</span>
|
||||
<span>{formatCurrency(balanceDue)}</span>
|
||||
<span>{<Money value={balanceDue} />}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
import { z } from "zod"
|
||||
import { BillStatus, DiscountType } from "@garage/api"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const optionalDateSchema = z.preprocess(
|
||||
(value) => (value === "" || value == null ? undefined : value),
|
||||
z.string().date().optional(),
|
||||
)
|
||||
|
||||
const optionalStringMax255Schema = z.preprocess(
|
||||
(value) => (value === "" || value == null ? undefined : value),
|
||||
z.string().max(255, "Must be at most 255 characters").optional(),
|
||||
)
|
||||
|
||||
const requiredDateSchema = z
|
||||
.string()
|
||||
.min(1, "Bill date is required")
|
||||
.date("Enter a valid date")
|
||||
|
||||
const billPartItemSchema = z.object({
|
||||
part_id: z.number(),
|
||||
title: z.string(),
|
||||
@@ -33,7 +49,7 @@ const billExpenseItemSchema = z.object({
|
||||
|
||||
const billFormSchema = z.object({
|
||||
// ── Required ──
|
||||
title: z.string().min(1, "Title is required"),
|
||||
title: z.string().trim().min(1, "Title is required").max(255, "Title must be at most 255 characters"),
|
||||
|
||||
// ── Relations ──
|
||||
vendor: relationFieldSchema,
|
||||
@@ -45,13 +61,14 @@ const billFormSchema = z.object({
|
||||
tax: relationFieldSchema,
|
||||
|
||||
// ── Optional fields ──
|
||||
bill_number: z.string().optional(),
|
||||
bill_date: z.string().optional(),
|
||||
bill_due_date: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
discount: z.string().optional(),
|
||||
bill_number: optionalStringMax255Schema,
|
||||
bill_date: requiredDateSchema,
|
||||
bill_due_date: optionalDateSchema,
|
||||
status: z.enum(BillStatus).optional(),
|
||||
discount: z.enum(DiscountType).optional(),
|
||||
discount_amount: z.coerce.number().min(0).optional(),
|
||||
notes: z.string().optional(),
|
||||
label_ids: z.array(z.number()).optional(),
|
||||
|
||||
// ── Line items ──
|
||||
part_items: z.array(billPartItemSchema).optional(),
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -10,6 +12,8 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { CreditNoteForm } from "./credit-note-form"
|
||||
|
||||
type CreditNoteActionsProps = {
|
||||
creditNoteId: string
|
||||
@@ -18,10 +22,7 @@ type CreditNoteActionsProps = {
|
||||
export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/sales/credit-notes/${creditNoteId}/edit`)
|
||||
}
|
||||
const editDialog = useFormDialog("credit-note-details-edit")
|
||||
|
||||
const handleDelete = async () => {
|
||||
await api.creditNotes.destroy(creditNoteId)
|
||||
@@ -29,6 +30,7 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
@@ -36,7 +38,7 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<DropdownMenuItem onClick={() => editDialog.open(creditNoteId)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
@@ -46,5 +48,23 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
|
||||
<DialogContent className="min-w-xl lg:min-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">Edit Credit Note</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<CreditNoteForm
|
||||
resourceId={editDialog.resourceId}
|
||||
onSuccess={() => {
|
||||
editDialog.close()
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
RhfSelectField,
|
||||
RhfTextareaField,
|
||||
RhfAsyncSelectField,
|
||||
RhfDateField,
|
||||
} from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
@@ -150,7 +151,7 @@ export function CreditNoteForm({ resourceId, initialData, onSuccess }: CreditNot
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="date" label="Date" type="date" />
|
||||
<RhfDateField name="date" label="Date" required />
|
||||
|
||||
<RhfSelectField
|
||||
name="status"
|
||||
|
||||
@@ -1,21 +1,28 @@
|
||||
import { z } from "zod"
|
||||
import { CreditNoteStatus } from "@garage/api"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const optionalStringMax255Schema = z.preprocess(
|
||||
(value) => (value === "" || value == null ? undefined : value),
|
||||
z.string().max(255, "Must be at most 255 characters").optional(),
|
||||
)
|
||||
|
||||
const creditNoteFormSchema = z.object({
|
||||
// ── Required fields ──
|
||||
subject: z.string().min(1, "Subject is required"),
|
||||
subject: z.string().trim().min(1, "Subject is required").max(255, "Subject must be at most 255 characters"),
|
||||
|
||||
// ── Relations ──
|
||||
customer: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
|
||||
// ── Optional fields ──
|
||||
date: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
date: z.string().min(1, "Date is required").date("Enter a valid date"),
|
||||
status: z.enum(CreditNoteStatus).optional(),
|
||||
notes: z.string().optional(),
|
||||
credit_invoice: optionalStringMax255Schema,
|
||||
})
|
||||
|
||||
type CreditNoteFormValues = z.infer<typeof creditNoteFormSchema>
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -12,6 +14,8 @@ import {
|
||||
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { toast } from "sonner"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { CustomerForm } from "./customer-form"
|
||||
|
||||
type CustomerActionsProps = {
|
||||
customerId: string
|
||||
@@ -20,10 +24,7 @@ type CustomerActionsProps = {
|
||||
export function CustomerActions({ customerId }: CustomerActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/sales/customers/${customerId}/edit`)
|
||||
}
|
||||
const editDialog = useFormDialog("customer-details-edit")
|
||||
|
||||
const handleDelete = async () => {
|
||||
const confirmed = await confirm({
|
||||
@@ -44,6 +45,7 @@ export function CustomerActions({ customerId }: CustomerActionsProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
@@ -51,7 +53,7 @@ export function CustomerActions({ customerId }: CustomerActionsProps) {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<DropdownMenuItem onClick={() => editDialog.open(customerId)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
@@ -61,5 +63,23 @@ export function CustomerActions({ customerId }: CustomerActionsProps) {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
|
||||
<DialogContent className="min-w-xl lg:min-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">Edit Customer</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<CustomerForm
|
||||
resourceId={editDialog.resourceId}
|
||||
onSuccess={() => {
|
||||
editDialog.close()
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -51,13 +51,16 @@ const CUSTOMER_DEFAULT_VALUES: CustomerFormValues = {
|
||||
payment_terms: null,
|
||||
country: null,
|
||||
state: null,
|
||||
salutation: "",
|
||||
salutation: "Mr.",
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
company_name: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
alternate_phone: "",
|
||||
opening_balance: undefined,
|
||||
credit_limit: undefined,
|
||||
website: "",
|
||||
address_line_1: "",
|
||||
address_line_2: "",
|
||||
city: "",
|
||||
@@ -82,6 +85,9 @@ function mapCustomerToFormValues(data: unknown): CustomerFormValues {
|
||||
email: c.email || "",
|
||||
phone: c.phone || "",
|
||||
alternate_phone: c.alternate_phone || "",
|
||||
opening_balance: c.opening_balance ?? undefined,
|
||||
credit_limit: c.credit_limit ?? undefined,
|
||||
website: c.website || "",
|
||||
address_line_1: c.address_line_1 || "",
|
||||
address_line_2: c.address_line_2 || "",
|
||||
city: c.city || "",
|
||||
@@ -96,13 +102,16 @@ function mapFormToPayload(values: CustomerFormValues) {
|
||||
payment_terms_id: toId(values.payment_terms),
|
||||
country_id: toId(values.country),
|
||||
state_id: toId(values.state),
|
||||
salutation: values.salutation || undefined,
|
||||
salutation: values.salutation,
|
||||
first_name: values.first_name,
|
||||
last_name: values.last_name,
|
||||
company_name: values.company_name || undefined,
|
||||
email: values.email || undefined,
|
||||
email: values.email,
|
||||
phone: values.phone || undefined,
|
||||
alternate_phone: values.alternate_phone || undefined,
|
||||
opening_balance: values.opening_balance,
|
||||
credit_limit: values.credit_limit,
|
||||
website: values.website || undefined,
|
||||
address_line_1: values.address_line_1 || undefined,
|
||||
address_line_2: values.address_line_2 || undefined,
|
||||
city: values.city || undefined,
|
||||
@@ -114,7 +123,7 @@ function mapFormToPayload(values: CustomerFormValues) {
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.title||item.name || `#${item.id}`,
|
||||
label: item.title || item.name || `#${item.id}`,
|
||||
})
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label || o.name || `#${o.id}` }
|
||||
@@ -134,6 +143,7 @@ export function CustomerForm({ resourceId, initialData, onSuccess }: CustomerFor
|
||||
mapToFormValues: mapCustomerToFormValues,
|
||||
})
|
||||
|
||||
const { customer_type} = form.watch()
|
||||
const { mutate, error, isPending } = useFormMutation(form, {
|
||||
mutationFn: (values: CustomerFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
@@ -168,6 +178,7 @@ export function CustomerForm({ resourceId, initialData, onSuccess }: CustomerFor
|
||||
{/* Basic Info */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfSelectField
|
||||
required
|
||||
name="salutation"
|
||||
label="Salutation"
|
||||
placeholder="Select salutation"
|
||||
@@ -192,16 +203,27 @@ export function CustomerForm({ resourceId, initialData, onSuccess }: CustomerFor
|
||||
<RhfTextField name="last_name" label="Last Name" placeholder="Doe" required />
|
||||
</div>
|
||||
|
||||
|
||||
{
|
||||
customer_type?.label === "Company" &&
|
||||
<RhfTextField name="company_name" label="Company Name" placeholder="Doe Holdings" />
|
||||
}
|
||||
|
||||
{/* Contact */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="email" label="Email" placeholder="john@example.com" type="email" />
|
||||
<RhfTextField name="email" label="Email" placeholder="john@example.com" type="email" required />
|
||||
<RhfTextField name="phone" label="Phone" placeholder="0501234567" type="tel" />
|
||||
</div>
|
||||
|
||||
<RhfTextField name="alternate_phone" label="Alternate Phone" placeholder="0551234567" type="tel" />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="opening_balance" label="Opening Balance" placeholder="0" type="number" />
|
||||
<RhfTextField name="credit_limit" label="Credit Limit" placeholder="0" type="number" />
|
||||
</div>
|
||||
|
||||
<RhfTextField name="website" label="Website" placeholder="https://example.com" type="url" />
|
||||
|
||||
{/* Relations */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
|
||||
@@ -10,6 +10,30 @@ const relationFieldSchema = z
|
||||
|
||||
type RelationField = z.infer<typeof relationFieldSchema>
|
||||
|
||||
const optionalTrimmedString = (max: number) =>
|
||||
z.preprocess(
|
||||
(value) => {
|
||||
if (typeof value !== "string") {
|
||||
return value
|
||||
}
|
||||
|
||||
const trimmed = value.trim()
|
||||
return trimmed === "" ? undefined : trimmed
|
||||
},
|
||||
z.string().max(max).optional(),
|
||||
)
|
||||
|
||||
const optionalInteger = z.preprocess(
|
||||
(value) => {
|
||||
if (value === "" || value == null) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return Number(value)
|
||||
},
|
||||
z.number().int().optional(),
|
||||
)
|
||||
|
||||
const customerFormSchema = z.object({
|
||||
// ── Relations (stored as objects, mapped to IDs on submit) ──
|
||||
customer_type: relationFieldSchema.refine((val) => !!val?.value, "Customer type is required"),
|
||||
@@ -19,23 +43,32 @@ const customerFormSchema = z.object({
|
||||
state: relationFieldSchema,
|
||||
|
||||
// ── Basic info ──
|
||||
salutation: z.string().optional(),
|
||||
first_name: z.string().min(1, "First name is required"),
|
||||
last_name: z.string().min(1, "Last name is required"),
|
||||
company_name: z.string().optional(),
|
||||
salutation: z.string().trim().min(1, "Salutation is required").max(50, "Salutation cannot exceed 50 characters"),
|
||||
first_name: z.string().trim().min(1, "First name is required").max(50, "First name cannot exceed 50 characters"),
|
||||
last_name: z.string().trim().min(1, "Last name is required").max(50, "Last name cannot exceed 50 characters"),
|
||||
company_name: optionalTrimmedString(50),
|
||||
|
||||
// ── Contact ──
|
||||
email: z
|
||||
.union([z.string().email("Enter a valid email address"), z.literal("")])
|
||||
.optional(),
|
||||
phone: z.string().optional(),
|
||||
alternate_phone: z.string().optional(),
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, "Email is required")
|
||||
.email("Enter a valid email address")
|
||||
.max(100, "Email cannot exceed 100 characters"),
|
||||
phone: optionalTrimmedString(20),
|
||||
alternate_phone: optionalTrimmedString(20),
|
||||
opening_balance: optionalInteger,
|
||||
credit_limit: optionalInteger,
|
||||
website: optionalTrimmedString(255).refine(
|
||||
(value) => !value || z.string().url().safeParse(value).success,
|
||||
"Enter a valid website URL",
|
||||
),
|
||||
|
||||
// ── Address ──
|
||||
address_line_1: z.string().optional(),
|
||||
address_line_2: z.string().optional(),
|
||||
city: z.string().optional(),
|
||||
zip_code: z.string().optional(),
|
||||
address_line_1: optionalTrimmedString(255),
|
||||
address_line_2: optionalTrimmedString(255),
|
||||
city: optionalTrimmedString(100),
|
||||
zip_code: optionalTrimmedString(20),
|
||||
})
|
||||
|
||||
type CustomerFormValues = z.infer<typeof customerFormSchema>
|
||||
|
||||
@@ -21,21 +21,29 @@ import { toRelation, toId } from "@/shared/lib/utils"
|
||||
import {
|
||||
employeeFormSchema,
|
||||
type EmployeeFormValues,
|
||||
STATUS_OPTIONS,
|
||||
TYPE_OPTIONS,
|
||||
WAGE_TYPE_OPTIONS,
|
||||
} from "./employee.schema"
|
||||
import { EMPLOYEE_ROUTES, DEPARTMENT_ROUTES, SHOP_TIMING_ROUTES, SHOP_CALENDAR_ROUTES, EmployeeType } from "@garage/api"
|
||||
import { EMPLOYEE_ROUTES, DEPARTMENT_ROUTES, SHOP_TIMING_ROUTES, SHOP_CALENDAR_ROUTES, GEO_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: "active", label: "Active" },
|
||||
{ value: "inactive", label: "Inactive" },
|
||||
]
|
||||
|
||||
const TYPE_OPTIONS = EmployeeType.map((v) => ({
|
||||
const STATUS_SELECT_OPTIONS = STATUS_OPTIONS.map((v) => ({
|
||||
value: v,
|
||||
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
}))
|
||||
|
||||
const TYPE_SELECT_OPTIONS = TYPE_OPTIONS.map((v) => ({
|
||||
value: v,
|
||||
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
}))
|
||||
|
||||
const WAGE_TYPE_SELECT_OPTIONS = WAGE_TYPE_OPTIONS.map((v) => ({
|
||||
value: v,
|
||||
label: v,
|
||||
}))
|
||||
|
||||
// ── Props ──
|
||||
|
||||
export type EmployeeFormProps = {
|
||||
@@ -48,18 +56,23 @@ export type EmployeeFormProps = {
|
||||
|
||||
const DEFAULT_VALUES: EmployeeFormValues = {
|
||||
department: null,
|
||||
country: null,
|
||||
shop_calender: null,
|
||||
shop_timing: null,
|
||||
role_id: null,
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
email: "",
|
||||
password: "",
|
||||
phone: "",
|
||||
position: "",
|
||||
designation: "",
|
||||
salary: null,
|
||||
wage_type: null,
|
||||
status: "active",
|
||||
type: "employee",
|
||||
track_attendance: true,
|
||||
notify_owner_when_punch_in_out: false,
|
||||
geo_fence_radius: 100,
|
||||
geo_fence_radius: null,
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
@@ -69,36 +82,46 @@ function mapToFormValues(data: unknown): EmployeeFormValues {
|
||||
|
||||
return {
|
||||
department: toRelation(d.department_id, d.department?.name),
|
||||
country: toRelation(d.country_id, d.country?.name),
|
||||
shop_calender: toRelation(d.shop_calender_id, d.shop_calender?.title),
|
||||
shop_timing: toRelation(d.shop_timing_id, d.shop_timing?.title),
|
||||
role_id: d.role_id ? Number(d.role_id) : null,
|
||||
first_name: d.first_name || "",
|
||||
last_name: d.last_name || "",
|
||||
email: d.email || "",
|
||||
password: "",
|
||||
phone: d.phone || "",
|
||||
position: d.position || "",
|
||||
designation: d.designation || "",
|
||||
salary: d.salary ?? null,
|
||||
wage_type: d.wage_type ?? null,
|
||||
status: d.status || "active",
|
||||
type: d.type || "employee",
|
||||
track_attendance: d.track_attendance ?? true,
|
||||
notify_owner_when_punch_in_out: d.notify_owner_when_punch_in_out ?? false,
|
||||
geo_fence_radius: d.geo_fence_radius ?? 100,
|
||||
geo_fence_radius: d.geo_fence_radius ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormToPayload(values: EmployeeFormValues) {
|
||||
return {
|
||||
department_id: toId(values.department),
|
||||
country_id: toId(values.country),
|
||||
shop_calender_id: toId(values.shop_calender),
|
||||
shop_timing_id: toId(values.shop_timing),
|
||||
role_id: values.role_id ?? undefined,
|
||||
first_name: values.first_name,
|
||||
last_name: values.last_name,
|
||||
email: values.email || undefined,
|
||||
email: values.email,
|
||||
password: values.password,
|
||||
phone: values.phone || undefined,
|
||||
position: values.position || undefined,
|
||||
status: values.status || undefined,
|
||||
type: values.type || undefined,
|
||||
designation: values.designation || undefined,
|
||||
salary: values.salary ?? undefined,
|
||||
wage_type: values.wage_type ?? undefined,
|
||||
status: values.status,
|
||||
type: values.type,
|
||||
track_attendance: values.track_attendance,
|
||||
notify_owner_when_punch_in_out: values.notify_owner_when_punch_in_out,
|
||||
geo_fence_radius: values.geo_fence_radius,
|
||||
geo_fence_radius: values.geo_fence_radius ?? undefined,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,11 +188,15 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="email" label="Email" placeholder="jane@example.com" type="email" />
|
||||
<RhfTextField name="phone" label="Phone" placeholder="0501234567" type="tel" />
|
||||
<RhfTextField name="password" label="Password" placeholder="At least 6 characters" type="password" required />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="phone" label="Phone" placeholder="0501234567" type="tel" />
|
||||
<RhfTextField name="designation" label="Designation" placeholder="Technician" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="position" label="Position" placeholder="Technician" />
|
||||
<RhfAsyncSelectField
|
||||
name="department"
|
||||
label="Department"
|
||||
@@ -179,6 +206,7 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfTextField name="role_id" label="Role ID" placeholder="1" type="number" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
@@ -186,17 +214,36 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
||||
name="status"
|
||||
label="Status"
|
||||
placeholder="Select status"
|
||||
options={STATUS_OPTIONS}
|
||||
options={STATUS_SELECT_OPTIONS}
|
||||
/>
|
||||
<RhfSelectField
|
||||
name="type"
|
||||
label="Type"
|
||||
placeholder="Select type"
|
||||
options={TYPE_OPTIONS}
|
||||
options={TYPE_SELECT_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="salary" label="Salary" placeholder="0" type="number" />
|
||||
<RhfSelectField
|
||||
name="wage_type"
|
||||
label="Wage Type"
|
||||
placeholder="Select wage type"
|
||||
options={WAGE_TYPE_SELECT_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="country"
|
||||
label="Country"
|
||||
placeholder="Select country"
|
||||
queryKey={[GEO_ROUTES.COUNTRIES]}
|
||||
listFn={() => api.geo.countries()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfAsyncSelectField
|
||||
name="shop_calender"
|
||||
label="Shop Calendar"
|
||||
|
||||
@@ -1,33 +1,56 @@
|
||||
import { z } from "zod"
|
||||
import { EmployeeType } from "@garage/api"
|
||||
import { EmployeeType, WageType } from "@garage/api"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const optionalNumericField = z.preprocess(
|
||||
(value) => {
|
||||
if (value === "" || value === null || value === undefined) {
|
||||
return null
|
||||
}
|
||||
return Number(value)
|
||||
},
|
||||
z.number().finite().nullable(),
|
||||
)
|
||||
|
||||
const optionalIntegerIdField = z.preprocess(
|
||||
(value) => {
|
||||
if (value === "" || value === null || value === undefined) {
|
||||
return null
|
||||
}
|
||||
return Number(value)
|
||||
},
|
||||
z.number().int().positive().nullable(),
|
||||
)
|
||||
|
||||
const STATUS_OPTIONS = ["active", "inactive"] as const
|
||||
const TYPE_OPTIONS = EmployeeType
|
||||
const WAGE_TYPE_OPTIONS = WageType
|
||||
|
||||
const employeeFormSchema = z.object({
|
||||
department: relationFieldSchema,
|
||||
country: relationFieldSchema,
|
||||
shop_calender: relationFieldSchema,
|
||||
shop_timing: relationFieldSchema,
|
||||
first_name: z.string().min(1, "First name is required"),
|
||||
last_name: z.string().min(1, "Last name is required"),
|
||||
email: z.union([
|
||||
z.string().email("Enter a valid email address"),
|
||||
z.literal(""),
|
||||
]).optional(),
|
||||
phone: z.string().optional(),
|
||||
position: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
type: z.string().optional(),
|
||||
role_id: optionalIntegerIdField,
|
||||
first_name: z.string().trim().min(1, "First name is required").max(50, "First name must be at most 50 characters"),
|
||||
last_name: z.string().trim().min(1, "Last name is required").max(50, "Last name must be at most 50 characters"),
|
||||
email: z.string().trim().min(1, "Email is required").email("Enter a valid email address").max(100, "Email must be at most 100 characters"),
|
||||
password: z.string().min(6, "Password must be at least 6 characters"),
|
||||
phone: z.string().trim().max(30, "Phone must be at most 30 characters").optional().or(z.literal("")),
|
||||
designation: z.string().trim().max(50, "Designation must be at most 50 characters").optional().or(z.literal("")),
|
||||
salary: optionalNumericField,
|
||||
wage_type: z.enum(WAGE_TYPE_OPTIONS).nullable(),
|
||||
status: z.enum(STATUS_OPTIONS),
|
||||
type: z.enum(TYPE_OPTIONS),
|
||||
track_attendance: z.boolean(),
|
||||
notify_owner_when_punch_in_out: z.boolean(),
|
||||
geo_fence_radius: z.coerce.number().min(0).optional(),
|
||||
geo_fence_radius: optionalNumericField,
|
||||
})
|
||||
|
||||
type EmployeeFormValues = z.infer<typeof employeeFormSchema>
|
||||
|
||||
export { employeeFormSchema, relationFieldSchema, STATUS_OPTIONS, TYPE_OPTIONS }
|
||||
export { employeeFormSchema, relationFieldSchema, STATUS_OPTIONS, TYPE_OPTIONS, WAGE_TYPE_OPTIONS }
|
||||
export type { EmployeeFormValues }
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import { Ellipsis, Pencil, Trash2, ShieldCheck, Check, X } 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"
|
||||
@@ -33,6 +33,8 @@ import { ESTIMATE_ROUTES } from "@garage/api"
|
||||
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
|
||||
@@ -131,8 +133,10 @@ function SectionHeading({ title }: { title: string }) {
|
||||
export function EstimateActions({ estimateId }: EstimateActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
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)
|
||||
@@ -218,6 +222,14 @@ export function EstimateActions({ estimateId }: EstimateActionsProps) {
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => print("estimate", estimateId, "print")} disabled={isPrinting}>
|
||||
<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
|
||||
@@ -229,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">
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
RhfAsyncSelectField,
|
||||
RhfDateField,
|
||||
RhfAutoGenerateField,
|
||||
RhfSelectField,
|
||||
RhfTextareaField,
|
||||
} from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
@@ -22,11 +24,12 @@ import {
|
||||
estimateFormSchema,
|
||||
type EstimateFormValues,
|
||||
} from "./estimate.schema"
|
||||
import { ESTIMATE_ROUTES, DEPARTMENT_ROUTES } from "@garage/api"
|
||||
import { ESTIMATE_ROUTES, DEPARTMENT_ROUTES, INSURANCE_TYPE_ROUTES, DiscountType } from "@garage/api"
|
||||
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
|
||||
import { RhfVehicleSelectField } from "@/modules/vehicles/rhf-vehicle-select-field"
|
||||
import { RhfLabelPickerField, type LabelItem } from "@/modules/labels/rhf-label-picker-field"
|
||||
import { RhfCustomerRemarksField } from "./rhf-customer-remarks-field"
|
||||
import { RhfEmployeeSelectField } from "@/modules/employees/rhf-employee-select-field"
|
||||
|
||||
// ── Props ──
|
||||
|
||||
@@ -44,26 +47,72 @@ const DEFAULT_VALUES: EstimateFormValues = {
|
||||
customer: null,
|
||||
vehicle: null,
|
||||
department: null,
|
||||
insurance_type: null,
|
||||
insurer: null,
|
||||
service_writer: null,
|
||||
estimate_number: "",
|
||||
date: "",
|
||||
has_insurance: false,
|
||||
enable_digital_authorisation: false,
|
||||
footer: "",
|
||||
discount: "no",
|
||||
discount_amount: undefined,
|
||||
remarks: [],
|
||||
labels: [],
|
||||
}
|
||||
|
||||
// ── 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),
|
||||
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?.id,
|
||||
d.insurer_name ?? customerLabel(d.insurer),
|
||||
),
|
||||
service_writer: toRelation(
|
||||
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] : "",
|
||||
has_insurance: d.has_insurance ?? false,
|
||||
enable_digital_authorisation: d.enable_digital_authorisation ?? false,
|
||||
footer: d.footer ?? "",
|
||||
discount: d.discount ?? d.discount_type ?? "no",
|
||||
discount_amount: d.discount_amount != null ? Number(d.discount_amount) : undefined,
|
||||
remarks: Array.isArray(d.remarks)
|
||||
? d.remarks.map((r: any) => (typeof r === "string" ? r : (r?.remark ?? ""))).filter(Boolean)
|
||||
: [],
|
||||
@@ -81,9 +130,16 @@ function mapFormToPayload(values: EstimateFormValues) {
|
||||
customer_id: toId(values.customer),
|
||||
vehicle_id: toId(values.vehicle),
|
||||
department_id: toId(values.department),
|
||||
insurance_type_id: values.insurance_type ? String(toId(values.insurance_type)) : null,
|
||||
insurer_id: toId(values.insurer),
|
||||
service_writer_id: toId(values.service_writer),
|
||||
estimate_number: values.estimate_number || undefined,
|
||||
date: values.date || undefined,
|
||||
has_insurance: values.has_insurance,
|
||||
enable_digital_authorisation: values.enable_digital_authorisation,
|
||||
footer: values.footer || undefined,
|
||||
discount: values.discount || undefined,
|
||||
discount_amount: values.discount_amount,
|
||||
remarks: values.remarks?.filter(Boolean) ?? [],
|
||||
label_ids: values.labels?.map((l) => l.id) ?? [],
|
||||
}
|
||||
@@ -98,17 +154,23 @@ const mapLookupOption = (item: any) => ({
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
const DISCOUNT_OPTIONS = DiscountType.map((value) => ({
|
||||
value,
|
||||
label: value.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
}))
|
||||
|
||||
// ── Component ──
|
||||
|
||||
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,
|
||||
})
|
||||
|
||||
@@ -116,8 +178,8 @@ export function EstimateForm({ resourceId, initialData, onSuccess }: EstimateFor
|
||||
mutationFn: (values: EstimateFormValues) => {
|
||||
const payload = mapFormToPayload(values)
|
||||
const promise = (isEditing && resourceId
|
||||
? api.estimates.update(resourceId, payload)
|
||||
: api.estimates.create(payload)) as Promise<any>
|
||||
? api.estimates.update(resourceId, payload as any)
|
||||
: api.estimates.create(payload as any)) as Promise<any>
|
||||
toast.promise(promise, {
|
||||
loading: isEditing ? "Updating estimate..." : "Creating estimate...",
|
||||
success: isEditing ? "Estimate updated successfully" : "Estimate created successfully",
|
||||
@@ -126,7 +188,7 @@ export function EstimateForm({ resourceId, initialData, onSuccess }: EstimateFor
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset()
|
||||
if (!isEditing) form.reset()
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
@@ -149,8 +211,8 @@ export function EstimateForm({ resourceId, initialData, onSuccess }: EstimateFor
|
||||
<RhfTextField name="title" label="Title" placeholder="Estimate title" required />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfCustomerSelectField name="customer" />
|
||||
<RhfVehicleSelectField name="vehicle" />
|
||||
<RhfCustomerSelectField name="customer" required />
|
||||
<RhfVehicleSelectField name="vehicle" required />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
@@ -164,11 +226,39 @@ export function EstimateForm({ resourceId, initialData, onSuccess }: EstimateFor
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfDateField name="date" label="Date" />
|
||||
<RhfAutoGenerateField autoFetch name="estimate_number" label="Estimate#" placeholder="EST-001" table="estimates" />
|
||||
<RhfAutoGenerateField autoFetch name="estimate_number" label="Estimate#" placeholder="EST-001" table="estimates" required />
|
||||
</div>
|
||||
|
||||
<RhfCheckboxField name="has_insurance" label="Has Insurance" />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<RhfAsyncSelectField
|
||||
name="insurance_type"
|
||||
label="Insurance Type"
|
||||
placeholder="Select insurance type"
|
||||
queryKey={[INSURANCE_TYPE_ROUTES.INDEX]}
|
||||
listFn={() => api.insuranceTypes.list()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfCustomerSelectField
|
||||
name="insurer"
|
||||
label="Insurer"
|
||||
placeholder="Search insurer..."
|
||||
customerType="Insurer"
|
||||
/>
|
||||
<RhfEmployeeSelectField name="service_writer" label="Service Writer" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfSelectField name="discount" label="Discount" options={DISCOUNT_OPTIONS} />
|
||||
<RhfTextField name="discount_amount" label="Discount Amount" type="number" placeholder="0.00" />
|
||||
</div>
|
||||
|
||||
<RhfCheckboxField name="enable_digital_authorisation" label="Enable Digital Authorisation" />
|
||||
|
||||
<RhfTextareaField name="footer" label="Footer" placeholder="Footer notes for this estimate" />
|
||||
|
||||
<RhfCustomerRemarksField name="remarks" />
|
||||
|
||||
<Button type="submit" variant="default" disabled={isPending}>
|
||||
|
||||
@@ -168,6 +168,7 @@ export function EstimatePartsSection({ estimateId }: { estimateId: string }) {
|
||||
onOpenChange={setPickerOpen}
|
||||
selectionMode="single"
|
||||
onConfirm={handlePickerConfirm}
|
||||
searchPlaceholder="Search parts by title, SKU, or part number..."
|
||||
crudProps={{
|
||||
routeKey: PARTS_ROUTES.INDEX,
|
||||
getClient: (api) => api.parts,
|
||||
|
||||
@@ -181,6 +181,7 @@ export function EstimateServicesSection({ estimateId }: { estimateId: string })
|
||||
onOpenChange={setPickerOpen}
|
||||
selectionMode="single"
|
||||
onConfirm={handlePickerConfirm}
|
||||
searchPlaceholder="Search services..."
|
||||
crudProps={{
|
||||
routeKey: SERVICE_ROUTES.INDEX,
|
||||
getClient: (api) => api.services,
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import { formatCurrency, formatEnum } from "@/shared/utils/formatters"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
import { useEstimate } from "./estimate-context"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
export function EstimateTotalsSummary() {
|
||||
const estimate = useEstimate()
|
||||
@@ -39,19 +40,19 @@ export function EstimateTotalsSummary() {
|
||||
{parts.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Parts ({parts.length})</span>
|
||||
<span>{formatCurrency(lineTotal(parts))}</span>
|
||||
<span>{<Money value={lineTotal(parts)} />}</span>
|
||||
</div>
|
||||
)}
|
||||
{services.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Services ({services.length})</span>
|
||||
<span>{formatCurrency(lineTotal(services))}</span>
|
||||
<span>{<Money value={lineTotal(services)} />}</span>
|
||||
</div>
|
||||
)}
|
||||
{expenses.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Expenses ({expenses.length})</span>
|
||||
<span>{formatCurrency(lineTotal(expenses))}</span>
|
||||
<span>{<Money value={lineTotal(expenses)} />}</span>
|
||||
</div>
|
||||
)}
|
||||
<Separator />
|
||||
@@ -60,7 +61,7 @@ export function EstimateTotalsSummary() {
|
||||
|
||||
<div className="flex justify-between text-sm font-medium">
|
||||
<span>Subtotal</span>
|
||||
<span>{formatCurrency(subTotal)}</span>
|
||||
<span>{<Money value={subTotal} />}</span>
|
||||
</div>
|
||||
|
||||
{discount && discount !== "no" && (
|
||||
@@ -74,7 +75,7 @@ export function EstimateTotalsSummary() {
|
||||
|
||||
<div className="flex justify-between text-base font-semibold">
|
||||
<span>Total</span>
|
||||
<span>{formatCurrency(displayTotal)}</span>
|
||||
<span>{<Money value={displayTotal} />}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@@ -1,22 +1,49 @@
|
||||
import { z } from "zod"
|
||||
import { DiscountType } from "@garage/api"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const requiredRelationFieldSchema = relationFieldSchema.superRefine((value, ctx) => {
|
||||
if (!value) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "This field is required",
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const optionalNumberSchema = z.preprocess(
|
||||
(value) => (value === "" || value == null ? undefined : value),
|
||||
z.coerce.number().min(0).optional(),
|
||||
)
|
||||
|
||||
const optionalDateSchema = z.preprocess(
|
||||
(value) => (value === "" || value == null ? undefined : value),
|
||||
z.string().date().optional(),
|
||||
)
|
||||
|
||||
const estimateFormSchema = z.object({
|
||||
// ── Required fields ──
|
||||
title: z.string().min(1, "Title is required"),
|
||||
title: z.string().trim().min(1, "Title is required").max(255, "Title must be at most 255 characters"),
|
||||
|
||||
// ── Relations ──
|
||||
customer: relationFieldSchema,
|
||||
vehicle: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
customer: requiredRelationFieldSchema,
|
||||
vehicle: requiredRelationFieldSchema,
|
||||
department: requiredRelationFieldSchema,
|
||||
insurance_type: relationFieldSchema,
|
||||
insurer: relationFieldSchema,
|
||||
service_writer: relationFieldSchema,
|
||||
|
||||
// ── Optional fields ──
|
||||
estimate_number: z.string().optional(),
|
||||
date: z.string().optional(),
|
||||
has_insurance: z.boolean().default(false),
|
||||
estimate_number: z.string().trim().min(1, "Estimate number is required").max(255, "Estimate number must be at most 255 characters"),
|
||||
date: optionalDateSchema,
|
||||
has_insurance: z.boolean().optional(),
|
||||
enable_digital_authorisation: z.boolean().optional(),
|
||||
footer: z.string().optional(),
|
||||
discount: z.enum(DiscountType).optional(),
|
||||
discount_amount: optionalNumberSchema,
|
||||
|
||||
// ── Remarks (array of strings) ──
|
||||
remarks: z.array(z.string()).optional(),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -5,14 +5,14 @@ export const relationFieldSchema = z
|
||||
.nullable()
|
||||
|
||||
export const expenseItemFormSchema = z.object({
|
||||
item_type: z.string().min(1, "Item type is required"),
|
||||
item_name: z.string().min(1, "Item name is required"),
|
||||
sku: z.string().optional(),
|
||||
item_type: z.string().min(1, "Item type is required").max(255, "Item type cannot exceed 255 characters"),
|
||||
item_name: z.string().min(1, "Item name is required").max(255, "Item name cannot exceed 255 characters"),
|
||||
sku: z.string().min(1, "SKU is required").max(255, "SKU cannot exceed 255 characters"),
|
||||
item_code: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
category: relationFieldSchema,
|
||||
unit_type: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
category: relationFieldSchema.refine((val) => !!val?.value, "Category is required"),
|
||||
unit_type: relationFieldSchema.refine((val) => !!val?.value, "Unit type is required"),
|
||||
department: relationFieldSchema.refine((val) => !!val?.value, "Department is required"),
|
||||
// Purchase
|
||||
purchase_information: z.boolean().default(true),
|
||||
purchase_price: z.coerce.number().min(0).optional(),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -10,6 +12,8 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { ExpenseForm } from "./expense-form"
|
||||
|
||||
type ExpenseActionsProps = {
|
||||
expenseId: string
|
||||
@@ -18,10 +22,7 @@ type ExpenseActionsProps = {
|
||||
export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/purchase/expense/${expenseId}/edit`)
|
||||
}
|
||||
const editDialog = useFormDialog("expense-details-edit")
|
||||
|
||||
const handleDelete = async () => {
|
||||
await api.expenses.destroy(expenseId)
|
||||
@@ -29,6 +30,7 @@ export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
@@ -36,7 +38,7 @@ export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<DropdownMenuItem onClick={() => editDialog.open(expenseId)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
@@ -46,5 +48,23 @@ export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
|
||||
<DialogContent className="min-w-xl lg:min-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">Edit Expense</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<ExpenseForm
|
||||
resourceId={editDialog.resourceId}
|
||||
onSuccess={() => {
|
||||
editDialog.close()
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user