This commit is contained in:
2026-04-01 15:34:50 +03:00
parent 13b56d4960
commit 5f3d208158
120 changed files with 36338 additions and 21265 deletions
@@ -0,0 +1,144 @@
"use client"
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 { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { VehicleDocumentForm } from "@/modules/vehicles/vehicle-document-form"
type VehicleDocument = {
id: number
name: string
created_at: string
updated_at: string
}
export default function VehicleDocumentsPage() {
const { id: vehicleId } = useParams<{ id: string }>()
const api = useAuthApi()
const queryClient = useQueryClient()
const [dialogOpen, setDialogOpen] = useState(false)
const queryKey = ["vehicle-documents", vehicleId]
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.vehicleDocuments.listDocuments({ vehicle_id: vehicleId }),
})
const deleteMutation = useMutation({
mutationFn: (id: number) => api.vehicleDocuments.destroyDocument(String(id)),
onSuccess: () => {
toast.success("Document deleted successfully.")
queryClient.invalidateQueries({ queryKey })
},
onError: () => {
toast.error("Failed to delete document.")
},
})
const handleDelete = async (doc: VehicleDocument) => {
const confirmed = await confirm({
title: "Delete Document",
description: `Are you sure you want to delete "${doc.name}"?`,
confirmLabel: "Delete",
variant: "destructive",
})
if (confirmed) {
deleteMutation.mutate(doc.id)
}
}
const columns: ColumnDef<VehicleDocument>[] = [
{
accessorKey: "name",
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
},
{
accessorKey: "created_at",
header: ({ column }) => <ColumnHeader column={column} title="Uploaded At" />,
cell: ({ getValue }) => {
const val = getValue<string>()
return val ? new Date(val).toLocaleDateString() : "—"
},
},
{
id: "actions",
header: () => <span className="sr-only">Actions</span>,
cell: ({ row }) => (
<Button
variant="ghost"
size="icon-sm"
onClick={() => handleDelete(row.original)}
title="Delete document"
>
<Trash2 className="size-4 text-destructive" />
</Button>
),
enableSorting: false,
},
]
const documents = (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,
}
return (
<div className="flex flex-col gap-4">
<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={() => {}}
isLoading={isLoading}
/>
</CardContent>
</Card>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="min-w-xl">
<DialogHeader>
<DialogTitle>Upload Document</DialogTitle>
</DialogHeader>
<VehicleDocumentForm
vehicleId={vehicleId}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey })
setDialogOpen(false)
}}
/>
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,102 @@
"use client"
import { use } 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 { EstimateForm } from '@/modules/estimates/estimate-form'
import { ESTIMATE_ROUTES } from '@garage/api'
import type { EstimatesClient } from '@garage/api'
import { FileTextIcon } from 'lucide-react'
import { useVehicle } from '@/modules/vehicles/vehicle-context'
type EstimateItem = {
id: number
title?: string
estimate_number?: string
date?: string
customer_name?: string
has_insurance?: boolean
created_at?: string
}
export default function VehicleEstimatesPage({ params }: { params: Promise<{ id: string }> }) {
const { id: vehicleId } = use(params)
const vehicle = useVehicle()
return (
<>
<ResourcePage<EstimatesClient>
toolbar={({ invalidateQuery, selectedItem, closeDialog }) => (
<FormDialog title="Estimate">
{(resourceId) => (
<EstimateForm
resourceId={resourceId}
initialData={{
vehicle: vehicle ? { value: vehicle.id, label: vehicle.label } : null,
}}
onSuccess={() => {
closeDialog();
invalidateQuery();
}}
/>
)}
</FormDialog>
)
}
pageTitle="Vehicle Estimates"
routeKey={ESTIMATE_ROUTES.INDEX}
getClient={(api) => api.estimates}
extraParams={{ vehicle_id: vehicleId }}
header={
null
}
columns={({ actionsColumn }) => [
{
accessorKey: "title",
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
cell: ({ row }) => {
const item = row.original as unknown as EstimateItem
return (
<div className="flex items-center gap-2">
<FileTextIcon className="text-muted-foreground h-4 w-4" />
<span>{item.title}</span>
</div>
)
},
},
{
accessorKey: "estimate_number",
header: ({ column }) => <ColumnHeader column={column} title="Estimate #" />,
},
{
accessorKey: "customer_name",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
},
{
accessorKey: "date",
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
},
{
accessorKey: "has_insurance",
header: ({ column }) => <ColumnHeader column={column} title="Insurance" />,
cell: ({ row }) => {
const item = row.original as unknown as EstimateItem
return item.has_insurance ? "Yes" : "No"
},
},
{
accessorKey: "created_at",
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
cell: ({ row }) => {
const item = row.original as unknown as EstimateItem
return item.created_at ? new Date(item.created_at).toLocaleDateString() : "—"
},
},
actionsColumn(),
]}
/>
</>
)
}
@@ -0,0 +1,50 @@
import { DashboardDetailsPageLayoutProps, DashboardDetailsPage } from '@/base/components/layout/dashboard'
import { getServerApi } from '@garage/api/server'
import { VehicleActions } from '@/modules/vehicles/vehicle-actions'
import { Car } from 'lucide-react'
import React from 'react'
import { CONSTANTS } from '@/config/constants'
export default async function layout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
const { id } = await props.params
const api = await getServerApi()
const vehicle = await api.vehicles.getById(id)
const title = `${vehicle.data?.make || ''} ${vehicle.data?.model || ''}`.trim() || 'Vehicle Details'
return (
<>
<DashboardDetailsPage
className='p-0 lg:p-0'
avatarSrc={vehicle.data?.image_url || ""}
// avatarSrc={vehicle.data?.image_url || ""}
title={title}
description={vehicle.data?.license_plate ? `License Plate: ${vehicle.data.license_plate}` : undefined}
backHref="/sales/vehicles"
actions={<VehicleActions vehicleId={id} />}
tabs={[
{
href: `/sales/vehicles/${id}`,
label: 'Details'
},
{
href: `/sales/vehicles/${id}/owners`,
label: 'Owners'
},
{
href: `/sales/vehicles/${id}/documents`,
label: "Documents"
},
{
href: `/sales/vehicles/${id}/mileage`,
label: "Mileage"
},
{
href: `/sales/vehicles/${id}/estimates`,
label: "Estimates"
}
]}
>
{props.children}
</DashboardDetailsPage>
</>
)
}
@@ -0,0 +1,191 @@
"use client"
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, Pencil, Trash2, MoreHorizontal } from "lucide-react"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { MileageForm } from "@/modules/vehicles/mileage-form"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
type MileageRecord = {
id: number
name: string
created_at: string
updated_at: string
}
export default function VehicleMileagePage() {
const { id: vehicleId } = useParams<{ id: string }>()
const api = useAuthApi()
const queryClient = useQueryClient()
const [dialogOpen, setDialogOpen] = useState(false)
const [editItem, setEditItem] = useState<MileageRecord | null>(null)
const queryKey = ["vehicle-mileage", vehicleId]
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.vehicleDocuments.listMileage({ vehicle_id: vehicleId }),
})
const deleteMutation = useMutation({
mutationFn: (id: number) => {
const promise = api.vehicleDocuments.destroyMileage(String(id))
toast.promise(promise, {
loading: "Deleting...",
success: "Mileage record deleted successfully.",
error: "Failed to delete mileage record.",
})
return promise
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey })
},
})
const handleDelete = async (record: MileageRecord) => {
const confirmed = await confirm({
title: "Delete Mileage Record",
description: `Are you sure you want to delete this mileage record?`,
confirmLabel: "Delete",
variant: "destructive",
})
if (confirmed) {
deleteMutation.mutate(record.id)
}
}
const handleEdit = (record: MileageRecord) => {
setEditItem(record)
setDialogOpen(true)
}
const handleCreate = () => {
setEditItem(null)
setDialogOpen(true)
}
const columns: ColumnDef<MileageRecord>[] = [
{
accessorKey: "name",
header: ({ column }) => <ColumnHeader column={column} title="Mileage" />,
},
{
accessorKey: "created_at",
header: ({ column }) => <ColumnHeader column={column} title="Recorded At" />,
cell: ({ getValue }) => {
const val = getValue<string>()
return val ? new Date(val).toLocaleDateString() : "—"
},
},
{
id: "actions",
header: () => <span className="sr-only">Actions</span>,
cell: ({ row }) => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreHorizontal className="size-4" />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => handleEdit(row.original)}>
<Pencil className="size-3.5 text-muted-foreground" />
Edit
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => handleDelete(row.original)}
>
<Trash2 className="size-3.5" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
enableSorting: false,
},
]
const records = (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,
}
return (
<div className="flex flex-col gap-4">
<DashboardPage
header={null}
toolbar={
<Button onClick={handleCreate}>
<Plus className="size-4" />
Add Mileage
</Button>
}
title='Milage'
>
<Card>
<CardContent>
<DataTable
columns={columns}
data={records}
pagination={pagination}
sorting={[]}
onChange={() => {}}
isLoading={isLoading}
/>
</CardContent>
</Card>
</DashboardPage>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="min-w-md">
<DialogHeader>
<DialogTitle>
{editItem ? "Edit Mileage" : "Add Mileage"}
</DialogTitle>
</DialogHeader>
<MileageForm
vehicleId={vehicleId}
resourceId={editItem ? String(editItem.id) : null}
initialData={editItem}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey })
setDialogOpen(false)
setEditItem(null)
}}
/>
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,240 @@
"use client"
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 { Unlink, Plus, Loader2 } from "lucide-react"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { DataTable } from "@/shared/data-view/table-view"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { RhfAsyncSelectField } from "@/shared/components/form"
import { Rhform } from "@/shared/components/form"
import { useForm } from "react-hook-form"
import { TableCell, TableRow } from "@/shared/components/ui/table"
import { ApiResponse, CustomersClient } from "@garage/api"
import { paths } from "@garage/api/types"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
type Owner = {
id: number
name: string
created_at: string
updated_at: string
}
const mapCustomerOption = (item: any) => ({
value: String(item.id),
label: `${item.first_name ?? ""} ${item.last_name ?? ""}`.trim() || item.name || `Customer #${item.id}`,
})
const STORE_OBJECT = {
getOptionValue: (o: any) => o,
getOptionLabel: (o: any) => o.label,
}
export default function VehicleOwnersPage() {
const { id: vehicleId } = useParams<{ id: string }>()
const api = useAuthApi()
const queryClient = useQueryClient()
const [linkDialogOpen, setLinkDialogOpen] = useState(false)
const queryKey = ["vehicle-owners", vehicleId]
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.vehicles.getOwners(vehicleId),
})
const unlinkMutation = useMutation({
mutationFn: (customerId: number) =>
api.vehicles.unlinkCustomer({ customer_id: customerId, vehicle_id: Number(vehicleId) }),
onSuccess: () => {
toast.success("Owner unlinked successfully.")
queryClient.invalidateQueries({ queryKey })
},
onError: () => {
toast.error("Failed to unlink owner.")
},
})
const handleUnlink = async (owner: Owner) => {
const confirmed = await confirm({
title: "Unlink Owner",
description: `Are you sure you want to unlink "${owner.name}" from this vehicle?`,
confirmLabel: "Unlink",
variant: "destructive",
})
if (confirmed) {
unlinkMutation.mutate(owner.id)
}
}
const columns: ColumnDef<any>[] = [
{
accessorKey: "first_name",
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
},
{
accessorKey: "phone",
header: ({ column }) => <ColumnHeader column={column} title="Phone" />,
},
{
accessorKey: "created_at",
header: ({ column }) => <ColumnHeader column={column} title="Linked At" />,
cell: ({ getValue }) => {
const val = getValue<string>()
return val ? new Date(val).toLocaleDateString() : "—"
},
},
{
id: "actions",
header: () => <span className="sr-only">Actions</span>,
cell: ({ row }) => (
<Button
variant="ghost"
size="icon-sm"
onClick={() => handleUnlink(row.original)}
title="Unlink owner"
>
<Unlink className="size-4 text-destructive" />
</Button>
),
enableSorting: false,
},
]
const owners = (data as any)?.data ?? []
// [BackendIssue] [FrontendWorkaround] : pagination should be replaced with "meta" property
const meta = (data as any)?.pagination
const pagination = {
page: meta?.current_page ?? 1,
pageSize: meta?.per_page ?? 15,
pageCount: meta?.last_page ?? 1,
total: meta?.total ?? 0,
}
return (
<DashboardPage title="Owners" header={null} toolbar={
<Button className="w-full" size={'lg'} onClick={() => setLinkDialogOpen(true)}>
<Plus />
Add Owner
</Button>
}>
<Card>
<CardContent>
<DataTable
columns={columns}
data={owners}
pagination={pagination}
sorting={[]}
onChange={() => { }}
isLoading={isLoading}
/>
<LinkOwnerDialog
vehicleId={vehicleId}
open={linkDialogOpen}
onOpenChange={setLinkDialogOpen}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey })
setLinkDialogOpen(false)
}}
/>
</CardContent>
</Card>
</DashboardPage >
)
}
function LinkOwnerDialog({
vehicleId,
open,
onOpenChange,
onSuccess,
}: {
vehicleId: string
open: boolean
onOpenChange: (open: boolean) => void
onSuccess: () => void
}) {
const api = useAuthApi()
const form = useForm<{ customer: { value: string; label: string } | null }>({
defaultValues: { customer: null },
})
const linkMutation = useMutation({
mutationFn: (customerId: number) =>
api.vehicles.linkCustomer({ customer_id: customerId, vehicle_id: Number(vehicleId) }),
onSuccess: () => {
toast.success("Owner linked successfully.")
form.reset()
onSuccess()
},
onError: () => {
toast.error("Failed to link owner.")
},
})
const handleSubmit = (values: { customer: { value: string; label: string } | null }) => {
if (!values.customer) return
linkMutation.mutate(Number(values.customer.value))
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="min-w-md">
<DialogHeader>
<DialogTitle>Add Owner</DialogTitle>
</DialogHeader>
<Rhform form={form} onSubmit={handleSubmit}>
<div className="flex flex-col gap-4">
<RhfAsyncSelectField
name="customer"
label="Customer"
placeholder="Search customers..."
queryKey={["customers-lookup"]}
listFn={() => api.customers.list()}
mapOption={mapCustomerOption}
{...STORE_OBJECT}
/>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
>
Cancel
</Button>
<Button
type="submit"
disabled={linkMutation.isPending || !form.watch("customer")}
>
{linkMutation.isPending && <Loader2 className="size-4 animate-spin" />}
Link Owner
</Button>
</div>
</div>
</Rhform>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,18 @@
import { getServerApi } from '@garage/api/server'
import { VehicleGeneralInfo } from '@/modules/vehicles/vehicle-general-info'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
export default async function page(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params
const api = await getServerApi()
const vehicle = await api.vehicles.getById(id)
if (!vehicle.data) {
return <div className="text-muted-foreground">Vehicle not found.</div>
}
return <DashboardPage header={null}>
<VehicleGeneralInfo vehicle={vehicle.data} />
</DashboardPage>
}
@@ -1,21 +1,35 @@
"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'
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
import { VEHICLE_ROUTES } from '@garage/api'
import type { VehiclesClient } from '@garage/api'
import { CarIcon } from 'lucide-react'
export default function VehiclesPage() {
const router = useRouter()
return (
<ResourcePage<VehiclesClient>
pageTitle="Vehicles"
title="Vehicle"
routeKey={VEHICLE_ROUTES.INDEX}
getClient={(api) => api.vehicles}
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Vehicle">
{(resourceId) => (
<VehicleForm
resourceId={resourceId}
initialData={selectedItem}
onSuccess={invalidateQuery}
/>
)}
</FormDialog>
),
})}
columns={({ actionsColumn }) => [
{
accessorKey: "name",
@@ -86,13 +100,6 @@ export default function VehiclesPage() {
},
actionsColumn(),
]}
renderForm={({ resourceId, initialData, onSuccess }) => (
<VehicleForm
resourceId={resourceId}
initialData={initialData}
onSuccess={onSuccess}
/>
)}
/>
)
}