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("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(null); const [renewTarget, setRenewTarget] = useState(null); const [historyAsset, setHistoryAsset] = useState<{ assetId: number; label: string; } | null>(null); // Warranty modals const [warrantyFormOpen, setWarrantyFormOpen] = useState(false); const [editingWarranty, setEditingWarranty] = useState(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[] = [ { id: "asset", accessorFn: (r) => `${r.asset_code} ${r.asset_name}`, header: "Asset", cell: ({ row }) => (
{row.original.asset_code}
{row.original.asset_name}
), }, { accessorKey: "department_name", header: "Department", cell: ({ getValue }) => (getValue() as string | null) || "—", }, { accessorKey: "contract_type", header: "Type", cell: ({ getValue }) => ( {String(getValue())} ), }, { accessorKey: "provider_name", header: "Provider", cell: ({ getValue }) => (getValue() as string | null) || "—", }, { accessorKey: "start_date", header: "Start", cell: ({ getValue }) => ( {formatDate(getValue() as string)} ), }, { accessorKey: "end_date", header: "End", cell: ({ getValue }) => ( {formatDate(getValue() as string)} ), }, { id: "expiry", accessorFn: (r) => r.days_to_expiry, header: "Status", cell: ({ row }) => ( ), }, { id: "attachments", header: "Docs", enableSorting: false, enableColumnFilter: false, cell: ({ row }) => ( ), }, { id: "actions", header: "Actions", enableSorting: false, enableColumnFilter: false, cell: ({ row }) => (
{canManage && !row.original.is_superseded && ( )} {canManage && ( <> )}
), }, ]; const warrantyColumns: ColumnDef[] = [ { id: "asset", accessorFn: (r) => `${r.asset_code} ${r.asset_name}`, header: "Asset", cell: ({ row }) => (
{row.original.asset_code}
{row.original.asset_name}
), }, { 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 }) => ( {formatDate(getValue() as string)} ), }, { accessorKey: "end_date", header: "End", cell: ({ getValue }) => ( {formatDate(getValue() as string)} ), }, { id: "expiry", accessorFn: (r) => r.days_to_expiry, header: "Status", cell: ({ row }) => ( ), }, { id: "attachments", header: "Docs", enableSorting: false, enableColumnFilter: false, cell: ({ row }) => ( ), }, ...(canManage ? [ { id: "actions", header: "Actions", enableSorting: false, enableColumnFilter: false, cell: ({ row }: { row: { original: WarrantyItem } }) => (
), } satisfies ColumnDef, ] : []), ]; return (

Contracts & Warranty

Track AMC/CMC contracts, renewal chains, and equipment warranty coverage

{canManage && ( )}
{/* Tabs */}
{/* Filter Chips & Bar */}
{STATUS_CHIPS.map((chip) => ( ))}
{tab === "contracts" && ( )}
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" />
{!isDeptUser && ( )} {tab === "contracts" && ( <> )}
{tab === "contracts" ? ( ) : ( )} {/* Contract Add/Edit Modal */} setContractFormOpen(false)} editing={editingContract} providers={contractProviders.length ? contractProviders : allVendors} /> {/* Contract Renew Modal */} setRenewTarget(null)} contract={renewTarget} providers={contractProviders.length ? contractProviders : allVendors} /> {/* Contract History Modal */} setHistoryAsset(null)} assetId={historyAsset?.assetId ?? null} assetLabel={historyAsset?.label ?? ""} /> {/* Warranty Add/Edit Modal */} setWarrantyFormOpen(false)} editing={editingWarranty} providers={contractProviders.length ? contractProviders : allVendors} /> {/* Row Attachments Modal */} !o && setAttachTarget(null)} title={attachTarget?.title ?? "Documents"} className="max-w-xl" > {attachTarget && ( )} !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); } }} />
); } 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(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(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 ( !o && onClose()} title={editing ? `Edit Contract — ${editing.asset_code}` : "Add AMC / CMC Contract"} className="max-w-2xl" > {error && (
{error}
)}
setStartDate(e.target.value)} className={inputCls} />
setEndDate(e.target.value)} className={inputCls} />
setCoveragePeriodText(e.target.value)} placeholder="e.g. 1 Year Comprehensive, 4 PM visits/year" className={inputCls} />