Roles section

This commit is contained in:
2026-01-29 16:41:21 -06:00
parent 13cc4528ff
commit 33b072436d
3 changed files with 315 additions and 97 deletions

View File

@@ -1,63 +1,148 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Plus, Trash2, Pencil, RefreshCcw } from "lucide-react"; import { Plus, Trash2, Pencil, RefreshCcw, AlertCircle, Loader2 } from "lucide-react";
import MaterialTable from "@material-table/core"; import MaterialTable from "@material-table/core";
import { getAllRoles, createRole, updateRole, deleteRole, type Role } from "../api/roles";
import ConfirmModal from "../components/layout/common/ConfirmModal";
export interface Role { interface RoleForm {
id: string;
name: string; name: string;
description: string; description: string;
status: "ACTIVE" | "INACTIVE"; permissions?: Record<string, Record<string, boolean>>;
createdAt: string;
} }
export default function RolesPage() { export default function RolesPage() {
const initialRoles: Role[] = [ const [roles, setRoles] = useState<Role[]>([]);
{ id: "1", name: "SUPER_ADMIN", description: "Full access", status: "ACTIVE", createdAt: "2025-12-17" },
{ id: "2", name: "USER", description: "Regular user", status: "ACTIVE", createdAt: "2025-12-16" },
];
const [roles, setRoles] = useState<Role[]>(initialRoles);
const [activeRole, setActiveRole] = useState<Role | null>(null); const [activeRole, setActiveRole] = useState<Role | null>(null);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null); const [editingId, setEditingId] = useState<string | null>(null);
const emptyRole: Omit<Role, "id"> = { const emptyForm: RoleForm = {
name: "", name: "",
description: "", description: "",
status: "ACTIVE", permissions: {},
createdAt: new Date().toISOString().slice(0, 10),
}; };
const [form, setForm] = useState<Omit<Role, "id">>(emptyRole); const [form, setForm] = useState<RoleForm>(emptyForm);
const handleSave = () => { useEffect(() => {
fetchRoles();
}, []);
const fetchRoles = async () => {
setLoading(true);
setError(null);
try {
const data = await getAllRoles();
setRoles(data);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to load roles");
console.error("Error fetching roles:", err);
} finally {
setLoading(false);
}
};
const handleSave = async () => {
if (!form.name.trim()) {
setError("Role name is required");
return;
}
setLoading(true);
setError(null);
try {
if (editingId) { if (editingId) {
setRoles(prev => prev.map(r => r.id === editingId ? { id: editingId, ...form } : r)); const updated = await updateRole(editingId, form);
setRoles(prev => prev.map(r => r.id === editingId ? updated : r));
} else { } else {
const newId = Date.now().toString(); const created = await createRole(form);
setRoles(prev => [...prev, { id: newId, ...form }]); setRoles(prev => [...prev, created]);
} }
setShowModal(false); setShowModal(false);
setEditingId(null); setEditingId(null);
setForm(emptyRole); setForm(emptyForm);
setActiveRole(null);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to save role");
console.error("Error saving role:", err);
} finally {
setLoading(false);
}
}; };
const handleDelete = () => { const handleDelete = async () => {
if (!activeRole) return; if (!activeRole) return;
setLoading(true);
setError(null);
try {
await deleteRole(activeRole.id);
setRoles(prev => prev.filter(r => r.id !== activeRole.id)); setRoles(prev => prev.filter(r => r.id !== activeRole.id));
setActiveRole(null); setActiveRole(null);
setShowDeleteConfirm(false);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to delete role");
console.error("Error deleting role:", err);
} finally {
setLoading(false);
}
}; };
const filtered = roles.filter(r => r.name.toLowerCase().includes(search.toLowerCase())); const openEditModal = () => {
if (!activeRole) return;
setEditingId(activeRole.id);
setForm({
name: activeRole.name,
description: activeRole.description,
permissions: activeRole.permissions,
});
setShowModal(true);
};
const filtered = roles.filter(r =>
r.name.toLowerCase().includes(search.toLowerCase()) ||
r.description?.toLowerCase().includes(search.toLowerCase())
);
return ( return (
<div className="flex gap-6 p-6 w-full bg-gray-100"> <div className="flex gap-6 p-6 w-full bg-gray-100">
{/* LEFT INFO SIDEBAR */} {/* LEFT INFO SIDEBAR */}
<div className="w-72 bg-white rounded-xl shadow p-4"> <div className="w-72 bg-white rounded-xl shadow p-4">
<h3 className="text-xs font-semibold text-gray-500 mb-3">Role Information</h3> <h3 className="text-xs font-semibold text-gray-500 mb-3">Role Information</h3>
<p className="text-sm text-gray-700">Aquí se listan los roles disponibles en el sistema.</p> <p className="text-sm text-gray-700 mb-4">
Manage system roles and their permissions. Roles define what actions users can perform.
</p>
{activeRole && (
<div className="mt-6 pt-4 border-t">
<h4 className="text-xs font-semibold text-gray-500 mb-2">Selected Role</h4>
<div className="space-y-2">
<div>
<p className="text-xs text-gray-500">Name</p>
<p className="text-sm font-medium">{activeRole.name}</p>
</div>
<div>
<p className="text-xs text-gray-500">Description</p>
<p className="text-sm">{activeRole.description || "No description"}</p>
</div>
<div>
<p className="text-xs text-gray-500">Created</p>
<p className="text-sm">{new Date(activeRole.created_at).toLocaleDateString()}</p>
</div>
{activeRole.permissions && Object.keys(activeRole.permissions).length > 0 && (
<div>
<p className="text-xs text-gray-500">Permissions</p>
<p className="text-sm">{Object.keys(activeRole.permissions).length} permission groups</p>
</div>
)}
</div>
</div>
)}
</div> </div>
{/* MAIN */} {/* MAIN */}
@@ -67,52 +152,112 @@ export default function RolesPage() {
style={{ background: "linear-gradient(135deg, #4c5f9e, #2a355d, #566bb8)" }}> style={{ background: "linear-gradient(135deg, #4c5f9e, #2a355d, #566bb8)" }}>
<div> <div>
<h1 className="text-2xl font-bold">Role Management</h1> <h1 className="text-2xl font-bold">Role Management</h1>
<p className="text-sm text-blue-100">Roles registrados</p> <p className="text-sm text-blue-100">{roles.length} roles registered</p>
</div> </div>
<div className="flex gap-3"> <div className="flex gap-3">
<button onClick={() => { setForm(emptyRole); setEditingId(null); setShowModal(true); }} <button
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg"> onClick={() => { setForm(emptyForm); setEditingId(null); setShowModal(true); }}
disabled={loading}
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg hover:bg-gray-100 transition disabled:opacity-50"
>
<Plus size={16} /> Add <Plus size={16} /> Add
</button> </button>
<button onClick={() => { if (!activeRole) return; setEditingId(activeRole.id); setForm({...activeRole}); setShowModal(true); }} <button
disabled={!activeRole} onClick={openEditModal}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"> disabled={!activeRole || loading}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg hover:bg-white/10 transition disabled:opacity-50"
>
<Pencil size={16} /> Edit <Pencil size={16} /> Edit
</button> </button>
<button onClick={handleDelete} <button
disabled={!activeRole} onClick={() => setShowDeleteConfirm(true)}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"> disabled={!activeRole || loading}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg hover:bg-red-500/20 transition disabled:opacity-50"
>
<Trash2 size={16} /> Delete <Trash2 size={16} /> Delete
</button> </button>
<button onClick={() => setRoles([...roles])} <button
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg"> onClick={fetchRoles}
<RefreshCcw size={16} /> Refresh disabled={loading}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg hover:bg-white/10 transition disabled:opacity-50"
>
{loading ? <Loader2 size={16} className="animate-spin" /> : <RefreshCcw size={16} />}
Refresh
</button> </button>
</div> </div>
</div> </div>
{/* ERROR ALERT */}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center gap-3">
<AlertCircle className="text-red-600" size={20} />
<div>
<p className="text-sm font-medium text-red-800">Error</p>
<p className="text-sm text-red-600">{error}</p>
</div>
<button
onClick={() => setError(null)}
className="ml-auto text-red-600 hover:text-red-800"
>
×
</button>
</div>
)}
{/* SEARCH */} {/* SEARCH */}
<input className="bg-white rounded-lg shadow px-4 py-2 text-sm" <input
placeholder="Search role..." className="bg-white rounded-lg shadow px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="Search role by name or description..."
value={search} value={search}
onChange={e => setSearch(e.target.value)} /> onChange={e => setSearch(e.target.value)}
/>
{/* TABLE */} {/* TABLE */}
<div className="bg-white rounded-xl shadow">
{loading && roles.length === 0 ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="animate-spin text-blue-600" size={32} />
</div>
) : (
<MaterialTable <MaterialTable
title="Roles" title="Roles"
columns={[ columns={[
{ title: "Name", field: "name" },
{ title: "Description", field: "description" },
{ {
title: "Status", title: "Name",
field: "status", field: "name",
render: (rowData) => ( render: (rowData) => (
<span className={`px-3 py-1 rounded-full text-xs font-semibold border ${rowData.status === "ACTIVE" ? "text-blue-600 border-blue-600" : "text-red-600 border-red-600"}`}> <span className="font-medium text-gray-900">{rowData.name}</span>
{rowData.status}
</span>
) )
}, },
{ title: "Created", field: "createdAt", type: "date" } {
title: "Description",
field: "description",
render: (rowData) => (
<span className="text-gray-600">{rowData.description || "—"}</span>
)
},
{
title: "Permissions",
field: "permissions",
render: (rowData) => {
const count = rowData.permissions ? Object.keys(rowData.permissions).length : 0;
return (
<span className="text-sm text-gray-600">
{count > 0 ? `${count} groups` : "No permissions"}
</span>
);
}
},
{
title: "Created",
field: "created_at",
type: "date",
render: (rowData) => (
<span className="text-sm text-gray-600">
{new Date(rowData.created_at).toLocaleDateString()}
</span>
)
}
]} ]}
data={filtered} data={filtered}
onRowClick={(_, rowData) => setActiveRole(rowData as Role)} onRowClick={(_, rowData) => setActiveRole(rowData as Role)}
@@ -120,30 +265,100 @@ export default function RolesPage() {
actionsColumnIndex: -1, actionsColumnIndex: -1,
search: false, search: false,
paging: true, paging: true,
pageSize: 10,
pageSizeOptions: [10, 20, 50],
sorting: true, sorting: true,
rowStyle: (rowData) => ({ backgroundColor: activeRole?.id === (rowData as Role).id ? "#EEF2FF" : "#FFFFFF" }) rowStyle: (rowData) => ({
backgroundColor: activeRole?.id === (rowData as Role).id ? "#EEF2FF" : "#FFFFFF",
cursor: "pointer"
})
}} }}
/> />
)}
</div>
</div>
{/* ADD/EDIT MODAL */}
{showModal && (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
<div className="bg-white rounded-xl p-6 w-96 space-y-4 shadow-xl">
<h2 className="text-lg font-semibold text-gray-900">
{editingId ? "Edit Role" : "Add New Role"}
</h2>
<div className="space-y-3">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Name <span className="text-red-500">*</span>
</label>
<input
className="w-full border border-gray-300 px-3 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="e.g., ADMIN, USER, MANAGER"
value={form.name}
onChange={e => setForm({...form, name: e.target.value})}
disabled={loading}
/>
</div> </div>
{/* MODAL */} <div>
{showModal && ( <label className="block text-sm font-medium text-gray-700 mb-1">
<div className="fixed inset-0 bg-black/40 flex items-center justify-center"> Description
<div className="bg-white rounded-xl p-6 w-96 space-y-3"> </label>
<h2 className="text-lg font-semibold">{editingId ? "Edit Role" : "Add Role"}</h2> <textarea
<input className="w-full border px-3 py-2 rounded" placeholder="Name" value={form.name} onChange={e => setForm({...form, name: e.target.value})} /> className="w-full border border-gray-300 px-3 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
<input className="w-full border px-3 py-2 rounded" placeholder="Description" value={form.description} onChange={e => setForm({...form, description: e.target.value})} /> placeholder="Describe the role's purpose..."
<button onClick={() => setForm({...form, status: form.status === "ACTIVE" ? "INACTIVE" : "ACTIVE"})} className="w-full border rounded px-3 py-2"> rows={3}
Status: {form.status} value={form.description}
onChange={e => setForm({...form, description: e.target.value})}
disabled={loading}
/>
</div>
{/* Note about permissions */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
<p className="text-xs text-blue-800">
<strong>Note:</strong> Permissions can be configured after creating the role.
</p>
</div>
</div>
<div className="flex justify-end gap-2 pt-3 border-t">
<button
onClick={() => {
setShowModal(false);
setEditingId(null);
setForm(emptyForm);
setError(null);
}}
disabled={loading}
className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition disabled:opacity-50"
>
Cancel
</button>
<button
onClick={handleSave}
disabled={loading || !form.name.trim()}
className="bg-[#4c5f9e] text-white px-4 py-2 rounded-lg hover:bg-[#3d4c7d] transition disabled:opacity-50 flex items-center gap-2"
>
{loading && <Loader2 size={16} className="animate-spin" />}
{loading ? "Saving..." : "Save"}
</button> </button>
<input type="date" className="w-full border px-3 py-2 rounded" value={form.createdAt} onChange={e => setForm({...form, createdAt: e.target.value})} />
<div className="flex justify-end gap-2 pt-3">
<button onClick={() => setShowModal(false)}>Cancel</button>
<button onClick={handleSave} className="bg-[#4c5f9e] text-white px-4 py-2 rounded">Save</button>
</div> </div>
</div> </div>
</div> </div>
)} )}
{/* DELETE CONFIRMATION MODAL */}
<ConfirmModal
open={showDeleteConfirm}
onClose={() => setShowDeleteConfirm(false)}
onConfirm={handleDelete}
title="Delete Role"
message={`Are you sure you want to delete the role "${activeRole?.name}"? This action cannot be undone.`}
confirmText="Delete"
danger={true}
loading={loading}
/>
</div> </div>
); );
} }

View File

@@ -1,5 +1,5 @@
import { Response } from 'express'; import { Response } from 'express';
import { AuthenticatedRequest } from '../middleware/auth.middleware'; import { AuthenticatedRequest } from '../types';
import * as roleService from '../services/role.service'; import * as roleService from '../services/role.service';
import { CreateRoleInput, UpdateRoleInput } from '../validators/role.validator'; import { CreateRoleInput, UpdateRoleInput } from '../validators/role.validator';
@@ -37,9 +37,10 @@ export async function getRoleById(
res: Response res: Response
): Promise<void> { ): Promise<void> {
try { try {
const roleId = parseInt(req.params.id, 10); const roleId = req.params.id;
if (isNaN(roleId)) { const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex.test(roleId)) {
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: 'Invalid role ID', error: 'Invalid role ID',
@@ -120,9 +121,10 @@ export async function updateRole(
res: Response res: Response
): Promise<void> { ): Promise<void> {
try { try {
const roleId = parseInt(req.params.id, 10); const roleId = req.params.id;
if (isNaN(roleId)) { const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex.test(roleId)) {
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: 'Invalid role ID', error: 'Invalid role ID',
@@ -178,9 +180,10 @@ export async function deleteRole(
res: Response res: Response
): Promise<void> { ): Promise<void> {
try { try {
const roleId = parseInt(req.params.id, 10); const roleId = req.params.id;
if (isNaN(roleId)) { const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex.test(roleId)) {
res.status(400).json({ res.status(400).json({
success: false, success: false,
error: 'Invalid role ID', error: 'Invalid role ID',

View File

@@ -32,10 +32,10 @@ export async function getAll(): Promise<Role[]> {
/** /**
* Get a single role by ID with user count * Get a single role by ID with user count
* @param id - Role ID * @param id - Role ID (UUID)
* @returns Role with user count or null if not found * @returns Role with user count or null if not found
*/ */
export async function getById(id: number): Promise<RoleWithUserCount | null> { export async function getById(id: string): Promise<RoleWithUserCount | null> {
const result = await query( const result = await query(
` `
SELECT SELECT
@@ -123,12 +123,12 @@ export async function create(data: {
/** /**
* Update a role * Update a role
* @param id - Role ID * @param id - Role ID (UUID)
* @param data - Fields to update * @param data - Fields to update
* @returns Updated role or null if not found * @returns Updated role or null if not found
*/ */
export async function update( export async function update(
id: number, id: string,
data: { data: {
name?: string; name?: string;
description?: string | null; description?: string | null;
@@ -194,11 +194,11 @@ export async function update(
/** /**
* Delete a role (only if no users assigned) * Delete a role (only if no users assigned)
* @param id - Role ID * @param id - Role ID (UUID)
* @returns True if deleted, false if role not found * @returns True if deleted, false if role not found
* @throws Error if users are assigned to the role * @throws Error if users are assigned to the role
*/ */
export async function deleteRole(id: number): Promise<boolean> { export async function deleteRole(id: string): Promise<boolean> {
// Check if role exists and get user count // Check if role exists and get user count
const role = await getById(id); const role = await getById(id);