phase-4: preventive maintenance and calibration modules
This commit is contained in:
@@ -0,0 +1,676 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { AlertCircle, Paperclip, X } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { validateAttachmentFile } from "@/components/Attachments";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { assetsApi } from "@/api/assets";
|
||||
import { vendorsApi } from "@/api/masters";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { calibrationApi, type CalibrationPlanItem } from "@/api/calibration";
|
||||
|
||||
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 ErrorAlert({ message }: { message: string | null }) {
|
||||
if (!message) return null;
|
||||
return (
|
||||
<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>{message}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddSingleCalibrationPlanModal({
|
||||
open,
|
||||
onClose,
|
||||
assetId,
|
||||
assetLabel,
|
||||
canApprove,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
assetId: number;
|
||||
assetLabel: string;
|
||||
canApprove: boolean;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [frequencyMonths, setFrequencyMonths] = useState("12");
|
||||
const [calPerYear, setCalPerYear] = useState("1");
|
||||
const [agencyId, setAgencyId] = useState("");
|
||||
const [nextDueDate, setNextDueDate] = useState("");
|
||||
const [approveNow, setApproveNow] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setFrequencyMonths("12");
|
||||
setCalPerYear("1");
|
||||
setAgencyId("");
|
||||
setNextDueDate(new Date().toISOString().slice(0, 10));
|
||||
setApproveNow(false);
|
||||
setError(null);
|
||||
}, [open, assetId]);
|
||||
|
||||
const agencies = (vendorsQuery.data?.items ?? []).filter(
|
||||
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
|
||||
);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await calibrationApi.createPlanFromAsset(assetId, {
|
||||
frequency_months: Math.max(1, Number(frequencyMonths) || 12),
|
||||
calibrations_per_year: calPerYear ? Math.max(1, Number(calPerYear)) : undefined,
|
||||
agency_id: agencyId ? Number(agencyId) : null,
|
||||
next_due_date: nextDueDate,
|
||||
approve: canApprove ? approveNow : false,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to add calibration plan.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Add to Calibration List — ${assetLabel}`}
|
||||
>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Frequency (Months) *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={frequencyMonths}
|
||||
onChange={(e) => setFrequencyMonths(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Calibrations / Year</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={calPerYear}
|
||||
onChange={(e) => setCalPerYear(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Calibration Agency</label>
|
||||
<select
|
||||
value={agencyId}
|
||||
onChange={(e) => setAgencyId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select agency (optional)...</option>
|
||||
{agencies.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Next Due Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={nextDueDate}
|
||||
onChange={(e) => setNextDueDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
{canApprove && (
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={approveNow}
|
||||
onChange={(e) => setApproveNow(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Approve frequency immediately
|
||||
</label>
|
||||
)}
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
Create Calibration Plan
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function BulkCalibrationAddModal({
|
||||
open,
|
||||
onClose,
|
||||
existingPlanAssetIds,
|
||||
canApprove,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
existingPlanAssetIds: number[];
|
||||
canApprove: boolean;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [search, setSearch] = useState("");
|
||||
const [onlyRequiresCal, setOnlyRequiresCal] = useState(false);
|
||||
const [selectedIds, setSelectedIds] = useState<number[]>([]);
|
||||
const [frequencyMonths, setFrequencyMonths] = useState("12");
|
||||
const [calPerYear, setCalPerYear] = useState("1");
|
||||
const [agencyId, setAgencyId] = useState("");
|
||||
const [nextDueDate, setNextDueDate] = useState("");
|
||||
const [approveNow, setApproveNow] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const assetsQuery = useQuery({
|
||||
queryKey: ["assets", "cal-candidates"],
|
||||
queryFn: () => assetsApi.list({ page_size: 500 }),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setSearch("");
|
||||
setSelectedIds([]);
|
||||
setFrequencyMonths("12");
|
||||
setCalPerYear("1");
|
||||
setAgencyId("");
|
||||
setNextDueDate(new Date().toISOString().slice(0, 10));
|
||||
setApproveNow(false);
|
||||
setError(null);
|
||||
}, [open]);
|
||||
|
||||
const existingSet = useMemo(() => new Set(existingPlanAssetIds), [existingPlanAssetIds]);
|
||||
const candidates = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
return (assetsQuery.data?.items ?? []).filter((a) => {
|
||||
if (existingSet.has(a.id)) return false;
|
||||
if (onlyRequiresCal && !a.requires_calibration) return false;
|
||||
if (
|
||||
q &&
|
||||
!`${a.asset_code} ${a.name} ${a.department_name ?? ""}`
|
||||
.toLowerCase()
|
||||
.includes(q)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [assetsQuery.data?.items, existingSet, onlyRequiresCal, search]);
|
||||
|
||||
const agencies = (vendorsQuery.data?.items ?? []).filter(
|
||||
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
|
||||
);
|
||||
|
||||
function toggleId(id: number) {
|
||||
setSelectedIds((prev) =>
|
||||
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (selectedIds.length === 0) {
|
||||
setError("Select at least one asset.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await calibrationApi.bulkCreatePlansFromAssets({
|
||||
asset_ids: selectedIds,
|
||||
frequency_months: Math.max(1, Number(frequencyMonths) || 12),
|
||||
calibrations_per_year: calPerYear ? Math.max(1, Number(calPerYear)) : undefined,
|
||||
agency_id: agencyId ? Number(agencyId) : null,
|
||||
next_due_date: nextDueDate,
|
||||
approve: canApprove ? approveNow : false,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Bulk creation failed.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Add Equipment to Calibration"
|
||||
className="max-w-2xl"
|
||||
>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search unconfigured assets..."
|
||||
className="flex-1 min-w-48 px-3 py-1.5 text-sm border border-gray-300 rounded-md"
|
||||
/>
|
||||
<label className="inline-flex items-center gap-1.5 text-xs text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={onlyRequiresCal}
|
||||
onChange={(e) => setOnlyRequiresCal(e.target.checked)}
|
||||
/>
|
||||
Requires calibration only
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="max-h-52 overflow-y-auto border border-gray-200 rounded-md divide-y divide-gray-100">
|
||||
{candidates.length === 0 ? (
|
||||
<div className="p-4 text-center text-xs text-gray-400">
|
||||
No matching assets without a calibration plan.
|
||||
</div>
|
||||
) : (
|
||||
candidates.map((a) => (
|
||||
<label
|
||||
key={a.id}
|
||||
className="flex items-center gap-3 px-3 py-2 hover:bg-blue-50/40 cursor-pointer text-sm"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedIds.includes(a.id)}
|
||||
onChange={() => toggleId(a.id)}
|
||||
/>
|
||||
<span className="font-mono text-xs text-[#1e3a8a] font-semibold">
|
||||
{a.asset_code}
|
||||
</span>
|
||||
<span className="flex-1 truncate">{a.name}</span>
|
||||
<span className="text-xs text-gray-500">{a.department_name}</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">{selectedIds.length} asset(s) selected</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Frequency (Months) *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={frequencyMonths}
|
||||
onChange={(e) => setFrequencyMonths(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Calibrations / Year</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={calPerYear}
|
||||
onChange={(e) => setCalPerYear(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Agency</label>
|
||||
<select
|
||||
value={agencyId}
|
||||
onChange={(e) => setAgencyId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select agency (optional)...</option>
|
||||
{agencies.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Next Due Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={nextDueDate}
|
||||
onChange={(e) => setNextDueDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canApprove && (
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={approveNow}
|
||||
onChange={(e) => setApproveNow(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Approve immediately
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
Add Selected ({selectedIds.length})
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function ApproveCalibrationPlanModal({
|
||||
open,
|
||||
onClose,
|
||||
plan,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
plan: CalibrationPlanItem | null;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [frequencyMonths, setFrequencyMonths] = useState("12");
|
||||
const [calPerYear, setCalPerYear] = useState("1");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !plan) return;
|
||||
setFrequencyMonths(String(plan.frequency_months));
|
||||
setCalPerYear(String(plan.calibrations_per_year));
|
||||
setError(null);
|
||||
}, [open, plan]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!plan) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await calibrationApi.approvePlan(plan.id, {
|
||||
frequency_months: Math.max(1, Number(frequencyMonths) || plan.frequency_months),
|
||||
calibrations_per_year: Math.max(
|
||||
1,
|
||||
Number(calPerYear) || plan.calibrations_per_year
|
||||
),
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["asset-overview", plan.asset_id] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Approval failed.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Approve / Edit Frequency — ${plan?.asset_code ?? ""}`}
|
||||
>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Frequency (Months) *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={frequencyMonths}
|
||||
onChange={(e) => setFrequencyMonths(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Calibrations / Year *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={calPerYear}
|
||||
onChange={(e) => setCalPerYear(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" variant="success" loading={submitting}>
|
||||
Approve Plan
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function CompleteCalibrationModal({
|
||||
open,
|
||||
onClose,
|
||||
recordId,
|
||||
assetLabel,
|
||||
defaultAgencyId,
|
||||
assetId,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
recordId: number | null;
|
||||
assetLabel: string;
|
||||
defaultAgencyId?: number | null;
|
||||
assetId?: number;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [completedDate, setCompletedDate] = useState("");
|
||||
const [certificateNo, setCertificateNo] = useState("");
|
||||
const [agencyId, setAgencyId] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [certFile, setCertFile] = useState<File | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setCompletedDate(new Date().toISOString().slice(0, 10));
|
||||
setCertificateNo("");
|
||||
setAgencyId(defaultAgencyId ? String(defaultAgencyId) : "");
|
||||
setRemarks("");
|
||||
setCertFile(null);
|
||||
setError(null);
|
||||
}, [open, recordId, defaultAgencyId]);
|
||||
|
||||
const agencies = (vendorsQuery.data?.items ?? []).filter(
|
||||
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
|
||||
);
|
||||
|
||||
function handlePickFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const f = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!f) return;
|
||||
const err = validateAttachmentFile(f);
|
||||
if (err) {
|
||||
setError(err);
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setCertFile(f);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!recordId) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await calibrationApi.completeRecord(recordId, {
|
||||
completed_date: completedDate,
|
||||
certificate_no: certificateNo.trim(),
|
||||
agency_id: agencyId ? Number(agencyId) : null,
|
||||
remarks: remarks.trim() || null,
|
||||
});
|
||||
if (certFile) {
|
||||
await attachmentsApi.upload("calibration_record", recordId, certFile);
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
|
||||
await qc.invalidateQueries({ queryKey: ["attachments", "calibration_record", recordId] });
|
||||
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to complete calibration.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Complete Calibration — ${assetLabel}`}
|
||||
>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Completed Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={completedDate}
|
||||
onChange={(e) => setCompletedDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Certificate No *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={certificateNo}
|
||||
onChange={(e) => setCertificateNo(e.target.value)}
|
||||
placeholder="e.g. CAL-2026-881"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Agency</label>
|
||||
<select
|
||||
value={agencyId}
|
||||
onChange={(e) => setAgencyId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Default / Plan Agency</option>
|
||||
{agencies.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.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>
|
||||
<label className={labelCls}>Calibration Certificate (Optional JPG/PNG/PDF)</label>
|
||||
{certFile ? (
|
||||
<div className="flex items-center justify-between text-xs bg-gray-50 border border-gray-200 rounded px-3 py-2">
|
||||
<span className="truncate">{certFile.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCertFile(null)}
|
||||
className="text-gray-400 hover:text-red-600 ml-2"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<label className="inline-flex items-center gap-2 px-3 py-2 rounded-md border border-gray-300 bg-white hover:bg-gray-50 text-xs font-medium text-gray-700 cursor-pointer">
|
||||
<Paperclip className="h-3.5 w-3.5" />
|
||||
Attach Certificate File
|
||||
<input
|
||||
type="file"
|
||||
accept=".jpg,.jpeg,.png,.pdf"
|
||||
onChange={handlePickFile}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" variant="success" loading={submitting}>
|
||||
Save & Complete
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
import { vendorsApi } from "@/api/masters";
|
||||
import { pmApi, type ServiceMode } from "@/api/pm";
|
||||
|
||||
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 ErrorAlert({ message }: { message: string | null }) {
|
||||
if (!message) return null;
|
||||
return (
|
||||
<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>{message}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function NewPMScheduleModal({
|
||||
open,
|
||||
onClose,
|
||||
fixedAsset = null,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
fixedAsset?: { id: number; asset_code: string; name: string } | null;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||||
const [serviceMode, setServiceMode] = useState<ServiceMode>("in_house");
|
||||
const [responsibleTeam, setResponsibleTeam] = useState("Biomedical Engineering");
|
||||
const [providerId, setProviderId] = useState("");
|
||||
const [contractId, setContractId] = useState("");
|
||||
const [frequencyMonths, setFrequencyMonths] = useState("6");
|
||||
const [nextPlannedDate, setNextPlannedDate] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const assetId = fixedAsset?.id ?? selectedAsset?.id ?? null;
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const assetOverviewQuery = useQuery({
|
||||
queryKey: ["asset-overview", assetId],
|
||||
queryFn: () => assetsApi.overview(assetId!),
|
||||
enabled: open && Boolean(assetId) && serviceMode === "outsourced",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setSelectedAsset(null);
|
||||
setServiceMode("in_house");
|
||||
setResponsibleTeam("Biomedical Engineering");
|
||||
setProviderId("");
|
||||
setContractId("");
|
||||
setFrequencyMonths("6");
|
||||
setNextPlannedDate(new Date().toISOString().slice(0, 10));
|
||||
setError(null);
|
||||
}, [open]);
|
||||
|
||||
const serviceVendors = (vendorsQuery.data?.items ?? []).filter(
|
||||
(v) => v.vendor_type === "service_provider" || v.vendor_type === "oem"
|
||||
);
|
||||
const vendorOptions =
|
||||
serviceVendors.length > 0 ? serviceVendors : vendorsQuery.data?.items ?? [];
|
||||
|
||||
const assetContracts = (assetOverviewQuery.data?.contracts ?? []).filter(
|
||||
(c) => !c.is_superseded
|
||||
);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!assetId) {
|
||||
setError("Please select an asset.");
|
||||
return;
|
||||
}
|
||||
if (serviceMode === "in_house" && !responsibleTeam.trim()) {
|
||||
setError("Responsible team is required for In-House PM.");
|
||||
return;
|
||||
}
|
||||
if (serviceMode === "outsourced" && !providerId) {
|
||||
setError("Service provider is required for Outsourced PM.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await pmApi.createSchedule({
|
||||
asset_id: assetId,
|
||||
service_mode: serviceMode,
|
||||
frequency_months: Math.max(1, Number(frequencyMonths) || 6),
|
||||
responsible_team: serviceMode === "in_house" ? responsibleTeam.trim() : null,
|
||||
provider_id: serviceMode === "outsourced" ? Number(providerId) : null,
|
||||
contract_id:
|
||||
serviceMode === "outsourced" && contractId ? Number(contractId) : null,
|
||||
next_planned_date: nextPlannedDate,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
||||
await qc.invalidateQueries({ queryKey: ["pm-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to create PM schedule.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} onOpenChange={(o) => !o && onClose()} title="New PM Schedule" className="max-w-xl">
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Asset *</label>
|
||||
{fixedAsset ? (
|
||||
<div className="px-3 py-2 text-sm bg-gray-50 border border-gray-200 rounded-md font-medium">
|
||||
<span className="font-mono text-[#1e3a8a]">{fixedAsset.asset_code}</span> —{" "}
|
||||
{fixedAsset.name}
|
||||
</div>
|
||||
) : (
|
||||
<AssetPicker selectedAsset={selectedAsset} onSelect={setSelectedAsset} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Service Mode *</label>
|
||||
<select
|
||||
value={serviceMode}
|
||||
onChange={(e) => setServiceMode(e.target.value as ServiceMode)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="in_house">In-House</option>
|
||||
<option value="outsourced">Outsourced</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Frequency (Months) *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={60}
|
||||
required
|
||||
value={frequencyMonths}
|
||||
onChange={(e) => setFrequencyMonths(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{serviceMode === "in_house" ? (
|
||||
<div>
|
||||
<label className={labelCls}>Responsible Team *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={responsibleTeam}
|
||||
onChange={(e) => setResponsibleTeam(e.target.value)}
|
||||
placeholder="e.g. Biomedical Engineering"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Service Provider *</label>
|
||||
<select
|
||||
value={providerId}
|
||||
onChange={(e) => setProviderId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select vendor...</option>
|
||||
{vendorOptions.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Linked Contract (Optional)</label>
|
||||
<select
|
||||
value={contractId}
|
||||
onChange={(e) => setContractId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">None</option>
|
||||
{assetContracts.map((c) => (
|
||||
<option key={c.id} value={String(c.id)}>
|
||||
{c.contract_type} — {c.provider_name || `Provider #${c.provider_id}`} (until{" "}
|
||||
{c.end_date})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Next Planned Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={nextPlannedDate}
|
||||
onChange={(e) => setNextPlannedDate(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}>
|
||||
Create Schedule
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function CompletePMModal({
|
||||
open,
|
||||
onClose,
|
||||
recordId,
|
||||
assetLabel,
|
||||
assetId,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
recordId: number | null;
|
||||
assetLabel: string;
|
||||
assetId?: number;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [completedDate, setCompletedDate] = useState("");
|
||||
const [serviceDetails, setServiceDetails] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setCompletedDate(new Date().toISOString().slice(0, 10));
|
||||
setServiceDetails("");
|
||||
setRemarks("");
|
||||
setError(null);
|
||||
}, [open, recordId]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!recordId) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await pmApi.completeRecord(recordId, {
|
||||
completed_date: completedDate,
|
||||
service_details: serviceDetails.trim(),
|
||||
remarks: remarks.trim() || null,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["pm-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
||||
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to complete PM.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={`Complete PM — ${assetLabel}`}>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Completed Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={completedDate}
|
||||
onChange={(e) => setCompletedDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Service Details *</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
required
|
||||
value={serviceDetails}
|
||||
onChange={(e) => setServiceDetails(e.target.value)}
|
||||
placeholder="Checklist items performed, parts cleaned/replaced..."
|
||||
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" variant="success" loading={submitting}>
|
||||
Mark Completed
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReschedulePMModal({
|
||||
open,
|
||||
onClose,
|
||||
recordId,
|
||||
assetLabel,
|
||||
assetId,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
recordId: number | null;
|
||||
assetLabel: string;
|
||||
assetId?: number;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [rescheduledTo, setRescheduledTo] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setRescheduledTo(new Date().toISOString().slice(0, 10));
|
||||
setRemarks("");
|
||||
setError(null);
|
||||
}, [open, recordId]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!recordId) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await pmApi.rescheduleRecord(recordId, {
|
||||
rescheduled_to: rescheduledTo,
|
||||
remarks: remarks.trim() || null,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["pm-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
||||
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to reschedule PM.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={`Reschedule PM — ${assetLabel}`}>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>New Planned Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={rescheduledTo}
|
||||
onChange={(e) => setRescheduledTo(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Reason / Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
placeholder="e.g. Equipment in active OT use"
|
||||
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}>
|
||||
Reschedule
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
AlertCircle,
|
||||
Ban,
|
||||
Clock,
|
||||
CalendarClock,
|
||||
ShieldAlert,
|
||||
MinusCircle,
|
||||
} from "lucide-react";
|
||||
@@ -72,6 +73,66 @@ export function AssetStatusBadge({
|
||||
);
|
||||
}
|
||||
|
||||
export function ScheduleStatusBadge({
|
||||
status,
|
||||
severity,
|
||||
className,
|
||||
}: {
|
||||
status: string;
|
||||
severity?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const map: Record<string, { label: string; cls: string; icon: React.ReactNode }> = {
|
||||
upcoming: {
|
||||
label: "Upcoming",
|
||||
cls: "bg-blue-100 text-blue-800 border border-blue-200",
|
||||
icon: <Clock className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
due: {
|
||||
label: "Due",
|
||||
cls:
|
||||
severity === "red"
|
||||
? "bg-red-100 text-red-800 border border-red-200"
|
||||
: "bg-amber-100 text-amber-800 border border-amber-200",
|
||||
icon: <Clock className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
overdue: {
|
||||
label: "Overdue",
|
||||
cls: "bg-red-100 text-red-800 border border-red-200",
|
||||
icon: <AlertTriangle className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
completed: {
|
||||
label: "Completed",
|
||||
cls: "bg-green-100 text-green-800 border border-green-200",
|
||||
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
rescheduled: {
|
||||
label: "Rescheduled",
|
||||
cls: "bg-purple-100 text-purple-800 border border-purple-200",
|
||||
icon: <CalendarClock className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
};
|
||||
|
||||
const cfg = map[status] ?? {
|
||||
label: status || "None",
|
||||
cls: "bg-gray-100 text-gray-700 border border-gray-200",
|
||||
icon: <MinusCircle className="h-3 w-3 shrink-0" />,
|
||||
};
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
|
||||
cfg.cls,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{cfg.icon}
|
||||
<span>{cfg.label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CoverageBadge({
|
||||
status,
|
||||
severity,
|
||||
|
||||
Reference in New Issue
Block a user