feat: add logo field to settings schema and update settings client to handle file uploads

feat: integrate dialog close context in vendor select field and CRUD dialog components

feat: enhance vendor general info to format status using utility function

feat: implement form dialog context for managing dialog close actions

feat: add async select field dialog close context for better form handling

fix: update form mutation hook to close dialog on successful submission

feat: extend document print types to include expense and credit note

feat: add settings update payload type to include logo and other fields

feat: create employee attendance and work history pages with resource management

feat: implement payment made and received detail pages with actions

feat: add quick shortcuts component for easy navigation in the dashboard

feat: create actions for payment made and received with print and delete options

feat: implement dialog close context for better dialog management

feat: add error parsing utility for improved error handling in API responses
This commit is contained in:
2026-05-19 17:56:39 +04:00
parent 2d6e3c5734
commit 4f0a2f790f
56 changed files with 1220 additions and 92 deletions
@@ -19,6 +19,7 @@ import { useQueryClient } from "@tanstack/react-query"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { useFormDialog } from "@/shared/components/form-dialog"
import { AppointmentForm } from "./appointment-form"
import { formatEnum } from "@/shared/utils/formatters"
type AppointmentActionsProps = {
appointmentId: string
@@ -50,7 +51,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
setIsLoading(true)
try {
await api.appointments.changeStatus(appointmentId, { status } as any)
toast.success(`Status updated to "${status}".`)
toast.success(`Status updated to "${formatEnum(status)}".`)
queryClient.invalidateQueries({ queryKey: [APPOINTMENT_ROUTES.INDEX] })
router.refresh()
} catch {
@@ -15,6 +15,7 @@ import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { formatEnum } from "@/shared/utils/formatters"
type AppointmentData = {
id?: number
@@ -89,7 +90,7 @@ export function AppointmentGeneralInfo({ appointment }: AppointmentGeneralInfoPr
<div className="flex items-center gap-2">
{appointment.status && (
<Badge className={statusClass}>
{appointment.status.replace("_", " ")}
{formatEnum(appointment.status)}
</Badge>
)}
</div>
@@ -11,11 +11,12 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2, Share2 } from "lucide-react"
import { Ellipsis, Pencil, Printer, 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"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type BillActionsProps = {
billId: string
@@ -25,6 +26,7 @@ export function BillActions({ billId }: BillActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("bill-details-edit")
const { print, isPrinting } = useDocumentPrint()
const [shareOpen, setShareOpen] = useState(false)
const handleDelete = async () => {
@@ -45,6 +47,10 @@ export function BillActions({ billId }: BillActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("bill", billId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-4" />
Share
@@ -1,6 +1,6 @@
"use client"
import { BillStatus } from "@garage/api"
import { BillStatus, parseApiError } from "@garage/api"
import { Badge, badgeVariants } from "@/shared/components/ui/badge"
import {
Select,
@@ -60,7 +60,7 @@ export default function BillStatusBadge({ bill }: BillStatusBadgeProps) {
toast.success("Bill status updated")
router.refresh()
} catch (error) {
toast.error("Failed to update bill status")
toast.error(parseApiError(error, "Failed to update bill status"))
} finally {
setIsLoading(false)
}
@@ -71,7 +71,9 @@ export default function BillStatusBadge({ bill }: BillStatusBadgeProps) {
<SelectTrigger
className={`border-0 size-auto p-0 h-auto font-medium ${STATUS_TRIGGER_CLASS_NAMES[status]}`}
>
<SelectValue placeholder="Select status" />
<SelectValue placeholder="Select status">
{formatEnum(status)}
</SelectValue>
</SelectTrigger>
<SelectContent>
{BillStatus.map((s) => (
@@ -11,9 +11,10 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { Ellipsis, Pencil, Printer, Trash2 } from "lucide-react"
import { useFormDialog } from "@/shared/components/form-dialog"
import { CreditNoteForm } from "./credit-note-form"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type CreditNoteActionsProps = {
creditNoteId: string
@@ -23,6 +24,7 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("credit-note-details-edit")
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.creditNotes.destroy(creditNoteId)
@@ -42,6 +44,10 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("credit_note", creditNoteId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
@@ -14,6 +14,7 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Separator } from "@/shared/components/ui/separator"
import { formatEnum } from "@/shared/utils/formatters"
type CreditNoteData = {
id?: number
@@ -84,7 +85,7 @@ export function CreditNoteGeneralInfo({ creditNote }: CreditNoteGeneralInfoProps
)}
{creditNote.status && (
<Badge variant={statusColorMap[creditNote.status] as any ?? "outline"}>
{creditNote.status.charAt(0).toUpperCase() + creditNote.status.slice(1)}
{formatEnum(creditNote.status)}
</Badge>
)}
</div>
@@ -10,6 +10,7 @@ import { Field, FieldLabel, FieldError, FieldDescription } from "@/shared/compon
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 { DialogCloseContext } from "@/shared/hooks/use-dialog-close"
import {
Combobox,
ComboboxInput,
@@ -131,10 +132,17 @@ export function RhfCustomerSelectField<
const handleCreateSuccess = (data?: any) => {
const item = data?.data ?? data
if (item?.id) {
field.onChange(buildCustomerOption(item))
if (!item?.id) {
setIsCreateOpen(false)
return
}
queryClient.invalidateQueries({ queryKey: [CUSTOMER_ROUTES.INDEX, "customer-select", customerType ?? "all"] })
const newOption = buildCustomerOption(item)
const key = [CUSTOMER_ROUTES.INDEX, "customer-select", customerType ?? "all"]
queryClient.setQueryData<CustomerOption[]>(key, (prev = []) =>
prev.some((o) => o.value === newOption.value) ? prev : [newOption, ...prev],
)
field.onChange(newOption)
setIsCreateOpen(false)
}
@@ -243,7 +251,9 @@ export function RhfCustomerSelectField<
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<CustomerForm onSuccess={handleCreateSuccess} />
<DialogCloseContext.Provider value={() => setIsCreateOpen(false)}>
<CustomerForm onSuccess={handleCreateSuccess} />
</DialogCloseContext.Provider>
</ScrollArea>
</DialogContent>
</Dialog>
@@ -6,6 +6,7 @@ import { Loader2 } from "lucide-react"
import { useAuthApi } from "@/shared/useApi"
import { EMPLOYEE_ROUTES } from "@garage/api"
import { Badge } from "@/shared/components/ui/badge"
import { formatEnum } from "@/shared/utils/formatters"
import {
Combobox,
ComboboxInput,
@@ -149,16 +150,16 @@ export function EmployeeCombobox({
{opt.type && (
<Badge
variant="secondary"
className="h-4 px-1.5 text-xs font-normal capitalize"
className="h-4 px-1.5 text-xs font-normal"
>
{opt.type}
{formatEnum(opt.type)}
</Badge>
)}
{opt.status && (
<span
className={`text-xs capitalize ${opt.status === "active" ? "text-green-600 dark:text-green-400" : "text-muted-foreground"}`}
className={`text-xs ${opt.status === "active" ? "text-green-600 dark:text-green-400" : "text-muted-foreground"}`}
>
{opt.status}
{formatEnum(opt.status)}
</span>
)}
</div>
@@ -18,6 +18,7 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Separator } from "@/shared/components/ui/separator"
import { formatEnum } from "@/shared/utils/formatters"
type EmployeeData = {
id?: number
@@ -86,16 +87,15 @@ export function EmployeeGeneralInfo({ employee }: EmployeeGeneralInfoProps) {
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary">{fullName || "Unknown"}</Badge>
{employee.type && (
<Badge variant="outline" className="capitalize">
{employee.type}
<Badge variant="outline">
{formatEnum(employee.type)}
</Badge>
)}
{employee.status && (
<Badge
variant={employee.status === "active" ? "default" : "secondary"}
className="capitalize"
>
{employee.status}
{formatEnum(employee.status)}
</Badge>
)}
</div>
@@ -11,9 +11,10 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { Ellipsis, Pencil, Printer, Trash2 } from "lucide-react"
import { useFormDialog } from "@/shared/components/form-dialog"
import { ExpenseForm } from "./expense-form"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type ExpenseActionsProps = {
expenseId: string
@@ -23,6 +24,7 @@ export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("expense-details-edit")
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.expenses.destroy(expenseId)
@@ -42,6 +44,10 @@ export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("expense", expenseId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
@@ -14,6 +14,7 @@ import { ItemsTotalsCard } from "./items-totals-card"
import { CustomersTotalsCard } from "./customers-totals-card"
import { SalesPurchaseCards } from "./sales-purchase-cards"
import { VehicleStatsCards } from "./vehicle-stats-cards"
import { QuickShortcuts } from "./quick-shortcuts"
import { DashboardPeriods, type DashboardPeriod, type HomeDashboardQuery } from "@garage/api"
const DEFAULT_PERIOD: DashboardPeriod = "this_month"
@@ -66,6 +67,9 @@ export function DashboardContent() {
return (
<div className="space-y-6">
{/* Quick Shortcuts */}
<QuickShortcuts />
{/* Financial Overview */}
<FinancialTotalsCards data={data} />
@@ -0,0 +1,117 @@
"use client"
import Link from "next/link"
import {
CalendarCheck2Icon,
CarIcon,
ClipboardCheckIcon,
ClipboardListIcon,
PackageIcon,
ReceiptIcon,
ReceiptTextIcon,
UsersIcon,
WrenchIcon,
} from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
type Shortcut = {
label: string
href: string
icon: typeof CarIcon
color: string
bg: string
}
const shortcuts: Shortcut[] = [
{
label: "Job Cards",
href: "/sales/job-cards",
icon: ClipboardListIcon,
color: "text-emerald-600",
bg: "bg-emerald-500/10",
},
{
label: "Appointments",
href: "/calendar/appointment/list",
icon: CalendarCheck2Icon,
color: "text-sky-600",
bg: "bg-sky-500/10",
},
{
label: "New Estimate",
href: "/sales/estimates/new",
icon: ReceiptTextIcon,
color: "text-violet-600",
bg: "bg-violet-500/10",
},
{
label: "Invoices",
href: "/sales/invoice",
icon: ReceiptIcon,
color: "text-amber-600",
bg: "bg-amber-500/10",
},
{
label: "Inspections",
href: "/sales/inspections",
icon: ClipboardCheckIcon,
color: "text-rose-600",
bg: "bg-rose-500/10",
},
{
label: "Customers",
href: "/sales/customers",
icon: UsersIcon,
color: "text-blue-600",
bg: "bg-blue-500/10",
},
{
label: "Vehicles",
href: "/sales/vehicles",
icon: CarIcon,
color: "text-indigo-600",
bg: "bg-indigo-500/10",
},
{
label: "Parts",
href: "/items/parts",
icon: PackageIcon,
color: "text-orange-600",
bg: "bg-orange-500/10",
},
{
label: "Services",
href: "/items/services",
icon: WrenchIcon,
color: "text-teal-600",
bg: "bg-teal-500/10",
},
]
export function QuickShortcuts() {
return (
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">Quick Shortcuts</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-3 gap-2 sm:grid-cols-4 lg:grid-cols-9">
{shortcuts.map((shortcut) => (
<Link
key={shortcut.label}
href={shortcut.href}
className="flex flex-col items-center gap-2 rounded-lg border p-3 text-center transition-colors hover:bg-muted/50"
>
<div className={`rounded-md p-2 ${shortcut.bg}`}>
<shortcut.icon className={`h-5 w-5 ${shortcut.color}`} />
</div>
<span className="text-[11px] font-medium leading-tight">
{shortcut.label}
</span>
</Link>
))}
</div>
</CardContent>
</Card>
)
}
@@ -4,6 +4,7 @@ import { Calendar, Clock } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
import { formatEnum } from "@/shared/utils/formatters"
import type { DashboardData } from "./use-dashboard-data"
type Props = { data: DashboardData }
@@ -36,7 +37,7 @@ function AppointmentRow({ appt }: { appt: AppointmentDetail }) {
{appt.from_time?.slice(0, 5)} - {appt.to_time?.slice(0, 5)}
</div>
<Badge variant="secondary" className={statusBadge[appt.status ?? ""] ?? ""}>
{appt.status}
{formatEnum(appt.status)}
</Badge>
</div>
</div>
@@ -2,6 +2,7 @@
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { parseApiError } from "@garage/api"
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"
@@ -50,17 +51,18 @@ export function InspectionActions({ inspectionId, status, onStatusChange }: Insp
}
const handleStatusChange = async (newStatus: string) => {
const promise = api.inspections.changeStatus({
status: newStatus,
} as never)
toast.promise(promise, {
loading: "Updating status...",
success: "Status updated successfully",
error: "Failed to update status",
})
await promise
onStatusChange?.()
router.refresh()
const loadingToast = toast.loading("Updating status...")
try {
await api.inspections.changeStatus({
id: Number(inspectionId),
status: newStatus,
} as never)
toast.success("Status updated successfully", { id: loadingToast })
onStatusChange?.()
router.refresh()
} catch (e) {
toast.error(parseApiError(e, "Failed to update status"), { id: loadingToast })
}
}
const transition = status ? STATUS_TRANSITIONS[status] : undefined
@@ -10,6 +10,7 @@ import {
MoreHorizontal,
Pencil,
PlayCircle,
Printer,
Share2,
Trash2,
XCircle,
@@ -28,6 +29,7 @@ import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
import { INSPECTION_ROUTES } from "@garage/api"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type InspectionStatus = "in_progress" | "completed" | "cancelled"
@@ -48,6 +50,7 @@ export function InspectionRowActions({
const router = useRouter()
const api = useAuthApi()
const queryClient = useQueryClient()
const { print, isPrinting } = useDocumentPrint()
const [shareOpen, setShareOpen] = useState(false)
const inspectionId = String(inspection.id)
@@ -125,6 +128,9 @@ export function InspectionRowActions({
<Pencil className="size-3.5 text-muted-foreground" /> Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("inspection", inspectionId, "print")} disabled={isPrinting}>
<Printer className="size-3.5 text-muted-foreground" /> {isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-3.5 text-muted-foreground" /> Share with customer
</DropdownMenuItem>
@@ -3,7 +3,7 @@
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { InvoiceStatus } from "@garage/api"
import { InvoiceStatus, parseApiError } from "@garage/api"
import { confirm } from "@/shared/components/confirm-dialog"
import { badgeVariants } from "@/shared/components/ui/badge"
import {
@@ -71,18 +71,13 @@ export default function InvoiceStatusBadge({ invoice }: InvoiceStatusBadgeProps)
setIsUpdating(true)
const loadingToast = toast.loading(`Updating invoice status to ${formatEnum(nextStatus)}...`)
try {
const promise = api.invoices.update(String(invoice.id), { status: nextStatus })
toast.promise(promise, {
loading: `Updating invoice status to ${formatEnum(nextStatus)}...`,
success: "Invoice status updated successfully.",
error: "Failed to update invoice status.",
})
await promise
setStatus(nextStatus)
await api.invoices.update(String(invoice.id), { status: nextStatus })
toast.success("Invoice status updated successfully.", { id: loadingToast })
router.refresh()
} catch (e) {
toast.error(parseApiError(e, "Failed to update invoice status."), { id: loadingToast })
} finally {
setIsUpdating(false)
}
@@ -0,0 +1,48 @@
"use client"
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Printer, Trash2 } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type PaymentMadeActionsProps = {
paymentId: string
}
export function PaymentMadeActions({ paymentId }: PaymentMadeActionsProps) {
const api = useAuthApi()
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.paymentMades.destroy(paymentId)
router.push("/purchase/payments-made")
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Ellipsis className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => print("payment_made", paymentId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -30,6 +30,7 @@ import {
BILL_ROUTES,
PAYMENT_MODE_ROUTES,
EMPLOYEE_ROUTES,
PAYMENT_MADE_ROUTES,
PaymentFor,
} from "@garage/api"
import { RhfVendorSelectField } from "@/modules/vendors/rhf-vendor-select-field"
@@ -182,6 +183,8 @@ export function PaymentMadeForm({ resourceId, initialData, onSuccess, billId, ex
defaultValues: DEFAULT_VALUES,
resourceId,
initialData: resolvedInitialData,
initialize: (id) => api.paymentMades.show(id),
queryKey: [PAYMENT_MADE_ROUTES.BY_ID, resourceId],
mapToFormValues,
})
@@ -0,0 +1,48 @@
"use client"
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Printer, Trash2 } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type PaymentReceivedActionsProps = {
paymentId: string
}
export function PaymentReceivedActions({ paymentId }: PaymentReceivedActionsProps) {
const api = useAuthApi()
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.paymentReceived.destroy(paymentId)
router.push("/sales/payment-received")
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Ellipsis className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => print("payment_received", paymentId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -25,7 +25,7 @@ import {
paymentReceivedFormSchema,
type PaymentReceivedFormValues,
} from "./payment-received.schema"
import { PAYMENT_MODE_ROUTES, CUSTOMER_ROUTES, JOB_CARD_ROUTES } from "@garage/api"
import { PAYMENT_MODE_ROUTES, CUSTOMER_ROUTES, JOB_CARD_ROUTES, PAYMENT_RECEIVED_ROUTES } from "@garage/api"
// ── Props ──
@@ -58,13 +58,29 @@ const DEFAULT_VALUES: PaymentReceivedFormValues = {
function mapToFormValues(data: unknown): PaymentReceivedFormValues {
const d = (data as any)?.data ?? data ?? {}
const jobCardId = d.job_card_id ?? d.job_card?.id
const jobCardLabel = d.job_card?.title ?? d.job_card_name
const paymentModeId = d.payment_mode_id ?? d.payment_mode?.id
const paymentModeLabel = d.payment_mode?.title ?? d.payment_mode?.name ?? d.payment_mode_name
const customerId = d.customer_id ?? d.customer?.id
const customerLabel = d.customer?.first_name
? `${d.customer.first_name} ${d.customer.last_name ?? ""}`.trim()
: d.customer?.company_name ?? d.customer?.name ?? d.customer_name
const rawDate = d.payment_date
const payment_date = typeof rawDate === "string" && rawDate
? rawDate.slice(0, 10)
: new Date().toISOString().split("T")[0]
return {
job_card: toRelation(d.job_card_id, d.job_card_name),
payment_mode: toRelation(d.payment_mode_id, d.payment_mode_name),
customer: toRelation(d.customer_id, d.customer_name),
job_card: toRelation(jobCardId, jobCardLabel),
payment_mode: toRelation(paymentModeId, paymentModeLabel),
customer: toRelation(customerId, customerLabel),
amount_received: d.amount_received != null ? Number(d.amount_received) : 0,
payment_number: d.payment_number || "",
payment_date: d.payment_date || new Date().toISOString().split("T")[0],
payment_date,
note: d.note || "",
}
}
@@ -126,6 +142,8 @@ export function PaymentReceivedForm({ resourceId, initialData, onSuccess, defaul
defaultValues: DEFAULT_VALUES,
resourceId,
initialData: resolvedInitialData,
initialize: (id) => api.paymentReceived.show(id),
queryKey: [PAYMENT_RECEIVED_ROUTES.BY_ID, resourceId],
mapToFormValues,
})
@@ -17,9 +17,11 @@ import {
RhfAsyncSelectField,
RhfTextareaField,
} from "@/shared/components/form"
import { RhfImageField } from "@/shared/components/form/fields/rhf-image-field"
import { useAuthApi } from "@/shared/useApi"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toId } from "@/shared/lib/utils"
import { CONSTANTS } from "@/config/constants"
import { FirstDayOfWork } from "@garage/api"
import { SETTINGS_ROUTES } from "@garage/api"
@@ -58,6 +60,7 @@ const DEFAULT_VALUES: SettingsFormValues = {
description: "",
security: "",
privacy_policy: "",
logo: null,
}
// ── Mapping helpers ──
@@ -85,6 +88,7 @@ function mapToFormValues(data: unknown): SettingsFormValues {
description: d.description ?? "",
security: d.security ?? "",
privacy_policy: d.privacy_policy ?? "",
logo: null,
}
}
@@ -93,11 +97,24 @@ function mapFormToPayload(values: SettingsFormValues) {
name: values.name,
email: values.email || undefined,
phone: values.phone || undefined,
alternative_phone: values.alternative_phone || undefined,
website: values.website || undefined,
time_zone: values.time_zone || undefined,
upi_id: values.upi_id || undefined,
first_day_of_work: values.first_day_of_work || undefined,
latitude: values.latitude || undefined,
longitude: values.longitude || undefined,
bank_details: values.bank_details || undefined,
first_address_line: values.first_address_line || undefined,
second_address_line: values.second_address_line || undefined,
country_id: toId(values.country),
state_id: toId(values.state),
city: values.city || undefined,
zip_code: values.zip_code || undefined,
description: values.description || undefined,
security: values.security || undefined,
privacy_policy: values.privacy_policy || undefined,
logo: values.logo instanceof File ? values.logo : undefined,
}
}
@@ -116,6 +133,14 @@ export function SettingsForm() {
queryFn: () => api.settings.fetch(),
})
const existingLogoPath: string | null = (() => {
const raw = (data as any)?.data
const record = Array.isArray(raw) ? raw[0] : raw
const logo = record?.logo
if (!logo || typeof logo !== "string") return null
return logo.startsWith("http") ? logo : CONSTANTS.getAssetUrl(`storage/${logo.replace(/^\/+/, "")}`)
})()
useEffect(() => {
if (!data) return
const raw = (data as any)?.data
@@ -286,6 +311,20 @@ export function SettingsForm() {
{/* Sidebar - 4/12 */}
<div className="lg:col-span-4">
<FieldGroup className="sticky top-24 space-y-6">
{/* Logo Section */}
<div className="rounded-lg border bg-card p-4">
<h3 className="mb-1 text-base font-semibold">Workshop Logo</h3>
<p className="text-muted-foreground mb-3 text-xs">
Shown on printed invoices, estimates, job cards and other documents.
</p>
<RhfImageField
name="logo"
accept="image/png,image/jpeg,image/jpg,image/webp,image/svg+xml"
disabled={isLoading}
initialPreviewUrl={existingLogoPath}
/>
</div>
{/* Location & Time Section */}
<div className="rounded-lg border bg-card p-4">
<h3 className="mb-4 text-base font-semibold">Location & Time</h3>
@@ -340,8 +379,8 @@ export function SettingsForm() {
<div className="mt-4">
<RhfTextareaField
name="privacy_policy"
label="Privacy Policy"
placeholder="Privacy policy text..."
label="Terms and Conditions"
placeholder="Terms and conditions text..."
disabled={isLoading}
/>
</div>
@@ -51,6 +51,14 @@ export const settingsFormSchema = z.object({
description: z.string().optional(),
security: z.string().optional(),
privacy_policy: z.string().optional(),
logo: z
.any()
.nullable()
.optional()
.refine(
(v) => v == null || v instanceof File,
"Logo must be an image file",
),
})
export type SettingsFormValues = z.infer<typeof settingsFormSchema>
+4 -1
View File
@@ -10,6 +10,7 @@ import { Field, FieldLabel, FieldError, FieldDescription } from "@/shared/compon
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 { DialogCloseContext } from "@/shared/hooks/use-dialog-close"
import {
Combobox,
ComboboxInput,
@@ -228,7 +229,9 @@ export function RhfVendorSelectField<
<DialogTitle className="text-2xl font-bold">Add Vendor</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<VendorForm onSuccess={handleCreateSuccess} />
<DialogCloseContext.Provider value={() => setIsCreateOpen(false)}>
<VendorForm onSuccess={handleCreateSuccess} />
</DialogCloseContext.Provider>
</ScrollArea>
</DialogContent>
</Dialog>
+3 -2
View File
@@ -16,6 +16,7 @@ import {
import { Badge } from "@/shared/components/ui/badge"
import { Separator } from "@/shared/components/ui/separator"
import { Money } from "@/shared/components/money"
import { formatEnum } from "@/shared/utils/formatters"
type VendorData = {
id?: number
@@ -82,8 +83,8 @@ export function VendorGeneralInfo({ vendor }: VendorGeneralInfoProps) {
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary">{vendor.company_name || fullName || "Unknown vendor"}</Badge>
{vendor.status && (
<Badge variant={vendor.status === "active" ? "default" : "outline"} className="capitalize">
{vendor.status}
<Badge variant={vendor.status === "active" ? "default" : "outline"}>
{formatEnum(vendor.status)}
</Badge>
)}
</div>