feat(M06): Add Department and UserDepartment models, seed 12 DMH departments, and enable department-level permissions

This commit is contained in:
Atharv1705
2026-11-27 15:07:34 +05:30
parent a79e21aad6
commit c7b3ead367
21 changed files with 1192 additions and 18 deletions
+2
View File
@@ -6,6 +6,7 @@ import { AppLayout } from './components/layout/AppLayout';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { AdminUsersPage } from './pages/AdminUsersPage';
import { AdminDepartmentsPage } from './pages/AdminDepartmentsPage';
import { AdminDatasetsPage } from './pages/AdminDatasetsPage';
import { AdminPermissionsPage } from './pages/AdminPermissionsPage';
@@ -30,6 +31,7 @@ export const App: React.FC = () => {
<Route path="/" element={<Navigate to="/dashboard" replace />} />
<Route path="/dashboard" element={<DashboardPage />} />
<Route path="/admin/users" element={<AdminUsersPage />} />
<Route path="/admin/departments" element={<AdminDepartmentsPage />} />
<Route path="/admin/datasets" element={<AdminDatasetsPage />} />
<Route path="/admin/permissions" element={<AdminPermissionsPage />} />
</Route>
+32
View File
@@ -0,0 +1,32 @@
import { api } from './client';
import { Department, DepartmentCreate, DepartmentUpdate } from '../types';
export const departmentsApi = {
getDepartments: async (isActive?: boolean, search?: string): Promise<Department[]> => {
const params = new URLSearchParams();
if (isActive !== undefined) params.append('is_active', String(isActive));
if (search) params.append('search', search);
const queryString = params.toString() ? `?${params.toString()}` : '';
return api.get<Department[]>(`/departments${queryString}`);
},
getDepartmentById: async (departmentId: number): Promise<Department> => {
return api.get<Department>(`/departments/${departmentId}`);
},
createDepartment: async (payload: DepartmentCreate): Promise<Department> => {
return api.post<Department>('/departments', payload);
},
updateDepartment: async (departmentId: number, payload: DepartmentUpdate): Promise<Department> => {
return api.put<Department>(`/departments/${departmentId}`, payload);
},
addMember: async (departmentId: number, userId: number, isHead: boolean = false): Promise<any> => {
return api.post(`/departments/${departmentId}/members`, { user_id: userId, is_head: isHead });
},
removeMember: async (departmentId: number, userId: number): Promise<void> => {
return api.delete(`/departments/${departmentId}/members/${userId}`);
},
};
+5 -1
View File
@@ -1,7 +1,7 @@
import React from 'react';
import { NavLink } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { LayoutDashboard, Users, Database, ShieldCheck, Lock } from 'lucide-react';
import { LayoutDashboard, Users, Building2, Database, ShieldCheck, Lock } from 'lucide-react';
export const Sidebar: React.FC = () => {
const { isSuperAdmin } = useAuth();
@@ -39,6 +39,10 @@ export const Sidebar: React.FC = () => {
<Users className="w-4 h-4" />
<span>User Management</span>
</NavLink>
<NavLink to="/admin/departments" className={navItemClass}>
<Building2 className="w-4 h-4" />
<span>Departments (M06)</span>
</NavLink>
<NavLink to="/admin/datasets" className={navItemClass}>
<Database className="w-4 h-4" />
<span>Datasets & Schemas</span>
+286
View File
@@ -0,0 +1,286 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { departmentsApi } from '../api/departments';
import { usersApi } from '../api/users';
import { Department, User } from '../types';
import { Building2, Search, Plus, Users, ShieldAlert, CheckCircle, X, Crown, Trash2 } from 'lucide-react';
export const AdminDepartmentsPage: React.FC = () => {
const queryClient = useQueryClient();
const [searchTerm, setSearchTerm] = useState('');
const [selectedDeptId, setSelectedDeptId] = useState<number | null>(null);
const [isCreateOpen, setIsCreateOpen] = useState(false);
const [newCode, setNewCode] = useState('');
const [newName, setNewName] = useState('');
const [newDesc, setNewDesc] = useState('');
const [selectedUserId, setSelectedUserId] = useState<string>('');
const [isHead, setIsHead] = useState(false);
const [feedbackMsg, setFeedbackMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
const { data: departments = [] } = useQuery({
queryKey: ['departments', searchTerm],
queryFn: () => departmentsApi.getDepartments(undefined, searchTerm),
});
const { data: allUsers = [] } = useQuery({
queryKey: ['allUsers'],
queryFn: () => usersApi.getUsers(0, 100),
});
const { data: selectedDept } = useQuery({
queryKey: ['departmentDetail', selectedDeptId],
queryFn: () => (selectedDeptId ? departmentsApi.getDepartmentById(selectedDeptId) : null),
enabled: !!selectedDeptId,
});
const createDeptMutation = useMutation({
mutationFn: departmentsApi.createDepartment,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['departments'] });
setIsCreateOpen(false);
setNewCode('');
setNewName('');
setNewDesc('');
setFeedbackMsg({ type: 'success', text: 'Department registered successfully!' });
setTimeout(() => setFeedbackMsg(null), 3500);
},
onError: (err: any) => {
setFeedbackMsg({ type: 'error', text: err?.response?.data?.detail || 'Failed to create department' });
},
});
const addMemberMutation = useMutation({
mutationFn: ({ deptId, userId, head }: { deptId: number; userId: number; head: boolean }) =>
departmentsApi.addMember(deptId, userId, head),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['departmentDetail', selectedDeptId] });
queryClient.invalidateQueries({ queryKey: ['departments'] });
setSelectedUserId('');
setIsHead(false);
},
onError: (err: any) => {
setFeedbackMsg({ type: 'error', text: err?.response?.data?.detail || 'Failed to assign member' });
},
});
const removeMemberMutation = useMutation({
mutationFn: ({ deptId, userId }: { deptId: number; userId: number }) =>
departmentsApi.removeMember(deptId, userId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['departmentDetail', selectedDeptId] });
queryClient.invalidateQueries({ queryKey: ['departments'] });
},
});
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-200 pb-4">
<div>
<div className="flex items-center space-x-2">
<Building2 className="w-6 h-6 text-blue-600" />
<h1 className="text-2xl font-bold text-slate-800">Hospital Departments</h1>
</div>
<p className="text-sm text-slate-500 mt-1">
MediInsight AI Module M06: Department directory, HOD leadership, and inherited access controls.
</p>
</div>
<button
onClick={() => setIsCreateOpen(true)}
className="flex items-center space-x-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition"
>
<Plus className="w-4 h-4" />
<span>New Department</span>
</button>
</div>
{feedbackMsg && (
<div className={`p-3 rounded-lg text-sm flex items-center space-x-2 ${
feedbackMsg.type === 'success' ? 'bg-emerald-50 text-emerald-800 border border-emerald-200' : 'bg-red-50 text-red-800 border border-red-200'
}`}>
{feedbackMsg.type === 'success' ? <CheckCircle className="w-4 h-4" /> : <ShieldAlert className="w-4 h-4" />}
<span>{feedbackMsg.text}</span>
</div>
)}
{/* Search Bar */}
<div className="relative max-w-md">
<Search className="w-4 h-4 absolute left-3 top-3 text-slate-400" />
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search by code (e.g. IPD, OPD) or name..."
className="w-full pl-9 pr-4 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
{/* Department Cards Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{departments.map((dept: Department) => (
<div
key={dept.id}
className={`bg-white border rounded-xl p-5 shadow-sm hover:shadow-md transition cursor-pointer flex flex-col justify-between ${
selectedDeptId === dept.id ? 'border-blue-500 ring-2 ring-blue-100' : 'border-slate-200'
}`}
onClick={() => setSelectedDeptId(dept.id)}
>
<div>
<div className="flex items-center justify-between mb-2">
<span className="font-mono text-xs font-semibold px-2.5 py-1 bg-slate-100 text-slate-700 rounded border border-slate-200">
{dept.code}
</span>
<span className="inline-flex items-center text-xs px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 font-medium">
Active
</span>
</div>
<h3 className="font-semibold text-slate-800 text-base">{dept.name}</h3>
<p className="text-xs text-slate-500 mt-1 line-clamp-2">{dept.description || 'No description provided'}</p>
</div>
<div className="flex items-center justify-between pt-4 mt-4 border-t border-slate-100 text-xs text-slate-500">
<span className="flex items-center space-x-1.5">
<Users className="w-3.5 h-3.5 text-blue-500" />
<span className="font-medium text-slate-700">{dept.member_count} member(s)</span>
</span>
<span className="text-blue-600 font-medium hover:underline">Manage Members &rarr;</span>
</div>
</div>
))}
</div>
{/* Department Member Management Modal / Drawer */}
{selectedDept && (
<div className="fixed inset-0 z-50 bg-slate-900/40 flex justify-end">
<div className="bg-white w-full max-w-md h-full shadow-2xl p-6 overflow-y-auto flex flex-col justify-between">
<div>
<div className="flex items-center justify-between border-b border-slate-200 pb-3">
<div>
<span className="font-mono text-xs font-bold text-blue-600">{selectedDept.code}</span>
<h2 className="text-lg font-bold text-slate-800">{selectedDept.name}</h2>
</div>
<button onClick={() => setSelectedDeptId(null)} className="p-1 hover:bg-slate-100 rounded">
<X className="w-5 h-5 text-slate-400" />
</button>
</div>
{/* Add Member Form */}
<div className="my-4 p-3 bg-slate-50 border border-slate-200 rounded-lg space-y-3">
<div className="text-xs font-semibold text-slate-700">Assign User to Department</div>
<select
value={selectedUserId}
onChange={(e) => setSelectedUserId(e.target.value)}
className="w-full text-xs p-2 border border-slate-300 rounded bg-white"
>
<option value="">-- Select Hospital Staff --</option>
{allUsers.map((u: User) => (
<option key={u.id} value={u.id}>
{u.full_name || u.username} ({u.role})
</option>
))}
</select>
<label className="flex items-center space-x-2 text-xs text-slate-600">
<input
type="checkbox"
checked={isHead}
onChange={(e) => setIsHead(e.target.checked)}
className="rounded border-slate-300 text-blue-600 focus:ring-blue-500"
/>
<span>Designate as Department Head / HOD</span>
</label>
<button
disabled={!selectedUserId}
onClick={() =>
addMemberMutation.mutate({
deptId: selectedDept.id,
userId: Number(selectedUserId),
head: isHead,
})
}
className="w-full bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-xs font-medium py-1.5 rounded transition"
>
Assign to Department
</button>
</div>
{/* Member List */}
<div className="space-y-2 mt-4">
<div className="text-xs font-semibold text-slate-600 uppercase tracking-wider">
Active Members ({selectedDept.members?.length || 0})
</div>
{selectedDept.members?.length === 0 ? (
<div className="text-xs text-slate-400 py-4 text-center">No staff assigned yet.</div>
) : (
selectedDept.members?.map((m) => (
<div
key={m.user_id}
className="flex items-center justify-between p-2.5 bg-white border border-slate-200 rounded-lg text-xs"
>
<div>
<div className="flex items-center space-x-1.5 font-medium text-slate-800">
<span>{m.full_name || m.username}</span>
{m.is_head && (
<span className="flex items-center text-[10px] text-amber-700 bg-amber-50 px-1.5 py-0.5 rounded font-semibold border border-amber-200">
<Crown className="w-2.5 h-2.5 mr-1 text-amber-500" /> HOD
</span>
)}
</div>
<div className="text-slate-400 text-[11px]">{m.email} &bull; {m.role}</div>
</div>
<button
onClick={() => removeMemberMutation.mutate({ deptId: selectedDept.id, userId: m.user_id })}
className="text-slate-400 hover:text-red-600 p-1 rounded"
title="Remove member"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
))
)}
</div>
</div>
<button
onClick={() => setSelectedDeptId(null)}
className="mt-6 w-full py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded text-xs font-medium"
>
Close Panel
</button>
</div>
</div>
)}
{/* New Department Modal */}
{isCreateOpen && (
<div className="fixed inset-0 z-50 bg-slate-900/50 flex items-center justify-center p-4">
<div className="bg-white rounded-xl max-w-md w-full p-6 shadow-xl space-y-4">
<h3 className="font-bold text-lg text-slate-800">Register Hospital Department</h3>
<div className="space-y-3">
<div>
<label className="text-xs font-semibold text-slate-700 block mb-1">Department Code</label>
<input type="text" value={newCode} onChange={(e) => setNewCode(e.target.value.toUpperCase())} placeholder="e.g. ICU, NEURO" className="w-full text-xs p-2 border border-slate-300 rounded font-mono" />
</div>
<div>
<label className="text-xs font-semibold text-slate-700 block mb-1">Department Name</label>
<input type="text" value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="e.g. Intensive Care Unit" className="w-full text-xs p-2 border border-slate-300 rounded" />
</div>
<div>
<label className="text-xs font-semibold text-slate-700 block mb-1">Description / Purpose</label>
<textarea value={newDesc} onChange={(e) => setNewDesc(e.target.value)} placeholder="Scope of medical or administrative activity..." className="w-full text-xs p-2 border border-slate-300 rounded h-20" />
</div>
</div>
<div className="flex justify-end space-x-2 pt-2 border-t border-slate-100">
<button
onClick={() => setIsCreateOpen(false)}
className="px-3 py-1.5 text-xs text-slate-600 hover:bg-slate-100 rounded font-medium"
>Cancel</button>
<button
disabled={!newCode || !newName || createDeptMutation.isPending}
onClick={() => createDeptMutation.mutate({ code: newCode, name: newName, description: newDesc })}
className="px-4 py-1.5 text-xs bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white rounded font-medium transition"
>Save Department</button>
</div>
</div>
</div>
)}
</div>
);
};
+36
View File
@@ -133,3 +133,39 @@ export interface DashboardWidget {
width: string;
chart_spec: ChartSpec;
}
export interface DepartmentMember {
user_id: number;
username: string;
full_name?: string | null;
email: string;
role: string;
is_head: boolean;
joined_at: string;
}
export interface Department {
id: number;
code: string;
name: string;
description?: string | null;
is_active: boolean;
member_count: number;
created_at: string;
updated_at: string;
members?: DepartmentMember[];
}
export interface DepartmentCreate {
code: string;
name: string;
description?: string;
}
export interface DepartmentUpdate {
code?: string;
name?: string;
description?: string;
is_active?: boolean;
}