This commit is contained in:
2026-04-23 14:38:41 +03:00
parent f17dd1486c
commit c0f78c6e18
90 changed files with 10819 additions and 1583 deletions
@@ -0,0 +1,50 @@
"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, Pencil, Trash2 } from "lucide-react"
type ExpenseActionsProps = {
expenseId: string
}
export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
const api = useAuthApi()
const router = useRouter()
const handleEdit = () => {
router.push(`/purchase/expense/${expenseId}/edit`)
}
const handleDelete = async () => {
await api.expenses.destroy(expenseId)
router.push("/purchase/expense")
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Ellipsis className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={handleEdit}>
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -0,0 +1,27 @@
"use client"
import { CrudShowResponse, ExpensesClient } from "@garage/api"
import { createContext, useContext } from "react"
export type ExpenseContextValue = CrudShowResponse<ExpensesClient>['data']
const ExpenseContext = createContext<ExpenseContextValue | null>(null)
export function ExpenseProvider({
expense,
children,
}: {
expense: ExpenseContextValue
children: React.ReactNode
}) {
return (
<ExpenseContext.Provider value={expense}>
{children}
</ExpenseContext.Provider>
)
}
export function useExpense() {
return useContext(ExpenseContext)
}
@@ -0,0 +1,62 @@
"use client"
import { useFormContext } from "react-hook-form"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import {
useDocumentTotals,
type DocumentLineItem,
} from "@/shared/hooks/use-document-totals"
import { DocumentTotalsSummary } from "@/shared/components/document-totals-summary"
import type { ExpenseFormValues } from "./expense.schema"
function parseTaxRateFromLabel(label: string | undefined | null): number | undefined {
if (!label) return undefined
const match = label.match(/\((\d+(?:\.\d+)?)%\)/)
return match ? Number(match[1]) : undefined
}
export function ExpenseFormSummary() {
const { watch } = useFormContext<ExpenseFormValues>()
const items = watch("items") ?? []
const discountType = watch("discount")
const discountAmount = watch("discount_amount")
const taxRelation = watch("tax")
const taxRate = parseTaxRateFromLabel(taxRelation?.label)
const taxLabel = taxRelation?.label ?? "Tax"
const lineItems: DocumentLineItem[] = items.map((item) => ({
quantity: item.quantity,
rate: item.rate,
discount_amount: item.discount_amount,
}))
const totals = useDocumentTotals({
lineItems,
discountType,
discountAmount,
taxRate,
})
if (!totals.hasLineItems) return null
return (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
Summary
</CardTitle>
</CardHeader>
<CardContent>
<DocumentTotalsSummary
totals={totals}
discountType={discountType}
taxLabel={taxLabel}
/>
</CardContent>
</Card>
)
}
+219 -76
View File
@@ -5,29 +5,49 @@ import { AlertTriangle, Plus, Save } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
import { FieldGroup } from "@/shared/components/ui/field"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import {
Rhform,
RhfTextField,
RhfSelectField,
RhfAsyncSelectField,
RhfTextareaField,
RhfDateField,
} from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toRelation, toId } from "@/shared/lib/utils"
import { getTodayDate, toRelation, toId } from "@/shared/lib/utils"
import {
expenseFormSchema,
type ExpenseFormValues,
} from "./expense.schema"
import { EXPENSE_ROUTES, JOB_CARD_ROUTES, VENDOR_ROUTES, DEPARTMENT_ROUTES, ExpenseStatus } from "@garage/api"
import { getFullName } from "@/shared/utils/getFullName"
import {
EXPENSE_ROUTES,
JOB_CARD_ROUTES,
VENDOR_ROUTES,
DEPARTMENT_ROUTES,
INVENTORY_CATEGORY_ROUTES,
TAX_ROUTES,
ExpenseStatus,
InvoiceDiscount,
} from "@garage/api"
import { useFormContext } from "react-hook-form"
import { RhfLabelPickerField, type LabelItem } from "@/modules/labels/rhf-label-picker-field"
import { ExpenseItemsSelectorField } from "@/modules/expense-items/expense-items-selector-field"
import { InventoryCategoryCrudDialog } from "@/modules/expense-items/inventory-category-crud-dialog"
import { ExpenseFormSummary } from "./expense-form-summary"
// ── Constants ──
const STATUS_OPTIONS = ExpenseStatus.map((v) => ({
const STATUS_OPTIONS = ExpenseStatus.map((value) => ({
value,
label: value.replace(/_/g, " ").replace(/\b\w/g, (char) => char.toUpperCase()),
}))
const DISCOUNT_OPTIONS = InvoiceDiscount.map((v) => ({
value: v,
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
}))
@@ -47,11 +67,16 @@ const DEFAULT_VALUES: ExpenseFormValues = {
category: null,
vendor: null,
department: null,
tax: null,
title: "",
invoice_number: "",
expense_date: "",
expense_date: getTodayDate(),
notes: "",
status: "open",
discount: "no",
discount_amount: undefined,
labels: [],
items: [],
}
// ── Mapping helpers ──
@@ -60,15 +85,32 @@ function mapToFormValues(data: unknown): ExpenseFormValues {
const d = (data as any)?.data ?? data ?? {}
return {
job_card: toRelation(d.job_card_id, d.job_card_name),
category: toRelation(d.category_id, d.category_name),
vendor: toRelation(d.vendor_id, d.vendor_name),
department: toRelation(d.department_id, d.department_name),
job_card: toRelation(d.job_card_id, d.job_card?.order_number ?? d.job_card_name),
category: toRelation(d.category_id, d.category?.name ?? d.category?.title ?? d.category_name),
vendor: toRelation(d.vendor_id, d.vendor?.company_name ?? d.vendor?.name ?? d.vendor_name),
department: toRelation(d.department_id, d.department?.name ?? d.department_name),
tax: toRelation(d.tax_id, d.tax?.title ? `${d.tax.title} (${d.tax.rate}%)` : undefined),
title: d.title || "",
invoice_number: d.invoice_number || "",
expense_date: d.expense_date || "",
expense_date: d.expense_date ? d.expense_date.split("T")[0] : "",
notes: d.notes || "",
status: d.status || "open",
discount: d.discount || "no",
discount_amount: d.discount_amount != null ? Number(d.discount_amount) : undefined,
labels: (d.labels ?? []).map((label: any): LabelItem => ({
id: Number(label.id),
title: label.title ?? label.name ?? "",
color_code: label.color_code ?? "",
})),
items: (d.expense_items ?? d.items ?? []).map((item: any) => ({
expense_id: item.expense_item_id ?? item.expense_item?.id ?? item.id,
title: item.expense_item?.item_name ?? item.expense_item?.name ?? item.item_name ?? item.title ?? "",
quantity: Number(item.quantity) || 1,
rate: Number(item.rate) || 0,
discount_amount: item.discount_amount != null ? Number(item.discount_amount) : undefined,
chart_of_account: item.chart_of_account != null ? String(item.chart_of_account) : "",
description: item.description ?? "",
})),
}
}
@@ -78,11 +120,23 @@ function mapFormToPayload(values: ExpenseFormValues) {
category_id: toId(values.category),
vendor_id: toId(values.vendor),
department_id: toId(values.department),
tax_id: toId(values.tax) ? Number(toId(values.tax)) : undefined,
title: values.title,
invoice_number: values.invoice_number || undefined,
expense_date: values.expense_date || undefined,
notes: values.notes || undefined,
status: values.status || undefined,
discount: values.discount || undefined,
discount_amount: values.discount === "transaction_level" ? (values.discount_amount ?? 0) : undefined,
label_ids: values.labels?.map((label) => label.id) ?? [],
items: (values.items ?? []).map((item) => ({
expense_item_id: item.expense_id,
quantity: item.quantity,
rate: item.rate,
discount_amount: values.discount === "line_item_level" ? (item.discount_amount ?? 0) : undefined,
chart_of_account: item.chart_of_account || undefined,
description: item.description || undefined,
})),
}
}
@@ -90,11 +144,32 @@ function mapFormToPayload(values: ExpenseFormValues) {
const mapLookupOption = (item: any) => ({
value: String(item.id),
label: item.name,
label: item.name ?? item.title ?? `#${item.id}`,
})
const mapVendorOption = (item: any) => ({
value: String(item.id),
label: item.company_name ?? item.name ?? `#${item.id}`,
})
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
// ── Transaction-level discount amount field ──
function TransactionDiscountField() {
const { watch } = useFormContext<ExpenseFormValues>()
const discount = watch("discount")
if (discount !== "transaction_level") return null
return (
<RhfTextField
name="discount_amount"
label="Discount Amount"
type="number"
placeholder="0.00"
/>
)
}
// ── Component ──
export function ExpenseForm({ resourceId, initialData, onSuccess }: ExpenseFormProps) {
@@ -105,15 +180,19 @@ export function ExpenseForm({ resourceId, initialData, onSuccess }: ExpenseFormP
defaultValues: DEFAULT_VALUES,
resourceId,
initialData,
queryKey: [EXPENSE_ROUTES.BY_ID, resourceId],
mapToFormValues,
})
const discount = form.watch("discount")
const isLineItemDiscount = discount === "line_item_level"
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: ExpenseFormValues) => {
const payload = mapFormToPayload(values)
const promise = isEditing && resourceId
? api.expenses.update(resourceId, payload)
: api.expenses.create(payload)
const promise = (isEditing && resourceId
? api.expenses.update(resourceId, payload as any)
: api.expenses.create(payload as any)) as Promise<any>
toast.promise(promise, {
loading: isEditing ? "Updating expense..." : "Creating expense...",
success: isEditing ? "Expense updated successfully" : "Expense created successfully",
@@ -139,72 +218,136 @@ export function ExpenseForm({ resourceId, initialData, onSuccess }: ExpenseFormP
</Alert>
)}
<FieldGroup>
<RhfTextField name="title" label="Title" placeholder="Enter expense title" required />
<div className="grid grid-cols-1 gap-6 lg:grid-cols-12">
<div className="lg:col-span-9">
<FieldGroup>
<RhfTextField name="title" label="Title" placeholder="Enter expense title" required />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfSelectField
name="status"
label="Status"
placeholder="Select status"
options={STATUS_OPTIONS}
/>
<RhfTextField name="expense_date" label="Expense Date" placeholder="YYYY-MM-DD" type="date" />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="invoice_number" label="Invoice Number" placeholder="INV-001" />
<RhfSelectField
name="status"
label="Status"
placeholder="Select status"
options={STATUS_OPTIONS}
/>
</div>
<RhfSelectField
name="discount"
label="Discount Type"
options={DISCOUNT_OPTIONS}
/>
<TransactionDiscountField />
<ExpenseItemsSelectorField<ExpenseFormValues, "items">
name="items"
label="Expense Items"
triggerLabel="Add Expense Items"
showChartOfAccount
showDiscount={isLineItemDiscount}
/>
<RhfTextareaField
name="notes"
label="Notes"
rows={3}
placeholder="Additional notes"
/>
<Button type="submit" variant="default" disabled={isPending}>
{isEditing ? <Save /> : <Plus />}
{isPending
? (isEditing ? "Updating..." : "Creating...")
: (isEditing ? "Update Expense" : "Create Expense")}
</Button>
</FieldGroup>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfAsyncSelectField
name="vendor"
label="Vendor"
placeholder="Select vendor"
queryKey={[VENDOR_ROUTES.INDEX]}
listFn={() => api.vendors.list()}
mapOption={(op: any) => ({ value: String(op.id), label: getFullName(op)})}
{...STORE_OBJECT}
/>
<RhfAsyncSelectField
name="department"
label="Department"
placeholder="Select department"
queryKey={[DEPARTMENT_ROUTES.INDEX]}
listFn={() => api.departments.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
<div className="lg:col-span-3">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
Details
</CardTitle>
</CardHeader>
<CardContent>
<FieldGroup>
<RhfDateField name="expense_date" label="Expense Date" />
<RhfAsyncSelectField
name="tax"
label="Tax"
placeholder="Select tax rate"
queryKey={[TAX_ROUTES.INDEX]}
listFn={() => api.taxes.list()}
mapOption={(item: any) => ({
value: String(item.id),
label: item.title ? `${item.title} (${item.rate}%)` : `#${item.id}`,
})}
{...STORE_OBJECT}
/>
<RhfAsyncSelectField
name="vendor"
label="Vendor"
placeholder="Select vendor"
queryKey={[VENDOR_ROUTES.INDEX]}
listFn={() => api.vendors.list()}
mapOption={mapVendorOption}
{...STORE_OBJECT}
/>
<RhfAsyncSelectField
name="department"
label="Department"
placeholder="Select department"
queryKey={[DEPARTMENT_ROUTES.INDEX]}
listFn={() => api.departments.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
<RhfAsyncSelectField
name="job_card"
label="Job Card"
placeholder="Select job card"
queryKey={[JOB_CARD_ROUTES.INDEX]}
listFn={() => api.jobCards.list()}
mapOption={(item: any) => ({
value: String(item.id),
label: item.order_number ?? item.estimate_number ?? `#${item.id}`,
})}
{...STORE_OBJECT}
/>
<div>
<div className="mb-1 flex items-center justify-between">
<span className="text-sm font-medium">Category</span>
<InventoryCategoryCrudDialog />
</div>
<RhfAsyncSelectField
name="category"
label=""
placeholder="Select category"
queryKey={[INVENTORY_CATEGORY_ROUTES.INDEX]}
listFn={() => api.inventoryCategories.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
</div>
<RhfLabelPickerField name="labels" label="Labels" />
</FieldGroup>
</CardContent>
</Card>
<div className="mt-4">
<ExpenseFormSummary />
</div>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfAsyncSelectField
name="job_card"
label="Job Card"
placeholder="Select job card"
queryKey={[JOB_CARD_ROUTES.INDEX]}
listFn={() => api.jobCards.list()}
mapOption={(item: any) => ({ value: String(item.id), label: item.job_card_number || item.name || `#${item.id}` })}
{...STORE_OBJECT}
/>
<RhfAsyncSelectField
name="category"
label="Category"
placeholder="Select category"
queryKey={[EXPENSE_ROUTES.ITEMS]}
listFn={() => api.expenses.listItems()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
</div>
<RhfTextField name="invoice_number" label="Invoice Number" placeholder="INV-001" />
<RhfTextareaField name="notes" label="Notes" rows={3} />
<Button type="submit" variant="default" disabled={isPending}>
{isEditing ? <Save /> : <Plus />}
{isPending
? (isEditing ? "Updating..." : "Creating...")
: (isEditing ? "Update Expense" : "Create Expense")}
</Button>
</FieldGroup>
</div>
</Rhform>
)
}
@@ -0,0 +1,235 @@
"use client"
import {
Calendar,
Hash,
Building2,
AlertTriangle,
CheckCircle2,
TimerIcon,
ReceiptIcon,
Wrench,
Tag,
Percent,
} from "lucide-react"
import {
Card,
CardContent,
CardHeader,
CardTitle,
} 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 { getFullName } from "@/shared/utils/getFullName"
import { useExpense } from "./expense-context"
function InfoItem({
icon: Icon,
label,
value,
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value?: string | null
}) {
return (
<div className="flex items-start gap-3">
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">
<Icon className="size-4" />
</div>
<div className="flex flex-col gap-0.5">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-sm font-medium">
{value || <span className="text-muted-foreground">—</span>}
</span>
</div>
</div>
)
}
const statusVariantMap: Record<string, "secondary" | "default" | "destructive" | "outline"> = {
draft: "secondary",
open: "default",
un_paid: "destructive",
partially_paid: "secondary",
paid: "default",
cancelled: "destructive",
}
export function ExpenseGeneralInfo() {
const expense = useExpense()
if (!expense) return null
const vendor = expense.vendor || {}
const department = expense.department || null
const jobCard = expense.job_card || null
const category = expense.category || null
const labels = (expense as any)?.labels || []
const balanceDue = expense.balance_due ?? null
const paymentsM = expense.payments_made ?? null
const taxLabel = expense.tax?.title
? `${expense.tax.title} (${expense.tax.rate}%)`
: "Tax"
return (
<div className="grid gap-6">
{/* ── Summary Hero ── */}
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{/* Status */}
<Card className="flex flex-col gap-1 p-4">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Status</span>
<div className="mt-1 flex items-center gap-2">
{expense.status === "paid" && <CheckCircle2 className="size-4 text-green-500" />}
{expense.status === "pending" && <TimerIcon className="size-4 text-muted-foreground" />}
{expense.status === "open" && <AlertTriangle className="size-4 text-yellow-600" />}
{expense.status === "un_paid" && <AlertTriangle className="size-4 text-destructive" />}
<Badge variant={statusVariantMap[String(expense.status ?? "")] ?? "outline"} className="text-sm px-2 py-0.5">
{formatEnum(String(expense.status ?? ""))}
</Badge>
</div>
</Card>
{/* Total */}
<Card className="flex flex-col gap-1 p-4">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Total</span>
<span className="mt-1 text-lg font-semibold">
{formatCurrency(expense.total ?? 0)}
</span>
{expense.sub_total != null && expense.sub_total !== expense.total && (
<span className="text-xs text-muted-foreground">Subtotal: {formatCurrency(expense.sub_total)}</span>
)}
</Card>
{/* Payments Made */}
<Card className="flex flex-col gap-1 p-4">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Paid</span>
<span className="mt-1 text-lg font-semibold text-green-600 dark:text-green-400">
{formatCurrency(paymentsM ?? 0)}
</span>
</Card>
{/* Balance Due */}
<Card className={cn("flex flex-col gap-1 p-4", (balanceDue ?? 0) > 0 && "border-destructive/50 bg-destructive/5")}>
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Balance Due</span>
<span className={cn("mt-1 text-lg font-semibold", (balanceDue ?? 0) > 0 ? "text-destructive" : "text-green-600 dark:text-green-400")}>
{formatCurrency(balanceDue ?? 0)}
</span>
</Card>
</div>
{/* ── Vendor ── */}
<Card className="flex flex-col gap-1 p-4">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Vendor</span>
<span className="mt-1 text-lg font-semibold">{vendor.company_name || getFullName(vendor as any) || "—"}</span>
</Card>
{/* ── Expense Details ── */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ReceiptIcon className="size-4" />
Expense Details
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid gap-4 sm:grid-cols-3">
<InfoItem icon={Hash} label="Invoice Number" value={expense.invoice_number} />
<InfoItem icon={Calendar} label="Expense Date" value={formatDate(expense.expense_date)} />
<InfoItem icon={Building2} label="Department" value={department?.name} />
{expense.discount && expense.discount !== "no" && (
<InfoItem icon={Percent} label="Discount Type" value={formatEnum(expense.discount)} />
)}
{expense.discount_amount_major != null && expense.discount_amount_major > 0 && (
<InfoItem icon={Percent} label="Discount" value={formatCurrency(expense.discount_amount_major)} />
)}
{expense.tax_amount != null && expense.tax_amount > 0 && (
<InfoItem icon={Percent} label={taxLabel} value={formatCurrency(expense.tax_amount)} />
)}
</div>
</CardContent>
</Card>
{/* ── Job Card & Category ── */}
{(jobCard || category) && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Wrench className="size-4" />
Related Information
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid gap-4 sm:grid-cols-2">
{jobCard && (
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-background text-muted-foreground">
<Wrench className="size-4" />
</div>
<div className="flex flex-col gap-0.5">
<span className="text-xs text-muted-foreground font-medium">Job Card</span>
<span className="text-sm font-semibold">{jobCard.order_number || "—"}</span>
<span className="text-xs text-muted-foreground">{jobCard.title || ""}</span>
</div>
</div>
)}
{category && (
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-background text-muted-foreground">
<Tag className="size-4" />
</div>
<div className="flex flex-col gap-0.5">
<span className="text-xs text-muted-foreground font-medium">Category</span>
<span className="text-sm font-semibold">{category.title || "—"}</span>
</div>
</div>
)}
</div>
</CardContent>
</Card>
)}
{/* ── Labels ── */}
{labels && labels.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Tag className="size-4" />
Labels
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-2">
{labels.map((label: any) => (
<Badge
key={label.id}
style={{
backgroundColor: label.color_code + "20",
borderColor: label.color_code,
color: label.color_code,
}}
variant="outline"
>
{label.title}
</Badge>
))}
</div>
</CardContent>
</Card>
)}
{/* ── Notes ── */}
{expense.notes && (
<Card>
<CardHeader>
<CardTitle className="text-base">Notes</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground whitespace-pre-wrap">{expense.notes}</p>
</CardContent>
</Card>
)}
</div>
)
}
@@ -0,0 +1,133 @@
"use client"
import { ShoppingCartIcon } 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 } from "@/shared/utils/formatters"
type ExpenseItem = {
id?: number
expense_id?: number
expense_item_id?: number
quantity?: number | string
rate?: string | number
description?: string | null
expense_item?: {
id?: number
item_name?: string
name?: string
item_code?: string
sku?: string
}
}
type ExpenseItemsSectionProps = {
items?: ExpenseItem[]
discountType?: string | null
subTotal?: number | null
discountAmount?: number | null
taxAmount?: number | null
total?: number | null
taxLabel?: string | null
}
export function ExpenseItemsSection({
items,
discountType,
subTotal,
discountAmount,
taxAmount,
total,
taxLabel,
}: ExpenseItemsSectionProps) {
if (!items || items.length === 0) return null
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ShoppingCartIcon className="size-4" />
Expense Items ({items.length})
</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent">
<TableHead>Item</TableHead>
<TableHead>Description</TableHead>
<TableHead className="text-right w-20">Qty</TableHead>
<TableHead className="text-right w-28">Rate</TableHead>
<TableHead className="text-right w-28">Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{items.map((item) => {
const qty = Number(item.quantity || 0)
const rate = Number(item.rate || 0)
const amount = qty * rate
const name = item.expense_item?.item_name || item.expense_item?.name || "—"
return (
<TableRow key={item.id}>
<TableCell className="font-medium">
<div>{name}</div>
{(item.expense_item?.sku || item.expense_item?.item_code) && (
<div className="text-xs text-muted-foreground font-mono">
{item.expense_item?.sku || item.expense_item?.item_code}
</div>
)}
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{item.description || "—"}
</TableCell>
<TableCell className="text-right text-sm">{qty.toLocaleString()}</TableCell>
<TableCell className="text-right text-sm">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-semibold">{formatCurrency(amount)}</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
{/* ── Totals summary ── */}
<div className="mt-4 flex justify-end">
<div className="w-64 space-y-1 text-sm">
{subTotal != null && (
<div className="flex justify-between">
<span className="text-muted-foreground">Subtotal</span>
<span className="font-medium">{formatCurrency(subTotal)}</span>
</div>
)}
{discountAmount != null && discountAmount > 0 && discountType !== "no" && (
<div className="flex justify-between text-destructive">
<span>Discount</span>
<span>− {formatCurrency(discountAmount)}</span>
</div>
)}
{taxAmount != null && taxAmount > 0 && (
<div className="flex justify-between">
<span className="text-muted-foreground">{taxLabel || "Tax"}</span>
<span className="font-medium">{formatCurrency(taxAmount)}</span>
</div>
)}
{total != null && (
<div className="flex justify-between border-t pt-2 text-base font-semibold">
<span>Total</span>
<span>{formatCurrency(total)}</span>
</div>
)}
</div>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,157 @@
"use client"
import { useRouter } from "next/navigation"
import {
BadgeDollarSignIcon,
CalendarIcon,
CreditCardIcon,
HashIcon,
UserIcon,
} from "lucide-react"
import { CrudResource } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { Card, CardContent } from "@/shared/components/ui/card"
import { PAYMENT_MADE_ROUTES } from "@garage/api"
import { PaymentMadeForm } from "@/modules/payment-mades/payment-made-form"
import { useExpense } from "./expense-context"
import { formatDate } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { toRelation } from "@/shared/lib/utils"
export function ExpensePaymentsSection() {
const expense = useExpense()
const router = useRouter()
return (
<CrudResource<any>
extraParams={{ expense_id: expense?.id }}
routeKey={PAYMENT_MADE_ROUTES.INDEX}
getClient={(api) => ({
list: (query?: any) => api.paymentMades.list(query),
destroy: (id: string) => api.paymentMades.destroy(id),
})}
tableHeader={({ invalidateQuery }) => (
<Card className="mb-4">
<CardContent className="flex items-center justify-between">
<h2 className="text-base font-semibold">Payments Made</h2>
<FormDialog title="Record Payment">
{(resourceId) => (
<PaymentMadeForm
initialData={{
amount: (expense as any)?.amount,
vendor: toRelation(expense?.vendor?.id, getFullName(expense?.vendor as any)),
payment_for: "expense",
}}
expenseId={expense?.id}
resourceId={resourceId}
onSuccess={() => {
router.refresh()
invalidateQuery()
}}
/>
)}
</FormDialog>
</CardContent>
</Card>
)}
columns={({ actionsColumn }) => [
{
accessorKey: "payment_number",
header: ({ column }) => <ColumnHeader column={column} title="Payment #" />,
cell: ({ row }) => {
const item = row.original as any
return (
<div className="flex items-center gap-2">
<HashIcon className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{item.payment_number || "—"}</span>
</div>
)
},
},
{
accessorKey: "vendor",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => {
const item = row.original as any
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>
</div>
)
},
},
{
accessorKey: "payment_made",
header: ({ column }) => <ColumnHeader column={column} title="Amount" />,
cell: ({ row }) => {
const item = row.original as any
const amount = item.payment_made != null
? Number(item.payment_made).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
: "—"
return (
<div className="flex items-center gap-2">
<BadgeDollarSignIcon className="h-4 w-4 text-emerald-600" />
<span className="font-semibold text-emerald-700 dark:text-emerald-400">
{amount}
</span>
</div>
)
},
},
{
accessorKey: "payment_mode",
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
cell: ({ row }) => {
const item = row.original as any
return (
<div className="flex items-center gap-2">
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
<span className="capitalize">
{item.payment_mode?.name || item.payment_mode_name || "—"}
</span>
</div>
)
},
},
{
accessorKey: "payment_date",
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
cell: ({ row }) => {
const item = row.original as any
return (
<div className="flex items-center gap-2">
<CalendarIcon className="h-4 w-4 text-muted-foreground" />
<span>{formatDate(item.payment_date) || "—"}</span>
</div>
)
},
},
{
accessorKey: "notes",
header: () => <span>Notes</span>,
enableSorting: false,
cell: ({ row }) => {
const item = row.original as any
const notes = item.notes
if (!notes) return <span className="text-muted-foreground">—</span>
return (
<span
className="max-w-50 truncate block text-muted-foreground"
title={notes}
>
{notes}
</span>
)
},
},
actionsColumn(),
]}
/>
)
}
@@ -4,12 +4,29 @@ const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
const labelItemSchema = z.object({
id: z.number(),
title: z.string(),
color_code: z.string(),
})
const expenseLineItemSchema = z.object({
expense_id: z.number(),
title: z.string(),
quantity: z.number().min(1),
rate: z.number().min(0),
discount_amount: z.number().min(0).optional(),
chart_of_account: z.string().optional(),
description: z.string().optional(),
})
const expenseFormSchema = z.object({
// ── Relations ──
job_card: relationFieldSchema,
category: relationFieldSchema,
vendor: relationFieldSchema,
department: relationFieldSchema,
tax: relationFieldSchema,
// ── Basic info ──
title: z.string().min(1, "Title is required"),
@@ -17,6 +34,13 @@ const expenseFormSchema = z.object({
expense_date: z.string().optional(),
notes: z.string().optional(),
status: z.string().optional(),
// ── Discount / Tax ──
discount: z.string().optional(),
discount_amount: z.coerce.number().min(0).optional(),
labels: z.array(labelItemSchema).optional(),
items: z.array(expenseLineItemSchema).optional(),
})
type ExpenseFormValues = z.infer<typeof expenseFormSchema>