Compare commits
2 Commits
13cc4528ff
...
b5ea12dd27
| Author | SHA1 | Date | |
|---|---|---|---|
| b5ea12dd27 | |||
| 33b072436d |
@@ -204,24 +204,24 @@ export default function Home({
|
|||||||
{/* Título + Selector */}
|
{/* Título + Selector */}
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
{/* ✅ Título + logo a la derecha */}
|
{/* ✅ Título + logo a la derecha */}
|
||||||
<div className="relative flex items-start justify-between gap-6">
|
<div className="relative flex items-start justify-between gap-6">
|
||||||
<div className="relative z-10">
|
<div className="relative z-10">
|
||||||
<h1 className="text-3xl font-bold text-gray-800">
|
<h1 className="text-3xl font-bold text-gray-800">
|
||||||
Sistema de Tomas de Agua
|
Sistema de Tomas de Agua
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-gray-600 mt-2">
|
<p className="text-gray-600 mt-2">
|
||||||
Monitorea, administra y controla tus operaciones en un solo lugar.
|
Monitorea, administra y controla tus operaciones en un solo lugar.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ✅ Logo con z-index bajo para NO tapar menús */}
|
{/* ✅ Logo con z-index bajo para NO tapar menús */}
|
||||||
<img
|
<img
|
||||||
src={grhWatermark}
|
src={grhWatermark}
|
||||||
alt="Gestión de Recursos Hídricos"
|
alt="Gestión de Recursos Hídricos"
|
||||||
className="relative z-0 h-10 w-auto opacity-80 select-none pointer-events-none shrink-0"
|
className="relative z-0 h-16 w-auto opacity-80 select-none pointer-events-none shrink-0"
|
||||||
draggable={false}
|
draggable={false}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Cards de Secciones */}
|
{/* Cards de Secciones */}
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||||
@@ -238,9 +238,11 @@ export default function Home({
|
|||||||
<span className="font-semibold text-gray-700">Alertas</span>
|
<span className="font-semibold text-gray-700">Alertas</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white rounded-xl shadow p-6 flex flex-col items-center justify-center gap-2 hover:bg-yellow-50 transition">
|
<div className="cursor-pointer bg-white rounded-xl shadow p-6 flex flex-col items-center justify-center gap-2 hover:bg-yellow-50 transition"
|
||||||
|
onClick={() => setPage("projects")}
|
||||||
|
>
|
||||||
<Settings size={40} className="text-yellow-600" />
|
<Settings size={40} className="text-yellow-600" />
|
||||||
<span className="font-semibold text-gray-700">Mantenimiento</span>
|
<span className="font-semibold text-gray-700">Proyectos</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-white rounded-xl shadow p-6 flex flex-col items-center justify-center gap-2 hover:bg-green-50 transition">
|
<div className="bg-white rounded-xl shadow p-6 flex flex-col items-center justify-center gap-2 hover:bg-green-50 transition">
|
||||||
@@ -270,15 +272,15 @@ export default function Home({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{showOrganisms && (
|
{showOrganisms && (
|
||||||
<div className="fixed inset-0 z-30">
|
<div className="fixed inset-0 z-30">
|
||||||
{/* Overlay */}
|
{/* Overlay */}
|
||||||
<div
|
<div
|
||||||
className="absolute inset-0 bg-black/40"
|
className="absolute inset-0 bg-black/40"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setShowOrganisms(false);
|
setShowOrganisms(false);
|
||||||
setOrganismQuery("");
|
setOrganismQuery("");
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Panel */}
|
{/* Panel */}
|
||||||
<div className="absolute right-0 top-0 h-full w-full sm:w-[520px] bg-white shadow-2xl flex flex-col">
|
<div className="absolute right-0 top-0 h-full w-full sm:w-[520px] bg-white shadow-2xl flex flex-col">
|
||||||
|
|||||||
@@ -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(() => {
|
||||||
if (editingId) {
|
fetchRoles();
|
||||||
setRoles(prev => prev.map(r => r.id === editingId ? { id: editingId, ...form } : r));
|
}, []);
|
||||||
} else {
|
|
||||||
const newId = Date.now().toString();
|
const fetchRoles = async () => {
|
||||||
setRoles(prev => [...prev, { id: newId, ...form }]);
|
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);
|
||||||
}
|
}
|
||||||
setShowModal(false);
|
|
||||||
setEditingId(null);
|
|
||||||
setForm(emptyRole);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = () => {
|
const handleSave = async () => {
|
||||||
|
if (!form.name.trim()) {
|
||||||
|
setError("Role name is required");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
if (editingId) {
|
||||||
|
const updated = await updateRole(editingId, form);
|
||||||
|
setRoles(prev => prev.map(r => r.id === editingId ? updated : r));
|
||||||
|
} else {
|
||||||
|
const created = await createRole(form);
|
||||||
|
setRoles(prev => [...prev, created]);
|
||||||
|
}
|
||||||
|
setShowModal(false);
|
||||||
|
setEditingId(null);
|
||||||
|
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 = async () => {
|
||||||
if (!activeRole) return;
|
if (!activeRole) return;
|
||||||
setRoles(prev => prev.filter(r => r.id !== activeRole.id));
|
|
||||||
setActiveRole(null);
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await deleteRole(activeRole.id);
|
||||||
|
setRoles(prev => prev.filter(r => r.id !== activeRole.id));
|
||||||
|
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,83 +152,213 @@ 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"
|
||||||
value={search}
|
placeholder="Search role by name or description..."
|
||||||
onChange={e => setSearch(e.target.value)} />
|
value={search}
|
||||||
|
onChange={e => setSearch(e.target.value)}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* TABLE */}
|
{/* TABLE */}
|
||||||
<MaterialTable
|
<div className="bg-white rounded-xl shadow">
|
||||||
title="Roles"
|
{loading && roles.length === 0 ? (
|
||||||
columns={[
|
<div className="flex items-center justify-center py-12">
|
||||||
{ title: "Name", field: "name" },
|
<Loader2 className="animate-spin text-blue-600" size={32} />
|
||||||
{ title: "Description", field: "description" },
|
</div>
|
||||||
{
|
) : (
|
||||||
title: "Status",
|
<MaterialTable
|
||||||
field: "status",
|
title="Roles"
|
||||||
render: (rowData) => (
|
columns={[
|
||||||
<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"}`}>
|
{
|
||||||
{rowData.status}
|
title: "Name",
|
||||||
</span>
|
field: "name",
|
||||||
)
|
render: (rowData) => (
|
||||||
},
|
<span className="font-medium text-gray-900">{rowData.name}</span>
|
||||||
{ title: "Created", field: "createdAt", type: "date" }
|
)
|
||||||
]}
|
},
|
||||||
data={filtered}
|
{
|
||||||
onRowClick={(_, rowData) => setActiveRole(rowData as Role)}
|
title: "Description",
|
||||||
options={{
|
field: "description",
|
||||||
actionsColumnIndex: -1,
|
render: (rowData) => (
|
||||||
search: false,
|
<span className="text-gray-600">{rowData.description || "—"}</span>
|
||||||
paging: true,
|
)
|
||||||
sorting: true,
|
},
|
||||||
rowStyle: (rowData) => ({ backgroundColor: activeRole?.id === (rowData as Role).id ? "#EEF2FF" : "#FFFFFF" })
|
{
|
||||||
}}
|
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}
|
||||||
|
onRowClick={(_, rowData) => setActiveRole(rowData as Role)}
|
||||||
|
options={{
|
||||||
|
actionsColumnIndex: -1,
|
||||||
|
search: false,
|
||||||
|
paging: true,
|
||||||
|
pageSize: 10,
|
||||||
|
pageSizeOptions: [10, 20, 50],
|
||||||
|
sorting: true,
|
||||||
|
rowStyle: (rowData) => ({
|
||||||
|
backgroundColor: activeRole?.id === (rowData as Role).id ? "#EEF2FF" : "#FFFFFF",
|
||||||
|
cursor: "pointer"
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* MODAL */}
|
{/* ADD/EDIT MODAL */}
|
||||||
{showModal && (
|
{showModal && (
|
||||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center">
|
<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-3">
|
<div className="bg-white rounded-xl p-6 w-96 space-y-4 shadow-xl">
|
||||||
<h2 className="text-lg font-semibold">{editingId ? "Edit Role" : "Add Role"}</h2>
|
<h2 className="text-lg font-semibold text-gray-900">
|
||||||
<input className="w-full border px-3 py-2 rounded" placeholder="Name" value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
|
{editingId ? "Edit Role" : "Add New Role"}
|
||||||
<input className="w-full border px-3 py-2 rounded" placeholder="Description" value={form.description} onChange={e => setForm({...form, description: e.target.value})} />
|
</h2>
|
||||||
<button onClick={() => setForm({...form, status: form.status === "ACTIVE" ? "INACTIVE" : "ACTIVE"})} className="w-full border rounded px-3 py-2">
|
|
||||||
Status: {form.status}
|
<div className="space-y-3">
|
||||||
</button>
|
<div>
|
||||||
<input type="date" className="w-full border px-3 py-2 rounded" value={form.createdAt} onChange={e => setForm({...form, createdAt: e.target.value})} />
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
<div className="flex justify-end gap-2 pt-3">
|
Name <span className="text-red-500">*</span>
|
||||||
<button onClick={() => setShowModal(false)}>Cancel</button>
|
</label>
|
||||||
<button onClick={handleSave} className="bg-[#4c5f9e] text-white px-4 py-2 rounded">Save</button>
|
<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>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Description
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
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"
|
||||||
|
placeholder="Describe the role's purpose..."
|
||||||
|
rows={3}
|
||||||
|
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>
|
||||||
</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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -100,6 +100,29 @@ export default function ConsumptionPage() {
|
|||||||
);
|
);
|
||||||
}, [readings, search]);
|
}, [readings, search]);
|
||||||
|
|
||||||
|
const currentMonthAverage = useMemo(() => {
|
||||||
|
const now = new Date();
|
||||||
|
const currentYear = now.getFullYear();
|
||||||
|
const currentMonth = now.getMonth();
|
||||||
|
|
||||||
|
const currentMonthReadings = readings.filter((r) => {
|
||||||
|
if (!r.receivedAt) return false;
|
||||||
|
const readingDate = new Date(r.receivedAt);
|
||||||
|
return (
|
||||||
|
readingDate.getFullYear() === currentYear &&
|
||||||
|
readingDate.getMonth() === currentMonth
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (currentMonthReadings.length === 0) return 0;
|
||||||
|
|
||||||
|
const sum = currentMonthReadings.reduce(
|
||||||
|
(acc, r) => acc + Number(r.readingValue),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
return sum / currentMonthReadings.length;
|
||||||
|
}, [readings]);
|
||||||
|
|
||||||
const formatDate = (dateStr: string | null): string => {
|
const formatDate = (dateStr: string | null): string => {
|
||||||
if (!dateStr) return "—";
|
if (!dateStr) return "—";
|
||||||
const date = new Date(dateStr);
|
const date = new Date(dateStr);
|
||||||
@@ -182,7 +205,7 @@ export default function ConsumptionPage() {
|
|||||||
<button
|
<button
|
||||||
onClick={exportToCSV}
|
onClick={exportToCSV}
|
||||||
disabled={filteredReadings.length === 0}
|
disabled={filteredReadings.length === 0}
|
||||||
className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-indigo-600 rounded-xl hover:from-blue-700 hover:to-indigo-700 transition-all shadow-sm shadow-blue-500/25 disabled:opacity-50 disabled:cursor-not-allowed"
|
className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-linear-to-r from-blue-600 to-indigo-600 rounded-xl hover:from-blue-700 hover:to-indigo-700 transition-all shadow-sm shadow-blue-500/25 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
<Download size={16} />
|
<Download size={16} />
|
||||||
Exportar
|
Exportar
|
||||||
@@ -214,6 +237,13 @@ export default function ConsumptionPage() {
|
|||||||
loading={loadingSummary}
|
loading={loadingSummary}
|
||||||
gradient="from-violet-500 to-purple-600"
|
gradient="from-violet-500 to-purple-600"
|
||||||
/>
|
/>
|
||||||
|
<StatCard
|
||||||
|
icon={<Droplets />}
|
||||||
|
label="Consumo Acumulado"
|
||||||
|
value={`${currentMonthAverage.toFixed(1)} m³`}
|
||||||
|
loading={loadingReadings}
|
||||||
|
gradient="from-red-500 to-red-600"
|
||||||
|
/>
|
||||||
<StatCard
|
<StatCard
|
||||||
icon={<Clock />}
|
icon={<Clock />}
|
||||||
label="Última Lectura"
|
label="Última Lectura"
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ export default function MetersPage({
|
|||||||
|
|
||||||
// UI state
|
// UI state
|
||||||
const [takeType, setTakeType] = useState<TakeType>("GENERAL");
|
const [takeType, setTakeType] = useState<TakeType>("GENERAL");
|
||||||
const isMockMode = takeType !== "GENERAL";
|
|
||||||
|
|
||||||
const [activeMeter, setActiveMeter] = useState<Meter | null>(null);
|
const [activeMeter, setActiveMeter] = useState<Meter | null>(null);
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
@@ -85,15 +84,19 @@ export default function MetersPage({
|
|||||||
}));
|
}));
|
||||||
}, [m.allProjects, m.projectsCounts]);
|
}, [m.allProjects, m.projectsCounts]);
|
||||||
|
|
||||||
const sidebarProjects = isMockMode ? [] : projectsDataReal;
|
const sidebarProjects = projectsDataReal;
|
||||||
|
|
||||||
// Search filtered meters
|
|
||||||
const searchFiltered = useMemo(() => {
|
const searchFiltered = useMemo(() => {
|
||||||
if (isMockMode) return [];
|
let filtered = m.filteredMeters;
|
||||||
const q = search.trim().toLowerCase();
|
|
||||||
if (!q) return m.filteredMeters;
|
|
||||||
|
|
||||||
return m.filteredMeters.filter((x) => {
|
if (takeType !== "GENERAL") {
|
||||||
|
filtered = filtered.filter((meter) => meter.type === takeType);
|
||||||
|
}
|
||||||
|
|
||||||
|
const q = search.trim().toLowerCase();
|
||||||
|
if (!q) return filtered;
|
||||||
|
|
||||||
|
return filtered.filter((x) => {
|
||||||
return (
|
return (
|
||||||
(x.name ?? "").toLowerCase().includes(q) ||
|
(x.name ?? "").toLowerCase().includes(q) ||
|
||||||
(x.serialNumber ?? "").toLowerCase().includes(q) ||
|
(x.serialNumber ?? "").toLowerCase().includes(q) ||
|
||||||
@@ -101,7 +104,7 @@ export default function MetersPage({
|
|||||||
(x.concentratorName ?? "").toLowerCase().includes(q)
|
(x.concentratorName ?? "").toLowerCase().includes(q)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}, [isMockMode, search, m.filteredMeters]);
|
}, [takeType, search, m.filteredMeters]);
|
||||||
|
|
||||||
// Validation
|
// Validation
|
||||||
const validateForm = (): boolean => {
|
const validateForm = (): boolean => {
|
||||||
@@ -117,7 +120,6 @@ export default function MetersPage({
|
|||||||
|
|
||||||
// CRUD handlers
|
// CRUD handlers
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
if (isMockMode) return;
|
|
||||||
if (!validateForm()) return;
|
if (!validateForm()) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -143,7 +145,6 @@ export default function MetersPage({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async () => {
|
const handleDelete = async () => {
|
||||||
if (isMockMode) return;
|
|
||||||
if (!activeMeter) return;
|
if (!activeMeter) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -169,7 +170,7 @@ export default function MetersPage({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const openEditModal = () => {
|
const openEditModal = () => {
|
||||||
if (isMockMode || !activeMeter) return;
|
if (!activeMeter) return;
|
||||||
|
|
||||||
setEditingId(activeMeter.id);
|
setEditingId(activeMeter.id);
|
||||||
setForm({
|
setForm({
|
||||||
@@ -187,8 +188,6 @@ export default function MetersPage({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const openCreateModal = () => {
|
const openCreateModal = () => {
|
||||||
if (isMockMode) return;
|
|
||||||
|
|
||||||
setForm(emptyForm);
|
setForm(emptyForm);
|
||||||
setErrors({});
|
setErrors({});
|
||||||
setEditingId(null);
|
setEditingId(null);
|
||||||
@@ -204,7 +203,7 @@ export default function MetersPage({
|
|||||||
setTakeType={setTakeType}
|
setTakeType={setTakeType}
|
||||||
selectedProject={m.selectedProject}
|
selectedProject={m.selectedProject}
|
||||||
setSelectedProject={m.setSelectedProject}
|
setSelectedProject={m.setSelectedProject}
|
||||||
isMockMode={isMockMode}
|
isMockMode={false}
|
||||||
projects={sidebarProjects}
|
projects={sidebarProjects}
|
||||||
onRefresh={handleRefresh}
|
onRefresh={handleRefresh}
|
||||||
refreshDisabled={false}
|
refreshDisabled={false}
|
||||||
@@ -221,10 +220,8 @@ export default function MetersPage({
|
|||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold">Meter Management</h1>
|
<h1 className="text-2xl font-bold">Meter Management</h1>
|
||||||
<p className="text-sm text-blue-100">
|
<p className="text-sm text-blue-100">
|
||||||
{isMockMode
|
{m.selectedProject
|
||||||
? `Modo demo (${takeType}) - backend pendiente`
|
? `Proyecto: ${m.selectedProject}${takeType !== "GENERAL" ? ` • Tipo: ${takeType}` : ""}`
|
||||||
: m.selectedProject
|
|
||||||
? `Proyecto: ${m.selectedProject}`
|
|
||||||
: "Selecciona un proyecto desde el panel izquierdo"}
|
: "Selecciona un proyecto desde el panel izquierdo"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -232,15 +229,14 @@ export default function MetersPage({
|
|||||||
<div className="flex gap-3">
|
<div className="flex gap-3">
|
||||||
<button
|
<button
|
||||||
onClick={openCreateModal}
|
onClick={openCreateModal}
|
||||||
disabled={isMockMode || m.allProjects.length === 0}
|
disabled={m.allProjects.length === 0}
|
||||||
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
|
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
|
||||||
>
|
>
|
||||||
<Plus size={16} /> Agregar
|
<Plus size={16} /> Agregar
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowBulkUpload(true)}
|
onClick={() => setShowBulkUpload(true)}
|
||||||
disabled={isMockMode}
|
|
||||||
className="flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-green-600"
|
className="flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-green-600"
|
||||||
>
|
>
|
||||||
<Upload size={16} /> Carga Masiva
|
<Upload size={16} /> Carga Masiva
|
||||||
@@ -248,19 +244,16 @@ export default function MetersPage({
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={openEditModal}
|
onClick={openEditModal}
|
||||||
disabled={isMockMode || !activeMeter}
|
disabled={!activeMeter}
|
||||||
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"
|
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60 hover:bg-white/10"
|
||||||
>
|
>
|
||||||
<Pencil size={16} /> Editar
|
<Pencil size={16} /> Editar
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => setConfirmOpen(true)}
|
||||||
if (isMockMode) return;
|
disabled={!activeMeter}
|
||||||
setConfirmOpen(true);
|
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60 hover:bg-red-500/20"
|
||||||
}}
|
|
||||||
disabled={isMockMode || !activeMeter}
|
|
||||||
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"
|
|
||||||
>
|
>
|
||||||
<Trash2 size={16} /> Eliminar
|
<Trash2 size={16} /> Eliminar
|
||||||
</button>
|
</button>
|
||||||
@@ -275,20 +268,21 @@ export default function MetersPage({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<input
|
<input
|
||||||
className="bg-white rounded-lg shadow px-4 py-2 text-sm"
|
className="bg-white rounded-lg shadow px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
placeholder="Buscar por nombre, serial, ubicación o concentrador..."
|
placeholder="Buscar por nombre, serial, ubicación o concentrador..."
|
||||||
value={search}
|
value={search}
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
disabled={isMockMode || !m.selectedProject}
|
disabled={!m.selectedProject}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<MetersTable
|
<MetersTable
|
||||||
data={searchFiltered}
|
data={searchFiltered}
|
||||||
isLoading={m.loadingMeters}
|
isLoading={m.loadingMeters}
|
||||||
isMockMode={isMockMode}
|
isMockMode={false}
|
||||||
selectedProject={m.selectedProject}
|
selectedProject={m.selectedProject}
|
||||||
activeMeter={activeMeter}
|
activeMeter={activeMeter}
|
||||||
onRowClick={(row) => setActiveMeter(row)}
|
onRowClick={(row) => setActiveMeter(row)}
|
||||||
|
takeType={takeType}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ConfirmModal
|
<ConfirmModal
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ export default function MetersSidebar({
|
|||||||
{" • "}
|
{" • "}
|
||||||
Seleccionado:{" "}
|
Seleccionado:{" "}
|
||||||
<span className="font-semibold">
|
<span className="font-semibold">
|
||||||
{selectedProject || (isMockMode ? "— (modo demo)" : "—")}
|
{selectedProject || "—"}
|
||||||
</span>
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -128,15 +128,10 @@ export default function MetersSidebar({
|
|||||||
setTakeType(opt.key);
|
setTakeType(opt.key);
|
||||||
setTypesMenuOpen(false);
|
setTypesMenuOpen(false);
|
||||||
|
|
||||||
// Reset selection/search desde el parent
|
|
||||||
onResetSelection?.();
|
onResetSelection?.();
|
||||||
|
|
||||||
if (opt.key !== "GENERAL") {
|
if (!selectedProject && allProjects.length > 0) {
|
||||||
// mock mode -> limpia selección real
|
setSelectedProject(allProjects[0]);
|
||||||
setSelectedProject("");
|
|
||||||
} else {
|
|
||||||
// vuelve a GENERAL -> autoselecciona real si no hay
|
|
||||||
setSelectedProject((prev) => prev || allProjects[0] || "");
|
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className={[
|
className={[
|
||||||
@@ -163,12 +158,10 @@ export default function MetersSidebar({
|
|||||||
{/* List */}
|
{/* List */}
|
||||||
<div className="mt-4 overflow-y-auto flex-1 space-y-3 pr-1">
|
<div className="mt-4 overflow-y-auto flex-1 space-y-3 pr-1">
|
||||||
{loadingProjects ? (
|
{loadingProjects ? (
|
||||||
<div className="text-sm text-gray-500">Loading projects...</div>
|
<div className="text-sm text-gray-500">Cargando proyectos...</div>
|
||||||
) : projects.length === 0 ? (
|
) : projects.length === 0 ? (
|
||||||
<div className="text-sm text-gray-500 text-center py-10">
|
<div className="text-sm text-gray-500 text-center py-10">
|
||||||
{isMockMode
|
No se encontraron proyectos.
|
||||||
? "No hay datos demo para este tipo."
|
|
||||||
: "No se encontraron proyectos."}
|
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
projects.map((p) => {
|
projects.map((p) => {
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import MaterialTable from "@material-table/core";
|
import MaterialTable from "@material-table/core";
|
||||||
import type { Meter } from "../../api/meters";
|
import type { Meter } from "../../api/meters";
|
||||||
|
import type { TakeType } from "./MeterPage";
|
||||||
|
|
||||||
type Props = {
|
export type MetersTableProps = {
|
||||||
data: Meter[];
|
data: Meter[];
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
|
||||||
isMockMode: boolean;
|
isMockMode: boolean;
|
||||||
selectedProject: string;
|
selectedProject: string;
|
||||||
|
takeType: TakeType;
|
||||||
activeMeter: Meter | null;
|
activeMeter: Meter | null;
|
||||||
onRowClick: (row: Meter) => void;
|
onRowClick: (row: Meter) => void;
|
||||||
};
|
};
|
||||||
@@ -17,10 +17,18 @@ export default function MetersTable({
|
|||||||
isLoading,
|
isLoading,
|
||||||
isMockMode,
|
isMockMode,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
|
takeType,
|
||||||
activeMeter,
|
activeMeter,
|
||||||
onRowClick,
|
onRowClick,
|
||||||
}: Props) {
|
}: MetersTableProps) {
|
||||||
const disabled = isMockMode || !selectedProject;
|
const disabled = isMockMode || !selectedProject;
|
||||||
|
|
||||||
|
const typeLabels: Record<TakeType, string> = {
|
||||||
|
GENERAL: "todos los tipos",
|
||||||
|
LORA: "LoRa",
|
||||||
|
LORAWAN: "LoRaWAN",
|
||||||
|
GRANDES: "Grandes consumidores",
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={disabled ? "opacity-60 pointer-events-none" : ""}>
|
<div className={disabled ? "opacity-60 pointer-events-none" : ""}>
|
||||||
@@ -80,7 +88,17 @@ export default function MetersTable({
|
|||||||
actionsColumnIndex: -1,
|
actionsColumnIndex: -1,
|
||||||
search: false,
|
search: false,
|
||||||
paging: true,
|
paging: true,
|
||||||
|
pageSize: 10,
|
||||||
|
pageSizeOptions: [10, 20, 50],
|
||||||
sorting: true,
|
sorting: true,
|
||||||
|
maxBodyHeight: "calc(100vh - 400px)",
|
||||||
|
headerStyle: {
|
||||||
|
position: "sticky",
|
||||||
|
top: 0,
|
||||||
|
backgroundColor: "#fff",
|
||||||
|
zIndex: 10,
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
rowStyle: (rowData) => ({
|
rowStyle: (rowData) => ({
|
||||||
backgroundColor:
|
backgroundColor:
|
||||||
activeMeter?.id === (rowData as Meter).id ? "#EEF2FF" : "#FFFFFF",
|
activeMeter?.id === (rowData as Meter).id ? "#EEF2FF" : "#FFFFFF",
|
||||||
@@ -91,10 +109,12 @@ export default function MetersTable({
|
|||||||
emptyDataSourceMessage: isMockMode
|
emptyDataSourceMessage: isMockMode
|
||||||
? "Modo demo: selecciona 'General' para ver datos reales."
|
? "Modo demo: selecciona 'General' para ver datos reales."
|
||||||
: !selectedProject
|
: !selectedProject
|
||||||
? "Select a project to view meters."
|
? "Selecciona un proyecto para ver medidores."
|
||||||
: isLoading
|
: isLoading
|
||||||
? "Loading meters..."
|
? "Cargando medidores..."
|
||||||
: "No meters found. Click 'Add' to create your first meter.",
|
: takeType !== "GENERAL"
|
||||||
|
? `No se encontraron medidores de tipo ${typeLabels[takeType]} en este proyecto.`
|
||||||
|
: "No se encontraron medidores. Haz clic en 'Agregar' para crear tu primer medidor.",
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -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',
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user