phase-4: preventive maintenance and calibration modules
This commit is contained in:
@@ -11,10 +11,10 @@ import { AssetsPage } from "@/pages/AssetsPage";
|
||||
import { AssetDetailPage } from "@/pages/AssetDetailPage";
|
||||
import { ComplaintsPage } from "@/pages/ComplaintsPage";
|
||||
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
|
||||
import { PMPage } from "@/pages/PMPage";
|
||||
import { CalibrationPage } from "@/pages/CalibrationPage";
|
||||
import {
|
||||
DashboardPage,
|
||||
PMPage,
|
||||
CalibrationPage,
|
||||
ContractsPage,
|
||||
InsurancePage,
|
||||
DemoEquipmentPage,
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export interface CalibrationPlanItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
frequency_months: number;
|
||||
calibrations_per_year: number;
|
||||
agency_id: number | null;
|
||||
agency_name: string | null;
|
||||
approved_by_id: number | null;
|
||||
approved_by_name: string | null;
|
||||
approved_on: string | null;
|
||||
next_due_date: string;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export interface CalibrationRecordItem {
|
||||
id: number;
|
||||
plan_id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_name: string | null;
|
||||
due_date: string;
|
||||
completed_date: string | null;
|
||||
agency_id: number | null;
|
||||
agency_name: string | null;
|
||||
certificate_no: string | null;
|
||||
remarks: string | null;
|
||||
status: "upcoming" | "due" | "overdue" | "completed" | string;
|
||||
severity: "ok" | "yellow" | "red" | string;
|
||||
frequency_months: number;
|
||||
approved_by_name: string | null;
|
||||
approved_on: string | null;
|
||||
}
|
||||
|
||||
export interface CalibrationSummary {
|
||||
upcoming: number;
|
||||
due: number;
|
||||
overdue: number;
|
||||
completed: number;
|
||||
}
|
||||
|
||||
export interface CalibrationPlanFromAssetPayload {
|
||||
frequency_months: number;
|
||||
calibrations_per_year?: number;
|
||||
agency_id?: number | null;
|
||||
next_due_date: string;
|
||||
approve?: boolean;
|
||||
}
|
||||
|
||||
export const calibrationApi = {
|
||||
listPlans: (
|
||||
params: {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
agency_id?: number;
|
||||
is_active?: boolean;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
} = {}
|
||||
) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||
if (params.agency_id) qs.set("agency_id", String(params.agency_id));
|
||||
if (params.is_active !== undefined) qs.set("is_active", String(params.is_active));
|
||||
qs.set("page", String(params.page ?? 1));
|
||||
qs.set("page_size", String(params.page_size ?? 200));
|
||||
return api.get<{ items: CalibrationPlanItem[]; total: number }>(
|
||||
`/calibration/plans?${qs.toString()}`
|
||||
);
|
||||
},
|
||||
createPlanFromAsset: (assetId: number, data: CalibrationPlanFromAssetPayload) =>
|
||||
api.post<CalibrationPlanItem>(`/calibration/plans/from-asset/${assetId}`, data),
|
||||
bulkCreatePlansFromAssets: (
|
||||
data: CalibrationPlanFromAssetPayload & { asset_ids: number[] }
|
||||
) =>
|
||||
api.post<{ created: CalibrationPlanItem[]; skipped_asset_ids: number[] }>(
|
||||
"/calibration/plans/bulk-from-assets",
|
||||
data
|
||||
),
|
||||
updatePlan: (
|
||||
id: number,
|
||||
data: Partial<{
|
||||
frequency_months: number;
|
||||
calibrations_per_year: number;
|
||||
agency_id: number | null;
|
||||
next_due_date: string;
|
||||
is_active: boolean;
|
||||
}>
|
||||
) => api.put<CalibrationPlanItem>(`/calibration/plans/${id}`, data),
|
||||
approvePlan: (
|
||||
id: number,
|
||||
data: { frequency_months?: number; calibrations_per_year?: number } = {}
|
||||
) => api.post<CalibrationPlanItem>(`/calibration/plans/${id}/approve`, data),
|
||||
listRecords: (
|
||||
params: {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
agency_id?: number;
|
||||
status?: string;
|
||||
due_from?: string;
|
||||
due_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
} = {}
|
||||
) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
||||
if (params.agency_id) qs.set("agency_id", String(params.agency_id));
|
||||
if (params.status) qs.set("status", params.status);
|
||||
if (params.due_from) qs.set("due_from", params.due_from);
|
||||
if (params.due_to) qs.set("due_to", params.due_to);
|
||||
qs.set("page", String(params.page ?? 1));
|
||||
qs.set("page_size", String(params.page_size ?? 200));
|
||||
return api.get<{
|
||||
items: CalibrationRecordItem[];
|
||||
total: number;
|
||||
summary: CalibrationSummary;
|
||||
}>(`/calibration/records?${qs.toString()}`);
|
||||
},
|
||||
completeRecord: (
|
||||
id: number,
|
||||
data: {
|
||||
completed_date: string;
|
||||
certificate_no: string;
|
||||
agency_id?: number | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
) =>
|
||||
api.post<{
|
||||
completed_record: CalibrationRecordItem;
|
||||
next_record: CalibrationRecordItem;
|
||||
}>(`/calibration/records/${id}/complete`, data),
|
||||
};
|
||||
@@ -0,0 +1,137 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export type ServiceMode = "in_house" | "outsourced";
|
||||
export type ScheduleStatus = "upcoming" | "due" | "overdue" | "completed" | "rescheduled";
|
||||
|
||||
export interface PMScheduleItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_name: string | null;
|
||||
service_mode: ServiceMode;
|
||||
frequency_months: number;
|
||||
responsible_team: string | null;
|
||||
provider_id: number | null;
|
||||
provider_name: string | null;
|
||||
contract_id: number | null;
|
||||
contract_summary: string | null;
|
||||
next_planned_date: string;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface PMRecordItem {
|
||||
id: number;
|
||||
schedule_id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_name: string | null;
|
||||
service_mode: ServiceMode;
|
||||
responsible_team: string | null;
|
||||
provider_id: number | null;
|
||||
provider_name: string | null;
|
||||
contract_id: number | null;
|
||||
planned_date: string;
|
||||
completed_date: string | null;
|
||||
status: ScheduleStatus | string;
|
||||
severity: "ok" | "yellow" | "red" | string;
|
||||
service_details: string | null;
|
||||
remarks: string | null;
|
||||
rescheduled_to: string | null;
|
||||
frequency_months: number;
|
||||
}
|
||||
|
||||
export interface PMSummary {
|
||||
upcoming: number;
|
||||
due: number;
|
||||
overdue: number;
|
||||
completed_this_month: number;
|
||||
}
|
||||
|
||||
export interface PMScheduleCreatePayload {
|
||||
asset_id: number;
|
||||
service_mode: ServiceMode;
|
||||
frequency_months: number;
|
||||
responsible_team?: string | null;
|
||||
provider_id?: number | null;
|
||||
contract_id?: number | null;
|
||||
next_planned_date: string;
|
||||
}
|
||||
|
||||
export const pmApi = {
|
||||
listSchedules: (
|
||||
params: {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
service_mode?: ServiceMode | "";
|
||||
is_active?: boolean;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
} = {}
|
||||
) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
||||
if (params.service_mode) qs.set("service_mode", params.service_mode);
|
||||
if (params.is_active !== undefined) qs.set("is_active", String(params.is_active));
|
||||
qs.set("page", String(params.page ?? 1));
|
||||
qs.set("page_size", String(params.page_size ?? 200));
|
||||
return api.get<{ items: PMScheduleItem[]; total: number }>(`/pm/schedules?${qs.toString()}`);
|
||||
},
|
||||
createSchedule: (data: PMScheduleCreatePayload) =>
|
||||
api.post<PMScheduleItem>("/pm/schedules", data),
|
||||
updateSchedule: (id: number, data: Partial<PMScheduleCreatePayload & { is_active: boolean }>) =>
|
||||
api.patch<PMScheduleItem>(`/pm/schedules/${id}`, data),
|
||||
deleteSchedule: (id: number) => api.delete<void>(`/pm/schedules/${id}`),
|
||||
listRecords: (
|
||||
params: {
|
||||
q?: string;
|
||||
month?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
schedule_id?: number;
|
||||
service_mode?: ServiceMode | "";
|
||||
status?: ScheduleStatus | "";
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
} = {}
|
||||
) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.month) qs.set("month", params.month);
|
||||
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
||||
if (params.schedule_id) qs.set("schedule_id", String(params.schedule_id));
|
||||
if (params.service_mode) qs.set("service_mode", params.service_mode);
|
||||
if (params.status) qs.set("status", params.status);
|
||||
qs.set("page", String(params.page ?? 1));
|
||||
qs.set("page_size", String(params.page_size ?? 200));
|
||||
return api.get<{ items: PMRecordItem[]; total: number; summary: PMSummary }>(
|
||||
`/pm/records?${qs.toString()}`
|
||||
);
|
||||
},
|
||||
completeRecord: (
|
||||
id: number,
|
||||
data: { completed_date: string; service_details: string; remarks?: string | null }
|
||||
) =>
|
||||
api.post<{ completed_record: PMRecordItem; next_record: PMRecordItem }>(
|
||||
`/pm/records/${id}/complete`,
|
||||
data
|
||||
),
|
||||
rescheduleRecord: (
|
||||
id: number,
|
||||
data: { rescheduled_to: string; remarks?: string | null }
|
||||
) =>
|
||||
api.post<{ rescheduled_record: PMRecordItem; next_record: PMRecordItem }>(
|
||||
`/pm/records/${id}/reschedule`,
|
||||
data
|
||||
),
|
||||
};
|
||||
@@ -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,
|
||||
|
||||
@@ -7,8 +7,10 @@ import {
|
||||
ShieldCheck,
|
||||
Ban,
|
||||
AlertCircle,
|
||||
Plus,
|
||||
} from "lucide-react";
|
||||
import { assetsApi } from "@/api/assets";
|
||||
import type { CalibrationPlanItem } from "@/api/calibration";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
@@ -20,9 +22,19 @@ import {
|
||||
CoverageBadge,
|
||||
CalibrationBadge,
|
||||
CriticalityBadge,
|
||||
ScheduleStatusBadge,
|
||||
} from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { AssetFormModal } from "@/components/AssetFormModal";
|
||||
import {
|
||||
NewPMScheduleModal,
|
||||
CompletePMModal,
|
||||
ReschedulePMModal,
|
||||
} from "@/components/PMModals";
|
||||
import {
|
||||
AddSingleCalibrationPlanModal,
|
||||
ApproveCalibrationPlanModal,
|
||||
} from "@/components/CalibrationModals";
|
||||
|
||||
type DetailTab =
|
||||
| "overview"
|
||||
@@ -52,10 +64,20 @@ export function AssetDetailPage() {
|
||||
|
||||
const [activeTab, setActiveTab] = useState<DetailTab>("overview");
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [addCalOpen, setAddCalOpen] = useState(false);
|
||||
const [approveCalOpen, setApproveCalOpen] = useState(false);
|
||||
const [newPMOpen, setNewPMOpen] = useState(false);
|
||||
const [completePMRecordId, setCompletePMRecordId] = useState<number | null>(null);
|
||||
const [reschedulePMRecordId, setReschedulePMRecordId] = useState<number | null>(null);
|
||||
|
||||
const canFullEdit = can(role, "create_edit_assets");
|
||||
const canContractOnlyEdit = !canFullEdit && can(role, "edit_asset_contracts_only");
|
||||
const canEdit = canFullEdit || canContractOnlyEdit;
|
||||
const canManagePM = can(role, "manage_pm") || role === "coordinator";
|
||||
const canAddCalPlan =
|
||||
can(role, "manage_calibration_contracts") || role === "management";
|
||||
const canApproveCalPlan =
|
||||
role === "management" || role === "system_admin" || role === "coordinator";
|
||||
|
||||
const { data, isLoading, isError, error } = useQuery({
|
||||
queryKey: ["asset-overview", assetId],
|
||||
@@ -365,7 +387,24 @@ export function AssetDetailPage() {
|
||||
{activeTab === "calibration" && (
|
||||
<div className="space-y-4">
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4">
|
||||
<h3 className="text-sm font-semibold text-gray-800 mb-2">Calibration Plan</h3>
|
||||
<div className="flex items-center justify-between gap-3 mb-2">
|
||||
<h3 className="text-sm font-semibold text-gray-800">Calibration Plan</h3>
|
||||
{!calibration_plan && canAddCalPlan && (
|
||||
<Button size="sm" onClick={() => setAddCalOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add to Calibration List
|
||||
</Button>
|
||||
)}
|
||||
{calibration_plan && canApproveCalPlan && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={calibration_plan.approved_on ? "outline" : "default"}
|
||||
onClick={() => setApproveCalOpen(true)}
|
||||
>
|
||||
{calibration_plan.approved_on ? "Edit Frequency" : "Approve Plan"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{calibration_plan ? (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm">
|
||||
<div>
|
||||
@@ -410,7 +449,15 @@ export function AssetDetailPage() {
|
||||
{activeTab === "pm" && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-gray-800 mb-2">PM Schedules</h3>
|
||||
<div className="flex items-center justify-between gap-3 mb-2">
|
||||
<h3 className="text-sm font-semibold text-gray-800">PM Schedules</h3>
|
||||
{canManagePM && (
|
||||
<Button size="sm" onClick={() => setNewPMOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add PM Schedule
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<SimpleTable
|
||||
emptyText="No PM schedules configured."
|
||||
headers={["Frequency", "Service Mode", "Responsible / Provider", "Next Planned", "Active"]}
|
||||
@@ -429,16 +476,48 @@ export function AssetDetailPage() {
|
||||
<h3 className="text-sm font-semibold text-gray-800 mb-2">Recent PM Records</h3>
|
||||
<SimpleTable
|
||||
emptyText="No PM records yet."
|
||||
headers={["Planned Date", "Completed Date", "Status", "Service Details", "Remarks"]}
|
||||
rows={pm_records.map((r) => [
|
||||
formatDate(r.planned_date),
|
||||
formatDate(r.completed_date),
|
||||
<Badge key="st" variant={r.status === "completed" ? "success" : "warning"}>
|
||||
{r.status}
|
||||
</Badge>,
|
||||
r.service_details || "—",
|
||||
r.remarks || "—",
|
||||
])}
|
||||
headers={
|
||||
canManagePM
|
||||
? ["Planned Date", "Completed Date", "Status", "Service Details", "Remarks", "Actions"]
|
||||
: ["Planned Date", "Completed Date", "Status", "Service Details", "Remarks"]
|
||||
}
|
||||
rows={pm_records.map((r) => {
|
||||
const isDone = r.status === "completed" || r.status === "rescheduled";
|
||||
const base = [
|
||||
formatDate(r.planned_date),
|
||||
formatDate(r.completed_date),
|
||||
<ScheduleStatusBadge key="st" status={r.status} severity={r.severity} />,
|
||||
r.service_details || "—",
|
||||
r.remarks || "—",
|
||||
];
|
||||
if (canManagePM) {
|
||||
base.push(
|
||||
isDone ? (
|
||||
<span key="act" className="text-xs text-gray-400">
|
||||
—
|
||||
</span>
|
||||
) : (
|
||||
<div key="act" className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setCompletePMRecordId(r.id)}
|
||||
>
|
||||
Complete
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setReschedulePMRecordId(r.id)}
|
||||
>
|
||||
Reschedule
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
return base;
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -493,6 +572,59 @@ export function AssetDetailPage() {
|
||||
coordinatorOnly={canContractOnlyEdit}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canAddCalPlan && (
|
||||
<AddSingleCalibrationPlanModal
|
||||
open={addCalOpen}
|
||||
onClose={() => setAddCalOpen(false)}
|
||||
assetId={asset.id}
|
||||
assetLabel={`${asset.asset_code} — ${asset.name}`}
|
||||
canApprove={canApproveCalPlan}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canApproveCalPlan && calibration_plan && (
|
||||
<ApproveCalibrationPlanModal
|
||||
open={approveCalOpen}
|
||||
onClose={() => setApproveCalOpen(false)}
|
||||
plan={{
|
||||
...calibration_plan,
|
||||
asset_code: asset.asset_code,
|
||||
asset_name: asset.name,
|
||||
department_id: asset.department_id,
|
||||
department_name: asset.department_name,
|
||||
approved_by_name: null,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canManagePM && (
|
||||
<>
|
||||
<NewPMScheduleModal
|
||||
open={newPMOpen}
|
||||
onClose={() => setNewPMOpen(false)}
|
||||
fixedAsset={{
|
||||
id: asset.id,
|
||||
asset_code: asset.asset_code,
|
||||
name: asset.name,
|
||||
}}
|
||||
/>
|
||||
<CompletePMModal
|
||||
open={completePMRecordId !== null}
|
||||
onClose={() => setCompletePMRecordId(null)}
|
||||
recordId={completePMRecordId}
|
||||
assetLabel={`${asset.asset_code} — ${asset.name}`}
|
||||
assetId={asset.id}
|
||||
/>
|
||||
<ReschedulePMModal
|
||||
open={reschedulePMRecordId !== null}
|
||||
onClose={() => setReschedulePMRecordId(null)}
|
||||
recordId={reschedulePMRecordId}
|
||||
assetLabel={`${asset.asset_code} — ${asset.name}`}
|
||||
assetId={asset.id}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,495 @@
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Plus, CheckCircle2, Paperclip, ShieldCheck, Search } from "lucide-react";
|
||||
import {
|
||||
calibrationApi,
|
||||
type CalibrationRecordItem,
|
||||
type CalibrationPlanItem,
|
||||
} from "@/api/calibration";
|
||||
import { departmentsApi, vendorsApi } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
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 { ScheduleStatusBadge } from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import {
|
||||
BulkCalibrationAddModal,
|
||||
ApproveCalibrationPlanModal,
|
||||
CompleteCalibrationModal,
|
||||
} from "@/components/CalibrationModals";
|
||||
|
||||
type CalTab = "records" | "plans";
|
||||
|
||||
export function CalibrationPage() {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const role = user?.role;
|
||||
const isDeptUser = role === "department_user";
|
||||
|
||||
const canAddCalPlan =
|
||||
role === "system_admin" ||
|
||||
role === "biomedical" ||
|
||||
role === "coordinator" ||
|
||||
role === "management";
|
||||
const canApproveCal =
|
||||
role === "management" || role === "system_admin" || role === "coordinator";
|
||||
const canCompleteCal =
|
||||
role === "system_admin" || role === "biomedical" || role === "coordinator";
|
||||
|
||||
const [tab, setTab] = useState<CalTab>("records");
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [agencyId, setAgencyId] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState("");
|
||||
const [dueFrom, setDueFrom] = useState("");
|
||||
const [dueTo, setDueTo] = useState("");
|
||||
|
||||
const [bulkAddOpen, setBulkAddOpen] = useState(false);
|
||||
const [approvingPlan, setApprovingPlan] = useState<CalibrationPlanItem | null>(null);
|
||||
const [completingRec, setCompletingRec] = useState<CalibrationRecordItem | null>(null);
|
||||
const [certModalRec, setCertModalRec] = useState<CalibrationRecordItem | 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 recordsQuery = useQuery({
|
||||
queryKey: [
|
||||
"calibration-records",
|
||||
q,
|
||||
departmentId,
|
||||
agencyId,
|
||||
statusFilter,
|
||||
dueFrom,
|
||||
dueTo,
|
||||
],
|
||||
queryFn: () =>
|
||||
calibrationApi.listRecords({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
agency_id: agencyId ? Number(agencyId) : undefined,
|
||||
status: statusFilter || undefined,
|
||||
due_from: dueFrom || undefined,
|
||||
due_to: dueTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const plansQuery = useQuery({
|
||||
queryKey: ["calibration-plans", q, departmentId, agencyId],
|
||||
queryFn: () =>
|
||||
calibrationApi.listPlans({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
agency_id: agencyId ? Number(agencyId) : undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const summary = recordsQuery.data?.summary ?? {
|
||||
upcoming: 0,
|
||||
due: 0,
|
||||
overdue: 0,
|
||||
completed: 0,
|
||||
};
|
||||
|
||||
const recordColumns: ColumnDef<CalibrationRecordItem, unknown>[] = [
|
||||
{
|
||||
accessorKey: "due_date",
|
||||
header: "Due Date",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap font-medium">
|
||||
{formatDate(getValue() as string)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "asset_display",
|
||||
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
|
||||
header: "Asset",
|
||||
enableColumnFilter: true,
|
||||
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",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "agency_name",
|
||||
header: "Agency",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: "Status",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<ScheduleStatusBadge
|
||||
status={row.original.status}
|
||||
severity={row.original.severity}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "completed_date",
|
||||
header: "Completed Date",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs">
|
||||
{formatDate(getValue() as string | null)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "certificate_no",
|
||||
header: "Certificate No",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono text-xs">{(getValue() as string | null) || "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => {
|
||||
const rec = row.original;
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{canCompleteCal && rec.status !== "completed" && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="success"
|
||||
onClick={() => setCompletingRec(rec)}
|
||||
>
|
||||
<CheckCircle2 className="h-3.5 w-3.5 mr-1" />
|
||||
Complete
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setCertModalRec(rec)}
|
||||
>
|
||||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||
Certificates
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const planColumns: ColumnDef<CalibrationPlanItem, unknown>[] = [
|
||||
{
|
||||
id: "asset_display",
|
||||
accessorFn: (p) => `${p.asset_code} ${p.asset_name}`,
|
||||
header: "Asset",
|
||||
enableColumnFilter: true,
|
||||
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",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "frequency_months",
|
||||
header: "Frequency",
|
||||
cell: ({ getValue }) => `${String(getValue())} months`,
|
||||
},
|
||||
{
|
||||
accessorKey: "calibrations_per_year",
|
||||
header: "Cal / Year",
|
||||
},
|
||||
{
|
||||
accessorKey: "agency_name",
|
||||
header: "Agency",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
id: "approval",
|
||||
accessorFn: (p) => p.approved_by_name ?? "Pending",
|
||||
header: "Approved By / On",
|
||||
cell: ({ row }) =>
|
||||
row.original.approved_on ? (
|
||||
<div className="text-xs">
|
||||
<div className="font-medium text-green-800">
|
||||
{row.original.approved_by_name || "Approved"}
|
||||
</div>
|
||||
<div className="text-gray-500">{formatDate(row.original.approved_on)}</div>
|
||||
</div>
|
||||
) : (
|
||||
<Badge variant="warning">Pending Approval</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "next_due_date",
|
||||
header: "Next Due Date",
|
||||
cell: ({ getValue }) => formatDate(getValue() as string),
|
||||
},
|
||||
...(canApproveCal
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: CalibrationPlanItem } }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setApprovingPlan(row.original)}
|
||||
>
|
||||
<ShieldCheck className="h-3.5 w-3.5 mr-1" />
|
||||
{row.original.approved_on ? "Edit Frequency" : "Approve / Edit Frequency"}
|
||||
</Button>
|
||||
),
|
||||
} satisfies ColumnDef<CalibrationPlanItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const agencies = (vendorsQuery.data?.items ?? []).filter(
|
||||
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
|
||||
);
|
||||
const existingPlanAssetIds = (plansQuery.data?.items ?? []).map((p) => p.asset_id);
|
||||
|
||||
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">Calibration</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Manage calibration plans, management approvals, due dates, and certificates
|
||||
</p>
|
||||
</div>
|
||||
{canAddCalPlan && (
|
||||
<Button onClick={() => setBulkAddOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Add Equipment to Calibration
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* KPI Strip */}
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
|
||||
<KpiCard label="Upcoming" value={summary.upcoming} color="text-blue-700 bg-blue-50 border-blue-200" />
|
||||
<KpiCard label="Due" value={summary.due} color="text-amber-700 bg-amber-50 border-amber-200" />
|
||||
<KpiCard label="Overdue" value={summary.overdue} color="text-red-700 bg-red-50 border-red-200" />
|
||||
<KpiCard label="Completed" value={summary.completed} color="text-green-700 bg-green-50 border-green-200" />
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5">
|
||||
<div className="relative lg:col-span-2">
|
||||
<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, certificate..."
|
||||
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>
|
||||
)}
|
||||
|
||||
<select
|
||||
value={agencyId}
|
||||
onChange={(e) => setAgencyId(e.target.value)}
|
||||
aria-label="Filter by Agency"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Agencies</option>
|
||||
{agencies.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{tab === "records" && (
|
||||
<>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
aria-label="Filter by Status"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Statuses</option>
|
||||
<option value="upcoming">Upcoming</option>
|
||||
<option value="due">Due</option>
|
||||
<option value="overdue">Overdue</option>
|
||||
<option value="completed">Completed</option>
|
||||
</select>
|
||||
|
||||
<div className="flex items-center gap-1.5 lg:col-span-2">
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Due from"
|
||||
value={dueFrom}
|
||||
onChange={(e) => setDueFrom(e.target.value)}
|
||||
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
<span className="text-xs text-gray-400">to</span>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Due to"
|
||||
value={dueTo}
|
||||
onChange={(e) => setDueTo(e.target.value)}
|
||||
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="border-b border-gray-200 flex gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab("records")}
|
||||
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
|
||||
tab === "records"
|
||||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||
}`}
|
||||
>
|
||||
Calibration Records
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab("plans")}
|
||||
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
|
||||
tab === "plans"
|
||||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||
}`}
|
||||
>
|
||||
Calibration Plans
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{tab === "records" && (
|
||||
<DataTable
|
||||
data={recordsQuery.data?.items ?? []}
|
||||
columns={recordColumns}
|
||||
loading={recordsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter calibration records..."
|
||||
exportFilename="calibration-records"
|
||||
emptyMessage="No calibration records match the current filters."
|
||||
/>
|
||||
)}
|
||||
|
||||
{tab === "plans" && (
|
||||
<DataTable
|
||||
data={plansQuery.data?.items ?? []}
|
||||
columns={planColumns}
|
||||
loading={plansQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter calibration plans..."
|
||||
exportFilename="calibration-plans"
|
||||
emptyMessage="No calibration plans found."
|
||||
/>
|
||||
)}
|
||||
|
||||
<BulkCalibrationAddModal
|
||||
open={bulkAddOpen}
|
||||
onClose={() => setBulkAddOpen(false)}
|
||||
existingPlanAssetIds={existingPlanAssetIds}
|
||||
canApprove={canApproveCal}
|
||||
/>
|
||||
|
||||
<ApproveCalibrationPlanModal
|
||||
open={Boolean(approvingPlan)}
|
||||
onClose={() => setApprovingPlan(null)}
|
||||
plan={approvingPlan}
|
||||
/>
|
||||
|
||||
<CompleteCalibrationModal
|
||||
open={Boolean(completingRec)}
|
||||
onClose={() => setCompletingRec(null)}
|
||||
recordId={completingRec?.id ?? null}
|
||||
assetLabel={completingRec ? `${completingRec.asset_code} ${completingRec.asset_name}` : ""}
|
||||
defaultAgencyId={completingRec?.agency_id}
|
||||
assetId={completingRec?.asset_id}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={Boolean(certModalRec)}
|
||||
onOpenChange={(o) => !o && setCertModalRec(null)}
|
||||
title={
|
||||
certModalRec
|
||||
? `Calibration Certificates — ${certModalRec.asset_code}`
|
||||
: "Certificates"
|
||||
}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{certModalRec && (
|
||||
<Attachments
|
||||
entityType="calibration_record"
|
||||
entityId={certModalRec.id}
|
||||
canUpload={canCompleteCal}
|
||||
canDelete={role === "system_admin" || role === "biomedical"}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function KpiCard({ label, value, color }: { label: string; value: number; color: string }) {
|
||||
return (
|
||||
<div className={`rounded-xl border p-4 ${color}`}>
|
||||
<div className="text-xs font-medium opacity-80">{label}</div>
|
||||
<div className="text-2xl font-bold mt-1">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,736 @@
|
||||
import { useState, useMemo } 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,
|
||||
Table as TableIcon,
|
||||
Calendar as CalendarIcon,
|
||||
CheckCircle2,
|
||||
CalendarClock,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Search,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
pmApi,
|
||||
type PMRecordItem,
|
||||
type PMScheduleItem,
|
||||
type ServiceMode,
|
||||
type ScheduleStatus,
|
||||
} from "@/api/pm";
|
||||
import { departmentsApi } from "@/api/masters";
|
||||
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 { ScheduleStatusBadge } from "@/components/StatusBadge";
|
||||
import {
|
||||
NewPMScheduleModal,
|
||||
CompletePMModal,
|
||||
ReschedulePMModal,
|
||||
} from "@/components/PMModals";
|
||||
|
||||
type ActiveTab = "records" | "schedules";
|
||||
type ViewMode = "table" | "calendar";
|
||||
|
||||
function currentYearMonth(): string {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function shiftYearMonth(ym: string, delta: number): string {
|
||||
const [y, m] = ym.split("-").map(Number);
|
||||
const d = new Date(y, m - 1 + delta, 1);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function buildMonthGrid(ym: string) {
|
||||
const [year, month] = ym.split("-").map(Number);
|
||||
const firstDay = new Date(year, month - 1, 1);
|
||||
const daysInMonth = new Date(year, month, 0).getDate();
|
||||
// Convert Sunday=0..Saturday=6 into Monday=0..Sunday=6
|
||||
const startOffset = (firstDay.getDay() + 6) % 7;
|
||||
|
||||
const cells: Array<{ dateStr: string | null; dayNum: number | null }> = [];
|
||||
for (let i = 0; i < startOffset; i++) {
|
||||
cells.push({ dateStr: null, dayNum: null });
|
||||
}
|
||||
for (let d = 1; d <= daysInMonth; d++) {
|
||||
const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
|
||||
cells.push({ dateStr, dayNum: d });
|
||||
}
|
||||
while (cells.length % 7 !== 0) {
|
||||
cells.push({ dateStr: null, dayNum: null });
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
const CHIP_COLOR: Record<string, string> = {
|
||||
upcoming: "bg-blue-100 text-blue-800 border-blue-200",
|
||||
due: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
overdue: "bg-red-100 text-red-800 border-red-200",
|
||||
completed: "bg-green-100 text-green-800 border-green-200",
|
||||
rescheduled: "bg-purple-100 text-purple-800 border-purple-200",
|
||||
};
|
||||
|
||||
export function PMPage() {
|
||||
const qc = useQueryClient();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const role = user?.role;
|
||||
const isDeptUser = role === "department_user";
|
||||
const canManagePm = can(role, "manage_pm") || role === "coordinator";
|
||||
|
||||
const [tab, setTab] = useState<ActiveTab>("records");
|
||||
const [viewMode, setViewMode] = useState<ViewMode>("table");
|
||||
const [monthFilter, setMonthFilter] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [serviceMode, setServiceMode] = useState<ServiceMode | "">("");
|
||||
const [statusFilter, setStatusFilter] = useState<ScheduleStatus | "">("");
|
||||
const [q, setQ] = useState("");
|
||||
|
||||
const [newScheduleOpen, setNewScheduleOpen] = useState(false);
|
||||
const [completingRec, setCompletingRec] = useState<PMRecordItem | null>(null);
|
||||
const [reschedulingRec, setReschedulingRec] = useState<PMRecordItem | null>(null);
|
||||
const [calendarDetailRec, setCalendarDetailRec] = useState<PMRecordItem | null>(null);
|
||||
|
||||
const effectiveCalendarMonth = monthFilter || currentYearMonth();
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: !isDeptUser,
|
||||
});
|
||||
|
||||
const recordsQuery = useQuery({
|
||||
queryKey: [
|
||||
"pm-records",
|
||||
viewMode === "calendar" ? effectiveCalendarMonth : monthFilter,
|
||||
departmentId,
|
||||
serviceMode,
|
||||
statusFilter,
|
||||
q,
|
||||
],
|
||||
queryFn: () =>
|
||||
pmApi.listRecords({
|
||||
q: q.trim() || undefined,
|
||||
month:
|
||||
viewMode === "calendar"
|
||||
? effectiveCalendarMonth
|
||||
: monthFilter || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
service_mode: serviceMode || undefined,
|
||||
status: statusFilter || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const schedulesQuery = useQuery({
|
||||
queryKey: ["pm-schedules", departmentId, serviceMode, q],
|
||||
queryFn: () =>
|
||||
pmApi.listSchedules({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
service_mode: serviceMode || undefined,
|
||||
is_active: true,
|
||||
page_size: 200,
|
||||
}),
|
||||
enabled: tab === "schedules",
|
||||
});
|
||||
|
||||
const deactivateScheduleMutation = useMutation({
|
||||
mutationFn: (id: number) => pmApi.deleteSchedule(id),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
||||
},
|
||||
});
|
||||
|
||||
const summary = recordsQuery.data?.summary ?? {
|
||||
upcoming: 0,
|
||||
due: 0,
|
||||
overdue: 0,
|
||||
completed_this_month: 0,
|
||||
};
|
||||
|
||||
const recordColumns: ColumnDef<PMRecordItem, unknown>[] = [
|
||||
{
|
||||
accessorKey: "planned_date",
|
||||
header: "Planned Date",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap font-medium">
|
||||
{formatDate(getValue() as string)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "asset_display",
|
||||
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
|
||||
header: "Asset",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<Link
|
||||
to={`/assets/${row.original.asset_id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
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",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "service_mode",
|
||||
header: "Mode",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (
|
||||
<Badge variant="outline">
|
||||
{getValue() === "in_house" ? "In-House" : "Outsourced"}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "team_provider",
|
||||
accessorFn: (r) => r.provider_name || r.responsible_team || "—",
|
||||
header: "Team / Provider",
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: "Status",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<ScheduleStatusBadge
|
||||
status={row.original.status}
|
||||
severity={row.original.severity}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "completed_date",
|
||||
header: "Completed Date",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs">
|
||||
{formatDate(getValue() as string | null)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "service_details",
|
||||
header: "Service Details",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="text-xs text-gray-600 line-clamp-2">
|
||||
{(getValue() as string | null) || "—"}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
...(canManagePm
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: PMRecordItem } }) => {
|
||||
const rec = row.original;
|
||||
const actionable =
|
||||
rec.status !== "completed" && rec.status !== "rescheduled";
|
||||
if (!actionable) return <span className="text-xs text-gray-400">—</span>;
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="success"
|
||||
onClick={() => setCompletingRec(rec)}
|
||||
>
|
||||
<CheckCircle2 className="h-3.5 w-3.5 mr-1" />
|
||||
Complete
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setReschedulingRec(rec)}
|
||||
>
|
||||
<CalendarClock className="h-3.5 w-3.5 mr-1" />
|
||||
Reschedule
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
} satisfies ColumnDef<PMRecordItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
const scheduleColumns: ColumnDef<PMScheduleItem, unknown>[] = [
|
||||
{
|
||||
id: "asset_display",
|
||||
accessorFn: (s) => `${s.asset_code} ${s.asset_name}`,
|
||||
header: "Asset",
|
||||
enableColumnFilter: true,
|
||||
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",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "service_mode",
|
||||
header: "Service Mode",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() === "in_house" ? "In-House" : "Outsourced"),
|
||||
},
|
||||
{
|
||||
accessorKey: "frequency_months",
|
||||
header: "Frequency",
|
||||
cell: ({ getValue }) => `Every ${String(getValue())} months`,
|
||||
},
|
||||
{
|
||||
id: "team_provider",
|
||||
accessorFn: (s) => s.provider_name || s.responsible_team || "—",
|
||||
header: "Team / Provider",
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "contract_summary",
|
||||
header: "Contract",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "next_planned_date",
|
||||
header: "Next Planned",
|
||||
cell: ({ getValue }) => formatDate(getValue() as string),
|
||||
},
|
||||
...(canManagePm
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: PMScheduleItem } }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:bg-red-50"
|
||||
disabled={deactivateScheduleMutation.isPending}
|
||||
onClick={() => deactivateScheduleMutation.mutate(row.original.id)}
|
||||
>
|
||||
Deactivate
|
||||
</Button>
|
||||
),
|
||||
} satisfies ColumnDef<PMScheduleItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
const recordsByDate = useMemo(() => {
|
||||
const map = new Map<string, PMRecordItem[]>();
|
||||
for (const r of recordsQuery.data?.items ?? []) {
|
||||
const list = map.get(r.planned_date) ?? [];
|
||||
list.push(r);
|
||||
map.set(r.planned_date, list);
|
||||
}
|
||||
return map;
|
||||
}, [recordsQuery.data?.items]);
|
||||
|
||||
const calendarCells = useMemo(
|
||||
() => buildMonthGrid(effectiveCalendarMonth),
|
||||
[effectiveCalendarMonth]
|
||||
);
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
|
||||
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">Preventive Maintenance</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Track in-house and outsourced PM schedules, due dates, and completion logs
|
||||
</p>
|
||||
</div>
|
||||
{canManagePm && (
|
||||
<Button onClick={() => setNewScheduleOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
New PM Schedule
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* KPI Strip */}
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
|
||||
<KpiCard label="Upcoming" value={summary.upcoming} color="text-blue-700 bg-blue-50 border-blue-200" />
|
||||
<KpiCard label="Due" value={summary.due} color="text-amber-700 bg-amber-50 border-amber-200" />
|
||||
<KpiCard label="Overdue" value={summary.overdue} color="text-red-700 bg-red-50 border-red-200" />
|
||||
<KpiCard
|
||||
label="Completed This Month"
|
||||
value={summary.completed_this_month}
|
||||
color="text-green-700 bg-green-50 border-green-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5">
|
||||
<div className="relative lg:col-span-2">
|
||||
<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, team..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<input
|
||||
type="month"
|
||||
aria-label="Filter by Month"
|
||||
value={monthFilter}
|
||||
onChange={(e) => setMonthFilter(e.target.value)}
|
||||
className="flex-1 px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
{monthFilter && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMonthFilter("")}
|
||||
className="px-2 py-1 text-xs border border-gray-200 rounded hover:bg-gray-50"
|
||||
>
|
||||
All
|
||||
</button>
|
||||
)}
|
||||
</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>
|
||||
)}
|
||||
|
||||
<select
|
||||
value={serviceMode}
|
||||
onChange={(e) => setServiceMode(e.target.value as ServiceMode | "")}
|
||||
aria-label="Filter by Service Mode"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Modes</option>
|
||||
<option value="in_house">In-House</option>
|
||||
<option value="outsourced">Outsourced</option>
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value as ScheduleStatus | "")}
|
||||
aria-label="Filter by Status"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Statuses</option>
|
||||
<option value="upcoming">Upcoming</option>
|
||||
<option value="due">Due</option>
|
||||
<option value="overdue">Overdue</option>
|
||||
<option value="completed">Completed</option>
|
||||
<option value="rescheduled">Rescheduled</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Tabs + View Switcher */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-gray-200 pb-2">
|
||||
<div className="flex gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab("records")}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-[9px] transition-colors ${
|
||||
tab === "records"
|
||||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||
}`}
|
||||
>
|
||||
PM Records
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab("schedules")}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-[9px] transition-colors ${
|
||||
tab === "schedules"
|
||||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||
}`}
|
||||
>
|
||||
Active Schedules
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{tab === "records" && (
|
||||
<div className="inline-flex rounded-md border border-gray-200 bg-white p-0.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setViewMode("table")}
|
||||
className={`inline-flex items-center gap-1.5 px-3 py-1 rounded text-xs font-medium transition-colors ${
|
||||
viewMode === "table"
|
||||
? "bg-[#1e3a8a] text-white"
|
||||
: "text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<TableIcon className="h-3.5 w-3.5" />
|
||||
Table View
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setViewMode("calendar")}
|
||||
className={`inline-flex items-center gap-1.5 px-3 py-1 rounded text-xs font-medium transition-colors ${
|
||||
viewMode === "calendar"
|
||||
? "bg-[#1e3a8a] text-white"
|
||||
: "text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<CalendarIcon className="h-3.5 w-3.5" />
|
||||
Calendar View
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
{tab === "records" && viewMode === "table" && (
|
||||
<DataTable
|
||||
data={recordsQuery.data?.items ?? []}
|
||||
columns={recordColumns}
|
||||
loading={recordsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter PM records..."
|
||||
exportFilename="pm-records"
|
||||
emptyMessage="No PM records match the current filters."
|
||||
/>
|
||||
)}
|
||||
|
||||
{tab === "records" && viewMode === "calendar" && (
|
||||
<div className="bg-white border border-gray-200 rounded-xl p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-gray-800">
|
||||
PM Calendar — {effectiveCalendarMonth}
|
||||
</h2>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setMonthFilter(shiftYearMonth(effectiveCalendarMonth, -1))}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setMonthFilter(currentYearMonth())}
|
||||
>
|
||||
Today
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setMonthFilter(shiftYearMonth(effectiveCalendarMonth, 1))}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-1 text-center text-xs font-semibold text-gray-500 pb-1">
|
||||
{["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
|
||||
<div key={d} className="py-1">
|
||||
{d}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-1">
|
||||
{calendarCells.map((cell, idx) => {
|
||||
const items = cell.dateStr ? recordsByDate.get(cell.dateStr) ?? [] : [];
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className={`min-h-24 rounded-md border p-1.5 text-left ${
|
||||
cell.dayNum ? "bg-white border-gray-200" : "bg-gray-50 border-gray-100"
|
||||
}`}
|
||||
>
|
||||
{cell.dayNum && (
|
||||
<>
|
||||
<div className="text-[11px] font-semibold text-gray-500 mb-1">
|
||||
{cell.dayNum}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => setCalendarDetailRec(item)}
|
||||
className={`w-full text-left px-1.5 py-0.5 rounded border text-[10px] font-medium truncate ${
|
||||
CHIP_COLOR[item.status] ?? "bg-gray-100 text-gray-700"
|
||||
}`}
|
||||
title={`${item.asset_code} — ${item.asset_name} (${item.status})`}
|
||||
>
|
||||
{item.asset_code}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === "schedules" && (
|
||||
<DataTable
|
||||
data={schedulesQuery.data?.items ?? []}
|
||||
columns={scheduleColumns}
|
||||
loading={schedulesQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter PM schedules..."
|
||||
exportFilename="pm-schedules"
|
||||
emptyMessage="No active PM schedules found."
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Calendar Item Quick Detail Modal */}
|
||||
<Modal
|
||||
open={Boolean(calendarDetailRec)}
|
||||
onOpenChange={(o) => !o && setCalendarDetailRec(null)}
|
||||
title={
|
||||
calendarDetailRec
|
||||
? `${calendarDetailRec.asset_code} — ${calendarDetailRec.asset_name}`
|
||||
: "PM Details"
|
||||
}
|
||||
>
|
||||
{calendarDetailRec && (
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<ScheduleStatusBadge
|
||||
status={calendarDetailRec.status}
|
||||
severity={calendarDetailRec.severity}
|
||||
/>
|
||||
<Badge variant="outline">
|
||||
{calendarDetailRec.service_mode === "in_house" ? "In-House" : "Outsourced"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2 text-xs">
|
||||
<div>
|
||||
<span className="text-gray-500">Planned Date:</span>{" "}
|
||||
<strong>{formatDate(calendarDetailRec.planned_date)}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500">Department:</span>{" "}
|
||||
<strong>{calendarDetailRec.department_name || "—"}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500">Team / Provider:</span>{" "}
|
||||
<strong>
|
||||
{calendarDetailRec.provider_name ||
|
||||
calendarDetailRec.responsible_team ||
|
||||
"—"}
|
||||
</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500">Completed:</span>{" "}
|
||||
<strong>{formatDate(calendarDetailRec.completed_date)}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Link to={`/assets/${calendarDetailRec.asset_id}`}>
|
||||
<Button variant="outline" size="sm">
|
||||
View Asset
|
||||
</Button>
|
||||
</Link>
|
||||
{canManagePm &&
|
||||
calendarDetailRec.status !== "completed" &&
|
||||
calendarDetailRec.status !== "rescheduled" && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setReschedulingRec(calendarDetailRec);
|
||||
setCalendarDetailRec(null);
|
||||
}}
|
||||
>
|
||||
Reschedule
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="success"
|
||||
onClick={() => {
|
||||
setCompletingRec(calendarDetailRec);
|
||||
setCalendarDetailRec(null);
|
||||
}}
|
||||
>
|
||||
Complete
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<NewPMScheduleModal open={newScheduleOpen} onClose={() => setNewScheduleOpen(false)} />
|
||||
|
||||
<CompletePMModal
|
||||
open={Boolean(completingRec)}
|
||||
onClose={() => setCompletingRec(null)}
|
||||
recordId={completingRec?.id ?? null}
|
||||
assetLabel={completingRec ? `${completingRec.asset_code} ${completingRec.asset_name}` : ""}
|
||||
assetId={completingRec?.asset_id}
|
||||
/>
|
||||
|
||||
<ReschedulePMModal
|
||||
open={Boolean(reschedulingRec)}
|
||||
onClose={() => setReschedulingRec(null)}
|
||||
recordId={reschedulingRec?.id ?? null}
|
||||
assetLabel={
|
||||
reschedulingRec ? `${reschedulingRec.asset_code} ${reschedulingRec.asset_name}` : ""
|
||||
}
|
||||
assetId={reschedulingRec?.asset_id}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function KpiCard({ label, value, color }: { label: string; value: number; color: string }) {
|
||||
return (
|
||||
<div className={`rounded-xl border p-4 ${color}`}>
|
||||
<div className="text-xs font-medium opacity-80">{label}</div>
|
||||
<div className="text-2xl font-bold mt-1">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -36,12 +36,6 @@ export const DashboardPage = () => (
|
||||
</div>
|
||||
</StubPage>
|
||||
);
|
||||
export const PMPage = () => (
|
||||
<StubPage title="Preventive Maintenance" phase={4} description="PM schedules and calendar view." />
|
||||
);
|
||||
export const CalibrationPage = () => (
|
||||
<StubPage title="Calibration" phase={4} description="Calibration plans and records with due-date alerts." />
|
||||
);
|
||||
export const ContractsPage = () => (
|
||||
<StubPage title="Contracts & Warranty" phase={5} description="AMC/CMC contracts and warranty tracking." />
|
||||
);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { CalibrationPage } from "@/pages/CalibrationPage";
|
||||
import {
|
||||
calibrationApi,
|
||||
type CalibrationPlanItem,
|
||||
} from "@/api/calibration";
|
||||
import { departmentsApi, vendorsApi } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
const MOCK_PLAN: CalibrationPlanItem = {
|
||||
id: 50,
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-LAB-0009",
|
||||
asset_name: "Auto Analyzer",
|
||||
department_id: 2,
|
||||
department_name: "Pathology",
|
||||
frequency_months: 12,
|
||||
calibrations_per_year: 1,
|
||||
agency_id: 4,
|
||||
agency_name: "NABL Calibration Labs",
|
||||
approved_by_id: null,
|
||||
approved_by_name: null,
|
||||
approved_on: null,
|
||||
next_due_date: "2026-12-01",
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
function renderCalibrationPage() {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter>
|
||||
<CalibrationPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("CalibrationPage", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.spyOn(departmentsApi, "list").mockResolvedValue({
|
||||
items: [{ id: 2, name: "Pathology", code: "LAB", description: null, is_active: true }],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(vendorsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(calibrationApi, "listRecords").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
summary: { upcoming: 1, due: 0, overdue: 0, completed: 2 },
|
||||
});
|
||||
vi.spyOn(calibrationApi, "listPlans").mockResolvedValue({
|
||||
items: [MOCK_PLAN],
|
||||
total: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows Approve / Edit Frequency button on Calibration Plans tab for management", async () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 5,
|
||||
email: "mgmt@poona.org",
|
||||
name: "Hospital Director",
|
||||
role: "management",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "test-token",
|
||||
});
|
||||
|
||||
renderCalibrationPage();
|
||||
|
||||
const plansTab = screen.getByRole("button", { name: /Calibration Plans/i });
|
||||
fireEvent.click(plansTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("PHRC-LAB-0009")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /Approve \/ Edit Frequency/i })
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("hides Approve / Edit Frequency button on Calibration Plans tab for biomedical", async () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 2,
|
||||
email: "bio@poona.org",
|
||||
name: "Biomed Engineer",
|
||||
role: "biomedical",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "test-token",
|
||||
});
|
||||
|
||||
renderCalibrationPage();
|
||||
|
||||
const plansTab = screen.getByRole("button", { name: /Calibration Plans/i });
|
||||
fireEvent.click(plansTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("PHRC-LAB-0009")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /Approve \/ Edit Frequency/i })
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /Edit Frequency/i })
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /Add Equipment to Calibration/i })
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { PMPage } from "@/pages/PMPage";
|
||||
import { pmApi, type PMRecordItem } from "@/api/pm";
|
||||
import { departmentsApi } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
function currentMonthDay(day = 15): string {
|
||||
const now = new Date();
|
||||
const y = now.getFullYear();
|
||||
const m = String(now.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(day).padStart(2, "0");
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
const MOCK_RECORD: PMRecordItem = {
|
||||
id: 101,
|
||||
schedule_id: 11,
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
location_name: "ICU Bay 1",
|
||||
service_mode: "in_house",
|
||||
responsible_team: "Biomed Team A",
|
||||
provider_id: null,
|
||||
provider_name: null,
|
||||
contract_id: null,
|
||||
frequency_months: 6,
|
||||
planned_date: currentMonthDay(15),
|
||||
completed_date: null,
|
||||
status: "due",
|
||||
severity: "yellow",
|
||||
service_details: null,
|
||||
remarks: null,
|
||||
rescheduled_to: null,
|
||||
};
|
||||
|
||||
function renderPMPage() {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter>
|
||||
<PMPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("PMPage", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 2,
|
||||
email: "bio@poona.org",
|
||||
name: "Biomed Engineer",
|
||||
role: "biomedical",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "test-token",
|
||||
});
|
||||
|
||||
vi.spyOn(departmentsApi, "list").mockResolvedValue({
|
||||
items: [{ id: 1, name: "ICU", code: "ICU", description: null, is_active: true }],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(pmApi, "listRecords").mockResolvedValue({
|
||||
items: [MOCK_RECORD],
|
||||
total: 1,
|
||||
summary: { upcoming: 3, due: 2, overdue: 1, completed_this_month: 5 },
|
||||
});
|
||||
vi.spyOn(pmApi, "listSchedules").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("renders KPI strip counts and switches between Table and Calendar views", async () => {
|
||||
renderPMPage();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText("Upcoming").length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText("Completed This Month")).toBeInTheDocument();
|
||||
expect(screen.getByText("3")).toBeInTheDocument();
|
||||
expect(screen.getByText("2")).toBeInTheDocument();
|
||||
expect(screen.getByText("5")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Initially in Table view
|
||||
expect(screen.getByText("PHRC-ICU-0001")).toBeInTheDocument();
|
||||
expect(screen.getByText("ICU Ventilator")).toBeInTheDocument();
|
||||
|
||||
// Switch to Calendar view
|
||||
const calendarBtn = screen.getByRole("button", { name: /Calendar/i });
|
||||
fireEvent.click(calendarBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Mon")).toBeInTheDocument();
|
||||
expect(screen.getByText("Sun")).toBeInTheDocument();
|
||||
expect(screen.getByText(/PHRC-ICU-0001/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Switch back to Table view
|
||||
const tableBtn = screen.getByRole("button", { name: /Table View/i });
|
||||
fireEvent.click(tableBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("Mon")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("ICU Ventilator")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1 +1 @@
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/pm.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/pmpage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
||||
Reference in New Issue
Block a user