diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index deca52f..ae71e95 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -13,3 +13,14 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her 9. **Demo Clock (`demo_as_of_date`)**: System-wide `effective_today()` reads `demo_as_of_date` (`YYYY-MM-DD`) from Settings if non-empty; otherwise uses the real current date in `Asia/Kolkata`. 10. **Soft Deletion for Masters & Users**: Deleting departments, locations, categories, vendors, or users sets `is_active = False` rather than hard-deleting rows so historical asset/complaint/maintenance foreign keys remain intact. 11. **Password Hashing on Python 3.13**: `passlib==1.7.4` is incompatible with `bcrypt>=4.1` on Python 3.13 (`__about__` attribute removed / 72-byte wrap-check error), so `app/core/security.py` uses `bcrypt` (`bcrypt==5.0.0`) directly. + +## Assumptions added post-Phase-8 + +12. **Permission Specifics**: `system_admin` and `biomedical` can create and edit full asset records (`coordinator` is restricted to updating `requires_calibration`, `insurance_applicable`, and `remarks`). Calibration frequency edits and plan approvals are restricted to `system_admin`, `management`, and `coordinator` (`biomedical` receives HTTP `403`). `department_user` is scoped to their assigned department (`ICU` in demo data) across assets, complaints, PM, calibration, contracts, notifications, dashboard, reports, and global search, whereas `system_admin`, `biomedical`, `management`, and `coordinator` view all departments hospital-wide. `management` and `coordinator` cannot raise complaints (enforced server-side with HTTP `403`). +13. **Critical Complaint Escalation & SLA Evaluation**: APScheduler runs `alerts.py` daily (default `06:00` in configured `TIMEZONE`) and raises `critical_complaint` notifications when open critical complaint age exceeds `escalation_open_complaint_hours` (default `24`h) or breaches `compute_sla_status` against `critical_complaint_sla_hours` (default `4`h) / `non_critical_complaint_sla_hours` (default `24`h). +14. **Insurance Drawer**: Insurance summary is surfaced via a read-only slide-over panel (`InsuranceDrawer`) from `AssetDetailPage`, `AssetPicker`, and `ComplaintDetailPage`; creating and editing policies is handled via modal dialogs on `/insurance` and the Asset Insurance tab. +15. **Demo-Only Features**: The TopBar **Demo Clock** (`demo_as_of_date`, admin-only date override for demonstrating expiry/overdue alerts and dynamic schedule transitions) and the deterministic seed loader (`python -m app.seed.seed`) exist specifically for demonstration and verification. +16. **Reopen Clears `restored_at`**: Reopening a closed breakdown complaint clears both `closed_at` and `restored_at` (`None`) on the complaint row so downtime resumes as ongoing until re-restored. +17. **Immediate Asset Return to Service**: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset), `Asset.status` transitions immediately to `in_service` rather than requiring an extra post-repair sign-off step. +18. **Code Prefixes (`complaint_no_prefix` & `asset_code_prefix`)**: Complaint numbers are auto-generated using `complaint_no_prefix` (default `CMP`, e.g. `CMP-2026-0001`; `BD-` or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, so `asset_code_prefix` (default `PHRC`) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code. +19. **Monthly Maintenance `Uptime %` Display**: The `monthly-maintenance` backend report aggregates uptime/downtime in minutes per department rather than returning per-asset `uptime_seconds`/`downtime_seconds`, so `Uptime %` (`uptime / (uptime + downtime) * 100`, 1 decimal place) is computed on the frontend in `ReportDetailPage.tsx` (falling back to `100 - downtime_pct`) and highlighted in the summary strip and table. diff --git a/frontend/src/components/AssetFormModal.tsx b/frontend/src/components/AssetFormModal.tsx index 1701099..3faa9e5 100644 --- a/frontend/src/components/AssetFormModal.tsx +++ b/frontend/src/components/AssetFormModal.tsx @@ -83,8 +83,14 @@ export function AssetFormModal({ }); const departments = deptsQuery.data?.items ?? []; - const allLocations = locsQuery.data?.items ?? []; - const categories = catsQuery.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; @@ -161,7 +167,7 @@ export function AssetFormModal({ remarks: "", }); } - }, [open, editing, categories.length, defaultDeptId, defaultLocId, reset]); + }, [open, editing, categories, defaultDeptId, defaultLocId, reset]); const watchedDeptId = Number(watch("department_id")); const filteredLocations = useMemo( diff --git a/frontend/src/components/Attachments.tsx b/frontend/src/components/Attachments.tsx index 07c1469..e50edff 100644 --- a/frontend/src/components/Attachments.tsx +++ b/frontend/src/components/Attachments.tsx @@ -16,26 +16,9 @@ import { } from "@/api/attachments"; import { ApiError } from "@/api/client"; import { formatDateTime } from "@/lib/format"; +import { validateAttachmentFile } from "@/lib/validation"; import { Button } from "@/components/ui/button"; -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; -} - function formatBytes(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; diff --git a/frontend/src/components/BulkAssetImportModal.tsx b/frontend/src/components/BulkAssetImportModal.tsx index 4972187..e191728 100644 --- a/frontend/src/components/BulkAssetImportModal.tsx +++ b/frontend/src/components/BulkAssetImportModal.tsx @@ -12,7 +12,7 @@ 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 "@/components/ToastProvider"; +import { toast } from "@/lib/toast"; import { cn } from "@/lib/utils"; interface BulkAssetImportModalProps { diff --git a/frontend/src/components/CalibrationModals.tsx b/frontend/src/components/CalibrationModals.tsx index 5dd9bec..adc721a 100644 --- a/frontend/src/components/CalibrationModals.tsx +++ b/frontend/src/components/CalibrationModals.tsx @@ -3,7 +3,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"; import { AlertCircle, Paperclip, X } from "lucide-react"; import { Modal } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; -import { validateAttachmentFile } from "@/components/Attachments"; +import { validateAttachmentFile } from "@/lib/validation"; import { ApiError } from "@/api/client"; import { assetsApi } from "@/api/assets"; import { vendorsApi } from "@/api/masters"; diff --git a/frontend/src/components/CalibrationReminderModal.tsx b/frontend/src/components/CalibrationReminderModal.tsx index 7808f58..1677b85 100644 --- a/frontend/src/components/CalibrationReminderModal.tsx +++ b/frontend/src/components/CalibrationReminderModal.tsx @@ -7,7 +7,7 @@ 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 "@/components/ToastProvider"; +import { toast } from "@/lib/toast"; export function CalibrationReminderModal() { const navigate = useNavigate(); diff --git a/frontend/src/components/RaiseComplaintModal.tsx b/frontend/src/components/RaiseComplaintModal.tsx index 41d57d3..52e6134 100644 --- a/frontend/src/components/RaiseComplaintModal.tsx +++ b/frontend/src/components/RaiseComplaintModal.tsx @@ -8,7 +8,7 @@ import { AlertCircle, Clock, Paperclip, X } from "lucide-react"; import { Modal } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { AssetPicker } from "@/components/AssetPicker"; -import { validateAttachmentFile } from "@/components/Attachments"; +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"; diff --git a/frontend/src/components/ToastProvider.tsx b/frontend/src/components/ToastProvider.tsx index b65dc39..6349508 100644 --- a/frontend/src/components/ToastProvider.tsx +++ b/frontend/src/components/ToastProvider.tsx @@ -1,44 +1,5 @@ -import { create } from "zustand"; import { CheckCircle2, Info, AlertTriangle, AlertCircle, X } from "lucide-react"; - -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) => void; - dismiss: (id: string) => void; -} - -export const useToastStore = create((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" }), -}; +import { useToastStore, type ToastVariant } from "@/lib/toast"; const VARIANT_CLS: Record = { success: "bg-emerald-50 border-emerald-300 text-emerald-900", diff --git a/frontend/src/components/layout/TopBar.tsx b/frontend/src/components/layout/TopBar.tsx index 2c63603..dc76940 100644 --- a/frontend/src/components/layout/TopBar.tsx +++ b/frontend/src/components/layout/TopBar.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useRef } from "react"; +import { useState, useEffect, useRef, useMemo } from "react"; import { useNavigate } from "react-router-dom"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { @@ -28,7 +28,7 @@ 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 { toast } from "@/components/ToastProvider"; +import { toast } from "@/lib/toast"; interface TopBarProps { title?: string; @@ -121,7 +121,10 @@ export function TopBar({ title, onMenuClick }: TopBarProps) { refetchInterval: 60_000, }); - const bellItems = bellQuery.data?.items ?? []; + 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 diff --git a/frontend/src/lib/toast.ts b/frontend/src/lib/toast.ts new file mode 100644 index 0000000..90197f1 --- /dev/null +++ b/frontend/src/lib/toast.ts @@ -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) => void; + dismiss: (id: string) => void; +} + +export const useToastStore = create((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" }), +}; diff --git a/frontend/src/lib/validation.ts b/frontend/src/lib/validation.ts new file mode 100644 index 0000000..c00bd1b --- /dev/null +++ b/frontend/src/lib/validation.ts @@ -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; +} diff --git a/frontend/src/pages/AssetDetailPage.tsx b/frontend/src/pages/AssetDetailPage.tsx index 05ddd34..a6c0ba5 100644 --- a/frontend/src/pages/AssetDetailPage.tsx +++ b/frontend/src/pages/AssetDetailPage.tsx @@ -10,7 +10,6 @@ import { Plus, } from "lucide-react"; import { assetsApi } from "@/api/assets"; -import type { CalibrationPlanItem } from "@/api/calibration"; import { ApiError } from "@/api/client"; import { useAuthStore } from "@/hooks/useAuth"; import { can } from "@/lib/permissions"; diff --git a/frontend/src/pages/ComplaintDetailPage.tsx b/frontend/src/pages/ComplaintDetailPage.tsx index 4e920ed..0115b4c 100644 --- a/frontend/src/pages/ComplaintDetailPage.tsx +++ b/frontend/src/pages/ComplaintDetailPage.tsx @@ -22,6 +22,7 @@ import { type TimestampField, } from "@/api/complaints"; import { fetchUsersLookup } from "@/api/masters"; +import { settingsApi } from "@/api/settings"; import { ApiError } from "@/api/client"; import { useAuthStore } from "@/hooks/useAuth"; import { can } from "@/lib/permissions"; @@ -90,6 +91,7 @@ export function ComplaintDetailPage() { const [closeOpen, setCloseOpen] = useState(false); const [closureRemarks, setClosureRemarks] = useState(""); + const [closeError, setCloseError] = useState(null); const [reopenOpen, setReopenOpen] = useState(false); const [reopenReason, setReopenReason] = useState(""); @@ -118,6 +120,21 @@ export function ComplaintDetailPage() { enabled: Number.isFinite(complaintId) && complaintId > 0, }); + const settingsQuery = useQuery({ + queryKey: ["settings"], + queryFn: () => settingsApi.getAll(), + enabled: isAdmin, + retry: false, + }); + + const requireClosureRemarks = (() => { + const setting = settingsQuery.data?.items?.find( + (s) => s.key === "require_closure_remarks" + ); + if (setting !== undefined) return Boolean(setting.value); + return true; + })(); + const eventsQuery = useQuery({ queryKey: ["complaint-events", complaintId], queryFn: () => complaintsApi.events(complaintId), @@ -193,11 +210,16 @@ export function ComplaintDetailPage() { }), onSuccess: async () => { setActionError(null); + setCloseError(null); setCloseOpen(false); setClosureRemarks(""); await refreshAll(); }, - onError: (err) => setActionError(err instanceof ApiError ? err.detail : "Close failed."), + onError: (err) => { + const msg = err instanceof ApiError ? err.detail : "Close failed."; + setCloseError(msg); + setActionError(msg); + }, }); const reopenMutation = useMutation({ @@ -541,7 +563,10 @@ export function ComplaintDetailPage() { size="sm" variant="outline" className="border-green-600 text-green-700 hover:bg-green-50" - onClick={() => setCloseOpen(true)} + onClick={() => { + setCloseError(null); + setCloseOpen(true); + }} > Close Call @@ -874,20 +899,48 @@ export function ComplaintDetailPage() { {/* Close Modal */} - + { + setCloseOpen(next); + if (!next) setCloseError(null); + }} + title="Close Complaint Call" + >
{ e.preventDefault(); + if (requireClosureRemarks && !closureRemarks.trim()) { + setCloseError("Closure remarks are required."); + return; + } + setCloseError(null); closeMutation.mutate(); }} className="space-y-4" > + {closeError && ( +
+ + {closeError} +
+ )}
- +