This commit is contained in:
2026-03-18 11:24:59 -05:00
parent 02e14319ac
commit f85563ce99
17 changed files with 1578 additions and 2 deletions

View File

@@ -14,6 +14,7 @@ const links = [
{ to: "/sales/quotes", label: "Quotes", icon: <QuoteIcon /> },
{ to: "/sales/orders", label: "Sales Orders", icon: <SalesOrderIcon /> },
{ to: "/purchasing/orders", label: "Purchase Orders", icon: <PurchaseOrderIcon /> },
{ to: "/finance", label: "Finance", icon: <FinanceIcon /> },
{ to: "/shipping/shipments", label: "Shipments", icon: <ShipmentIcon /> },
{ to: "/projects", label: "Projects", icon: <ProjectsIcon /> },
{ to: "/manufacturing/work-orders", label: "Manufacturing", icon: <ManufacturingIcon /> },
@@ -146,6 +147,18 @@ function ShipmentIcon() {
);
}
function FinanceIcon() {
return (
<NavIcon>
<path d="M4 18h16" />
<path d="M7 15V9" />
<path d="M12 15V6" />
<path d="M17 15v-4" />
<path d="M5 6h14" />
</NavIcon>
);
}
function WorkbenchIcon() {
return (
<NavIcon>

View File

@@ -14,6 +14,13 @@ import type {
ApiResponse,
CompanyProfileDto,
CompanyProfileInput,
FinanceCapexDto,
FinanceCapexInput,
FinanceCustomerPaymentDto,
FinanceCustomerPaymentInput,
FinanceDashboardDto,
FinanceProfileDto,
FinanceProfileInput,
FileAttachmentDto,
PlanningTimelineDto,
LoginRequest,
@@ -287,6 +294,21 @@ export const api = {
token
);
},
getFinanceDashboard(token: string) {
return request<FinanceDashboardDto>("/api/v1/finance/overview", undefined, token);
},
updateFinanceProfile(token: string, payload: FinanceProfileInput) {
return request<FinanceProfileDto>("/api/v1/finance/profile", { method: "PUT", body: JSON.stringify(payload) }, token);
},
createFinancePayment(token: string, payload: FinanceCustomerPaymentInput) {
return request<FinanceCustomerPaymentDto>("/api/v1/finance/payments", { method: "POST", body: JSON.stringify(payload) }, token);
},
createCapexEntry(token: string, payload: FinanceCapexInput) {
return request<FinanceCapexDto>("/api/v1/finance/capex", { method: "POST", body: JSON.stringify(payload) }, token);
},
updateCapexEntry(token: string, capexId: string, payload: FinanceCapexInput) {
return request<FinanceCapexDto>(`/api/v1/finance/capex/${capexId}`, { method: "PUT", body: JSON.stringify(payload) }, token);
},
getCustomers(
token: string,
filters?: {

View File

@@ -101,6 +101,9 @@ const ShipmentDetailPage = React.lazy(() =>
const ShipmentFormPage = React.lazy(() =>
import("./modules/shipping/ShipmentFormPage").then((module) => ({ default: module.ShipmentFormPage }))
);
const FinancePage = React.lazy(() =>
import("./modules/finance/FinancePage").then((module) => ({ default: module.FinancePage }))
);
const WorkbenchPage = React.lazy(() =>
import("./modules/workbench/WorkbenchPage").then((module) => ({ default: module.WorkbenchPage }))
);
@@ -201,6 +204,10 @@ const router = createBrowserRouter([
{ path: "/shipping/shipments/:shipmentId", element: lazyElement(<ShipmentDetailPage />) },
],
},
{
element: <ProtectedRoute requiredPermissions={[permissions.financeRead]} />,
children: [{ path: "/finance", element: lazyElement(<FinancePage />) }],
},
{
element: <ProtectedRoute requiredPermissions={[permissions.crmWrite]} />,
children: [

View File

@@ -0,0 +1,481 @@
import { permissions } from "@mrp/shared";
import type {
CapexCategory,
CapexStatus,
FinanceCapexInput,
FinanceCustomerPaymentInput,
FinanceDashboardDto,
FinancePaymentMethod,
FinancePaymentType,
FinanceProfileInput,
} from "@mrp/shared";
import { capexCategories, capexStatuses, financePaymentMethods, financePaymentTypes } from "@mrp/shared";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
function formatCurrency(value: number, currencyCode = "USD") {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: currencyCode,
maximumFractionDigits: 0,
}).format(value);
}
function formatPercent(value: number) {
return `${value.toFixed(1)}%`;
}
export function FinancePage() {
const { token, user } = useAuth();
const canManage = user?.permissions.includes(permissions.financeWrite) ?? false;
const [dashboard, setDashboard] = useState<FinanceDashboardDto | null>(null);
const [salesOrders, setSalesOrders] = useState<Awaited<ReturnType<typeof api.getSalesOrders>>>([]);
const [purchaseOrders, setPurchaseOrders] = useState<Awaited<ReturnType<typeof api.getPurchaseOrders>>>([]);
const [vendors, setVendors] = useState<Awaited<ReturnType<typeof api.getPurchaseVendors>>>([]);
const [status, setStatus] = useState("Loading finance workbench...");
const [isSavingProfile, setIsSavingProfile] = useState(false);
const [isPostingPayment, setIsPostingPayment] = useState(false);
const [isSavingCapex, setIsSavingCapex] = useState(false);
const [editingCapexId, setEditingCapexId] = useState<string | null>(null);
const [profileForm, setProfileForm] = useState<FinanceProfileInput>({
currencyCode: "USD",
standardLaborRatePerHour: 45,
overheadRatePerHour: 18,
});
const [paymentForm, setPaymentForm] = useState<FinanceCustomerPaymentInput>({
salesOrderId: "",
paymentType: "DEPOSIT",
paymentMethod: "ACH",
paymentDate: new Date().toISOString(),
amount: 0,
reference: "",
notes: "",
});
const [capexForm, setCapexForm] = useState<FinanceCapexInput>({
title: "",
category: "EQUIPMENT",
status: "PLANNED",
vendorId: null,
purchaseOrderId: null,
plannedAmount: 0,
actualAmount: 0,
requestDate: new Date().toISOString(),
targetInServiceDate: null,
purchasedAt: null,
notes: "",
});
async function loadFinance(activeToken: string) {
const [nextDashboard, nextSalesOrders, nextPurchaseOrders, nextVendors] = await Promise.all([
api.getFinanceDashboard(activeToken),
api.getSalesOrders(activeToken),
api.getPurchaseOrders(activeToken),
api.getPurchaseVendors(activeToken),
]);
setDashboard(nextDashboard);
setSalesOrders(nextSalesOrders);
setPurchaseOrders(nextPurchaseOrders);
setVendors(nextVendors);
setProfileForm({
currencyCode: nextDashboard.profile.currencyCode,
standardLaborRatePerHour: nextDashboard.profile.standardLaborRatePerHour,
overheadRatePerHour: nextDashboard.profile.overheadRatePerHour,
});
setPaymentForm((current) => ({
...current,
salesOrderId: current.salesOrderId || nextSalesOrders[0]?.id || "",
}));
setStatus("Finance workbench loaded.");
}
useEffect(() => {
if (!token) {
return;
}
loadFinance(token).catch((error: unknown) => {
setStatus(error instanceof ApiError ? error.message : "Unable to load finance workbench.");
});
}, [token]);
function resetCapexForm() {
setEditingCapexId(null);
setCapexForm({
title: "",
category: "EQUIPMENT",
status: "PLANNED",
vendorId: null,
purchaseOrderId: null,
plannedAmount: 0,
actualAmount: 0,
requestDate: new Date().toISOString(),
targetInServiceDate: null,
purchasedAt: null,
notes: "",
});
}
async function handleSaveProfile() {
if (!token) {
return;
}
setIsSavingProfile(true);
setStatus("Saving finance assumptions...");
try {
const nextProfile = await api.updateFinanceProfile(token, profileForm);
setDashboard((current) => (current ? { ...current, profile: nextProfile } : current));
setStatus("Finance assumptions updated.");
} catch (error: unknown) {
setStatus(error instanceof ApiError ? error.message : "Unable to save finance assumptions.");
} finally {
setIsSavingProfile(false);
}
}
async function handlePostPayment() {
if (!token) {
return;
}
setIsPostingPayment(true);
setStatus("Posting customer payment...");
try {
await api.createFinancePayment(token, paymentForm);
await loadFinance(token);
setPaymentForm((current) => ({
...current,
amount: 0,
reference: "",
notes: "",
paymentDate: new Date().toISOString(),
}));
setStatus("Customer payment posted.");
} catch (error: unknown) {
setStatus(error instanceof ApiError ? error.message : "Unable to post customer payment.");
} finally {
setIsPostingPayment(false);
}
}
async function handleSaveCapex() {
if (!token) {
return;
}
setIsSavingCapex(true);
setStatus(editingCapexId ? "Updating CapEx entry..." : "Creating CapEx entry...");
try {
if (editingCapexId) {
await api.updateCapexEntry(token, editingCapexId, capexForm);
} else {
await api.createCapexEntry(token, capexForm);
}
await loadFinance(token);
resetCapexForm();
setStatus(editingCapexId ? "CapEx entry updated." : "CapEx entry created.");
} catch (error: unknown) {
setStatus(error instanceof ApiError ? error.message : "Unable to save CapEx entry.");
} finally {
setIsSavingCapex(false);
}
}
if (!dashboard) {
return <div className="rounded-[20px] border border-line/70 bg-surface/90 p-4 text-sm text-muted shadow-panel">{status}</div>;
}
const { profile, summary, salesOrderLedgers, payments, capex } = dashboard;
const currencyCode = profile.currencyCode || "USD";
return (
<section className="space-y-4">
<div className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Finance</p>
<h2 className="mt-2 text-2xl font-bold text-text">Cash, spend, and CapEx control</h2>
<p className="mt-2 max-w-3xl text-sm text-muted">
Track customer payments against sales orders, compare them to linked purchasing and manufacturing spend, and manage capital purchases for equipment, tooling, and consumables.
</p>
</div>
<div className="rounded-[18px] border border-line/70 bg-page/60 px-3 py-3 text-sm text-muted">
Live snapshot generated {new Date(dashboard.generatedAt).toLocaleString()}
</div>
</div>
</div>
<section className="grid gap-3 xl:grid-cols-6">
{[
{ label: "Booked Revenue", value: formatCurrency(summary.bookedRevenue, currencyCode) },
{ label: "Payments In", value: formatCurrency(summary.paymentsReceived, currencyCode) },
{ label: "A/R Open", value: formatCurrency(summary.accountsReceivableOpen, currencyCode) },
{ label: "PO Spend", value: formatCurrency(summary.linkedPurchaseReceivedValue, currencyCode) },
{ label: "Mfg Cost", value: formatCurrency(summary.manufacturingTotalCost, currencyCode) },
{ label: "CapEx Actual", value: formatCurrency(summary.capexActual, currencyCode) },
].map((card) => (
<article key={card.label} className="rounded-[18px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel">
<p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">{card.label}</p>
<div className="mt-2 text-xl font-extrabold text-text">{card.value}</div>
</article>
))}
</section>
<div className="grid gap-3 xl:grid-cols-[minmax(0,1.15fr)_minmax(360px,0.85fr)]">
<article className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
<div className="flex items-center justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Sales Order Ledger</p>
<p className="mt-2 text-sm text-muted">Revenue, receipts, purchasing, and manufacturing cost by order.</p>
</div>
</div>
<div className="mt-5 overflow-x-auto">
<table className="min-w-full divide-y divide-line/60 text-sm">
<thead>
<tr className="text-left text-xs uppercase tracking-[0.16em] text-muted">
<th className="pb-3 pr-3 font-semibold">Order</th>
<th className="pb-3 pr-3 font-semibold">Revenue</th>
<th className="pb-3 pr-3 font-semibold">Payments</th>
<th className="pb-3 pr-3 font-semibold">PO</th>
<th className="pb-3 pr-3 font-semibold">Manufacturing</th>
<th className="pb-3 pr-3 font-semibold">Spend</th>
<th className="pb-3 font-semibold">Margin</th>
</tr>
</thead>
<tbody className="divide-y divide-line/50">
{salesOrderLedgers.map((ledger) => (
<tr key={ledger.salesOrderId}>
<td className="py-3 pr-3 align-top">
<Link to={`/sales/orders/${ledger.salesOrderId}`} className="font-semibold text-brand hover:underline">
{ledger.salesOrderNumber}
</Link>
<div className="text-xs text-muted">{ledger.customerName}</div>
<div className="text-xs text-muted">
{ledger.linkedPurchaseOrderCount} PO / {ledger.linkedWorkOrderCount} WO
</div>
</td>
<td className="py-3 pr-3 align-top text-text">{formatCurrency(ledger.revenueTotal, currencyCode)}</td>
<td className="py-3 pr-3 align-top">
<div className="text-text">{formatCurrency(ledger.paymentsReceived, currencyCode)}</div>
<div className="text-xs text-muted">A/R {formatCurrency(ledger.accountsReceivableOpen, currencyCode)}</div>
</td>
<td className="py-3 pr-3 align-top">
<div className="text-text">{formatCurrency(ledger.linkedPurchaseReceivedValue, currencyCode)}</div>
<div className="text-xs text-muted">Committed {formatCurrency(ledger.linkedPurchaseCommitted, currencyCode)}</div>
</td>
<td className="py-3 pr-3 align-top">
<div className="text-text">{formatCurrency(ledger.manufacturingTotalCost, currencyCode)}</div>
<div className="text-xs text-muted">
Mat {formatCurrency(ledger.manufacturingMaterialCost, currencyCode)} / Lab+OH {formatCurrency(ledger.manufacturingLaborCost + ledger.manufacturingOverheadCost, currencyCode)}
</div>
</td>
<td className="py-3 pr-3 align-top">
<div className="text-text">{formatCurrency(ledger.totalRecognizedSpend, currencyCode)}</div>
<div className="text-xs text-muted">Coverage {formatPercent(ledger.paymentCoveragePercent)}</div>
</td>
<td className="py-3 align-top">
<div className={`font-semibold ${ledger.grossMarginEstimate >= 0 ? "text-emerald-700 dark:text-emerald-300" : "text-rose-700 dark:text-rose-300"}`}>
{formatCurrency(ledger.grossMarginEstimate, currencyCode)}
</div>
<div className="text-xs text-muted">{formatPercent(ledger.grossMarginPercent)}</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</article>
<div className="space-y-3">
<article className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Costing Assumptions</p>
<div className="mt-4 grid gap-3">
<label className="text-sm text-text">
<span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">Currency</span>
<input value={profileForm.currencyCode} onChange={(event) => setProfileForm((current) => ({ ...current, currencyCode: event.target.value }))} className="w-full rounded-2xl border border-line/70 bg-page px-3 py-2 outline-none" />
</label>
<label className="text-sm text-text">
<span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">Labor Rate / Hour</span>
<input type="number" step="0.01" min={0} value={profileForm.standardLaborRatePerHour} onChange={(event) => setProfileForm((current) => ({ ...current, standardLaborRatePerHour: Number(event.target.value) }))} className="w-full rounded-2xl border border-line/70 bg-page px-3 py-2 outline-none" />
</label>
<label className="text-sm text-text">
<span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">Overhead / Labor Hour</span>
<input type="number" step="0.01" min={0} value={profileForm.overheadRatePerHour} onChange={(event) => setProfileForm((current) => ({ ...current, overheadRatePerHour: Number(event.target.value) }))} className="w-full rounded-2xl border border-line/70 bg-page px-3 py-2 outline-none" />
</label>
</div>
{canManage ? (
<button type="button" onClick={() => void handleSaveProfile()} disabled={isSavingProfile} className="mt-4 inline-flex rounded-2xl bg-brand px-4 py-2 text-sm font-semibold text-white disabled:opacity-60">
{isSavingProfile ? "Saving..." : "Save assumptions"}
</button>
) : null}
</article>
<article className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Post Payment</p>
<div className="mt-4 grid gap-3">
<select value={paymentForm.salesOrderId} onChange={(event) => setPaymentForm((current) => ({ ...current, salesOrderId: event.target.value }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none">
{salesOrders.map((order) => (
<option key={order.id} value={order.id}>
{order.documentNumber} / {order.customerName}
</option>
))}
</select>
<div className="grid gap-3 sm:grid-cols-2">
<select value={paymentForm.paymentType} onChange={(event) => setPaymentForm((current) => ({ ...current, paymentType: event.target.value as FinancePaymentType }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none">
{financePaymentTypes.map((type) => <option key={type} value={type}>{type}</option>)}
</select>
<select value={paymentForm.paymentMethod} onChange={(event) => setPaymentForm((current) => ({ ...current, paymentMethod: event.target.value as FinancePaymentMethod }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none">
{financePaymentMethods.map((method) => <option key={method} value={method}>{method}</option>)}
</select>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<input type="datetime-local" value={paymentForm.paymentDate.slice(0, 16)} onChange={(event) => setPaymentForm((current) => ({ ...current, paymentDate: new Date(event.target.value).toISOString() }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
<input type="number" min={0} step="0.01" value={paymentForm.amount} onChange={(event) => setPaymentForm((current) => ({ ...current, amount: Number(event.target.value) }))} placeholder="Amount" className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
</div>
<input value={paymentForm.reference} onChange={(event) => setPaymentForm((current) => ({ ...current, reference: event.target.value }))} placeholder="Reference / remittance" className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
<textarea value={paymentForm.notes} onChange={(event) => setPaymentForm((current) => ({ ...current, notes: event.target.value }))} placeholder="Notes" rows={3} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
</div>
{canManage ? (
<button type="button" onClick={() => void handlePostPayment()} disabled={isPostingPayment || !paymentForm.salesOrderId || paymentForm.amount <= 0} className="mt-4 inline-flex rounded-2xl bg-brand px-4 py-2 text-sm font-semibold text-white disabled:opacity-60">
{isPostingPayment ? "Posting..." : "Post payment"}
</button>
) : null}
</article>
</div>
</div>
<div className="grid gap-3 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]">
<article className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
<div className="flex items-center justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Recent Payments</p>
<p className="mt-2 text-sm text-muted">Posted receipts linked directly to sales orders.</p>
</div>
</div>
<div className="mt-5 space-y-3">
{payments.length === 0 ? (
<div className="rounded-[18px] border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">No payments posted yet.</div>
) : (
payments.map((payment) => (
<div key={payment.id} className="rounded-[18px] border border-line/70 bg-page/60 p-3">
<div className="flex items-start justify-between gap-3">
<div>
<Link to={`/sales/orders/${payment.salesOrderId}`} className="font-semibold text-brand hover:underline">
{payment.salesOrderNumber}
</Link>
<div className="text-xs text-muted">{payment.customerName}</div>
<div className="mt-1 text-sm text-text">{payment.paymentType} via {payment.paymentMethod}</div>
</div>
<div className="text-right">
<div className="font-semibold text-text">{formatCurrency(payment.amount, currencyCode)}</div>
<div className="text-xs text-muted">{new Date(payment.paymentDate).toLocaleString()}</div>
</div>
</div>
<div className="mt-2 text-xs text-muted">{payment.reference || "No reference"} / {payment.createdByName}</div>
</div>
))
)}
</div>
</article>
<article className="rounded-[20px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
<div className="flex items-center justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">CapEx Tracker</p>
<p className="mt-2 text-sm text-muted">Manage equipment, tooling, and consumable capital plans with optional PO linkage.</p>
</div>
{editingCapexId ? (
<button type="button" onClick={resetCapexForm} className="rounded-2xl border border-line/70 px-3 py-2 text-sm font-semibold text-text">
Clear edit
</button>
) : null}
</div>
<div className="mt-5 grid gap-3 lg:grid-cols-2">
<input value={capexForm.title} onChange={(event) => setCapexForm((current) => ({ ...current, title: event.target.value }))} placeholder="CapEx title" className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
<select value={capexForm.category} onChange={(event) => setCapexForm((current) => ({ ...current, category: event.target.value as CapexCategory }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none">
{capexCategories.map((category) => <option key={category} value={category}>{category}</option>)}
</select>
<select value={capexForm.status} onChange={(event) => setCapexForm((current) => ({ ...current, status: event.target.value as CapexStatus }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none">
{capexStatuses.map((capexStatus) => <option key={capexStatus} value={capexStatus}>{capexStatus}</option>)}
</select>
<select value={capexForm.vendorId ?? ""} onChange={(event) => setCapexForm((current) => ({ ...current, vendorId: event.target.value || null }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none">
<option value="">No vendor linked</option>
{vendors.map((vendor) => <option key={vendor.id} value={vendor.id}>{vendor.name}</option>)}
</select>
<select value={capexForm.purchaseOrderId ?? ""} onChange={(event) => setCapexForm((current) => ({ ...current, purchaseOrderId: event.target.value || null }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none">
<option value="">No purchase order linked</option>
{purchaseOrders.map((order) => <option key={order.id} value={order.id}>{order.documentNumber} / {order.vendorName}</option>)}
</select>
<div className="grid gap-3 sm:grid-cols-2">
<input type="number" min={0} step="0.01" value={capexForm.plannedAmount} onChange={(event) => setCapexForm((current) => ({ ...current, plannedAmount: Number(event.target.value) }))} placeholder="Planned amount" className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
<input type="number" min={0} step="0.01" value={capexForm.actualAmount} onChange={(event) => setCapexForm((current) => ({ ...current, actualAmount: Number(event.target.value) }))} placeholder="Actual amount" className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
</div>
<input type="date" value={capexForm.requestDate.slice(0, 10)} onChange={(event) => setCapexForm((current) => ({ ...current, requestDate: new Date(`${event.target.value}T00:00:00`).toISOString() }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
<input type="date" value={capexForm.targetInServiceDate ? capexForm.targetInServiceDate.slice(0, 10) : ""} onChange={(event) => setCapexForm((current) => ({ ...current, targetInServiceDate: event.target.value ? new Date(`${event.target.value}T00:00:00`).toISOString() : null }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
<input type="date" value={capexForm.purchasedAt ? capexForm.purchasedAt.slice(0, 10) : ""} onChange={(event) => setCapexForm((current) => ({ ...current, purchasedAt: event.target.value ? new Date(`${event.target.value}T00:00:00`).toISOString() : null }))} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none" />
<textarea value={capexForm.notes} onChange={(event) => setCapexForm((current) => ({ ...current, notes: event.target.value }))} placeholder="Business justification, install notes, or sourcing detail" rows={3} className="rounded-2xl border border-line/70 bg-page px-3 py-2 text-sm text-text outline-none lg:col-span-2" />
</div>
{canManage ? (
<button type="button" onClick={() => void handleSaveCapex()} disabled={isSavingCapex || !capexForm.title.trim()} className="mt-4 inline-flex rounded-2xl bg-brand px-4 py-2 text-sm font-semibold text-white disabled:opacity-60">
{isSavingCapex ? "Saving..." : editingCapexId ? "Update CapEx" : "Create CapEx"}
</button>
) : null}
<div className="mt-5 space-y-3">
{capex.length === 0 ? (
<div className="rounded-[18px] border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">No CapEx entries yet.</div>
) : (
capex.map((entry) => (
<button
key={entry.id}
type="button"
onClick={() => {
setEditingCapexId(entry.id);
setCapexForm({
title: entry.title,
category: entry.category,
status: entry.status,
vendorId: entry.vendorId,
purchaseOrderId: entry.purchaseOrderId,
plannedAmount: entry.plannedAmount,
actualAmount: entry.actualAmount,
requestDate: entry.requestDate,
targetInServiceDate: entry.targetInServiceDate,
purchasedAt: entry.purchasedAt,
notes: entry.notes,
});
}}
className="block w-full rounded-[18px] border border-line/70 bg-page/60 p-3 text-left transition hover:bg-page/80"
>
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="font-semibold text-text">{entry.title}</div>
<div className="text-xs text-muted">
{entry.category} / {entry.status}
{entry.vendorName ? ` / ${entry.vendorName}` : ""}
{entry.purchaseOrderNumber ? ` / ${entry.purchaseOrderNumber}` : ""}
</div>
</div>
<div className="text-right">
<div className="font-semibold text-text">{formatCurrency(entry.actualAmount || entry.plannedAmount, currencyCode)}</div>
<div className="text-xs text-muted">Plan {formatCurrency(entry.plannedAmount, currencyCode)}</div>
</div>
</div>
</button>
))
)}
</div>
</article>
</div>
<div className="rounded-[20px] border border-line/70 bg-surface/90 p-4 text-sm text-muted shadow-panel">
{status}
</div>
</section>
);
}