phase-1: data model, auth, permissions, masters, settings, seed

This commit is contained in:
Atharv1705
2026-11-12 12:28:55 +05:30
parent cb2f48620c
commit e58232a657
48 changed files with 5463 additions and 98 deletions
+102 -19
View File
@@ -1,7 +1,12 @@
import { BrowserRouter, Routes, Route } from "react-router-dom";
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 {
DashboardPage,
AssetsPage,
@@ -14,34 +19,112 @@ import {
VisitsPage,
ReportsPage,
NotificationsPage,
SettingsPage,
} from "@/pages/stubs";
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="/complaints" element={<ComplaintsPage />} />
<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="/notifications" element={<NotificationsPage />} />
<Route
path="/masters"
element={
<RoleGuard capability="manage_admin">
<MastersPage />
</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}>
<BrowserRouter>
<Routes>
<Route element={<AppShell />}>
<Route path="/" element={<DashboardPage />} />
<Route path="/assets" element={<AssetsPage />} />
<Route path="/complaints" element={<ComplaintsPage />} />
<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={<VisitsPage />} />
<Route path="/reports" element={<ReportsPage />} />
<Route path="/notifications" element={<NotificationsPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/demo" element={<DataTableDemoPage />} />
</Route>
</Routes>
<AppRoutes />
</BrowserRouter>
</QueryClientProvider>
);
+27
View File
@@ -0,0 +1,27 @@
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");
}
+11 -1
View File
@@ -10,6 +10,12 @@ export class ApiError extends Error {
}
}
let onUnauthorizedCallback: (() => void) | null = null;
export function setUnauthorizedHandler(cb: () => void) {
onUnauthorizedCallback = cb;
}
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = sessionStorage.getItem("access_token");
const headers: Record<string, string> = {
@@ -21,6 +27,10 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
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 && !path.startsWith("/auth/login")) {
sessionStorage.removeItem("access_token");
onUnauthorizedCallback?.();
}
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
}
if (res.status === 204) return undefined as T;
@@ -30,7 +40,7 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, data?: unknown) =>
request<T>(path, { method: "POST", body: data ? JSON.stringify(data) : undefined }),
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) =>
+156
View File
@@ -0,0 +1,156 @@
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;
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 }) =>
api.post<Category>("/categories", data),
update: (id: number, data: Partial<{ name: string; description: string | 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}`),
};
+32
View File
@@ -0,0 +1,32 @@
import { api } from "./client";
export type SettingType = "int" | "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 }),
};
+67 -15
View File
@@ -11,27 +11,79 @@ import {
Building2,
BarChart3,
Bell,
Database,
Settings,
ChevronRight,
type LucideIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { can, type Capability } from "@/lib/permissions";
import { useAuthStore } from "@/hooks/useAuth";
const NAV_ITEMS = [
{ to: "/", label: "Dashboard", icon: LayoutDashboard, phase: 6 },
{ to: "/assets", label: "Assets", icon: Package, phase: 2 },
{ to: "/complaints", label: "Complaints", icon: AlertCircle, phase: 3 },
{ to: "/pm", label: "Preventive Maintenance", icon: Wrench, phase: 4 },
{ to: "/calibration", label: "Calibration", icon: FlaskConical, phase: 4 },
{ to: "/contracts", label: "Contracts & Warranty", icon: FileText, phase: 5 },
{ to: "/insurance", label: "Insurance", icon: Shield, phase: 5 },
{ to: "/demo-equipment", label: "Demo Equipment", icon: Truck, phase: 5 },
{ to: "/visits", label: "Department Visits", icon: Building2, phase: 5 },
{ to: "/reports", label: "Reports", icon: BarChart3, phase: 7 },
{ to: "/notifications", label: "Notifications", icon: Bell, phase: 6 },
{ to: "/settings", label: "Settings", icon: Settings, phase: 1, adminOnly: true },
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: "/settings", label: "Settings", icon: Settings, capability: "manage_admin" },
];
export function Sidebar() {
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;
});
return (
<aside className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col">
{/* Logo */}
@@ -50,7 +102,7 @@ export function Sidebar() {
{/* Navigation */}
<nav className="flex-1 px-2 py-4 space-y-0.5 overflow-y-auto">
{NAV_ITEMS.map(({ to, label, icon: Icon }) => (
{visibleItems.map(({ to, label, icon: Icon }) => (
<NavLink
key={to}
to={to}
@@ -73,7 +125,7 @@ export function Sidebar() {
{/* Footer */}
<div className="px-4 py-3 border-t border-blue-700 text-xs text-blue-300">
Phase 0 — Scaffold
Phase 1 — Foundation
</div>
</aside>
);
+132 -12
View File
@@ -1,18 +1,58 @@
import { Search, Bell, ChevronDown, User } from "lucide-react";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { Search, Bell, ChevronDown, User, LogOut, CalendarClock, RotateCcw } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatDate } from "@/lib/format";
import { ROLE_LABELS } from "@/lib/permissions";
import { useAuthStore } from "@/hooks/useAuth";
import { settingsApi } from "@/api/settings";
import { Badge } from "@/components/ui/badge";
interface TopBarProps {
title?: string;
}
export function TopBar({ title }: TopBarProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
const [menuOpen, setMenuOpen] = useState(false);
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
const [savingDate, setSavingDate] = useState(false);
useEffect(() => {
setDateInput(demoAsOfDate ?? "");
}, [demoAsOfDate]);
const isAdmin = user?.role === "system_admin";
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 queryClient.invalidateQueries();
} finally {
setSavingDate(false);
}
}
function handleSignOut() {
setMenuOpen(false);
logout();
navigate("/login", { replace: true });
}
return (
<header className="h-14 bg-white border-b border-gray-200 flex items-center px-4 gap-4 sticky top-0 z-10">
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-4 py-2 gap-3 sticky top-0 z-10">
{/* Page title */}
{title && <h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">{title}</h1>}
{/* Global search placeholder */}
<div className={cn("relative ml-auto", title ? "" : "flex-1 max-w-md")}>
<div className={cn("relative", title ? "" : "flex-1 max-w-xs sm:max-w-sm")}>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<input
type="text"
@@ -21,20 +61,100 @@ export function TopBar({ title }: TopBarProps) {
/>
</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 */}
{isAdmin && (
<div className="flex items-center gap-1.5 bg-gray-50 border border-gray-200 rounded-md px-2 py-1 text-xs">
<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>
)}
</div>
)}
{/* Notification bell placeholder */}
<button className="relative p-2 rounded-md hover:bg-gray-100 text-gray-500">
<button
type="button"
onClick={() => navigate("/notifications")}
className="relative p-2 rounded-md hover:bg-gray-100 text-gray-500 ml-auto"
aria-label="Notifications"
>
<Bell className="h-5 w-5" />
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500" />
</button>
{/* User menu placeholder */}
<button className="flex items-center gap-2 px-3 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700">
<div className="h-7 w-7 rounded-full bg-[#1e3a8a] flex items-center justify-center text-white text-xs font-bold">
<User className="h-4 w-4" />
</div>
<span className="hidden sm:block">Admin</span>
<ChevronDown className="h-4 w-4 text-gray-400" />
</button>
{/* User menu */}
<div className="relative">
<button
type="button"
onClick={() => setMenuOpen((o) => !o)}
className="flex items-center gap-2 px-2.5 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700"
>
<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={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>
</header>
);
}
+55
View File
@@ -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-full max-w-lg -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white 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>
);
}
+55 -6
View File
@@ -1,21 +1,70 @@
import { create } from "zustand";
import { fetchMeApi, type UserOut } from "@/api/auth";
import { setUnauthorizedHandler } from "@/api/client";
interface AuthState {
user: { id: number; email: string; name: string; role: string } | null;
user: UserOut | null;
token: string | null;
setAuth: (user: AuthState["user"], token: string) => void;
demoAsOfDate: string | null;
hydrating: boolean;
setAuth: (user: UserOut, token: string) => void;
setDemoAsOfDate: (date: string | null) => void;
hydrate: () => Promise<void>;
logout: () => void;
}
export const useAuthStore = create<AuthState>((set) => ({
const initialToken = sessionStorage.getItem("access_token");
export const useAuthStore = create<AuthState>((set, get) => ({
user: null,
token: sessionStorage.getItem("access_token"),
token: initialToken,
demoAsOfDate: null,
hydrating: Boolean(initialToken),
setAuth: (user, token) => {
sessionStorage.setItem("access_token", token);
set({ user, token });
set({
user,
token,
demoAsOfDate: user.demo_as_of_date ?? null,
hydrating: false,
});
},
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 });
set({ user: null, token: null, demoAsOfDate: null, hydrating: false });
},
}));
setUnauthorizedHandler(() => {
useAuthStore.getState().logout();
});
+98 -5
View File
@@ -1,4 +1,28 @@
export type Role = "system_admin" | "biomedical" | "department_user" | "management" | "coordinator";
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";
export const ROLE_LABELS: Record<Role, string> = {
system_admin: "System Administrator",
@@ -8,9 +32,78 @@ export const ROLE_LABELS: Record<Role, string> = {
coordinator: "Coordinator",
};
// Full permission matrix will be added in Phase 1
export function can(role: Role | undefined, _capability: string): boolean {
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",
]),
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",
]),
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",
]),
coordinator: new Set<Capability>([
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"view_pm",
"manage_calibration_contracts",
"view_calibration_contracts",
"manage_demo_equipment",
"view_demo_equipment",
"view_all_reports",
"view_dept_reports",
]),
};
export function can(role: Role | undefined | null, capability: Capability | string): boolean {
if (!role) return false;
if (role === "system_admin") return true;
return false; // placeholder
const caps = ROLE_CAPABILITIES[role];
if (!caps) return false;
return caps.has(capability as Capability);
}
+20
View File
@@ -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>
);
}
+1 -1
View File
@@ -12,7 +12,7 @@ interface MockAsset {
const MOCK_DATA: MockAsset[] = [
{ code: "PHRC-ICU-0001", name: "Ventilator", department: "ICU", status: "In Service", category: "Life Support" },
{ code: "PHRC-ICU-0002", name: "Patient Monitor", department: "ICU", status: "Under Repair", category: "Monitoring" },
{ 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" },
+177
View File
@@ -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 &amp; Research Centre
</h1>
<p className="text-sm text-gray-500 mt-0.5">
Asset Management &amp; 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>
);
}
+951
View File
@@ -0,0 +1,951 @@
import { useState, useMemo } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import type { ColumnDef } from "@tanstack/react-table";
import { Plus, Pencil, Power, AlertCircle } from "lucide-react";
import { DataTable } from "@/components/DataTable";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Modal } from "@/components/ui/dialog";
import { ApiError } from "@/api/client";
import { ROLE_LABELS, type Role } from "@/lib/permissions";
import {
departmentsApi,
locationsApi,
categoriesApi,
vendorsApi,
usersApi,
VENDOR_TYPE_LABELS,
type Department,
type LocationItem,
type Category,
type Vendor,
type VendorType,
type MasterUser,
} from "@/api/masters";
type TabKey = "departments" | "locations" | "categories" | "vendors" | "users";
const TABS: { key: TabKey; label: string }[] = [
{ key: "departments", label: "Departments" },
{ key: "locations", label: "Locations" },
{ key: "categories", label: "Categories" },
{ key: "vendors", label: "Vendors" },
{ key: "users", label: "Users" },
];
function StatusBadge({ active }: { active: boolean }) {
return <Badge variant={active ? "success" : "outline"}>{active ? "Active" : "Inactive"}</Badge>;
}
function RowActions({
active,
onEdit,
onToggleActive,
busy,
}: {
active: boolean;
onEdit: () => void;
onToggleActive: () => void;
busy?: boolean;
}) {
return (
<div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
<Button variant="outline" size="sm" onClick={onEdit}>
<Pencil className="h-3.5 w-3.5 mr-1" />
Edit
</Button>
<Button
variant={active ? "ghost" : "outline"}
size="sm"
disabled={busy}
onClick={onToggleActive}
className={active ? "text-red-600 hover:bg-red-50" : "text-green-700 hover:bg-green-50"}
>
<Power className="h-3.5 w-3.5 mr-1" />
{active ? "Deactivate" : "Reactivate"}
</Button>
</div>
);
}
function FormErrorBanner({ message }: { message: string | null }) {
if (!message) return null;
return (
<div className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700 mb-3">
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
<span>{message}</span>
</div>
);
}
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 errCls = "text-xs text-red-600 mt-1";
// --- Department Modal ---
const deptSchema = z.object({
name: z.string().trim().min(1, "Department name is required"),
code: z.string().trim().min(1, "Department code is required").max(20, "Max 20 characters"),
description: z.string().optional(),
});
type DeptForm = z.infer<typeof deptSchema>;
function DepartmentModal({
open,
onClose,
editing,
}: {
open: boolean;
onClose: () => void;
editing: Department | null;
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<DeptForm>({
resolver: zodResolver(deptSchema),
values: editing
? { name: editing.name, code: editing.code, description: editing.description ?? "" }
: { name: "", code: "", description: "" },
});
async function onSubmit(values: DeptForm) {
setServerError(null);
const payload = {
name: values.name,
code: values.code.toUpperCase(),
description: values.description?.trim() || null,
};
try {
if (editing) await departmentsApi.update(editing.id, payload);
else await departmentsApi.create(payload);
await qc.invalidateQueries({ queryKey: ["departments"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save department.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit Department" : "Add Department"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className={labelCls}>Name *</label>
<input {...register("name")} className={inputCls} placeholder="e.g. Intensive Care Unit" />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Code *</label>
<input {...register("code")} className={inputCls} placeholder="e.g. ICU" />
{errors.code && <p className={errCls}>{errors.code.message}</p>}
</div>
<div>
<label className={labelCls}>Description</label>
<textarea {...register("description")} 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"}</Button>
</div>
</form>
</Modal>
);
}
// --- Location Modal ---
const locSchema = z.object({
department_id: z.coerce.number().int().min(1, "Select a department"),
name: z.string().trim().min(1, "Location name is required"),
floor_wing: z.string().optional(),
});
type LocForm = z.infer<typeof locSchema>;
function LocationModal({
open,
onClose,
editing,
departments,
}: {
open: boolean;
onClose: () => void;
editing: LocationItem | null;
departments: Department[];
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<LocForm>({
resolver: zodResolver(locSchema),
values: editing
? {
department_id: editing.department_id,
name: editing.name,
floor_wing: editing.floor_wing ?? "",
}
: { department_id: departments[0]?.id ?? 0, name: "", floor_wing: "" },
});
async function onSubmit(values: LocForm) {
setServerError(null);
const payload = {
department_id: values.department_id,
name: values.name,
floor_wing: values.floor_wing?.trim() || null,
};
try {
if (editing) await locationsApi.update(editing.id, payload);
else await locationsApi.create(payload);
await qc.invalidateQueries({ queryKey: ["locations"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save location.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit Location" : "Add Location"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className={labelCls}>Department *</label>
<select {...register("department_id")} 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 Name *</label>
<input {...register("name")} className={inputCls} placeholder="e.g. ICU Bay 1" />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Floor / Wing</label>
<input {...register("floor_wing")} className={inputCls} placeholder="e.g. 2nd Floor, East Wing" />
</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"}</Button>
</div>
</form>
</Modal>
);
}
// --- Category Modal ---
const catSchema = z.object({
name: z.string().trim().min(1, "Category name is required"),
description: z.string().optional(),
});
type CatForm = z.infer<typeof catSchema>;
function CategoryModal({
open,
onClose,
editing,
}: {
open: boolean;
onClose: () => void;
editing: Category | null;
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<CatForm>({
resolver: zodResolver(catSchema),
values: editing
? { name: editing.name, description: editing.description ?? "" }
: { name: "", description: "" },
});
async function onSubmit(values: CatForm) {
setServerError(null);
const payload = {
name: values.name,
description: values.description?.trim() || null,
};
try {
if (editing) await categoriesApi.update(editing.id, payload);
else await categoriesApi.create(payload);
await qc.invalidateQueries({ queryKey: ["categories"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save category.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit Category" : "Add Category"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className={labelCls}>Name *</label>
<input {...register("name")} className={inputCls} placeholder="e.g. Life Support" />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Description</label>
<textarea {...register("description")} 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"}</Button>
</div>
</form>
</Modal>
);
}
// --- Vendor Modal ---
const vendorSchema = z.object({
name: z.string().trim().min(1, "Vendor name is required"),
vendor_type: z.enum(["supplier", "service_provider", "calibration_agency", "insurer", "oem"]),
contact_person: z.string().optional(),
phone: z.string().optional(),
email: z.string().email("Invalid email").or(z.literal("")).optional(),
address: z.string().optional(),
});
type VendorForm = z.infer<typeof vendorSchema>;
function VendorModal({
open,
onClose,
editing,
}: {
open: boolean;
onClose: () => void;
editing: Vendor | null;
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<VendorForm>({
resolver: zodResolver(vendorSchema),
values: editing
? {
name: editing.name,
vendor_type: editing.vendor_type,
contact_person: editing.contact_person ?? "",
phone: editing.phone ?? "",
email: editing.email ?? "",
address: editing.address ?? "",
}
: { name: "", vendor_type: "supplier", contact_person: "", phone: "", email: "", address: "" },
});
async function onSubmit(values: VendorForm) {
setServerError(null);
const payload = {
name: values.name,
vendor_type: values.vendor_type,
contact_person: values.contact_person?.trim() || null,
phone: values.phone?.trim() || null,
email: values.email?.trim() || null,
address: values.address?.trim() || null,
};
try {
if (editing) await vendorsApi.update(editing.id, payload);
else await vendorsApi.create(payload);
await qc.invalidateQueries({ queryKey: ["vendors"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save vendor.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit Vendor" : "Add Vendor"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
<div>
<label className={labelCls}>Vendor Name *</label>
<input {...register("name")} className={inputCls} />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Vendor Type *</label>
<select {...register("vendor_type")} className={inputCls}>
{(Object.keys(VENDOR_TYPE_LABELS) as VendorType[]).map((vt) => (
<option key={vt} value={vt}>{VENDOR_TYPE_LABELS[vt]}</option>
))}
</select>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Contact Person</label>
<input {...register("contact_person")} className={inputCls} />
</div>
<div>
<label className={labelCls}>Phone</label>
<input {...register("phone")} className={inputCls} />
</div>
</div>
<div>
<label className={labelCls}>Email</label>
<input {...register("email")} type="email" className={inputCls} />
{errors.email && <p className={errCls}>{errors.email.message}</p>}
</div>
<div>
<label className={labelCls}>Address</label>
<textarea {...register("address")} 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"}</Button>
</div>
</form>
</Modal>
);
}
// --- User Modal ---
function buildUserSchema(isEdit: boolean) {
return z.object({
name: z.string().trim().min(1, "Name is required"),
email: z.string().email("Enter a valid email"),
role: z.enum(["system_admin", "biomedical", "department_user", "management", "coordinator"]),
department_id: z.string().optional(),
password: isEdit
? z.string().refine((v) => v === "" || v.length >= 6, "Password must be at least 6 characters")
: z.string().min(6, "Password must be at least 6 characters"),
});
}
function UserModal({
open,
onClose,
editing,
departments,
}: {
open: boolean;
onClose: () => void;
editing: MasterUser | null;
departments: Department[];
}) {
const qc = useQueryClient();
const [serverError, setServerError] = useState<string | null>(null);
const schema = useMemo(() => buildUserSchema(Boolean(editing)), [editing]);
type UserForm = z.infer<typeof schema>;
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<UserForm>({
resolver: zodResolver(schema),
values: editing
? {
name: editing.name,
email: editing.email,
role: editing.role,
department_id: editing.department_id ? String(editing.department_id) : "",
password: "",
}
: { name: "", email: "", role: "department_user", department_id: "", password: "" },
});
async function onSubmit(values: UserForm) {
setServerError(null);
const deptId = values.department_id ? Number(values.department_id) : null;
try {
if (editing) {
const payload: Parameters<typeof usersApi.update>[1] = {
name: values.name,
email: values.email,
role: values.role,
department_id: deptId,
};
if (values.password) payload.password = values.password;
await usersApi.update(editing.id, payload);
} else {
await usersApi.create({
name: values.name,
email: values.email,
role: values.role,
department_id: deptId,
password: values.password,
});
}
await qc.invalidateQueries({ queryKey: ["users"] });
onClose();
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to save user.");
}
}
return (
<Modal open={open} onOpenChange={(o) => !o && onClose()} title={editing ? "Edit User" : "Add User"}>
<FormErrorBanner message={serverError} />
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
<div>
<label className={labelCls}>Full Name *</label>
<input {...register("name")} className={inputCls} />
{errors.name && <p className={errCls}>{errors.name.message}</p>}
</div>
<div>
<label className={labelCls}>Email *</label>
<input {...register("email")} type="email" className={inputCls} />
{errors.email && <p className={errCls}>{errors.email.message}</p>}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Role *</label>
<select {...register("role")} className={inputCls}>
{(Object.keys(ROLE_LABELS) as Role[]).map((r) => (
<option key={r} value={r}>{ROLE_LABELS[r]}</option>
))}
</select>
</div>
<div>
<label className={labelCls}>Department</label>
<select {...register("department_id")} className={inputCls}>
<option value="">None (Hospital-wide)</option>
{departments.map((d) => (
<option key={d.id} value={String(d.id)}>{d.name}</option>
))}
</select>
</div>
</div>
<div>
<label className={labelCls}>
{editing ? "New Password (leave blank to keep current)" : "Password *"}
</label>
<input {...register("password")} type="password" className={inputCls} />
{errors.password && <p className={errCls}>{errors.password.message}</p>}
</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"}</Button>
</div>
</form>
</Modal>
);
}
// --- Main MastersPage ---
export function MastersPage() {
const qc = useQueryClient();
const [activeTab, setActiveTab] = useState<TabKey>("departments");
const [includeInactive, setIncludeInactive] = useState(true);
const [modalOpen, setModalOpen] = useState(false);
const [editingDept, setEditingDept] = useState<Department | null>(null);
const [editingLoc, setEditingLoc] = useState<LocationItem | null>(null);
const [editingCat, setEditingCat] = useState<Category | null>(null);
const [editingVendor, setEditingVendor] = useState<Vendor | null>(null);
const [editingUser, setEditingUser] = useState<MasterUser | null>(null);
const deptsQuery = useQuery({
queryKey: ["departments", includeInactive],
queryFn: () => departmentsApi.list(includeInactive),
});
const activeDeptsQuery = useQuery({
queryKey: ["departments", "active-only"],
queryFn: () => departmentsApi.list(false),
});
const locsQuery = useQuery({
queryKey: ["locations", includeInactive],
queryFn: () => locationsApi.list(includeInactive),
enabled: activeTab === "locations",
});
const catsQuery = useQuery({
queryKey: ["categories", includeInactive],
queryFn: () => categoriesApi.list(includeInactive),
enabled: activeTab === "categories",
});
const vendorsQuery = useQuery({
queryKey: ["vendors", includeInactive],
queryFn: () => vendorsApi.list(includeInactive),
enabled: activeTab === "vendors",
});
const usersQuery = useQuery({
queryKey: ["users", includeInactive],
queryFn: () => usersApi.list(includeInactive),
enabled: activeTab === "users",
});
const toggleMutation = useMutation({
mutationFn: async ({
tab,
id,
currentlyActive,
}: {
tab: TabKey;
id: number;
currentlyActive: boolean;
}) => {
if (tab === "departments") {
return currentlyActive ? departmentsApi.remove(id) : departmentsApi.update(id, { is_active: true });
}
if (tab === "locations") {
return currentlyActive ? locationsApi.remove(id) : locationsApi.update(id, { is_active: true });
}
if (tab === "categories") {
return currentlyActive ? categoriesApi.remove(id) : categoriesApi.update(id, { is_active: true });
}
if (tab === "vendors") {
return currentlyActive ? vendorsApi.remove(id) : vendorsApi.update(id, { is_active: true });
}
return currentlyActive ? usersApi.remove(id) : usersApi.update(id, { is_active: true });
},
onSuccess: (_data, vars) => {
qc.invalidateQueries({ queryKey: [vars.tab] });
},
});
function openCreate() {
setEditingDept(null);
setEditingLoc(null);
setEditingCat(null);
setEditingVendor(null);
setEditingUser(null);
setModalOpen(true);
}
const deptColumns: ColumnDef<Department, unknown>[] = [
{ accessorKey: "code", header: "Code", enableColumnFilter: true },
{ accessorKey: "name", header: "Name", enableColumnFilter: true },
{
accessorKey: "description",
header: "Description",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingDept(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "departments", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const locColumns: ColumnDef<LocationItem, unknown>[] = [
{ accessorKey: "name", header: "Location Name", enableColumnFilter: true },
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "floor_wing",
header: "Floor / Wing",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingLoc(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "locations", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const catColumns: ColumnDef<Category, unknown>[] = [
{ accessorKey: "name", header: "Category Name", enableColumnFilter: true },
{
accessorKey: "description",
header: "Description",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingCat(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "categories", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const vendorColumns: ColumnDef<Vendor, unknown>[] = [
{ accessorKey: "name", header: "Vendor Name", enableColumnFilter: true },
{
accessorKey: "vendor_type",
header: "Type",
enableColumnFilter: true,
cell: ({ getValue }) => VENDOR_TYPE_LABELS[getValue() as VendorType] ?? String(getValue()),
},
{
accessorKey: "contact_person",
header: "Contact",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "phone",
header: "Phone",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "email",
header: "Email",
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingVendor(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "vendors", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const userColumns: ColumnDef<MasterUser, unknown>[] = [
{ accessorKey: "name", header: "Name", enableColumnFilter: true },
{ accessorKey: "email", header: "Email", enableColumnFilter: true },
{
accessorKey: "role",
header: "Role",
enableColumnFilter: true,
cell: ({ getValue }) => (
<Badge variant="info">{ROLE_LABELS[getValue() as Role] ?? String(getValue())}</Badge>
),
},
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "Hospital-wide",
},
{
accessorKey: "is_active",
header: "Status",
cell: ({ getValue }) => <StatusBadge active={Boolean(getValue())} />,
},
{
id: "actions",
header: "Actions",
enableSorting: false,
enableColumnFilter: false,
cell: ({ row }) => (
<RowActions
active={row.original.is_active}
busy={toggleMutation.isPending}
onEdit={() => {
setEditingUser(row.original);
setModalOpen(true);
}}
onToggleActive={() =>
toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active })
}
/>
),
},
];
const activeDepartments = activeDeptsQuery.data?.items ?? [];
const addLabelMap: Record<TabKey, string> = {
departments: "Add Department",
locations: "Add Location",
categories: "Add Category",
vendors: "Add Vendor",
users: "Add User",
};
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">Master Lists</h1>
<p className="text-sm text-gray-500 mt-0.5">
Manage departments, locations, equipment categories, vendors, and user accounts.
</p>
</div>
<div className="flex items-center gap-3">
<label className="inline-flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
<input
type="checkbox"
checked={includeInactive}
onChange={(e) => setIncludeInactive(e.target.checked)}
className="rounded border-gray-300"
/>
Show inactive
</label>
<Button onClick={openCreate}>
<Plus className="h-4 w-4 mr-1.5" />
{addLabelMap[activeTab]}
</Button>
</div>
</div>
{/* Tabs */}
<div className="border-b border-gray-200 flex gap-1 overflow-x-auto">
{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 === "departments" && (
<DataTable
data={deptsQuery.data?.items ?? []}
columns={deptColumns}
loading={deptsQuery.isLoading}
globalFilterPlaceholder="Search departments..."
exportFilename="departments"
/>
)}
{activeTab === "locations" && (
<DataTable
data={locsQuery.data?.items ?? []}
columns={locColumns}
loading={locsQuery.isLoading}
globalFilterPlaceholder="Search locations..."
exportFilename="locations"
/>
)}
{activeTab === "categories" && (
<DataTable
data={catsQuery.data?.items ?? []}
columns={catColumns}
loading={catsQuery.isLoading}
globalFilterPlaceholder="Search categories..."
exportFilename="categories"
/>
)}
{activeTab === "vendors" && (
<DataTable
data={vendorsQuery.data?.items ?? []}
columns={vendorColumns}
loading={vendorsQuery.isLoading}
globalFilterPlaceholder="Search vendors..."
exportFilename="vendors"
/>
)}
{activeTab === "users" && (
<DataTable
data={usersQuery.data?.items ?? []}
columns={userColumns}
loading={usersQuery.isLoading}
globalFilterPlaceholder="Search users..."
exportFilename="users"
/>
)}
{/* Modals */}
{modalOpen && activeTab === "departments" && (
<DepartmentModal open={modalOpen} onClose={() => setModalOpen(false)} editing={editingDept} />
)}
{modalOpen && activeTab === "locations" && (
<LocationModal
open={modalOpen}
onClose={() => setModalOpen(false)}
editing={editingLoc}
departments={activeDepartments}
/>
)}
{modalOpen && activeTab === "categories" && (
<CategoryModal open={modalOpen} onClose={() => setModalOpen(false)} editing={editingCat} />
)}
{modalOpen && activeTab === "vendors" && (
<VendorModal open={modalOpen} onClose={() => setModalOpen(false)} editing={editingVendor} />
)}
{modalOpen && activeTab === "users" && (
<UserModal
open={modalOpen}
onClose={() => setModalOpen(false)}
editing={editingUser}
departments={activeDepartments}
/>
)}
</div>
);
}
+226
View File
@@ -0,0 +1,226 @@
import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Save, CheckCircle2, AlertCircle, X } from "lucide-react";
import { settingsApi, type SettingItem } from "@/api/settings";
import { ApiError } from "@/api/client";
import { useAuthStore } from "@/hooks/useAuth";
import { Button } from "@/components/ui/button";
export function SettingsPage() {
const qc = useQueryClient();
const setDemoAsOfDate = useAuthStore((s) => s.setDemoAsOfDate);
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,
});
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 === "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>
);
}
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, 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>
)}
<div className="bg-white rounded-lg border border-gray-200 divide-y divide-gray-100">
{data?.items.map((item) => {
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.min != null && item.max != null && (
<> • Range: {item.min}–{item.max}</>
)}
</p>
</div>
<div className="sm:w-64 shrink-0">
{item.type === "int" && (
<input
id={`setting-${item.key}`}
type="number"
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">{Boolean(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>
);
})}
</div>
</form>
);
}
-3
View File
@@ -70,6 +70,3 @@ export const ReportsPage = () => (
export const NotificationsPage = () => (
<StubPage title="Notifications" phase={6} description="In-app alerts and notification centre." />
);
export const SettingsPage = () => (
<StubPage title="Settings" phase={1} description="Configurable lead days, downtime rules, and system settings." />
);
+67
View File
@@ -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");
});
});
});
+57
View File
@@ -0,0 +1,57 @@
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", "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);
});
});
+66 -3
View File
@@ -1,12 +1,30 @@
import { describe, it, expect } from "vitest";
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 { DashboardPage } from "@/pages/stubs";
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
import { useAuthStore } from "@/hooks/useAuth";
describe("Phase 0 Frontend Smoke Tests", () => {
it("renders Sidebar with Poona Hospital logo, subtitle, and all 12 navigation links", () => {
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 />
@@ -30,6 +48,7 @@ describe("Phase 0 Frontend Smoke Tests", () => {
"Department Visits",
"Reports",
"Notifications",
"Masters",
"Settings",
];
for (const label of labels) {
@@ -37,6 +56,50 @@ describe("Phase 0 Frontend Smoke Tests", () => {
}
});
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("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("Settings")).not.toBeInTheDocument();
expect(screen.queryByText("Department Visits")).not.toBeInTheDocument();
expect(screen.getByText("Contracts & Warranty")).toBeInTheDocument();
});
it("renders DashboardPage with clickable link to /demo", () => {
render(
<MemoryRouter>
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/api/health.ts","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/datatabledemopage.tsx","./src/pages/stubs.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/auth.ts","./src/api/client.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/settings.ts","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}