initial commit
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useEffect } from "react";
|
||||
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { AppShell } from "@/components/layout/AppShell";
|
||||
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
|
||||
import { LoginPage } from "@/pages/LoginPage";
|
||||
import { AccessDeniedPage } from "@/pages/AccessDeniedPage";
|
||||
import { MastersPage } from "@/pages/MastersPage";
|
||||
import { SettingsPage } from "@/pages/SettingsPage";
|
||||
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 { ContractsPage } from "@/pages/ContractsPage";
|
||||
import { InsurancePage } from "@/pages/InsurancePage";
|
||||
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
||||
import { VisitsPage } from "@/pages/VisitsPage";
|
||||
import { DashboardPage } from "@/pages/DashboardPage";
|
||||
import { NotificationsPage } from "@/pages/NotificationsPage";
|
||||
import { ReportsPage } from "@/pages/ReportsPage";
|
||||
import { AIReportPage } from "@/pages/AIReportPage";
|
||||
import { ReportDetailPage } from "@/pages/ReportDetailPage";
|
||||
import { AuditLogsPage } from "@/pages/AuditLogsPage";
|
||||
import { ToastProvider } from "@/components/ToastProvider";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can, type Capability } from "@/lib/permissions";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: 1, staleTime: 30_000 } },
|
||||
});
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { user, token, hydrating } = useAuthStore();
|
||||
|
||||
if (hydrating) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-center space-y-2">
|
||||
<div className="h-8 w-8 border-4 border-[#1e3a8a] border-t-transparent rounded-full animate-spin mx-auto" />
|
||||
<p className="text-sm text-gray-500">Loading Poona Hospital AMS...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!token || !user) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function RoleGuard({
|
||||
capability,
|
||||
children,
|
||||
}: {
|
||||
capability: Capability;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
if (!can(user?.role, capability)) {
|
||||
return <AccessDeniedPage />;
|
||||
}
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function AppRoutes() {
|
||||
const hydrate = useAuthStore((s) => s.hydrate);
|
||||
|
||||
useEffect(() => {
|
||||
hydrate();
|
||||
}, [hydrate]);
|
||||
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<AppShell />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
>
|
||||
<Route path="/" element={<DashboardPage />} />
|
||||
<Route path="/assets" element={<AssetsPage />} />
|
||||
<Route path="/assets/:id" element={<AssetDetailPage />} />
|
||||
<Route path="/complaints" element={<ComplaintsPage />} />
|
||||
<Route path="/complaints/:id" element={<ComplaintDetailPage />} />
|
||||
<Route path="/pm" element={<PMPage />} />
|
||||
<Route path="/calibration" element={<CalibrationPage />} />
|
||||
<Route path="/contracts" element={<ContractsPage />} />
|
||||
<Route path="/insurance" element={<InsurancePage />} />
|
||||
<Route path="/demo-equipment" element={<DemoEquipmentPage />} />
|
||||
<Route
|
||||
path="/visits"
|
||||
element={
|
||||
<RoleGuard capability="view_visits">
|
||||
<VisitsPage />
|
||||
</RoleGuard>
|
||||
}
|
||||
/>
|
||||
<Route path="/reports" element={<ReportsPage />} />
|
||||
<Route
|
||||
path="/reports/ai"
|
||||
element={
|
||||
<RoleGuard capability="view_ai_reports">
|
||||
<AIReportPage />
|
||||
</RoleGuard>
|
||||
}
|
||||
/>
|
||||
<Route path="/reports/:reportKey" element={<ReportDetailPage />} />
|
||||
<Route path="/notifications" element={<NotificationsPage />} />
|
||||
<Route
|
||||
path="/masters"
|
||||
element={
|
||||
<RoleGuard capability="manage_admin">
|
||||
<MastersPage />
|
||||
</RoleGuard>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/audit-logs"
|
||||
element={
|
||||
<RoleGuard capability="manage_admin">
|
||||
<AuditLogsPage />
|
||||
</RoleGuard>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/settings"
|
||||
element={
|
||||
<RoleGuard capability="manage_admin">
|
||||
<SettingsPage />
|
||||
</RoleGuard>
|
||||
}
|
||||
/>
|
||||
<Route path="/demo" element={<DataTableDemoPage />} />
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<BrowserRouter>
|
||||
<AppRoutes />
|
||||
</BrowserRouter>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export type AIPeriod = "3m" | "6m" | "12m" | "custom";
|
||||
export type AISectionKey =
|
||||
| "summary"
|
||||
| "comparison"
|
||||
| "depreciation"
|
||||
| "efficiency"
|
||||
| "breakdown-frequency";
|
||||
|
||||
export interface AIFilterParams {
|
||||
period?: AIPeriod;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
department_id?: number;
|
||||
category_id?: number;
|
||||
}
|
||||
|
||||
export interface AIStatus {
|
||||
enabled: boolean;
|
||||
ai_enabled_setting: boolean;
|
||||
provider: string;
|
||||
model: string;
|
||||
reachable: boolean;
|
||||
}
|
||||
|
||||
export interface AIMetric {
|
||||
id: string;
|
||||
label: string;
|
||||
value: number | string | null;
|
||||
unit: string;
|
||||
formatted: string;
|
||||
}
|
||||
|
||||
export interface AINarrativeBullet {
|
||||
text: string;
|
||||
metric_ids: string[];
|
||||
}
|
||||
|
||||
export interface AINarrative {
|
||||
source: "ai" | "rule_based";
|
||||
model: string | null;
|
||||
validated: boolean;
|
||||
failure_reason: string | null;
|
||||
generated_at: string;
|
||||
headline: string;
|
||||
bullets: AINarrativeBullet[];
|
||||
}
|
||||
|
||||
export interface AIHowCalculated {
|
||||
formulas: string[];
|
||||
latest_equipment_rule?: string;
|
||||
missing_data_rule?: string;
|
||||
weights?: Record<string, number>;
|
||||
settings_used?: Record<string, string | number | boolean | null>;
|
||||
}
|
||||
|
||||
export interface AISuggestion {
|
||||
id: string;
|
||||
rule: string;
|
||||
severity: "red" | "yellow" | "info";
|
||||
title: string;
|
||||
detail: string;
|
||||
asset_codes: string[];
|
||||
evidence_metric_ids: string[];
|
||||
action_for_human: string;
|
||||
}
|
||||
|
||||
export interface AIComparisonRow {
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_name: string;
|
||||
category_name: string;
|
||||
installation_date: string | null;
|
||||
purchase_date: string | null;
|
||||
purchase_value: number | null;
|
||||
in_house_cost: number | null;
|
||||
in_house_reason: string | null;
|
||||
outsourced_cost: number | null;
|
||||
outsourced_reason: string | null;
|
||||
rent_cost: number | null;
|
||||
rent_reason: string | null;
|
||||
lowest_scenario: string | null;
|
||||
lowest_scenario_label: string | null;
|
||||
lowest_cost: number | null;
|
||||
savings_vs_next: number | null;
|
||||
current_setup: string | null;
|
||||
}
|
||||
|
||||
export interface AIComparisonChartPoint {
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
in_house: number | null;
|
||||
outsourced: number | null;
|
||||
rent: number | null;
|
||||
}
|
||||
|
||||
export interface AIComparisonResponse {
|
||||
section: "comparison";
|
||||
title: string;
|
||||
period_start: string;
|
||||
period_end: string;
|
||||
horizon_years: number;
|
||||
summary: {
|
||||
latest_count: number;
|
||||
horizon_years: number;
|
||||
in_house_lowest_count: number;
|
||||
outsourced_lowest_count: number;
|
||||
rent_lowest_count: number;
|
||||
};
|
||||
rows: AIComparisonRow[];
|
||||
chart_data: AIComparisonChartPoint[];
|
||||
metrics: AIMetric[];
|
||||
narrative: AINarrative;
|
||||
how_calculated: AIHowCalculated;
|
||||
}
|
||||
|
||||
export interface AIDepreciationCurvePoint {
|
||||
year: number;
|
||||
book_value: number;
|
||||
}
|
||||
|
||||
export interface AIDepreciationRow {
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_name: string;
|
||||
category_name: string;
|
||||
acquisition_mode: string;
|
||||
purchase_value: number | null;
|
||||
depreciation_applicable: boolean;
|
||||
depreciation_reason: string | null;
|
||||
method: string | null;
|
||||
useful_life_years: number | null;
|
||||
book_value: number | null;
|
||||
accumulated_depreciation: number | null;
|
||||
annual_charge: number | null;
|
||||
fully_depreciated: boolean;
|
||||
contract_cost_to_date: number;
|
||||
repair_and_spare_cost_to_date: number;
|
||||
inhouse_pm_cost_to_date: number;
|
||||
maintenance_cost: number;
|
||||
maintenance_ratio: number | null;
|
||||
lifetime_cost: number | null;
|
||||
cost_per_year_of_use: number | null;
|
||||
review_flag: boolean;
|
||||
curve: AIDepreciationCurvePoint[];
|
||||
}
|
||||
|
||||
export interface AIDepreciationResponse {
|
||||
section: "depreciation";
|
||||
title: string;
|
||||
period_start: string;
|
||||
period_end: string;
|
||||
summary: {
|
||||
total_purchase_value: number;
|
||||
total_book_value: number;
|
||||
total_accumulated_depreciation: number;
|
||||
total_maintenance_cost: number;
|
||||
fully_depreciated_count: number;
|
||||
review_flag_count: number;
|
||||
replacement_review_ratio: number;
|
||||
excluded_count: number;
|
||||
};
|
||||
rows: AIDepreciationRow[];
|
||||
chart_data: AIDepreciationCurvePoint[];
|
||||
metrics: AIMetric[];
|
||||
narrative: AINarrative;
|
||||
how_calculated: AIHowCalculated;
|
||||
}
|
||||
|
||||
export interface AIEfficiencyGroupRow {
|
||||
group: string;
|
||||
group_type: "department" | "category";
|
||||
assets_in_scope: number;
|
||||
uptime_pct: number;
|
||||
pm_compliance_pct: number;
|
||||
response_score: number;
|
||||
repeat_free_score: number;
|
||||
mttr_hours: number | null;
|
||||
mtbf_hours: number | null;
|
||||
avg_response_minutes: number | null;
|
||||
efficiency_score: number;
|
||||
parts: {
|
||||
uptime: number;
|
||||
pm_compliance: number;
|
||||
response: number;
|
||||
repeat_free: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AIEfficiencyChartPoint {
|
||||
group: string;
|
||||
uptime: number;
|
||||
pm_compliance: number;
|
||||
response: number;
|
||||
repeat_free: number;
|
||||
efficiency_score: number;
|
||||
}
|
||||
|
||||
export interface AIEfficiencyResponse {
|
||||
section: "efficiency";
|
||||
title: string;
|
||||
period_start: string;
|
||||
period_end: string;
|
||||
weights: Record<string, number>;
|
||||
summary: {
|
||||
assets_in_scope: number;
|
||||
avg_uptime_pct: number;
|
||||
mttr_hours: number | null;
|
||||
mtbf_hours: number | null;
|
||||
avg_response_minutes: number | null;
|
||||
pm_compliance_pct: number;
|
||||
avg_efficiency_score: number;
|
||||
};
|
||||
rows: AIEfficiencyGroupRow[];
|
||||
by_department: AIEfficiencyGroupRow[];
|
||||
by_category: AIEfficiencyGroupRow[];
|
||||
chart_data: AIEfficiencyChartPoint[];
|
||||
metrics: AIMetric[];
|
||||
narrative: AINarrative;
|
||||
how_calculated: AIHowCalculated;
|
||||
}
|
||||
|
||||
export interface AIBreakdownAssetRow {
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_name: string;
|
||||
category_name: string;
|
||||
breakdown_count: number;
|
||||
avg_downtime_minutes: number;
|
||||
avg_downtime_hours: number;
|
||||
repeat_window_count: number;
|
||||
repeat_failure: boolean;
|
||||
}
|
||||
|
||||
export interface AIBreakdownGroupRow {
|
||||
group: string;
|
||||
group_type: "department" | "category";
|
||||
breakdowns: number;
|
||||
assets_in_scope: number;
|
||||
avg_breakdowns_per_equipment: number;
|
||||
breakdowns_per_1000_hours: number;
|
||||
}
|
||||
|
||||
export interface AIBreakdownFrequencyResponse {
|
||||
section: "breakdown_frequency";
|
||||
title: string;
|
||||
period_start: string;
|
||||
period_end: string;
|
||||
summary: {
|
||||
total_breakdowns: number;
|
||||
assets_in_scope: number;
|
||||
avg_breakdowns_per_equipment: number;
|
||||
repeat_failure_count: number;
|
||||
repeat_threshold: number;
|
||||
repeat_window_days: number;
|
||||
};
|
||||
rows: AIBreakdownAssetRow[];
|
||||
by_department: AIBreakdownGroupRow[];
|
||||
by_category: AIBreakdownGroupRow[];
|
||||
chart_data: {
|
||||
monthly_trend: { month: string; label: string; breakdowns: number }[];
|
||||
by_department: AIBreakdownGroupRow[];
|
||||
by_category: AIBreakdownGroupRow[];
|
||||
};
|
||||
metrics: AIMetric[];
|
||||
narrative: AINarrative;
|
||||
how_calculated: AIHowCalculated;
|
||||
}
|
||||
|
||||
export interface AISummaryResponse {
|
||||
section: "summary";
|
||||
title: string;
|
||||
period_start: string;
|
||||
period_end: string;
|
||||
sections: {
|
||||
comparison: AIComparisonResponse["summary"];
|
||||
depreciation: AIDepreciationResponse["summary"];
|
||||
efficiency: AIEfficiencyResponse["summary"];
|
||||
breakdown_frequency: AIBreakdownFrequencyResponse["summary"];
|
||||
};
|
||||
suggestions: AISuggestion[];
|
||||
suggestions_evidence: AIMetric[];
|
||||
metrics: AIMetric[];
|
||||
narrative: AINarrative;
|
||||
how_calculated: AIHowCalculated;
|
||||
}
|
||||
|
||||
function buildAIQuery(params: AIFilterParams & { format?: "xlsx" | "csv" } = {}): string {
|
||||
const sp = new URLSearchParams();
|
||||
if (params.period) sp.set("period", params.period);
|
||||
if (params.period === "custom") {
|
||||
if (params.date_from) sp.set("date_from", params.date_from);
|
||||
if (params.date_to) sp.set("date_to", params.date_to);
|
||||
}
|
||||
if (params.department_id != null) sp.set("department_id", String(params.department_id));
|
||||
if (params.category_id != null) sp.set("category_id", String(params.category_id));
|
||||
if (params.format) sp.set("format", params.format);
|
||||
const qs = sp.toString();
|
||||
return qs ? `?${qs}` : "";
|
||||
}
|
||||
|
||||
export const aiApi = {
|
||||
getStatus: () => api.get<AIStatus>("/ai/status"),
|
||||
getSummary: (filters: AIFilterParams = {}) =>
|
||||
api.get<AISummaryResponse>(`/ai/summary${buildAIQuery(filters)}`),
|
||||
getComparison: (filters: AIFilterParams = {}) =>
|
||||
api.get<AIComparisonResponse>(`/ai/comparison${buildAIQuery(filters)}`),
|
||||
getDepreciation: (filters: AIFilterParams = {}) =>
|
||||
api.get<AIDepreciationResponse>(`/ai/depreciation${buildAIQuery(filters)}`),
|
||||
getEfficiency: (filters: AIFilterParams = {}) =>
|
||||
api.get<AIEfficiencyResponse>(`/ai/efficiency${buildAIQuery(filters)}`),
|
||||
getBreakdownFrequency: (filters: AIFilterParams = {}) =>
|
||||
api.get<AIBreakdownFrequencyResponse>(`/ai/breakdown-frequency${buildAIQuery(filters)}`),
|
||||
regenerateNarrative: (section: AISectionKey, filters: AIFilterParams = {}) =>
|
||||
api.post<{ section: string; narrative: AINarrative }>("/ai/narrative/regenerate", {
|
||||
section,
|
||||
filters,
|
||||
}),
|
||||
exportSection: async (
|
||||
section: AISectionKey,
|
||||
format: "xlsx" | "csv",
|
||||
filters: AIFilterParams = {}
|
||||
) => {
|
||||
const qs = buildAIQuery({ ...filters, format });
|
||||
const { blob } = await api.downloadBlob(`/ai/${section}/export${qs}`);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `ai-${section}.${format}`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
import { api } from "./client";
|
||||
import type { AttachmentItem } from "./attachments";
|
||||
|
||||
export type AssetStatus = "in_service" | "under_repair" | "out_of_service" | "condemned";
|
||||
export type AssetCriticality = "critical" | "non_critical";
|
||||
export type AcquisitionMode = "purchased" | "rented";
|
||||
export type DepreciationMethod = "straight_line" | "written_down";
|
||||
export type CoverageTag = "warranty" | "cmc" | "amc" | "other_contract" | "out_of_contract";
|
||||
export type CoverageStatus = "active" | "expiring" | "expired" | "none";
|
||||
export type AlertSeverity = "ok" | "yellow" | "red" | "none";
|
||||
export type CalibrationStatus = "upcoming" | "due" | "overdue" | "completed" | "none";
|
||||
|
||||
export interface CoverageInfo {
|
||||
tag: CoverageTag;
|
||||
contract_id: number | null;
|
||||
warranty_id: number | null;
|
||||
provider_id: number | null;
|
||||
provider_name: string | null;
|
||||
provider_contact: string | null;
|
||||
valid_from: string | null;
|
||||
valid_until: string | null;
|
||||
days_left: number | null;
|
||||
severity: "ok" | "yellow" | "red";
|
||||
}
|
||||
|
||||
export interface AssetItem {
|
||||
id: number;
|
||||
asset_code: string;
|
||||
serial_no: string;
|
||||
name: string;
|
||||
category_id: number;
|
||||
category_name: string | null;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_id: number;
|
||||
location_name: string | null;
|
||||
supplier_id: number | null;
|
||||
supplier_name: string | null;
|
||||
purchase_value?: number | null;
|
||||
acquisition_mode?: AcquisitionMode | string;
|
||||
monthly_rent?: number | null;
|
||||
useful_life_years?: number | null;
|
||||
salvage_pct?: number | null;
|
||||
depreciation_method?: DepreciationMethod | string | null;
|
||||
purchase_date: string | null;
|
||||
installation_date: string | null;
|
||||
status: AssetStatus;
|
||||
criticality: AssetCriticality;
|
||||
requires_calibration: boolean;
|
||||
insurance_applicable: boolean;
|
||||
remarks: string | null;
|
||||
warranty_status: CoverageStatus;
|
||||
warranty_end_date: string | null;
|
||||
warranty_severity: AlertSeverity;
|
||||
contract_status: CoverageStatus;
|
||||
contract_type: string | null;
|
||||
contract_end_date: string | null;
|
||||
contract_severity: AlertSeverity;
|
||||
calibration_status: CalibrationStatus;
|
||||
calibration_due_date: string | null;
|
||||
calibration_severity: AlertSeverity;
|
||||
insurance_status: CoverageStatus;
|
||||
insurance_end_date: string | null;
|
||||
coverage_tag?: CoverageTag | string;
|
||||
coverage?: CoverageInfo | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AssetLookupItem {
|
||||
id: number;
|
||||
asset_code: string;
|
||||
serial_no: string;
|
||||
name: string;
|
||||
category_id: number;
|
||||
category_name: string | null;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_id: number;
|
||||
location_name: string | null;
|
||||
supplier_id: number | null;
|
||||
supplier_name: string | null;
|
||||
status: AssetStatus;
|
||||
criticality: AssetCriticality;
|
||||
requires_calibration: boolean;
|
||||
insurance_applicable: boolean;
|
||||
warranty_status: CoverageStatus;
|
||||
warranty_end_date: string | null;
|
||||
contract_status: CoverageStatus;
|
||||
contract_type: string | null;
|
||||
contract_end_date: string | null;
|
||||
contract_summary: string;
|
||||
insurance_status: CoverageStatus;
|
||||
insurance_end_date: string | null;
|
||||
insurance_summary: string;
|
||||
coverage_tag?: CoverageTag | string;
|
||||
coverage?: CoverageInfo | null;
|
||||
}
|
||||
|
||||
export interface WarrantySummary {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
duration_months: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
provider_id: number | null;
|
||||
provider_name: string | null;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
remarks: string | null;
|
||||
}
|
||||
|
||||
export interface ContractSummary {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
contract_type: string;
|
||||
provider_id: number;
|
||||
provider_name: string | null;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
contract_value?: number | null;
|
||||
coverage_period_text: string | null;
|
||||
renewed_from_id: number | null;
|
||||
is_superseded: boolean;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
remarks: string | null;
|
||||
}
|
||||
|
||||
export interface InsuranceSummary {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
insurer_id: number;
|
||||
insurer_name: string | null;
|
||||
policy_no: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_amount: number | null;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
remarks: string | null;
|
||||
}
|
||||
|
||||
export interface CalibrationPlanSummary {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
frequency_months: number;
|
||||
calibrations_per_year: number;
|
||||
agency_id: number | null;
|
||||
agency_name: string | null;
|
||||
approved_by_id: number | null;
|
||||
approved_on: string | null;
|
||||
next_due_date: string;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export interface CalibrationRecordSummary {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
plan_id: number;
|
||||
due_date: string;
|
||||
completed_date: string | null;
|
||||
agency_id: number | null;
|
||||
agency_name: string | null;
|
||||
certificate_no: string | null;
|
||||
remarks: string | null;
|
||||
status: CalibrationStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
}
|
||||
|
||||
export interface PMScheduleSummary {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
service_mode: string;
|
||||
frequency_months: number;
|
||||
responsible_team: string | null;
|
||||
provider_id: number | null;
|
||||
provider_name: string | null;
|
||||
contract_id: number | null;
|
||||
cost_per_visit?: number | null;
|
||||
next_planned_date: string;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export interface PMRecordSummary {
|
||||
id: number;
|
||||
schedule_id: number;
|
||||
asset_id: number;
|
||||
planned_date: string;
|
||||
completed_date: string | null;
|
||||
status: string;
|
||||
severity: string;
|
||||
service_details: string | null;
|
||||
remarks: string | null;
|
||||
rescheduled_to: string | null;
|
||||
}
|
||||
|
||||
export interface ComplaintSummary {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
asset_id: number;
|
||||
description: string;
|
||||
priority: string;
|
||||
call_status: string;
|
||||
registered_at: string;
|
||||
closed_at: string | null;
|
||||
}
|
||||
|
||||
export interface AssetOverview {
|
||||
asset: AssetItem;
|
||||
coverage?: CoverageInfo;
|
||||
warranties: WarrantySummary[];
|
||||
contracts: ContractSummary[];
|
||||
insurance_policies: InsuranceSummary[];
|
||||
calibration_plan: CalibrationPlanSummary | null;
|
||||
calibration_records: CalibrationRecordSummary[];
|
||||
pm_schedules: PMScheduleSummary[];
|
||||
pm_records: PMRecordSummary[];
|
||||
complaints: ComplaintSummary[];
|
||||
attachments: AttachmentItem[];
|
||||
}
|
||||
|
||||
export interface AssetListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
category_id?: number;
|
||||
location_id?: number;
|
||||
supplier_id?: number;
|
||||
status?: AssetStatus | "";
|
||||
criticality?: AssetCriticality | "";
|
||||
requires_calibration?: boolean;
|
||||
insurance_applicable?: boolean;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
sort?: string;
|
||||
}
|
||||
|
||||
export interface AssetCreatePayload {
|
||||
asset_code: string;
|
||||
serial_no: string;
|
||||
name: string;
|
||||
category_id: number;
|
||||
department_id: number;
|
||||
location_id: number;
|
||||
supplier_id?: number | null;
|
||||
purchase_value?: number | null;
|
||||
acquisition_mode?: AcquisitionMode;
|
||||
monthly_rent?: number | null;
|
||||
useful_life_years?: number | null;
|
||||
salvage_pct?: number | null;
|
||||
depreciation_method?: DepreciationMethod | null;
|
||||
purchase_date?: string | null;
|
||||
installation_date?: string | null;
|
||||
status: AssetStatus;
|
||||
criticality: AssetCriticality;
|
||||
requires_calibration: boolean;
|
||||
insurance_applicable: boolean;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export type AssetUpdatePayload = Partial<AssetCreatePayload>;
|
||||
|
||||
export interface BulkImportErrorItem {
|
||||
row: number;
|
||||
asset_code: string | null;
|
||||
error: string;
|
||||
}
|
||||
|
||||
export interface BulkImportPreviewRow {
|
||||
row: number;
|
||||
asset_code: string | null;
|
||||
serial_no: string | null;
|
||||
name: string | null;
|
||||
category_name: string | null;
|
||||
department_name: string | null;
|
||||
location_name: string | null;
|
||||
status: string | null;
|
||||
valid: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface BulkImportResult {
|
||||
dry_run: boolean;
|
||||
total_rows: number;
|
||||
valid_count: number;
|
||||
error_count: number;
|
||||
created_count: number;
|
||||
errors: BulkImportErrorItem[];
|
||||
preview_rows: BulkImportPreviewRow[];
|
||||
}
|
||||
|
||||
export const assetsApi = {
|
||||
list: (params: AssetListParams = {}) => {
|
||||
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.category_id) qs.set("category_id", String(params.category_id));
|
||||
if (params.location_id) qs.set("location_id", String(params.location_id));
|
||||
if (params.supplier_id) qs.set("supplier_id", String(params.supplier_id));
|
||||
if (params.status) qs.set("status", params.status);
|
||||
if (params.criticality) qs.set("criticality", params.criticality);
|
||||
if (params.requires_calibration !== undefined) qs.set("requires_calibration", String(params.requires_calibration));
|
||||
if (params.insurance_applicable !== undefined) qs.set("insurance_applicable", String(params.insurance_applicable));
|
||||
qs.set("page", String(params.page ?? 1));
|
||||
qs.set("page_size", String(params.page_size ?? 200));
|
||||
if (params.sort) qs.set("sort", params.sort);
|
||||
return api.get<{ items: AssetItem[]; total: number }>(`/assets?${qs.toString()}`);
|
||||
},
|
||||
lookup: (params: { q?: string; department_id?: number; limit?: number } = {}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q !== undefined) qs.set("q", params.q);
|
||||
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||
qs.set("limit", String(params.limit ?? 25));
|
||||
return api.get<{ items: AssetLookupItem[] }>(`/assets/lookup?${qs.toString()}`);
|
||||
},
|
||||
get: (id: number) => api.get<AssetItem>(`/assets/${id}`),
|
||||
coverage: (id: number, onDate?: string) =>
|
||||
api.get<CoverageInfo>(`/assets/${id}/coverage${onDate ? `?on_date=${onDate}` : ""}`),
|
||||
overview: (id: number) => api.get<AssetOverview>(`/assets/${id}/overview`),
|
||||
create: (data: AssetCreatePayload) => api.post<AssetItem>("/assets", data),
|
||||
update: (id: number, data: AssetUpdatePayload) => api.patch<AssetItem>(`/assets/${id}`, data),
|
||||
downloadImportTemplate: async () => {
|
||||
const { blob } = await api.downloadBlob("/assets/import-template");
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "asset_import_template.xlsx";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return api.upload<BulkImportResult>(
|
||||
`/assets/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export type AttachmentEntityType =
|
||||
| "complaint"
|
||||
| "contract"
|
||||
| "calibration_record"
|
||||
| "insurance"
|
||||
| "demo_equipment"
|
||||
| "asset"
|
||||
| "warranty"
|
||||
| "pm_record";
|
||||
|
||||
export interface AttachmentItem {
|
||||
id: number;
|
||||
entity_type: AttachmentEntityType | string;
|
||||
entity_id: number;
|
||||
original_name: string;
|
||||
mime_type: string;
|
||||
size_bytes: number;
|
||||
uploaded_by_id?: number | null;
|
||||
uploaded_by_name?: string | null;
|
||||
uploaded_at: string;
|
||||
}
|
||||
|
||||
export const attachmentsApi = {
|
||||
list: (entityType: AttachmentEntityType, entityId: number) => {
|
||||
const qs = new URLSearchParams({
|
||||
entity_type: entityType,
|
||||
entity_id: String(entityId),
|
||||
});
|
||||
return api.get<{ items: AttachmentItem[]; total: number }>(`/attachments?${qs.toString()}`);
|
||||
},
|
||||
upload: (entityType: AttachmentEntityType, entityId: number, file: File) => {
|
||||
const formData = new FormData();
|
||||
formData.append("entity_type", entityType);
|
||||
formData.append("entity_id", String(entityId));
|
||||
formData.append("file", file);
|
||||
return api.upload<AttachmentItem>("/attachments", formData);
|
||||
},
|
||||
download: async (id: number, originalName: string, preview = false) => {
|
||||
const { blob } = await api.downloadBlob(`/attachments/${id}/download`);
|
||||
const url = URL.createObjectURL(blob);
|
||||
if (preview) {
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30_000);
|
||||
} else {
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = originalName;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
},
|
||||
remove: (id: number) => api.delete<void>(`/attachments/${id}`),
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export interface AuditLogItem {
|
||||
id: number;
|
||||
entity_type: string;
|
||||
entity_id: number;
|
||||
action: string;
|
||||
changes_json: string | null;
|
||||
by_user_id: number | null;
|
||||
by_user_name: string | null;
|
||||
at: string;
|
||||
}
|
||||
|
||||
export interface AuditLogsResponse {
|
||||
items: AuditLogItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface AuditLogFilters {
|
||||
entity_type?: string;
|
||||
by_user_id?: number;
|
||||
action?: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
q?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export const auditApi = {
|
||||
list: (filters: AuditLogFilters = {}) => {
|
||||
const params = new URLSearchParams();
|
||||
if (filters.entity_type) params.set("entity_type", filters.entity_type);
|
||||
if (filters.by_user_id != null) {
|
||||
params.set("by_user_id", String(filters.by_user_id));
|
||||
}
|
||||
if (filters.action) params.set("action", filters.action);
|
||||
if (filters.date_from) params.set("date_from", filters.date_from);
|
||||
if (filters.date_to) params.set("date_to", filters.date_to);
|
||||
if (filters.q) params.set("q", filters.q);
|
||||
if (filters.page != null) params.set("page", String(filters.page));
|
||||
params.set("page_size", String(filters.page_size ?? 200));
|
||||
return api.get<AuditLogsResponse>(`/audit-logs?${params.toString()}`);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import { api } from "./client";
|
||||
import type { Role } from "@/lib/permissions";
|
||||
|
||||
export interface UserOut {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
department_id: number | null;
|
||||
department_name: string | null;
|
||||
is_active: boolean;
|
||||
demo_as_of_date?: string | null;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
user: UserOut;
|
||||
}
|
||||
|
||||
export function loginApi(email: string, password: string) {
|
||||
return api.post<LoginResponse>("/auth/login", { email, password });
|
||||
}
|
||||
|
||||
export function fetchMeApi() {
|
||||
return api.get<UserOut>("/auth/me");
|
||||
}
|
||||
|
||||
export interface ChangePasswordResponse {
|
||||
message: string;
|
||||
access_token?: string;
|
||||
token_type?: string;
|
||||
}
|
||||
|
||||
export function changePasswordApi(current_password: string, new_password: string) {
|
||||
return api.post<ChangePasswordResponse>("/auth/change-password", {
|
||||
current_password,
|
||||
new_password,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { api } from "./client";
|
||||
import type { BulkImportResult } from "./assets";
|
||||
|
||||
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),
|
||||
downloadImportTemplate: async () => {
|
||||
const { blob } = await api.downloadBlob("/calibration/import-template");
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "calibration_import_template.xlsx";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return api.upload<BulkImportResult>(
|
||||
`/calibration/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
const BASE_URL = "/api";
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public detail: string,
|
||||
public code?: string
|
||||
) {
|
||||
super(detail);
|
||||
}
|
||||
}
|
||||
|
||||
let onUnauthorizedCallback: (() => void) | null = null;
|
||||
|
||||
export function setUnauthorizedHandler(cb: () => void) {
|
||||
onUnauthorizedCallback = cb;
|
||||
}
|
||||
|
||||
function handleUnauthorized(path: string) {
|
||||
sessionStorage.removeItem("access_token");
|
||||
if (!path.startsWith("/auth/login")) {
|
||||
onUnauthorizedCallback?.();
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const token = sessionStorage.getItem("access_token");
|
||||
const isFormData = typeof FormData !== "undefined" && options.body instanceof FormData;
|
||||
const headers: Record<string, string> = {
|
||||
...(isFormData ? {} : { "Content-Type": "application/json" }),
|
||||
...(options.headers as Record<string, string>),
|
||||
};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
|
||||
const res = await fetch(`${BASE_URL}${path}`, { ...options, headers });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
if (res.status === 401) handleUnauthorized(path);
|
||||
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async function downloadBlob(path: string): Promise<{ blob: Blob; contentType: string }> {
|
||||
const token = sessionStorage.getItem("access_token");
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
|
||||
const res = await fetch(`${BASE_URL}${path}`, { headers });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
if (res.status === 401) handleUnauthorized(path);
|
||||
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
|
||||
}
|
||||
const blob = await res.blob();
|
||||
const contentType = res.headers.get("Content-Type") || blob.type || "application/octet-stream";
|
||||
return { blob, contentType };
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string) => request<T>(path),
|
||||
post: <T>(path: string, data?: unknown) =>
|
||||
request<T>(path, { method: "POST", body: data !== undefined ? JSON.stringify(data) : undefined }),
|
||||
patch: <T>(path: string, data: unknown) =>
|
||||
request<T>(path, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
put: <T>(path: string, data: unknown) =>
|
||||
request<T>(path, { method: "PUT", body: JSON.stringify(data) }),
|
||||
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
|
||||
upload: <T>(path: string, formData: FormData) =>
|
||||
request<T>(path, { method: "POST", body: formData }),
|
||||
downloadBlob,
|
||||
};
|
||||
@@ -0,0 +1,167 @@
|
||||
import { api } from "./client";
|
||||
import type { AssetCriticality, AssetStatus, CoverageInfo, CoverageTag } from "./assets";
|
||||
|
||||
export type CallStatus = "open" | "in_progress" | "closed";
|
||||
|
||||
export type TimestampField =
|
||||
| "registered_at"
|
||||
| "received_at"
|
||||
| "attended_at"
|
||||
| "restored_at"
|
||||
| "closed_at"
|
||||
| "ce_attended_at";
|
||||
|
||||
export interface ComplaintItem {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
asset_status: AssetStatus | string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_name: string | null;
|
||||
description: string;
|
||||
breakdown_details: string | null;
|
||||
priority: AssetCriticality | string;
|
||||
notes: string | null;
|
||||
registered_at: string;
|
||||
registered_by_id: number;
|
||||
registered_by_name: string | null;
|
||||
received_by_id: number | null;
|
||||
received_by_name: string | null;
|
||||
received_at: string | null;
|
||||
assigned_to_id: number | null;
|
||||
assigned_to_name: string | null;
|
||||
assigned_team?: string | null;
|
||||
assigned_at: string | null;
|
||||
attended_by_id: number | null;
|
||||
attended_by_name: string | null;
|
||||
attended_at: string | null;
|
||||
restored_at: string | null;
|
||||
closed_by_id: number | null;
|
||||
closed_by_name: string | null;
|
||||
closed_at: string | null;
|
||||
call_status: CallStatus;
|
||||
closure_remarks: string | null;
|
||||
action_taken: string | null;
|
||||
root_cause: string | null;
|
||||
corrective_action: string | null;
|
||||
lessons_learned: string | null;
|
||||
ce_name: string | null;
|
||||
ce_attended_at: string | null;
|
||||
ce_action_taken: string | null;
|
||||
spare_required: boolean;
|
||||
spare_details: string | null;
|
||||
spare_cost_estimate?: number | null;
|
||||
repair_cost?: number | null;
|
||||
coverage_tag?: CoverageTag | string | null;
|
||||
coverage_contract_id?: number | null;
|
||||
coverage_provider_id?: number | null;
|
||||
coverage_at_registration?: CoverageInfo | null;
|
||||
coverage_now?: CoverageInfo | null;
|
||||
response_time_minutes: number | null;
|
||||
downtime_minutes: number;
|
||||
downtime_is_ongoing: boolean;
|
||||
downtime_end_milestone: string;
|
||||
response_start_setting: string;
|
||||
ce_response_time_minutes: number | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ComplaintEventItem {
|
||||
id: number;
|
||||
complaint_id: number;
|
||||
event_type: string;
|
||||
from_value: string | null;
|
||||
to_value: string | null;
|
||||
by_user_id: number | null;
|
||||
by_user_name: string | null;
|
||||
at: string;
|
||||
note: string | null;
|
||||
}
|
||||
|
||||
export interface ComplaintListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
location_id?: number;
|
||||
asset_id?: number;
|
||||
call_status?: CallStatus | "";
|
||||
priority?: AssetCriticality | "";
|
||||
coverage_tag?: CoverageTag | "";
|
||||
assigned_to_id?: number;
|
||||
closure_state?: "open_only" | "closed_only" | "";
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface ComplaintCreatePayload {
|
||||
asset_id: number;
|
||||
description: string;
|
||||
breakdown_details?: string | null;
|
||||
priority: AssetCriticality;
|
||||
notes?: string | null;
|
||||
assigned_team?: string | null;
|
||||
received_by_id?: number | null;
|
||||
}
|
||||
|
||||
export interface ComplaintUpdatePayload {
|
||||
description?: string;
|
||||
breakdown_details?: string | null;
|
||||
priority?: AssetCriticality;
|
||||
notes?: string | null;
|
||||
assigned_team?: string | null;
|
||||
action_taken?: string | null;
|
||||
root_cause?: string | null;
|
||||
corrective_action?: string | null;
|
||||
lessons_learned?: string | null;
|
||||
ce_name?: string | null;
|
||||
ce_attended_at?: string | null;
|
||||
ce_action_taken?: string | null;
|
||||
spare_required?: boolean;
|
||||
spare_details?: string | null;
|
||||
spare_cost_estimate?: number | null;
|
||||
repair_cost?: number | null;
|
||||
}
|
||||
|
||||
export const complaintsApi = {
|
||||
list: (params: ComplaintListParams = {}) => {
|
||||
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.location_id) qs.set("location_id", String(params.location_id));
|
||||
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
||||
if (params.call_status) qs.set("call_status", params.call_status);
|
||||
if (params.priority) qs.set("priority", params.priority);
|
||||
if (params.coverage_tag) qs.set("coverage_tag", params.coverage_tag);
|
||||
if (params.assigned_to_id) qs.set("assigned_to_id", String(params.assigned_to_id));
|
||||
if (params.closure_state) qs.set("closure_state", params.closure_state);
|
||||
if (params.date_from) qs.set("date_from", params.date_from);
|
||||
if (params.date_to) qs.set("date_to", params.date_to);
|
||||
qs.set("page", String(params.page ?? 1));
|
||||
qs.set("page_size", String(params.page_size ?? 200));
|
||||
return api.get<{ items: ComplaintItem[]; total: number }>(`/complaints?${qs.toString()}`);
|
||||
},
|
||||
create: (data: ComplaintCreatePayload) => api.post<ComplaintItem>("/complaints", data),
|
||||
get: (id: number) => api.get<ComplaintItem>(`/complaints/${id}`),
|
||||
events: (id: number) =>
|
||||
api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`),
|
||||
update: (id: number, data: ComplaintUpdatePayload) =>
|
||||
api.patch<ComplaintItem>(`/complaints/${id}`, data),
|
||||
assign: (id: number, data: { assigned_to_id?: number | null; assigned_team?: string | null; note?: string }) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/assign`, data),
|
||||
attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/attend`, data),
|
||||
restore: (id: number, data: { note?: string } = {}) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/restore`, data),
|
||||
close: (id: number, data: { closure_remarks?: string } = {}) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/close`, data),
|
||||
reopen: (id: number, data: { reason: string }) =>
|
||||
api.post<ComplaintItem>(`/complaints/${id}/reopen`, data),
|
||||
correctTimestamp: (
|
||||
id: number,
|
||||
data: { field: TimestampField; new_value: string; reason: string }
|
||||
) => api.post<ComplaintItem>(`/complaints/${id}/correct-timestamp`, data),
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export interface DashboardKPIs {
|
||||
total_assets: number;
|
||||
assets_under_repair: number;
|
||||
open_complaints: number;
|
||||
pm_due_this_month: number;
|
||||
calibrations_due: number;
|
||||
contracts_expiring: number;
|
||||
equipment_on_demo: number;
|
||||
}
|
||||
|
||||
export interface StatusCountItem {
|
||||
status: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface DeptComplaintCountItem {
|
||||
department: string;
|
||||
critical: number;
|
||||
non_critical: number;
|
||||
}
|
||||
|
||||
export interface MonthlyDowntimePoint {
|
||||
month: string;
|
||||
label: string;
|
||||
downtime_minutes: number;
|
||||
downtime_hours: number;
|
||||
}
|
||||
|
||||
export interface MonthlyPMPoint {
|
||||
month: string;
|
||||
label: string;
|
||||
planned: number;
|
||||
completed: number;
|
||||
}
|
||||
|
||||
export interface NeedsAttentionItem {
|
||||
id: number;
|
||||
type: string;
|
||||
severity: string;
|
||||
title: string;
|
||||
message: string;
|
||||
entity_type: string | null;
|
||||
entity_id: number | null;
|
||||
due_date: string | null;
|
||||
link_url: string;
|
||||
}
|
||||
|
||||
export interface RecentComplaintItem {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_name: string | null;
|
||||
priority: string;
|
||||
call_status: string;
|
||||
registered_at: string;
|
||||
downtime_minutes: number;
|
||||
downtime_is_ongoing: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardSummary {
|
||||
department_scope: string | null;
|
||||
effective_today: string;
|
||||
kpis: DashboardKPIs;
|
||||
complaints_by_status: StatusCountItem[];
|
||||
complaints_by_department: DeptComplaintCountItem[];
|
||||
monthly_downtime_trend: MonthlyDowntimePoint[];
|
||||
pm_planned_vs_completed: MonthlyPMPoint[];
|
||||
needs_attention: NeedsAttentionItem[];
|
||||
recent_complaints: RecentComplaintItem[];
|
||||
}
|
||||
|
||||
export const dashboardApi = {
|
||||
summary: () => api.get<DashboardSummary>("/dashboard/summary"),
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export const fetchHealth = () =>
|
||||
api.get<{ status: string; service: string; version: string }>("/health");
|
||||
@@ -0,0 +1,183 @@
|
||||
import { api } from "./client";
|
||||
import type { Role } from "@/lib/permissions";
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface Department {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
description: string | null;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export interface LocationItem {
|
||||
id: number;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
name: string;
|
||||
floor_wing: string | null;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export interface Category {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string | null;
|
||||
default_useful_life_years?: number | null;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export type VendorType =
|
||||
| "supplier"
|
||||
| "service_provider"
|
||||
| "calibration_agency"
|
||||
| "insurer"
|
||||
| "oem";
|
||||
|
||||
export const VENDOR_TYPE_LABELS: Record<VendorType, string> = {
|
||||
supplier: "Supplier",
|
||||
service_provider: "Service Provider",
|
||||
calibration_agency: "Calibration Agency",
|
||||
insurer: "Insurer",
|
||||
oem: "OEM",
|
||||
};
|
||||
|
||||
export interface Vendor {
|
||||
id: number;
|
||||
name: string;
|
||||
vendor_type: VendorType;
|
||||
contact_person: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
address: string | null;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
export interface MasterUser {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
department_id: number | null;
|
||||
department_name: string | null;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
function buildListQuery(includeInactive: boolean) {
|
||||
const params = new URLSearchParams();
|
||||
params.set("page_size", "500");
|
||||
if (includeInactive) params.set("include_inactive", "true");
|
||||
return `?${params.toString()}`;
|
||||
}
|
||||
|
||||
export const departmentsApi = {
|
||||
list: (includeInactive = false) =>
|
||||
api.get<PaginatedResponse<Department>>(`/departments${buildListQuery(includeInactive)}`),
|
||||
create: (data: { name: string; code: string; description?: string | null }) =>
|
||||
api.post<Department>("/departments", data),
|
||||
update: (id: number, data: Partial<{ name: string; code: string; description: string | null; is_active: boolean }>) =>
|
||||
api.patch<Department>(`/departments/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/departments/${id}`),
|
||||
};
|
||||
|
||||
export const locationsApi = {
|
||||
list: (includeInactive = false) =>
|
||||
api.get<PaginatedResponse<LocationItem>>(`/locations${buildListQuery(includeInactive)}`),
|
||||
create: (data: { department_id: number; name: string; floor_wing?: string | null }) =>
|
||||
api.post<LocationItem>("/locations", data),
|
||||
update: (
|
||||
id: number,
|
||||
data: Partial<{ department_id: number; name: string; floor_wing: string | null; is_active: boolean }>
|
||||
) => api.patch<LocationItem>(`/locations/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/locations/${id}`),
|
||||
};
|
||||
|
||||
export const categoriesApi = {
|
||||
list: (includeInactive = false) =>
|
||||
api.get<PaginatedResponse<Category>>(`/categories${buildListQuery(includeInactive)}`),
|
||||
create: (data: { name: string; description?: string | null; default_useful_life_years?: number | null }) =>
|
||||
api.post<Category>("/categories", data),
|
||||
update: (
|
||||
id: number,
|
||||
data: Partial<{
|
||||
name: string;
|
||||
description: string | null;
|
||||
default_useful_life_years: number | null;
|
||||
is_active: boolean;
|
||||
}>
|
||||
) => api.patch<Category>(`/categories/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/categories/${id}`),
|
||||
};
|
||||
|
||||
export const vendorsApi = {
|
||||
list: (includeInactive = false) =>
|
||||
api.get<PaginatedResponse<Vendor>>(`/vendors${buildListQuery(includeInactive)}`),
|
||||
create: (data: {
|
||||
name: string;
|
||||
vendor_type: VendorType;
|
||||
contact_person?: string | null;
|
||||
phone?: string | null;
|
||||
email?: string | null;
|
||||
address?: string | null;
|
||||
}) => api.post<Vendor>("/vendors", data),
|
||||
update: (
|
||||
id: number,
|
||||
data: Partial<{
|
||||
name: string;
|
||||
vendor_type: VendorType;
|
||||
contact_person: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
address: string | null;
|
||||
is_active: boolean;
|
||||
}>
|
||||
) => api.patch<Vendor>(`/vendors/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/vendors/${id}`),
|
||||
};
|
||||
|
||||
export const usersApi = {
|
||||
list: (includeInactive = false) =>
|
||||
api.get<PaginatedResponse<MasterUser>>(`/users${buildListQuery(includeInactive)}`),
|
||||
create: (data: {
|
||||
name: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
department_id?: number | null;
|
||||
password: string;
|
||||
}) => api.post<MasterUser>("/users", data),
|
||||
update: (
|
||||
id: number,
|
||||
data: Partial<{
|
||||
name: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
department_id: number | null;
|
||||
password: string;
|
||||
is_active: boolean;
|
||||
}>
|
||||
) => api.patch<MasterUser>(`/users/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/users/${id}`),
|
||||
resetPassword: (id: number, new_password: string) =>
|
||||
api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }),
|
||||
};
|
||||
|
||||
export interface UserLookupItem {
|
||||
id: number;
|
||||
name: string;
|
||||
role: Role;
|
||||
department_id: number | null;
|
||||
}
|
||||
|
||||
export async function fetchUsersLookup(): Promise<{ items: UserLookupItem[]; total: number }> {
|
||||
const res = await api.get<UserLookupItem[] | { items: UserLookupItem[]; total: number }>(
|
||||
"/users/lookup"
|
||||
);
|
||||
if (Array.isArray(res)) {
|
||||
return { items: res, total: res.length };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export type NotificationSeverity = "info" | "yellow" | "red";
|
||||
|
||||
export type NotificationType =
|
||||
| "amc_expiry"
|
||||
| "calibration_due"
|
||||
| "pm_due"
|
||||
| "insurance_expiry"
|
||||
| "warranty_expiry"
|
||||
| "demo_overdue"
|
||||
| "critical_complaint"
|
||||
| "sla_breach";
|
||||
|
||||
export interface NotificationItem {
|
||||
id: number;
|
||||
type: NotificationType | string;
|
||||
severity: NotificationSeverity | string;
|
||||
title: string;
|
||||
message: string;
|
||||
entity_type: string | null;
|
||||
entity_id: number | null;
|
||||
due_date: string | null;
|
||||
created_at: string;
|
||||
is_read: boolean;
|
||||
read_at: string | null;
|
||||
link_url: string;
|
||||
}
|
||||
|
||||
export interface NotificationListResponse {
|
||||
items: NotificationItem[];
|
||||
total: number;
|
||||
unread_count: number;
|
||||
unread_calibration_count: number;
|
||||
}
|
||||
|
||||
export interface NotificationListParams {
|
||||
type?: string;
|
||||
severity?: string;
|
||||
unread_only?: boolean;
|
||||
limit?: number;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export const notificationsApi = {
|
||||
list: (params: NotificationListParams = {}) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params.type) sp.set("type", params.type);
|
||||
if (params.severity) sp.set("severity", params.severity);
|
||||
if (params.unread_only) sp.set("unread_only", "true");
|
||||
if (params.limit != null) sp.set("limit", String(params.limit));
|
||||
if (params.page != null) sp.set("page", String(params.page));
|
||||
if (params.page_size != null) sp.set("page_size", String(params.page_size));
|
||||
const qs = sp.toString();
|
||||
return api.get<NotificationListResponse>(`/notifications${qs ? `?${qs}` : ""}`);
|
||||
},
|
||||
markRead: (id: number) =>
|
||||
api.post<{ status: string; id: number }>(`/notifications/${id}/read`),
|
||||
markAllRead: (type?: string) => {
|
||||
const qs = type ? `?type=${encodeURIComponent(type)}` : "";
|
||||
return api.post<{ status: string; marked_count?: number }>(
|
||||
`/notifications/read-all${qs}`
|
||||
);
|
||||
},
|
||||
runAlertsNow: () =>
|
||||
api.post<{ created: number; evaluated_today: string }>("/alerts/run"),
|
||||
};
|
||||
@@ -0,0 +1,354 @@
|
||||
import { api } from "./client";
|
||||
import type { AlertSeverity, BulkImportResult, CoverageStatus } from "./assets";
|
||||
|
||||
export type ContractStatus = CoverageStatus | "superseded";
|
||||
export type DemoStatus = "on_demo" | "overdue_return" | "returned";
|
||||
|
||||
export interface ContractItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
contract_type: string;
|
||||
provider_id: number;
|
||||
provider_name: string | null;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
contract_value?: number | null;
|
||||
coverage_period_text: string | null;
|
||||
renewed_from_id: number | null;
|
||||
is_superseded: boolean;
|
||||
status: ContractStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ContractListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
provider_id?: number;
|
||||
contract_type?: string;
|
||||
status?: string;
|
||||
include_superseded?: boolean;
|
||||
expiry_from?: string;
|
||||
expiry_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface ContractCreatePayload {
|
||||
asset_id: number;
|
||||
contract_type: string;
|
||||
provider_id: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
contract_value?: number | null;
|
||||
coverage_period_text?: string | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractRenewPayload {
|
||||
contract_type?: string;
|
||||
provider_id?: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
contract_value?: number | null;
|
||||
coverage_period_text?: string | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface WarrantyItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
duration_months: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
provider_id: number | null;
|
||||
provider_name: string | null;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface WarrantyListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
status?: string;
|
||||
expiry_from?: string;
|
||||
expiry_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface WarrantyCreatePayload {
|
||||
asset_id: number;
|
||||
duration_months: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
provider_id?: number | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface InsuranceItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
insurer_id: number;
|
||||
insurer_name: string | null;
|
||||
policy_no: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_amount: number | null;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface InsuranceListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
insurer_id?: number;
|
||||
status?: string;
|
||||
expiry_from?: string;
|
||||
expiry_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface InsuranceCreatePayload {
|
||||
asset_id: number;
|
||||
insurer_id: number;
|
||||
policy_no: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_amount?: number | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface DemoEquipmentItem {
|
||||
id: number;
|
||||
name: string;
|
||||
equipment_type: string;
|
||||
serial_no?: string | null;
|
||||
supplier_id: number;
|
||||
supplier_name: string | null;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_id: number | null;
|
||||
location_name: string | null;
|
||||
start_date: string;
|
||||
expected_return_date: string;
|
||||
actual_return_date: string | null;
|
||||
status: DemoStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_remaining: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface DemoListParams {
|
||||
q?: string;
|
||||
supplier_id?: number;
|
||||
department_id?: number;
|
||||
status?: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface DemoCreatePayload {
|
||||
name: string;
|
||||
equipment_type: string;
|
||||
serial_no?: string | null;
|
||||
supplier_id: number;
|
||||
department_id: number;
|
||||
location_id?: number | null;
|
||||
start_date: string;
|
||||
expected_return_date: string;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface VisitAssetBrief {
|
||||
id: number;
|
||||
asset_code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface VisitComplaintBrief {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
call_status: string;
|
||||
priority: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface VisitItem {
|
||||
id: number;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
visited_by_id: number;
|
||||
visited_by_name: string | null;
|
||||
visit_date: string;
|
||||
observations: string;
|
||||
new_requirements?: string | null;
|
||||
assets: VisitAssetBrief[];
|
||||
complaints: VisitComplaintBrief[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface VisitListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
visited_by_id?: number;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface VisitCreatePayload {
|
||||
department_id: number;
|
||||
visit_date: string;
|
||||
observations: string;
|
||||
new_requirements?: string | null;
|
||||
asset_ids?: number[];
|
||||
complaint_ids?: number[];
|
||||
}
|
||||
|
||||
function toQS(params: Record<string, string | number | boolean | undefined>): string {
|
||||
const sp = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v === undefined || v === "") continue;
|
||||
sp.set(k, String(v));
|
||||
}
|
||||
const s = sp.toString();
|
||||
return s ? `?${s}` : "";
|
||||
}
|
||||
|
||||
export const contractsApi = {
|
||||
list: (params: ContractListParams = {}) =>
|
||||
api.get<{ items: ContractItem[]; total: number }>(
|
||||
`/contracts${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: ContractCreatePayload) => api.post<ContractItem>("/contracts", data),
|
||||
update: (id: number, data: Partial<ContractCreatePayload>) =>
|
||||
api.patch<ContractItem>(`/contracts/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/contracts/${id}`),
|
||||
renew: (id: number, data: ContractRenewPayload) =>
|
||||
api.post<{ old_contract: ContractItem; new_contract: ContractItem }>(
|
||||
`/contracts/${id}/renew`,
|
||||
data
|
||||
),
|
||||
history: (assetId: number) =>
|
||||
api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`),
|
||||
downloadImportTemplate: async () => {
|
||||
const { blob } = await api.downloadBlob("/contracts/import-template");
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "contracts_import_template.xlsx";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return api.upload<BulkImportResult>(
|
||||
`/contracts/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export const warrantiesApi = {
|
||||
list: (params: WarrantyListParams = {}) =>
|
||||
api.get<{ items: WarrantyItem[]; total: number }>(
|
||||
`/warranties${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: WarrantyCreatePayload) => api.post<WarrantyItem>("/warranties", data),
|
||||
update: (id: number, data: Partial<WarrantyCreatePayload>) =>
|
||||
api.patch<WarrantyItem>(`/warranties/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/warranties/${id}`),
|
||||
};
|
||||
|
||||
export const insuranceApi = {
|
||||
list: (params: InsuranceListParams = {}) =>
|
||||
api.get<{ items: InsuranceItem[]; total: number }>(
|
||||
`/insurance${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: InsuranceCreatePayload) => api.post<InsuranceItem>("/insurance", data),
|
||||
update: (id: number, data: Partial<InsuranceCreatePayload>) =>
|
||||
api.patch<InsuranceItem>(`/insurance/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/insurance/${id}`),
|
||||
downloadImportTemplate: async () => {
|
||||
const { blob } = await api.downloadBlob("/insurance/import-template");
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "insurance_import_template.xlsx";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return api.upload<BulkImportResult>(
|
||||
`/insurance/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||
formData
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export const demoEquipmentApi = {
|
||||
list: (params: DemoListParams = {}) =>
|
||||
api.get<{ items: DemoEquipmentItem[]; total: number }>(
|
||||
`/demo-equipment${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: DemoCreatePayload) =>
|
||||
api.post<DemoEquipmentItem>("/demo-equipment", data),
|
||||
update: (id: number, data: Partial<DemoCreatePayload>) =>
|
||||
api.patch<DemoEquipmentItem>(`/demo-equipment/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/demo-equipment/${id}`),
|
||||
markReturned: (id: number, data: { actual_return_date: string; remarks?: string | null }) =>
|
||||
api.post<DemoEquipmentItem>(`/demo-equipment/${id}/return`, data),
|
||||
};
|
||||
|
||||
export const visitsApi = {
|
||||
list: (params: VisitListParams = {}) =>
|
||||
api.get<{ items: VisitItem[]; total: number }>(
|
||||
`/visits${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
get: (id: number) => api.get<VisitItem>(`/visits/${id}`),
|
||||
create: (data: VisitCreatePayload) => api.post<VisitItem>("/visits", data),
|
||||
update: (id: number, data: Partial<VisitCreatePayload>) =>
|
||||
api.patch<VisitItem>(`/visits/${id}`, data),
|
||||
linkComplaint: (id: number, complaintId: number) =>
|
||||
api.post<VisitItem>(`/visits/${id}/link-complaint`, { complaint_id: complaintId }),
|
||||
};
|
||||
@@ -0,0 +1,145 @@
|
||||
import { api } from "./client";
|
||||
import type { CoverageInfo, CoverageTag } from "./assets";
|
||||
|
||||
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;
|
||||
cost_per_visit?: number | null;
|
||||
coverage_tag?: CoverageTag | string | null;
|
||||
coverage?: CoverageInfo | null;
|
||||
no_active_contract?: boolean | 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;
|
||||
coverage_tag?: CoverageTag | string | null;
|
||||
coverage?: CoverageInfo | null;
|
||||
}
|
||||
|
||||
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;
|
||||
cost_per_visit?: 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,143 @@
|
||||
import { api } from "./client";
|
||||
import type { Role } from "@/lib/permissions";
|
||||
|
||||
export type ReportKey =
|
||||
| "monthly-maintenance"
|
||||
| "monthly-department"
|
||||
| "daily-visit"
|
||||
| "breakdown-complaints"
|
||||
| "pm-compliance"
|
||||
| "calibration-due"
|
||||
| "contracts-warranty"
|
||||
| "demo-equipment";
|
||||
|
||||
export interface ReportColumn {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface FormulaInfo {
|
||||
scheduled_hours_per_day: number;
|
||||
downtime_end_milestone: string;
|
||||
days_in_month: number;
|
||||
uptime_formula: string;
|
||||
downtime_formula: string;
|
||||
}
|
||||
|
||||
export interface ReportChartPoint {
|
||||
department: string;
|
||||
downtime_hours: number;
|
||||
uptime_hours: number;
|
||||
}
|
||||
|
||||
export interface ReportPayload {
|
||||
report_key: ReportKey | string;
|
||||
title: string;
|
||||
filters_applied: Record<string, string | number | null>;
|
||||
formula_info?: FormulaInfo | null;
|
||||
summary: Record<string, string | number>;
|
||||
columns: ReportColumn[];
|
||||
rows: Record<string, unknown>[];
|
||||
chart_data?: ReportChartPoint[] | null;
|
||||
}
|
||||
|
||||
export interface ReportMeta {
|
||||
key: ReportKey;
|
||||
title: string;
|
||||
description: string;
|
||||
category: string;
|
||||
hiddenForRoles?: Role[];
|
||||
}
|
||||
|
||||
export const REPORT_CATALOG: ReportMeta[] = [
|
||||
{
|
||||
key: "monthly-maintenance",
|
||||
title: "Monthly Maintenance Summary",
|
||||
description:
|
||||
"Department-wise uptime vs downtime, clipped breakdown hours, distinct downtime days, and availability %.",
|
||||
category: "Maintenance & Uptime",
|
||||
},
|
||||
{
|
||||
key: "monthly-department",
|
||||
title: "Monthly Department Report",
|
||||
description:
|
||||
"Asset health counts, under-repair equipment, outstanding complaints, visit counts, and requirement notes per department.",
|
||||
category: "Department Operations",
|
||||
},
|
||||
{
|
||||
key: "daily-visit",
|
||||
title: "Daily Department Visit Report",
|
||||
description:
|
||||
"Daily biomedical round logs, equipment checked, observations, and linked breakdown complaints.",
|
||||
category: "Department Operations",
|
||||
hiddenForRoles: ["department_user", "coordinator"],
|
||||
},
|
||||
{
|
||||
key: "breakdown-complaints",
|
||||
title: "Breakdown / Complaint Report",
|
||||
description:
|
||||
"Full breakdown register with response time, total downtime, ongoing status, action taken, and closure remarks.",
|
||||
category: "Breakdowns",
|
||||
},
|
||||
{
|
||||
key: "pm-compliance",
|
||||
title: "PM Compliance Report",
|
||||
description:
|
||||
"Planned vs completed preventive maintenance schedules across in-house and outsourced teams with compliance %.",
|
||||
category: "Compliance & Schedules",
|
||||
},
|
||||
{
|
||||
key: "calibration-due",
|
||||
title: "Calibration Due Report",
|
||||
description:
|
||||
"Calibration status, due/completed dates, agencies, certificate numbers, and overdue tracking.",
|
||||
category: "Compliance & Schedules",
|
||||
},
|
||||
{
|
||||
key: "contracts-warranty",
|
||||
title: "AMC / CMC & Warranty Report",
|
||||
description:
|
||||
"Active, expiring, expired, and superseded AMC/CMC contracts and equipment warranties with days to expiry.",
|
||||
category: "Commercial & Coverage",
|
||||
},
|
||||
{
|
||||
key: "demo-equipment",
|
||||
title: "Demo Equipment Report",
|
||||
description:
|
||||
"Supplier trial equipment register highlighting expected return dates, returned units, and overdue days.",
|
||||
category: "Commercial & Coverage",
|
||||
},
|
||||
];
|
||||
|
||||
export type ReportFilterParams = Record<string, string | number | undefined>;
|
||||
|
||||
function buildQuery(params: ReportFilterParams): string {
|
||||
const sp = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v === undefined || v === "") continue;
|
||||
sp.set(k, String(v));
|
||||
}
|
||||
const qs = sp.toString();
|
||||
return qs ? `?${qs}` : "";
|
||||
}
|
||||
|
||||
export function fetchReport(key: ReportKey, params: ReportFilterParams = {}) {
|
||||
return api.get<ReportPayload>(`/reports/${key}${buildQuery(params)}`);
|
||||
}
|
||||
|
||||
export async function exportReport(
|
||||
key: ReportKey,
|
||||
format: "xlsx" | "csv",
|
||||
params: ReportFilterParams = {}
|
||||
) {
|
||||
const qs = buildQuery({ ...params, format });
|
||||
const { blob } = await api.downloadBlob(`/reports/${key}/export${qs}`);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${key}.${format}`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export interface SearchAssetItem {
|
||||
id: number;
|
||||
asset_code: string;
|
||||
name: string;
|
||||
serial_no: string | null;
|
||||
department_name: string | null;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface SearchComplaintItem {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
asset_code: string | null;
|
||||
asset_name: string | null;
|
||||
department_name: string | null;
|
||||
call_status: string;
|
||||
priority: string;
|
||||
}
|
||||
|
||||
export interface GlobalSearchResponse {
|
||||
assets: SearchAssetItem[];
|
||||
complaints: SearchComplaintItem[];
|
||||
}
|
||||
|
||||
export const searchApi = {
|
||||
query: (q: string) => {
|
||||
const params = new URLSearchParams({ q });
|
||||
return api.get<GlobalSearchResponse>(`/search?${params.toString()}`);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import { api } from "./client";
|
||||
|
||||
export type SettingType = "int" | "float" | "bool" | "enum" | "str" | "date_or_empty";
|
||||
|
||||
export interface SettingItem {
|
||||
key: string;
|
||||
value: unknown;
|
||||
type: SettingType;
|
||||
label: string;
|
||||
description: string;
|
||||
default: unknown;
|
||||
min?: number | null;
|
||||
max?: number | null;
|
||||
options?: string[] | null;
|
||||
}
|
||||
|
||||
export interface SettingsResponse {
|
||||
items: SettingItem[];
|
||||
}
|
||||
|
||||
export interface DemoDateResponse {
|
||||
demo_as_of_date: string | null;
|
||||
effective_today: string;
|
||||
}
|
||||
|
||||
export const settingsApi = {
|
||||
getAll: () => api.get<SettingsResponse>("/settings"),
|
||||
updateAll: (values: Record<string, unknown>) =>
|
||||
api.put<SettingsResponse>("/settings", { values }),
|
||||
setDemoDate: (demo_as_of_date: string | null) =>
|
||||
api.post<DemoDateResponse>("/settings/demo-date", { demo_as_of_date }),
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import { api } from "./client";
|
||||
import { usersApi } from "./masters";
|
||||
|
||||
export { usersApi };
|
||||
|
||||
export const resetPassword = (id: number, new_password: string) =>
|
||||
api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password });
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,541 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ApiError } from "@/api/client";
|
||||
import {
|
||||
assetsApi,
|
||||
type AssetItem,
|
||||
type AssetStatus,
|
||||
type AssetCriticality,
|
||||
type AcquisitionMode,
|
||||
type DepreciationMethod,
|
||||
} from "@/api/assets";
|
||||
import {
|
||||
departmentsApi,
|
||||
locationsApi,
|
||||
categoriesApi,
|
||||
vendorsApi,
|
||||
} from "@/api/masters";
|
||||
|
||||
const assetSchema = z.object({
|
||||
asset_code: z.string().trim().min(1, "Asset code is required"),
|
||||
serial_no: z.string().trim().min(1, "Serial number is required"),
|
||||
name: z.string().trim().min(1, "Equipment name is required"),
|
||||
category_id: z.coerce.number().int().min(1, "Select a category"),
|
||||
department_id: z.coerce.number().int().min(1, "Select a department"),
|
||||
location_id: z.coerce.number().int().min(1, "Select a location"),
|
||||
supplier_id: z.string().optional(),
|
||||
acquisition_mode: z.enum(["purchased", "rented"]),
|
||||
purchase_value: z.string().optional(),
|
||||
monthly_rent: z.string().optional(),
|
||||
useful_life_years: z.string().optional(),
|
||||
salvage_pct: z.string().optional(),
|
||||
depreciation_method: z.string().optional(),
|
||||
purchase_date: z.string().optional(),
|
||||
installation_date: z.string().optional(),
|
||||
status: z.enum(["in_service", "under_repair", "out_of_service", "condemned"]),
|
||||
criticality: z.enum(["critical", "non_critical"]),
|
||||
requires_calibration: z.boolean(),
|
||||
insurance_applicable: z.boolean(),
|
||||
remarks: z.string().optional(),
|
||||
});
|
||||
|
||||
type AssetFormValues = z.infer<typeof assetSchema>;
|
||||
|
||||
interface AssetFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing?: AssetItem | null;
|
||||
coordinatorOnly?: boolean;
|
||||
}
|
||||
|
||||
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 disabled:bg-gray-100 disabled:text-gray-500";
|
||||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||
const errCls = "text-xs text-red-600 mt-1";
|
||||
|
||||
export function AssetFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing = null,
|
||||
coordinatorOnly = false,
|
||||
}: AssetFormModalProps) {
|
||||
const qc = useQueryClient();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
const locsQuery = useQuery({
|
||||
queryKey: ["locations", "active-only"],
|
||||
queryFn: () => locationsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
const catsQuery = useQuery({
|
||||
queryKey: ["categories", "active-only"],
|
||||
queryFn: () => categoriesApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const allLocations = useMemo(
|
||||
() => locsQuery.data?.items ?? [],
|
||||
[locsQuery.data?.items]
|
||||
);
|
||||
const categories = useMemo(
|
||||
() => catsQuery.data?.items ?? [],
|
||||
[catsQuery.data?.items]
|
||||
);
|
||||
const vendors = vendorsQuery.data?.items ?? [];
|
||||
|
||||
const defaultDeptId = editing?.department_id ?? departments[0]?.id ?? 0;
|
||||
const defaultLocId =
|
||||
editing?.location_id ??
|
||||
allLocations.find((l) => l.department_id === defaultDeptId)?.id ??
|
||||
0;
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<AssetFormValues>({
|
||||
resolver: zodResolver(assetSchema),
|
||||
defaultValues: {
|
||||
asset_code: "",
|
||||
serial_no: "",
|
||||
name: "",
|
||||
category_id: 0,
|
||||
department_id: 0,
|
||||
location_id: 0,
|
||||
supplier_id: "",
|
||||
acquisition_mode: "purchased",
|
||||
purchase_value: "",
|
||||
monthly_rent: "",
|
||||
useful_life_years: "",
|
||||
salvage_pct: "",
|
||||
depreciation_method: "",
|
||||
purchase_date: "",
|
||||
installation_date: "",
|
||||
status: "in_service",
|
||||
criticality: "non_critical",
|
||||
requires_calibration: false,
|
||||
insurance_applicable: false,
|
||||
remarks: "",
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setServerError(null);
|
||||
if (editing) {
|
||||
reset({
|
||||
asset_code: editing.asset_code,
|
||||
serial_no: editing.serial_no ?? "",
|
||||
name: editing.name,
|
||||
category_id: editing.category_id,
|
||||
department_id: editing.department_id,
|
||||
location_id: editing.location_id,
|
||||
supplier_id: editing.supplier_id ? String(editing.supplier_id) : "",
|
||||
acquisition_mode: (editing.acquisition_mode === "rented" ? "rented" : "purchased") as AcquisitionMode,
|
||||
purchase_value: editing.purchase_value != null ? String(editing.purchase_value) : "",
|
||||
monthly_rent: editing.monthly_rent != null ? String(editing.monthly_rent) : "",
|
||||
useful_life_years: editing.useful_life_years != null ? String(editing.useful_life_years) : "",
|
||||
salvage_pct: editing.salvage_pct != null ? String(editing.salvage_pct) : "",
|
||||
depreciation_method: editing.depreciation_method ?? "",
|
||||
purchase_date: editing.purchase_date ?? "",
|
||||
installation_date: editing.installation_date ?? "",
|
||||
status: editing.status,
|
||||
criticality: editing.criticality,
|
||||
requires_calibration: editing.requires_calibration,
|
||||
insurance_applicable: editing.insurance_applicable,
|
||||
remarks: editing.remarks ?? "",
|
||||
});
|
||||
} else {
|
||||
reset({
|
||||
asset_code: "",
|
||||
serial_no: "",
|
||||
name: "",
|
||||
category_id: categories[0]?.id ?? 0,
|
||||
department_id: defaultDeptId,
|
||||
location_id: defaultLocId,
|
||||
supplier_id: "",
|
||||
acquisition_mode: "purchased",
|
||||
purchase_value: "",
|
||||
monthly_rent: "",
|
||||
useful_life_years: "",
|
||||
salvage_pct: "",
|
||||
depreciation_method: "",
|
||||
purchase_date: "",
|
||||
installation_date: "",
|
||||
status: "in_service",
|
||||
criticality: "non_critical",
|
||||
requires_calibration: false,
|
||||
insurance_applicable: false,
|
||||
remarks: "",
|
||||
});
|
||||
}
|
||||
}, [open, editing, categories, defaultDeptId, defaultLocId, reset]);
|
||||
|
||||
const watchedDeptId = Number(watch("department_id"));
|
||||
const filteredLocations = useMemo(
|
||||
() => allLocations.filter((l) => l.department_id === watchedDeptId),
|
||||
[allLocations, watchedDeptId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || coordinatorOnly) return;
|
||||
const currentLoc = Number(watch("location_id"));
|
||||
if (
|
||||
watchedDeptId > 0 &&
|
||||
filteredLocations.length > 0 &&
|
||||
!filteredLocations.some((l) => l.id === currentLoc)
|
||||
) {
|
||||
setValue("location_id", filteredLocations[0].id);
|
||||
} else if (watchedDeptId > 0 && filteredLocations.length === 0 && currentLoc !== 0) {
|
||||
setValue("location_id", 0);
|
||||
}
|
||||
}, [watchedDeptId, filteredLocations, open, coordinatorOnly, setValue, watch]);
|
||||
|
||||
async function onSubmit(values: AssetFormValues) {
|
||||
setServerError(null);
|
||||
try {
|
||||
if (editing && coordinatorOnly) {
|
||||
await assetsApi.update(editing.id, {
|
||||
requires_calibration: values.requires_calibration,
|
||||
insurance_applicable: values.insurance_applicable,
|
||||
remarks: values.remarks?.trim() || null,
|
||||
});
|
||||
} else {
|
||||
const payload = {
|
||||
asset_code: values.asset_code.trim(),
|
||||
serial_no: values.serial_no.trim(),
|
||||
name: values.name.trim(),
|
||||
category_id: values.category_id,
|
||||
department_id: values.department_id,
|
||||
location_id: values.location_id,
|
||||
supplier_id: values.supplier_id ? Number(values.supplier_id) : null,
|
||||
acquisition_mode: values.acquisition_mode as AcquisitionMode,
|
||||
purchase_value:
|
||||
values.purchase_value && values.purchase_value.trim() !== ""
|
||||
? Number(values.purchase_value)
|
||||
: null,
|
||||
monthly_rent:
|
||||
values.monthly_rent && values.monthly_rent.trim() !== ""
|
||||
? Number(values.monthly_rent)
|
||||
: null,
|
||||
useful_life_years:
|
||||
values.useful_life_years && values.useful_life_years.trim() !== ""
|
||||
? Math.trunc(Number(values.useful_life_years))
|
||||
: null,
|
||||
salvage_pct:
|
||||
values.salvage_pct && values.salvage_pct.trim() !== ""
|
||||
? Number(values.salvage_pct)
|
||||
: null,
|
||||
depreciation_method:
|
||||
values.depreciation_method && values.depreciation_method.trim() !== ""
|
||||
? (values.depreciation_method as DepreciationMethod)
|
||||
: null,
|
||||
purchase_date: values.purchase_date || null,
|
||||
installation_date: values.installation_date || null,
|
||||
status: values.status as AssetStatus,
|
||||
criticality: values.criticality as AssetCriticality,
|
||||
requires_calibration: values.requires_calibration,
|
||||
insurance_applicable: values.insurance_applicable,
|
||||
remarks: values.remarks?.trim() || null,
|
||||
};
|
||||
if (editing) {
|
||||
await assetsApi.update(editing.id, payload);
|
||||
} else {
|
||||
await assetsApi.create(payload);
|
||||
}
|
||||
}
|
||||
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
if (editing) {
|
||||
await qc.invalidateQueries({ queryKey: ["asset-overview", editing.id] });
|
||||
}
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setServerError(err instanceof ApiError ? err.detail : "Failed to save asset.");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? `Edit Asset — ${editing.asset_code}` : "Add New Asset"}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{coordinatorOnly && (
|
||||
<div className="mb-3 rounded-md bg-blue-50 border border-blue-200 px-3 py-2 text-xs text-blue-800">
|
||||
Coordinator permissions: only calibration requirement, insurance applicability, and remarks can be edited.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{serverError && (
|
||||
<div 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>{serverError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Asset Code *</label>
|
||||
<input
|
||||
{...register("asset_code")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="e.g. PHRC-ICU-0099"
|
||||
className={inputCls}
|
||||
/>
|
||||
{errors.asset_code && <p className={errCls}>{errors.asset_code.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Serial No *</label>
|
||||
<input
|
||||
{...register("serial_no")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="Manufacturer serial number"
|
||||
className={inputCls}
|
||||
/>
|
||||
{errors.serial_no && <p className={errCls}>{errors.serial_no.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Equipment Name *</label>
|
||||
<input
|
||||
{...register("name")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="e.g. Multipara Patient Monitor"
|
||||
className={inputCls}
|
||||
/>
|
||||
{errors.name && <p className={errCls}>{errors.name.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Category *</label>
|
||||
<select {...register("category_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value={0}>Select category...</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.category_id && <p className={errCls}>{errors.category_id.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Department *</label>
|
||||
<select {...register("department_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value={0}>Select department...</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.name} ({d.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.department_id && <p className={errCls}>{errors.department_id.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Location *</label>
|
||||
<select {...register("location_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value={0}>
|
||||
{filteredLocations.length === 0 ? "No locations in department" : "Select location..."}
|
||||
</option>
|
||||
{filteredLocations.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.name}
|
||||
{l.floor_wing ? ` (${l.floor_wing})` : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.location_id && <p className={errCls}>{errors.location_id.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Supplier</label>
|
||||
<select {...register("supplier_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value="">None / Not specified</option>
|
||||
{vendors.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Purchase Value (INR)</label>
|
||||
<input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
{...register("purchase_value")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="e.g. 450000"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Acquisition Mode</label>
|
||||
<select {...register("acquisition_mode")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value="purchased">Purchased (Owned)</option>
|
||||
<option value="rented">Rented / Leased</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>
|
||||
{watch("acquisition_mode") === "rented"
|
||||
? "Monthly Rent (INR)"
|
||||
: "Monthly Rent Quote (INR, for comparison)"}
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
{...register("monthly_rent")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="e.g. 15000"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Useful Life (Years)</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
step="1"
|
||||
{...register("useful_life_years")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="Category/system default"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Salvage Value (%)</label>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="50"
|
||||
step="0.5"
|
||||
{...register("salvage_pct")}
|
||||
disabled={coordinatorOnly}
|
||||
placeholder="Default 5%"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Depreciation Method</label>
|
||||
<select {...register("depreciation_method")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value="">System Default</option>
|
||||
<option value="straight_line">Straight Line</option>
|
||||
<option value="written_down">Written Down Value</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Purchase Date</label>
|
||||
<input
|
||||
type="date"
|
||||
{...register("purchase_date")}
|
||||
disabled={coordinatorOnly}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Installation Date</label>
|
||||
<input
|
||||
type="date"
|
||||
{...register("installation_date")}
|
||||
disabled={coordinatorOnly}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Status *</label>
|
||||
<select {...register("status")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value="in_service">In Service</option>
|
||||
<option value="under_repair">Under Repair</option>
|
||||
<option value="out_of_service">Out of Service</option>
|
||||
<option value="condemned">Condemned</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Criticality *</label>
|
||||
<select {...register("criticality")} disabled={coordinatorOnly} className={inputCls}>
|
||||
<option value="critical">Critical</option>
|
||||
<option value="non_critical">Non-Critical</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-6 pt-1">
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
{...register("requires_calibration")}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Requires Calibration
|
||||
</label>
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
{...register("insurance_applicable")}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Insurance Applicable
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea {...register("remarks")} rows={2} 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={isSubmitting}>
|
||||
{editing ? "Save Changes" : "Create Asset"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Search, X, ShieldCheck, Ban } from "lucide-react";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { CoverageBadge, AssetStatusBadge } from "./StatusBadge";
|
||||
import { InsuranceDrawer } from "./InsuranceDrawer";
|
||||
|
||||
interface AssetPickerProps {
|
||||
selectedAsset: AssetLookupItem | null;
|
||||
onSelect: (asset: AssetLookupItem | null) => void;
|
||||
departmentId?: number;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function AssetPicker({
|
||||
selectedAsset,
|
||||
onSelect,
|
||||
departmentId,
|
||||
disabled = false,
|
||||
placeholder = "Search by asset code, equipment name, or serial no...",
|
||||
}: AssetPickerProps) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [debouncedQuery, setDebouncedQuery] = useState("");
|
||||
const [results, setResults] = useState<AssetLookupItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [insuranceOpen, setInsuranceOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedQuery(query);
|
||||
}, 250);
|
||||
return () => clearTimeout(timer);
|
||||
}, [query]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || disabled) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
assetsApi
|
||||
.lookup({ q: debouncedQuery, department_id: departmentId, limit: 25 })
|
||||
.then((res) => {
|
||||
if (!cancelled) setResults(res.items);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setResults([]);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [debouncedQuery, departmentId, open, disabled]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleOutsideClick(e: MouseEvent) {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleOutsideClick);
|
||||
return () => document.removeEventListener("mousedown", handleOutsideClick);
|
||||
}, []);
|
||||
|
||||
if (selectedAsset) {
|
||||
const isUnderWarranty =
|
||||
selectedAsset.warranty_status === "active" || selectedAsset.warranty_status === "expiring";
|
||||
const isCondemned = selectedAsset.status === "condemned";
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-blue-200 bg-blue-50/40 p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-mono text-sm font-bold text-[#1e3a8a]">
|
||||
{selectedAsset.asset_code}
|
||||
</span>
|
||||
<span className="font-semibold text-gray-900">{selectedAsset.name}</span>
|
||||
<AssetStatusBadge status={selectedAsset.status} />
|
||||
{(selectedAsset.coverage || selectedAsset.coverage_tag) && (
|
||||
<CoverageBadge
|
||||
coverage={selectedAsset.coverage}
|
||||
tag={selectedAsset.coverage_tag}
|
||||
/>
|
||||
)}
|
||||
{isUnderWarranty && (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800 border border-emerald-300">
|
||||
<ShieldCheck className="h-3 w-3" />
|
||||
Under Warranty
|
||||
</span>
|
||||
)}
|
||||
{isCondemned && (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-300">
|
||||
<Ban className="h-3 w-3" />
|
||||
Condemned Asset
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{selectedAsset.serial_no && (
|
||||
<div className="text-xs text-gray-500 mt-0.5">
|
||||
Serial No: <span className="font-mono">{selectedAsset.serial_no}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!disabled && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(null);
|
||||
setQuery("");
|
||||
}}
|
||||
aria-label="Clear selected asset"
|
||||
className="inline-flex items-center gap-1 text-xs text-gray-600 hover:text-gray-900 px-2 py-1 rounded border border-gray-200 bg-white"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
Change
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs">
|
||||
<div>
|
||||
<div className="text-gray-500">Category</div>
|
||||
<div className="font-medium text-gray-800">{selectedAsset.category_name || "—"}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Department</div>
|
||||
<div className="font-medium text-gray-800">{selectedAsset.department_name || "—"}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Location</div>
|
||||
<div className="font-medium text-gray-800">{selectedAsset.location_name || "—"}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Warranty</div>
|
||||
<div className="mt-0.5 flex items-center gap-1.5 flex-wrap">
|
||||
<CoverageBadge status={selectedAsset.warranty_status} />
|
||||
{selectedAsset.warranty_end_date && (
|
||||
<span className="text-gray-600">
|
||||
till {formatDate(selectedAsset.warranty_end_date)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Contract</div>
|
||||
<div className="font-medium text-gray-800">
|
||||
{selectedAsset.contract_summary ||
|
||||
(selectedAsset.contract_type
|
||||
? `${selectedAsset.contract_type} (${selectedAsset.contract_status})`
|
||||
: "None")}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Insurance</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-medium text-gray-800">
|
||||
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setInsuranceOpen(true)}
|
||||
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||
>
|
||||
View Insurance
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{insuranceOpen && (
|
||||
<InsuranceDrawer
|
||||
open={insuranceOpen}
|
||||
onClose={() => setInsuranceOpen(false)}
|
||||
assetId={selectedAsset.id}
|
||||
assetLabel={`${selectedAsset.asset_code} — ${selectedAsset.name}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
disabled={disabled}
|
||||
value={query}
|
||||
onFocus={() => setOpen(true)}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setOpen(true);
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
className="w-full pl-9 pr-4 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white disabled:bg-gray-100"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{open && !disabled && (
|
||||
<div className="absolute left-0 right-0 mt-1 max-h-72 overflow-y-auto bg-white border border-gray-200 rounded-md shadow-lg z-30 divide-y divide-gray-100">
|
||||
{loading ? (
|
||||
<div className="px-4 py-3 text-xs text-gray-500">Searching assets...</div>
|
||||
) : results.length === 0 ? (
|
||||
<div className="px-4 py-3 text-xs text-gray-500">No matching assets found.</div>
|
||||
) : (
|
||||
results.map((item) => {
|
||||
const underWarranty =
|
||||
item.warranty_status === "active" || item.warranty_status === "expiring";
|
||||
const condemned = item.status === "condemned";
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(item);
|
||||
setOpen(false);
|
||||
}}
|
||||
className="w-full text-left px-3 py-2.5 hover:bg-blue-50/60 transition-colors flex items-center justify-between gap-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
<span className="font-mono text-[#1e3a8a]">{item.asset_code}</span> —{" "}
|
||||
{item.name}
|
||||
{item.serial_no ? ` (${item.serial_no})` : ""}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 truncate">
|
||||
{item.department_name || "—"} • {item.location_name || "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
{(item.coverage || item.coverage_tag) && (
|
||||
<CoverageBadge coverage={item.coverage} tag={item.coverage_tag} />
|
||||
)}
|
||||
{underWarranty && (
|
||||
<span className="px-2 py-0.5 rounded-full text-[11px] font-medium bg-emerald-100 text-emerald-800">
|
||||
Under Warranty
|
||||
</span>
|
||||
)}
|
||||
{condemned && (
|
||||
<span className="px-2 py-0.5 rounded-full text-[11px] font-medium bg-red-100 text-red-800">
|
||||
Condemned
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Upload,
|
||||
FileText,
|
||||
Image as ImageIcon,
|
||||
Download,
|
||||
Trash2,
|
||||
AlertCircle,
|
||||
ExternalLink,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
attachmentsApi,
|
||||
type AttachmentEntityType,
|
||||
type AttachmentItem,
|
||||
} from "@/api/attachments";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { validateAttachmentFile } from "@/lib/validation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
interface AttachmentsProps {
|
||||
entityType: AttachmentEntityType;
|
||||
entityId: number;
|
||||
canUpload: boolean;
|
||||
canDelete: boolean;
|
||||
}
|
||||
|
||||
export function Attachments({
|
||||
entityType,
|
||||
entityId,
|
||||
canUpload,
|
||||
canDelete,
|
||||
}: AttachmentsProps) {
|
||||
const qc = useQueryClient();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [dragActive, setDragActive] = useState(false);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null);
|
||||
|
||||
const queryKey = ["attachments", entityType, entityId];
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => attachmentsApi.list(entityType, entityId),
|
||||
enabled: Boolean(entityId),
|
||||
});
|
||||
|
||||
const uploadMutation = useMutation({
|
||||
mutationFn: (file: File) => attachmentsApi.upload(entityType, entityId, file),
|
||||
onSuccess: () => {
|
||||
setErrorMsg(null);
|
||||
qc.invalidateQueries({ queryKey });
|
||||
if (entityType === "asset") {
|
||||
qc.invalidateQueries({ queryKey: ["asset-overview", entityId] });
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to upload attachment.");
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => attachmentsApi.remove(id),
|
||||
onSuccess: () => {
|
||||
setConfirmDeleteId(null);
|
||||
setErrorMsg(null);
|
||||
qc.invalidateQueries({ queryKey });
|
||||
if (entityType === "asset") {
|
||||
qc.invalidateQueries({ queryKey: ["asset-overview", entityId] });
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to delete attachment.");
|
||||
},
|
||||
});
|
||||
|
||||
function handleFiles(files: FileList | null) {
|
||||
if (!files || files.length === 0) return;
|
||||
const file = files[0];
|
||||
const validationError = validateAttachmentFile(file);
|
||||
if (validationError) {
|
||||
setErrorMsg(validationError);
|
||||
return;
|
||||
}
|
||||
setErrorMsg(null);
|
||||
uploadMutation.mutate(file);
|
||||
}
|
||||
|
||||
async function handleDownload(att: AttachmentItem, preview = false) {
|
||||
try {
|
||||
setErrorMsg(null);
|
||||
await attachmentsApi.download(att.id, att.original_name, preview);
|
||||
} catch (err) {
|
||||
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to download file.");
|
||||
}
|
||||
}
|
||||
|
||||
const items = data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{errorMsg && (
|
||||
<div
|
||||
role="alert"
|
||||
className="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>{errorMsg}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canUpload && (
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setDragActive(true);
|
||||
}}
|
||||
onDragLeave={() => setDragActive(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setDragActive(false);
|
||||
handleFiles(e.dataTransfer.files);
|
||||
}}
|
||||
className={`border-2 border-dashed rounded-lg p-5 text-center transition-colors ${
|
||||
dragActive
|
||||
? "border-[#1e3a8a] bg-blue-50/50"
|
||||
: "border-gray-300 bg-gray-50/50 hover:border-gray-400"
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".jpg,.jpeg,.png,.pdf"
|
||||
aria-label="Upload attachment"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
handleFiles(e.target.files);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<Upload className="h-6 w-6 text-gray-400 mx-auto mb-2" />
|
||||
<p className="text-sm text-gray-600">
|
||||
Drag and drop a file here, or{" "}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={uploadMutation.isPending}
|
||||
className="text-[#1e3a8a] font-medium hover:underline disabled:opacity-50"
|
||||
>
|
||||
browse
|
||||
</button>
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
Allowed: JPG, PNG, PDF • Max size: 10 MB
|
||||
</p>
|
||||
{uploadMutation.isPending && (
|
||||
<p className="text-xs text-blue-600 mt-2">Uploading...</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-2">
|
||||
{[1, 2].map((i) => (
|
||||
<div key={i} className="h-14 bg-gray-100 rounded-md animate-pulse" />
|
||||
))}
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="text-sm text-gray-400 py-6 text-center border border-gray-200 rounded-lg bg-white">
|
||||
No attachments uploaded yet.
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white border border-gray-200 rounded-lg divide-y divide-gray-100">
|
||||
{items.map((att) => {
|
||||
const isPdf = att.mime_type === "application/pdf";
|
||||
return (
|
||||
<div
|
||||
key={att.id}
|
||||
className="flex items-center justify-between gap-3 px-4 py-3 hover:bg-gray-50/60"
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="h-9 w-9 rounded-md bg-blue-50 text-[#1e3a8a] flex items-center justify-center shrink-0">
|
||||
{isPdf ? <FileText className="h-5 w-5" /> : <ImageIcon className="h-5 w-5" />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{att.original_name}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{formatBytes(att.size_bytes)}
|
||||
{att.uploaded_by_name ? ` • Uploaded by ${att.uploaded_by_name}` : ""}
|
||||
{" • "}
|
||||
{formatDateTime(att.uploaded_at)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDownload(att, true)}
|
||||
title="Preview in new tab"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5 mr-1" />
|
||||
Preview
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDownload(att, false)}
|
||||
title="Download file"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5 mr-1" />
|
||||
Download
|
||||
</Button>
|
||||
{canDelete && (
|
||||
confirmDeleteId === att.id ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="danger"
|
||||
size="sm"
|
||||
loading={deleteMutation.isPending}
|
||||
onClick={() => deleteMutation.mutate(att.id)}
|
||||
>
|
||||
Confirm
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setConfirmDeleteId(null)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-red-600 hover:bg-red-50"
|
||||
onClick={() => setConfirmDeleteId(att.id)}
|
||||
aria-label={`Delete ${att.original_name}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Download,
|
||||
FileSpreadsheet,
|
||||
Upload,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { assetsApi, type BulkImportResult } from "@/api/assets";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface BulkAssetImportModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const ACCEPTED_EXTS = [".xlsx", ".xls", ".csv"];
|
||||
|
||||
export function BulkAssetImportModal({ open, onClose }: BulkAssetImportModalProps) {
|
||||
const qc = useQueryClient();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [dragActive, setDragActive] = useState(false);
|
||||
const [downloadingTemplate, setDownloadingTemplate] = useState(false);
|
||||
const [validating, setValidating] = useState(false);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [skipInvalid, setSkipInvalid] = useState(false);
|
||||
const [preview, setPreview] = useState<BulkImportResult | null>(null);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
|
||||
function resetState() {
|
||||
setSelectedFile(null);
|
||||
setPreview(null);
|
||||
setErrorMsg(null);
|
||||
setSkipInvalid(false);
|
||||
setValidating(false);
|
||||
setImporting(false);
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (importing) return;
|
||||
resetState();
|
||||
onClose();
|
||||
}
|
||||
|
||||
async function handleDownloadTemplate() {
|
||||
setDownloadingTemplate(true);
|
||||
setErrorMsg(null);
|
||||
try {
|
||||
await assetsApi.downloadImportTemplate();
|
||||
toast.success("Downloaded asset_import_template.xlsx");
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError
|
||||
? err.detail
|
||||
: "Failed to download import template.";
|
||||
setErrorMsg(msg);
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setDownloadingTemplate(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleFileSelect(files: FileList | null) {
|
||||
if (!files || files.length === 0) return;
|
||||
const file = files[0];
|
||||
const lower = file.name.toLowerCase();
|
||||
if (!ACCEPTED_EXTS.some((ext) => lower.endsWith(ext))) {
|
||||
setErrorMsg("Unsupported file type. Please upload an .xlsx, .xls, or .csv file.");
|
||||
setSelectedFile(null);
|
||||
setPreview(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFile(file);
|
||||
setErrorMsg(null);
|
||||
setPreview(null);
|
||||
setSkipInvalid(false);
|
||||
setValidating(true);
|
||||
|
||||
try {
|
||||
const result = await assetsApi.bulkImport(file, true, false);
|
||||
setPreview(result);
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError
|
||||
? err.detail
|
||||
: "Failed to validate import file.";
|
||||
setErrorMsg(msg);
|
||||
} finally {
|
||||
setValidating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleConfirmImport() {
|
||||
if (!selectedFile || !preview) return;
|
||||
setImporting(true);
|
||||
setErrorMsg(null);
|
||||
try {
|
||||
const result = await assetsApi.bulkImport(selectedFile, false, skipInvalid);
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: ["assets"] }),
|
||||
qc.invalidateQueries({ queryKey: ["dashboard"] }),
|
||||
]);
|
||||
toast.success(
|
||||
`Imported ${result.created_count} asset${result.created_count === 1 ? "" : "s"}`
|
||||
);
|
||||
resetState();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError ? err.detail : "Bulk asset import failed.";
|
||||
setErrorMsg(msg);
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const canImport =
|
||||
Boolean(selectedFile && preview) &&
|
||||
!validating &&
|
||||
!importing &&
|
||||
preview!.valid_count > 0 &&
|
||||
(preview!.error_count === 0 || skipInvalid);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) handleClose();
|
||||
}}
|
||||
title="Bulk Import Assets"
|
||||
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register multiple hospital assets at once."
|
||||
className="max-w-4xl"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* Step 1: Template Download */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-lg border border-blue-200 bg-blue-50/70 p-3.5">
|
||||
<div className="flex items-start gap-2.5 text-xs text-blue-950">
|
||||
<FileSpreadsheet className="h-5 w-5 text-[#1e3a8a] shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<div className="font-semibold text-sm text-[#1e3a8a]">
|
||||
Step 1: Download the Excel Template
|
||||
</div>
|
||||
<p className="mt-0.5 text-blue-900/90">
|
||||
Fill equipment rows in the <strong>Assets</strong> sheet and check valid
|
||||
departments, locations, categories, and suppliers in the{" "}
|
||||
<strong>Master Reference</strong> sheet.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
loading={downloadingTemplate}
|
||||
onClick={handleDownloadTemplate}
|
||||
className="shrink-0 bg-white"
|
||||
>
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
Download Template (.xlsx)
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Step 2: File Picker / Dropzone */}
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setDragActive(true);
|
||||
}}
|
||||
onDragLeave={() => setDragActive(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setDragActive(false);
|
||||
void handleFileSelect(e.dataTransfer.files);
|
||||
}}
|
||||
className={cn(
|
||||
"border-2 border-dashed rounded-lg p-5 text-center transition-colors",
|
||||
dragActive
|
||||
? "border-[#1e3a8a] bg-blue-50"
|
||||
: "border-gray-300 bg-gray-50/60 hover:bg-gray-50"
|
||||
)}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
aria-label="Upload asset spreadsheet"
|
||||
onChange={(e) => void handleFileSelect(e.target.files)}
|
||||
className="hidden"
|
||||
/>
|
||||
<Upload className="h-7 w-7 text-gray-400 mx-auto mb-2" />
|
||||
<p className="text-sm font-medium text-gray-800">
|
||||
{selectedFile ? selectedFile.name : "Drop your spreadsheet here, or browse"}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Accepts <code>.xlsx</code>, <code>.xls</code>, or <code>.csv</code> — automatically validates rows before importing.
|
||||
</p>
|
||||
<div className="mt-3 flex items-center justify-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={validating || importing}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
{selectedFile ? "Choose Another File" : "Select Spreadsheet"}
|
||||
</Button>
|
||||
{selectedFile && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={validating || importing}
|
||||
onClick={resetState}
|
||||
>
|
||||
<X className="h-3.5 w-3.5 mr-1" />
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{validating && (
|
||||
<div className="rounded-md border border-blue-200 bg-blue-50 px-3.5 py-2.5 text-xs text-blue-900">
|
||||
Validating rows against hospital masters...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errorMsg && (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
|
||||
<span>{errorMsg}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step 3: Dry-run Validation Preview */}
|
||||
{preview && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200">
|
||||
Total Rows: {preview.total_rows}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
|
||||
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||
Valid: {preview.valid_count}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium border",
|
||||
preview.error_count > 0
|
||||
? "bg-red-100 text-red-800 border-red-200"
|
||||
: "bg-gray-100 text-gray-600 border-gray-200"
|
||||
)}
|
||||
>
|
||||
<AlertCircle className="h-3.5 w-3.5" />
|
||||
Errors: {preview.error_count}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{preview.error_count > 0 && preview.valid_count > 0 && (
|
||||
<label className="inline-flex items-center gap-2 text-xs font-medium text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={skipInvalid}
|
||||
onChange={(e) => setSkipInvalid(e.target.checked)}
|
||||
className="rounded border-gray-300 text-[#1e3a8a] focus:ring-blue-500"
|
||||
/>
|
||||
Skip invalid rows and import valid rows only
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden">
|
||||
<div className="max-h-64 overflow-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead className="bg-gray-50 border-b border-gray-200 sticky top-0">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium text-gray-600">Row</th>
|
||||
<th className="px-3 py-2 text-left font-medium text-gray-600">Asset Code</th>
|
||||
<th className="px-3 py-2 text-left font-medium text-gray-600">Name</th>
|
||||
<th className="px-3 py-2 text-left font-medium text-gray-600">Department</th>
|
||||
<th className="px-3 py-2 text-left font-medium text-gray-600">Location</th>
|
||||
<th className="px-3 py-2 text-left font-medium text-gray-600">Validation</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 bg-white">
|
||||
{preview.preview_rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-3 py-6 text-center text-gray-400">
|
||||
No data rows found in spreadsheet.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
preview.preview_rows.map((r) => (
|
||||
<tr
|
||||
key={r.row}
|
||||
className={r.valid ? "bg-white" : "bg-red-50/60"}
|
||||
>
|
||||
<td className="px-3 py-2 font-mono text-gray-500">{r.row}</td>
|
||||
<td className="px-3 py-2 font-mono font-medium text-gray-900">
|
||||
{r.asset_code || "—"}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-gray-800">{r.name || "—"}</td>
|
||||
<td className="px-3 py-2 text-gray-700">
|
||||
{r.department_name || "—"}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-gray-700">
|
||||
{r.location_name || "—"}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
{r.valid ? (
|
||||
<span className="inline-flex items-center gap-1 text-green-700 font-medium">
|
||||
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||
Ready
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-start gap-1 text-red-700">
|
||||
<AlertCircle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
|
||||
<span>{r.error || "Invalid row"}</span>
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex flex-col-reverse sm:flex-row sm:items-center justify-end gap-2 pt-2 border-t border-gray-100">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={importing}
|
||||
onClick={handleClose}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
loading={importing}
|
||||
disabled={!canImport}
|
||||
onClick={handleConfirmImport}
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-1.5" />
|
||||
Import {preview?.valid_count ?? 0} Asset
|
||||
{(preview?.valid_count ?? 0) === 1 ? "" : "s"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Download,
|
||||
FileSpreadsheet,
|
||||
Upload,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import type { BulkImportResult } from "@/api/assets";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface PreviewColumn {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface BulkGenericImportModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
description: string;
|
||||
entityName: string;
|
||||
templateFilename: string;
|
||||
onDownloadTemplate: () => Promise<void>;
|
||||
onImport: (file: File, dryRun: boolean, skipInvalid: boolean) => Promise<BulkImportResult>;
|
||||
queryKeysToInvalidate: string[][];
|
||||
previewColumns: PreviewColumn[];
|
||||
}
|
||||
|
||||
const ACCEPTED_EXTS = [".xlsx", ".xls", ".csv"];
|
||||
|
||||
export function BulkGenericImportModal({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
description,
|
||||
entityName,
|
||||
templateFilename,
|
||||
onDownloadTemplate,
|
||||
onImport,
|
||||
queryKeysToInvalidate,
|
||||
previewColumns,
|
||||
}: BulkGenericImportModalProps) {
|
||||
const qc = useQueryClient();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [dragActive, setDragActive] = useState(false);
|
||||
const [downloadingTemplate, setDownloadingTemplate] = useState(false);
|
||||
const [validating, setValidating] = useState(false);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [skipInvalid, setSkipInvalid] = useState(false);
|
||||
const [preview, setPreview] = useState<BulkImportResult | null>(null);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
|
||||
function resetState() {
|
||||
setSelectedFile(null);
|
||||
setPreview(null);
|
||||
setErrorMsg(null);
|
||||
setSkipInvalid(false);
|
||||
setValidating(false);
|
||||
setImporting(false);
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (importing) return;
|
||||
resetState();
|
||||
onClose();
|
||||
}
|
||||
|
||||
async function handleDownloadTemplate() {
|
||||
setDownloadingTemplate(true);
|
||||
setErrorMsg(null);
|
||||
try {
|
||||
await onDownloadTemplate();
|
||||
toast.success(`Downloaded ${templateFilename}`);
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError
|
||||
? err.detail
|
||||
: "Failed to download import template.";
|
||||
setErrorMsg(msg);
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setDownloadingTemplate(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleFileSelect(files: FileList | null) {
|
||||
if (!files || files.length === 0) return;
|
||||
const file = files[0];
|
||||
const lower = file.name.toLowerCase();
|
||||
if (!ACCEPTED_EXTS.some((ext) => lower.endsWith(ext))) {
|
||||
setErrorMsg("Unsupported file type. Please upload an .xlsx, .xls, or .csv file.");
|
||||
setSelectedFile(null);
|
||||
setPreview(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFile(file);
|
||||
setErrorMsg(null);
|
||||
setPreview(null);
|
||||
setSkipInvalid(false);
|
||||
setValidating(true);
|
||||
|
||||
try {
|
||||
const result = await onImport(file, true, false);
|
||||
setPreview(result);
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError
|
||||
? err.detail
|
||||
: "Failed to validate import file.";
|
||||
setErrorMsg(msg);
|
||||
} finally {
|
||||
setValidating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleConfirmImport() {
|
||||
if (!selectedFile || !preview) return;
|
||||
setImporting(true);
|
||||
setErrorMsg(null);
|
||||
try {
|
||||
const result = await onImport(selectedFile, false, skipInvalid);
|
||||
await Promise.all(
|
||||
queryKeysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))
|
||||
);
|
||||
toast.success(
|
||||
`Imported ${result.created_count} ${entityName.toLowerCase()}${
|
||||
result.created_count === 1 ? "" : "s"
|
||||
}`
|
||||
);
|
||||
resetState();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError ? err.detail : `Bulk ${entityName.toLowerCase()} import failed.`;
|
||||
setErrorMsg(msg);
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const canImport =
|
||||
Boolean(selectedFile && preview) &&
|
||||
!validating &&
|
||||
!importing &&
|
||||
preview!.valid_count > 0 &&
|
||||
(preview!.error_count === 0 || skipInvalid);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) handleClose();
|
||||
}}
|
||||
title={title}
|
||||
description={description}
|
||||
className="max-w-4xl"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* Step 1: Template Download */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-lg border border-blue-200 bg-blue-50/70 p-3.5">
|
||||
<div className="flex items-start gap-2.5 text-xs text-blue-950">
|
||||
<FileSpreadsheet className="h-5 w-5 text-[#1e3a8a] shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<div className="font-semibold text-sm text-[#1e3a8a]">
|
||||
Step 1: Download the Excel Template
|
||||
</div>
|
||||
<p className="mt-0.5 text-blue-900/90">
|
||||
Download the official pre-formatted template with lookup references before uploading.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
loading={downloadingTemplate}
|
||||
onClick={handleDownloadTemplate}
|
||||
className="shrink-0 bg-white"
|
||||
>
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
Download Template (.xlsx)
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Step 2: File Picker / Dropzone */}
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setDragActive(true);
|
||||
}}
|
||||
onDragLeave={() => setDragActive(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setDragActive(false);
|
||||
void handleFileSelect(e.dataTransfer.files);
|
||||
}}
|
||||
className={cn(
|
||||
"border-2 border-dashed rounded-lg p-5 text-center transition-colors",
|
||||
dragActive
|
||||
? "border-[#1e3a8a] bg-blue-50"
|
||||
: "border-gray-300 bg-gray-50/60 hover:bg-gray-50"
|
||||
)}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
aria-label={`Upload ${entityName.toLowerCase()} spreadsheet`}
|
||||
onChange={(e) => void handleFileSelect(e.target.files)}
|
||||
className="hidden"
|
||||
/>
|
||||
<Upload className="h-7 w-7 text-gray-400 mx-auto mb-2" />
|
||||
<p className="text-sm font-medium text-gray-800">
|
||||
{selectedFile ? selectedFile.name : "Drop your spreadsheet here, or browse"}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Accepts <code>.xlsx</code>, <code>.xls</code>, or <code>.csv</code> — automatically validates rows before importing.
|
||||
</p>
|
||||
<div className="mt-3 flex items-center justify-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={validating || importing}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
{selectedFile ? "Choose Another File" : "Select Spreadsheet"}
|
||||
</Button>
|
||||
{selectedFile && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={validating || importing}
|
||||
onClick={resetState}
|
||||
>
|
||||
<X className="h-3.5 w-3.5 mr-1" />
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{validating && (
|
||||
<div className="rounded-md border border-blue-200 bg-blue-50 px-3.5 py-2.5 text-xs text-blue-900">
|
||||
Validating rows against hospital masters...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errorMsg && (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
|
||||
<span>{errorMsg}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step 3: Dry-run Validation Preview */}
|
||||
{preview && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200">
|
||||
Total Rows: {preview.total_rows}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
|
||||
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||
Valid: {preview.valid_count}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium border",
|
||||
preview.error_count > 0
|
||||
? "bg-red-100 text-red-800 border-red-200"
|
||||
: "bg-gray-100 text-gray-600 border-gray-200"
|
||||
)}
|
||||
>
|
||||
<AlertCircle className="h-3.5 w-3.5" />
|
||||
Errors: {preview.error_count}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{preview.error_count > 0 && preview.valid_count > 0 && (
|
||||
<label className="inline-flex items-center gap-2 text-xs font-medium text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={skipInvalid}
|
||||
onChange={(e) => setSkipInvalid(e.target.checked)}
|
||||
className="rounded border-gray-300 text-[#1e3a8a] focus:ring-blue-500"
|
||||
/>
|
||||
Skip invalid rows and import valid rows only
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden">
|
||||
<div className="max-h-64 overflow-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead className="bg-gray-50 border-b border-gray-200 sticky top-0">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium text-gray-600">Row</th>
|
||||
{previewColumns.map((col) => (
|
||||
<th key={col.key} className="px-3 py-2 text-left font-medium text-gray-600">
|
||||
{col.label}
|
||||
</th>
|
||||
))}
|
||||
<th className="px-3 py-2 text-left font-medium text-gray-600">Validation</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 bg-white">
|
||||
{preview.preview_rows.length === 0 ? (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={previewColumns.length + 2}
|
||||
className="px-3 py-6 text-center text-gray-400"
|
||||
>
|
||||
No data rows found in spreadsheet.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
preview.preview_rows.map((r) => {
|
||||
const rowRecord = r as unknown as Record<string, unknown>;
|
||||
const rowData = (rowRecord.data as Record<string, unknown> | undefined) || rowRecord;
|
||||
return (
|
||||
<tr
|
||||
key={r.row}
|
||||
className={r.valid ? "bg-white" : "bg-red-50/60"}
|
||||
>
|
||||
<td className="px-3 py-2 font-mono text-gray-500">{r.row}</td>
|
||||
{previewColumns.map((col) => {
|
||||
const val = rowRecord[col.key] ?? rowData[col.key];
|
||||
return (
|
||||
<td key={col.key} className="px-3 py-2 text-gray-800">
|
||||
{val !== null && val !== undefined && val !== ""
|
||||
? String(val)
|
||||
: "—"}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
<td className="px-3 py-2">
|
||||
{r.valid ? (
|
||||
<span className="inline-flex items-center gap-1 text-green-700 font-medium">
|
||||
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||
Ready
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-start gap-1 text-red-700">
|
||||
<AlertCircle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
|
||||
<span>{r.error || "Invalid row"}</span>
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex flex-col-reverse sm:flex-row sm:items-center justify-end gap-2 pt-2 border-t border-gray-100">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={importing}
|
||||
onClick={handleClose}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
loading={importing}
|
||||
disabled={!canImport}
|
||||
onClick={handleConfirmImport}
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-1.5" />
|
||||
Import {preview?.valid_count ?? 0} {entityName}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -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 "@/lib/validation";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { assetsApi } from "@/api/assets";
|
||||
import { vendorsApi } from "@/api/masters";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { calibrationApi, type CalibrationPlanItem } from "@/api/calibration";
|
||||
|
||||
const inputCls =
|
||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||
|
||||
function ErrorAlert({ message }: { message: string | null }) {
|
||||
if (!message) return null;
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{message}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddSingleCalibrationPlanModal({
|
||||
open,
|
||||
onClose,
|
||||
assetId,
|
||||
assetLabel,
|
||||
canApprove,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
assetId: number;
|
||||
assetLabel: string;
|
||||
canApprove: boolean;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [frequencyMonths, setFrequencyMonths] = useState("12");
|
||||
const [calPerYear, setCalPerYear] = useState("1");
|
||||
const [agencyId, setAgencyId] = useState("");
|
||||
const [nextDueDate, setNextDueDate] = useState("");
|
||||
const [approveNow, setApproveNow] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setFrequencyMonths("12");
|
||||
setCalPerYear("1");
|
||||
setAgencyId("");
|
||||
setNextDueDate(new Date().toISOString().slice(0, 10));
|
||||
setApproveNow(false);
|
||||
setError(null);
|
||||
}, [open, assetId]);
|
||||
|
||||
const agencies = (vendorsQuery.data?.items ?? []).filter(
|
||||
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
|
||||
);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await calibrationApi.createPlanFromAsset(assetId, {
|
||||
frequency_months: Math.max(1, Number(frequencyMonths) || 12),
|
||||
calibrations_per_year: calPerYear ? Math.max(1, Number(calPerYear)) : undefined,
|
||||
agency_id: agencyId ? Number(agencyId) : null,
|
||||
next_due_date: nextDueDate,
|
||||
approve: canApprove ? approveNow : false,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to add calibration plan.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Add to Calibration List — ${assetLabel}`}
|
||||
>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Frequency (Months) *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={frequencyMonths}
|
||||
onChange={(e) => setFrequencyMonths(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Calibrations / Year</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={calPerYear}
|
||||
onChange={(e) => setCalPerYear(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Calibration Agency</label>
|
||||
<select
|
||||
value={agencyId}
|
||||
onChange={(e) => setAgencyId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select agency (optional)...</option>
|
||||
{agencies.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Next Due Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={nextDueDate}
|
||||
onChange={(e) => setNextDueDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
{canApprove && (
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={approveNow}
|
||||
onChange={(e) => setApproveNow(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Approve frequency immediately
|
||||
</label>
|
||||
)}
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
Create Calibration Plan
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function BulkCalibrationAddModal({
|
||||
open,
|
||||
onClose,
|
||||
existingPlanAssetIds,
|
||||
canApprove,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
existingPlanAssetIds: number[];
|
||||
canApprove: boolean;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [search, setSearch] = useState("");
|
||||
const [onlyRequiresCal, setOnlyRequiresCal] = useState(false);
|
||||
const [selectedIds, setSelectedIds] = useState<number[]>([]);
|
||||
const [frequencyMonths, setFrequencyMonths] = useState("12");
|
||||
const [calPerYear, setCalPerYear] = useState("1");
|
||||
const [agencyId, setAgencyId] = useState("");
|
||||
const [nextDueDate, setNextDueDate] = useState("");
|
||||
const [approveNow, setApproveNow] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const assetsQuery = useQuery({
|
||||
queryKey: ["assets", "cal-candidates"],
|
||||
queryFn: () => assetsApi.list({ page_size: 500 }),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setSearch("");
|
||||
setSelectedIds([]);
|
||||
setFrequencyMonths("12");
|
||||
setCalPerYear("1");
|
||||
setAgencyId("");
|
||||
setNextDueDate(new Date().toISOString().slice(0, 10));
|
||||
setApproveNow(false);
|
||||
setError(null);
|
||||
}, [open]);
|
||||
|
||||
const existingSet = useMemo(() => new Set(existingPlanAssetIds), [existingPlanAssetIds]);
|
||||
const candidates = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
return (assetsQuery.data?.items ?? []).filter((a) => {
|
||||
if (existingSet.has(a.id)) return false;
|
||||
if (onlyRequiresCal && !a.requires_calibration) return false;
|
||||
if (
|
||||
q &&
|
||||
!`${a.asset_code} ${a.name} ${a.department_name ?? ""}`
|
||||
.toLowerCase()
|
||||
.includes(q)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [assetsQuery.data?.items, existingSet, onlyRequiresCal, search]);
|
||||
|
||||
const agencies = (vendorsQuery.data?.items ?? []).filter(
|
||||
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
|
||||
);
|
||||
|
||||
function toggleId(id: number) {
|
||||
setSelectedIds((prev) =>
|
||||
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (selectedIds.length === 0) {
|
||||
setError("Select at least one asset.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await calibrationApi.bulkCreatePlansFromAssets({
|
||||
asset_ids: selectedIds,
|
||||
frequency_months: Math.max(1, Number(frequencyMonths) || 12),
|
||||
calibrations_per_year: calPerYear ? Math.max(1, Number(calPerYear)) : undefined,
|
||||
agency_id: agencyId ? Number(agencyId) : null,
|
||||
next_due_date: nextDueDate,
|
||||
approve: canApprove ? approveNow : false,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Bulk creation failed.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Add Equipment to Calibration"
|
||||
className="max-w-2xl"
|
||||
>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search unconfigured assets..."
|
||||
className="flex-1 min-w-48 px-3 py-1.5 text-sm border border-gray-300 rounded-md"
|
||||
/>
|
||||
<label className="inline-flex items-center gap-1.5 text-xs text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={onlyRequiresCal}
|
||||
onChange={(e) => setOnlyRequiresCal(e.target.checked)}
|
||||
/>
|
||||
Requires calibration only
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="max-h-52 overflow-y-auto border border-gray-200 rounded-md divide-y divide-gray-100">
|
||||
{candidates.length === 0 ? (
|
||||
<div className="p-4 text-center text-xs text-gray-400">
|
||||
No matching assets without a calibration plan.
|
||||
</div>
|
||||
) : (
|
||||
candidates.map((a) => (
|
||||
<label
|
||||
key={a.id}
|
||||
className="flex items-center gap-3 px-3 py-2 hover:bg-blue-50/40 cursor-pointer text-sm"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedIds.includes(a.id)}
|
||||
onChange={() => toggleId(a.id)}
|
||||
/>
|
||||
<span className="font-mono text-xs text-[#1e3a8a] font-semibold">
|
||||
{a.asset_code}
|
||||
</span>
|
||||
<span className="flex-1 truncate">{a.name}</span>
|
||||
<span className="text-xs text-gray-500">{a.department_name}</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">{selectedIds.length} asset(s) selected</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Frequency (Months) *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={frequencyMonths}
|
||||
onChange={(e) => setFrequencyMonths(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Calibrations / Year</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={calPerYear}
|
||||
onChange={(e) => setCalPerYear(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Agency</label>
|
||||
<select
|
||||
value={agencyId}
|
||||
onChange={(e) => setAgencyId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select agency (optional)...</option>
|
||||
{agencies.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Next Due Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={nextDueDate}
|
||||
onChange={(e) => setNextDueDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canApprove && (
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={approveNow}
|
||||
onChange={(e) => setApproveNow(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Approve immediately
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
Add Selected ({selectedIds.length})
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function ApproveCalibrationPlanModal({
|
||||
open,
|
||||
onClose,
|
||||
plan,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
plan: CalibrationPlanItem | null;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [frequencyMonths, setFrequencyMonths] = useState("12");
|
||||
const [calPerYear, setCalPerYear] = useState("1");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !plan) return;
|
||||
setFrequencyMonths(String(plan.frequency_months));
|
||||
setCalPerYear(String(plan.calibrations_per_year));
|
||||
setError(null);
|
||||
}, [open, plan]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!plan) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await calibrationApi.approvePlan(plan.id, {
|
||||
frequency_months: Math.max(1, Number(frequencyMonths) || plan.frequency_months),
|
||||
calibrations_per_year: Math.max(
|
||||
1,
|
||||
Number(calPerYear) || plan.calibrations_per_year
|
||||
),
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["asset-overview", plan.asset_id] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Approval failed.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Approve / Edit Frequency — ${plan?.asset_code ?? ""}`}
|
||||
>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Frequency (Months) *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={frequencyMonths}
|
||||
onChange={(e) => setFrequencyMonths(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Calibrations / Year *</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
required
|
||||
value={calPerYear}
|
||||
onChange={(e) => setCalPerYear(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" variant="success" loading={submitting}>
|
||||
Approve Plan
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function CompleteCalibrationModal({
|
||||
open,
|
||||
onClose,
|
||||
recordId,
|
||||
assetLabel,
|
||||
defaultAgencyId,
|
||||
assetId,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
recordId: number | null;
|
||||
assetLabel: string;
|
||||
defaultAgencyId?: number | null;
|
||||
assetId?: number;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [completedDate, setCompletedDate] = useState("");
|
||||
const [certificateNo, setCertificateNo] = useState("");
|
||||
const [agencyId, setAgencyId] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [certFile, setCertFile] = useState<File | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setCompletedDate(new Date().toISOString().slice(0, 10));
|
||||
setCertificateNo("");
|
||||
setAgencyId(defaultAgencyId ? String(defaultAgencyId) : "");
|
||||
setRemarks("");
|
||||
setCertFile(null);
|
||||
setError(null);
|
||||
}, [open, recordId, defaultAgencyId]);
|
||||
|
||||
const agencies = (vendorsQuery.data?.items ?? []).filter(
|
||||
(v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider"
|
||||
);
|
||||
|
||||
function handlePickFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const f = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (!f) return;
|
||||
const err = validateAttachmentFile(f);
|
||||
if (err) {
|
||||
setError(err);
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setCertFile(f);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!recordId) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await calibrationApi.completeRecord(recordId, {
|
||||
completed_date: completedDate,
|
||||
certificate_no: certificateNo.trim(),
|
||||
agency_id: agencyId ? Number(agencyId) : null,
|
||||
remarks: remarks.trim() || null,
|
||||
});
|
||||
if (certFile) {
|
||||
await attachmentsApi.upload("calibration_record", recordId, certFile);
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["calibration-plans"] });
|
||||
await qc.invalidateQueries({ queryKey: ["attachments", "calibration_record", recordId] });
|
||||
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to complete calibration.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Complete Calibration — ${assetLabel}`}
|
||||
>
|
||||
<ErrorAlert message={error} />
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Completed Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={completedDate}
|
||||
onChange={(e) => setCompletedDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Certificate No *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={certificateNo}
|
||||
onChange={(e) => setCertificateNo(e.target.value)}
|
||||
placeholder="e.g. CAL-2026-881"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Agency</label>
|
||||
<select
|
||||
value={agencyId}
|
||||
onChange={(e) => setAgencyId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Default / Plan Agency</option>
|
||||
{agencies.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Calibration Certificate (Optional JPG/PNG/PDF)</label>
|
||||
{certFile ? (
|
||||
<div className="flex items-center justify-between text-xs bg-gray-50 border border-gray-200 rounded px-3 py-2">
|
||||
<span className="truncate">{certFile.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCertFile(null)}
|
||||
className="text-gray-400 hover:text-red-600 ml-2"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<label className="inline-flex items-center gap-2 px-3 py-2 rounded-md border border-gray-300 bg-white hover:bg-gray-50 text-xs font-medium text-gray-700 cursor-pointer">
|
||||
<Paperclip className="h-3.5 w-3.5" />
|
||||
Attach Certificate File
|
||||
<input
|
||||
type="file"
|
||||
accept=".jpg,.jpeg,.png,.pdf"
|
||||
onChange={handlePickFile}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" variant="success" loading={submitting}>
|
||||
Save & Complete
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { AlertTriangle, Clock, CheckCircle2, ExternalLink } from "lucide-react";
|
||||
import { notificationsApi } from "@/api/notifications";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
export function CalibrationReminderModal() {
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const { user, token } = useAuthStore();
|
||||
const [open, setOpen] = useState(false);
|
||||
const promptedTokensRef = useRef<Set<string>>(new Set());
|
||||
|
||||
const sessionKey = token ? `cal_popup_shown:${token.slice(-16)}` : null;
|
||||
|
||||
const calNotifsQuery = useQuery({
|
||||
queryKey: ["notifications", "calibration-login-popup", user?.id],
|
||||
queryFn: () =>
|
||||
notificationsApi.list({
|
||||
type: "calibration_due",
|
||||
unread_only: true,
|
||||
limit: 25,
|
||||
}),
|
||||
enabled: Boolean(user && token),
|
||||
});
|
||||
|
||||
const items = calNotifsQuery.data?.items ?? [];
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !user || items.length === 0) return;
|
||||
const alreadyShownInRef = promptedTokensRef.current.has(token);
|
||||
let alreadyShownInSession = false;
|
||||
try {
|
||||
alreadyShownInSession = Boolean(
|
||||
sessionKey && sessionStorage.getItem(sessionKey)
|
||||
);
|
||||
} catch {
|
||||
alreadyShownInSession = false;
|
||||
}
|
||||
|
||||
if (!alreadyShownInRef && !alreadyShownInSession) {
|
||||
promptedTokensRef.current.add(token);
|
||||
try {
|
||||
if (sessionKey) sessionStorage.setItem(sessionKey, "1");
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
setOpen(true);
|
||||
}
|
||||
}, [token, user, items.length, sessionKey]);
|
||||
|
||||
const acknowledgeMutation = useMutation({
|
||||
mutationFn: () => notificationsApi.markAllRead("calibration_due"),
|
||||
onSuccess: async () => {
|
||||
await qc.invalidateQueries({ queryKey: ["notifications"] });
|
||||
await qc.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
toast.success("Calibration reminders acknowledged");
|
||||
setOpen(false);
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to acknowledge calibration reminders");
|
||||
},
|
||||
});
|
||||
|
||||
if (!open || items.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && setOpen(false)}
|
||||
title={`Calibration Reminders (${items.length} Unread)`}
|
||||
className="max-w-xl"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-gray-600">
|
||||
The following equipment calibration schedules are due or overdue and require
|
||||
attention:
|
||||
</p>
|
||||
|
||||
<div className="max-h-72 overflow-y-auto divide-y divide-gray-100 border border-gray-200 rounded-lg">
|
||||
{items.map((n) => {
|
||||
const isRed = n.severity === "red";
|
||||
return (
|
||||
<div
|
||||
key={n.id}
|
||||
className="p-3 flex items-start gap-2.5 bg-white hover:bg-gray-50"
|
||||
>
|
||||
{isRed ? (
|
||||
<AlertTriangle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
|
||||
) : (
|
||||
<Clock className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-sm font-semibold text-gray-900 truncate">
|
||||
{n.title}
|
||||
</span>
|
||||
<span
|
||||
className={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase ${
|
||||
isRed
|
||||
? "bg-red-100 text-red-800"
|
||||
: "bg-amber-100 text-amber-800"
|
||||
}`}
|
||||
>
|
||||
{n.severity}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-600 mt-0.5">{n.message}</p>
|
||||
{n.due_date && (
|
||||
<div className="text-[11px] text-gray-500 mt-1">
|
||||
Due Date: <strong>{formatDate(n.due_date)}</strong>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
navigate("/calibration");
|
||||
}}
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5 mr-1.5" />
|
||||
Open Calibration Register
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Remind Me Later
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
loading={acknowledgeMutation.isPending}
|
||||
onClick={() => acknowledgeMutation.mutate()}
|
||||
>
|
||||
<CheckCircle2 className="h-4 w-4 mr-1.5" />
|
||||
Acknowledge & Mark Read
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { useState } from "react";
|
||||
import { KeyRound, AlertCircle, Eye, EyeOff } from "lucide-react";
|
||||
import { changePasswordApi } from "@/api/auth";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
interface ChangePasswordModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) {
|
||||
const [currentPassword, setCurrentPassword] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [showCurrent, setShowCurrent] = useState(false);
|
||||
const [showNew, setShowNew] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
|
||||
function resetState() {
|
||||
setCurrentPassword("");
|
||||
setNewPassword("");
|
||||
setConfirmPassword("");
|
||||
setShowCurrent(false);
|
||||
setShowNew(false);
|
||||
setErrorMsg(null);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (loading) return;
|
||||
resetState();
|
||||
onClose();
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setErrorMsg(null);
|
||||
|
||||
if (!currentPassword) {
|
||||
setErrorMsg("Please enter your current password.");
|
||||
return;
|
||||
}
|
||||
if (!newPassword || newPassword.length < 8) {
|
||||
setErrorMsg("New password must be at least 8 characters.");
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
setErrorMsg("New passwords do not match.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await changePasswordApi(currentPassword, newPassword);
|
||||
if (res.access_token) {
|
||||
useAuthStore.getState().setToken(res.access_token);
|
||||
}
|
||||
toast.success(res.message || "Password changed successfully.");
|
||||
handleClose();
|
||||
} catch (err) {
|
||||
const msg =
|
||||
err instanceof ApiError ? err.detail : "Failed to change password.";
|
||||
setErrorMsg(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) handleClose();
|
||||
}}
|
||||
title="Change Password"
|
||||
description="Update your account login password."
|
||||
className="max-w-md"
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{errorMsg && (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
|
||||
<span>{errorMsg}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-gray-700">
|
||||
Current Password <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showCurrent ? "text" : "password"}
|
||||
value={currentPassword}
|
||||
onChange={(e) => setCurrentPassword(e.target.value)}
|
||||
required
|
||||
autoComplete="current-password"
|
||||
placeholder="Enter current password"
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCurrent((s) => !s)}
|
||||
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
|
||||
aria-label={showCurrent ? "Hide current password" : "Show current password"}
|
||||
>
|
||||
{showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-gray-700">
|
||||
New Password <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showNew ? "text" : "password"}
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
autoComplete="new-password"
|
||||
placeholder="At least 8 characters"
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNew((s) => !s)}
|
||||
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
|
||||
aria-label={showNew ? "Hide new password" : "Show new password"}
|
||||
>
|
||||
{showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">At least 8 characters, with a letter and a number.</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-gray-700">
|
||||
Confirm New Password <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
autoComplete="new-password"
|
||||
placeholder="Re-enter new password"
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-3 border-t border-gray-100">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={handleClose}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" size="sm" loading={loading}>
|
||||
<KeyRound className="h-4 w-4 mr-1.5" />
|
||||
Update Password
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { AlertTriangle } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export interface ConfirmDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
variant?: "danger" | "default";
|
||||
loading?: boolean;
|
||||
onConfirm: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
message,
|
||||
confirmLabel = "Confirm",
|
||||
cancelLabel = "Cancel",
|
||||
variant = "danger",
|
||||
loading = false,
|
||||
onConfirm,
|
||||
}: ConfirmDialogProps) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!loading) onOpenChange(next);
|
||||
}}
|
||||
title={title}
|
||||
description={message}
|
||||
className="max-w-md"
|
||||
>
|
||||
<div className="space-y-5">
|
||||
{variant === "danger" && (
|
||||
<div className="flex items-start gap-3 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800">
|
||||
<AlertTriangle className="h-4 w-4 shrink-0 text-red-600 mt-0.5" />
|
||||
<span>This action cannot be undone.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
{cancelLabel}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={variant === "danger" ? "danger" : "default"}
|
||||
size="sm"
|
||||
loading={loading}
|
||||
onClick={() => void onConfirm()}
|
||||
>
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { CoverageBadge } from "./StatusBadge";
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import XLSX from "xlsx-js-style";
|
||||
import { DataTable } from "./DataTable";
|
||||
|
||||
vi.mock("xlsx-js-style", async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>();
|
||||
const base = ((actual as { default?: Record<string, unknown> }).default ?? actual) as Record<string, unknown>;
|
||||
const writeFileMock = vi.fn();
|
||||
return {
|
||||
...base,
|
||||
writeFile: writeFileMock,
|
||||
default: {
|
||||
...base,
|
||||
writeFile: writeFileMock,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
interface RowItem {
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const columns: ColumnDef<RowItem, unknown>[] = [
|
||||
{ accessorKey: "code", header: "Code", enableColumnFilter: true },
|
||||
{ accessorKey: "name", header: "Name", enableColumnFilter: true },
|
||||
];
|
||||
|
||||
const data: RowItem[] = [
|
||||
{ code: "A-001", name: "Ventilator" },
|
||||
{ code: "A-002", name: "Monitor" },
|
||||
];
|
||||
|
||||
describe("DataTable", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", async () => {
|
||||
render(
|
||||
<DataTable
|
||||
data={data}
|
||||
columns={columns}
|
||||
globalFilterPlaceholder="Search..."
|
||||
exportFilename="test-assets"
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText("Ventilator")).toBeInTheDocument();
|
||||
expect(screen.getByText("Monitor")).toBeInTheDocument();
|
||||
|
||||
const searchInput = screen.getByPlaceholderText("Search...");
|
||||
fireEvent.change(searchInput, { target: { value: "Ventilator" } });
|
||||
|
||||
expect(screen.getByText("Ventilator")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Monitor")).not.toBeInTheDocument();
|
||||
|
||||
const exportBtn = screen.getByRole("button", {
|
||||
name: /Export current view to Excel/i,
|
||||
});
|
||||
expect(exportBtn).toHaveTextContent("Export Excel (.xlsx)");
|
||||
fireEvent.click(exportBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(XLSX.writeFile).toHaveBeenCalledTimes(1);
|
||||
expect(XLSX.writeFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ SheetNames: ["Data"] }),
|
||||
"test-assets.xlsx"
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,404 @@
|
||||
import {
|
||||
useReactTable,
|
||||
getCoreRowModel,
|
||||
getFilteredRowModel,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel,
|
||||
flexRender,
|
||||
ColumnDef,
|
||||
SortingState,
|
||||
ColumnFiltersState,
|
||||
VisibilityState,
|
||||
PaginationState,
|
||||
FilterFn,
|
||||
type Table as TanStackTable,
|
||||
} from "@tanstack/react-table";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
ChevronUp,
|
||||
ChevronDown,
|
||||
ChevronsUpDown,
|
||||
FileSpreadsheet,
|
||||
Eye,
|
||||
Search,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface DataTableProps<TData> {
|
||||
data: TData[];
|
||||
columns: ColumnDef<TData, unknown>[];
|
||||
loading?: boolean;
|
||||
emptyMessage?: string;
|
||||
emptyAction?: React.ReactNode;
|
||||
globalFilterPlaceholder?: string;
|
||||
onRowClick?: (row: TData) => void;
|
||||
getRowClassName?: (row: TData) => string;
|
||||
exportFilename?: string;
|
||||
}
|
||||
|
||||
function formatExcelCell(val: unknown): string | number {
|
||||
if (val === null || val === undefined) return "";
|
||||
if (typeof val === "boolean") return val ? "Yes" : "No";
|
||||
if (typeof val === "number") return Number.isFinite(val) ? val : "";
|
||||
if (typeof val === "string") return val;
|
||||
return JSON.stringify(val);
|
||||
}
|
||||
|
||||
async function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
||||
const rows = table.getPrePaginationRowModel().rows;
|
||||
if (!rows.length) return;
|
||||
|
||||
const visibleCols = table
|
||||
.getVisibleLeafColumns()
|
||||
.filter((col) => col.id !== "actions");
|
||||
if (!visibleCols.length) return;
|
||||
|
||||
const XLSXModule = await import("xlsx-js-style");
|
||||
const XLSX = XLSXModule.default ?? XLSXModule;
|
||||
|
||||
const exportRows = rows.map((row) => {
|
||||
const record: Record<string, string | number> = {};
|
||||
for (const col of visibleCols) {
|
||||
const headerLabel =
|
||||
typeof col.columnDef.header === "string"
|
||||
? col.columnDef.header
|
||||
: col.id;
|
||||
record[headerLabel] = formatExcelCell(row.getValue(col.id));
|
||||
}
|
||||
return record;
|
||||
});
|
||||
|
||||
const ws = XLSX.utils.json_to_sheet(exportRows);
|
||||
|
||||
// Apply rich executive styling to table header row (Navy fill, bold white font, borders)
|
||||
for (let c = 0; c < visibleCols.length; c++) {
|
||||
const headerAddr = XLSX.utils.encode_cell({ r: 0, c });
|
||||
if (ws[headerAddr]) {
|
||||
ws[headerAddr].s = {
|
||||
fill: { fgColor: { rgb: "1E3A8A" } }, // Poona Hospital Deep Navy
|
||||
font: { name: "Calibri", sz: 11, bold: true, color: { rgb: "FFFFFF" } },
|
||||
alignment: { horizontal: "center", vertical: "center", wrapText: true },
|
||||
border: {
|
||||
top: { style: "thin", color: { rgb: "334155" } },
|
||||
bottom: { style: "medium", color: { rgb: "0F172A" } },
|
||||
left: { style: "thin", color: { rgb: "334155" } },
|
||||
right: { style: "thin", color: { rgb: "334155" } },
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Apply zebra striping, borders, and column-aware alignment to data rows
|
||||
for (let r = 0; r < rows.length; r++) {
|
||||
const isOdd = r % 2 === 1;
|
||||
for (let c = 0; c < visibleCols.length; c++) {
|
||||
const cellAddr = XLSX.utils.encode_cell({ r: r + 1, c });
|
||||
if (!ws[cellAddr]) continue;
|
||||
|
||||
const col = visibleCols[c];
|
||||
const headerLabel = (typeof col.columnDef.header === "string" ? col.columnDef.header : col.id).toLowerCase();
|
||||
const val = rows[r].getValue(col.id);
|
||||
|
||||
let horizontalAlign: "left" | "center" | "right" = "left";
|
||||
if (
|
||||
typeof val === "number" ||
|
||||
headerLabel.includes("cost") ||
|
||||
headerLabel.includes("value") ||
|
||||
headerLabel.includes("amount") ||
|
||||
headerLabel.includes("price") ||
|
||||
headerLabel.includes("minutes") ||
|
||||
headerLabel.includes("downtime") ||
|
||||
headerLabel.includes("total")
|
||||
) {
|
||||
horizontalAlign = "right";
|
||||
} else if (
|
||||
headerLabel.includes("code") ||
|
||||
headerLabel.includes("date") ||
|
||||
headerLabel.includes("status") ||
|
||||
headerLabel.includes("priority") ||
|
||||
headerLabel.includes("criticality") ||
|
||||
headerLabel.includes("serial") ||
|
||||
headerLabel.includes("mode") ||
|
||||
headerLabel.includes("id") ||
|
||||
typeof val === "boolean"
|
||||
) {
|
||||
horizontalAlign = "center";
|
||||
}
|
||||
|
||||
ws[cellAddr].s = {
|
||||
fill: { fgColor: { rgb: isOdd ? "F8FAFC" : "FFFFFF" } },
|
||||
font: { name: "Calibri", sz: 10, color: { rgb: "0F172A" } },
|
||||
alignment: { horizontal: horizontalAlign, vertical: "center" },
|
||||
border: {
|
||||
top: { style: "thin", color: { rgb: "E2E8F0" } },
|
||||
bottom: { style: "thin", color: { rgb: "E2E8F0" } },
|
||||
left: { style: "thin", color: { rgb: "E2E8F0" } },
|
||||
right: { style: "thin", color: { rgb: "E2E8F0" } },
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-fit column widths with generous padding so text/codes are never truncated
|
||||
const colWidths = visibleCols.map((col) => {
|
||||
const headerLabel =
|
||||
typeof col.columnDef.header === "string" ? col.columnDef.header : col.id;
|
||||
let maxLen = headerLabel.length;
|
||||
for (const row of rows) {
|
||||
const cellVal = formatExcelCell(row.getValue(col.id));
|
||||
const strVal = String(cellVal ?? "");
|
||||
if (strVal.length > maxLen) {
|
||||
maxLen = strVal.length;
|
||||
}
|
||||
}
|
||||
return { wch: Math.min(50, Math.max(14, maxLen + 3)) };
|
||||
});
|
||||
ws["!cols"] = colWidths;
|
||||
|
||||
// Add comfortable row heights: header row taller (28pt), data rows spacious (20pt)
|
||||
ws["!rows"] = [
|
||||
{ hpt: 28 },
|
||||
...rows.map(() => ({ hpt: 20 })),
|
||||
];
|
||||
|
||||
// Enable native Excel AutoFilter dropdowns on the header row
|
||||
const lastColLetter = XLSX.utils.encode_col(visibleCols.length - 1);
|
||||
ws["!autofilter"] = { ref: `A1:${lastColLetter}${rows.length + 1}` };
|
||||
|
||||
// Explicitly enable grid lines in Excel view
|
||||
ws["!views"] = [{ showGridLines: true }];
|
||||
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, "Data");
|
||||
XLSX.writeFile(wb, `${filename}.xlsx`);
|
||||
}
|
||||
|
||||
export function DataTable<TData>({
|
||||
data,
|
||||
columns,
|
||||
loading = false,
|
||||
emptyMessage = "No records found.",
|
||||
emptyAction,
|
||||
globalFilterPlaceholder = "Search...",
|
||||
onRowClick,
|
||||
getRowClassName,
|
||||
exportFilename = "export",
|
||||
}: DataTableProps<TData>) {
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [globalFilter, setGlobalFilter] = useState("");
|
||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 20 });
|
||||
const [showColVis, setShowColVis] = useState(false);
|
||||
|
||||
const globalFilterFn: FilterFn<TData> = (row, _columnId, filterValue: string) => {
|
||||
const search = String(filterValue ?? "").toLowerCase();
|
||||
return Object.values(row.original as Record<string, unknown>).some((v) =>
|
||||
String(v ?? "").toLowerCase().includes(search)
|
||||
);
|
||||
};
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
state: { sorting, columnFilters, columnVisibility, globalFilter, pagination },
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onGlobalFilterChange: setGlobalFilter,
|
||||
onPaginationChange: setPagination,
|
||||
globalFilterFn,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
});
|
||||
|
||||
const visibleRows = table.getRowModel().rows;
|
||||
const filteredRows = table.getFilteredRowModel().rows;
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Toolbar */}
|
||||
<div className="no-print flex flex-col sm:flex-row sm:items-center gap-2">
|
||||
<div className="relative flex-1 min-w-0">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<input
|
||||
value={globalFilter}
|
||||
onChange={(e) => setGlobalFilter(e.target.value)}
|
||||
placeholder={globalFilterPlaceholder}
|
||||
aria-label={globalFilterPlaceholder}
|
||||
className="w-full pl-9 pr-4 py-1.5 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="relative">
|
||||
<Button variant="outline" size="sm" onClick={() => setShowColVis(!showColVis)}>
|
||||
<Eye className="h-4 w-4 mr-1" /> Columns
|
||||
</Button>
|
||||
{showColVis && (
|
||||
<div className="absolute right-0 mt-1 w-48 bg-white border border-gray-200 rounded-md shadow-lg z-20 p-2">
|
||||
{table.getAllLeafColumns().map((col) => (
|
||||
<label key={col.id} className="flex items-center gap-2 px-2 py-1 hover:bg-gray-50 rounded cursor-pointer text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={col.getIsVisible()}
|
||||
onChange={col.getToggleVisibilityHandler()}
|
||||
className="rounded"
|
||||
/>
|
||||
{typeof col.columnDef.header === "string"
|
||||
? col.columnDef.header
|
||||
: col.id}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label="Export current view to Excel"
|
||||
onClick={() => exportToExcel(table, exportFilename)}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-1" /> Export Excel (.xlsx)
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
{table.getHeaderGroups().map((hg) => (
|
||||
<tr key={hg.id}>
|
||||
{hg.headers.map((header) => (
|
||||
<th key={header.id} className="text-left font-medium text-gray-600 px-2.5 py-2 sm:px-4 sm:py-3">
|
||||
{header.isPlaceholder ? null : (
|
||||
<div className="space-y-1">
|
||||
{/* Sortable header */}
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"flex items-center gap-1 hover:text-gray-900 font-medium",
|
||||
header.column.getCanSort() ? "cursor-pointer select-none" : "cursor-default"
|
||||
)}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{header.column.getCanSort() && (
|
||||
header.column.getIsSorted() === "asc" ? (
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
) : header.column.getIsSorted() === "desc" ? (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronsUpDown className="h-3 w-3 opacity-30" />
|
||||
)
|
||||
)}
|
||||
</button>
|
||||
{/* Per-column filter */}
|
||||
{header.column.getCanFilter() && (
|
||||
<input
|
||||
value={(header.column.getFilterValue() as string) ?? ""}
|
||||
onChange={(e) => header.column.setFilterValue(e.target.value)}
|
||||
placeholder="Filter..."
|
||||
className="no-print w-full px-2 py-0.5 text-xs border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-blue-400"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{loading ? (
|
||||
[...Array(5)].map((_, i) => (
|
||||
<tr key={i}>
|
||||
{columns.map((_, j) => (
|
||||
<td key={j} className="px-2.5 py-2 sm:px-4 sm:py-3">
|
||||
<div className="h-4 bg-gray-100 rounded animate-pulse" />
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))
|
||||
) : visibleRows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={columns.length} className="px-4 py-12 text-center">
|
||||
<div className="text-gray-400 space-y-2">
|
||||
<p>{emptyMessage}</p>
|
||||
{emptyAction}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
visibleRows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={cn(
|
||||
"hover:bg-blue-50/50 transition-colors",
|
||||
getRowClassName?.(row.original),
|
||||
onRowClick && "cursor-pointer"
|
||||
)}
|
||||
onClick={() => onRowClick?.(row.original)}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td key={cell.id} className="px-2.5 py-2 sm:px-4 sm:py-3 text-gray-700">
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{!loading && visibleRows.length > 0 && (
|
||||
<div className="no-print flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 sm:px-4 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
|
||||
<span>
|
||||
{filteredRows.length} record{filteredRows.length !== 1 ? "s" : ""}
|
||||
{globalFilter || columnFilters.length ? " (filtered)" : ""}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
value={pagination.pageSize}
|
||||
onChange={(e) => table.setPageSize(Number(e.target.value))}
|
||||
className="border border-gray-200 rounded px-2 py-1 text-xs"
|
||||
>
|
||||
{[10, 20, 50, 100].map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{s} / page
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => table.previousPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
className="px-2 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white"
|
||||
>
|
||||
←
|
||||
</button>
|
||||
<span className="text-xs">
|
||||
Page {pagination.pageIndex + 1} / {table.getPageCount()}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => table.nextPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
className="px-2 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white"
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { DataTable } from "./DataTable";
|
||||
@@ -0,0 +1,180 @@
|
||||
import { useEffect } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Link } from "react-router-dom";
|
||||
import { X, ShieldCheck, AlertCircle, ExternalLink } from "lucide-react";
|
||||
import { insuranceApi } from "@/api/phase5";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate, formatINR } from "@/lib/format";
|
||||
import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface InsuranceDrawerProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
assetId: number | null;
|
||||
assetLabel?: string;
|
||||
}
|
||||
|
||||
export function InsuranceDrawer({
|
||||
open,
|
||||
onClose,
|
||||
assetId,
|
||||
assetLabel,
|
||||
}: InsuranceDrawerProps) {
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const canManage = can(role, "manage_calibration_contracts");
|
||||
|
||||
const policiesQuery = useQuery({
|
||||
queryKey: ["insurance", "asset-drawer", assetId],
|
||||
queryFn: () => insuranceApi.list({ asset_id: assetId!, page_size: 200 }),
|
||||
enabled: open && Boolean(assetId),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open || !assetId) return null;
|
||||
|
||||
const policies = policiesQuery.data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex justify-end bg-black/40"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Asset Insurance Policies"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-lg bg-white h-full shadow-2xl border-l border-gray-200 flex flex-col"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 bg-gray-50">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-gray-900">
|
||||
<ShieldCheck className="h-4 w-4 text-[#1e3a8a] shrink-0" />
|
||||
<span>Asset Insurance</span>
|
||||
</div>
|
||||
{assetLabel && (
|
||||
<p className="text-xs text-gray-500 truncate mt-0.5">{assetLabel}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close insurance drawer"
|
||||
className="p-1.5 rounded-md text-gray-500 hover:text-gray-800 hover:bg-gray-200"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-5 space-y-4">
|
||||
{policiesQuery.isLoading ? (
|
||||
<div className="space-y-3">
|
||||
<div className="h-28 bg-gray-100 rounded-lg animate-pulse" />
|
||||
<div className="h-28 bg-gray-100 rounded-lg animate-pulse" />
|
||||
</div>
|
||||
) : policiesQuery.isError ? (
|
||||
<div className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 p-3 text-sm text-red-700">
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>Failed to load insurance policies for this asset.</span>
|
||||
</div>
|
||||
) : policies.length === 0 ? (
|
||||
<div className="text-center py-10 bg-gray-50 border border-dashed border-gray-200 rounded-lg space-y-2">
|
||||
<ShieldCheck className="h-8 w-8 text-gray-300 mx-auto" />
|
||||
<p className="text-sm font-medium text-gray-700">
|
||||
No insurance policies recorded for this asset.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Policies can be added from the Insurance register.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
policies.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="rounded-lg border border-gray-200 bg-white p-4 space-y-3 shadow-sm"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="font-mono text-sm font-bold text-[#1e3a8a]">
|
||||
{p.policy_no}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 mt-0.5">
|
||||
{p.insurer_name || `Insurer #${p.insurer_id}`}
|
||||
</div>
|
||||
</div>
|
||||
<ExpiryChip
|
||||
daysToExpiry={p.days_to_expiry}
|
||||
status={p.status}
|
||||
severity={p.severity}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 text-xs bg-gray-50 rounded-md p-2.5 border border-gray-100">
|
||||
<div>
|
||||
<div className="text-gray-500">Start</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatDate(p.start_date)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">End</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatDate(p.end_date)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Coverage</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatINR(p.coverage_amount)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{p.remarks && (
|
||||
<p className="text-xs text-gray-600">
|
||||
<span className="font-medium">Remarks:</span> {p.remarks}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="pt-2 border-t border-gray-100">
|
||||
<div className="text-xs font-semibold text-gray-700 mb-1.5">
|
||||
Policy Certificates & Documents
|
||||
</div>
|
||||
<Attachments
|
||||
entityType="insurance"
|
||||
entityId={p.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="px-5 py-3 border-t border-gray-200 bg-gray-50 flex items-center justify-between gap-2">
|
||||
<Link to={`/insurance`} onClick={onClose}>
|
||||
<Button variant="outline" size="sm">
|
||||
<ExternalLink className="h-3.5 w-3.5 mr-1.5" />
|
||||
Open Insurance Register
|
||||
</Button>
|
||||
</Link>
|
||||
<Button variant="outline" size="sm" onClick={onClose}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
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";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
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 role = useAuthStore((s) => s.user?.role);
|
||||
const canEditPmCost = role === "system_admin" || role === "biomedical";
|
||||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||||
const [serviceMode, setServiceMode] = useState<ServiceMode>("in_house");
|
||||
const [responsibleTeam, setResponsibleTeam] = useState("Biomedical Engineering");
|
||||
const [costPerVisit, setCostPerVisit] = useState("");
|
||||
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");
|
||||
setCostPerVisit("");
|
||||
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;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const created = 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" && providerId ? Number(providerId) : null,
|
||||
contract_id:
|
||||
serviceMode === "outsourced" && contractId ? Number(contractId) : null,
|
||||
cost_per_visit:
|
||||
serviceMode === "in_house" && canEditPmCost && costPerVisit.trim() !== ""
|
||||
? Number(costPerVisit)
|
||||
: null,
|
||||
next_planned_date: nextPlannedDate,
|
||||
});
|
||||
if (created.no_active_contract) {
|
||||
toast.info("PM schedule created without active AMC/CMC contract — assign a provider once contracted.");
|
||||
}
|
||||
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 className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<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>
|
||||
{canEditPmCost && (
|
||||
<div>
|
||||
<label className={labelCls}>Est. Cost per Visit (INR)</label>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
value={costPerVisit}
|
||||
onChange={(e) => setCostPerVisit(e.target.value)}
|
||||
placeholder="e.g. 5000"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Service Provider (Auto-fills from AMC/CMC)</label>
|
||||
<select
|
||||
value={providerId}
|
||||
onChange={(e) => setProviderId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Auto-detect from active contract...</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 [reportFile, setReportFile] = useState<File | null>(null);
|
||||
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("");
|
||||
setReportFile(null);
|
||||
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,
|
||||
});
|
||||
if (reportFile) {
|
||||
await attachmentsApi.upload("pm_record", recordId, reportFile);
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["pm-records"] });
|
||||
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
||||
await qc.invalidateQueries({ queryKey: ["attachments", "pm_record", recordId] });
|
||||
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>
|
||||
<label className={labelCls}>Service Report / Checklist (optional)</label>
|
||||
<input
|
||||
type="file"
|
||||
accept=".pdf,.png,.jpg,.jpeg,.doc,.docx"
|
||||
onChange={(e) => setReportFile(e.target.files?.[0] ?? null)}
|
||||
className="w-full text-xs text-gray-700 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:text-xs file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 border border-gray-200 rounded-md p-1"
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { AlertCircle, Clock, Paperclip, PhoneCall, X } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { CoverageBadge } from "@/components/StatusBadge";
|
||||
import { validateAttachmentFile } from "@/lib/validation";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { assetsApi, type AssetLookupItem, type AssetCriticality } from "@/api/assets";
|
||||
import { complaintsApi, type ComplaintItem } from "@/api/complaints";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { fetchUsersLookup } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
const complaintSchema = z.object({
|
||||
description: z.string().trim().min(1, "Problem description is required"),
|
||||
breakdown_details: z.string().optional(),
|
||||
priority: z.enum(["critical", "non_critical"]),
|
||||
notes: z.string().optional(),
|
||||
received_by_id: z.string().optional(),
|
||||
});
|
||||
|
||||
type ComplaintFormValues = z.infer<typeof complaintSchema>;
|
||||
|
||||
interface RaiseComplaintModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
initialAssetId?: number | null;
|
||||
initialDescription?: string;
|
||||
onCreated?: (complaint: ComplaintItem) => Promise<void> | void;
|
||||
navigateOnCreate?: boolean;
|
||||
}
|
||||
|
||||
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";
|
||||
|
||||
export function RaiseComplaintModal({
|
||||
open,
|
||||
onClose,
|
||||
initialAssetId = null,
|
||||
initialDescription = "",
|
||||
onCreated,
|
||||
navigateOnCreate = true,
|
||||
}: RaiseComplaintModalProps) {
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const isDeptUser = user?.role === "department_user";
|
||||
|
||||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||||
const [files, setFiles] = useState<File[]>([]);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ["users-lookup"],
|
||||
queryFn: fetchUsersLookup,
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const liveCoverageQuery = useQuery({
|
||||
queryKey: ["asset-coverage", selectedAsset?.id],
|
||||
queryFn: () => assetsApi.coverage(selectedAsset!.id),
|
||||
enabled: open && Boolean(selectedAsset?.id),
|
||||
});
|
||||
const liveCoverage = liveCoverageQuery.data ?? selectedAsset?.coverage ?? null;
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<ComplaintFormValues>({
|
||||
resolver: zodResolver(complaintSchema),
|
||||
defaultValues: {
|
||||
description: "",
|
||||
breakdown_details: "",
|
||||
priority: "non_critical",
|
||||
notes: "",
|
||||
received_by_id: user?.id ? String(user.id) : "",
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setFiles([]);
|
||||
setServerError(null);
|
||||
reset({
|
||||
description: initialDescription,
|
||||
breakdown_details: "",
|
||||
priority: "non_critical",
|
||||
notes: "",
|
||||
received_by_id: user?.id ? String(user.id) : "",
|
||||
});
|
||||
if (initialAssetId) {
|
||||
let cancelled = false;
|
||||
assetsApi
|
||||
.get(initialAssetId)
|
||||
.then((a) => {
|
||||
if (cancelled) return;
|
||||
setSelectedAsset({
|
||||
...a,
|
||||
contract_summary: a.contract_type
|
||||
? `${a.contract_type} (${a.contract_status})`
|
||||
: "None",
|
||||
insurance_summary: a.insurance_status || "None",
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setSelectedAsset(null);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
} else {
|
||||
setSelectedAsset(null);
|
||||
}
|
||||
}, [open, user?.id, initialAssetId, initialDescription, reset]);
|
||||
|
||||
function handleFilePick(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const picked = Array.from(e.target.files ?? []);
|
||||
e.target.value = "";
|
||||
for (const f of picked) {
|
||||
const err = validateAttachmentFile(f);
|
||||
if (err) {
|
||||
setServerError(`${f.name}: ${err}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setServerError(null);
|
||||
setFiles((prev) => [...prev, ...picked]);
|
||||
}
|
||||
|
||||
async function onSubmit(values: ComplaintFormValues) {
|
||||
if (!selectedAsset) {
|
||||
setServerError("Please select an asset first.");
|
||||
return;
|
||||
}
|
||||
setServerError(null);
|
||||
try {
|
||||
const created = await complaintsApi.create({
|
||||
asset_id: selectedAsset.id,
|
||||
description: values.description.trim(),
|
||||
breakdown_details: values.breakdown_details?.trim() || null,
|
||||
priority: values.priority as AssetCriticality,
|
||||
notes: values.notes?.trim() || null,
|
||||
received_by_id: values.received_by_id ? Number(values.received_by_id) : null,
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
await attachmentsApi.upload("complaint", created.id, file);
|
||||
}
|
||||
|
||||
await qc.invalidateQueries({ queryKey: ["complaints"] });
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
if (onCreated) {
|
||||
await onCreated(created);
|
||||
}
|
||||
onClose();
|
||||
if (navigateOnCreate) {
|
||||
navigate(`/complaints/${created.id}`);
|
||||
}
|
||||
} catch (err) {
|
||||
setServerError(err instanceof ApiError ? err.detail : "Failed to register complaint.");
|
||||
}
|
||||
}
|
||||
|
||||
const users = usersQuery.data?.items ?? [];
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Raise Breakdown / Complaint"
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{serverError && (
|
||||
<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>{serverError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Select Asset *</label>
|
||||
<AssetPicker
|
||||
selectedAsset={selectedAsset}
|
||||
onSelect={setSelectedAsset}
|
||||
departmentId={isDeptUser ? user?.department_id ?? undefined : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{selectedAsset && liveCoverage && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md bg-slate-50 border border-slate-200 px-3 py-2 text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-gray-600">Coverage Status:</span>
|
||||
<CoverageBadge coverage={liveCoverage} />
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 text-gray-700">
|
||||
{liveCoverage.provider_name ? (
|
||||
<>
|
||||
<PhoneCall className="h-3.5 w-3.5 text-[#1e3a8a]" />
|
||||
<span>
|
||||
Call: <strong>{liveCoverage.provider_name}</strong>
|
||||
{liveCoverage.provider_contact ? `, ${liveCoverage.provider_contact}` : ""}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-red-700 font-medium">
|
||||
No active contract — Biomedical team / vendor quote needed
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2 rounded-md bg-gray-50 border border-gray-200 px-3 py-2 text-xs text-gray-600">
|
||||
<Clock className="h-4 w-4 text-gray-400 shrink-0" />
|
||||
<span>Registered At: Auto-captured by server on submit</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Priority *</label>
|
||||
<select {...register("priority")} className={inputCls}>
|
||||
<option value="non_critical">Non-Critical</option>
|
||||
<option value="critical">Critical (Emergency / Life Support)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Received By</label>
|
||||
<select {...register("received_by_id")} className={inputCls}>
|
||||
<option value="">Current User</option>
|
||||
{users.map((u) => (
|
||||
<option key={u.id} value={String(u.id)}>
|
||||
{u.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Complaint Description *</label>
|
||||
<textarea
|
||||
{...register("description")}
|
||||
rows={2}
|
||||
placeholder="Brief summary of the breakdown or issue..."
|
||||
className={inputCls}
|
||||
/>
|
||||
{errors.description && (
|
||||
<p className="text-xs text-red-600 mt-1">{errors.description.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Breakdown Details</label>
|
||||
<textarea
|
||||
{...register("breakdown_details")}
|
||||
rows={2}
|
||||
placeholder="Error codes, observed symptoms, clinical impact..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Additional Notes</label>
|
||||
<input
|
||||
{...register("notes")}
|
||||
placeholder="Optional caller contact or bay number..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Multi-file photo/PDF picker */}
|
||||
<div>
|
||||
<label className={labelCls}>Photos / Supporting Documents (Optional)</label>
|
||||
<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 JPG, PNG, or PDF (max 10 MB each)
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept=".jpg,.jpeg,.png,.pdf"
|
||||
onChange={handleFilePick}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
{files.length > 0 && (
|
||||
<ul className="mt-2 space-y-1">
|
||||
{files.map((f, idx) => (
|
||||
<li
|
||||
key={`${f.name}-${idx}`}
|
||||
className="flex items-center justify-between text-xs bg-gray-50 border border-gray-200 rounded px-2.5 py-1.5"
|
||||
>
|
||||
<span className="truncate">{f.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setFiles((prev) => prev.filter((_, i) => i !== idx))}
|
||||
className="text-gray-400 hover:text-red-600 ml-2"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
Submit Complaint
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
import {
|
||||
CheckCircle2,
|
||||
Wrench,
|
||||
AlertTriangle,
|
||||
AlertCircle,
|
||||
Ban,
|
||||
Clock,
|
||||
CalendarClock,
|
||||
ShieldAlert,
|
||||
MinusCircle,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type {
|
||||
AssetStatus,
|
||||
AssetCriticality,
|
||||
CoverageInfo,
|
||||
CoverageStatus,
|
||||
CoverageTag,
|
||||
AlertSeverity,
|
||||
CalibrationStatus,
|
||||
} from "@/api/assets";
|
||||
|
||||
export function AssetStatusBadge({
|
||||
status,
|
||||
className,
|
||||
}: {
|
||||
status: AssetStatus | string;
|
||||
className?: string;
|
||||
}) {
|
||||
const map: Record<string, { label: string; cls: string; dot: string; icon: React.ReactNode }> = {
|
||||
in_service: {
|
||||
label: "In Service",
|
||||
cls: "bg-green-100 text-green-800 border border-green-200",
|
||||
dot: "bg-green-600",
|
||||
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
under_repair: {
|
||||
label: "Under Repair",
|
||||
cls: "bg-red-100 text-red-800 border border-red-200",
|
||||
dot: "bg-red-600",
|
||||
icon: <Wrench className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
out_of_service: {
|
||||
label: "Out of Service",
|
||||
cls: "bg-amber-100 text-amber-800 border border-amber-200",
|
||||
dot: "bg-amber-600",
|
||||
icon: <AlertTriangle className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
condemned: {
|
||||
label: "Condemned",
|
||||
cls: "bg-gray-100 text-gray-700 border border-gray-300",
|
||||
dot: "bg-gray-500",
|
||||
icon: <Ban className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
};
|
||||
|
||||
const cfg = map[status] ?? {
|
||||
label: status,
|
||||
cls: "bg-gray-100 text-gray-700",
|
||||
dot: "bg-gray-500",
|
||||
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 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>
|
||||
);
|
||||
}
|
||||
|
||||
const COVERAGE_TAG_STYLES: Record<string, { label: string; cls: string; dot: string }> = {
|
||||
warranty: {
|
||||
label: "Warranty",
|
||||
cls: "bg-blue-100 text-blue-800 border border-blue-200",
|
||||
dot: "bg-blue-600",
|
||||
},
|
||||
cmc: {
|
||||
label: "CMC",
|
||||
cls: "bg-green-100 text-green-800 border border-green-200",
|
||||
dot: "bg-green-600",
|
||||
},
|
||||
amc: {
|
||||
label: "AMC",
|
||||
cls: "bg-teal-100 text-teal-800 border border-teal-200",
|
||||
dot: "bg-teal-600",
|
||||
},
|
||||
other_contract: {
|
||||
label: "Other Contract",
|
||||
cls: "bg-gray-100 text-gray-700 border border-gray-300",
|
||||
dot: "bg-gray-500",
|
||||
},
|
||||
out_of_contract: {
|
||||
label: "Out of Contract",
|
||||
cls: "bg-red-100 text-red-800 border border-red-200",
|
||||
dot: "bg-red-600",
|
||||
},
|
||||
};
|
||||
|
||||
export function CoverageBadge({
|
||||
coverage,
|
||||
tag,
|
||||
status,
|
||||
severity,
|
||||
prefix,
|
||||
className,
|
||||
}: {
|
||||
coverage?: CoverageInfo | null;
|
||||
tag?: CoverageTag | string | null;
|
||||
status?: CoverageStatus | string;
|
||||
severity?: AlertSeverity | string;
|
||||
prefix?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const effectiveTag = coverage?.tag ?? tag ?? null;
|
||||
if (effectiveTag) {
|
||||
const cfg = COVERAGE_TAG_STYLES[effectiveTag] ?? COVERAGE_TAG_STYLES.out_of_contract;
|
||||
let tooltip = cfg.label;
|
||||
if (coverage?.provider_name) {
|
||||
tooltip = coverage.provider_contact
|
||||
? `Call: ${coverage.provider_name}, ${coverage.provider_contact}`
|
||||
: `Call: ${coverage.provider_name}`;
|
||||
if (coverage.valid_until) {
|
||||
tooltip += ` (Valid until ${coverage.valid_until})`;
|
||||
}
|
||||
} else if (effectiveTag === "out_of_contract") {
|
||||
tooltip = "Out of contract — no active warranty or AMC/CMC";
|
||||
}
|
||||
return (
|
||||
<span
|
||||
title={tooltip}
|
||||
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
|
||||
)}
|
||||
>
|
||||
<span className={cn("h-1.5 w-1.5 rounded-full shrink-0", cfg.dot)} />
|
||||
<span>{prefix ? `${prefix}: ${cfg.label}` : cfg.label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
let cls = "bg-gray-100 text-gray-600 border border-gray-200";
|
||||
let dot = "bg-gray-400";
|
||||
let label = "None";
|
||||
|
||||
if (status === "active") {
|
||||
cls = "bg-green-100 text-green-800 border border-green-200";
|
||||
dot = "bg-green-600";
|
||||
label = "Active";
|
||||
} else if (status === "expiring") {
|
||||
if (severity === "red") {
|
||||
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||
dot = "bg-red-600";
|
||||
} else {
|
||||
cls = "bg-yellow-100 text-yellow-800 border border-yellow-300";
|
||||
dot = "bg-yellow-500";
|
||||
}
|
||||
label = "Expiring";
|
||||
} else if (status === "expired") {
|
||||
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||
dot = "bg-red-600";
|
||||
label = "Expired";
|
||||
}
|
||||
|
||||
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",
|
||||
cls,
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className={cn("h-1.5 w-1.5 rounded-full shrink-0", dot)} />
|
||||
<span>{prefix ? `${prefix}: ${label}` : label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CalibrationBadge({
|
||||
status,
|
||||
severity,
|
||||
className,
|
||||
}: {
|
||||
status: CalibrationStatus | string;
|
||||
severity?: AlertSeverity | string;
|
||||
className?: string;
|
||||
}) {
|
||||
let cls = "bg-gray-100 text-gray-600 border border-gray-200";
|
||||
let icon: React.ReactNode = <MinusCircle className="h-3 w-3 shrink-0" />;
|
||||
let label = "None";
|
||||
|
||||
if (status === "completed") {
|
||||
cls = "bg-green-100 text-green-800 border border-green-200";
|
||||
icon = <CheckCircle2 className="h-3 w-3 shrink-0" />;
|
||||
label = "Completed";
|
||||
} else if (status === "upcoming") {
|
||||
cls = "bg-blue-100 text-blue-800 border border-blue-200";
|
||||
icon = <Clock className="h-3 w-3 shrink-0" />;
|
||||
label = "Upcoming";
|
||||
} else if (status === "due") {
|
||||
cls =
|
||||
severity === "red"
|
||||
? "bg-red-100 text-red-800 border border-red-200"
|
||||
: "bg-yellow-100 text-yellow-800 border border-yellow-300";
|
||||
icon = <AlertTriangle className="h-3 w-3 shrink-0" />;
|
||||
label = "Due";
|
||||
} else if (status === "overdue") {
|
||||
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||
icon = <AlertTriangle className="h-3 w-3 shrink-0" />;
|
||||
label = "Overdue";
|
||||
}
|
||||
|
||||
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",
|
||||
cls,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
<span>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CriticalityBadge({
|
||||
criticality,
|
||||
className,
|
||||
}: {
|
||||
criticality: AssetCriticality | string;
|
||||
className?: string;
|
||||
}) {
|
||||
if (criticality === "critical") {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold border border-red-400 text-red-700 bg-red-50 whitespace-nowrap",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<ShieldAlert className="h-3 w-3 shrink-0" />
|
||||
Critical
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-700 border border-slate-200 whitespace-nowrap",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-slate-500 shrink-0" />
|
||||
Non-Critical
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CallStatusBadge({
|
||||
status,
|
||||
className,
|
||||
}: {
|
||||
status: "open" | "in_progress" | "closed" | string;
|
||||
className?: string;
|
||||
}) {
|
||||
const map: Record<string, { label: string; cls: string; icon: React.ReactNode }> = {
|
||||
open: {
|
||||
label: "Open",
|
||||
cls: "bg-red-100 text-red-800 border border-red-200",
|
||||
icon: <AlertCircle className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
in_progress: {
|
||||
label: "In Progress",
|
||||
cls: "bg-amber-100 text-amber-800 border border-amber-200",
|
||||
icon: <Clock className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
closed: {
|
||||
label: "Closed",
|
||||
cls: "bg-green-100 text-green-800 border border-green-200",
|
||||
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
|
||||
},
|
||||
};
|
||||
|
||||
const cfg = map[status] ?? {
|
||||
label: status,
|
||||
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 ExpiryChip({
|
||||
daysToExpiry,
|
||||
status,
|
||||
severity,
|
||||
className,
|
||||
}: {
|
||||
daysToExpiry: number;
|
||||
status: string;
|
||||
severity?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
if (status === "superseded") {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-gray-100 text-gray-600 border border-gray-300",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<MinusCircle className="h-3 w-3 shrink-0" />
|
||||
Superseded
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "expired" || daysToExpiry < 0) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-red-100 text-red-800 border border-red-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<AlertCircle className="h-3 w-3 shrink-0" />
|
||||
Expired
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "expiring") {
|
||||
const isRed = severity === "red";
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap border",
|
||||
isRed
|
||||
? "bg-red-100 text-red-800 border-red-200"
|
||||
: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Clock className="h-3 w-3 shrink-0" />
|
||||
{daysToExpiry} {daysToExpiry === 1 ? "day" : "days"} left
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-green-100 text-green-800 border border-green-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<CheckCircle2 className="h-3 w-3 shrink-0" />
|
||||
Active
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function DemoStatusBadge({
|
||||
status,
|
||||
daysRemaining,
|
||||
className,
|
||||
}: {
|
||||
status: string;
|
||||
daysRemaining?: number;
|
||||
className?: string;
|
||||
}) {
|
||||
if (status === "returned") {
|
||||
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 bg-green-100 text-green-800 border border-green-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<CheckCircle2 className="h-3 w-3 shrink-0" />
|
||||
Returned
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "overdue_return") {
|
||||
const overdueDays =
|
||||
daysRemaining != null && daysRemaining < 0 ? Math.abs(daysRemaining) : null;
|
||||
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 bg-red-100 text-red-800 border border-red-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<AlertTriangle className="h-3 w-3 shrink-0" />
|
||||
{overdueDays != null ? `Overdue by ${overdueDays}d` : "Overdue Return"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
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 bg-blue-100 text-blue-800 border border-blue-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Clock className="h-3 w-3 shrink-0" />
|
||||
On Demo
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CheckCircle2, Info, AlertTriangle, AlertCircle, X } from "lucide-react";
|
||||
import { useToastStore, type ToastVariant } from "@/lib/toast";
|
||||
|
||||
const VARIANT_CLS: Record<ToastVariant, string> = {
|
||||
success: "bg-emerald-50 border-emerald-300 text-emerald-900",
|
||||
info: "bg-blue-50 border-blue-300 text-blue-900",
|
||||
warning: "bg-amber-50 border-amber-300 text-amber-900",
|
||||
error: "bg-red-50 border-red-300 text-red-900",
|
||||
};
|
||||
|
||||
function VariantIcon({ variant }: { variant: ToastVariant }) {
|
||||
switch (variant) {
|
||||
case "success":
|
||||
return <CheckCircle2 className="h-4 w-4 text-emerald-600 shrink-0 mt-0.5" />;
|
||||
case "warning":
|
||||
return <AlertTriangle className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />;
|
||||
case "error":
|
||||
return <AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />;
|
||||
default:
|
||||
return <Info className="h-4 w-4 text-blue-600 shrink-0 mt-0.5" />;
|
||||
}
|
||||
}
|
||||
|
||||
export function ToastProvider({ children }: { children?: React.ReactNode }) {
|
||||
const { toasts, dismiss } = useToastStore();
|
||||
|
||||
return (
|
||||
<>
|
||||
{children}
|
||||
{toasts.length > 0 && (
|
||||
<div
|
||||
aria-live="polite"
|
||||
className="fixed bottom-4 right-4 z-[60] flex flex-col gap-2 w-full max-w-sm pointer-events-none px-4 sm:px-0"
|
||||
>
|
||||
{toasts.map((t) => (
|
||||
<div
|
||||
key={t.id}
|
||||
className={`pointer-events-auto flex items-start gap-2.5 rounded-lg border p-3.5 shadow-lg transition-all ${VARIANT_CLS[t.variant]}`}
|
||||
>
|
||||
<VariantIcon variant={t.variant} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-xs font-semibold">{t.title}</div>
|
||||
{t.description && (
|
||||
<div className="text-xs opacity-90 mt-0.5">{t.description}</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dismiss(t.id)}
|
||||
aria-label="Dismiss notification"
|
||||
className="p-0.5 rounded hover:bg-black/5 shrink-0"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useState } from "react";
|
||||
import { Outlet } from "react-router-dom";
|
||||
import { Sidebar } from "./Sidebar";
|
||||
import { TopBar } from "./TopBar";
|
||||
import { CalibrationReminderModal } from "@/components/CalibrationReminderModal";
|
||||
|
||||
export function AppShell() {
|
||||
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen bg-gray-50">
|
||||
<Sidebar
|
||||
mobileOpen={mobileNavOpen}
|
||||
onClose={() => setMobileNavOpen(false)}
|
||||
/>
|
||||
<div className="flex-1 flex flex-col min-w-0">
|
||||
<TopBar onMenuClick={() => setMobileNavOpen(true)} />
|
||||
<main className="flex-1 p-3 sm:p-4 lg:p-6 overflow-auto">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
<CalibrationReminderModal />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { NavLink } from "react-router-dom";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Package,
|
||||
AlertCircle,
|
||||
Wrench,
|
||||
FlaskConical,
|
||||
FileText,
|
||||
Shield,
|
||||
Truck,
|
||||
Building2,
|
||||
BarChart3,
|
||||
Bell,
|
||||
Database,
|
||||
History,
|
||||
Settings,
|
||||
ChevronRight,
|
||||
X,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { can, type Capability } from "@/lib/permissions";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
interface NavItem {
|
||||
to: string;
|
||||
label: string;
|
||||
icon: LucideIcon;
|
||||
capability?: Capability;
|
||||
anyCapabilities?: Capability[];
|
||||
}
|
||||
|
||||
const NAV_ITEMS: NavItem[] = [
|
||||
{ to: "/", label: "Dashboard", icon: LayoutDashboard },
|
||||
{ to: "/assets", label: "Assets", icon: Package, capability: "view_assets" },
|
||||
{ to: "/complaints", label: "Complaints", icon: AlertCircle },
|
||||
{ to: "/pm", label: "Preventive Maintenance", icon: Wrench, capability: "view_pm" },
|
||||
{
|
||||
to: "/calibration",
|
||||
label: "Calibration",
|
||||
icon: FlaskConical,
|
||||
capability: "view_calibration_contracts",
|
||||
},
|
||||
{
|
||||
to: "/contracts",
|
||||
label: "Contracts & Warranty",
|
||||
icon: FileText,
|
||||
capability: "view_calibration_contracts",
|
||||
},
|
||||
{
|
||||
to: "/insurance",
|
||||
label: "Insurance",
|
||||
icon: Shield,
|
||||
capability: "view_calibration_contracts",
|
||||
},
|
||||
{
|
||||
to: "/demo-equipment",
|
||||
label: "Demo Equipment",
|
||||
icon: Truck,
|
||||
capability: "view_demo_equipment",
|
||||
},
|
||||
{
|
||||
to: "/visits",
|
||||
label: "Department Visits",
|
||||
icon: Building2,
|
||||
capability: "view_visits",
|
||||
},
|
||||
{
|
||||
to: "/reports",
|
||||
label: "Reports",
|
||||
icon: BarChart3,
|
||||
anyCapabilities: ["view_all_reports", "view_dept_reports"],
|
||||
},
|
||||
{ to: "/notifications", label: "Notifications", icon: Bell },
|
||||
{ to: "/masters", label: "Masters", icon: Database, capability: "manage_admin" },
|
||||
{ to: "/audit-logs", label: "Audit Log", icon: History, capability: "manage_admin" },
|
||||
{ to: "/settings", label: "Settings", icon: Settings, capability: "manage_admin" },
|
||||
];
|
||||
|
||||
interface SidebarProps {
|
||||
mobileOpen?: boolean;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
export function Sidebar({ mobileOpen, onClose }: SidebarProps = {}) {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const role = user?.role;
|
||||
|
||||
const visibleItems = NAV_ITEMS.filter((item) => {
|
||||
if (item.capability) return can(role, item.capability);
|
||||
if (item.anyCapabilities) return item.anyCapabilities.some((c) => can(role, c));
|
||||
return true;
|
||||
});
|
||||
|
||||
const asideContent = (
|
||||
<aside
|
||||
aria-label="Primary Navigation"
|
||||
className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col"
|
||||
>
|
||||
{/* Logo */}
|
||||
<div className="px-4 py-4 border-b border-blue-700 space-y-2 relative">
|
||||
{onClose && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close navigation menu"
|
||||
className="lg:hidden absolute right-2 top-2 p-1 rounded text-blue-200 hover:text-white hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
<div className="bg-white rounded-lg p-2">
|
||||
<img
|
||||
src="/logo.jpg"
|
||||
alt="Poona Hospital and Research Centre"
|
||||
className="w-full h-16 object-contain"
|
||||
/>
|
||||
</div>
|
||||
<div className="text-xs text-blue-200 text-center">
|
||||
Asset Management & Maintenance
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="flex-1 px-2 py-4 space-y-0.5 overflow-y-auto">
|
||||
{visibleItems.map(({ to, label, icon: Icon }) => (
|
||||
<NavLink
|
||||
key={to}
|
||||
to={to}
|
||||
end={to === "/"}
|
||||
onClick={() => onClose?.()}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
"flex items-center gap-3 px-3 py-2.5 rounded-md text-sm transition-colors group focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white",
|
||||
isActive
|
||||
? "bg-blue-700 text-white"
|
||||
: "text-blue-100 hover:bg-blue-700/50 hover:text-white"
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon className="h-4 w-4 shrink-0" />
|
||||
<span className="flex-1 truncate">{label}</span>
|
||||
<ChevronRight className="h-3 w-3 opacity-0 group-hover:opacity-50" />
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-4 py-3 border-t border-blue-700 text-xs text-blue-300">
|
||||
Poona Hospital AMS • v1.0
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
|
||||
// When controlled by AppShell, hide desktop rail on small screens and render slide-over drawer when open
|
||||
if (mobileOpen === undefined) {
|
||||
return asideContent;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="hidden lg:flex shrink-0">{asideContent}</div>
|
||||
{mobileOpen && (
|
||||
<div className="fixed inset-0 z-40 flex lg:hidden">
|
||||
<div
|
||||
className="fixed inset-0 bg-black/40"
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div className="relative z-50 flex">{asideContent}</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
import { useState, useEffect, useRef, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Search,
|
||||
Bell,
|
||||
ChevronDown,
|
||||
User,
|
||||
LogOut,
|
||||
CalendarClock,
|
||||
RotateCcw,
|
||||
Play,
|
||||
CheckCheck,
|
||||
AlertTriangle,
|
||||
Info,
|
||||
Clock,
|
||||
Menu,
|
||||
X,
|
||||
Package,
|
||||
AlertCircle,
|
||||
KeyRound,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatDate, formatRelative } from "@/lib/format";
|
||||
import { ROLE_LABELS } from "@/lib/permissions";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { settingsApi } from "@/api/settings";
|
||||
import { notificationsApi, type NotificationItem } from "@/api/notifications";
|
||||
import { searchApi } from "@/api/search";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { AssetStatusBadge, CallStatusBadge } from "@/components/StatusBadge";
|
||||
import { ChangePasswordModal } from "@/components/ChangePasswordModal";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
interface TopBarProps {
|
||||
title?: string;
|
||||
onMenuClick?: () => void;
|
||||
}
|
||||
|
||||
export function TopBar({ title, onMenuClick }: TopBarProps) {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
||||
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
|
||||
const [bellOpen, setBellOpen] = useState(false);
|
||||
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
|
||||
const [savingDate, setSavingDate] = useState(false);
|
||||
const [runningAlerts, setRunningAlerts] = useState(false);
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
const [debouncedQuery, setDebouncedQuery] = useState("");
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
|
||||
const bellContainerRef = useRef<HTMLDivElement>(null);
|
||||
const searchContainerRef = useRef<HTMLDivElement>(null);
|
||||
const userMenuRef = useRef<HTMLDivElement>(null);
|
||||
const seenIdsRef = useRef<Set<number> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setDateInput(demoAsOfDate ?? "");
|
||||
}, [demoAsOfDate]);
|
||||
|
||||
useEffect(() => {
|
||||
const trimmed = searchInput.trim();
|
||||
if (trimmed.length < 2) {
|
||||
setDebouncedQuery("");
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
setDebouncedQuery(trimmed);
|
||||
}, 200);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [searchInput]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleOutside(e: MouseEvent) {
|
||||
const target = e.target as Node;
|
||||
if (
|
||||
bellContainerRef.current &&
|
||||
!bellContainerRef.current.contains(target)
|
||||
) {
|
||||
setBellOpen(false);
|
||||
}
|
||||
if (
|
||||
searchContainerRef.current &&
|
||||
!searchContainerRef.current.contains(target)
|
||||
) {
|
||||
setSearchOpen(false);
|
||||
}
|
||||
if (userMenuRef.current && !userMenuRef.current.contains(target)) {
|
||||
setMenuOpen(false);
|
||||
}
|
||||
}
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") {
|
||||
setSearchOpen(false);
|
||||
setBellOpen(false);
|
||||
setMenuOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleOutside);
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleOutside);
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const searchQuery = useQuery({
|
||||
queryKey: ["global-search", debouncedQuery, user?.id],
|
||||
queryFn: () => searchApi.query(debouncedQuery),
|
||||
enabled: Boolean(user) && debouncedQuery.length >= 2,
|
||||
staleTime: 10_000,
|
||||
});
|
||||
|
||||
const isAdmin = user?.role === "system_admin";
|
||||
|
||||
const bellQuery = useQuery({
|
||||
queryKey: ["notifications", "bell", user?.id],
|
||||
queryFn: () => notificationsApi.list({ limit: 10 }),
|
||||
enabled: Boolean(user),
|
||||
refetchInterval: 60_000,
|
||||
});
|
||||
|
||||
const bellItems = useMemo(
|
||||
() => bellQuery.data?.items ?? [],
|
||||
[bellQuery.data?.items]
|
||||
);
|
||||
const unreadCount = bellQuery.data?.unread_count ?? 0;
|
||||
|
||||
// Detect newly arrived unread notifications while app is open
|
||||
useEffect(() => {
|
||||
if (!bellQuery.data) return;
|
||||
const currentIds = new Set(bellItems.map((n) => n.id));
|
||||
if (seenIdsRef.current === null) {
|
||||
seenIdsRef.current = currentIds;
|
||||
return;
|
||||
}
|
||||
const newlyArrived = bellItems.filter(
|
||||
(n) => !n.is_read && !seenIdsRef.current!.has(n.id)
|
||||
);
|
||||
for (const n of newlyArrived.slice(0, 2)) {
|
||||
if (n.severity === "red") {
|
||||
toast.error(n.title, n.message);
|
||||
} else if (n.severity === "yellow") {
|
||||
toast.warning(n.title, n.message);
|
||||
} else {
|
||||
toast.info(n.title, n.message);
|
||||
}
|
||||
}
|
||||
seenIdsRef.current = currentIds;
|
||||
}, [bellQuery.data, bellItems]);
|
||||
|
||||
const markReadMutation = useMutation({
|
||||
mutationFn: (id: number) => notificationsApi.markRead(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
},
|
||||
});
|
||||
|
||||
const markAllReadMutation = useMutation({
|
||||
mutationFn: () => notificationsApi.markAllRead(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
toast.success("All notifications marked as read");
|
||||
},
|
||||
});
|
||||
|
||||
async function invalidateDateSensitiveQueries() {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["dashboard"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["pm-records"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["calibration-records"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["contracts"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["warranties"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["insurance"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["demo-equipment"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["assets"] }),
|
||||
queryClient.invalidateQueries(),
|
||||
]);
|
||||
}
|
||||
|
||||
async function handleDemoDateUpdate(newDate: string | null) {
|
||||
setSavingDate(true);
|
||||
try {
|
||||
const res = await settingsApi.setDemoDate(newDate);
|
||||
setDemoAsOfDate(res.demo_as_of_date ?? null);
|
||||
setDateInput(res.demo_as_of_date ?? "");
|
||||
await invalidateDateSensitiveQueries();
|
||||
toast.info(
|
||||
res.demo_as_of_date
|
||||
? `Demo clock set to ${formatDate(res.demo_as_of_date)}`
|
||||
: "Demo clock reset to today"
|
||||
);
|
||||
} finally {
|
||||
setSavingDate(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRunAlertsNow() {
|
||||
setRunningAlerts(true);
|
||||
try {
|
||||
const res = await notificationsApi.runAlertsNow();
|
||||
await queryClient.invalidateQueries({ queryKey: ["notifications"] });
|
||||
await queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
toast.success(
|
||||
`Alert check completed (${formatDate(res.evaluated_today)})`,
|
||||
`${res.created} new alert${res.created === 1 ? "" : "s"} created.`
|
||||
);
|
||||
} catch {
|
||||
toast.error("Failed to run alert check");
|
||||
} finally {
|
||||
setRunningAlerts(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleNotificationClick(n: NotificationItem) {
|
||||
setBellOpen(false);
|
||||
if (!n.is_read) {
|
||||
markReadMutation.mutate(n.id);
|
||||
}
|
||||
if (n.link_url) {
|
||||
navigate(n.link_url);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSignOut() {
|
||||
setMenuOpen(false);
|
||||
logout();
|
||||
navigate("/login", { replace: true });
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-3 sm:px-4 py-2 gap-2 sm:gap-3 sticky top-0 z-10">
|
||||
{/* Mobile/tablet nav toggle */}
|
||||
{onMenuClick && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onMenuClick}
|
||||
aria-label="Open navigation menu"
|
||||
className="lg:hidden p-1.5 rounded-md text-gray-600 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Page title */}
|
||||
{title && (
|
||||
<h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">
|
||||
{title}
|
||||
</h1>
|
||||
)}
|
||||
|
||||
{/* Live Global Quick Search */}
|
||||
<div
|
||||
ref={searchContainerRef}
|
||||
className={cn(
|
||||
"relative order-last lg:order-none w-full lg:w-auto",
|
||||
title ? "lg:w-72" : "lg:flex-1 lg:max-w-md"
|
||||
)}
|
||||
>
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
|
||||
<input
|
||||
type="text"
|
||||
aria-label="Search assets and complaints"
|
||||
value={searchInput}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setSearchInput(val);
|
||||
setSearchOpen(val.trim().length >= 2);
|
||||
}}
|
||||
onFocus={() => {
|
||||
if (searchInput.trim().length >= 2) {
|
||||
setSearchOpen(true);
|
||||
}
|
||||
}}
|
||||
placeholder="Search assets, complaints..."
|
||||
className="w-full pl-9 pr-8 py-1.5 text-sm border border-gray-200 rounded-md bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white"
|
||||
/>
|
||||
{searchInput && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Clear search"
|
||||
onClick={() => {
|
||||
setSearchInput("");
|
||||
setDebouncedQuery("");
|
||||
setSearchOpen(false);
|
||||
}}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-0.5 rounded text-gray-400 hover:text-gray-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{searchOpen && searchInput.trim().length >= 2 && (
|
||||
<div
|
||||
role="listbox"
|
||||
aria-label="Global search results"
|
||||
className="absolute left-0 right-0 mt-1.5 bg-white border border-gray-200 rounded-lg shadow-xl z-30 max-h-96 overflow-y-auto divide-y divide-gray-100"
|
||||
>
|
||||
{searchQuery.isFetching && !searchQuery.data ? (
|
||||
<div className="px-4 py-6 text-center text-xs text-gray-500">
|
||||
Searching assets & complaints...
|
||||
</div>
|
||||
) : searchQuery.isError ? (
|
||||
<div className="px-4 py-5 text-center text-xs text-red-600">
|
||||
Unable to load search results.
|
||||
</div>
|
||||
) : (
|
||||
(() => {
|
||||
const assets = searchQuery.data?.assets ?? [];
|
||||
const complaints = searchQuery.data?.complaints ?? [];
|
||||
if (assets.length === 0 && complaints.length === 0) {
|
||||
return (
|
||||
<div className="px-4 py-6 text-center text-xs text-gray-500">
|
||||
No matching assets or complaints found.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{assets.length > 0 && (
|
||||
<div className="py-1.5">
|
||||
<div className="px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
|
||||
<Package className="h-3.5 w-3.5 text-[#1e3a8a]" />
|
||||
Assets ({assets.length})
|
||||
</div>
|
||||
{assets.map((asset) => (
|
||||
<button
|
||||
key={`asset-${asset.id}`}
|
||||
type="button"
|
||||
role="option"
|
||||
onClick={() => {
|
||||
setSearchOpen(false);
|
||||
navigate(`/assets/${asset.id}`);
|
||||
}}
|
||||
className="w-full text-left px-3 py-2 hover:bg-blue-50/70 focus-visible:outline-none focus-visible:bg-blue-50 flex items-center justify-between gap-2 transition-colors"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs font-semibold text-[#1e3a8a]">
|
||||
{asset.asset_code}
|
||||
</span>
|
||||
<span className="text-xs font-medium text-gray-900 truncate">
|
||||
{asset.name}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[11px] text-gray-500 truncate mt-0.5">
|
||||
{asset.department_name ?? "No Dept"}
|
||||
{asset.serial_no ? ` • SN: ${asset.serial_no}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<AssetStatusBadge status={asset.status} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{complaints.length > 0 && (
|
||||
<div className="py-1.5">
|
||||
<div className="px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
|
||||
<AlertCircle className="h-3.5 w-3.5 text-red-600" />
|
||||
Complaints ({complaints.length})
|
||||
</div>
|
||||
{complaints.map((c) => (
|
||||
<button
|
||||
key={`complaint-${c.id}`}
|
||||
type="button"
|
||||
role="option"
|
||||
onClick={() => {
|
||||
setSearchOpen(false);
|
||||
navigate(`/complaints/${c.id}`);
|
||||
}}
|
||||
className="w-full text-left px-3 py-2 hover:bg-blue-50/70 focus-visible:outline-none focus-visible:bg-blue-50 flex items-center justify-between gap-2 transition-colors"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs font-semibold text-gray-900">
|
||||
{c.complaint_no}
|
||||
</span>
|
||||
<span className="text-xs text-gray-700 truncate">
|
||||
{c.asset_code
|
||||
? `${c.asset_code}${c.asset_name ? ` — ${c.asset_name}` : ""}`
|
||||
: c.asset_name ?? "Equipment"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-[11px] text-gray-500 truncate mt-0.5">
|
||||
{c.department_name ?? "—"} • Priority: {c.priority}
|
||||
</div>
|
||||
</div>
|
||||
<CallStatusBadge status={c.call_status} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})()
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Active Demo Date Pill */}
|
||||
{demoAsOfDate && (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-amber-100 text-amber-800 border border-amber-300">
|
||||
<CalendarClock className="h-3.5 w-3.5" />
|
||||
Demo Date: {formatDate(demoAsOfDate)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Admin Demo Clock Picker + Run Alert Check */}
|
||||
{isAdmin && (
|
||||
<div className="w-full xl:w-auto order-last xl:order-none flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs flex-wrap">
|
||||
<span className="text-gray-500 font-medium hidden md:inline">
|
||||
As of Date:
|
||||
</span>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="As of Date"
|
||||
value={dateInput}
|
||||
onChange={(e) => setDateInput(e.target.value)}
|
||||
className="border border-gray-200 rounded px-1.5 py-0.5 text-xs bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={savingDate || !dateInput}
|
||||
onClick={() => handleDemoDateUpdate(dateInput || null)}
|
||||
className="px-2 py-0.5 rounded bg-[#1e3a8a] text-white hover:bg-[#1e3480] disabled:opacity-40"
|
||||
>
|
||||
Apply
|
||||
</button>
|
||||
{demoAsOfDate && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={savingDate}
|
||||
onClick={() => handleDemoDateUpdate(null)}
|
||||
title="Reset to Today"
|
||||
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-gray-300 bg-white text-gray-600 hover:bg-gray-100 disabled:opacity-40"
|
||||
>
|
||||
<RotateCcw className="h-3 w-3" />
|
||||
<span className="hidden lg:inline">Reset</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={runningAlerts}
|
||||
onClick={handleRunAlertsNow}
|
||||
className="inline-flex items-center gap-1 px-2 py-0.5 rounded border border-blue-300 bg-blue-50 text-[#1e3a8a] hover:bg-blue-100 disabled:opacity-40 font-medium"
|
||||
title="Run alert engine immediately for current effective date"
|
||||
>
|
||||
<Play className="h-3 w-3" />
|
||||
<span>{runningAlerts ? "Running..." : "Run alert check now"}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right utility cluster (Bell + User Menu) */}
|
||||
<div className="ml-auto flex items-center gap-1.5 sm:gap-2">
|
||||
{/* Live Notification Bell & Dropdown */}
|
||||
<div ref={bellContainerRef} className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBellOpen((o) => !o)}
|
||||
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
aria-label="Notifications"
|
||||
aria-expanded={bellOpen}
|
||||
>
|
||||
<Bell className="h-5 w-5" />
|
||||
{unreadCount > 0 && (
|
||||
<span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] px-1 rounded-full bg-red-600 text-white text-[10px] font-bold flex items-center justify-center leading-none">
|
||||
{unreadCount > 99 ? "99+" : unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{bellOpen && (
|
||||
<div className="absolute right-0 mt-1.5 w-80 sm:w-96 bg-white border border-gray-200 rounded-lg shadow-xl z-30 overflow-hidden">
|
||||
<div className="flex items-center justify-between px-3.5 py-2.5 border-b border-gray-100 bg-gray-50">
|
||||
<div className="text-xs font-semibold text-gray-800">
|
||||
Notifications{" "}
|
||||
{unreadCount > 0 && (
|
||||
<span className="ml-1 text-red-600">({unreadCount} unread)</span>
|
||||
)}
|
||||
</div>
|
||||
{unreadCount > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => markAllReadMutation.mutate()}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-medium text-[#1e3a8a] hover:underline"
|
||||
>
|
||||
<CheckCheck className="h-3.5 w-3.5" />
|
||||
Mark all read
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="max-h-80 overflow-y-auto divide-y divide-gray-100">
|
||||
{bellItems.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-gray-400">
|
||||
No notifications yet.
|
||||
</div>
|
||||
) : (
|
||||
bellItems.map((n) => (
|
||||
<button
|
||||
key={n.id}
|
||||
type="button"
|
||||
onClick={() => handleNotificationClick(n)}
|
||||
className={cn(
|
||||
"w-full text-left px-3.5 py-2.5 hover:bg-gray-50 flex items-start gap-2.5 transition-colors",
|
||||
!n.is_read && "bg-blue-50/40"
|
||||
)}
|
||||
>
|
||||
<SeverityIcon severity={n.severity} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
"text-xs truncate",
|
||||
!n.is_read
|
||||
? "font-semibold text-gray-900"
|
||||
: "font-medium text-gray-700"
|
||||
)}
|
||||
>
|
||||
{n.title}
|
||||
</span>
|
||||
{!n.is_read && (
|
||||
<span className="h-2 w-2 rounded-full bg-blue-600 shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
<p className="text-[11px] text-gray-600 line-clamp-2 mt-0.5">
|
||||
{n.message}
|
||||
</p>
|
||||
<div className="text-[10px] text-gray-400 mt-1">
|
||||
{formatRelative(n.created_at)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="px-3.5 py-2 border-t border-gray-100 bg-gray-50 text-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setBellOpen(false);
|
||||
navigate("/notifications");
|
||||
}}
|
||||
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||
>
|
||||
View all notifications →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* User menu */}
|
||||
<div ref={userMenuRef} className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMenuOpen((o) => !o)}
|
||||
aria-label="User menu"
|
||||
aria-expanded={menuOpen}
|
||||
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<div className="h-7 w-7 rounded-full bg-[#1e3a8a] flex items-center justify-center text-white text-xs font-bold shrink-0">
|
||||
<User className="h-4 w-4" />
|
||||
</div>
|
||||
<div className="hidden sm:flex flex-col items-start leading-tight">
|
||||
<span className="font-medium text-gray-800 text-xs">
|
||||
{user?.name ?? "User"}
|
||||
</span>
|
||||
<span className="text-[10px] text-gray-500">
|
||||
{user?.role ? ROLE_LABELS[user.role] : ""}
|
||||
{user?.department_name ? ` • ${user.department_name}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className="h-4 w-4 text-gray-400" />
|
||||
</button>
|
||||
|
||||
{menuOpen && (
|
||||
<div className="absolute right-0 mt-1 w-60 bg-white border border-gray-200 rounded-md shadow-lg z-30 py-2">
|
||||
<div className="px-3 py-2 border-b border-gray-100 space-y-1">
|
||||
<div className="text-sm font-medium text-gray-900 truncate">
|
||||
{user?.name}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 truncate">{user?.email}</div>
|
||||
<div className="flex items-center gap-1.5 flex-wrap pt-0.5">
|
||||
{user?.role && (
|
||||
<Badge variant="info">{ROLE_LABELS[user.role]}</Badge>
|
||||
)}
|
||||
{user?.department_name && (
|
||||
<Badge variant="outline">{user.department_name}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMenuOpen(false);
|
||||
setChangePasswordOpen(true);
|
||||
}}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 text-left"
|
||||
>
|
||||
<KeyRound className="h-4 w-4 text-gray-500" />
|
||||
Change Password
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSignOut}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50 text-left"
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
Sign Out
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<ChangePasswordModal
|
||||
open={changePasswordOpen}
|
||||
onClose={() => setChangePasswordOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SeverityIcon({ severity }: { severity: string }) {
|
||||
if (severity === "red") {
|
||||
return <AlertTriangle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />;
|
||||
}
|
||||
if (severity === "yellow") {
|
||||
return <Clock className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />;
|
||||
}
|
||||
return <Info className="h-4 w-4 text-blue-600 shrink-0 mt-0.5" />;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface BadgeProps {
|
||||
variant?: "default" | "success" | "warning" | "danger" | "info" | "outline";
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const variantClasses = {
|
||||
default: "bg-gray-100 text-gray-800",
|
||||
success: "bg-green-100 text-green-800",
|
||||
warning: "bg-yellow-100 text-yellow-800",
|
||||
danger: "bg-red-100 text-red-800",
|
||||
info: "bg-blue-100 text-blue-800",
|
||||
outline: "border border-gray-300 text-gray-700 bg-white",
|
||||
};
|
||||
|
||||
export function Badge({ variant = "default", className, children }: BadgeProps) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",
|
||||
variantClasses[variant],
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ButtonHTMLAttributes, forwardRef } from "react";
|
||||
|
||||
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: "default" | "outline" | "ghost" | "danger" | "success";
|
||||
size?: "sm" | "md" | "lg";
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
const variantClasses = {
|
||||
default: "bg-[#1e3a8a] text-white hover:bg-[#1e3480] focus:ring-blue-500",
|
||||
outline: "border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 focus:ring-blue-500",
|
||||
ghost: "text-gray-600 hover:bg-gray-100 focus:ring-gray-400",
|
||||
danger: "bg-red-600 text-white hover:bg-red-700 focus:ring-red-500",
|
||||
success: "bg-green-600 text-white hover:bg-green-700 focus:ring-green-500",
|
||||
};
|
||||
|
||||
const sizeClasses = {
|
||||
sm: "px-3 py-1.5 text-sm",
|
||||
md: "px-4 py-2 text-sm",
|
||||
lg: "px-6 py-3 text-base",
|
||||
};
|
||||
|
||||
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ variant = "default", size = "md", loading, className, children, disabled, ...props }, ref) => (
|
||||
<button
|
||||
ref={ref}
|
||||
disabled={disabled || loading}
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center rounded-md font-medium transition-colors",
|
||||
"focus:outline-none focus:ring-2 focus:ring-offset-1",
|
||||
"disabled:opacity-50 disabled:cursor-not-allowed",
|
||||
variantClasses[variant],
|
||||
sizeClasses[size],
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{loading && (
|
||||
<svg className="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
)}
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
);
|
||||
Button.displayName = "Button";
|
||||
@@ -0,0 +1,55 @@
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { X } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
description?: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Modal({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
className,
|
||||
}: ModalProps) {
|
||||
return (
|
||||
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPrimitive.Portal>
|
||||
<DialogPrimitive.Overlay className="fixed inset-0 z-40 bg-black/40 backdrop-blur-[1px]" />
|
||||
<DialogPrimitive.Content
|
||||
className={cn(
|
||||
"fixed left-1/2 top-1/2 z-50 w-[95vw] sm:w-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-4 sm:p-6 shadow-xl border border-gray-200 max-h-[90vh] overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4 mb-4">
|
||||
<div>
|
||||
<DialogPrimitive.Title className="text-lg font-semibold text-gray-900">
|
||||
{title}
|
||||
</DialogPrimitive.Title>
|
||||
{description && (
|
||||
<DialogPrimitive.Description className="text-sm text-gray-500 mt-0.5">
|
||||
{description}
|
||||
</DialogPrimitive.Description>
|
||||
)}
|
||||
</div>
|
||||
<DialogPrimitive.Close
|
||||
aria-label="Close"
|
||||
className="rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</DialogPrimitive.Close>
|
||||
</div>
|
||||
{children}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPrimitive.Portal>
|
||||
</DialogPrimitive.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { create } from "zustand";
|
||||
import { fetchMeApi, type UserOut } from "@/api/auth";
|
||||
import { setUnauthorizedHandler } from "@/api/client";
|
||||
|
||||
interface AuthState {
|
||||
user: UserOut | null;
|
||||
token: string | null;
|
||||
demoAsOfDate: string | null;
|
||||
hydrating: boolean;
|
||||
setAuth: (user: UserOut, token: string) => void;
|
||||
setToken: (token: string) => void;
|
||||
setDemoAsOfDate: (date: string | null) => void;
|
||||
hydrate: () => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const initialToken = sessionStorage.getItem("access_token");
|
||||
|
||||
export const useAuthStore = create<AuthState>((set, get) => ({
|
||||
user: null,
|
||||
token: initialToken,
|
||||
demoAsOfDate: null,
|
||||
hydrating: Boolean(initialToken),
|
||||
|
||||
setAuth: (user, token) => {
|
||||
sessionStorage.setItem("access_token", token);
|
||||
set({
|
||||
user,
|
||||
token,
|
||||
demoAsOfDate: user.demo_as_of_date ?? null,
|
||||
hydrating: false,
|
||||
});
|
||||
},
|
||||
|
||||
setToken: (token) => {
|
||||
sessionStorage.setItem("access_token", token);
|
||||
set({ token });
|
||||
},
|
||||
|
||||
setDemoAsOfDate: (date) => {
|
||||
set((state) => ({
|
||||
demoAsOfDate: date || null,
|
||||
user: state.user ? { ...state.user, demo_as_of_date: date || null } : null,
|
||||
}));
|
||||
},
|
||||
|
||||
hydrate: async () => {
|
||||
const token = get().token ?? sessionStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
set({ user: null, token: null, demoAsOfDate: null, hydrating: false });
|
||||
return;
|
||||
}
|
||||
set({ hydrating: true });
|
||||
try {
|
||||
const user = await fetchMeApi();
|
||||
set({
|
||||
user,
|
||||
token,
|
||||
demoAsOfDate: user.demo_as_of_date ?? null,
|
||||
hydrating: false,
|
||||
});
|
||||
} catch {
|
||||
sessionStorage.removeItem("access_token");
|
||||
set({ user: null, token: null, demoAsOfDate: null, hydrating: false });
|
||||
}
|
||||
},
|
||||
|
||||
logout: () => {
|
||||
sessionStorage.removeItem("access_token");
|
||||
set({ user: null, token: null, demoAsOfDate: null, hydrating: false });
|
||||
},
|
||||
}));
|
||||
|
||||
setUnauthorizedHandler(() => {
|
||||
useAuthStore.getState().logout();
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--brand: #1e3a8a;
|
||||
}
|
||||
body {
|
||||
@apply bg-gray-50 text-gray-900 antialiased;
|
||||
}
|
||||
}
|
||||
|
||||
@media screen {
|
||||
.print-only {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media print {
|
||||
@page {
|
||||
size: A4 landscape;
|
||||
margin: 8mm 10mm;
|
||||
}
|
||||
|
||||
aside,
|
||||
header,
|
||||
nav,
|
||||
.no-print {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.print-only {
|
||||
display: block !important;
|
||||
}
|
||||
|
||||
body {
|
||||
background: #ffffff !important;
|
||||
color: #0f172a !important;
|
||||
-webkit-print-color-adjust: exact !important;
|
||||
print-color-adjust: exact !important;
|
||||
font-size: 10px !important;
|
||||
line-height: 1.35 !important;
|
||||
}
|
||||
|
||||
main {
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
overflow: visible !important;
|
||||
max-width: 100% !important;
|
||||
}
|
||||
|
||||
/* Prevent elements from breaking across PDF pages */
|
||||
.print-break-inside-avoid {
|
||||
break-inside: avoid !important;
|
||||
page-break-inside: avoid !important;
|
||||
}
|
||||
|
||||
.print-break-before {
|
||||
break-before: page !important;
|
||||
page-break-before: always !important;
|
||||
}
|
||||
|
||||
/* Clean up card shadows and borders for crisp PDF generation */
|
||||
.shadow-sm,
|
||||
.shadow,
|
||||
.shadow-md,
|
||||
.shadow-lg {
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
/* High-fidelity PDF Table Styling */
|
||||
table {
|
||||
border-collapse: collapse !important;
|
||||
width: 100% !important;
|
||||
page-break-inside: auto;
|
||||
}
|
||||
|
||||
thead {
|
||||
display: table-header-group !important;
|
||||
}
|
||||
|
||||
tfoot {
|
||||
display: table-footer-group !important;
|
||||
}
|
||||
|
||||
tr {
|
||||
page-break-inside: avoid !important;
|
||||
break-inside: avoid !important;
|
||||
}
|
||||
|
||||
th {
|
||||
background-color: #1e3a8a !important;
|
||||
color: #ffffff !important;
|
||||
font-weight: 600 !important;
|
||||
font-size: 9.5px !important;
|
||||
padding: 5px 6px !important;
|
||||
border: 1px solid #1e293b !important;
|
||||
text-align: center !important;
|
||||
}
|
||||
|
||||
td {
|
||||
border: 1px solid #cbd5e1 !important;
|
||||
font-size: 9px !important;
|
||||
padding: 4px 6px !important;
|
||||
color: #0f172a !important;
|
||||
}
|
||||
|
||||
tbody tr:nth-child(even) td {
|
||||
background-color: #f8fafc !important;
|
||||
}
|
||||
|
||||
/* Force chart svg visibility */
|
||||
.recharts-wrapper {
|
||||
margin: 0 auto !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { format, formatDistanceToNow } from "date-fns";
|
||||
import { toZonedTime } from "date-fns-tz";
|
||||
|
||||
// Kolkata offset: +05:30
|
||||
const KOLKATA_TZ = "Asia/Kolkata";
|
||||
|
||||
export function formatDateTime(isoString: string | null | undefined): string {
|
||||
if (!isoString) return "—";
|
||||
try {
|
||||
const d = toZonedTime(new Date(isoString), KOLKATA_TZ);
|
||||
return format(d, "dd-MMM-yyyy HH:mm");
|
||||
} catch {
|
||||
return "—";
|
||||
}
|
||||
}
|
||||
|
||||
export function formatDate(isoString: string | null | undefined): string {
|
||||
if (!isoString) return "—";
|
||||
try {
|
||||
const d = toZonedTime(new Date(isoString), KOLKATA_TZ);
|
||||
return format(d, "dd-MMM-yyyy");
|
||||
} catch {
|
||||
return "—";
|
||||
}
|
||||
}
|
||||
|
||||
export function formatDuration(minutes: number | null | undefined): string {
|
||||
if (minutes == null) return "—";
|
||||
const d = Math.floor(minutes / 1440);
|
||||
const h = Math.floor((minutes % 1440) / 60);
|
||||
const m = minutes % 60;
|
||||
const parts: string[] = [];
|
||||
if (d) parts.push(`${d}d`);
|
||||
if (h) parts.push(`${h}h`);
|
||||
if (m || !parts.length) parts.push(`${m}m`);
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
export function formatINR(amount: number | null | undefined): string {
|
||||
if (amount == null) return "—";
|
||||
return new Intl.NumberFormat("en-IN", {
|
||||
style: "currency",
|
||||
currency: "INR",
|
||||
maximumFractionDigits: 0,
|
||||
}).format(amount);
|
||||
}
|
||||
|
||||
export function formatRelative(isoString: string | null | undefined): string {
|
||||
if (!isoString) return "—";
|
||||
try {
|
||||
return formatDistanceToNow(new Date(isoString), { addSuffix: true });
|
||||
} catch {
|
||||
return "—";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
export type Role =
|
||||
| "system_admin"
|
||||
| "biomedical"
|
||||
| "department_user"
|
||||
| "management"
|
||||
| "coordinator";
|
||||
|
||||
export type Capability =
|
||||
| "manage_admin"
|
||||
| "create_edit_assets"
|
||||
| "edit_asset_contracts_only"
|
||||
| "view_assets"
|
||||
| "raise_complaint"
|
||||
| "handle_complaint"
|
||||
| "edit_technical_fields"
|
||||
| "manage_pm"
|
||||
| "view_pm"
|
||||
| "manage_calibration_contracts"
|
||||
| "view_calibration_contracts"
|
||||
| "manage_demo_equipment"
|
||||
| "view_demo_equipment"
|
||||
| "manage_visits"
|
||||
| "view_visits"
|
||||
| "view_all_reports"
|
||||
| "view_dept_reports"
|
||||
| "view_ai_reports"
|
||||
| "view_costs";
|
||||
|
||||
export const ROLE_LABELS: Record<Role, string> = {
|
||||
system_admin: "System Administrator",
|
||||
biomedical: "Biomedical / Maintenance",
|
||||
department_user: "Department User",
|
||||
management: "Management",
|
||||
coordinator: "Coordinator",
|
||||
};
|
||||
|
||||
const ROLE_CAPABILITIES: Record<Role, ReadonlySet<Capability>> = {
|
||||
system_admin: new Set<Capability>([
|
||||
"manage_admin",
|
||||
"create_edit_assets",
|
||||
"edit_asset_contracts_only",
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"handle_complaint",
|
||||
"edit_technical_fields",
|
||||
"manage_pm",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"manage_visits",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
]),
|
||||
biomedical: new Set<Capability>([
|
||||
"create_edit_assets",
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"handle_complaint",
|
||||
"edit_technical_fields",
|
||||
"manage_pm",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"manage_visits",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
]),
|
||||
department_user: new Set<Capability>([
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"view_pm",
|
||||
"view_calibration_contracts",
|
||||
"view_demo_equipment",
|
||||
"view_dept_reports",
|
||||
]),
|
||||
management: new Set<Capability>([
|
||||
"view_assets",
|
||||
"view_pm",
|
||||
"view_calibration_contracts",
|
||||
"view_demo_equipment",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
]),
|
||||
coordinator: new Set<Capability>([
|
||||
"edit_asset_contracts_only",
|
||||
"view_assets",
|
||||
"handle_complaint",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
]),
|
||||
};
|
||||
|
||||
export function can(role: Role | undefined | null, capability: Capability | string): boolean {
|
||||
if (!role) return false;
|
||||
const caps = ROLE_CAPABILITIES[role];
|
||||
if (!caps) return false;
|
||||
return caps.has(capability as Capability);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
export type ToastVariant = "success" | "info" | "warning" | "error";
|
||||
|
||||
export interface ToastEntry {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
variant: ToastVariant;
|
||||
}
|
||||
|
||||
interface ToastState {
|
||||
toasts: ToastEntry[];
|
||||
push: (t: Omit<ToastEntry, "id">) => void;
|
||||
dismiss: (id: string) => void;
|
||||
}
|
||||
|
||||
export const useToastStore = create<ToastState>((set) => ({
|
||||
toasts: [],
|
||||
push: (entry) => {
|
||||
const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
set((s) => ({ toasts: [...s.toasts.slice(-4), { ...entry, id }] }));
|
||||
setTimeout(() => {
|
||||
set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) }));
|
||||
}, 5000);
|
||||
},
|
||||
dismiss: (id) =>
|
||||
set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
|
||||
}));
|
||||
|
||||
export const toast = {
|
||||
success: (title: string, description?: string) =>
|
||||
useToastStore.getState().push({ title, description, variant: "success" }),
|
||||
info: (title: string, description?: string) =>
|
||||
useToastStore.getState().push({ title, description, variant: "info" }),
|
||||
warning: (title: string, description?: string) =>
|
||||
useToastStore.getState().push({ title, description, variant: "warning" }),
|
||||
error: (title: string, description?: string) =>
|
||||
useToastStore.getState().push({ title, description, variant: "error" }),
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
const MAX_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
|
||||
const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".pdf"];
|
||||
const ALLOWED_MIME_TYPES = ["image/jpeg", "image/png", "application/pdf"];
|
||||
|
||||
export function validateAttachmentFile(file: File): string | null {
|
||||
const nameLower = file.name.toLowerCase();
|
||||
const hasAllowedExt = ALLOWED_EXTENSIONS.some((ext) => nameLower.endsWith(ext));
|
||||
const hasAllowedMime = !file.type || ALLOWED_MIME_TYPES.includes(file.type);
|
||||
|
||||
if (!hasAllowedExt || !hasAllowedMime) {
|
||||
return "Invalid file type. Only JPG, PNG, and PDF files are allowed.";
|
||||
}
|
||||
if (file.size > MAX_SIZE_BYTES) {
|
||||
return "File is too large. Maximum allowed size is 10 MB.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import App from "./App";
|
||||
import "./index.css";
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { ShieldAlert } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function AccessDeniedPage() {
|
||||
return (
|
||||
<div className="max-w-md mx-auto mt-16 text-center bg-white border border-gray-200 rounded-xl p-8 shadow-sm">
|
||||
<div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-red-50 text-red-600 mb-4">
|
||||
<ShieldAlert className="h-7 w-7" />
|
||||
</div>
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-2">Access Denied</h2>
|
||||
<p className="text-sm text-gray-500 mb-6">
|
||||
Your role does not have permission to access this page.
|
||||
</p>
|
||||
<Link to="/">
|
||||
<Button variant="default">Return to Dashboard</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,702 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, Link } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
ArrowLeft,
|
||||
Pencil,
|
||||
ShieldCheck,
|
||||
Ban,
|
||||
AlertCircle,
|
||||
Plus,
|
||||
} from "lucide-react";
|
||||
import { assetsApi } from "@/api/assets";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate, formatDateTime, formatINR } from "@/lib/format";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
AssetStatusBadge,
|
||||
CoverageBadge,
|
||||
CalibrationBadge,
|
||||
CriticalityBadge,
|
||||
ScheduleStatusBadge,
|
||||
} from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { AssetFormModal } from "@/components/AssetFormModal";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import {
|
||||
NewPMScheduleModal,
|
||||
CompletePMModal,
|
||||
ReschedulePMModal,
|
||||
} from "@/components/PMModals";
|
||||
import {
|
||||
AddSingleCalibrationPlanModal,
|
||||
ApproveCalibrationPlanModal,
|
||||
} from "@/components/CalibrationModals";
|
||||
|
||||
type DetailTab =
|
||||
| "overview"
|
||||
| "warranty"
|
||||
| "contracts"
|
||||
| "insurance"
|
||||
| "calibration"
|
||||
| "pm"
|
||||
| "breakdowns"
|
||||
| "documents";
|
||||
|
||||
const DETAIL_TABS: { key: DetailTab; label: string }[] = [
|
||||
{ key: "overview", label: "Overview" },
|
||||
{ key: "warranty", label: "Warranty" },
|
||||
{ key: "contracts", label: "AMC/CMC" },
|
||||
{ key: "insurance", label: "Insurance" },
|
||||
{ key: "calibration", label: "Calibration" },
|
||||
{ key: "pm", label: "Preventive Maintenance" },
|
||||
{ key: "breakdowns", label: "Breakdowns" },
|
||||
{ key: "documents", label: "Documents" },
|
||||
];
|
||||
|
||||
export function AssetDetailPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const assetId = Number(id);
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
|
||||
const [activeTab, setActiveTab] = useState<DetailTab>("overview");
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [insuranceDrawerOpen, setInsuranceDrawerOpen] = 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 canViewCosts = can(role, "view_costs");
|
||||
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],
|
||||
queryFn: () => assetsApi.overview(assetId),
|
||||
enabled: Number.isFinite(assetId) && assetId > 0,
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="h-8 w-40 bg-gray-200 rounded animate-pulse" />
|
||||
<div className="h-40 bg-white border border-gray-200 rounded-lg animate-pulse" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className="max-w-lg mx-auto mt-10 bg-white border border-red-200 rounded-lg p-6 text-center space-y-3">
|
||||
<AlertCircle className="h-8 w-8 text-red-500 mx-auto" />
|
||||
<h2 className="text-lg font-semibold text-gray-900">Unable to load asset</h2>
|
||||
<p className="text-sm text-red-600">
|
||||
{error instanceof ApiError ? error.detail : "Asset not found or access denied."}
|
||||
</p>
|
||||
<Link to="/assets">
|
||||
<Button variant="outline">Back to Assets</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
asset,
|
||||
warranties,
|
||||
contracts,
|
||||
insurance_policies,
|
||||
calibration_plan,
|
||||
calibration_records,
|
||||
pm_schedules,
|
||||
pm_records,
|
||||
complaints,
|
||||
} = data;
|
||||
|
||||
const isUnderWarranty =
|
||||
asset.warranty_status === "active" || asset.warranty_status === "expiring";
|
||||
const isCondemned = asset.status === "condemned";
|
||||
const openComplaintsCount = complaints.filter((c) => c.call_status !== "closed").length;
|
||||
const latestPm = pm_records[0];
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<Link
|
||||
to="/assets"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-800"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to Asset Register
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Header Card */}
|
||||
<div className="bg-white rounded-xl border border-gray-200 p-5 sm:p-6 shadow-sm space-y-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-2.5 flex-wrap">
|
||||
<span className="font-mono text-sm font-bold px-2.5 py-0.5 rounded bg-blue-50 text-[#1e3a8a] border border-blue-200">
|
||||
{asset.asset_code}
|
||||
</span>
|
||||
<AssetStatusBadge status={asset.status} />
|
||||
<CriticalityBadge criticality={asset.criticality} />
|
||||
<CoverageBadge
|
||||
coverage={data.coverage ?? asset.coverage}
|
||||
tag={data.coverage?.tag ?? asset.coverage_tag}
|
||||
/>
|
||||
{isUnderWarranty && (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800 border border-emerald-300">
|
||||
<ShieldCheck className="h-3.5 w-3.5" />
|
||||
Under Warranty
|
||||
</span>
|
||||
)}
|
||||
{isCondemned && (
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-300">
|
||||
<Ban className="h-3.5 w-3.5" />
|
||||
Condemned
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">{asset.name}</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
{asset.department_name || "—"} • {asset.location_name || "—"}
|
||||
{asset.serial_no ? ` • Serial: ${asset.serial_no}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" onClick={() => setInsuranceDrawerOpen(true)}>
|
||||
<ShieldCheck className="h-4 w-4 mr-1.5" />
|
||||
View Insurance
|
||||
</Button>
|
||||
{canEdit && (
|
||||
<Button variant="outline" onClick={() => setEditOpen(true)}>
|
||||
<Pencil className="h-4 w-4 mr-1.5" />
|
||||
Edit Asset
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 pt-3 border-t border-gray-100 text-sm">
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">Category</div>
|
||||
<div className="font-medium text-gray-900">{asset.category_name || "—"}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">Supplier</div>
|
||||
<div className="font-medium text-gray-900">{asset.supplier_name || "—"}</div>
|
||||
</div>
|
||||
{canViewCosts && (
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{asset.acquisition_mode === "rented" ? "Monthly Rent" : "Purchase Value"}
|
||||
</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{asset.acquisition_mode === "rented"
|
||||
? `${formatINR(asset.monthly_rent)} / mo (Rented)`
|
||||
: formatINR(asset.purchase_value)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">Purchase / Installed</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatDate(asset.purchase_date)} / {formatDate(asset.installation_date)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="border-b border-gray-200 flex gap-1 overflow-x-auto">
|
||||
{DETAIL_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab.key)}
|
||||
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
|
||||
activeTab === tab.key
|
||||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Tab Content */}
|
||||
{activeTab === "overview" && (
|
||||
<div className="space-y-5">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||
<div className="text-xs font-medium text-gray-500">Warranty</div>
|
||||
<div>
|
||||
<CoverageBadge status={asset.warranty_status} severity={asset.warranty_severity} />
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
Ends: {formatDate(asset.warranty_end_date)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||
<div className="text-xs font-medium text-gray-500">AMC / CMC Contract</div>
|
||||
<div>
|
||||
<CoverageBadge
|
||||
status={asset.contract_status}
|
||||
severity={asset.contract_severity}
|
||||
prefix={asset.contract_type ?? undefined}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
Ends: {formatDate(asset.contract_end_date)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||
<div className="text-xs font-medium text-gray-500">Insurance</div>
|
||||
<div>
|
||||
<CoverageBadge status={asset.insurance_status} />
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
{asset.insurance_applicable
|
||||
? `Ends: ${formatDate(asset.insurance_end_date)}`
|
||||
: "Not applicable"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||
<div className="text-xs font-medium text-gray-500">Calibration</div>
|
||||
<div>
|
||||
<CalibrationBadge
|
||||
status={asset.calibration_status}
|
||||
severity={asset.calibration_severity}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
{asset.requires_calibration
|
||||
? `Next due: ${formatDate(asset.calibration_due_date)}`
|
||||
: "Not required"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||
<div className="text-xs font-medium text-gray-500">Latest PM</div>
|
||||
<div className="text-sm font-semibold text-gray-900">
|
||||
{latestPm ? latestPm.status : "No PM records"}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
{latestPm
|
||||
? latestPm.completed_date
|
||||
? `Completed: ${formatDate(latestPm.completed_date)}`
|
||||
: `Planned: ${formatDate(latestPm.planned_date)}`
|
||||
: `${pm_schedules.length} schedule(s)`}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||
<div className="text-xs font-medium text-gray-500">Breakdowns</div>
|
||||
<div className="text-sm font-semibold text-gray-900">
|
||||
{openComplaintsCount} open / {complaints.length} total
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">Click Breakdowns tab for full history</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-5 space-y-3">
|
||||
<h3 className="text-sm font-semibold text-gray-800">Full Asset Metadata</h3>
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm">
|
||||
<div>
|
||||
<dt className="text-xs text-gray-500">Asset Code</dt>
|
||||
<dd className="font-mono text-gray-900">{asset.asset_code}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs text-gray-500">Serial Number</dt>
|
||||
<dd className="font-mono text-gray-900">{asset.serial_no || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs text-gray-500">Requires Calibration</dt>
|
||||
<dd className="text-gray-900">{asset.requires_calibration ? "Yes" : "No"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs text-gray-500">Insurance Applicable</dt>
|
||||
<dd className="text-gray-900">{asset.insurance_applicable ? "Yes" : "No"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs text-gray-500">Created At</dt>
|
||||
<dd className="text-gray-900">{formatDateTime(asset.created_at)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-xs text-gray-500">Last Updated</dt>
|
||||
<dd className="text-gray-900">{formatDateTime(asset.updated_at)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">Remarks</div>
|
||||
<div className="text-sm text-gray-800 mt-0.5 whitespace-pre-wrap">
|
||||
{asset.remarks || "No remarks."}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === "warranty" && (
|
||||
<SimpleTable
|
||||
emptyText="No warranty records for this asset."
|
||||
headers={["Start Date", "End Date", "Duration", "Provider", "Status", "Remarks"]}
|
||||
rows={warranties.map((w) => [
|
||||
formatDate(w.start_date),
|
||||
formatDate(w.end_date),
|
||||
`${w.duration_months} months`,
|
||||
w.provider_name || "—",
|
||||
<CoverageBadge key="st" status={w.status} severity={w.severity} />,
|
||||
w.remarks || "—",
|
||||
])}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === "contracts" && (
|
||||
<SimpleTable
|
||||
emptyText="No AMC/CMC contracts for this asset."
|
||||
headers={["Type", "Provider", "Start Date", "End Date", "Coverage Period", "History / Status", "Remarks"]}
|
||||
rows={contracts.map((c) => [
|
||||
<Badge key="t" variant="info">{c.contract_type}</Badge>,
|
||||
c.provider_name || `Provider #${c.provider_id}`,
|
||||
formatDate(c.start_date),
|
||||
formatDate(c.end_date),
|
||||
c.coverage_period_text || "—",
|
||||
c.is_superseded ? (
|
||||
<Badge key="s" variant="outline">Superseded</Badge>
|
||||
) : (
|
||||
<CoverageBadge key="s" status={c.status} severity={c.severity} />
|
||||
),
|
||||
c.remarks || "—",
|
||||
])}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === "insurance" && (
|
||||
<SimpleTable
|
||||
emptyText="No insurance policies for this asset."
|
||||
headers={["Policy No", "Insurer", "Start Date", "End Date", "Coverage Amount", "Status", "Remarks"]}
|
||||
rows={insurance_policies.map((p) => [
|
||||
<span key="pn" className="font-mono">{p.policy_no}</span>,
|
||||
p.insurer_name || `Insurer #${p.insurer_id}`,
|
||||
formatDate(p.start_date),
|
||||
formatDate(p.end_date),
|
||||
formatINR(p.coverage_amount),
|
||||
<CoverageBadge key="st" status={p.status} severity={p.severity} />,
|
||||
p.remarks || "—",
|
||||
])}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === "calibration" && (
|
||||
<div className="space-y-4">
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4">
|
||||
<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>
|
||||
<div className="text-xs text-gray-500">Frequency</div>
|
||||
<div className="font-medium">
|
||||
{calibration_plan.frequency_months} months ({calibration_plan.calibrations_per_year}/yr)
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">Agency</div>
|
||||
<div className="font-medium">{calibration_plan.agency_name || "—"}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">Approved On</div>
|
||||
<div className="font-medium">{formatDate(calibration_plan.approved_on)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">Next Due</div>
|
||||
<div className="font-medium">{formatDate(calibration_plan.next_due_date)}</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-400">No calibration plan configured.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SimpleTable
|
||||
emptyText="No calibration records yet."
|
||||
headers={["Due Date", "Completed Date", "Agency", "Certificate No", "Status", "Remarks"]}
|
||||
rows={calibration_records.map((r) => [
|
||||
formatDate(r.due_date),
|
||||
formatDate(r.completed_date),
|
||||
r.agency_name || "—",
|
||||
r.certificate_no || "—",
|
||||
<CalibrationBadge key="st" status={r.status} severity={r.severity} />,
|
||||
r.remarks || "—",
|
||||
])}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === "pm" && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<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"]}
|
||||
rows={pm_schedules.map((s) => [
|
||||
`${s.frequency_months} months`,
|
||||
s.service_mode,
|
||||
s.provider_name || s.responsible_team || "—",
|
||||
formatDate(s.next_planned_date),
|
||||
<Badge key="a" variant={s.is_active ? "success" : "outline"}>
|
||||
{s.is_active ? "Active" : "Inactive"}
|
||||
</Badge>,
|
||||
])}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-gray-800 mb-2">Recent PM Records</h3>
|
||||
<SimpleTable
|
||||
emptyText="No PM records yet."
|
||||
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>
|
||||
)}
|
||||
|
||||
{activeTab === "breakdowns" && (
|
||||
<SimpleTable
|
||||
emptyText="No breakdown complaints recorded for this asset."
|
||||
headers={["Complaint No", "Registered At", "Call Status", "Priority", "Closed At", "Description"]}
|
||||
rows={complaints.map((c) => [
|
||||
<Link
|
||||
key="t"
|
||||
to={`/complaints/${c.id}`}
|
||||
className="font-mono text-[#1e3a8a] hover:underline font-medium"
|
||||
>
|
||||
{c.complaint_no}
|
||||
</Link>,
|
||||
formatDateTime(c.registered_at),
|
||||
<Badge
|
||||
key="st"
|
||||
variant={
|
||||
c.call_status === "closed"
|
||||
? "success"
|
||||
: c.call_status === "in_progress" || c.call_status === "assigned"
|
||||
? "warning"
|
||||
: "danger"
|
||||
}
|
||||
>
|
||||
{c.call_status}
|
||||
</Badge>,
|
||||
c.priority,
|
||||
formatDateTime(c.closed_at),
|
||||
c.description,
|
||||
])}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === "documents" && (
|
||||
<Attachments
|
||||
entityType="asset"
|
||||
entityId={asset.id}
|
||||
canUpload={canFullEdit}
|
||||
canDelete={canFullEdit}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canEdit && (
|
||||
<AssetFormModal
|
||||
open={editOpen}
|
||||
onClose={() => setEditOpen(false)}
|
||||
editing={asset}
|
||||
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}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<InsuranceDrawer
|
||||
open={insuranceDrawerOpen}
|
||||
onClose={() => setInsuranceDrawerOpen(false)}
|
||||
assetId={asset.id}
|
||||
assetLabel={`${asset.asset_code} — ${asset.name}`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SimpleTable({
|
||||
headers,
|
||||
rows,
|
||||
emptyText,
|
||||
}: {
|
||||
headers: string[];
|
||||
rows: React.ReactNode[][];
|
||||
emptyText: string;
|
||||
}) {
|
||||
if (rows.length === 0) {
|
||||
return (
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-8 text-center text-sm text-gray-400">
|
||||
{emptyText}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
{headers.map((h) => (
|
||||
<th key={h} className="text-left font-medium text-gray-600 px-4 py-3">
|
||||
{h}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{rows.map((cells, idx) => (
|
||||
<tr key={idx} className="hover:bg-gray-50/50">
|
||||
{cells.map((cell, cIdx) => (
|
||||
<td key={cIdx} className="px-4 py-3 text-gray-700">
|
||||
{cell}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Plus, Upload } from "lucide-react";
|
||||
import { assetsApi, type AssetItem, type AssetStatus } from "@/api/assets";
|
||||
import { departmentsApi } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
AssetStatusBadge,
|
||||
CoverageBadge,
|
||||
CalibrationBadge,
|
||||
} from "@/components/StatusBadge";
|
||||
import { AssetFormModal } from "@/components/AssetFormModal";
|
||||
import { BulkAssetImportModal } from "@/components/BulkAssetImportModal";
|
||||
|
||||
const STATUS_CHIPS: { value: AssetStatus | ""; label: string }[] = [
|
||||
{ value: "", label: "All Statuses" },
|
||||
{ value: "in_service", label: "In Service" },
|
||||
{ value: "under_repair", label: "Under Repair" },
|
||||
{ value: "out_of_service", label: "Out of Service" },
|
||||
{ value: "condemned", label: "Condemned" },
|
||||
];
|
||||
|
||||
export function AssetsPage() {
|
||||
const navigate = useNavigate();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const role = user?.role;
|
||||
const isDeptUser = role === "department_user";
|
||||
const canCreate = can(role, "create_edit_assets");
|
||||
|
||||
const [selectedDeptId, setSelectedDeptId] = useState<number | undefined>(undefined);
|
||||
const [selectedStatus, setSelectedStatus] = useState<AssetStatus | "">("");
|
||||
const [calibrationFilter, setCalibrationFilter] = useState<"all" | "required" | "not_required">("all");
|
||||
const [insuranceFilter, setInsuranceFilter] = useState<"all" | "insured" | "uninsured">("all");
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [bulkOpen, setBulkOpen] = useState(false);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: !isDeptUser,
|
||||
});
|
||||
|
||||
const assetsQuery = useQuery({
|
||||
queryKey: [
|
||||
"assets",
|
||||
selectedDeptId ?? "all",
|
||||
selectedStatus || "all",
|
||||
calibrationFilter,
|
||||
insuranceFilter,
|
||||
],
|
||||
queryFn: () =>
|
||||
assetsApi.list({
|
||||
department_id: isDeptUser ? undefined : selectedDeptId,
|
||||
status: selectedStatus || undefined,
|
||||
requires_calibration:
|
||||
calibrationFilter === "required"
|
||||
? true
|
||||
: calibrationFilter === "not_required"
|
||||
? false
|
||||
: undefined,
|
||||
insurance_applicable:
|
||||
insuranceFilter === "insured"
|
||||
? true
|
||||
: insuranceFilter === "uninsured"
|
||||
? false
|
||||
: undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const columns: ColumnDef<AssetItem, unknown>[] = [
|
||||
{
|
||||
accessorKey: "asset_code",
|
||||
header: "Asset Code",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono font-semibold text-[#1e3a8a] whitespace-nowrap">
|
||||
{String(getValue())}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ accessorKey: "name", header: "Equipment Name", enableColumnFilter: true },
|
||||
{
|
||||
accessorKey: "category_name",
|
||||
header: "Category",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "location_name",
|
||||
header: "Location",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "supplier_name",
|
||||
header: "Supplier",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: "Status",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => <AssetStatusBadge status={String(getValue())} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "coverage_tag",
|
||||
header: "Coverage",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<CoverageBadge
|
||||
coverage={row.original.coverage}
|
||||
tag={row.original.coverage_tag}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "warranty_status",
|
||||
header: "Warranty",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<CoverageBadge
|
||||
status={row.original.warranty_status}
|
||||
severity={row.original.warranty_severity}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "contract_status",
|
||||
header: "Contract",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<CoverageBadge
|
||||
status={row.original.contract_status}
|
||||
severity={row.original.contract_severity}
|
||||
prefix={row.original.contract_type ?? undefined}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "calibration_status",
|
||||
header: "Calibration",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<CalibrationBadge
|
||||
status={row.original.calibration_status}
|
||||
severity={row.original.calibration_severity}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Asset Register</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
{isDeptUser && user?.department_name
|
||||
? `Showing assets in ${user.department_name}`
|
||||
: "Hospital biomedical and facility equipment inventory"}
|
||||
</p>
|
||||
</div>
|
||||
{canCreate && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" onClick={() => setBulkOpen(true)}>
|
||||
<Upload className="h-4 w-4 mr-1.5" />
|
||||
Bulk Import
|
||||
</Button>
|
||||
<Button onClick={() => setCreateOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Add Asset
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Quick Filter Chips */}
|
||||
<div className="space-y-2">
|
||||
{!isDeptUser && departments.length > 0 && (
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className="text-xs font-medium text-gray-500 mr-1">Department:</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedDeptId(undefined)}
|
||||
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||
selectedDeptId === undefined
|
||||
? "bg-[#1e3a8a] text-white"
|
||||
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
All Departments
|
||||
</button>
|
||||
{departments.map((d) => (
|
||||
<button
|
||||
key={d.id}
|
||||
type="button"
|
||||
onClick={() => setSelectedDeptId(d.id)}
|
||||
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||
selectedDeptId === d.id
|
||||
? "bg-[#1e3a8a] text-white"
|
||||
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
{d.code}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className="text-xs font-medium text-gray-500 mr-1">Status:</span>
|
||||
{STATUS_CHIPS.map((chip) => (
|
||||
<button
|
||||
key={chip.value || "all"}
|
||||
type="button"
|
||||
onClick={() => setSelectedStatus(chip.value)}
|
||||
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||
selectedStatus === chip.value
|
||||
? "bg-blue-700 text-white"
|
||||
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className="text-xs font-medium text-gray-500 mr-1">Calibration:</span>
|
||||
{[
|
||||
{ value: "all", label: "All" },
|
||||
{ value: "required", label: "Calibration Required" },
|
||||
{ value: "not_required", label: "Not Required" },
|
||||
].map((chip) => (
|
||||
<button
|
||||
key={chip.value}
|
||||
type="button"
|
||||
onClick={() => setCalibrationFilter(chip.value as typeof calibrationFilter)}
|
||||
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||
calibrationFilter === chip.value
|
||||
? "bg-emerald-700 text-white"
|
||||
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
</button>
|
||||
))}
|
||||
|
||||
<span className="text-xs font-medium text-gray-500 ml-3 mr-1">Insurance:</span>
|
||||
{[
|
||||
{ value: "all", label: "All" },
|
||||
{ value: "insured", label: "Insurance Applicable" },
|
||||
{ value: "uninsured", label: "Not Applicable" },
|
||||
].map((chip) => (
|
||||
<button
|
||||
key={chip.value}
|
||||
type="button"
|
||||
onClick={() => setInsuranceFilter(chip.value as typeof insuranceFilter)}
|
||||
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||
insuranceFilter === chip.value
|
||||
? "bg-purple-700 text-white"
|
||||
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={assetsQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={assetsQuery.isLoading}
|
||||
globalFilterPlaceholder="Search by asset code, equipment, department, serial..."
|
||||
exportFilename="poona-hospital-assets"
|
||||
emptyMessage="No assets match the current filters."
|
||||
onRowClick={(row) => navigate(`/assets/${row.id}`)}
|
||||
/>
|
||||
|
||||
{canCreate && (
|
||||
<>
|
||||
<AssetFormModal open={createOpen} onClose={() => setCreateOpen(false)} />
|
||||
<BulkAssetImportModal open={bulkOpen} onClose={() => setBulkOpen(false)} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { History, Search, RotateCcw, Eye } from "lucide-react";
|
||||
import { auditApi, type AuditLogItem } from "@/api/audit";
|
||||
import { usersApi } from "@/api/masters";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
|
||||
const ENTITY_TYPES = [
|
||||
{ value: "", label: "All Entity Types" },
|
||||
{ value: "asset", label: "Asset" },
|
||||
{ value: "complaint", label: "Complaint" },
|
||||
{ value: "pm_schedule", label: "PM Schedule" },
|
||||
{ value: "pm_record", label: "PM Record" },
|
||||
{ value: "calibration_plan", label: "Calibration Plan" },
|
||||
{ value: "calibration_record", label: "Calibration Record" },
|
||||
{ value: "contract", label: "Contract" },
|
||||
{ value: "warranty", label: "Warranty" },
|
||||
{ value: "insurance_policy", label: "Insurance Policy" },
|
||||
{ value: "demo_equipment", label: "Demo Equipment" },
|
||||
{ value: "department_visit", label: "Department Visit" },
|
||||
{ value: "attachment", label: "Attachment" },
|
||||
{ value: "setting", label: "Setting" },
|
||||
{ value: "user", label: "User" },
|
||||
{ value: "department", label: "Department" },
|
||||
{ value: "location", label: "Location" },
|
||||
{ value: "category", label: "Category" },
|
||||
{ value: "vendor", label: "Vendor" },
|
||||
];
|
||||
|
||||
const ACTIONS = [
|
||||
{ value: "", label: "All Actions" },
|
||||
{ value: "create", label: "Create" },
|
||||
{ value: "update", label: "Update" },
|
||||
{ value: "delete", label: "Delete" },
|
||||
{ value: "status_change", label: "Status Change" },
|
||||
{ value: "complete", label: "Complete" },
|
||||
{ value: "reschedule", label: "Reschedule" },
|
||||
{ value: "renew", label: "Renew" },
|
||||
{ value: "return", label: "Return" },
|
||||
{ value: "login", label: "Login" },
|
||||
];
|
||||
|
||||
function ActionBadge({ action }: { action: string }) {
|
||||
const lower = action.toLowerCase();
|
||||
let cls = "bg-slate-100 text-slate-700 border-slate-200";
|
||||
if (lower.includes("create") || lower.includes("upload")) {
|
||||
cls = "bg-green-100 text-green-800 border-green-200";
|
||||
} else if (lower.includes("delete") || lower.includes("deactivate") || lower.includes("remove")) {
|
||||
cls = "bg-red-100 text-red-800 border-red-200";
|
||||
} else if (
|
||||
lower.includes("update") ||
|
||||
lower.includes("status") ||
|
||||
lower.includes("reschedule")
|
||||
) {
|
||||
cls = "bg-blue-100 text-blue-800 border-blue-200";
|
||||
} else if (
|
||||
lower.includes("complete") ||
|
||||
lower.includes("renew") ||
|
||||
lower.includes("return") ||
|
||||
lower.includes("approve")
|
||||
) {
|
||||
cls = "bg-emerald-100 text-emerald-800 border-emerald-200";
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border whitespace-nowrap capitalize",
|
||||
cls
|
||||
)}
|
||||
>
|
||||
{action.replace(/_/g, " ")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function summarizeChanges(changesJson: string | null): string {
|
||||
if (!changesJson) return "—";
|
||||
try {
|
||||
const parsed = JSON.parse(changesJson);
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||
const keys = Object.keys(parsed);
|
||||
if (keys.length === 0) return "—";
|
||||
const preview = keys
|
||||
.slice(0, 3)
|
||||
.map((k) => {
|
||||
const val = (parsed as Record<string, unknown>)[k];
|
||||
if (val && typeof val === "object" && "old" in val && "new" in val) {
|
||||
const pair = val as { old: unknown; new: unknown };
|
||||
return `${k}: ${String(pair.old ?? "∅")} → ${String(pair.new ?? "∅")}`;
|
||||
}
|
||||
const str = typeof val === "string" ? val : JSON.stringify(val);
|
||||
return `${k}: ${str}`;
|
||||
})
|
||||
.join(", ");
|
||||
return keys.length > 3 ? `${preview} (+${keys.length - 3} more)` : preview;
|
||||
}
|
||||
return String(parsed);
|
||||
} catch {
|
||||
return changesJson.length > 90 ? `${changesJson.slice(0, 90)}…` : changesJson;
|
||||
}
|
||||
}
|
||||
|
||||
function formatJsonPretty(changesJson: string | null): string {
|
||||
if (!changesJson) return "No payload recorded.";
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(changesJson), null, 2);
|
||||
} catch {
|
||||
return changesJson;
|
||||
}
|
||||
}
|
||||
|
||||
export function AuditLogsPage() {
|
||||
const [entityType, setEntityType] = useState("");
|
||||
const [byUserId, setByUserId] = useState("");
|
||||
const [action, setAction] = useState("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
const [selectedEntry, setSelectedEntry] = useState<AuditLogItem | null>(null);
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ["users", "audit-filter"],
|
||||
queryFn: () => usersApi.list(true),
|
||||
});
|
||||
|
||||
const logsQuery = useQuery({
|
||||
queryKey: [
|
||||
"audit-logs",
|
||||
entityType,
|
||||
byUserId,
|
||||
action,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
q,
|
||||
],
|
||||
queryFn: () =>
|
||||
auditApi.list({
|
||||
entity_type: entityType || undefined,
|
||||
by_user_id: byUserId ? Number(byUserId) : undefined,
|
||||
action: action || undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
q: q.trim() || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const hasFilters = Boolean(
|
||||
entityType || byUserId || action || dateFrom || dateTo || q.trim()
|
||||
);
|
||||
|
||||
function handleReset() {
|
||||
setEntityType("");
|
||||
setByUserId("");
|
||||
setAction("");
|
||||
setDateFrom("");
|
||||
setDateTo("");
|
||||
setQ("");
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<AuditLogItem, unknown>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "at",
|
||||
header: "Timestamp",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs text-gray-700">
|
||||
{formatDateTime(getValue() as string)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
accessorFn: (r) => r.by_user_name ?? `User #${r.by_user_id ?? "System"}`,
|
||||
header: "User",
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm font-medium text-gray-900">
|
||||
{row.original.by_user_name ||
|
||||
(row.original.by_user_id != null
|
||||
? `User #${row.original.by_user_id}`
|
||||
: "System")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "entity_type",
|
||||
header: "Entity Type",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded bg-gray-100 text-gray-700 font-mono text-xs">
|
||||
{String(getValue() ?? "")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "entity_id",
|
||||
header: "Entity ID",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono text-xs text-gray-700">
|
||||
#{String(getValue() ?? "")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "action",
|
||||
header: "Action",
|
||||
cell: ({ getValue }) => <ActionBadge action={String(getValue() ?? "")} />,
|
||||
},
|
||||
{
|
||||
id: "changes",
|
||||
accessorFn: (r) => r.changes_json ?? "",
|
||||
header: "Changes",
|
||||
cell: ({ row }) => {
|
||||
const summary = summarizeChanges(row.original.changes_json);
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-2 max-w-md">
|
||||
<span className="text-xs text-gray-600 truncate" title={summary}>
|
||||
{summary}
|
||||
</span>
|
||||
{row.original.changes_json && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setSelectedEntry(row.original);
|
||||
}}
|
||||
aria-label={`View JSON changes for audit entry ${row.original.id}`}
|
||||
className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium text-[#1e3a8a] hover:bg-blue-50 border border-blue-200 shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
|
||||
>
|
||||
<Eye className="h-3 w-3" />
|
||||
JSON
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
[]
|
||||
);
|
||||
|
||||
const items = logsQuery.data?.items ?? [];
|
||||
const total = logsQuery.data?.total ?? items.length;
|
||||
const users = usersQuery.data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* Header */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<History className="h-6 w-6 text-[#1e3a8a]" />
|
||||
<h1 className="text-2xl font-bold text-gray-900">Audit Log</h1>
|
||||
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-[#1e3a8a] border border-blue-200">
|
||||
{total} {total === 1 ? "entry" : "entries"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Track system-wide creations, updates, status transitions, and deletions.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 shadow-sm">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5 items-end">
|
||||
<div className="lg:col-span-2">
|
||||
<label
|
||||
htmlFor="audit-search"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
Search
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Search className="h-3.5 w-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
id="audit-search"
|
||||
type="text"
|
||||
aria-label="Search audit logs"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Search entity ID, action, changes..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="audit-entity-type"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
Entity Type
|
||||
</label>
|
||||
<select
|
||||
id="audit-entity-type"
|
||||
aria-label="Filter by Entity Type"
|
||||
value={entityType}
|
||||
onChange={(e) => setEntityType(e.target.value)}
|
||||
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
{ENTITY_TYPES.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="audit-user"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
User
|
||||
</label>
|
||||
<select
|
||||
id="audit-user"
|
||||
aria-label="Filter by User"
|
||||
value={byUserId}
|
||||
onChange={(e) => setByUserId(e.target.value)}
|
||||
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="">All Users</option>
|
||||
{users.map((u) => (
|
||||
<option key={u.id} value={String(u.id)}>
|
||||
{u.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="audit-action"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
Action
|
||||
</label>
|
||||
<select
|
||||
id="audit-action"
|
||||
aria-label="Filter by Action"
|
||||
value={action}
|
||||
onChange={(e) => setAction(e.target.value)}
|
||||
className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
{ACTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-end gap-1.5">
|
||||
<div className="flex-1 min-w-0">
|
||||
<label
|
||||
htmlFor="audit-date-from"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
From
|
||||
</label>
|
||||
<input
|
||||
id="audit-date-from"
|
||||
type="date"
|
||||
aria-label="Date from"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<label
|
||||
htmlFor="audit-date-to"
|
||||
className="block text-xs font-medium text-gray-600 mb-1"
|
||||
>
|
||||
To
|
||||
</label>
|
||||
<input
|
||||
id="audit-date-to"
|
||||
type="date"
|
||||
aria-label="Date to"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasFilters && (
|
||||
<div className="mt-2.5 flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleReset}
|
||||
className="text-xs h-7 px-2.5"
|
||||
>
|
||||
<RotateCcw className="h-3.5 w-3.5 mr-1" />
|
||||
Reset filters
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
data={items}
|
||||
columns={columns}
|
||||
loading={logsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter loaded audit entries..."
|
||||
exportFilename="audit-logs"
|
||||
emptyMessage="No audit log entries match your selected filters."
|
||||
/>
|
||||
|
||||
{/* JSON Diff Modal */}
|
||||
<Modal
|
||||
open={Boolean(selectedEntry)}
|
||||
onOpenChange={(o) => !o && setSelectedEntry(null)}
|
||||
title={
|
||||
selectedEntry
|
||||
? `Audit Entry #${selectedEntry.id} — ${selectedEntry.entity_type} #${selectedEntry.entity_id}`
|
||||
: "Audit Entry Details"
|
||||
}
|
||||
description={
|
||||
selectedEntry
|
||||
? `${selectedEntry.action.replace(/_/g, " ")} by ${
|
||||
selectedEntry.by_user_name || "System"
|
||||
} at ${formatDateTime(selectedEntry.at)}`
|
||||
: undefined
|
||||
}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{selectedEntry && (
|
||||
<div className="space-y-3">
|
||||
<pre className="rounded-md bg-gray-900 text-gray-100 p-4 text-xs overflow-x-auto max-h-96 font-mono leading-relaxed">
|
||||
{formatJsonPretty(selectedEntry.changes_json)}
|
||||
</pre>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSelectedEntry(null)}
|
||||
>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
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, Download, Upload } 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";
|
||||
import { BulkGenericImportModal } from "@/components/BulkGenericImportModal";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
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 [importModalOpen, setImportModalOpen] = 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 && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await calibrationApi.downloadImportTemplate();
|
||||
toast.success("Downloaded Calibration import template (.xlsx)");
|
||||
} catch {
|
||||
toast.error("Failed to download template");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
Template (.xlsx)
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setImportModalOpen(true)}
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-1.5" />
|
||||
Import (.xlsx)
|
||||
</Button>
|
||||
<Button onClick={() => setBulkAddOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Add Equipment to Calibration
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</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 overflow-x-auto whitespace-nowrap">
|
||||
<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>
|
||||
|
||||
<BulkGenericImportModal
|
||||
open={importModalOpen}
|
||||
onClose={() => setImportModalOpen(false)}
|
||||
title="Bulk Import Calibration Plans"
|
||||
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register multiple equipment calibration frequencies and agency assignments at once."
|
||||
entityName="Calibration Plans"
|
||||
templateFilename="calibration_import_template.xlsx"
|
||||
onDownloadTemplate={() => calibrationApi.downloadImportTemplate()}
|
||||
onImport={(file, dryRun, skipInvalid) => calibrationApi.bulkImport(file, dryRun, skipInvalid)}
|
||||
queryKeysToInvalidate={[["calibration-plans"], ["calibration-records"], ["dashboard"]]}
|
||||
previewColumns={[
|
||||
{ key: "asset_code", label: "Asset Code" },
|
||||
{ key: "frequency_months", label: "Frequency (Mo)" },
|
||||
{ key: "agency_name", label: "Agency" },
|
||||
{ key: "next_due_date", label: "Next Due Date" },
|
||||
]}
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,388 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Plus, Search } from "lucide-react";
|
||||
import {
|
||||
complaintsApi,
|
||||
type ComplaintItem,
|
||||
type CallStatus,
|
||||
} from "@/api/complaints";
|
||||
import type { AssetCriticality, CoverageTag } from "@/api/assets";
|
||||
import { departmentsApi, locationsApi, fetchUsersLookup } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDateTime, formatDuration } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { CallStatusBadge, CoverageBadge, CriticalityBadge } from "@/components/StatusBadge";
|
||||
import { RaiseComplaintModal } from "@/components/RaiseComplaintModal";
|
||||
|
||||
const CALL_STATUS_CHIPS: { value: CallStatus | ""; label: string }[] = [
|
||||
{ value: "", label: "All Calls" },
|
||||
{ value: "open", label: "Open" },
|
||||
{ value: "in_progress", label: "In Progress" },
|
||||
{ value: "closed", label: "Closed" },
|
||||
];
|
||||
|
||||
export function ComplaintsPage() {
|
||||
const navigate = useNavigate();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const role = user?.role;
|
||||
const isDeptUser = role === "department_user";
|
||||
const canRaise = can(role, "raise_complaint");
|
||||
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState<string>("");
|
||||
const [locationId, setLocationId] = useState<string>("");
|
||||
const [callStatus, setCallStatus] = useState<CallStatus | "">("");
|
||||
const [priority, setPriority] = useState<AssetCriticality | "">("");
|
||||
const [coverageTag, setCoverageTag] = useState<CoverageTag | "">("");
|
||||
const [assignedToId, setAssignedToId] = useState<string>("");
|
||||
const [closureState, setClosureState] = useState<"open_only" | "closed_only" | "">("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
const [raiseOpen, setRaiseOpen] = useState(false);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: !isDeptUser,
|
||||
});
|
||||
|
||||
const locationsQuery = useQuery({
|
||||
queryKey: ["locations", "active-only"],
|
||||
queryFn: () => locationsApi.list(false),
|
||||
});
|
||||
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ["users-lookup"],
|
||||
queryFn: fetchUsersLookup,
|
||||
});
|
||||
|
||||
const complaintsQuery = useQuery({
|
||||
queryKey: [
|
||||
"complaints",
|
||||
q,
|
||||
departmentId,
|
||||
locationId,
|
||||
callStatus,
|
||||
priority,
|
||||
coverageTag,
|
||||
assignedToId,
|
||||
closureState,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
],
|
||||
queryFn: () =>
|
||||
complaintsApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
location_id: locationId ? Number(locationId) : undefined,
|
||||
call_status: callStatus || undefined,
|
||||
priority: priority || undefined,
|
||||
coverage_tag: coverageTag || undefined,
|
||||
assigned_to_id: assignedToId ? Number(assignedToId) : undefined,
|
||||
closure_state: closureState || undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const columns: ColumnDef<ComplaintItem, unknown>[] = [
|
||||
{
|
||||
accessorKey: "complaint_no",
|
||||
header: "Complaint No",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono font-semibold text-[#1e3a8a] whitespace-nowrap">
|
||||
{String(getValue())}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "asset_display",
|
||||
accessorFn: (row) => `${row.asset_code} ${row.asset_name}`,
|
||||
header: "Asset",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<div className="min-w-36">
|
||||
<div className="font-mono text-xs text-[#1e3a8a] font-medium">
|
||||
{row.original.asset_code}
|
||||
</div>
|
||||
<div className="text-xs text-gray-800 truncate">{row.original.asset_name}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "coverage_tag",
|
||||
header: "Coverage",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<CoverageBadge
|
||||
coverage={row.original.coverage_at_registration ?? row.original.coverage_now}
|
||||
tag={row.original.coverage_tag}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "priority",
|
||||
header: "Priority",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => <CriticalityBadge criticality={String(getValue())} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "call_status",
|
||||
header: "Call Status",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => <CallStatusBadge status={String(getValue())} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "assigned_to_name",
|
||||
header: "Assigned To",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "Unassigned",
|
||||
},
|
||||
{
|
||||
accessorKey: "registered_at",
|
||||
header: "Registered At",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs">{formatDateTime(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "response_time_minutes",
|
||||
header: "Response Time",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs font-medium">
|
||||
{formatDuration(getValue() as number | null)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "downtime_minutes",
|
||||
header: "Downtime",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1.5 whitespace-nowrap">
|
||||
<span className="text-xs font-semibold text-gray-900">
|
||||
{formatDuration(row.original.downtime_minutes)}
|
||||
</span>
|
||||
{row.original.downtime_is_ongoing && (
|
||||
<Badge variant="danger" className="text-[10px] px-1.5 py-0">
|
||||
Ongoing
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "closed_at",
|
||||
header: "Closed At",
|
||||
enableColumnFilter: false,
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap text-xs">
|
||||
{formatDateTime(getValue() as string | null)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const allLocations = locationsQuery.data?.items ?? [];
|
||||
const filteredLocations = departmentId
|
||||
? allLocations.filter((l) => l.department_id === Number(departmentId))
|
||||
: allLocations;
|
||||
const techUsers = (usersQuery.data?.items ?? []).filter(
|
||||
(u) => u.role === "biomedical" || u.role === "system_admin"
|
||||
);
|
||||
|
||||
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">Breakdown & Complaint Register</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
{isDeptUser && user?.department_name
|
||||
? `Complaints for ${user.department_name}`
|
||||
: "Track breakdown calls, response times, downtime, and technical resolution"}
|
||||
</p>
|
||||
</div>
|
||||
{canRaise && (
|
||||
<Button onClick={() => setRaiseOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Raise Complaint
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 space-y-3">
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className="text-xs font-medium text-gray-500 mr-1">Call Status:</span>
|
||||
{CALL_STATUS_CHIPS.map((chip) => (
|
||||
<button
|
||||
key={chip.value || "all"}
|
||||
type="button"
|
||||
onClick={() => setCallStatus(chip.value)}
|
||||
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||
callStatus === chip.value
|
||||
? "bg-[#1e3a8a] text-white"
|
||||
: "bg-gray-50 border border-gray-200 text-gray-700 hover:bg-gray-100"
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="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 complaint no, asset, description..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!isDeptUser && (
|
||||
<select
|
||||
value={departmentId}
|
||||
onChange={(e) => {
|
||||
setDepartmentId(e.target.value);
|
||||
setLocationId("");
|
||||
}}
|
||||
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={locationId}
|
||||
onChange={(e) => setLocationId(e.target.value)}
|
||||
aria-label="Filter by Location"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Locations</option>
|
||||
{filteredLocations.map((loc) => (
|
||||
<option key={loc.id} value={String(loc.id)}>
|
||||
{loc.name} {loc.floor_wing ? `(${loc.floor_wing})` : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={priority}
|
||||
onChange={(e) => setPriority(e.target.value as AssetCriticality | "")}
|
||||
aria-label="Filter by Priority"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Priorities</option>
|
||||
<option value="critical">Critical</option>
|
||||
<option value="non_critical">Non-Critical</option>
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={coverageTag}
|
||||
onChange={(e) => setCoverageTag(e.target.value as CoverageTag | "")}
|
||||
aria-label="Filter by Coverage"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Coverage</option>
|
||||
<option value="warranty">Warranty</option>
|
||||
<option value="cmc">CMC</option>
|
||||
<option value="amc">AMC</option>
|
||||
<option value="other_contract">Other Contract</option>
|
||||
<option value="out_of_contract">Out of Contract</option>
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={assignedToId}
|
||||
onChange={(e) => setAssignedToId(e.target.value)}
|
||||
aria-label="Filter by Assigned To"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Assignees</option>
|
||||
{techUsers.map((u) => (
|
||||
<option key={u.id} value={String(u.id)}>
|
||||
{u.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={closureState}
|
||||
onChange={(e) =>
|
||||
setClosureState(e.target.value as "open_only" | "closed_only" | "")
|
||||
}
|
||||
aria-label="Filter by Closure State"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Closure States</option>
|
||||
<option value="open_only">Unclosed Only</option>
|
||||
<option value="closed_only">Closed Only</option>
|
||||
</select>
|
||||
|
||||
<div className="flex items-center gap-1.5 lg:col-span-2">
|
||||
<input
|
||||
type="date"
|
||||
aria-label="From date"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(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="To date"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={complaintsQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={complaintsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter loaded table..."
|
||||
exportFilename="poona-hospital-complaints"
|
||||
emptyMessage="No complaints match the current filters."
|
||||
onRowClick={(row) => navigate(`/complaints/${row.id}`)}
|
||||
getRowClassName={(row) =>
|
||||
row.call_status === "open"
|
||||
? "bg-red-50/35"
|
||||
: row.call_status === "in_progress"
|
||||
? "bg-amber-50/35"
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
|
||||
{canRaise && (
|
||||
<RaiseComplaintModal open={raiseOpen} onClose={() => setRaiseOpen(false)} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,424 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
ResponsiveContainer,
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
BarChart,
|
||||
Bar,
|
||||
AreaChart,
|
||||
Area,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
Legend,
|
||||
} from "recharts";
|
||||
import {
|
||||
Package,
|
||||
Wrench,
|
||||
AlertCircle,
|
||||
CalendarCheck,
|
||||
Gauge,
|
||||
FileText,
|
||||
Truck,
|
||||
AlertTriangle,
|
||||
ArrowRight,
|
||||
Building2,
|
||||
} from "lucide-react";
|
||||
import { dashboardApi } from "@/api/dashboard";
|
||||
import { formatDate, formatDuration } from "@/lib/format";
|
||||
import { CallStatusBadge, CriticalityBadge } from "@/components/StatusBadge";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
const STATUS_COLORS: Record<string, { label: string; color: string }> = {
|
||||
open: { label: "Open", color: "#ef4444" },
|
||||
in_progress: { label: "In Progress", color: "#f59e0b" },
|
||||
closed: { label: "Closed", color: "#22c55e" },
|
||||
};
|
||||
|
||||
export function DashboardPage() {
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ["dashboard", "summary"],
|
||||
queryFn: () => dashboardApi.summary(),
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="h-8 w-56 bg-gray-200 rounded animate-pulse" />
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-7 gap-3">
|
||||
{Array.from({ length: 7 }).map((_, i) => (
|
||||
<div key={i} className="h-24 bg-white border border-gray-200 rounded-xl animate-pulse" />
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<div className="h-72 bg-white border border-gray-200 rounded-xl animate-pulse" />
|
||||
<div className="h-72 bg-white border border-gray-200 rounded-xl animate-pulse" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className="bg-white border border-red-200 rounded-xl p-6 text-center text-sm text-red-700">
|
||||
Unable to load dashboard summary. Please refresh and try again.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
department_scope,
|
||||
effective_today,
|
||||
kpis,
|
||||
complaints_by_status,
|
||||
complaints_by_department,
|
||||
monthly_downtime_trend,
|
||||
pm_planned_vs_completed,
|
||||
needs_attention,
|
||||
recent_complaints,
|
||||
} = data;
|
||||
|
||||
const kpiCards = [
|
||||
{
|
||||
label: "Total Assets",
|
||||
value: kpis.total_assets,
|
||||
to: "/assets",
|
||||
icon: Package,
|
||||
tone: "text-[#1e3a8a] bg-blue-50 border-blue-200",
|
||||
},
|
||||
{
|
||||
label: "Under Repair",
|
||||
value: kpis.assets_under_repair,
|
||||
to: "/assets?status=under_repair",
|
||||
icon: Wrench,
|
||||
tone: "text-amber-800 bg-amber-50 border-amber-200",
|
||||
},
|
||||
{
|
||||
label: "Open Complaints",
|
||||
value: kpis.open_complaints,
|
||||
to: "/complaints",
|
||||
icon: AlertCircle,
|
||||
tone: "text-red-800 bg-red-50 border-red-200",
|
||||
},
|
||||
{
|
||||
label: "PM Due This Month",
|
||||
value: kpis.pm_due_this_month,
|
||||
to: "/pm",
|
||||
icon: CalendarCheck,
|
||||
tone: "text-indigo-800 bg-indigo-50 border-indigo-200",
|
||||
},
|
||||
{
|
||||
label: "Calibrations Due",
|
||||
value: kpis.calibrations_due,
|
||||
to: "/calibration",
|
||||
icon: Gauge,
|
||||
tone: "text-orange-800 bg-orange-50 border-orange-200",
|
||||
},
|
||||
{
|
||||
label: "Contracts Expiring",
|
||||
value: kpis.contracts_expiring,
|
||||
to: "/contracts",
|
||||
icon: FileText,
|
||||
tone: "text-purple-800 bg-purple-50 border-purple-200",
|
||||
},
|
||||
{
|
||||
label: "Equipment on Demo",
|
||||
value: kpis.equipment_on_demo,
|
||||
to: "/demo-equipment",
|
||||
icon: Truck,
|
||||
tone: "text-teal-800 bg-teal-50 border-teal-200",
|
||||
},
|
||||
];
|
||||
|
||||
const statusChartData = complaints_by_status.map((item) => ({
|
||||
name: STATUS_COLORS[item.status]?.label ?? item.status,
|
||||
value: item.count,
|
||||
color: STATUS_COLORS[item.status]?.color ?? "#6b7280",
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* Header */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Hospital Operations Dashboard</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Live equipment health, breakdown downtime, PM compliance, and expiry alerts as of{" "}
|
||||
<span className="font-medium text-gray-700">{formatDate(effective_today)}</span>
|
||||
</p>
|
||||
</div>
|
||||
{department_scope && (
|
||||
<div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-blue-50 border border-blue-200 text-xs font-semibold text-[#1e3a8a]">
|
||||
<Building2 className="h-3.5 w-3.5" />
|
||||
Viewing department scope: {department_scope}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 7 KPI Cards */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-7 gap-3">
|
||||
{kpiCards.map((card) => {
|
||||
const Icon = card.icon;
|
||||
return (
|
||||
<Link
|
||||
key={card.label}
|
||||
to={card.to}
|
||||
className={`rounded-xl border p-3.5 transition-shadow hover:shadow-md flex flex-col justify-between ${card.tone}`}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-xs font-medium opacity-85">{card.label}</span>
|
||||
<Icon className="h-4 w-4 shrink-0 opacity-80" />
|
||||
</div>
|
||||
<div className="text-2xl font-bold mt-2">{card.value}</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 4 Charts Grid */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Chart 1: Complaints by Status */}
|
||||
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
|
||||
<h2 className="text-sm font-semibold text-gray-800 mb-3">
|
||||
Complaints by Status
|
||||
</h2>
|
||||
<div className="h-60">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={statusChartData}
|
||||
dataKey="value"
|
||||
nameKey="name"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={52}
|
||||
outerRadius={82}
|
||||
paddingAngle={3}
|
||||
>
|
||||
{statusChartData.map((entry, idx) => (
|
||||
<Cell key={idx} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chart 2: Complaints by Department */}
|
||||
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
|
||||
<h2 className="text-sm font-semibold text-gray-800 mb-3">
|
||||
Complaints by Department
|
||||
</h2>
|
||||
<div className="h-60">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={complaints_by_department}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
||||
<XAxis dataKey="department" tick={{ fontSize: 11 }} />
|
||||
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Bar
|
||||
dataKey="critical"
|
||||
name="Critical"
|
||||
stackId="a"
|
||||
fill="#ef4444"
|
||||
radius={[0, 0, 0, 0]}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="non_critical"
|
||||
name="Non-Critical"
|
||||
stackId="a"
|
||||
fill="#3b82f6"
|
||||
radius={[4, 4, 0, 0]}
|
||||
/>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chart 3: Monthly Downtime Trend */}
|
||||
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
|
||||
<h2 className="text-sm font-semibold text-gray-800 mb-3">
|
||||
Monthly Downtime Trend (Hours)
|
||||
</h2>
|
||||
<div className="h-60">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={monthly_downtime_trend}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
||||
<XAxis dataKey="label" tick={{ fontSize: 11 }} />
|
||||
<YAxis tick={{ fontSize: 11 }} />
|
||||
<Tooltip />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="downtime_hours"
|
||||
name="Downtime (hrs)"
|
||||
stroke="#ef4444"
|
||||
fill="#fee2e2"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chart 4: PM Planned vs Completed */}
|
||||
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm">
|
||||
<h2 className="text-sm font-semibold text-gray-800 mb-3">
|
||||
PM Planned vs Completed (Last 6 Months)
|
||||
</h2>
|
||||
<div className="h-60">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={pm_planned_vs_completed}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
||||
<XAxis dataKey="label" tick={{ fontSize: 11 }} />
|
||||
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Bar dataKey="planned" name="Planned" fill="#1e3a8a" radius={[4, 4, 0, 0]} />
|
||||
<Bar dataKey="completed" name="Completed" fill="#22c55e" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bottom Panels: Needs Attention & Recent Complaints */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
|
||||
{/* Needs Attention */}
|
||||
<div className="lg:col-span-5 bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-gray-900 flex items-center gap-1.5">
|
||||
<AlertTriangle className="h-4 w-4 text-red-600" />
|
||||
Needs Attention
|
||||
</h2>
|
||||
<Link
|
||||
to="/notifications"
|
||||
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||
>
|
||||
View all →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{needs_attention.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-gray-400">
|
||||
No urgent red-severity alerts right now.
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-gray-100 max-h-80 overflow-y-auto">
|
||||
{needs_attention.map((item) => (
|
||||
<Link
|
||||
key={item.id}
|
||||
to={item.link_url}
|
||||
className="flex items-start justify-between gap-2 py-2.5 px-2 -mx-2 rounded-md hover:bg-red-50/50 transition-colors"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="text-xs font-semibold text-gray-900 truncate">
|
||||
{item.title}
|
||||
</div>
|
||||
<div className="text-[11px] text-gray-600 line-clamp-2 mt-0.5">
|
||||
{item.message}
|
||||
</div>
|
||||
{item.due_date && (
|
||||
<div className="text-[10px] text-red-700 font-medium mt-0.5">
|
||||
Due: {formatDate(item.due_date)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<ArrowRight className="h-3.5 w-3.5 text-gray-400 shrink-0 mt-1" />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Recent Complaints */}
|
||||
<div className="lg:col-span-7 bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold text-gray-900">
|
||||
Recent Complaints
|
||||
</h2>
|
||||
<Link
|
||||
to="/complaints"
|
||||
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||
>
|
||||
All complaints →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{recent_complaints.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-gray-400">
|
||||
No complaints recorded yet.
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||
Complaint
|
||||
</th>
|
||||
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||
Asset
|
||||
</th>
|
||||
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||
Status
|
||||
</th>
|
||||
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||
Priority
|
||||
</th>
|
||||
<th className="text-left font-medium text-gray-600 px-3 py-2">
|
||||
Downtime
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{recent_complaints.map((c) => (
|
||||
<tr key={c.id} className="hover:bg-gray-50/70">
|
||||
<td className="px-3 py-2 whitespace-nowrap">
|
||||
<Link
|
||||
to={`/complaints/${c.id}`}
|
||||
className="font-mono font-semibold text-[#1e3a8a] hover:underline"
|
||||
>
|
||||
{c.complaint_no}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<div className="font-mono text-[11px] text-gray-700">
|
||||
{c.asset_code}
|
||||
</div>
|
||||
<div className="text-gray-900 truncate max-w-[160px]">
|
||||
{c.asset_name}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<CallStatusBadge status={c.call_status} />
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<CriticalityBadge criticality={c.priority} />
|
||||
</td>
|
||||
<td className="px-3 py-2 whitespace-nowrap">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span>{formatDuration(c.downtime_minutes)}</span>
|
||||
{c.downtime_is_ongoing && (
|
||||
<Badge variant="danger" className="text-[10px] px-1.5 py-0">
|
||||
Ongoing
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
interface MockAsset {
|
||||
code: string;
|
||||
name: string;
|
||||
department: string;
|
||||
status: string;
|
||||
category: string;
|
||||
}
|
||||
|
||||
const MOCK_DATA: MockAsset[] = [
|
||||
{ code: "PHRC-ICU-0001", name: "Ventilator", department: "ICU", status: "In Service", category: "Life Support" },
|
||||
{ code: "PHRC-I CU-0002", name: "Patient Monitor", department: "ICU", status: "Under Repair", category: "Monitoring" },
|
||||
{ code: "PHRC-OT-0001", name: "Anaesthesia Machine", department: "Operation Theatre", status: "In Service", category: "Life Support" },
|
||||
{ code: "PHRC-RAD-0001", name: "CT Scanner", department: "Radiology", status: "In Service", category: "Imaging" },
|
||||
{ code: "PHRC-RAD-0002", name: "X-Ray Unit", department: "Radiology", status: "Out of Service", category: "Imaging" },
|
||||
{ code: "PHRC-EM-0001", name: "Defibrillator", department: "Emergency", status: "In Service", category: "Life Support" },
|
||||
{ code: "PHRC-PATH-0001", name: "Centrifuge", department: "Pathology", status: "In Service", category: "Laboratory" },
|
||||
{ code: "PHRC-DIAL-0001", name: "Dialysis Machine", department: "Dialysis", status: "In Service", category: "Dialysis" },
|
||||
];
|
||||
|
||||
const STATUS_VARIANTS: Record<string, "success" | "danger" | "warning" | "outline"> = {
|
||||
"In Service": "success",
|
||||
"Under Repair": "danger",
|
||||
"Out of Service": "warning",
|
||||
Condemned: "outline",
|
||||
};
|
||||
|
||||
const columns: ColumnDef<MockAsset, unknown>[] = [
|
||||
{ accessorKey: "code", header: "Asset Code", enableColumnFilter: true },
|
||||
{ accessorKey: "name", header: "Equipment Name", enableColumnFilter: true },
|
||||
{ accessorKey: "category", header: "Category", enableColumnFilter: true },
|
||||
{ accessorKey: "department", header: "Department", enableColumnFilter: true },
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: "Status",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ getValue }) => {
|
||||
const v = getValue() as string;
|
||||
return <Badge variant={STATUS_VARIANTS[v] ?? "default"}>{v}</Badge>;
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export function DataTableDemoPage() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Phase 0 — DataTable Demo</h1>
|
||||
<p className="text-gray-500 mt-1 text-sm">
|
||||
Mock asset data demonstrating column filters, sort, pagination, column visibility, and CSV export.
|
||||
Every list in the app will use this component.
|
||||
</p>
|
||||
</div>
|
||||
<DataTable
|
||||
data={MOCK_DATA}
|
||||
columns={columns}
|
||||
globalFilterPlaceholder="Search assets..."
|
||||
exportFilename="assets-demo"
|
||||
emptyMessage="No assets found."
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,741 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import {
|
||||
Plus,
|
||||
Paperclip,
|
||||
Pencil,
|
||||
Trash2,
|
||||
CornerDownLeft,
|
||||
Search,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { demoEquipmentApi, type DemoEquipmentItem } from "@/api/phase5";
|
||||
import { departmentsApi, locationsApi, vendorsApi } from "@/api/masters";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { DemoStatusBadge } from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
type ViewTab = "active" | "returned" | "all";
|
||||
|
||||
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";
|
||||
|
||||
export function DemoEquipmentPage() {
|
||||
const qc = useQueryClient();
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const isDeptUser = role === "department_user";
|
||||
const canManage = can(role, "manage_demo_equipment");
|
||||
|
||||
const [viewTab, setViewTab] = useState<ViewTab>("active");
|
||||
const [q, setQ] = useState("");
|
||||
const [supplierId, setSupplierId] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<DemoEquipmentItem | null>(null);
|
||||
const [returnTarget, setReturnTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
const [attachTarget, setAttachTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: !isDeptUser,
|
||||
});
|
||||
|
||||
const locationsQuery = useQuery({
|
||||
queryKey: ["locations", "active-only"],
|
||||
queryFn: () => locationsApi.list(false),
|
||||
});
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
});
|
||||
|
||||
const demoQuery = useQuery({
|
||||
queryKey: [
|
||||
"demo-equipment",
|
||||
viewTab,
|
||||
q,
|
||||
supplierId,
|
||||
departmentId,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
],
|
||||
queryFn: () =>
|
||||
demoEquipmentApi.list({
|
||||
q: q.trim() || undefined,
|
||||
supplier_id: supplierId ? Number(supplierId) : undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
status: viewTab === "returned" ? "returned" : undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => demoEquipmentApi.remove(id),
|
||||
onSuccess: () => {
|
||||
setDeleteTarget(null);
|
||||
qc.invalidateQueries({ queryKey: ["demo-equipment"] });
|
||||
toast.success("Demo equipment entry deleted");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.detail : "Failed to delete demo entry");
|
||||
},
|
||||
});
|
||||
|
||||
const items = useMemo(() => {
|
||||
const raw = demoQuery.data?.items ?? [];
|
||||
if (viewTab === "active") {
|
||||
return raw.filter((item) => item.status !== "returned");
|
||||
}
|
||||
if (viewTab === "returned") {
|
||||
return raw.filter((item) => item.status === "returned");
|
||||
}
|
||||
return raw;
|
||||
}, [demoQuery.data?.items, viewTab]);
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const locations = locationsQuery.data?.items ?? [];
|
||||
const allVendors = vendorsQuery.data?.items ?? [];
|
||||
const suppliers = allVendors.filter((v) => v.vendor_type === "supplier");
|
||||
const supplierOptions = suppliers.length ? suppliers : allVendors;
|
||||
|
||||
const columns: ColumnDef<DemoEquipmentItem, unknown>[] = [
|
||||
{
|
||||
id: "equipment",
|
||||
accessorFn: (r) => `${r.name} ${r.equipment_type ?? ""} ${r.serial_no ?? ""}`,
|
||||
header: "Equipment",
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<div className="font-medium text-gray-900">{row.original.name}</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{[
|
||||
row.original.equipment_type,
|
||||
row.original.serial_no ? `SN: ${row.original.serial_no}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" • ")}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "supplier_name",
|
||||
header: "Supplier",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
id: "dept_loc",
|
||||
accessorFn: (r) => `${r.department_name ?? ""} ${r.location_name ?? ""}`,
|
||||
header: "Department / Location",
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<div className="text-gray-800">{row.original.department_name || "—"}</div>
|
||||
{row.original.location_name && (
|
||||
<div className="text-xs text-gray-500">{row.original.location_name}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: "Start Date",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "expected_return_date",
|
||||
header: "Expected Return",
|
||||
cell: ({ row }) => (
|
||||
<span
|
||||
className={`whitespace-nowrap ${
|
||||
row.original.status === "overdue_return" ? "font-semibold text-red-700" : ""
|
||||
}`}
|
||||
>
|
||||
{formatDate(row.original.expected_return_date)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "actual_return_date",
|
||||
header: "Actual Return",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string | null)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: "Status",
|
||||
cell: ({ row }) => (
|
||||
<DemoStatusBadge
|
||||
status={row.original.status}
|
||||
daysRemaining={row.original.days_remaining}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: "Docs",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setAttachTarget(row.original)}
|
||||
title="View or upload demo equipment documents"
|
||||
>
|
||||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||
<span className="text-xs">{row.original.attachment_count}</span>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
...(canManage
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: DemoEquipmentItem } }) => (
|
||||
<div className="flex items-center gap-1">
|
||||
{row.original.status !== "returned" && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setReturnTarget(row.original)}
|
||||
>
|
||||
<CornerDownLeft className="h-3.5 w-3.5 mr-1" />
|
||||
Return
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditing(row.original);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
aria-label={`Edit demo equipment ${row.original.name}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => setDeleteTarget(row.original)}
|
||||
aria-label={`Delete demo equipment ${row.original.name}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
} satisfies ColumnDef<DemoEquipmentItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Demo Equipment Register</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Monitor supplier trial equipment, expected return dates, and overdue alerts
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Log Demo Equipment
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* View Tabs */}
|
||||
<div className="flex gap-1 border-b border-gray-200 overflow-x-auto whitespace-nowrap">
|
||||
{(
|
||||
[
|
||||
{ key: "active", label: "Active & Overdue" },
|
||||
{ key: "returned", label: "Returned History" },
|
||||
{ key: "all", label: "All" },
|
||||
] as { key: ViewTab; label: string }[]
|
||||
).map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
onClick={() => setViewTab(t.key)}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
|
||||
viewTab === t.key
|
||||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||
}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<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 equipment name, type, remarks..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<select
|
||||
value={supplierId}
|
||||
onChange={(e) => setSupplierId(e.target.value)}
|
||||
aria-label="Filter by Supplier"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Suppliers</option>
|
||||
{supplierOptions.map((s) => (
|
||||
<option key={s.id} value={String(s.id)}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{!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>
|
||||
)}
|
||||
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Start Date From"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Start Date To"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={items}
|
||||
columns={columns}
|
||||
loading={demoQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter demo equipment..."
|
||||
exportFilename="demo-equipment"
|
||||
emptyMessage="No demo equipment entries found."
|
||||
/>
|
||||
|
||||
<DemoFormModal
|
||||
open={formOpen}
|
||||
onClose={() => setFormOpen(false)}
|
||||
editing={editing}
|
||||
suppliers={supplierOptions}
|
||||
departments={departments}
|
||||
locations={locations}
|
||||
/>
|
||||
|
||||
<ReturnDemoModal
|
||||
open={Boolean(returnTarget)}
|
||||
onClose={() => setReturnTarget(null)}
|
||||
item={returnTarget}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={Boolean(attachTarget)}
|
||||
onOpenChange={(o) => !o && setAttachTarget(null)}
|
||||
title={`Documents — ${attachTarget?.name ?? ""}`}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{attachTarget && (
|
||||
<Attachments
|
||||
entityType="demo_equipment"
|
||||
entityId={attachTarget.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(deleteTarget)}
|
||||
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||
title="Delete Demo Equipment Entry"
|
||||
message={`Are you sure you want to delete "${deleteTarget?.name ?? "this demo entry"}"?`}
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => {
|
||||
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DemoFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing,
|
||||
suppliers,
|
||||
departments,
|
||||
locations,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing: DemoEquipmentItem | null;
|
||||
suppliers: Array<{ id: number; name: string }>;
|
||||
departments: Array<{ id: number; name: string }>;
|
||||
locations: Array<{ id: number; department_id: number; name: string }>;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [name, setName] = useState("");
|
||||
const [equipmentType, setEquipmentType] = useState("");
|
||||
const [serialNo, setSerialNo] = useState("");
|
||||
const [supplierId, setSupplierId] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [locationId, setLocationId] = useState("");
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [expectedReturnDate, setExpectedReturnDate] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
if (editing) {
|
||||
setName(editing.name);
|
||||
setEquipmentType(editing.equipment_type ?? "");
|
||||
setSerialNo(editing.serial_no ?? "");
|
||||
setSupplierId(String(editing.supplier_id));
|
||||
setDepartmentId(String(editing.department_id));
|
||||
setLocationId(editing.location_id ? String(editing.location_id) : "");
|
||||
setStartDate(editing.start_date);
|
||||
setExpectedReturnDate(editing.expected_return_date);
|
||||
setRemarks(editing.remarks ?? "");
|
||||
} else {
|
||||
const today = new Date();
|
||||
const plus14 = new Date(today);
|
||||
plus14.setDate(plus14.getDate() + 14);
|
||||
setName("");
|
||||
setEquipmentType("");
|
||||
setSerialNo("");
|
||||
setSupplierId("");
|
||||
setDepartmentId("");
|
||||
setLocationId("");
|
||||
setStartDate(today.toISOString().slice(0, 10));
|
||||
setExpectedReturnDate(plus14.toISOString().slice(0, 10));
|
||||
setRemarks("");
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
const deptLocations = locations.filter(
|
||||
(l) => !departmentId || l.department_id === Number(departmentId)
|
||||
);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const payload = {
|
||||
name: name.trim(),
|
||||
equipment_type: equipmentType.trim(),
|
||||
serial_no: serialNo.trim() || null,
|
||||
supplier_id: Number(supplierId),
|
||||
department_id: Number(departmentId),
|
||||
location_id: locationId ? Number(locationId) : null,
|
||||
start_date: startDate,
|
||||
expected_return_date: expectedReturnDate,
|
||||
remarks: remarks.trim() || null,
|
||||
};
|
||||
if (editing) {
|
||||
await demoEquipmentApi.update(editing.id, payload);
|
||||
} else {
|
||||
await demoEquipmentApi.create(payload);
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["demo-equipment"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to save demo equipment.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? `Edit Demo Equipment — ${editing.name}` : "Log Demo Equipment"}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Equipment Name *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. Portable Ultrasound Demo Unit"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Equipment Type / Model *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={equipmentType}
|
||||
onChange={(e) => setEquipmentType(e.target.value)}
|
||||
placeholder="e.g. Diagnostic Imaging"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Serial Number</label>
|
||||
<input
|
||||
type="text"
|
||||
value={serialNo}
|
||||
onChange={(e) => setSerialNo(e.target.value)}
|
||||
placeholder="e.g. SN-DEMO-901"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Supplier *</label>
|
||||
<select
|
||||
required
|
||||
value={supplierId}
|
||||
onChange={(e) => setSupplierId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select supplier...</option>
|
||||
{suppliers.map((s) => (
|
||||
<option key={s.id} value={String(s.id)}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Department *</label>
|
||||
<select
|
||||
required
|
||||
value={departmentId}
|
||||
onChange={(e) => {
|
||||
setDepartmentId(e.target.value);
|
||||
setLocationId("");
|
||||
}}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select department...</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Location</label>
|
||||
<select
|
||||
value={locationId}
|
||||
onChange={(e) => setLocationId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select location...</option>
|
||||
{deptLocations.map((l) => (
|
||||
<option key={l.id} value={String(l.id)}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div />
|
||||
<div>
|
||||
<label className={labelCls}>Start Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Expected Return Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={expectedReturnDate}
|
||||
onChange={(e) => setExpectedReturnDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Changes" : "Log Demo Equipment"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function ReturnDemoModal({
|
||||
open,
|
||||
onClose,
|
||||
item,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
item: DemoEquipmentItem | null;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [actualReturnDate, setActualReturnDate] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setActualReturnDate(new Date().toISOString().slice(0, 10));
|
||||
setRemarks(item?.remarks ?? "");
|
||||
setError(null);
|
||||
}, [open, item]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!item) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await demoEquipmentApi.markReturned(item.id, {
|
||||
actual_return_date: actualReturnDate,
|
||||
remarks: remarks.trim() || null,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["demo-equipment"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to mark returned.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Mark Returned — ${item?.name ?? ""}`}
|
||||
>
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Actual Return Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={actualReturnDate}
|
||||
onChange={(e) => setActualReturnDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Return Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
placeholder="Condition, handover person, gate pass reference..."
|
||||
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}>
|
||||
Confirm Return
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,665 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import {
|
||||
Plus,
|
||||
Paperclip,
|
||||
Pencil,
|
||||
Trash2,
|
||||
ShieldCheck,
|
||||
Search,
|
||||
AlertCircle,
|
||||
Download,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import { insuranceApi, type InsuranceItem } from "@/api/phase5";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
import { departmentsApi, vendorsApi } from "@/api/masters";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate, formatINR } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { BulkGenericImportModal } from "@/components/BulkGenericImportModal";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
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";
|
||||
|
||||
const STATUS_CHIPS = [
|
||||
{ key: "", label: "All" },
|
||||
{ key: "active", label: "Active" },
|
||||
{ key: "expiring", label: "Expiring Soon" },
|
||||
{ key: "expired", label: "Expired" },
|
||||
];
|
||||
|
||||
export function InsurancePage() {
|
||||
const qc = useQueryClient();
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const isDeptUser = role === "department_user";
|
||||
const canManage = can(role, "manage_calibration_contracts");
|
||||
|
||||
const [statusFilter, setStatusFilter] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [insurerId, setInsurerId] = useState("");
|
||||
const [expiryFrom, setExpiryFrom] = useState("");
|
||||
const [expiryTo, setExpiryTo] = useState("");
|
||||
const [importModalOpen, setImportModalOpen] = useState(false);
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<InsuranceItem | null>(null);
|
||||
const [drawerAsset, setDrawerAsset] = useState<{
|
||||
assetId: number;
|
||||
label: string;
|
||||
} | null>(null);
|
||||
const [attachPolicy, setAttachPolicy] = useState<InsuranceItem | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<InsuranceItem | 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 policiesQuery = useQuery({
|
||||
queryKey: [
|
||||
"insurance",
|
||||
q,
|
||||
departmentId,
|
||||
insurerId,
|
||||
statusFilter,
|
||||
expiryFrom,
|
||||
expiryTo,
|
||||
],
|
||||
queryFn: () =>
|
||||
insuranceApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
insurer_id: insurerId ? Number(insurerId) : undefined,
|
||||
status: statusFilter || undefined,
|
||||
expiry_from: expiryFrom || undefined,
|
||||
expiry_to: expiryTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => insuranceApi.remove(id),
|
||||
onSuccess: () => {
|
||||
setDeleteTarget(null);
|
||||
qc.invalidateQueries({ queryKey: ["insurance"] });
|
||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
toast.success("Insurance policy deleted");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.detail : "Failed to delete insurance policy");
|
||||
},
|
||||
});
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const allVendors = vendorsQuery.data?.items ?? [];
|
||||
const insurers = allVendors.filter((v) => v.vendor_type === "insurer");
|
||||
const insurerOptions = insurers.length ? insurers : allVendors;
|
||||
|
||||
const columns: ColumnDef<InsuranceItem, unknown>[] = [
|
||||
{
|
||||
id: "asset",
|
||||
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
|
||||
header: "Asset",
|
||||
cell: ({ row }) => (
|
||||
<Link to={`/assets/${row.original.asset_id}`} className="hover:underline">
|
||||
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
|
||||
{row.original.asset_code}
|
||||
</div>
|
||||
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "insurer_name",
|
||||
header: "Insurer",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "policy_no",
|
||||
header: "Policy No",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono text-xs font-medium">{String(getValue())}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: "Start",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "end_date",
|
||||
header: "End",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "coverage_amount",
|
||||
header: "Coverage",
|
||||
cell: ({ getValue }) => formatINR(getValue() as number | null),
|
||||
},
|
||||
{
|
||||
id: "expiry",
|
||||
accessorFn: (r) => r.days_to_expiry,
|
||||
header: "Status",
|
||||
cell: ({ row }) => (
|
||||
<ExpiryChip
|
||||
daysToExpiry={row.original.days_to_expiry}
|
||||
status={row.original.status}
|
||||
severity={row.original.severity}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: "Docs",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setAttachPolicy(row.original)}
|
||||
title="View or upload policy certificates"
|
||||
>
|
||||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||
<span className="text-xs">{row.original.attachment_count}</span>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
setDrawerAsset({
|
||||
assetId: row.original.asset_id,
|
||||
label: `${row.original.asset_code} — ${row.original.asset_name}`,
|
||||
})
|
||||
}
|
||||
>
|
||||
<ShieldCheck className="h-3.5 w-3.5 mr-1" />
|
||||
Drawer
|
||||
</Button>
|
||||
{canManage && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditing(row.original);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
aria-label={`Edit policy ${row.original.policy_no}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => setDeleteTarget(row.original)}
|
||||
aria-label={`Delete policy ${row.original.policy_no}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
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">Asset Insurance</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Track insurance policies, coverage amounts, expiry alerts, and policy certificates
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await insuranceApi.downloadImportTemplate();
|
||||
toast.success("Downloaded Insurance import template (.xlsx)");
|
||||
} catch {
|
||||
toast.error("Failed to download template");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-1.5" />
|
||||
Template (.xlsx)
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setImportModalOpen(true)}
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-1.5" />
|
||||
Import (.xlsx)
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Add Insurance Policy
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 space-y-3">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{STATUS_CHIPS.map((chip) => (
|
||||
<button
|
||||
key={chip.key}
|
||||
type="button"
|
||||
onClick={() => setStatusFilter(chip.key)}
|
||||
className={`px-3 py-1 rounded-full text-xs font-medium border transition-colors ${
|
||||
statusFilter === chip.key
|
||||
? "bg-[#1e3a8a] text-white border-[#1e3a8a]"
|
||||
: "bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100"
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2.5">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Search asset code, name, policy no..."
|
||||
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={insurerId}
|
||||
onChange={(e) => setInsurerId(e.target.value)}
|
||||
aria-label="Filter by Insurer"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Insurers</option>
|
||||
{insurerOptions.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<div className="flex items-center gap-1.5 sm:col-span-2 lg:col-span-3">
|
||||
<span className="text-[11px] text-gray-500 whitespace-nowrap">Expiry:</span>
|
||||
<input
|
||||
type="date"
|
||||
value={expiryFrom}
|
||||
onChange={(e) => setExpiryFrom(e.target.value)}
|
||||
title="Expiry From"
|
||||
placeholder="From"
|
||||
className="px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||
/>
|
||||
<span className="text-[11px] text-gray-400">to</span>
|
||||
<input
|
||||
type="date"
|
||||
value={expiryTo}
|
||||
onChange={(e) => setExpiryTo(e.target.value)}
|
||||
title="Expiry To"
|
||||
placeholder="To"
|
||||
className="px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||
/>
|
||||
{(expiryFrom || expiryTo) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setExpiryFrom("");
|
||||
setExpiryTo("");
|
||||
}}
|
||||
className="text-[11px] text-[#1e3a8a] hover:underline whitespace-nowrap"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={policiesQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={policiesQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter insurance policies..."
|
||||
exportFilename="insurance-policies"
|
||||
emptyMessage="No insurance policies match the selected filters."
|
||||
/>
|
||||
|
||||
<InsuranceFormModal
|
||||
open={formOpen}
|
||||
onClose={() => setFormOpen(false)}
|
||||
editing={editing}
|
||||
insurers={insurerOptions}
|
||||
/>
|
||||
|
||||
<InsuranceDrawer
|
||||
open={Boolean(drawerAsset)}
|
||||
onClose={() => setDrawerAsset(null)}
|
||||
assetId={drawerAsset?.assetId ?? null}
|
||||
assetLabel={drawerAsset?.label}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={Boolean(attachPolicy)}
|
||||
onOpenChange={(o) => !o && setAttachPolicy(null)}
|
||||
title={`Policy Documents — ${attachPolicy?.policy_no ?? ""}`}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{attachPolicy && (
|
||||
<Attachments
|
||||
entityType="insurance"
|
||||
entityId={attachPolicy.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(deleteTarget)}
|
||||
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||
title="Delete Insurance Policy"
|
||||
message={`Are you sure you want to delete policy ${deleteTarget?.policy_no ?? ""}?`}
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => {
|
||||
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
||||
}}
|
||||
/>
|
||||
|
||||
<BulkGenericImportModal
|
||||
open={importModalOpen}
|
||||
onClose={() => setImportModalOpen(false)}
|
||||
title="Bulk Import Insurance Policies"
|
||||
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register or update multiple equipment insurance policies at once."
|
||||
entityName="Insurance Policies"
|
||||
templateFilename="insurance_import_template.xlsx"
|
||||
onDownloadTemplate={() => insuranceApi.downloadImportTemplate()}
|
||||
onImport={(file, dryRun, skipInvalid) => insuranceApi.bulkImport(file, dryRun, skipInvalid)}
|
||||
queryKeysToInvalidate={[["insurance"], ["dashboard"]]}
|
||||
previewColumns={[
|
||||
{ key: "asset_code", label: "Asset Code" },
|
||||
{ key: "insurer_name", label: "Insurer" },
|
||||
{ key: "policy_number", label: "Policy No" },
|
||||
{ key: "start_date", label: "Start Date" },
|
||||
{ key: "end_date", label: "End Date" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InsuranceFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing,
|
||||
insurers,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing: InsuranceItem | null;
|
||||
insurers: Array<{ id: number; name: string }>;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||||
const [insurerId, setInsurerId] = useState("");
|
||||
const [policyNo, setPolicyNo] = useState("");
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
const [coverageAmount, setCoverageAmount] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
if (editing) {
|
||||
setInsurerId(String(editing.insurer_id));
|
||||
setPolicyNo(editing.policy_no);
|
||||
setStartDate(editing.start_date);
|
||||
setEndDate(editing.end_date);
|
||||
setCoverageAmount(
|
||||
editing.coverage_amount != null ? String(editing.coverage_amount) : ""
|
||||
);
|
||||
setRemarks(editing.remarks ?? "");
|
||||
assetsApi
|
||||
.get(editing.asset_id)
|
||||
.then((a) =>
|
||||
setSelectedAsset({
|
||||
...a,
|
||||
contract_summary: a.contract_type ?? "None",
|
||||
insurance_summary: a.insurance_status,
|
||||
})
|
||||
)
|
||||
.catch(() => setSelectedAsset(null));
|
||||
} else {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const nextYear = new Date();
|
||||
nextYear.setFullYear(nextYear.getFullYear() + 1);
|
||||
setSelectedAsset(null);
|
||||
setInsurerId("");
|
||||
setPolicyNo("");
|
||||
setStartDate(today);
|
||||
setEndDate(nextYear.toISOString().slice(0, 10));
|
||||
setCoverageAmount("");
|
||||
setRemarks("");
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!editing && !selectedAsset) {
|
||||
setError("Please select an asset.");
|
||||
return;
|
||||
}
|
||||
if (!insurerId) {
|
||||
setError("Please select an insurer.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const payload = {
|
||||
insurer_id: Number(insurerId),
|
||||
policy_no: policyNo.trim(),
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
coverage_amount: coverageAmount.trim() !== "" ? Number(coverageAmount) : null,
|
||||
remarks: remarks.trim() || null,
|
||||
};
|
||||
if (editing) {
|
||||
await insuranceApi.update(editing.id, payload);
|
||||
} else {
|
||||
await insuranceApi.create({
|
||||
asset_id: selectedAsset!.id,
|
||||
...payload,
|
||||
});
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["insurance"] });
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to save insurance policy.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? `Edit Policy — ${editing.policy_no}` : "Add Insurance Policy"}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Asset *</label>
|
||||
<AssetPicker
|
||||
selectedAsset={selectedAsset}
|
||||
onSelect={setSelectedAsset}
|
||||
disabled={Boolean(editing)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Insurer *</label>
|
||||
<select
|
||||
required
|
||||
value={insurerId}
|
||||
onChange={(e) => setInsurerId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select insurer...</option>
|
||||
{insurers.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Policy Number *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={policyNo}
|
||||
onChange={(e) => setPolicyNo(e.target.value)}
|
||||
placeholder="e.g. POL-MED-2026-001"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Start Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>End Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Coverage Amount (INR)</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step="any"
|
||||
value={coverageAmount}
|
||||
onChange={(e) => setCoverageAmount(e.target.value)}
|
||||
placeholder="e.g. 500000"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Changes" : "Create Policy"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { useState } from "react";
|
||||
import { Navigate, useNavigate } from "react-router-dom";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { AlertCircle, LogIn, ShieldCheck } from "lucide-react";
|
||||
import { loginApi } from "@/api/auth";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email("Enter a valid email address"),
|
||||
password: z.string().min(1, "Password is required"),
|
||||
});
|
||||
|
||||
type LoginFormValues = z.infer<typeof loginSchema>;
|
||||
|
||||
const DEMO_ACCOUNTS = [
|
||||
{ label: "System Admin", email: "admin@poona.demo", hint: "Full system control" },
|
||||
{ label: "Biomedical", email: "bio@poona.demo", hint: "Assets, PM, repairs" },
|
||||
{ label: "Department User (ICU)", email: "dept@poona.demo", hint: "ICU complaints & assets" },
|
||||
{ label: "Management", email: "mgmt@poona.demo", hint: "Reports & oversight" },
|
||||
{ label: "Coordinator", email: "coord@poona.demo", hint: "Contracts, demo, calibration" },
|
||||
];
|
||||
|
||||
export function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { user, token, setAuth } = useAuthStore();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [quickLoadingEmail, setQuickLoadingEmail] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<LoginFormValues>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
defaultValues: { email: "", password: "" },
|
||||
});
|
||||
|
||||
if (token && user) {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
async function doLogin(email: string, password: string) {
|
||||
setServerError(null);
|
||||
try {
|
||||
const res = await loginApi(email, password);
|
||||
setAuth(res.user, res.access_token);
|
||||
navigate("/", { replace: true });
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setServerError(err.detail);
|
||||
} else {
|
||||
setServerError("Unable to reach server. Please ensure the backend is running.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function onSubmit(values: LoginFormValues) {
|
||||
await doLogin(values.email, values.password);
|
||||
}
|
||||
|
||||
async function handleQuickLogin(email: string) {
|
||||
setValue("email", email);
|
||||
setValue("password", "Demo@123");
|
||||
setQuickLoadingEmail(email);
|
||||
try {
|
||||
await doLogin(email, "Demo@123");
|
||||
} finally {
|
||||
setQuickLoadingEmail(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-gray-50 to-indigo-50 flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-md space-y-5">
|
||||
<div className="bg-white rounded-xl shadow-md border border-gray-200 p-6 sm:p-8">
|
||||
{/* Hospital Branding */}
|
||||
<div className="text-center mb-6">
|
||||
<img
|
||||
src="/logo.jpg"
|
||||
alt="Poona Hospital and Research Centre"
|
||||
className="h-20 mx-auto object-contain mb-3"
|
||||
/>
|
||||
<h1 className="text-xl font-bold text-[#1e3a8a]">
|
||||
Poona Hospital & Research Centre
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Asset Management & Maintenance System
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{serverError && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-4 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2.5 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{serverError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Email Address
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="you@poona.demo"
|
||||
{...register("email")}
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
{errors.email && (
|
||||
<p className="text-xs text-red-600 mt-1">{errors.email.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
placeholder="Enter your password"
|
||||
{...register("password")}
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
{errors.password && (
|
||||
<p className="text-xs text-red-600 mt-1">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" loading={isSubmitting}>
|
||||
<LogIn className="h-4 w-4 mr-2" />
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Quick Demo Login Panel */}
|
||||
<div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
|
||||
<div className="flex items-center gap-1.5 text-xs font-semibold text-gray-600 uppercase tracking-wide mb-2.5">
|
||||
<ShieldCheck className="h-4 w-4 text-[#1e3a8a]" />
|
||||
Quick Demo Login (Password: Demo@123)
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
{DEMO_ACCOUNTS.map((acct) => (
|
||||
<button
|
||||
key={acct.email}
|
||||
type="button"
|
||||
disabled={isSubmitting || quickLoadingEmail !== null}
|
||||
onClick={() => handleQuickLogin(acct.email)}
|
||||
className="text-left px-3 py-2 rounded-md border border-gray-200 hover:border-[#1e3a8a] hover:bg-blue-50/50 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<div className="text-xs font-semibold text-gray-800 flex items-center justify-between">
|
||||
<span>{acct.label}</span>
|
||||
{quickLoadingEmail === acct.email && (
|
||||
<span className="text-[10px] text-blue-600">Signing in…</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[11px] text-gray-500 truncate">{acct.email}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,256 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Bell,
|
||||
CheckCheck,
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
Info,
|
||||
ExternalLink,
|
||||
Check,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
notificationsApi,
|
||||
type NotificationItem,
|
||||
type NotificationType,
|
||||
} from "@/api/notifications";
|
||||
import { formatDate, formatDateTime } from "@/lib/format";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
const TYPE_OPTIONS: { value: NotificationType | ""; label: string }[] = [
|
||||
{ value: "", label: "All Types" },
|
||||
{ value: "amc_expiry", label: "AMC / CMC Expiry" },
|
||||
{ value: "calibration_due", label: "Calibration Due" },
|
||||
{ value: "pm_due", label: "PM Due" },
|
||||
{ value: "insurance_expiry", label: "Insurance Expiry" },
|
||||
{ value: "warranty_expiry", label: "Warranty Expiry" },
|
||||
{ value: "demo_overdue", label: "Demo Overdue" },
|
||||
{ value: "critical_complaint", label: "Critical Complaint" },
|
||||
{ value: "sla_breach", label: "SLA Breach" },
|
||||
];
|
||||
|
||||
const TYPE_LABELS: Record<string, string> = {
|
||||
amc_expiry: "AMC / CMC Expiry",
|
||||
calibration_due: "Calibration Due",
|
||||
pm_due: "PM Due",
|
||||
insurance_expiry: "Insurance Expiry",
|
||||
warranty_expiry: "Warranty Expiry",
|
||||
demo_overdue: "Demo Overdue",
|
||||
critical_complaint: "Critical Complaint",
|
||||
sla_breach: "SLA Breach",
|
||||
};
|
||||
|
||||
export function NotificationsPage() {
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
|
||||
const [typeFilter, setTypeFilter] = useState("");
|
||||
const [severityFilter, setSeverityFilter] = useState("");
|
||||
const [unreadOnly, setUnreadOnly] = useState(false);
|
||||
|
||||
const notifsQuery = useQuery({
|
||||
queryKey: ["notifications", "page", typeFilter, severityFilter, unreadOnly],
|
||||
queryFn: () =>
|
||||
notificationsApi.list({
|
||||
type: typeFilter || undefined,
|
||||
severity: severityFilter || undefined,
|
||||
unread_only: unreadOnly,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const markReadMutation = useMutation({
|
||||
mutationFn: (id: number) => notificationsApi.markRead(id),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["notifications"] });
|
||||
qc.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
},
|
||||
});
|
||||
|
||||
const markAllMutation = useMutation({
|
||||
mutationFn: () => notificationsApi.markAllRead(typeFilter || undefined),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["notifications"] });
|
||||
qc.invalidateQueries({ queryKey: ["dashboard"] });
|
||||
toast.success("Notifications marked as read");
|
||||
},
|
||||
});
|
||||
|
||||
const items = notifsQuery.data?.items ?? [];
|
||||
const unreadCount = notifsQuery.data?.unread_count ?? 0;
|
||||
|
||||
function handleOpen(n: NotificationItem) {
|
||||
if (!n.is_read) {
|
||||
markReadMutation.mutate(n.id);
|
||||
}
|
||||
if (n.link_url) {
|
||||
navigate(n.link_url);
|
||||
}
|
||||
}
|
||||
|
||||
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">Notifications Centre</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Hospital-wide and department-scoped alerts for PM, calibration, expiry, demo returns, and critical breakdowns
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={unreadCount === 0}
|
||||
loading={markAllMutation.isPending}
|
||||
onClick={() => markAllMutation.mutate()}
|
||||
>
|
||||
<CheckCheck className="h-4 w-4 mr-1.5" />
|
||||
Mark all read{unreadCount > 0 ? ` (${unreadCount})` : ""}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 flex flex-wrap items-center gap-3">
|
||||
<select
|
||||
aria-label="Filter by Type"
|
||||
value={typeFilter}
|
||||
onChange={(e) => setTypeFilter(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
{TYPE_OPTIONS.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<select
|
||||
aria-label="Filter by Severity"
|
||||
value={severityFilter}
|
||||
onChange={(e) => setSeverityFilter(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Severities</option>
|
||||
<option value="red">Red (Urgent / Overdue)</option>
|
||||
<option value="yellow">Yellow (Expiring / Due Soon)</option>
|
||||
<option value="info">Info</option>
|
||||
</select>
|
||||
|
||||
<label className="inline-flex items-center gap-2 text-xs text-gray-700 cursor-pointer ml-auto">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={unreadOnly}
|
||||
onChange={(e) => setUnreadOnly(e.target.checked)}
|
||||
className="h-3.5 w-3.5 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Unread Only
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Notifications List */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
{notifsQuery.isLoading ? (
|
||||
<div className="p-8 text-center text-sm text-gray-500">
|
||||
Loading notifications...
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="p-12 text-center space-y-2">
|
||||
<Bell className="h-8 w-8 text-gray-300 mx-auto" />
|
||||
<p className="text-sm font-medium text-gray-600">
|
||||
No notifications match your filters.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{items.map((n) => (
|
||||
<div
|
||||
key={n.id}
|
||||
className={`p-4 flex flex-wrap items-start justify-between gap-3 transition-colors ${
|
||||
n.is_read ? "bg-white" : "bg-blue-50/40"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-3 flex-1 min-w-0">
|
||||
<SeverityBadge severity={n.severity} />
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span
|
||||
className={`text-sm ${
|
||||
n.is_read
|
||||
? "font-medium text-gray-800"
|
||||
: "font-semibold text-gray-900"
|
||||
}`}
|
||||
>
|
||||
{n.title}
|
||||
</span>
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{TYPE_LABELS[n.type] ?? n.type}
|
||||
</Badge>
|
||||
{!n.is_read && <Badge variant="info">Unread</Badge>}
|
||||
</div>
|
||||
<p className="text-xs text-gray-600">{n.message}</p>
|
||||
<div className="flex flex-wrap items-center gap-4 text-[11px] text-gray-500 pt-0.5">
|
||||
<span>Due: {formatDate(n.due_date)}</span>
|
||||
<span>Created: {formatDateTime(n.created_at)}</span>
|
||||
{n.is_read && n.read_at && (
|
||||
<span>Read: {formatDateTime(n.read_at)}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{!n.is_read && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => markReadMutation.mutate(n.id)}
|
||||
title="Mark as read"
|
||||
>
|
||||
<Check className="h-3.5 w-3.5 mr-1" />
|
||||
Mark Read
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleOpen(n)}
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5 mr-1" />
|
||||
Open
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeverityBadge({ severity }: { severity: string }) {
|
||||
if (severity === "red") {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-red-100 text-red-800 border border-red-200 text-[11px] font-semibold uppercase shrink-0">
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
Red
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (severity === "yellow") {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-amber-100 text-amber-800 border border-amber-200 text-[11px] font-semibold uppercase shrink-0">
|
||||
<Clock className="h-3.5 w-3.5" />
|
||||
Yellow
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-blue-100 text-blue-800 border border-blue-200 text-[11px] font-semibold uppercase shrink-0">
|
||||
<Info className="h-3.5 w-3.5" />
|
||||
Info
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,786 @@
|
||||
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,
|
||||
Paperclip,
|
||||
} 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 { CoverageBadge, ScheduleStatusBadge } from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
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 [attachRec, setAttachRec] = 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>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: "Reports",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setAttachRec(row.original)}
|
||||
aria-label={`Attachments for PM ${row.original.id}`}
|
||||
>
|
||||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||
Docs
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
...(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: "coverage_tag",
|
||||
header: "Coverage",
|
||||
enableColumnFilter: true,
|
||||
cell: ({ row }) => (
|
||||
<CoverageBadge
|
||||
coverage={row.original.coverage}
|
||||
tag={row.original.coverage_tag}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
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="overflow-x-auto">
|
||||
<div className="min-w-[640px]">
|
||||
<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>
|
||||
</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}
|
||||
/>
|
||||
|
||||
{attachRec && (
|
||||
<Modal
|
||||
open={Boolean(attachRec)}
|
||||
onOpenChange={(o) => !o && setAttachRec(null)}
|
||||
title={`PM Service Reports — ${attachRec.asset_code} (${attachRec.asset_name})`}
|
||||
>
|
||||
<Attachments
|
||||
entityType="pm_record"
|
||||
entityId={attachRec.id}
|
||||
canUpload={canManagePm}
|
||||
canDelete={canManagePm}
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,131 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
BarChart3,
|
||||
Building2,
|
||||
ClipboardCheck,
|
||||
AlertTriangle,
|
||||
CalendarCheck,
|
||||
Gauge,
|
||||
FileSpreadsheet,
|
||||
Truck,
|
||||
ArrowRight,
|
||||
} from "lucide-react";
|
||||
import { REPORT_CATALOG, type ReportKey } from "@/api/reports";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
const REPORT_ICONS: Record<ReportKey, React.ComponentType<{ className?: string }>> = {
|
||||
"monthly-maintenance": BarChart3,
|
||||
"monthly-department": Building2,
|
||||
"daily-visit": ClipboardCheck,
|
||||
"breakdown-complaints": AlertTriangle,
|
||||
"pm-compliance": CalendarCheck,
|
||||
"calibration-due": Gauge,
|
||||
"contracts-warranty": FileSpreadsheet,
|
||||
"demo-equipment": Truck,
|
||||
};
|
||||
|
||||
export function ReportsPage() {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const role = user?.role;
|
||||
|
||||
const visibleReports = REPORT_CATALOG.filter(
|
||||
(r) => !role || !r.hiddenForRoles?.includes(role)
|
||||
);
|
||||
|
||||
const canViewAI = can(role, "view_ai_reports");
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Reports & Exports</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Operational reports with live filters, Excel (.xlsx) & CSV downloads, and A4 print layout
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2.5 flex-wrap">
|
||||
{canViewAI && (
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label="Report mode"
|
||||
className="inline-flex rounded-lg border border-gray-200 bg-gray-100 p-0.5"
|
||||
>
|
||||
<span
|
||||
role="tab"
|
||||
aria-selected={true}
|
||||
className="px-3 py-1.5 text-xs font-semibold rounded-md bg-white text-[#1e3a8a] shadow-sm"
|
||||
>
|
||||
Simple reports
|
||||
</span>
|
||||
<Link
|
||||
to="/reports/ai"
|
||||
role="tab"
|
||||
aria-selected={false}
|
||||
className="px-3 py-1.5 text-xs font-medium rounded-md text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
AI report
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
{role === "department_user" && user?.department_name && (
|
||||
<Badge variant="info">
|
||||
Department Scope: {user.department_name}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
|
||||
{visibleReports.map((report) => {
|
||||
const Icon = REPORT_ICONS[report.key] ?? BarChart3;
|
||||
return (
|
||||
<Link
|
||||
key={report.key}
|
||||
to={`/reports/${report.key}`}
|
||||
className="group bg-white border border-gray-200 rounded-xl p-5 shadow-sm hover:shadow-md hover:border-[#1e3a8a]/40 transition-all flex flex-col justify-between"
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="h-10 w-10 rounded-lg bg-blue-50 border border-blue-100 flex items-center justify-center text-[#1e3a8a]">
|
||||
<Icon className="h-5 w-5" />
|
||||
</div>
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{report.category}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-gray-900 group-hover:text-[#1e3a8a] transition-colors">
|
||||
{report.title}
|
||||
</h2>
|
||||
<p className="text-xs text-gray-600 mt-1 leading-relaxed">
|
||||
{report.description}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5 flex-wrap pt-2.5">
|
||||
<span className="inline-flex items-center text-[10px] text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded font-medium border border-emerald-100">
|
||||
Excel (.xlsx)
|
||||
</span>
|
||||
<span className="inline-flex items-center text-[10px] text-blue-700 bg-blue-50 px-2 py-0.5 rounded font-medium border border-blue-100">
|
||||
A4 / PDF Print
|
||||
</span>
|
||||
{report.key === "monthly-maintenance" && (
|
||||
<span className="inline-flex items-center text-[10px] text-purple-700 bg-purple-50 px-2 py-0.5 rounded font-medium border border-purple-100">
|
||||
Interactive Charts
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 pt-3 border-t border-gray-100 flex items-center justify-between text-xs font-medium text-[#1e3a8a]">
|
||||
<span>Open Report</span>
|
||||
<ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { Save, CheckCircle2, AlertCircle, X, Cpu } from "lucide-react";
|
||||
import { settingsApi, type SettingItem } from "@/api/settings";
|
||||
import { aiApi } from "@/api/ai";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const AI_COST_SETTING_KEYS = new Set([
|
||||
"comparison_horizon_years",
|
||||
"latest_equipment_count",
|
||||
"default_useful_life_years",
|
||||
"default_salvage_pct",
|
||||
"default_depreciation_method",
|
||||
"repeat_failure_count",
|
||||
"repeat_failure_days",
|
||||
"replacement_review_ratio",
|
||||
]);
|
||||
|
||||
const HIDDEN_SETTING_KEYS = new Set(["ai_enabled"]);
|
||||
|
||||
export function SettingsPage() {
|
||||
const qc = useQueryClient();
|
||||
const setDemoAsOfDate = useAuthStore((s) => s.setDemoAsOfDate);
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const isAdmin = role === "system_admin";
|
||||
|
||||
const [draft, setDraft] = useState<Record<string, unknown>>({});
|
||||
const [savedNotice, setSavedNotice] = useState(false);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
|
||||
const { data, isLoading, isError, error } = useQuery({
|
||||
queryKey: ["settings"],
|
||||
queryFn: settingsApi.getAll,
|
||||
});
|
||||
|
||||
const aiStatusQuery = useQuery({
|
||||
queryKey: ["ai-status"],
|
||||
queryFn: aiApi.getStatus,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.items) {
|
||||
const next: Record<string, unknown> = {};
|
||||
for (const item of data.items) {
|
||||
next[item.key] = item.value ?? "";
|
||||
}
|
||||
setDraft(next);
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (values: Record<string, unknown>) => settingsApi.updateAll(values),
|
||||
onSuccess: async (res) => {
|
||||
setErrorMsg(null);
|
||||
setSavedNotice(true);
|
||||
const demoItem = res.items.find((i) => i.key === "demo_as_of_date");
|
||||
if (demoItem !== undefined) {
|
||||
const val = typeof demoItem.value === "string" && demoItem.value ? demoItem.value : null;
|
||||
setDemoAsOfDate(val);
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["settings"] });
|
||||
await qc.invalidateQueries();
|
||||
setTimeout(() => setSavedNotice(false), 3500);
|
||||
},
|
||||
onError: (err) => {
|
||||
setSavedNotice(false);
|
||||
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to save settings.");
|
||||
},
|
||||
});
|
||||
|
||||
function handleChange(item: SettingItem, raw: unknown) {
|
||||
setSavedNotice(false);
|
||||
setDraft((prev) => ({ ...prev, [item.key]: raw }));
|
||||
}
|
||||
|
||||
function handleSave(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!data?.items) return;
|
||||
setErrorMsg(null);
|
||||
|
||||
const values: Record<string, unknown> = {};
|
||||
for (const item of data.items) {
|
||||
const raw = draft[item.key];
|
||||
if (item.type === "int") {
|
||||
const num = Number(raw);
|
||||
if (Number.isNaN(num)) {
|
||||
setErrorMsg(`"${item.label}" must be a valid integer.`);
|
||||
return;
|
||||
}
|
||||
values[item.key] = Math.trunc(num);
|
||||
} else if (item.type === "float") {
|
||||
const num = Number(raw);
|
||||
if (Number.isNaN(num)) {
|
||||
setErrorMsg(`"${item.label}" must be a valid number.`);
|
||||
return;
|
||||
}
|
||||
values[item.key] = num;
|
||||
} else if (item.type === "bool") {
|
||||
values[item.key] = Boolean(raw);
|
||||
} else if (item.type === "date_or_empty") {
|
||||
values[item.key] = raw ? String(raw) : "";
|
||||
} else {
|
||||
values[item.key] = raw == null ? "" : String(raw);
|
||||
}
|
||||
}
|
||||
saveMutation.mutate(values);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="max-w-3xl space-y-4">
|
||||
<div className="h-8 w-48 bg-gray-200 rounded animate-pulse" />
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<div key={i} className="h-20 bg-white border border-gray-200 rounded-lg animate-pulse" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<div className="max-w-3xl rounded-lg bg-red-50 border border-red-200 p-4 text-sm text-red-700">
|
||||
{error instanceof ApiError ? error.detail : "Failed to load settings."}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const generalItems = (data?.items ?? []).filter(
|
||||
(item) => !AI_COST_SETTING_KEYS.has(item.key) && !HIDDEN_SETTING_KEYS.has(item.key)
|
||||
);
|
||||
const aiCostItems = (data?.items ?? []).filter(
|
||||
(item) => AI_COST_SETTING_KEYS.has(item.key) && !HIDDEN_SETTING_KEYS.has(item.key)
|
||||
);
|
||||
|
||||
function renderSettingRow(item: SettingItem) {
|
||||
const val = draft[item.key];
|
||||
return (
|
||||
<div
|
||||
key={item.key}
|
||||
className="p-4 sm:p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4"
|
||||
>
|
||||
<div className="space-y-1 flex-1">
|
||||
<label htmlFor={`setting-${item.key}`} className="block text-sm font-semibold text-gray-800">
|
||||
{item.label}
|
||||
</label>
|
||||
<p className="text-xs text-gray-500">{item.description}</p>
|
||||
<p className="text-[11px] text-gray-400">
|
||||
Default: <code className="bg-gray-100 px-1 rounded">{String(item.default || "empty")}</code>
|
||||
{(item.type === "int" || item.type === "float") && item.min != null && item.max != null && (
|
||||
<> • Range: {item.min}–{item.max}</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="sm:w-64 shrink-0">
|
||||
{(item.type === "int" || item.type === "float") && (
|
||||
<input
|
||||
id={`setting-${item.key}`}
|
||||
type="number"
|
||||
step={item.type === "float" ? "any" : "1"}
|
||||
min={item.min ?? undefined}
|
||||
max={item.max ?? undefined}
|
||||
value={val === undefined || val === null ? "" : String(val)}
|
||||
onChange={(e) => handleChange(item, e.target.value)}
|
||||
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
)}
|
||||
|
||||
{item.type === "bool" && (
|
||||
<label className="inline-flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
id={`setting-${item.key}`}
|
||||
type="checkbox"
|
||||
checked={Boolean(val)}
|
||||
onChange={(e) => handleChange(item, e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a] focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm text-gray-700">{val ? "Enabled" : "Disabled"}</span>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{item.type === "enum" && (
|
||||
<select
|
||||
id={`setting-${item.key}`}
|
||||
value={String(val ?? "")}
|
||||
onChange={(e) => handleChange(item, e.target.value)}
|
||||
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
|
||||
>
|
||||
{item.options?.map((opt) => (
|
||||
<option key={opt} value={opt}>
|
||||
{opt}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
|
||||
{item.type === "str" && (
|
||||
<input
|
||||
id={`setting-${item.key}`}
|
||||
type="text"
|
||||
value={String(val ?? "")}
|
||||
onChange={(e) => handleChange(item, e.target.value)}
|
||||
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
)}
|
||||
|
||||
{item.type === "date_or_empty" && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<input
|
||||
id={`setting-${item.key}`}
|
||||
type="date"
|
||||
value={String(val ?? "")}
|
||||
onChange={(e) => handleChange(item, e.target.value)}
|
||||
className="flex-1 px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
{Boolean(val) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleChange(item, "")}
|
||||
title="Clear date"
|
||||
className="p-1.5 rounded border border-gray-300 text-gray-500 hover:bg-gray-100"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSave} className="max-w-3xl space-y-5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">System Settings</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Configure lead days, downtime computation rules, escalation thresholds, AI cost analysis, and demo clock.
|
||||
</p>
|
||||
</div>
|
||||
<Button type="submit" loading={saveMutation.isPending}>
|
||||
<Save className="h-4 w-4 mr-1.5" />
|
||||
Save Settings
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{savedNotice && (
|
||||
<div className="flex items-center gap-2 rounded-md bg-green-50 border border-green-200 px-4 py-2.5 text-sm text-green-800">
|
||||
<CheckCircle2 className="h-4 w-4 shrink-0" />
|
||||
Settings saved successfully.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errorMsg && (
|
||||
<div className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-4 py-2.5 text-sm text-red-700">
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{errorMsg}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* General Operational Settings */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 divide-y divide-gray-100">
|
||||
{generalItems.map(renderSettingRow)}
|
||||
</div>
|
||||
|
||||
{/* AI and Cost Analysis Group */}
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<div className="px-4 sm:px-5 py-3.5 bg-slate-50 border-b border-gray-200 flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Cpu className="h-4 w-4 text-[#1e3a8a]" />
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-gray-900">AI and cost analysis</h2>
|
||||
<p className="text-xs text-gray-500">
|
||||
Depreciation defaults, scenario comparison horizon, and repeat-failure thresholds.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Read-only AI runtime status */}
|
||||
<div className="px-4 sm:px-5 py-3 bg-blue-50/40 border-b border-gray-100 flex flex-wrap items-center justify-between gap-3 text-xs">
|
||||
<div>
|
||||
<span className="text-gray-500 block">AI Summary Status</span>
|
||||
<span
|
||||
className={
|
||||
aiStatusQuery.data?.reachable && aiStatusQuery.data?.enabled
|
||||
? "inline-flex items-center font-semibold text-emerald-700"
|
||||
: "inline-flex items-center font-semibold text-gray-600"
|
||||
}
|
||||
>
|
||||
{aiStatusQuery.isLoading
|
||||
? "Checking..."
|
||||
: aiStatusQuery.data?.reachable && aiStatusQuery.data?.enabled
|
||||
? "Active (Automated Analysis Enabled)"
|
||||
: "Standby (Rule-based summaries)"}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 block">System Privacy</span>
|
||||
<span className="font-semibold text-gray-700">100% In-House & Secure</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-gray-100">{aiCostItems.map(renderSettingRow)}</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import {
|
||||
Plus,
|
||||
Pencil,
|
||||
AlertTriangle,
|
||||
Search,
|
||||
AlertCircle,
|
||||
CheckSquare,
|
||||
} from "lucide-react";
|
||||
import { visitsApi, type VisitItem } from "@/api/phase5";
|
||||
import { assetsApi } from "@/api/assets";
|
||||
import { departmentsApi } from "@/api/masters";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { CallStatusBadge } from "@/components/StatusBadge";
|
||||
import { RaiseComplaintModal } from "@/components/RaiseComplaintModal";
|
||||
|
||||
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";
|
||||
|
||||
export function VisitsPage() {
|
||||
const qc = useQueryClient();
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const canManage = can(role, "manage_visits");
|
||||
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
|
||||
const [visitModalOpen, setVisitModalOpen] = useState(false);
|
||||
const [editingVisit, setEditingVisit] = useState<VisitItem | null>(null);
|
||||
const [complaintVisitTarget, setComplaintVisitTarget] = useState<VisitItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
});
|
||||
|
||||
const visitsQuery = useQuery({
|
||||
queryKey: ["visits", q, departmentId, dateFrom, dateTo],
|
||||
queryFn: () =>
|
||||
visitsApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: departmentId ? Number(departmentId) : undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
|
||||
const columns: ColumnDef<VisitItem, unknown>[] = [
|
||||
{
|
||||
accessorKey: "visit_date",
|
||||
header: "Visit Date",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap font-medium">
|
||||
{formatDate(getValue() as string)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "visited_by_name",
|
||||
header: "Visited By",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
id: "assets",
|
||||
header: "Equipment Checked",
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => r.assets.map((a) => `${a.asset_code} ${a.name}`).join(" "),
|
||||
cell: ({ row }) =>
|
||||
row.original.assets.length === 0 ? (
|
||||
<span className="text-xs text-gray-400">None</span>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-1 max-w-xs">
|
||||
{row.original.assets.map((a) => (
|
||||
<Link
|
||||
key={a.id}
|
||||
to={`/assets/${a.id}`}
|
||||
title={a.name}
|
||||
className="inline-flex items-center px-2 py-0.5 rounded bg-blue-50 text-[#1e3a8a] border border-blue-200 font-mono text-[11px] hover:bg-blue-100"
|
||||
>
|
||||
{a.asset_code}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "observations",
|
||||
header: "Observations & Requirements",
|
||||
cell: ({ row }) => (
|
||||
<div className="space-y-1 max-w-sm">
|
||||
<p className="text-xs text-gray-800 whitespace-pre-wrap">{row.original.observations}</p>
|
||||
{row.original.new_requirements && (
|
||||
<p className="text-xs text-blue-700 bg-blue-50 border border-blue-100 rounded px-1.5 py-0.5">
|
||||
<span className="font-semibold">Requirements:</span> {row.original.new_requirements}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "complaints",
|
||||
header: "Linked Complaints",
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => r.complaints.map((c) => c.complaint_no).join(" "),
|
||||
cell: ({ row }) =>
|
||||
row.original.complaints.length === 0 ? (
|
||||
<span className="text-xs text-gray-400">—</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1">
|
||||
{row.original.complaints.map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
to={`/complaints/${c.id}`}
|
||||
className="inline-flex items-center gap-1.5 text-xs hover:underline"
|
||||
>
|
||||
<span className="font-mono font-semibold text-[#1e3a8a]">
|
||||
{c.complaint_no}
|
||||
</span>
|
||||
<CallStatusBadge status={c.call_status} />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
...(canManage
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: VisitItem } }) => (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setComplaintVisitTarget(row.original)}
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5 mr-1 text-amber-600" />
|
||||
Raise Complaint
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditingVisit(row.original);
|
||||
setVisitModalOpen(true);
|
||||
}}
|
||||
aria-label={`Edit visit ${row.original.id}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
} satisfies ColumnDef<VisitItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Department Visits</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Daily biomedical rounds, equipment checks, observations, and breakdown escalation
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditingVisit(null);
|
||||
setVisitModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Log Visit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 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 observations, department, visitor..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Visit Date From"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Visit Date To"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={visitsQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={visitsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter visits..."
|
||||
exportFilename="department-visits"
|
||||
emptyMessage="No department visits recorded yet."
|
||||
/>
|
||||
|
||||
{canManage && (
|
||||
<>
|
||||
<VisitFormModal
|
||||
open={visitModalOpen}
|
||||
onClose={() => setVisitModalOpen(false)}
|
||||
editing={editingVisit}
|
||||
departments={departments}
|
||||
onCreatedAndRaise={(created) => setComplaintVisitTarget(created)}
|
||||
/>
|
||||
|
||||
<RaiseComplaintModal
|
||||
open={Boolean(complaintVisitTarget)}
|
||||
onClose={() => setComplaintVisitTarget(null)}
|
||||
initialAssetId={complaintVisitTarget?.assets[0]?.id ?? null}
|
||||
initialDescription={complaintVisitTarget?.observations ?? ""}
|
||||
navigateOnCreate={false}
|
||||
onCreated={async (complaint) => {
|
||||
if (!complaintVisitTarget) return;
|
||||
await visitsApi.linkComplaint(complaintVisitTarget.id, complaint.id);
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VisitFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing,
|
||||
departments,
|
||||
onCreatedAndRaise,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing: VisitItem | null;
|
||||
departments: Array<{ id: number; name: string }>;
|
||||
onCreatedAndRaise: (visit: VisitItem) => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [visitDate, setVisitDate] = useState("");
|
||||
const [observations, setObservations] = useState("");
|
||||
const [newRequirements, setNewRequirements] = useState("");
|
||||
const [selectedAssetIds, setSelectedAssetIds] = useState<number[]>([]);
|
||||
const [assetSearch, setAssetSearch] = useState("");
|
||||
const [raiseImmediately, setRaiseImmediately] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
setAssetSearch("");
|
||||
setRaiseImmediately(false);
|
||||
if (editing) {
|
||||
setDepartmentId(String(editing.department_id));
|
||||
setVisitDate(editing.visit_date);
|
||||
setObservations(editing.observations);
|
||||
setNewRequirements(editing.new_requirements ?? "");
|
||||
setSelectedAssetIds(editing.assets.map((a) => a.id));
|
||||
} else {
|
||||
setDepartmentId("");
|
||||
setVisitDate(new Date().toISOString().slice(0, 10));
|
||||
setObservations("");
|
||||
setNewRequirements("");
|
||||
setSelectedAssetIds([]);
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
const deptAssetsQuery = useQuery({
|
||||
queryKey: ["assets", "visit-checklist", departmentId],
|
||||
queryFn: () =>
|
||||
assetsApi.lookup({
|
||||
department_id: departmentId ? Number(departmentId) : undefined,
|
||||
limit: 200,
|
||||
}),
|
||||
enabled: open && Boolean(departmentId),
|
||||
});
|
||||
|
||||
const filteredAssets = useMemo(() => {
|
||||
const list = deptAssetsQuery.data?.items ?? [];
|
||||
const term = assetSearch.trim().toLowerCase();
|
||||
if (!term) return list;
|
||||
return list.filter((a) =>
|
||||
`${a.asset_code} ${a.name} ${a.location_name ?? ""}`
|
||||
.toLowerCase()
|
||||
.includes(term)
|
||||
);
|
||||
}, [deptAssetsQuery.data?.items, assetSearch]);
|
||||
|
||||
function toggleAsset(id: number) {
|
||||
setSelectedAssetIds((prev) =>
|
||||
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!departmentId) {
|
||||
setError("Please select a department.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (editing) {
|
||||
await visitsApi.update(editing.id, {
|
||||
department_id: Number(departmentId),
|
||||
visit_date: visitDate,
|
||||
observations: observations.trim(),
|
||||
new_requirements: newRequirements.trim() || null,
|
||||
asset_ids: selectedAssetIds,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
onClose();
|
||||
} else {
|
||||
const created = await visitsApi.create({
|
||||
department_id: Number(departmentId),
|
||||
visit_date: visitDate,
|
||||
observations: observations.trim(),
|
||||
new_requirements: newRequirements.trim() || null,
|
||||
asset_ids: selectedAssetIds,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
onClose();
|
||||
if (raiseImmediately) {
|
||||
onCreatedAndRaise(created);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to save visit.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? "Edit Department Visit" : "Log Department Visit"}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Department *</label>
|
||||
<select
|
||||
required
|
||||
value={departmentId}
|
||||
onChange={(e) => {
|
||||
setDepartmentId(e.target.value);
|
||||
if (!editing) setSelectedAssetIds([]);
|
||||
}}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select department...</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Visit Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={visitDate}
|
||||
onChange={(e) => setVisitDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<label className="text-sm font-medium text-gray-700 flex items-center gap-1.5">
|
||||
<CheckSquare className="h-4 w-4 text-[#1e3a8a]" />
|
||||
Equipment Checked ({selectedAssetIds.length} selected)
|
||||
</label>
|
||||
{departmentId && (
|
||||
<input
|
||||
type="text"
|
||||
value={assetSearch}
|
||||
onChange={(e) => setAssetSearch(e.target.value)}
|
||||
placeholder="Filter department equipment..."
|
||||
className="px-2.5 py-1 text-xs border border-gray-200 rounded-md w-52"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="max-h-44 overflow-y-auto border border-gray-200 rounded-md divide-y divide-gray-100 bg-gray-50/40">
|
||||
{!departmentId ? (
|
||||
<div className="p-4 text-center text-xs text-gray-400">
|
||||
Select a department to view its equipment checklist.
|
||||
</div>
|
||||
) : deptAssetsQuery.isLoading ? (
|
||||
<div className="p-4 text-center text-xs text-gray-500">
|
||||
Loading department equipment...
|
||||
</div>
|
||||
) : filteredAssets.length === 0 ? (
|
||||
<div className="p-4 text-center text-xs text-gray-400">
|
||||
No matching assets found in this department.
|
||||
</div>
|
||||
) : (
|
||||
filteredAssets.map((a) => (
|
||||
<label
|
||||
key={a.id}
|
||||
className="flex items-center justify-between gap-2 px-3 py-2 text-xs hover:bg-blue-50/50 cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedAssetIds.includes(a.id)}
|
||||
onChange={() => toggleAsset(a.id)}
|
||||
className="h-3.5 w-3.5 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
<span className="font-mono font-semibold text-[#1e3a8a]">
|
||||
{a.asset_code}
|
||||
</span>
|
||||
<span className="text-gray-800 truncate">{a.name}</span>
|
||||
</div>
|
||||
<Badge variant="outline" className="text-[10px] shrink-0">
|
||||
{a.location_name || "—"}
|
||||
</Badge>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Observations *</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
required
|
||||
value={observations}
|
||||
onChange={(e) => setObservations(e.target.value)}
|
||||
placeholder="Round findings, preventive checks, nurse feedback, issues spotted..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>New Equipment / Maintenance Requirements</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={newRequirements}
|
||||
onChange={(e) => setNewRequirements(e.target.value)}
|
||||
placeholder="e.g. Additional infusion pumps requested, new mounting brackets needed..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!editing && (
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={raiseImmediately}
|
||||
onChange={(e) => setRaiseImmediately(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Raise & link a complaint immediately from this observation
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Visit" : raiseImmediately ? "Save & Raise Complaint" : "Save Visit"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { ResetPasswordModal } from "@/pages/MastersPage";
|
||||
import { usersApi, type MasterUser } from "@/api/masters";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { ApiError } from "@/api/client";
|
||||
|
||||
const mockUser: MasterUser = {
|
||||
id: 42,
|
||||
name: "Dr. Jane Doe",
|
||||
email: "jane@poona.demo",
|
||||
role: "department_user",
|
||||
department_id: 2,
|
||||
department_name: "Cardiology",
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
describe("Admin ResetPasswordModal", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("renders the dialog with user details, helper text, and show/hide password toggle", () => {
|
||||
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||
|
||||
expect(screen.getByText("Reset Password for Dr. Jane Doe")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("Enter new password")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("Re-enter new password")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("At least 8 characters, with a letter and a number.")
|
||||
).toBeInTheDocument();
|
||||
|
||||
const input = screen.getByPlaceholderText("Enter new password");
|
||||
expect(input).toHaveAttribute("type", "password");
|
||||
|
||||
const toggleBtn = screen.getByLabelText("Show password");
|
||||
fireEvent.click(toggleBtn);
|
||||
expect(input).toHaveAttribute("type", "text");
|
||||
expect(screen.getByLabelText("Hide password")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("validates password mismatch before calling API", async () => {
|
||||
const resetSpy = vi.spyOn(usersApi, "resetPassword").mockResolvedValue({ message: "OK" });
|
||||
|
||||
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||
target: { value: "SecurePass1" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||
target: { value: "DifferentPass2" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/passwords do not match/i)).toBeInTheDocument();
|
||||
});
|
||||
expect(resetSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls API on match, shows success toast, and closes dialog", async () => {
|
||||
const onClose = vi.fn();
|
||||
const resetSpy = vi
|
||||
.spyOn(usersApi, "resetPassword")
|
||||
.mockResolvedValue({ message: "Password reset successfully." });
|
||||
const toastSpy = vi.spyOn(toast, "success");
|
||||
|
||||
render(<ResetPasswordModal user={mockUser} onClose={onClose} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||
target: { value: "NewSecure99" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||
target: { value: "NewSecure99" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(resetSpy).toHaveBeenCalledWith(42, "NewSecure99");
|
||||
expect(toastSpy).toHaveBeenCalledWith("Password for Dr. Jane Doe has been reset.");
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("displays server error message when API returns 422 error", async () => {
|
||||
vi.spyOn(usersApi, "resetPassword").mockRejectedValue(
|
||||
new ApiError(422, "Password must not start or end with a space.")
|
||||
);
|
||||
|
||||
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||
target: { value: " SpacePass1 " },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||
target: { value: " SpacePass1 " },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText("Password must not start or end with a space.")
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,502 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ReportsPage } from "@/pages/ReportsPage";
|
||||
import { AIReportPage } from "@/pages/AIReportPage";
|
||||
import { SettingsPage } from "@/pages/SettingsPage";
|
||||
import { aiApi } from "@/api/ai";
|
||||
import { categoriesApi, departmentsApi } from "@/api/masters";
|
||||
import { settingsApi } from "@/api/settings";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
vi.mock("recharts", async () => {
|
||||
const actual = await vi.importActual<typeof import("recharts")>("recharts");
|
||||
return {
|
||||
...actual,
|
||||
ResponsiveContainer: ({ children }: { children: React.ReactNode }) => (
|
||||
<div style={{ width: 640, height: 240 }}>{children}</div>
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
function renderWithProviders(ui: React.ReactNode, initialEntries = ["/"]) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter initialEntries={initialEntries}>{ui}</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const RULE_BASED_NARRATIVE = {
|
||||
source: "rule_based" as const,
|
||||
model: null,
|
||||
validated: true,
|
||||
failure_reason: null,
|
||||
generated_at: "2026-11-18T00:00:00Z",
|
||||
headline: "Rule-based headline summary.",
|
||||
bullets: [{ text: "Deterministic bullet from computed evidence.", metric_ids: ["m_cmp_latest_count"] }],
|
||||
};
|
||||
|
||||
function mockAllAIEndpoints() {
|
||||
vi.spyOn(departmentsApi, "list").mockResolvedValue({
|
||||
items: [{ id: 1, name: "ICU", code: "ICU", description: null, is_active: true }],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(categoriesApi, "list").mockResolvedValue({
|
||||
items: [{ id: 1, name: "Ventilator", description: null, is_active: true }],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(aiApi, "getStatus").mockResolvedValue({
|
||||
enabled: false,
|
||||
ai_enabled_setting: false,
|
||||
provider: "none",
|
||||
model: "",
|
||||
reachable: false,
|
||||
});
|
||||
vi.spyOn(aiApi, "getSummary").mockResolvedValue({
|
||||
section: "summary",
|
||||
title: "AI Report Executive Summary",
|
||||
period_start: "2025-11-18",
|
||||
period_end: "2026-11-18",
|
||||
sections: {
|
||||
comparison: {
|
||||
latest_count: 1,
|
||||
horizon_years: 5,
|
||||
in_house_lowest_count: 1,
|
||||
outsourced_lowest_count: 0,
|
||||
rent_lowest_count: 0,
|
||||
},
|
||||
depreciation: {
|
||||
total_purchase_value: 1000000,
|
||||
total_book_value: 715000,
|
||||
total_accumulated_depreciation: 285000,
|
||||
total_maintenance_cost: 50000,
|
||||
fully_depreciated_count: 0,
|
||||
review_flag_count: 0,
|
||||
replacement_review_ratio: 0.4,
|
||||
excluded_count: 0,
|
||||
},
|
||||
efficiency: {
|
||||
assets_in_scope: 10,
|
||||
avg_uptime_pct: 99.2,
|
||||
mttr_hours: 3.5,
|
||||
mtbf_hours: 720.0,
|
||||
avg_response_minutes: 45,
|
||||
pm_compliance_pct: 95.0,
|
||||
avg_efficiency_score: 96.4,
|
||||
},
|
||||
breakdown_frequency: {
|
||||
total_breakdowns: 5,
|
||||
assets_in_scope: 10,
|
||||
avg_breakdowns_per_equipment: 0.5,
|
||||
repeat_failure_count: 1,
|
||||
repeat_threshold: 3,
|
||||
repeat_window_days: 90,
|
||||
},
|
||||
},
|
||||
suggestions: [
|
||||
{
|
||||
id: "S1_PHRC_ICU_0001",
|
||||
rule: "S1",
|
||||
severity: "red",
|
||||
title: "Repeat failure on PHRC-ICU-0001 (ICU Ventilator)",
|
||||
detail: "PHRC-ICU-0001 recorded 4 breakdowns in 90 days.",
|
||||
asset_codes: ["PHRC-ICU-0001"],
|
||||
evidence_metric_ids: ["m_bf_repeat_window_PHRC_ICU_0001"],
|
||||
action_for_human: "Review root cause and escalate to the vendor. Needs a human decision.",
|
||||
},
|
||||
],
|
||||
suggestions_evidence: [
|
||||
{
|
||||
id: "m_bf_repeat_window_PHRC_ICU_0001",
|
||||
label: "Breakdowns in Last 90d (PHRC-ICU-0001)",
|
||||
value: 4,
|
||||
unit: "count",
|
||||
formatted: "4",
|
||||
},
|
||||
],
|
||||
metrics: [
|
||||
{
|
||||
id: "m_cmp_latest_count",
|
||||
label: "Latest Equipment Evaluated",
|
||||
value: 1,
|
||||
unit: "count",
|
||||
formatted: "1",
|
||||
},
|
||||
],
|
||||
narrative: RULE_BASED_NARRATIVE,
|
||||
how_calculated: { formulas: ["Test formula"], settings_used: { comparison_horizon_years: 5 } },
|
||||
});
|
||||
|
||||
vi.spyOn(aiApi, "getComparison").mockResolvedValue({
|
||||
section: "comparison",
|
||||
title: "Comparison: In-House vs Outsourced vs Rent",
|
||||
period_start: "2025-11-18",
|
||||
period_end: "2026-11-18",
|
||||
horizon_years: 5,
|
||||
summary: {
|
||||
latest_count: 1,
|
||||
horizon_years: 5,
|
||||
in_house_lowest_count: 1,
|
||||
outsourced_lowest_count: 0,
|
||||
rent_lowest_count: 0,
|
||||
},
|
||||
rows: [
|
||||
{
|
||||
asset_id: 101,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_name: "ICU",
|
||||
category_name: "Ventilator",
|
||||
installation_date: "2026-01-10",
|
||||
purchase_date: "2026-01-01",
|
||||
purchase_value: 1000000,
|
||||
in_house_cost: 775000,
|
||||
in_house_reason: null,
|
||||
outsourced_cost: 975000,
|
||||
outsourced_reason: null,
|
||||
rent_cost: null,
|
||||
rent_reason: "Insufficient data: monthly_rent",
|
||||
lowest_scenario: "in_house",
|
||||
lowest_scenario_label: "Buy + In-House",
|
||||
lowest_cost: 775000,
|
||||
savings_vs_next: 200000,
|
||||
current_setup: "in_house",
|
||||
},
|
||||
],
|
||||
chart_data: [
|
||||
{
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
in_house: 775000,
|
||||
outsourced: 975000,
|
||||
rent: null,
|
||||
},
|
||||
],
|
||||
metrics: [
|
||||
{
|
||||
id: "m_cmp_latest_count",
|
||||
label: "Latest Equipment Evaluated",
|
||||
value: 1,
|
||||
unit: "count",
|
||||
formatted: "1",
|
||||
},
|
||||
],
|
||||
narrative: RULE_BASED_NARRATIVE,
|
||||
how_calculated: { formulas: ["In-house = ..."], settings_used: { comparison_horizon_years: 5 } },
|
||||
});
|
||||
|
||||
vi.spyOn(aiApi, "getDepreciation").mockResolvedValue({
|
||||
section: "depreciation",
|
||||
title: "Depreciated Price & Cost Analysis",
|
||||
period_start: "2025-11-18",
|
||||
period_end: "2026-11-18",
|
||||
summary: {
|
||||
total_purchase_value: 1000000,
|
||||
total_book_value: 715000,
|
||||
total_accumulated_depreciation: 285000,
|
||||
total_maintenance_cost: 50000,
|
||||
fully_depreciated_count: 0,
|
||||
review_flag_count: 0,
|
||||
replacement_review_ratio: 0.4,
|
||||
excluded_count: 0,
|
||||
},
|
||||
rows: [
|
||||
{
|
||||
asset_id: 101,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_name: "ICU",
|
||||
category_name: "Ventilator",
|
||||
acquisition_mode: "purchased",
|
||||
purchase_value: 1000000,
|
||||
depreciation_applicable: true,
|
||||
depreciation_reason: null,
|
||||
method: "straight_line",
|
||||
useful_life_years: 10,
|
||||
book_value: 715000,
|
||||
accumulated_depreciation: 285000,
|
||||
annual_charge: 95000,
|
||||
fully_depreciated: false,
|
||||
contract_cost_to_date: 20000,
|
||||
repair_and_spare_cost_to_date: 20000,
|
||||
inhouse_pm_cost_to_date: 10000,
|
||||
maintenance_cost: 50000,
|
||||
maintenance_ratio: 0.05,
|
||||
lifetime_cost: 1050000,
|
||||
cost_per_year_of_use: 350000,
|
||||
review_flag: false,
|
||||
curve: [
|
||||
{ year: 0, book_value: 1000000 },
|
||||
{ year: 1, book_value: 905000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
chart_data: [
|
||||
{ year: 0, book_value: 1000000 },
|
||||
{ year: 1, book_value: 905000 },
|
||||
],
|
||||
metrics: [],
|
||||
narrative: RULE_BASED_NARRATIVE,
|
||||
how_calculated: { formulas: ["SLM"], settings_used: {} },
|
||||
});
|
||||
|
||||
vi.spyOn(aiApi, "getEfficiency").mockResolvedValue({
|
||||
section: "efficiency",
|
||||
title: "Equipment Efficiency",
|
||||
period_start: "2025-11-18",
|
||||
period_end: "2026-11-18",
|
||||
weights: { uptime: 0.5, pm_compliance: 0.2, response: 0.15, repeat_free: 0.15 },
|
||||
summary: {
|
||||
assets_in_scope: 10,
|
||||
avg_uptime_pct: 99.2,
|
||||
mttr_hours: 3.5,
|
||||
mtbf_hours: null,
|
||||
avg_response_minutes: 45,
|
||||
pm_compliance_pct: 95.0,
|
||||
avg_efficiency_score: 96.4,
|
||||
},
|
||||
rows: [
|
||||
{
|
||||
group: "ICU",
|
||||
group_type: "department",
|
||||
assets_in_scope: 10,
|
||||
uptime_pct: 99.2,
|
||||
pm_compliance_pct: 95.0,
|
||||
response_score: 92.0,
|
||||
repeat_free_score: 90.0,
|
||||
mttr_hours: 3.5,
|
||||
mtbf_hours: null,
|
||||
avg_response_minutes: 45,
|
||||
efficiency_score: 96.4,
|
||||
parts: { uptime: 49.6, pm_compliance: 19.0, response: 13.8, repeat_free: 13.5 },
|
||||
},
|
||||
],
|
||||
by_department: [],
|
||||
by_category: [],
|
||||
chart_data: [
|
||||
{ group: "ICU", uptime: 49.6, pm_compliance: 19.0, response: 13.8, repeat_free: 13.5, efficiency_score: 96.4 },
|
||||
],
|
||||
metrics: [],
|
||||
narrative: RULE_BASED_NARRATIVE,
|
||||
how_calculated: { formulas: ["Efficiency"], settings_used: {} },
|
||||
});
|
||||
|
||||
vi.spyOn(aiApi, "getBreakdownFrequency").mockResolvedValue({
|
||||
section: "breakdown_frequency",
|
||||
title: "Breakdown Frequency & Average Breakdowns",
|
||||
period_start: "2025-11-18",
|
||||
period_end: "2026-11-18",
|
||||
summary: {
|
||||
total_breakdowns: 5,
|
||||
assets_in_scope: 10,
|
||||
avg_breakdowns_per_equipment: 0.5,
|
||||
repeat_failure_count: 1,
|
||||
repeat_threshold: 3,
|
||||
repeat_window_days: 90,
|
||||
},
|
||||
rows: [
|
||||
{
|
||||
asset_id: 101,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_name: "ICU",
|
||||
category_name: "Ventilator",
|
||||
breakdown_count: 4,
|
||||
avg_downtime_minutes: 180,
|
||||
avg_downtime_hours: 3.0,
|
||||
repeat_window_count: 4,
|
||||
repeat_failure: true,
|
||||
},
|
||||
],
|
||||
by_department: [
|
||||
{
|
||||
group: "ICU",
|
||||
group_type: "department",
|
||||
breakdowns: 5,
|
||||
assets_in_scope: 10,
|
||||
avg_breakdowns_per_equipment: 0.5,
|
||||
breakdowns_per_1000_hours: 0.057,
|
||||
},
|
||||
],
|
||||
by_category: [],
|
||||
chart_data: {
|
||||
monthly_trend: [{ month: "2026-10", label: "Oct 2026", breakdowns: 5 }],
|
||||
by_department: [],
|
||||
by_category: [],
|
||||
},
|
||||
metrics: [],
|
||||
narrative: RULE_BASED_NARRATIVE,
|
||||
how_calculated: { formulas: ["Frequency"], settings_used: {} },
|
||||
});
|
||||
}
|
||||
|
||||
describe("AI Report & Settings (Task 7)", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("hides the Simple reports | AI report toggle for department_user and shows it for management", () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 3,
|
||||
email: "dept@poona.demo",
|
||||
name: "ICU Nurse",
|
||||
role: "department_user",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
is_active: true,
|
||||
},
|
||||
token: "t-dept",
|
||||
});
|
||||
|
||||
const { rerender } = renderWithProviders(<ReportsPage />);
|
||||
expect(screen.queryByRole("tab", { name: /AI report/i })).not.toBeInTheDocument();
|
||||
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 4,
|
||||
email: "mgmt@poona.demo",
|
||||
name: "Director",
|
||||
role: "management",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "t-mgmt",
|
||||
});
|
||||
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
rerender(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter>
|
||||
<ReportsPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
|
||||
const aiTab = screen.getByRole("tab", { name: /AI report/i });
|
||||
expect(aiTab).toBeInTheDocument();
|
||||
expect(aiTab).toHaveAttribute("href", "/reports/ai");
|
||||
});
|
||||
|
||||
it("renders Rule-based summary badge, Insufficient data cells, and hides Regenerate button for non-admin", async () => {
|
||||
mockAllAIEndpoints();
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 4,
|
||||
email: "mgmt@poona.demo",
|
||||
name: "Director",
|
||||
role: "management",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "t-mgmt",
|
||||
});
|
||||
|
||||
renderWithProviders(<AIReportPage />, ["/reports/ai"]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("ai-status-chip")).toHaveTextContent("Rule-based summary");
|
||||
expect(screen.getByText("Insufficient data: monthly_rent")).toBeInTheDocument();
|
||||
expect(screen.getByText(/1\. Comparison: in-house vs outsourced vs rent/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/2\. Depreciated price and cost analysis/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/3\. Efficiency/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/4\. Breakdown frequency and average breakdowns/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Non-admin (management) must NOT see Regenerate summary button
|
||||
expect(screen.queryByRole("button", { name: /Regenerate summary/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows Regenerate summary buttons ONLY for system_admin", async () => {
|
||||
mockAllAIEndpoints();
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 1,
|
||||
email: "admin@poona.demo",
|
||||
name: "System Admin",
|
||||
role: "system_admin",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "t-admin",
|
||||
});
|
||||
|
||||
renderWithProviders(<AIReportPage />, ["/reports/ai"]);
|
||||
|
||||
await waitFor(() => {
|
||||
const regenBtns = screen.getAllByRole("button", { name: /Regenerate summary/i });
|
||||
expect(regenBtns.length).toBeGreaterThanOrEqual(5);
|
||||
});
|
||||
});
|
||||
|
||||
it("renders AI and cost analysis group with read-only AI status on SettingsPage", async () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 1,
|
||||
email: "admin@poona.demo",
|
||||
name: "System Admin",
|
||||
role: "system_admin",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "t-admin",
|
||||
});
|
||||
|
||||
vi.spyOn(settingsApi, "getAll").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
key: "scheduled_hours_per_day",
|
||||
label: "Scheduled Hours per Day",
|
||||
description: "Operating hours per day",
|
||||
type: "int",
|
||||
default: 24,
|
||||
value: 24,
|
||||
min: 1,
|
||||
max: 24,
|
||||
},
|
||||
{
|
||||
key: "ai_enabled",
|
||||
label: "Enable AI Narrative",
|
||||
description: "Allow local AI provider narratives",
|
||||
type: "bool",
|
||||
default: false,
|
||||
value: false,
|
||||
},
|
||||
{
|
||||
key: "comparison_horizon_years",
|
||||
label: "Comparison Horizon (Years)",
|
||||
description: "Horizon for buy vs rent comparison",
|
||||
type: "int",
|
||||
default: 5,
|
||||
value: 5,
|
||||
min: 1,
|
||||
max: 15,
|
||||
},
|
||||
],
|
||||
});
|
||||
vi.spyOn(aiApi, "getStatus").mockResolvedValue({
|
||||
enabled: false,
|
||||
ai_enabled_setting: false,
|
||||
provider: "none",
|
||||
model: "",
|
||||
reachable: false,
|
||||
});
|
||||
|
||||
renderWithProviders(<SettingsPage />, ["/settings"]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("AI and cost analysis")).toBeInTheDocument();
|
||||
expect(screen.getByText("AI Summary Status")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Enable AI Narrative")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Comparison Horizon (Years)")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useState } from "react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
|
||||
const MOCK_ITEMS: AssetLookupItem[] = [
|
||||
{
|
||||
id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
serial_no: "SN-VENT-101",
|
||||
name: "ICU Ventilator",
|
||||
category_id: 1,
|
||||
category_name: "Life Support",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
location_id: 1,
|
||||
location_name: "ICU Bay 1",
|
||||
supplier_id: 1,
|
||||
supplier_name: "MedTech India",
|
||||
status: "in_service",
|
||||
criticality: "critical",
|
||||
requires_calibration: true,
|
||||
insurance_applicable: true,
|
||||
warranty_status: "active",
|
||||
warranty_end_date: "2027-05-01",
|
||||
contract_status: "active",
|
||||
contract_type: "CMC",
|
||||
contract_end_date: "2027-12-31",
|
||||
contract_summary: "CMC — Active until 31-Dec-2027",
|
||||
insurance_status: "active",
|
||||
insurance_end_date: "2027-06-30",
|
||||
insurance_summary: "Policy #INS-100 (Active)",
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
asset_code: "PHRC-RAD-0009",
|
||||
serial_no: "SN-XR-99",
|
||||
name: "Portable X-Ray",
|
||||
category_id: 2,
|
||||
category_name: "Imaging",
|
||||
department_id: 2,
|
||||
department_name: "Radiology",
|
||||
location_id: 2,
|
||||
location_name: "X-Ray Room",
|
||||
supplier_id: null,
|
||||
supplier_name: null,
|
||||
status: "condemned",
|
||||
criticality: "non_critical",
|
||||
requires_calibration: false,
|
||||
insurance_applicable: false,
|
||||
warranty_status: "none",
|
||||
warranty_end_date: null,
|
||||
contract_status: "none",
|
||||
contract_type: null,
|
||||
contract_end_date: null,
|
||||
contract_summary: "No active contract",
|
||||
insurance_status: "none",
|
||||
insurance_end_date: null,
|
||||
insurance_summary: "No policy",
|
||||
},
|
||||
];
|
||||
|
||||
function PickerHarness({ onPicked }: { onPicked?: (a: AssetLookupItem | null) => void }) {
|
||||
const [selected, setSelected] = useState<AssetLookupItem | null>(null);
|
||||
return (
|
||||
<AssetPicker
|
||||
selectedAsset={selected}
|
||||
onSelect={(item) => {
|
||||
setSelected(item);
|
||||
onPicked?.(item);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe("AssetPicker", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("renders search results with badges and pre-fills summary card on selection", async () => {
|
||||
const lookupSpy = vi
|
||||
.spyOn(assetsApi, "lookup")
|
||||
.mockResolvedValue({ items: MOCK_ITEMS });
|
||||
const onPicked = vi.fn();
|
||||
|
||||
render(<PickerHarness onPicked={onPicked} />);
|
||||
|
||||
const input = screen.getByPlaceholderText(/Search by asset code/i);
|
||||
fireEvent.focus(input);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(lookupSpy).toHaveBeenCalled();
|
||||
expect(screen.getByText(/ICU Ventilator/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText("Under Warranty")).toBeInTheDocument();
|
||||
expect(screen.getByText("Condemned")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByText(/ICU Ventilator/));
|
||||
|
||||
expect(onPicked).toHaveBeenCalledWith(MOCK_ITEMS[0]);
|
||||
expect(screen.getByText("Life Support")).toBeInTheDocument();
|
||||
expect(screen.getByText("ICU Bay 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("CMC — Active until 31-Dec-2027")).toBeInTheDocument();
|
||||
expect(screen.getByText("Policy #INS-100 (Active)")).toBeInTheDocument();
|
||||
expect(screen.getByText("Under Warranty")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { validateAttachmentFile } from "@/lib/validation";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
|
||||
function renderWithQuery(ui: React.ReactNode) {
|
||||
const qc = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
return render(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
|
||||
}
|
||||
|
||||
describe("Attachments", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("validates allowed file types and 10 MB size limit", () => {
|
||||
const validPdf = new File(["%PDF-1.4"], "manual.pdf", { type: "application/pdf" });
|
||||
const validJpg = new File(["abc"], "photo.jpg", { type: "image/jpeg" });
|
||||
const badExe = new File(["MZ"], "malware.exe", { type: "application/octet-stream" });
|
||||
const bigFile = new File(["x"], "huge.pdf", { type: "application/pdf" });
|
||||
Object.defineProperty(bigFile, "size", { value: 11 * 1024 * 1024 });
|
||||
|
||||
expect(validateAttachmentFile(validPdf)).toBeNull();
|
||||
expect(validateAttachmentFile(validJpg)).toBeNull();
|
||||
expect(validateAttachmentFile(badExe)).toMatch(/Invalid file type/i);
|
||||
expect(validateAttachmentFile(bigFile)).toMatch(/too large/i);
|
||||
});
|
||||
|
||||
it("renders list and blocks invalid or oversized uploads with clear error banner", async () => {
|
||||
vi.spyOn(attachmentsApi, "list").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 10,
|
||||
entity_type: "asset",
|
||||
entity_id: 1,
|
||||
original_name: "invoice.pdf",
|
||||
mime_type: "application/pdf",
|
||||
size_bytes: 2048,
|
||||
uploaded_by_name: "Admin",
|
||||
uploaded_at: "2026-11-10T09:30:00Z",
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
const uploadSpy = vi.spyOn(attachmentsApi, "upload");
|
||||
|
||||
renderWithQuery(
|
||||
<Attachments entityType="asset" entityId={1} canUpload={true} canDelete={true} />
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("invoice.pdf")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const input = screen.getByLabelText("Upload attachment") as HTMLInputElement;
|
||||
const badTxt = new File(["hello"], "notes.txt", { type: "text/plain" });
|
||||
fireEvent.change(input, { target: { files: [badTxt] } });
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(/Invalid file type/i);
|
||||
expect(uploadSpy).not.toHaveBeenCalled();
|
||||
|
||||
const oversized = new File(["x"], "big.png", { type: "image/png" });
|
||||
Object.defineProperty(oversized, "size", { value: 12 * 1024 * 1024 });
|
||||
fireEvent.change(input, { target: { files: [oversized] } });
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(/too large/i);
|
||||
expect(uploadSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { BulkAssetImportModal } from "@/components/BulkAssetImportModal";
|
||||
import { ToastProvider } from "@/components/ToastProvider";
|
||||
import * as assetsModule from "@/api/assets";
|
||||
|
||||
function renderModal(onClose = vi.fn()) {
|
||||
const qc = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<ToastProvider>
|
||||
<BulkAssetImportModal open={true} onClose={onClose} />
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("BulkAssetImportModal", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("renders template download, previews validation rows on upload, and imports valid rows", async () => {
|
||||
const templateSpy = vi
|
||||
.spyOn(assetsModule.assetsApi, "downloadImportTemplate")
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
const bulkImportSpy = vi
|
||||
.spyOn(assetsModule.assetsApi, "bulkImport")
|
||||
.mockResolvedValueOnce({
|
||||
dry_run: true,
|
||||
total_rows: 2,
|
||||
valid_count: 1,
|
||||
error_count: 1,
|
||||
created_count: 0,
|
||||
errors: [
|
||||
{
|
||||
row: 3,
|
||||
asset_code: "PHRC-BAD-1",
|
||||
error: "Unknown department 'NOPE'",
|
||||
},
|
||||
],
|
||||
preview_rows: [
|
||||
{
|
||||
row: 2,
|
||||
asset_code: "PHRC-ICU-0901",
|
||||
serial_no: "SN-901",
|
||||
name: "Infusion Pump",
|
||||
category_name: "Infusion Pump",
|
||||
department_name: "ICU",
|
||||
location_name: "ICU Bed 1",
|
||||
status: "in_service",
|
||||
valid: true,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
row: 3,
|
||||
asset_code: "PHRC-BAD-1",
|
||||
serial_no: "SN-902",
|
||||
name: "Bad Device",
|
||||
category_name: "Monitor",
|
||||
department_name: "NOPE",
|
||||
location_name: "Room 1",
|
||||
status: "in_service",
|
||||
valid: false,
|
||||
error: "Unknown department 'NOPE'",
|
||||
},
|
||||
],
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
dry_run: false,
|
||||
total_rows: 2,
|
||||
valid_count: 1,
|
||||
error_count: 1,
|
||||
created_count: 1,
|
||||
errors: [],
|
||||
preview_rows: [],
|
||||
});
|
||||
|
||||
const onClose = vi.fn();
|
||||
renderModal(onClose);
|
||||
|
||||
const templateBtn = screen.getByRole("button", {
|
||||
name: /Download Template \(\.xlsx\)/i,
|
||||
});
|
||||
fireEvent.click(templateBtn);
|
||||
await waitFor(() => {
|
||||
expect(templateSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const fileInput = screen.getByLabelText("Upload asset spreadsheet");
|
||||
const file = new File(["dummy"], "assets.xlsx", {
|
||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(bulkImportSpy).toHaveBeenCalledWith(file, true, false);
|
||||
expect(screen.getByText("Valid: 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("Errors: 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("PHRC-ICU-0901")).toBeInTheDocument();
|
||||
expect(screen.getByText("Unknown department 'NOPE'")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const importBtn = screen.getByRole("button", { name: /Import 1 Asset/i });
|
||||
expect(importBtn).toBeDisabled();
|
||||
|
||||
const skipCheckbox = screen.getByLabelText(
|
||||
/Skip invalid rows and import valid rows only/i
|
||||
);
|
||||
fireEvent.click(skipCheckbox);
|
||||
expect(importBtn).toBeEnabled();
|
||||
|
||||
fireEvent.click(importBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(bulkImportSpy).toHaveBeenNthCalledWith(2, file, false, true);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,166 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
|
||||
import { complaintsApi, type ComplaintItem } from "@/api/complaints";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import * as mastersApi from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
const MOCK_COMPLAINT: ComplaintItem = {
|
||||
id: 42,
|
||||
complaint_no: "CMP-2026-0042",
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "Ventilator",
|
||||
asset_status: "under_repair",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
location_name: "ICU Bay 1",
|
||||
description: "Oxygen sensor alarm",
|
||||
breakdown_details: "Sensor failing calibration check",
|
||||
priority: "critical",
|
||||
notes: null,
|
||||
registered_at: "2026-11-11T06:00:00Z",
|
||||
registered_by_id: 3,
|
||||
registered_by_name: "ICU Nurse",
|
||||
received_by_id: 2,
|
||||
received_by_name: "Bio Eng",
|
||||
received_at: "2026-11-11T06:00:00Z",
|
||||
assigned_to_id: 2,
|
||||
assigned_to_name: "Bio Eng",
|
||||
assigned_at: "2026-11-11T06:10:00Z",
|
||||
attended_by_id: 2,
|
||||
attended_by_name: "Bio Eng",
|
||||
attended_at: "2026-11-11T06:25:00Z",
|
||||
restored_at: null,
|
||||
closed_by_id: null,
|
||||
closed_by_name: null,
|
||||
closed_at: null,
|
||||
call_status: "in_progress",
|
||||
closure_remarks: null,
|
||||
action_taken: "Replaced flow sensor",
|
||||
root_cause: "Sensor drift",
|
||||
corrective_action: "Calibration scheduled",
|
||||
lessons_learned: null,
|
||||
ce_name: null,
|
||||
ce_attended_at: null,
|
||||
ce_action_taken: null,
|
||||
spare_required: true,
|
||||
spare_details: "O2 cell",
|
||||
spare_cost_estimate: 4500,
|
||||
response_time_minutes: 25,
|
||||
downtime_minutes: 1420,
|
||||
downtime_is_ongoing: true,
|
||||
downtime_end_milestone: "restored_at",
|
||||
response_start_setting: "registered_at",
|
||||
ce_response_time_minutes: null,
|
||||
updated_at: "2026-11-11T06:30:00Z",
|
||||
};
|
||||
|
||||
function renderPage() {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter initialEntries={["/complaints/42"]}>
|
||||
<Routes>
|
||||
<Route path="/complaints/:id" element={<ComplaintDetailPage />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("ComplaintDetailPage", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.spyOn(complaintsApi, "get").mockResolvedValue(MOCK_COMPLAINT);
|
||||
vi.spyOn(complaintsApi, "events").mockResolvedValue({ items: [], total: 0 });
|
||||
vi.spyOn(attachmentsApi, "list").mockResolvedValue({ items: [], total: 0 });
|
||||
vi.spyOn(mastersApi, "fetchUsersLookup").mockResolvedValue({
|
||||
items: [{ id: 2, name: "Bio Eng", role: "biomedical", department_id: null }],
|
||||
total: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("renders technical section read-only with Lock banner for department_user and displays downtime metrics", async () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 3,
|
||||
name: "ICU Nurse",
|
||||
email: "dept@poona.demo",
|
||||
role: "department_user",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
is_active: true,
|
||||
},
|
||||
token: "t",
|
||||
hydrating: false,
|
||||
});
|
||||
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("CMP-2026-0042")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(
|
||||
screen.getByText(/Restricted: Editable by Biomedical team only/i)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /Save Technical Details/i })).not.toBeInTheDocument();
|
||||
|
||||
// Downtime formatting (1420 mins = 23h 40m) + total mins + Ongoing + milestone
|
||||
expect(screen.getByText("23h 40m")).toBeInTheDocument();
|
||||
expect(screen.getByText("1,420 mins")).toBeInTheDocument();
|
||||
expect(screen.getByText("Ongoing")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Downtime ends at: restored_at/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders editable technical section for biomedical role", async () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 2,
|
||||
name: "Bio Eng",
|
||||
email: "bio@poona.demo",
|
||||
role: "biomedical",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "t",
|
||||
hydrating: false,
|
||||
});
|
||||
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("CMP-2026-0042")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(
|
||||
screen.queryByText(/Restricted: Editable by Biomedical team only/i)
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: /Save Technical Details/i })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue("Replaced flow sensor")).toBeInTheDocument();
|
||||
|
||||
const closeSpy = vi.spyOn(complaintsApi, "close").mockResolvedValue(MOCK_COMPLAINT);
|
||||
fireEvent.click(screen.getByRole("button", { name: /Close Call/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Close Complaint Call")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const remarksInput = screen.getByLabelText(/Closure Remarks/i);
|
||||
expect(remarksInput).toBeRequired();
|
||||
|
||||
const submitForm = remarksInput.closest("form")!;
|
||||
fireEvent.submit(submitForm);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Closure remarks are required.")).toBeInTheDocument();
|
||||
});
|
||||
expect(closeSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { LoginPage } from "@/pages/LoginPage";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import * as authApi from "@/api/auth";
|
||||
import { ApiError } from "@/api/client";
|
||||
|
||||
describe("LoginPage", () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
useAuthStore.setState({ user: null, token: null, demoAsOfDate: null, hydrating: false });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("renders branding, form fields, and all 5 Quick Demo Login buttons", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<LoginPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByAltText("Poona Hospital and Research Centre")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Email Address")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Password")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /Sign In/i })).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText("admin@poona.demo")).toBeInTheDocument();
|
||||
expect(screen.getByText("bio@poona.demo")).toBeInTheDocument();
|
||||
expect(screen.getByText("dept@poona.demo")).toBeInTheDocument();
|
||||
expect(screen.getByText("mgmt@poona.demo")).toBeInTheDocument();
|
||||
expect(screen.getByText("coord@poona.demo")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows validation errors when submitting empty credentials", async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<LoginPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Sign In/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Enter a valid email address")).toBeInTheDocument();
|
||||
expect(screen.getByText("Password is required")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("displays server error alert when login fails", async () => {
|
||||
vi.spyOn(authApi, "loginApi").mockRejectedValueOnce(new ApiError(401, "Invalid email or password"));
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<LoginPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Email Address"), { target: { value: "admin@poona.demo" } });
|
||||
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "wrong" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /Sign In/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Invalid email or password");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { can, type Role } from "@/lib/permissions";
|
||||
|
||||
describe("permissions.can()", () => {
|
||||
it("returns false when role is undefined", () => {
|
||||
expect(can(undefined, "view_assets")).toBe(false);
|
||||
expect(can(undefined, "manage_admin")).toBe(false);
|
||||
});
|
||||
|
||||
it("enforces manage_admin for system_admin only", () => {
|
||||
expect(can("system_admin", "manage_admin")).toBe(true);
|
||||
const nonAdmins: Role[] = ["biomedical", "department_user", "management", "coordinator"];
|
||||
for (const role of nonAdmins) {
|
||||
expect(can(role, "manage_admin")).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("enforces edit_technical_fields for system_admin and biomedical only", () => {
|
||||
expect(can("system_admin", "edit_technical_fields")).toBe(true);
|
||||
expect(can("biomedical", "edit_technical_fields")).toBe(true);
|
||||
expect(can("department_user", "edit_technical_fields")).toBe(false);
|
||||
expect(can("management", "edit_technical_fields")).toBe(false);
|
||||
expect(can("coordinator", "edit_technical_fields")).toBe(false);
|
||||
});
|
||||
|
||||
it("enforces role-specific capabilities across all 5 roles", () => {
|
||||
// biomedical
|
||||
expect(can("biomedical", "create_edit_assets")).toBe(true);
|
||||
expect(can("biomedical", "handle_complaint")).toBe(true);
|
||||
expect(can("biomedical", "manage_pm")).toBe(true);
|
||||
expect(can("biomedical", "manage_visits")).toBe(true);
|
||||
|
||||
// department_user
|
||||
expect(can("department_user", "view_assets")).toBe(true);
|
||||
expect(can("department_user", "raise_complaint")).toBe(true);
|
||||
expect(can("department_user", "handle_complaint")).toBe(false);
|
||||
expect(can("department_user", "view_visits")).toBe(false);
|
||||
expect(can("department_user", "view_all_reports")).toBe(false);
|
||||
expect(can("department_user", "view_dept_reports")).toBe(true);
|
||||
|
||||
// management
|
||||
expect(can("management", "view_assets")).toBe(true);
|
||||
expect(can("management", "view_all_reports")).toBe(true);
|
||||
expect(can("management", "view_visits")).toBe(true);
|
||||
expect(can("management", "create_edit_assets")).toBe(false);
|
||||
expect(can("management", "raise_complaint")).toBe(false);
|
||||
expect(can("management", "handle_complaint")).toBe(false);
|
||||
|
||||
// coordinator
|
||||
expect(can("coordinator", "edit_asset_contracts_only")).toBe(true);
|
||||
expect(can("coordinator", "create_edit_assets")).toBe(false);
|
||||
expect(can("coordinator", "raise_complaint")).toBe(false);
|
||||
expect(can("coordinator", "handle_complaint")).toBe(true);
|
||||
expect(can("coordinator", "manage_calibration_contracts")).toBe(true);
|
||||
expect(can("coordinator", "manage_demo_equipment")).toBe(true);
|
||||
expect(can("coordinator", "view_visits")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
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 { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import { ContractsPage } from "@/pages/ContractsPage";
|
||||
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
||||
import {
|
||||
insuranceApi,
|
||||
contractsApi,
|
||||
warrantiesApi,
|
||||
demoEquipmentApi,
|
||||
type ContractItem,
|
||||
type DemoEquipmentItem,
|
||||
} from "@/api/phase5";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { departmentsApi, locationsApi, vendorsApi } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
function renderWithProviders(ui: React.ReactNode) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter>{ui}</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("Phase 5 Modules", () => {
|
||||
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(locationsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(vendorsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(attachmentsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("InsuranceDrawer renders policy details for an asset", async () => {
|
||||
vi.spyOn(insuranceApi, "list").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 10,
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
insurer_id: 5,
|
||||
insurer_name: "New India Assurance",
|
||||
policy_no: "POL-MED-2026-001",
|
||||
start_date: "2026-01-01",
|
||||
end_date: "2026-12-31",
|
||||
coverage_amount: 850000,
|
||||
status: "expiring",
|
||||
severity: "yellow",
|
||||
days_to_expiry: 18,
|
||||
attachment_count: 1,
|
||||
remarks: "All risk cover",
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
renderWithProviders(
|
||||
<InsuranceDrawer
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
assetId={1}
|
||||
assetLabel="PHRC-ICU-0001 — ICU Ventilator"
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("POL-MED-2026-001")).toBeInTheDocument();
|
||||
expect(screen.getByText("New India Assurance")).toBeInTheDocument();
|
||||
expect(screen.getByText("18 days left")).toBeInTheDocument();
|
||||
expect(screen.getByText(/All risk cover/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("ContractsPage renders renewal history with Superseded badge on older contract", async () => {
|
||||
const activeContract: ContractItem = {
|
||||
id: 202,
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
contract_type: "CMC",
|
||||
provider_id: 3,
|
||||
provider_name: "MedTech Services",
|
||||
start_date: "2026-01-01",
|
||||
end_date: "2026-12-31",
|
||||
coverage_period_text: "1 Year",
|
||||
renewed_from_id: 201,
|
||||
is_superseded: false,
|
||||
status: "active",
|
||||
severity: "ok",
|
||||
days_to_expiry: 120,
|
||||
attachment_count: 0,
|
||||
remarks: "Renewed CMC",
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
const oldSupersededContract: ContractItem = {
|
||||
...activeContract,
|
||||
id: 201,
|
||||
contract_type: "AMC",
|
||||
start_date: "2025-01-01",
|
||||
end_date: "2025-12-31",
|
||||
renewed_from_id: null,
|
||||
is_superseded: true,
|
||||
status: "superseded",
|
||||
severity: "ok",
|
||||
days_to_expiry: -30,
|
||||
remarks: "Initial AMC",
|
||||
};
|
||||
|
||||
vi.spyOn(contractsApi, "list").mockResolvedValue({
|
||||
items: [activeContract],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(warrantiesApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(contractsApi, "history").mockResolvedValue({
|
||||
items: [activeContract, oldSupersededContract],
|
||||
});
|
||||
|
||||
renderWithProviders(<ContractsPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("PHRC-ICU-0001")).toBeInTheDocument();
|
||||
expect(screen.getByText("MedTech Services")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const historyBtn = screen.getByRole("button", { name: /History/i });
|
||||
fireEvent.click(historyBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/Contract Renewal History — PHRC-ICU-0001/i)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("Superseded")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Renewed from #201/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("DemoEquipmentPage highlights overdue returns", async () => {
|
||||
const overdueItem: DemoEquipmentItem = {
|
||||
id: 301,
|
||||
name: "Portable Ultrasound Demo",
|
||||
equipment_type: "Imaging",
|
||||
supplier_id: 4,
|
||||
supplier_name: "MedEquip India",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
location_id: null,
|
||||
location_name: "ICU Bay 2",
|
||||
start_date: "2026-10-01",
|
||||
expected_return_date: "2026-10-15",
|
||||
actual_return_date: null,
|
||||
status: "overdue_return",
|
||||
severity: "red",
|
||||
days_remaining: -5,
|
||||
attachment_count: 0,
|
||||
remarks: "Pending pickup",
|
||||
created_at: "2026-10-01T00:00:00Z",
|
||||
};
|
||||
|
||||
vi.spyOn(demoEquipmentApi, "list").mockResolvedValue({
|
||||
items: [overdueItem],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
renderWithProviders(<DemoEquipmentPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Portable Ultrasound Demo")).toBeInTheDocument();
|
||||
expect(screen.getByText("Overdue by 5d")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /^Return$/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
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 { DashboardPage } from "@/pages/DashboardPage";
|
||||
import { NotificationsPage } from "@/pages/NotificationsPage";
|
||||
import { CalibrationReminderModal } from "@/components/CalibrationReminderModal";
|
||||
import { dashboardApi, type DashboardSummary } from "@/api/dashboard";
|
||||
import {
|
||||
notificationsApi,
|
||||
type NotificationItem,
|
||||
} from "@/api/notifications";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
vi.mock("recharts", async () => {
|
||||
const actual = await vi.importActual<typeof import("recharts")>("recharts");
|
||||
return {
|
||||
...actual,
|
||||
ResponsiveContainer: ({ children }: { children: React.ReactNode }) => (
|
||||
<div style={{ width: 600, height: 240 }}>{children}</div>
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
function renderWithProviders(ui: React.ReactNode) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter>{ui}</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const MOCK_SUMMARY: DashboardSummary = {
|
||||
department_scope: "ICU",
|
||||
effective_today: "2026-11-12",
|
||||
kpis: {
|
||||
total_assets: 18,
|
||||
assets_under_repair: 2,
|
||||
open_complaints: 4,
|
||||
pm_due_this_month: 5,
|
||||
calibrations_due: 3,
|
||||
contracts_expiring: 6,
|
||||
equipment_on_demo: 1,
|
||||
},
|
||||
complaints_by_status: [
|
||||
{ status: "open", count: 2 },
|
||||
{ status: "in_progress", count: 2 },
|
||||
{ status: "closed", count: 8 },
|
||||
],
|
||||
complaints_by_department: [
|
||||
{ department: "ICU", critical: 3, non_critical: 9 },
|
||||
],
|
||||
monthly_downtime_trend: [
|
||||
{ month: "2026-06", label: "Jun 2026", downtime_minutes: 120, downtime_hours: 2 },
|
||||
{ month: "2026-07", label: "Jul 2026", downtime_minutes: 60, downtime_hours: 1 },
|
||||
{ month: "2026-08", label: "Aug 2026", downtime_minutes: 0, downtime_hours: 0 },
|
||||
{ month: "2026-09", label: "Sep 2026", downtime_minutes: 180, downtime_hours: 3 },
|
||||
{ month: "2026-10", label: "Oct 2026", downtime_minutes: 90, downtime_hours: 1.5 },
|
||||
{ month: "2026-11", label: "Nov 2026", downtime_minutes: 240, downtime_hours: 4 },
|
||||
],
|
||||
pm_planned_vs_completed: [
|
||||
{ month: "2026-06", label: "Jun 2026", planned: 4, completed: 4 },
|
||||
{ month: "2026-07", label: "Jul 2026", planned: 3, completed: 3 },
|
||||
{ month: "2026-08", label: "Aug 2026", planned: 5, completed: 4 },
|
||||
{ month: "2026-09", label: "Sep 2026", planned: 2, completed: 2 },
|
||||
{ month: "2026-10", label: "Oct 2026", planned: 4, completed: 3 },
|
||||
{ month: "2026-11", label: "Nov 2026", planned: 6, completed: 1 },
|
||||
],
|
||||
needs_attention: [
|
||||
{
|
||||
id: 901,
|
||||
type: "calibration_due",
|
||||
severity: "red",
|
||||
title: "Calibration Overdue: PHRC-ICU-0001",
|
||||
message: "ICU Ventilator calibration overdue by 3 days",
|
||||
entity_type: "calibration_record",
|
||||
entity_id: 12,
|
||||
due_date: "2026-11-09",
|
||||
link_url: "/calibration",
|
||||
},
|
||||
],
|
||||
recent_complaints: [
|
||||
{
|
||||
id: 42,
|
||||
complaint_no: "CMP-2026-0042",
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_name: "ICU",
|
||||
priority: "critical",
|
||||
call_status: "open",
|
||||
registered_at: "2026-11-11T08:00:00Z",
|
||||
downtime_minutes: 150,
|
||||
downtime_is_ongoing: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const MOCK_CAL_NOTIF: NotificationItem = {
|
||||
id: 501,
|
||||
type: "calibration_due",
|
||||
severity: "red",
|
||||
title: "Calibration Overdue: PHRC-ICU-0001",
|
||||
message: "Ventilator calibration due on 09-Nov-2026",
|
||||
entity_type: "calibration_record",
|
||||
entity_id: 12,
|
||||
due_date: "2026-11-09",
|
||||
created_at: "2026-11-12T06:00:00Z",
|
||||
is_read: false,
|
||||
read_at: null,
|
||||
link_url: "/calibration",
|
||||
};
|
||||
|
||||
describe("Phase 6 Modules", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
sessionStorage.clear();
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 2,
|
||||
email: "bio@poona.org",
|
||||
name: "Biomed Engineer",
|
||||
role: "biomedical",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "token-phase6-test",
|
||||
});
|
||||
});
|
||||
|
||||
it("DashboardPage renders KPI cards, department scope banner, and Needs Attention panel", async () => {
|
||||
vi.spyOn(dashboardApi, "summary").mockResolvedValue(MOCK_SUMMARY);
|
||||
|
||||
renderWithProviders(<DashboardPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Viewing department scope: ICU")).toBeInTheDocument();
|
||||
expect(screen.getByText("Total Assets")).toBeInTheDocument();
|
||||
expect(screen.getByText("18")).toBeInTheDocument();
|
||||
expect(screen.getByText("PM Due This Month")).toBeInTheDocument();
|
||||
expect(screen.getByText("Needs Attention")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Calibration Overdue: PHRC-ICU-0001")
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("CMP-2026-0042")).toBeInTheDocument();
|
||||
expect(screen.getByText("Ongoing")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("NotificationsPage renders notifications and marks single & all read", async () => {
|
||||
vi.spyOn(notificationsApi, "list").mockResolvedValue({
|
||||
items: [MOCK_CAL_NOTIF],
|
||||
total: 1,
|
||||
unread_count: 1,
|
||||
unread_calibration_count: 1,
|
||||
});
|
||||
const markReadSpy = vi
|
||||
.spyOn(notificationsApi, "markRead")
|
||||
.mockResolvedValue({ status: "ok", id: 501 });
|
||||
const markAllSpy = vi
|
||||
.spyOn(notificationsApi, "markAllRead")
|
||||
.mockResolvedValue({ status: "ok", marked_count: 1 });
|
||||
|
||||
renderWithProviders(<NotificationsPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText("Calibration Overdue: PHRC-ICU-0001")
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("Unread")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /^Mark Read$/i }));
|
||||
await waitFor(() => {
|
||||
expect(markReadSpy).toHaveBeenCalledWith(501);
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Mark all read/i }));
|
||||
await waitFor(() => {
|
||||
expect(markAllSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("CalibrationReminderModal pops up when unread calibration notifications exist and marks read on acknowledge", async () => {
|
||||
vi.spyOn(notificationsApi, "list").mockResolvedValue({
|
||||
items: [MOCK_CAL_NOTIF],
|
||||
total: 1,
|
||||
unread_count: 1,
|
||||
unread_calibration_count: 1,
|
||||
});
|
||||
const markAllSpy = vi
|
||||
.spyOn(notificationsApi, "markAllRead")
|
||||
.mockResolvedValue({ status: "ok", marked_count: 1 });
|
||||
|
||||
renderWithProviders(<CalibrationReminderModal />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/Calibration Reminders \(1 Unread\)/i)
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Calibration Overdue: PHRC-ICU-0001")
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole("button", { name: /Acknowledge & Mark Read/i })
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(markAllSpy).toHaveBeenCalledWith("calibration_due");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter, Routes, Route, useLocation } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { TopBar } from "@/components/layout/TopBar";
|
||||
import { AuditLogsPage } from "@/pages/AuditLogsPage";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { ToastProvider } from "@/components/ToastProvider";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import * as searchModule from "@/api/search";
|
||||
import * as auditModule from "@/api/audit";
|
||||
import * as mastersModule from "@/api/masters";
|
||||
import * as notificationsModule from "@/api/notifications";
|
||||
|
||||
function LocationEcho() {
|
||||
const loc = useLocation();
|
||||
return <div data-testid="current-location">{loc.pathname}</div>;
|
||||
}
|
||||
|
||||
function renderWithProviders(ui: React.ReactNode, initialEntries = ["/"]) {
|
||||
const qc = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<ToastProvider>
|
||||
<MemoryRouter initialEntries={initialEntries}>{ui}</MemoryRouter>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("Phase 8 Frontend Polish", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 1,
|
||||
name: "System Admin",
|
||||
email: "admin@poona.demo",
|
||||
role: "system_admin",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "test-token",
|
||||
demoAsOfDate: null,
|
||||
hydrating: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("TopBar global quick search displays grouped Assets and Complaints and navigates on click", async () => {
|
||||
vi.spyOn(notificationsModule.notificationsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
unread_count: 0,
|
||||
unread_calibration_count: 0,
|
||||
});
|
||||
const searchSpy = vi
|
||||
.spyOn(searchModule.searchApi, "query")
|
||||
.mockResolvedValue({
|
||||
assets: [
|
||||
{
|
||||
id: 42,
|
||||
asset_code: "PHRC-ICU-0042",
|
||||
name: "Drager Ventilator",
|
||||
serial_no: "SN-9901",
|
||||
department_name: "ICU",
|
||||
status: "in_service",
|
||||
},
|
||||
],
|
||||
complaints: [
|
||||
{
|
||||
id: 17,
|
||||
complaint_no: "CMP-2026-0017",
|
||||
asset_code: "PHRC-ICU-0042",
|
||||
asset_name: "Drager Ventilator",
|
||||
department_name: "ICU",
|
||||
call_status: "open",
|
||||
priority: "high",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
renderWithProviders(
|
||||
<>
|
||||
<TopBar />
|
||||
<LocationEcho />
|
||||
<Routes>
|
||||
<Route path="/" element={<div />} />
|
||||
<Route path="/assets/:id" element={<div>Asset Detail View</div>} />
|
||||
<Route
|
||||
path="/complaints/:id"
|
||||
element={<div>Complaint Detail View</div>}
|
||||
/>
|
||||
</Routes>
|
||||
</>
|
||||
);
|
||||
|
||||
const searchInput = screen.getByLabelText("Search assets and complaints");
|
||||
fireEvent.change(searchInput, { target: { value: "Ventilator" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(searchSpy).toHaveBeenCalledWith("Ventilator");
|
||||
expect(screen.getByText("Assets (1)")).toBeInTheDocument();
|
||||
expect(screen.getByText("Complaints (1)")).toBeInTheDocument();
|
||||
expect(screen.getByText("Drager Ventilator")).toBeInTheDocument();
|
||||
expect(screen.getByText("CMP-2026-0017")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText("Drager Ventilator"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("current-location")).toHaveTextContent(
|
||||
"/assets/42"
|
||||
);
|
||||
expect(screen.getByText("Asset Detail View")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("AuditLogsPage renders filter controls, audit log rows, and opens JSON changes modal", async () => {
|
||||
vi.spyOn(mastersModule.usersApi, "list").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
name: "System Admin",
|
||||
email: "admin@poona.demo",
|
||||
role: "system_admin",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
vi.spyOn(auditModule.auditApi, "list").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 101,
|
||||
entity_type: "asset",
|
||||
entity_id: 55,
|
||||
action: "update",
|
||||
changes_json: JSON.stringify({
|
||||
status: { old: "in_service", new: "under_repair" },
|
||||
}),
|
||||
by_user_id: 1,
|
||||
by_user_name: "System Admin",
|
||||
at: "2026-11-12T08:30:00Z",
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
renderWithProviders(<AuditLogsPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Audit Log" })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Filter by Entity Type")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Filter by User")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Filter by Action")).toBeInTheDocument();
|
||||
expect(screen.getByText("#55")).toBeInTheDocument();
|
||||
expect(screen.getByText("asset")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const jsonBtn = screen.getByLabelText("View JSON changes for audit entry 101");
|
||||
fireEvent.click(jsonBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/Audit Entry #101 — asset #55/i)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText(/"under_repair"/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("ConfirmDialog renders danger warning and invokes onConfirm", () => {
|
||||
const onConfirm = vi.fn();
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<ConfirmDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
title="Delete Contract"
|
||||
message="Are you sure you want to delete PHRC-ICU-0001 (AMC)?"
|
||||
confirmLabel="Delete"
|
||||
variant="danger"
|
||||
onConfirm={onConfirm}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Delete Contract")).toBeInTheDocument();
|
||||
expect(screen.getByText("This action cannot be undone.")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ReportsPage } from "@/pages/ReportsPage";
|
||||
import { ReportDetailPage } from "@/pages/ReportDetailPage";
|
||||
import * as reportsApi from "@/api/reports";
|
||||
import { departmentsApi } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
vi.mock("recharts", async () => {
|
||||
const actual = await vi.importActual<typeof import("recharts")>("recharts");
|
||||
return {
|
||||
...actual,
|
||||
ResponsiveContainer: ({ children }: { children: React.ReactNode }) => (
|
||||
<div style={{ width: 600, height: 240 }}>{children}</div>
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
function renderWithRouter(ui: React.ReactNode, initialEntries = ["/"]) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter initialEntries={initialEntries}>{ui}</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("Phase 7 Reports", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.spyOn(departmentsApi, "list").mockResolvedValue({
|
||||
items: [{ id: 1, name: "ICU", code: "ICU", description: null, is_active: true }],
|
||||
total: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("ReportsPage renders all 8 reports for management and hides Daily Department Visit Report for department_user", () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 5,
|
||||
email: "mgmt@poona.org",
|
||||
name: "Director",
|
||||
role: "management",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "t-mgmt",
|
||||
});
|
||||
|
||||
const { rerender } = renderWithRouter(<ReportsPage />);
|
||||
expect(screen.getByText("Monthly Maintenance Summary")).toBeInTheDocument();
|
||||
expect(screen.getByText("Daily Department Visit Report")).toBeInTheDocument();
|
||||
expect(screen.getByText("Demo Equipment Report")).toBeInTheDocument();
|
||||
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 3,
|
||||
email: "icu@poona.org",
|
||||
name: "ICU Nurse",
|
||||
role: "department_user",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
is_active: true,
|
||||
},
|
||||
token: "t-dept",
|
||||
});
|
||||
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
rerender(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter>
|
||||
<ReportsPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Monthly Maintenance Summary")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText("Daily Department Visit Report")
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("ReportDetailPage renders Monthly Maintenance summary, How this is calculated popover, and Export Excel button", async () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 5,
|
||||
email: "mgmt@poona.org",
|
||||
name: "Director",
|
||||
role: "management",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "t-mgmt",
|
||||
});
|
||||
|
||||
vi.spyOn(reportsApi, "fetchReport").mockResolvedValue({
|
||||
report_key: "monthly-maintenance",
|
||||
title: "Monthly Maintenance Summary",
|
||||
filters_applied: { month: "2026-11" },
|
||||
formula_info: {
|
||||
scheduled_hours_per_day: 24,
|
||||
downtime_end_milestone: "restored_at",
|
||||
days_in_month: 30,
|
||||
uptime_formula: "Scheduled Minutes - Clipped Downtime Minutes",
|
||||
downtime_formula: "Sum of breakdown intervals clipped to month in IST",
|
||||
},
|
||||
summary: {
|
||||
total_assets: 10,
|
||||
total_complaints: 3,
|
||||
downtime_formatted: "1d 2h 0m",
|
||||
downtime_days_count: 3,
|
||||
uptime_formatted: "298d 22h 0m",
|
||||
downtime_pct: 0.36,
|
||||
},
|
||||
columns: [
|
||||
{ key: "department_name", label: "Department" },
|
||||
{ key: "asset_count", label: "Assets" },
|
||||
{ key: "downtime_formatted", label: "Downtime" },
|
||||
{ key: "downtime_pct", label: "Downtime %" },
|
||||
],
|
||||
rows: [
|
||||
{
|
||||
department_name: "ICU",
|
||||
asset_count: 10,
|
||||
downtime_formatted: "1d 2h 0m",
|
||||
downtime_pct: 0.36,
|
||||
},
|
||||
],
|
||||
chart_data: [
|
||||
{ department: "ICU", downtime_hours: 26, uptime_hours: 7174 },
|
||||
],
|
||||
});
|
||||
|
||||
const exportSpy = vi
|
||||
.spyOn(reportsApi, "exportReport")
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
renderWithRouter(
|
||||
<Routes>
|
||||
<Route path="/reports/:reportKey" element={<ReportDetailPage />} />
|
||||
</Routes>,
|
||||
["/reports/monthly-maintenance"]
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByRole("heading", { name: /Monthly Maintenance Summary/i })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("Distinct Downtime Days")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("99.6 %").length).toBeGreaterThanOrEqual(2);
|
||||
expect(screen.getByRole("cell", { name: "ICU" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const formulaBtn = screen.getByRole("button", {
|
||||
name: /How this is calculated/i,
|
||||
});
|
||||
fireEvent.click(formulaBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/Uptime & Downtime Calculation Methodology/i)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText(/24 hrs/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/30 days/i)).toBeInTheDocument();
|
||||
expect(screen.getByText("restored_at")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const exportXlsxBtn = screen.getByRole("button", {
|
||||
name: /Export Excel \(\.xlsx\)/i,
|
||||
});
|
||||
fireEvent.click(exportXlsxBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(exportSpy).toHaveBeenCalledWith(
|
||||
"monthly-maintenance",
|
||||
"xlsx",
|
||||
expect.any(Object)
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
import "@testing-library/jest-dom";
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { Sidebar } from "@/components/layout/Sidebar";
|
||||
import { ReportsPage } from "@/pages/ReportsPage";
|
||||
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
describe("Phase 1 Frontend Smoke Tests", () => {
|
||||
beforeEach(() => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 1,
|
||||
name: "Admin",
|
||||
email: "admin@poona.demo",
|
||||
role: "system_admin",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "test-token",
|
||||
demoAsOfDate: null,
|
||||
hydrating: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("renders Sidebar with Poona Hospital logo, subtitle, and all admin navigation links", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Sidebar />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const logo = screen.getByAltText("Poona Hospital and Research Centre") as HTMLImageElement;
|
||||
expect(logo).toBeInTheDocument();
|
||||
expect(logo.getAttribute("src")).toBe("/logo.jpg");
|
||||
expect(screen.getByText("Asset Management & Maintenance")).toBeInTheDocument();
|
||||
|
||||
const labels = [
|
||||
"Dashboard",
|
||||
"Assets",
|
||||
"Complaints",
|
||||
"Preventive Maintenance",
|
||||
"Calibration",
|
||||
"Contracts & Warranty",
|
||||
"Insurance",
|
||||
"Demo Equipment",
|
||||
"Department Visits",
|
||||
"Reports",
|
||||
"Notifications",
|
||||
"Masters",
|
||||
"Audit Log",
|
||||
"Settings",
|
||||
];
|
||||
for (const label of labels) {
|
||||
expect(screen.getByText(label)).toBeInTheDocument();
|
||||
}
|
||||
expect(screen.getByText("Poona Hospital AMS • v1.0")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides Masters, Settings, and Department Visits for department_user and coordinator", () => {
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 3,
|
||||
name: "Dept User",
|
||||
email: "dept@poona.demo",
|
||||
role: "department_user",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
is_active: true,
|
||||
},
|
||||
});
|
||||
const { rerender } = render(
|
||||
<MemoryRouter>
|
||||
<Sidebar />
|
||||
</MemoryRouter>
|
||||
);
|
||||
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Audit Log")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Assets")).toBeInTheDocument();
|
||||
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 5,
|
||||
name: "Coordinator",
|
||||
email: "coord@poona.demo",
|
||||
role: "coordinator",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
});
|
||||
rerender(
|
||||
<MemoryRouter>
|
||||
<Sidebar />
|
||||
</MemoryRouter>
|
||||
);
|
||||
expect(screen.queryByText("Masters")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Audit Log")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Settings")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders ReportsPage catalog cards", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ReportsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
expect(screen.getByText("Reports & Exports")).toBeInTheDocument();
|
||||
expect(screen.getByText("Monthly Maintenance Summary")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders DataTableDemoPage with mock rows", () => {
|
||||
render(<DataTableDemoPage />);
|
||||
expect(screen.getByText("Phase 0 — DataTable Demo")).toBeInTheDocument();
|
||||
expect(screen.getByText("PHRC-ICU-0001")).toBeInTheDocument();
|
||||
expect(screen.getByText("CT Scanner")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
Reference in New Issue
Block a user