Files
poona-ams/frontend/src/components/CalibrationModals.tsx
T

677 lines
22 KiB
TypeScript

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 "@/lib/validation";
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 &amp; Complete
</Button>
</div>
</form>
</Modal>
);
}