1341 lines
43 KiB
TypeScript
1341 lines
43 KiB
TypeScript
import { useState, useEffect } from "react";
|
||
import { Link } from "react-router-dom";
|
||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||
import type { ColumnDef } from "@tanstack/react-table";
|
||
import {
|
||
Plus,
|
||
RefreshCw,
|
||
History,
|
||
Paperclip,
|
||
Pencil,
|
||
Trash2,
|
||
Search,
|
||
AlertCircle,
|
||
} from "lucide-react";
|
||
import {
|
||
contractsApi,
|
||
warrantiesApi,
|
||
type ContractItem,
|
||
type WarrantyItem,
|
||
} from "@/api/phase5";
|
||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||
import { departmentsApi, vendorsApi } from "@/api/masters";
|
||
import { ApiError } from "@/api/client";
|
||
import { useAuthStore } from "@/hooks/useAuth";
|
||
import { can } from "@/lib/permissions";
|
||
import { formatDate } from "@/lib/format";
|
||
import { DataTable } from "@/components/DataTable";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Modal } from "@/components/ui/dialog";
|
||
import { ExpiryChip } from "@/components/StatusBadge";
|
||
import { AssetPicker } from "@/components/AssetPicker";
|
||
import { Attachments } from "@/components/Attachments";
|
||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||
import { toast } from "@/components/ToastProvider";
|
||
|
||
type TabKey = "contracts" | "warranties";
|
||
|
||
const inputCls =
|
||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||
|
||
function addMonthsISO(isoDate: string, months: number): string {
|
||
if (!isoDate || !Number.isFinite(months) || months <= 0) return "";
|
||
const [y, m, d] = isoDate.split("-").map(Number);
|
||
if (!y || !m || !d) return "";
|
||
const totalMonths = m - 1 + months;
|
||
const targetYear = y + Math.floor(totalMonths / 12);
|
||
const targetMonth = ((totalMonths % 12) + 12) % 12;
|
||
const maxDay = new Date(targetYear, targetMonth + 1, 0).getDate();
|
||
const clampedDay = Math.min(d, maxDay);
|
||
return `${targetYear}-${String(targetMonth + 1).padStart(2, "0")}-${String(
|
||
clampedDay
|
||
).padStart(2, "0")}`;
|
||
}
|
||
|
||
function addDaysISO(isoDate: string, days: number): string {
|
||
if (!isoDate) return "";
|
||
const [y, m, d] = isoDate.split("-").map(Number);
|
||
if (!y || !m || !d) return "";
|
||
const dt = new Date(Date.UTC(y, m - 1, d + days));
|
||
return dt.toISOString().slice(0, 10);
|
||
}
|
||
|
||
const STATUS_CHIPS = [
|
||
{ key: "", label: "All" },
|
||
{ key: "active", label: "Active" },
|
||
{ key: "expiring", label: "Expiring Soon" },
|
||
{ key: "expired", label: "Expired" },
|
||
];
|
||
|
||
export function ContractsPage() {
|
||
const qc = useQueryClient();
|
||
const role = useAuthStore((s) => s.user?.role);
|
||
const isDeptUser = role === "department_user";
|
||
const canManage = can(role, "manage_calibration_contracts");
|
||
|
||
const [tab, setTab] = useState<TabKey>("contracts");
|
||
const [statusFilter, setStatusFilter] = useState("");
|
||
const [includeSuperseded, setIncludeSuperseded] = useState(true);
|
||
const [q, setQ] = useState("");
|
||
const [departmentId, setDepartmentId] = useState("");
|
||
const [providerId, setProviderId] = useState("");
|
||
const [contractTypeFilter, setContractTypeFilter] = useState("");
|
||
|
||
// Contract modals
|
||
const [contractFormOpen, setContractFormOpen] = useState(false);
|
||
const [editingContract, setEditingContract] = useState<ContractItem | null>(null);
|
||
const [renewTarget, setRenewTarget] = useState<ContractItem | null>(null);
|
||
const [historyAsset, setHistoryAsset] = useState<{
|
||
assetId: number;
|
||
label: string;
|
||
} | null>(null);
|
||
|
||
// Warranty modals
|
||
const [warrantyFormOpen, setWarrantyFormOpen] = useState(false);
|
||
const [editingWarranty, setEditingWarranty] = useState<WarrantyItem | null>(null);
|
||
|
||
// Attachments modal
|
||
const [attachTarget, setAttachTarget] = useState<{
|
||
entityType: "contract" | "warranty";
|
||
entityId: number;
|
||
title: string;
|
||
} | null>(null);
|
||
|
||
// Confirm delete dialog
|
||
const [deleteTarget, setDeleteTarget] = useState<{
|
||
kind: "contract" | "warranty";
|
||
id: number;
|
||
label: string;
|
||
} | null>(null);
|
||
|
||
const deptsQuery = useQuery({
|
||
queryKey: ["departments", "active-only"],
|
||
queryFn: () => departmentsApi.list(false),
|
||
enabled: !isDeptUser,
|
||
});
|
||
|
||
const vendorsQuery = useQuery({
|
||
queryKey: ["vendors", "active-only"],
|
||
queryFn: () => vendorsApi.list(false),
|
||
});
|
||
|
||
const contractsQuery = useQuery({
|
||
queryKey: [
|
||
"contracts",
|
||
q,
|
||
departmentId,
|
||
providerId,
|
||
contractTypeFilter,
|
||
statusFilter,
|
||
includeSuperseded,
|
||
],
|
||
queryFn: () =>
|
||
contractsApi.list({
|
||
q: q.trim() || undefined,
|
||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||
provider_id: providerId ? Number(providerId) : undefined,
|
||
contract_type: contractTypeFilter || undefined,
|
||
status: statusFilter || undefined,
|
||
include_superseded: includeSuperseded,
|
||
page_size: 200,
|
||
}),
|
||
enabled: tab === "contracts",
|
||
});
|
||
|
||
const warrantiesQuery = useQuery({
|
||
queryKey: ["warranties", q, departmentId, statusFilter],
|
||
queryFn: () =>
|
||
warrantiesApi.list({
|
||
q: q.trim() || undefined,
|
||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||
status: statusFilter || undefined,
|
||
page_size: 200,
|
||
}),
|
||
enabled: tab === "warranties",
|
||
});
|
||
|
||
const deleteContractMutation = useMutation({
|
||
mutationFn: (id: number) => contractsApi.remove(id),
|
||
onSuccess: () => {
|
||
setDeleteTarget(null);
|
||
qc.invalidateQueries({ queryKey: ["contracts"] });
|
||
qc.invalidateQueries({ queryKey: ["assets"] });
|
||
toast.success("Contract deleted");
|
||
},
|
||
onError: (err) => {
|
||
toast.error(err instanceof ApiError ? err.detail : "Failed to delete contract");
|
||
},
|
||
});
|
||
|
||
const deleteWarrantyMutation = useMutation({
|
||
mutationFn: (id: number) => warrantiesApi.remove(id),
|
||
onSuccess: () => {
|
||
setDeleteTarget(null);
|
||
qc.invalidateQueries({ queryKey: ["warranties"] });
|
||
qc.invalidateQueries({ queryKey: ["assets"] });
|
||
toast.success("Warranty deleted");
|
||
},
|
||
onError: (err) => {
|
||
toast.error(err instanceof ApiError ? err.detail : "Failed to delete warranty");
|
||
},
|
||
});
|
||
|
||
const departments = deptsQuery.data?.items ?? [];
|
||
const allVendors = vendorsQuery.data?.items ?? [];
|
||
const contractProviders = allVendors.filter(
|
||
(v) =>
|
||
v.vendor_type === "service_provider" ||
|
||
v.vendor_type === "oem" ||
|
||
v.vendor_type === "supplier"
|
||
);
|
||
|
||
const contractColumns: ColumnDef<ContractItem, unknown>[] = [
|
||
{
|
||
id: "asset",
|
||
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
|
||
header: "Asset",
|
||
cell: ({ row }) => (
|
||
<Link to={`/assets/${row.original.asset_id}`} className="hover:underline">
|
||
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
|
||
{row.original.asset_code}
|
||
</div>
|
||
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
|
||
</Link>
|
||
),
|
||
},
|
||
{
|
||
accessorKey: "department_name",
|
||
header: "Department",
|
||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||
},
|
||
{
|
||
accessorKey: "contract_type",
|
||
header: "Type",
|
||
cell: ({ getValue }) => (
|
||
<Badge variant="outline" className="uppercase">
|
||
{String(getValue())}
|
||
</Badge>
|
||
),
|
||
},
|
||
{
|
||
accessorKey: "provider_name",
|
||
header: "Provider",
|
||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||
},
|
||
{
|
||
accessorKey: "start_date",
|
||
header: "Start",
|
||
cell: ({ getValue }) => (
|
||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||
),
|
||
},
|
||
{
|
||
accessorKey: "end_date",
|
||
header: "End",
|
||
cell: ({ getValue }) => (
|
||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||
),
|
||
},
|
||
{
|
||
id: "expiry",
|
||
accessorFn: (r) => r.days_to_expiry,
|
||
header: "Status",
|
||
cell: ({ row }) => (
|
||
<ExpiryChip
|
||
daysToExpiry={row.original.days_to_expiry}
|
||
status={row.original.status}
|
||
severity={row.original.severity}
|
||
/>
|
||
),
|
||
},
|
||
{
|
||
id: "attachments",
|
||
header: "Docs",
|
||
enableSorting: false,
|
||
enableColumnFilter: false,
|
||
cell: ({ row }) => (
|
||
<Button
|
||
size="sm"
|
||
variant="ghost"
|
||
onClick={() =>
|
||
setAttachTarget({
|
||
entityType: "contract",
|
||
entityId: row.original.id,
|
||
title: `Contract Docs — ${row.original.asset_code} (${row.original.contract_type})`,
|
||
})
|
||
}
|
||
title="View or upload contract documents"
|
||
>
|
||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||
<span className="text-xs">{row.original.attachment_count}</span>
|
||
</Button>
|
||
),
|
||
},
|
||
{
|
||
id: "actions",
|
||
header: "Actions",
|
||
enableSorting: false,
|
||
enableColumnFilter: false,
|
||
cell: ({ row }) => (
|
||
<div className="flex items-center gap-1 flex-wrap">
|
||
{canManage && !row.original.is_superseded && (
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={() => setRenewTarget(row.original)}
|
||
title="Renew contract"
|
||
>
|
||
<RefreshCw className="h-3.5 w-3.5 mr-1" />
|
||
Renew
|
||
</Button>
|
||
)}
|
||
<Button
|
||
size="sm"
|
||
variant="ghost"
|
||
onClick={() =>
|
||
setHistoryAsset({
|
||
assetId: row.original.asset_id,
|
||
label: `${row.original.asset_code} — ${row.original.asset_name}`,
|
||
})
|
||
}
|
||
title="View renewal history"
|
||
>
|
||
<History className="h-3.5 w-3.5 mr-1" />
|
||
History
|
||
</Button>
|
||
{canManage && (
|
||
<>
|
||
<Button
|
||
size="sm"
|
||
variant="ghost"
|
||
onClick={() => {
|
||
setEditingContract(row.original);
|
||
setContractFormOpen(true);
|
||
}}
|
||
aria-label={`Edit contract ${row.original.id}`}
|
||
>
|
||
<Pencil className="h-3.5 w-3.5" />
|
||
</Button>
|
||
<Button
|
||
size="sm"
|
||
variant="ghost"
|
||
className="text-red-600 hover:text-red-700"
|
||
onClick={() =>
|
||
setDeleteTarget({
|
||
kind: "contract",
|
||
id: row.original.id,
|
||
label: `${row.original.asset_code} (${row.original.contract_type})`,
|
||
})
|
||
}
|
||
aria-label={`Delete contract ${row.original.id}`}
|
||
>
|
||
<Trash2 className="h-3.5 w-3.5" />
|
||
</Button>
|
||
</>
|
||
)}
|
||
</div>
|
||
),
|
||
},
|
||
];
|
||
|
||
const warrantyColumns: ColumnDef<WarrantyItem, unknown>[] = [
|
||
{
|
||
id: "asset",
|
||
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
|
||
header: "Asset",
|
||
cell: ({ row }) => (
|
||
<Link to={`/assets/${row.original.asset_id}`} className="hover:underline">
|
||
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
|
||
{row.original.asset_code}
|
||
</div>
|
||
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
|
||
</Link>
|
||
),
|
||
},
|
||
{
|
||
accessorKey: "department_name",
|
||
header: "Department",
|
||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||
},
|
||
{
|
||
accessorKey: "provider_name",
|
||
header: "Provider / OEM",
|
||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||
},
|
||
{
|
||
accessorKey: "duration_months",
|
||
header: "Duration",
|
||
cell: ({ getValue }) => `${getValue()} mo`,
|
||
},
|
||
{
|
||
accessorKey: "start_date",
|
||
header: "Start",
|
||
cell: ({ getValue }) => (
|
||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||
),
|
||
},
|
||
{
|
||
accessorKey: "end_date",
|
||
header: "End",
|
||
cell: ({ getValue }) => (
|
||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||
),
|
||
},
|
||
{
|
||
id: "expiry",
|
||
accessorFn: (r) => r.days_to_expiry,
|
||
header: "Status",
|
||
cell: ({ row }) => (
|
||
<ExpiryChip
|
||
daysToExpiry={row.original.days_to_expiry}
|
||
status={row.original.status}
|
||
severity={row.original.severity}
|
||
/>
|
||
),
|
||
},
|
||
{
|
||
id: "attachments",
|
||
header: "Docs",
|
||
enableSorting: false,
|
||
enableColumnFilter: false,
|
||
cell: ({ row }) => (
|
||
<Button
|
||
size="sm"
|
||
variant="ghost"
|
||
onClick={() =>
|
||
setAttachTarget({
|
||
entityType: "warranty",
|
||
entityId: row.original.id,
|
||
title: `Warranty Docs — ${row.original.asset_code}`,
|
||
})
|
||
}
|
||
>
|
||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||
<span className="text-xs">{row.original.attachment_count}</span>
|
||
</Button>
|
||
),
|
||
},
|
||
...(canManage
|
||
? [
|
||
{
|
||
id: "actions",
|
||
header: "Actions",
|
||
enableSorting: false,
|
||
enableColumnFilter: false,
|
||
cell: ({ row }: { row: { original: WarrantyItem } }) => (
|
||
<div className="flex items-center gap-1">
|
||
<Button
|
||
size="sm"
|
||
variant="ghost"
|
||
onClick={() => {
|
||
setEditingWarranty(row.original);
|
||
setWarrantyFormOpen(true);
|
||
}}
|
||
aria-label={`Edit warranty ${row.original.id}`}
|
||
>
|
||
<Pencil className="h-3.5 w-3.5" />
|
||
</Button>
|
||
<Button
|
||
size="sm"
|
||
variant="ghost"
|
||
className="text-red-600 hover:text-red-700"
|
||
onClick={() =>
|
||
setDeleteTarget({
|
||
kind: "warranty",
|
||
id: row.original.id,
|
||
label: `${row.original.asset_code} warranty`,
|
||
})
|
||
}
|
||
aria-label={`Delete warranty ${row.original.id}`}
|
||
>
|
||
<Trash2 className="h-3.5 w-3.5" />
|
||
</Button>
|
||
</div>
|
||
),
|
||
} satisfies ColumnDef<WarrantyItem, unknown>,
|
||
]
|
||
: []),
|
||
];
|
||
|
||
return (
|
||
<div className="space-y-4">
|
||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||
<div>
|
||
<h1 className="text-2xl font-bold text-gray-900">Contracts & Warranty</h1>
|
||
<p className="text-sm text-gray-500 mt-0.5">
|
||
Track AMC/CMC contracts, renewal chains, and equipment warranty coverage
|
||
</p>
|
||
</div>
|
||
{canManage && (
|
||
<Button
|
||
onClick={() => {
|
||
if (tab === "contracts") {
|
||
setEditingContract(null);
|
||
setContractFormOpen(true);
|
||
} else {
|
||
setEditingWarranty(null);
|
||
setWarrantyFormOpen(true);
|
||
}
|
||
}}
|
||
>
|
||
<Plus className="h-4 w-4 mr-1.5" />
|
||
{tab === "contracts" ? "Add Contract" : "Add Warranty"}
|
||
</Button>
|
||
)}
|
||
</div>
|
||
|
||
{/* Tabs */}
|
||
<div className="flex gap-1 border-b border-gray-200 overflow-x-auto whitespace-nowrap">
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
setTab("contracts");
|
||
setStatusFilter("");
|
||
}}
|
||
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
|
||
tab === "contracts"
|
||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||
}`}
|
||
>
|
||
AMC / CMC Contracts
|
||
</button>
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
setTab("warranties");
|
||
setStatusFilter("");
|
||
}}
|
||
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
|
||
tab === "warranties"
|
||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||
}`}
|
||
>
|
||
Warranties
|
||
</button>
|
||
</div>
|
||
|
||
{/* Filter Chips & Bar */}
|
||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 space-y-3">
|
||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||
<div className="flex flex-wrap gap-1.5">
|
||
{STATUS_CHIPS.map((chip) => (
|
||
<button
|
||
key={chip.key}
|
||
type="button"
|
||
onClick={() => setStatusFilter(chip.key)}
|
||
className={`px-3 py-1 rounded-full text-xs font-medium border transition-colors ${
|
||
statusFilter === chip.key
|
||
? "bg-[#1e3a8a] text-white border-[#1e3a8a]"
|
||
: "bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100"
|
||
}`}
|
||
>
|
||
{chip.label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
{tab === "contracts" && (
|
||
<label className="inline-flex items-center gap-2 text-xs text-gray-700 cursor-pointer">
|
||
<input
|
||
type="checkbox"
|
||
checked={includeSuperseded}
|
||
onChange={(e) => setIncludeSuperseded(e.target.checked)}
|
||
className="h-3.5 w-3.5 rounded border-gray-300 text-[#1e3a8a]"
|
||
/>
|
||
Include Superseded
|
||
</label>
|
||
)}
|
||
</div>
|
||
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2.5">
|
||
<div className="relative">
|
||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
|
||
<input
|
||
type="text"
|
||
value={q}
|
||
onChange={(e) => setQ(e.target.value)}
|
||
placeholder="Search asset code, name, remarks..."
|
||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||
/>
|
||
</div>
|
||
|
||
{!isDeptUser && (
|
||
<select
|
||
value={departmentId}
|
||
onChange={(e) => setDepartmentId(e.target.value)}
|
||
aria-label="Filter by Department"
|
||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||
>
|
||
<option value="">All Departments</option>
|
||
{departments.map((d) => (
|
||
<option key={d.id} value={String(d.id)}>
|
||
{d.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
)}
|
||
|
||
{tab === "contracts" && (
|
||
<>
|
||
<select
|
||
value={providerId}
|
||
onChange={(e) => setProviderId(e.target.value)}
|
||
aria-label="Filter by Provider"
|
||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||
>
|
||
<option value="">All Providers</option>
|
||
{contractProviders.map((v) => (
|
||
<option key={v.id} value={String(v.id)}>
|
||
{v.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
|
||
<select
|
||
value={contractTypeFilter}
|
||
onChange={(e) => setContractTypeFilter(e.target.value)}
|
||
aria-label="Filter by Contract Type"
|
||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||
>
|
||
<option value="">All Types (AMC/CMC)</option>
|
||
<option value="AMC">AMC</option>
|
||
<option value="CMC">CMC</option>
|
||
</select>
|
||
</>
|
||
)}
|
||
</div>
|
||
</div>
|
||
|
||
{tab === "contracts" ? (
|
||
<DataTable
|
||
data={contractsQuery.data?.items ?? []}
|
||
columns={contractColumns}
|
||
loading={contractsQuery.isLoading}
|
||
globalFilterPlaceholder="Quick filter contracts..."
|
||
exportFilename="contracts"
|
||
emptyMessage="No contracts match the selected filters."
|
||
/>
|
||
) : (
|
||
<DataTable
|
||
data={warrantiesQuery.data?.items ?? []}
|
||
columns={warrantyColumns}
|
||
loading={warrantiesQuery.isLoading}
|
||
globalFilterPlaceholder="Quick filter warranties..."
|
||
exportFilename="warranties"
|
||
emptyMessage="No warranties match the selected filters."
|
||
/>
|
||
)}
|
||
|
||
{/* Contract Add/Edit Modal */}
|
||
<ContractFormModal
|
||
open={contractFormOpen}
|
||
onClose={() => setContractFormOpen(false)}
|
||
editing={editingContract}
|
||
providers={contractProviders.length ? contractProviders : allVendors}
|
||
/>
|
||
|
||
{/* Contract Renew Modal */}
|
||
<RenewContractModal
|
||
open={Boolean(renewTarget)}
|
||
onClose={() => setRenewTarget(null)}
|
||
contract={renewTarget}
|
||
providers={contractProviders.length ? contractProviders : allVendors}
|
||
/>
|
||
|
||
{/* Contract History Modal */}
|
||
<ContractHistoryModal
|
||
open={Boolean(historyAsset)}
|
||
onClose={() => setHistoryAsset(null)}
|
||
assetId={historyAsset?.assetId ?? null}
|
||
assetLabel={historyAsset?.label ?? ""}
|
||
/>
|
||
|
||
{/* Warranty Add/Edit Modal */}
|
||
<WarrantyFormModal
|
||
open={warrantyFormOpen}
|
||
onClose={() => setWarrantyFormOpen(false)}
|
||
editing={editingWarranty}
|
||
providers={contractProviders.length ? contractProviders : allVendors}
|
||
/>
|
||
|
||
{/* Row Attachments Modal */}
|
||
<Modal
|
||
open={Boolean(attachTarget)}
|
||
onOpenChange={(o) => !o && setAttachTarget(null)}
|
||
title={attachTarget?.title ?? "Documents"}
|
||
className="max-w-xl"
|
||
>
|
||
{attachTarget && (
|
||
<Attachments
|
||
entityType={attachTarget.entityType}
|
||
entityId={attachTarget.entityId}
|
||
canUpload={canManage}
|
||
canDelete={canManage}
|
||
/>
|
||
)}
|
||
</Modal>
|
||
|
||
<ConfirmDialog
|
||
open={Boolean(deleteTarget)}
|
||
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||
title={
|
||
deleteTarget?.kind === "warranty" ? "Delete Warranty" : "Delete Contract"
|
||
}
|
||
message={`Are you sure you want to delete ${deleteTarget?.label ?? "this record"}?`}
|
||
confirmLabel="Delete"
|
||
variant="danger"
|
||
loading={
|
||
deleteContractMutation.isPending || deleteWarrantyMutation.isPending
|
||
}
|
||
onConfirm={() => {
|
||
if (!deleteTarget) return;
|
||
if (deleteTarget.kind === "warranty") {
|
||
deleteWarrantyMutation.mutate(deleteTarget.id);
|
||
} else {
|
||
deleteContractMutation.mutate(deleteTarget.id);
|
||
}
|
||
}}
|
||
/>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ContractFormModal({
|
||
open,
|
||
onClose,
|
||
editing,
|
||
providers,
|
||
}: {
|
||
open: boolean;
|
||
onClose: () => void;
|
||
editing: ContractItem | null;
|
||
providers: Array<{ id: number; name: string }>;
|
||
}) {
|
||
const qc = useQueryClient();
|
||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||
const [contractType, setContractType] = useState("AMC");
|
||
const [providerId, setProviderId] = useState("");
|
||
const [startDate, setStartDate] = useState("");
|
||
const [endDate, setEndDate] = useState("");
|
||
const [coveragePeriodText, setCoveragePeriodText] = useState("");
|
||
const [remarks, setRemarks] = useState("");
|
||
const [submitting, setSubmitting] = useState(false);
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
if (!open) return;
|
||
setError(null);
|
||
if (editing) {
|
||
setContractType(editing.contract_type || "AMC");
|
||
setProviderId(String(editing.provider_id));
|
||
setStartDate(editing.start_date);
|
||
setEndDate(editing.end_date);
|
||
setCoveragePeriodText(editing.coverage_period_text ?? "");
|
||
setRemarks(editing.remarks ?? "");
|
||
assetsApi
|
||
.get(editing.asset_id)
|
||
.then((a) =>
|
||
setSelectedAsset({
|
||
...a,
|
||
contract_summary: a.contract_type ?? "None",
|
||
insurance_summary: a.insurance_status,
|
||
})
|
||
)
|
||
.catch(() => setSelectedAsset(null));
|
||
} else {
|
||
const today = new Date().toISOString().slice(0, 10);
|
||
setSelectedAsset(null);
|
||
setContractType("AMC");
|
||
setProviderId("");
|
||
setStartDate(today);
|
||
setEndDate(addMonthsISO(today, 12));
|
||
setCoveragePeriodText("1 Year");
|
||
setRemarks("");
|
||
}
|
||
}, [open, editing]);
|
||
|
||
async function handleSubmit(e: React.FormEvent) {
|
||
e.preventDefault();
|
||
if (!editing && !selectedAsset) {
|
||
setError("Please select an asset.");
|
||
return;
|
||
}
|
||
if (!providerId) {
|
||
setError("Please select a service provider.");
|
||
return;
|
||
}
|
||
setSubmitting(true);
|
||
setError(null);
|
||
try {
|
||
if (editing) {
|
||
await contractsApi.update(editing.id, {
|
||
contract_type: contractType,
|
||
provider_id: Number(providerId),
|
||
start_date: startDate,
|
||
end_date: endDate,
|
||
coverage_period_text: coveragePeriodText.trim() || null,
|
||
remarks: remarks.trim() || null,
|
||
});
|
||
} else {
|
||
await contractsApi.create({
|
||
asset_id: selectedAsset!.id,
|
||
contract_type: contractType,
|
||
provider_id: Number(providerId),
|
||
start_date: startDate,
|
||
end_date: endDate,
|
||
coverage_period_text: coveragePeriodText.trim() || null,
|
||
remarks: remarks.trim() || null,
|
||
});
|
||
}
|
||
await qc.invalidateQueries({ queryKey: ["contracts"] });
|
||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||
onClose();
|
||
} catch (err) {
|
||
setError(err instanceof ApiError ? err.detail : "Failed to save contract.");
|
||
} finally {
|
||
setSubmitting(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Modal
|
||
open={open}
|
||
onOpenChange={(o) => !o && onClose()}
|
||
title={editing ? `Edit Contract — ${editing.asset_code}` : "Add AMC / CMC Contract"}
|
||
className="max-w-2xl"
|
||
>
|
||
{error && (
|
||
<div
|
||
role="alert"
|
||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||
>
|
||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||
<span>{error}</span>
|
||
</div>
|
||
)}
|
||
<form onSubmit={handleSubmit} className="space-y-4">
|
||
<div>
|
||
<label className={labelCls}>Asset *</label>
|
||
<AssetPicker
|
||
selectedAsset={selectedAsset}
|
||
onSelect={setSelectedAsset}
|
||
disabled={Boolean(editing)}
|
||
/>
|
||
</div>
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||
<div>
|
||
<label className={labelCls}>Contract Type *</label>
|
||
<select
|
||
value={contractType}
|
||
onChange={(e) => setContractType(e.target.value)}
|
||
className={inputCls}
|
||
>
|
||
<option value="AMC">AMC</option>
|
||
<option value="CMC">CMC</option>
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Service Provider *</label>
|
||
<select
|
||
required
|
||
value={providerId}
|
||
onChange={(e) => setProviderId(e.target.value)}
|
||
className={inputCls}
|
||
>
|
||
<option value="">Select provider...</option>
|
||
{providers.map((p) => (
|
||
<option key={p.id} value={String(p.id)}>
|
||
{p.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Start Date *</label>
|
||
<input
|
||
type="date"
|
||
required
|
||
value={startDate}
|
||
onChange={(e) => setStartDate(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>End Date *</label>
|
||
<input
|
||
type="date"
|
||
required
|
||
value={endDate}
|
||
onChange={(e) => setEndDate(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Coverage Period Description</label>
|
||
<input
|
||
type="text"
|
||
value={coveragePeriodText}
|
||
onChange={(e) => setCoveragePeriodText(e.target.value)}
|
||
placeholder="e.g. 1 Year Comprehensive, 4 PM visits/year"
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Remarks</label>
|
||
<textarea
|
||
rows={2}
|
||
value={remarks}
|
||
onChange={(e) => setRemarks(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div className="flex justify-end gap-2 pt-2">
|
||
<Button type="button" variant="outline" onClick={onClose}>
|
||
Cancel
|
||
</Button>
|
||
<Button type="submit" loading={submitting}>
|
||
{editing ? "Save Changes" : "Create Contract"}
|
||
</Button>
|
||
</div>
|
||
</form>
|
||
</Modal>
|
||
);
|
||
}
|
||
|
||
function RenewContractModal({
|
||
open,
|
||
onClose,
|
||
contract,
|
||
providers,
|
||
}: {
|
||
open: boolean;
|
||
onClose: () => void;
|
||
contract: ContractItem | null;
|
||
providers: Array<{ id: number; name: string }>;
|
||
}) {
|
||
const qc = useQueryClient();
|
||
const [contractType, setContractType] = useState("AMC");
|
||
const [providerId, setProviderId] = useState("");
|
||
const [startDate, setStartDate] = useState("");
|
||
const [endDate, setEndDate] = useState("");
|
||
const [coveragePeriodText, setCoveragePeriodText] = useState("");
|
||
const [remarks, setRemarks] = useState("");
|
||
const [submitting, setSubmitting] = useState(false);
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
if (!open || !contract) return;
|
||
const nextStart = addDaysISO(contract.end_date, 1) || new Date().toISOString().slice(0, 10);
|
||
setContractType(contract.contract_type || "AMC");
|
||
setProviderId(String(contract.provider_id));
|
||
setStartDate(nextStart);
|
||
setEndDate(addMonthsISO(nextStart, 12));
|
||
setCoveragePeriodText(contract.coverage_period_text ?? "");
|
||
setRemarks("");
|
||
setError(null);
|
||
}, [open, contract]);
|
||
|
||
async function handleSubmit(e: React.FormEvent) {
|
||
e.preventDefault();
|
||
if (!contract) return;
|
||
setSubmitting(true);
|
||
setError(null);
|
||
try {
|
||
await contractsApi.renew(contract.id, {
|
||
contract_type: contractType,
|
||
provider_id: providerId ? Number(providerId) : undefined,
|
||
start_date: startDate,
|
||
end_date: endDate,
|
||
coverage_period_text: coveragePeriodText.trim() || null,
|
||
remarks: remarks.trim() || null,
|
||
});
|
||
await qc.invalidateQueries({ queryKey: ["contracts"] });
|
||
await qc.invalidateQueries({ queryKey: ["contracts-history"] });
|
||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||
onClose();
|
||
} catch (err) {
|
||
setError(err instanceof ApiError ? err.detail : "Failed to renew contract.");
|
||
} finally {
|
||
setSubmitting(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Modal
|
||
open={open}
|
||
onOpenChange={(o) => !o && onClose()}
|
||
title={`Renew Contract — ${contract?.asset_code ?? ""}`}
|
||
className="max-w-lg"
|
||
>
|
||
{error && (
|
||
<div
|
||
role="alert"
|
||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||
>
|
||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||
<span>{error}</span>
|
||
</div>
|
||
)}
|
||
{contract && (
|
||
<div className="mb-3 rounded-md bg-blue-50 border border-blue-200 px-3 py-2 text-xs text-blue-900">
|
||
Renewing marks the previous {contract.contract_type} ({formatDate(contract.start_date)} –{" "}
|
||
{formatDate(contract.end_date)}) as <strong>Superseded</strong> while keeping its full history.
|
||
</div>
|
||
)}
|
||
<form onSubmit={handleSubmit} className="space-y-4">
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||
<div>
|
||
<label className={labelCls}>Contract Type *</label>
|
||
<select
|
||
value={contractType}
|
||
onChange={(e) => setContractType(e.target.value)}
|
||
className={inputCls}
|
||
>
|
||
<option value="AMC">AMC</option>
|
||
<option value="CMC">CMC</option>
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Provider *</label>
|
||
<select
|
||
required
|
||
value={providerId}
|
||
onChange={(e) => setProviderId(e.target.value)}
|
||
className={inputCls}
|
||
>
|
||
{providers.map((p) => (
|
||
<option key={p.id} value={String(p.id)}>
|
||
{p.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>New Start Date *</label>
|
||
<input
|
||
type="date"
|
||
required
|
||
value={startDate}
|
||
onChange={(e) => setStartDate(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>New End Date *</label>
|
||
<input
|
||
type="date"
|
||
required
|
||
value={endDate}
|
||
onChange={(e) => setEndDate(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Coverage Period Description</label>
|
||
<input
|
||
type="text"
|
||
value={coveragePeriodText}
|
||
onChange={(e) => setCoveragePeriodText(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Remarks</label>
|
||
<textarea
|
||
rows={2}
|
||
value={remarks}
|
||
onChange={(e) => setRemarks(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div className="flex justify-end gap-2 pt-2">
|
||
<Button type="button" variant="outline" onClick={onClose}>
|
||
Cancel
|
||
</Button>
|
||
<Button type="submit" loading={submitting}>
|
||
Confirm Renewal
|
||
</Button>
|
||
</div>
|
||
</form>
|
||
</Modal>
|
||
);
|
||
}
|
||
|
||
function ContractHistoryModal({
|
||
open,
|
||
onClose,
|
||
assetId,
|
||
assetLabel,
|
||
}: {
|
||
open: boolean;
|
||
onClose: () => void;
|
||
assetId: number | null;
|
||
assetLabel: string;
|
||
}) {
|
||
const historyQuery = useQuery({
|
||
queryKey: ["contracts-history", assetId],
|
||
queryFn: () => contractsApi.history(assetId!),
|
||
enabled: open && Boolean(assetId),
|
||
});
|
||
|
||
const items = historyQuery.data?.items ?? [];
|
||
|
||
return (
|
||
<Modal
|
||
open={open}
|
||
onOpenChange={(o) => !o && onClose()}
|
||
title={`Contract Renewal History — ${assetLabel}`}
|
||
className="max-w-2xl"
|
||
>
|
||
{historyQuery.isLoading ? (
|
||
<div className="py-8 text-center text-sm text-gray-500">Loading history...</div>
|
||
) : items.length === 0 ? (
|
||
<div className="py-8 text-center text-sm text-gray-400">No contract history found.</div>
|
||
) : (
|
||
<div className="space-y-3 max-h-96 overflow-y-auto pr-1">
|
||
{items.map((item) => (
|
||
<div
|
||
key={item.id}
|
||
className={`rounded-lg border p-3.5 text-sm ${
|
||
item.is_superseded
|
||
? "bg-gray-50 border-gray-200 opacity-85"
|
||
: "bg-white border-blue-200"
|
||
}`}
|
||
>
|
||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||
<div className="flex items-center gap-2">
|
||
<Badge variant="outline">{item.contract_type}</Badge>
|
||
<span className="font-semibold text-gray-900">
|
||
{item.provider_name || `Provider #${item.provider_id}`}
|
||
</span>
|
||
</div>
|
||
<ExpiryChip
|
||
daysToExpiry={item.days_to_expiry}
|
||
status={item.status}
|
||
severity={item.severity}
|
||
/>
|
||
</div>
|
||
<div className="mt-2 text-xs text-gray-600 flex flex-wrap gap-4">
|
||
<span>
|
||
Period: <strong>{formatDate(item.start_date)}</strong> →{" "}
|
||
<strong>{formatDate(item.end_date)}</strong>
|
||
</span>
|
||
{item.coverage_period_text && <span>({item.coverage_period_text})</span>}
|
||
{item.renewed_from_id && (
|
||
<span className="text-blue-700">Renewed from #{item.renewed_from_id}</span>
|
||
)}
|
||
</div>
|
||
{item.remarks && (
|
||
<p className="mt-1.5 text-xs text-gray-500">Remarks: {item.remarks}</p>
|
||
)}
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</Modal>
|
||
);
|
||
}
|
||
|
||
function WarrantyFormModal({
|
||
open,
|
||
onClose,
|
||
editing,
|
||
providers,
|
||
}: {
|
||
open: boolean;
|
||
onClose: () => void;
|
||
editing: WarrantyItem | null;
|
||
providers: Array<{ id: number; name: string }>;
|
||
}) {
|
||
const qc = useQueryClient();
|
||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||
const [durationMonths, setDurationMonths] = useState("12");
|
||
const [startDate, setStartDate] = useState("");
|
||
const [endDate, setEndDate] = useState("");
|
||
const [providerId, setProviderId] = useState("");
|
||
const [remarks, setRemarks] = useState("");
|
||
const [submitting, setSubmitting] = useState(false);
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
if (!open) return;
|
||
setError(null);
|
||
if (editing) {
|
||
setDurationMonths(String(editing.duration_months));
|
||
setStartDate(editing.start_date);
|
||
setEndDate(editing.end_date);
|
||
setProviderId(editing.provider_id ? String(editing.provider_id) : "");
|
||
setRemarks(editing.remarks ?? "");
|
||
assetsApi
|
||
.get(editing.asset_id)
|
||
.then((a) =>
|
||
setSelectedAsset({
|
||
...a,
|
||
contract_summary: a.contract_type ?? "None",
|
||
insurance_summary: a.insurance_status,
|
||
})
|
||
)
|
||
.catch(() => setSelectedAsset(null));
|
||
} else {
|
||
const today = new Date().toISOString().slice(0, 10);
|
||
setSelectedAsset(null);
|
||
setDurationMonths("12");
|
||
setStartDate(today);
|
||
setEndDate(addMonthsISO(today, 12));
|
||
setProviderId("");
|
||
setRemarks("");
|
||
}
|
||
}, [open, editing]);
|
||
|
||
function handleStartChange(newStart: string) {
|
||
setStartDate(newStart);
|
||
const months = Number(durationMonths);
|
||
const computed = addMonthsISO(newStart, months);
|
||
if (computed) setEndDate(computed);
|
||
}
|
||
|
||
function handleDurationChange(newDur: string) {
|
||
setDurationMonths(newDur);
|
||
const months = Number(newDur);
|
||
const computed = addMonthsISO(startDate, months);
|
||
if (computed) setEndDate(computed);
|
||
}
|
||
|
||
async function handleSubmit(e: React.FormEvent) {
|
||
e.preventDefault();
|
||
if (!editing && !selectedAsset) {
|
||
setError("Please select an asset.");
|
||
return;
|
||
}
|
||
setSubmitting(true);
|
||
setError(null);
|
||
try {
|
||
if (editing) {
|
||
await warrantiesApi.update(editing.id, {
|
||
duration_months: Number(durationMonths),
|
||
start_date: startDate,
|
||
end_date: endDate,
|
||
provider_id: providerId ? Number(providerId) : null,
|
||
remarks: remarks.trim() || null,
|
||
});
|
||
} else {
|
||
await warrantiesApi.create({
|
||
asset_id: selectedAsset!.id,
|
||
duration_months: Number(durationMonths),
|
||
start_date: startDate,
|
||
end_date: endDate,
|
||
provider_id: providerId ? Number(providerId) : null,
|
||
remarks: remarks.trim() || null,
|
||
});
|
||
}
|
||
await qc.invalidateQueries({ queryKey: ["warranties"] });
|
||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||
onClose();
|
||
} catch (err) {
|
||
setError(err instanceof ApiError ? err.detail : "Failed to save warranty.");
|
||
} finally {
|
||
setSubmitting(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Modal
|
||
open={open}
|
||
onOpenChange={(o) => !o && onClose()}
|
||
title={editing ? `Edit Warranty — ${editing.asset_code}` : "Add Warranty"}
|
||
className="max-w-2xl"
|
||
>
|
||
{error && (
|
||
<div
|
||
role="alert"
|
||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||
>
|
||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||
<span>{error}</span>
|
||
</div>
|
||
)}
|
||
<form onSubmit={handleSubmit} className="space-y-4">
|
||
<div>
|
||
<label className={labelCls}>Asset *</label>
|
||
<AssetPicker
|
||
selectedAsset={selectedAsset}
|
||
onSelect={setSelectedAsset}
|
||
disabled={Boolean(editing)}
|
||
/>
|
||
</div>
|
||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||
<div>
|
||
<label className={labelCls}>Start Date *</label>
|
||
<input
|
||
type="date"
|
||
required
|
||
value={startDate}
|
||
onChange={(e) => handleStartChange(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Duration (Months) *</label>
|
||
<input
|
||
type="number"
|
||
min={1}
|
||
max={240}
|
||
required
|
||
value={durationMonths}
|
||
onChange={(e) => handleDurationChange(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>End Date *</label>
|
||
<input
|
||
type="date"
|
||
required
|
||
value={endDate}
|
||
onChange={(e) => setEndDate(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Warranty Provider / OEM</label>
|
||
<select
|
||
value={providerId}
|
||
onChange={(e) => setProviderId(e.target.value)}
|
||
className={inputCls}
|
||
>
|
||
<option value="">None specified</option>
|
||
{providers.map((p) => (
|
||
<option key={p.id} value={String(p.id)}>
|
||
{p.name}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label className={labelCls}>Remarks</label>
|
||
<textarea
|
||
rows={2}
|
||
value={remarks}
|
||
onChange={(e) => setRemarks(e.target.value)}
|
||
className={inputCls}
|
||
/>
|
||
</div>
|
||
<div className="flex justify-end gap-2 pt-2">
|
||
<Button type="button" variant="outline" onClick={onClose}>
|
||
Cancel
|
||
</Button>
|
||
<Button type="submit" loading={submitting}>
|
||
{editing ? "Save Changes" : "Create Warranty"}
|
||
</Button>
|
||
</div>
|
||
</form>
|
||
</Modal>
|
||
);
|
||
}
|