Migrar backend a PostgreSQL + Node.js/Express con nuevas funcionalidades

Backend (water-api/):
- Crear API REST completa con Express + TypeScript
- Implementar autenticación JWT con refresh tokens
- CRUD completo para: projects, concentrators, meters, gateways, devices, users, roles
- Agregar validación con Zod para todas las entidades
- Implementar webhooks para The Things Stack (LoRaWAN)
- Agregar endpoint de lecturas con filtros y resumen de consumo
- Implementar carga masiva de medidores via Excel (.xlsx)

Frontend:
- Crear cliente HTTP con manejo automático de JWT y refresh
- Actualizar todas las APIs para usar nuevo backend
- Agregar sistema de autenticación real (login, logout, me)
- Agregar selector de tipo (LORA, LoRaWAN, Grandes) en concentradores y medidores
- Agregar campo Meter ID en medidores
- Crear modal de carga masiva para medidores
- Agregar página de consumo con gráficas y filtros
- Corregir carga de proyectos independiente de datos existentes

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Exteban08
2026-01-23 10:13:26 +00:00
parent 2b5735d78d
commit c81a18987f
92 changed files with 14088 additions and 1866 deletions

View File

@@ -117,7 +117,7 @@ export default function Home({
);
const filteredProjects = useMemo(
() => [...new Set(filteredMeters.map((m) => m.areaName))],
() => [...new Set(filteredMeters.map((m) => m.projectName))].filter(Boolean) as string[],
[filteredMeters]
);
@@ -125,7 +125,7 @@ export default function Home({
() =>
filteredProjects.map((projectName) => ({
name: projectName,
meterCount: filteredMeters.filter((m) => m.areaName === projectName)
meterCount: filteredMeters.filter((m) => m.projectName === projectName)
.length,
})),
[filteredProjects, filteredMeters]

View File

@@ -1,27 +1,26 @@
import { useMemo, useState } from "react";
import { Lock, User, Eye, EyeOff, Loader2, Check } from "lucide-react";
import { Lock, Mail, Eye, EyeOff, Loader2 } from "lucide-react";
import grhWatermark from "../assets/images/grhWatermark.png";
import { login } from "../api/auth";
type Form = { usuario: string; contrasena: string };
type Form = { email: string; password: string };
type LoginPageProps = {
onSuccess: (payload?: { token?: string }) => void;
onSuccess: () => void;
};
export default function LoginPage({ onSuccess }: LoginPageProps) {
const [form, setForm] = useState<Form>({ usuario: "", contrasena: "" });
const [form, setForm] = useState<Form>({ email: "", password: "" });
const [showPass, setShowPass] = useState(false);
const [loading, setLoading] = useState(false);
const [serverError, setServerError] = useState("");
const [notRobot, setNotRobot] = useState(false);
const errors = useMemo(() => {
const e: Partial<Record<keyof Form | "robot", string>> = {};
if (!form.usuario.trim()) e.usuario = "El usuario es obligatorio.";
if (!form.contrasena) e.contrasena = "La contraseña es obligatoria.";
if (!notRobot) e.robot = "Confirma que no eres un robot.";
const e: Partial<Record<keyof Form, string>> = {};
if (!form.email.trim()) e.email = "El correo es obligatorio.";
if (!form.password) e.password = "La contraseña es obligatoria.";
return e;
}, [form.usuario, form.contrasena, notRobot]);
}, [form.email, form.password]);
const canSubmit = Object.keys(errors).length === 0 && !loading;
@@ -30,12 +29,13 @@ export default function LoginPage({ onSuccess }: LoginPageProps) {
setServerError("");
if (!canSubmit) return;
setLoading(true);
try {
setLoading(true);
await new Promise((r) => setTimeout(r, 700));
onSuccess({ token: "demo" });
} catch {
setServerError("No se pudo iniciar sesión. Verifica tus datos.");
await login({ email: form.email, password: form.password });
// Tokens are stored by the auth module
onSuccess();
} catch (err) {
setServerError(err instanceof Error ? err.message : "Error de autenticación");
} finally {
setLoading(false);
}
@@ -111,27 +111,28 @@ export default function LoginPage({ onSuccess }: LoginPageProps) {
</div>
)}
{/* Usuario */}
{/* Email */}
<div>
<label className="block text-sm font-medium text-slate-700">
Usuario
Correo electrónico
</label>
<div className="relative mt-2">
<input
value={form.usuario}
type="email"
value={form.email}
onChange={(e) =>
setForm((s) => ({ ...s, usuario: e.target.value }))
setForm((s) => ({ ...s, email: e.target.value }))
}
className="w-full border-b border-slate-300 py-2 pr-10 outline-none focus:border-slate-600"
/>
<User
<Mail
className="absolute right-1 top-1/2 -translate-y-1/2 text-slate-500"
size={18}
/>
</div>
{errors.usuario && (
{errors.email && (
<p className="mt-1 text-xs text-red-600">
{errors.usuario}
{errors.email}
</p>
)}
</div>
@@ -143,9 +144,9 @@ export default function LoginPage({ onSuccess }: LoginPageProps) {
</label>
<div className="relative mt-2">
<input
value={form.contrasena}
value={form.password}
onChange={(e) =>
setForm((s) => ({ ...s, contrasena: e.target.value }))
setForm((s) => ({ ...s, password: e.target.value }))
}
type={showPass ? "text" : "password"}
className="w-full border-b border-slate-300 py-2 pr-16 outline-none focus:border-slate-600"
@@ -162,36 +163,13 @@ export default function LoginPage({ onSuccess }: LoginPageProps) {
size={18}
/>
</div>
{errors.contrasena && (
{errors.password && (
<p className="mt-1 text-xs text-red-600">
{errors.contrasena}
{errors.password}
</p>
)}
</div>
{/* NO SOY UN ROBOT */}
<div className="flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
<button
type="button"
onClick={() => setNotRobot((v) => !v)}
className={`h-5 w-5 rounded border flex items-center justify-center ${
notRobot
? "bg-blue-600 border-blue-600 text-white"
: "bg-white border-slate-300"
}`}
>
{notRobot && <Check size={14} />}
</button>
<span className="text-sm text-slate-700">No soy un robot</span>
<span className="ml-auto text-xs text-slate-400">
reCAPTCHA
</span>
</div>
{errors.robot && (
<p className="text-xs text-red-600">{errors.robot}</p>
)}
{/* Botón */}
<button
type="submit"

View File

@@ -1,381 +1,191 @@
// src/pages/concentrators/ConcentratorsModal.tsx
import type React from "react";
import type { Concentrator } from "../../api/concentrators";
import type { GatewayData } from "./ConcentratorsPage";
import { useEffect, useState } from "react";
import type { ConcentratorInput } from "../../api/concentrators";
import { fetchProjects, type Project } from "../../api/projects";
type Props = {
editingSerial: string | null;
form: Omit<Concentrator, "id">;
setForm: React.Dispatch<React.SetStateAction<Omit<Concentrator, "id">>>;
gatewayForm: GatewayData;
setGatewayForm: React.Dispatch<React.SetStateAction<GatewayData>>;
editingId: string | null;
form: ConcentratorInput;
setForm: React.Dispatch<React.SetStateAction<ConcentratorInput>>;
errors: Record<string, boolean>;
setErrors: React.Dispatch<React.SetStateAction<Record<string, boolean>>>;
toDatetimeLocalValue: (value?: string) => string;
fromDatetimeLocalValue: (value: string) => string;
allProjects: string[];
onClose: () => void;
onSave: () => void | Promise<void>;
};
export default function ConcentratorsModal({
editingSerial,
editingId,
form,
setForm,
gatewayForm,
setGatewayForm,
errors,
setErrors,
toDatetimeLocalValue,
fromDatetimeLocalValue,
onClose,
onSave,
}: Props) {
const title = editingSerial ? "Edit Concentrator" : "Add Concentrator";
const title = editingId ? "Editar Concentrador" : "Agregar Concentrador";
const [projects, setProjects] = useState<Project[]>([]);
const [loadingProjects, setLoadingProjects] = useState(true);
useEffect(() => {
const load = async () => {
try {
const data = await fetchProjects();
setProjects(data);
} catch (error) {
console.error("Error loading projects:", error);
} finally {
setLoadingProjects(false);
}
};
load();
}, []);
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
<div className="bg-white rounded-xl p-6 w-[700px] max-h-[90vh] overflow-y-auto space-y-4">
<div className="bg-white rounded-xl p-6 w-[500px] max-h-[90vh] overflow-y-auto space-y-4">
<h2 className="text-lg font-semibold">{title}</h2>
{/* FORM */}
<div className="space-y-3">
<h3 className="text-sm font-semibold text-gray-700 border-b pb-2">
Concentrator Information
Información del Concentrador
</h3>
<div className="grid grid-cols-2 gap-3">
<div>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-gray-50"
placeholder="Area Name"
value={form["Area Name"] ?? ""}
disabled
/>
<p className="text-xs text-gray-400 mt-1">
El proyecto seleccionado define el Area Name.
</p>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Serial *</label>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Device S/N"] ? "border-red-500" : ""
errors["serialNumber"] ? "border-red-500" : ""
}`}
placeholder="Device S/N *"
value={form["Device S/N"]}
placeholder="Número de serie"
value={form.serialNumber}
onChange={(e) => {
setForm({ ...form, "Device S/N": e.target.value });
if (errors["Device S/N"])
setErrors({ ...errors, "Device S/N": false });
setForm({ ...form, serialNumber: e.target.value });
if (errors["serialNumber"]) setErrors({ ...errors, serialNumber: false });
}}
required
/>
{errors["Device S/N"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Device Name"] ? "border-red-500" : ""
}`}
placeholder="Device Name *"
value={form["Device Name"]}
onChange={(e) => {
setForm({ ...form, "Device Name": e.target.value });
if (errors["Device Name"])
setErrors({ ...errors, "Device Name": false });
}}
required
/>
{errors["Device Name"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
{errors["serialNumber"] && (
<p className="text-red-500 text-xs mt-1">Campo requerido</p>
)}
</div>
<div>
<select
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
value={form["Device Status"]}
onChange={(e) =>
setForm({
...form,
"Device Status": e.target.value as any,
})
}
>
<option value="ACTIVE">ACTIVE</option>
<option value="INACTIVE">INACTIVE</option>
</select>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm text-gray-600 mb-1">Nombre *</label>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Operator"] ? "border-red-500" : ""
errors["name"] ? "border-red-500" : ""
}`}
placeholder="Operator *"
value={form["Operator"]}
placeholder="Nombre del concentrador"
value={form.name}
onChange={(e) => {
setForm({ ...form, Operator: e.target.value });
if (errors["Operator"])
setErrors({ ...errors, Operator: false });
setForm({ ...form, name: e.target.value });
if (errors["name"]) setErrors({ ...errors, name: false });
}}
required
/>
{errors["Operator"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
</div>
<div>
<input
type="date"
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Installed Time"] ? "border-red-500" : ""
}`}
value={(form["Installed Time"] ?? "").slice(0, 10)}
onChange={(e) => {
setForm({ ...form, "Installed Time": e.target.value });
if (errors["Installed Time"])
setErrors({ ...errors, "Installed Time": false });
}}
required
/>
{errors["Installed Time"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<input
type="datetime-local"
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Device Time"] ? "border-red-500" : ""
}`}
value={toDatetimeLocalValue(form["Device Time"])}
onChange={(e) => {
setForm({
...form,
"Device Time": fromDatetimeLocalValue(e.target.value),
});
if (errors["Device Time"])
setErrors({ ...errors, "Device Time": false });
}}
required
/>
{errors["Device Time"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
</div>
<div>
<input
type="datetime-local"
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Communication Time"] ? "border-red-500" : ""
}`}
value={toDatetimeLocalValue(form["Communication Time"])}
onChange={(e) => {
setForm({
...form,
"Communication Time": fromDatetimeLocalValue(e.target.value),
});
if (errors["Communication Time"])
setErrors({ ...errors, "Communication Time": false });
}}
required
/>
{errors["Communication Time"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
{errors["name"] && <p className="text-red-500 text-xs mt-1">Campo requerido</p>}
</div>
</div>
<div>
<input
<label className="block text-sm text-gray-600 mb-1">Proyecto *</label>
<select
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Instruction Manual"] ? "border-red-500" : ""
errors["projectId"] ? "border-red-500" : ""
}`}
placeholder="Instruction Manual *"
value={form["Instruction Manual"]}
value={form.projectId}
onChange={(e) => {
setForm({ ...form, "Instruction Manual": e.target.value });
if (errors["Instruction Manual"])
setErrors({ ...errors, "Instruction Manual": false });
setForm({ ...form, projectId: e.target.value });
if (errors["projectId"]) setErrors({ ...errors, projectId: false });
}}
disabled={loadingProjects}
required
/>
{errors["Instruction Manual"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
>
<option value="">
{loadingProjects ? "Cargando..." : "Selecciona un proyecto"}
</option>
{projects.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
{errors["projectId"] && (
<p className="text-red-500 text-xs mt-1">Selecciona un proyecto</p>
)}
</div>
</div>
{/* GATEWAY */}
<div className="space-y-3 pt-4">
<h3 className="text-sm font-semibold text-gray-700 border-b pb-2">
Gateway Configuration
</h3>
<div className="grid grid-cols-2 gap-3">
<div>
<input
type="number"
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Gateway ID"] ? "border-red-500" : ""
}`}
placeholder="Gateway ID *"
value={gatewayForm["Gateway ID"] || ""}
onChange={(e) => {
setGatewayForm({
...gatewayForm,
"Gateway ID": parseInt(e.target.value) || 0,
});
if (errors["Gateway ID"])
setErrors({ ...errors, "Gateway ID": false });
}}
required
min={1}
/>
{errors["Gateway ID"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
</div>
<div>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Gateway EUI"] ? "border-red-500" : ""
}`}
placeholder="Gateway EUI *"
value={gatewayForm["Gateway EUI"]}
onChange={(e) => {
setGatewayForm({
...gatewayForm,
"Gateway EUI": e.target.value,
});
if (errors["Gateway EUI"])
setErrors({ ...errors, "Gateway EUI": false });
}}
required
/>
{errors["Gateway EUI"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Ubicación</label>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Ubicación del concentrador (opcional)"
value={form.location ?? ""}
onChange={(e) => setForm({ ...form, location: e.target.value || undefined })}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Gateway Name"] ? "border-red-500" : ""
}`}
placeholder="Gateway Name *"
value={gatewayForm["Gateway Name"]}
onChange={(e) => {
setGatewayForm({
...gatewayForm,
"Gateway Name": e.target.value,
});
if (errors["Gateway Name"])
setErrors({ ...errors, "Gateway Name": false });
}}
required
/>
{errors["Gateway Name"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
<label className="block text-sm text-gray-600 mb-1">Tipo *</label>
<select
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
value={form.type ?? "LORA"}
onChange={(e) => setForm({ ...form, type: e.target.value as "LORA" | "LORAWAN" | "GRANDES" })}
>
<option value="LORA">LoRa</option>
<option value="LORAWAN">LoRaWAN</option>
<option value="GRANDES">Grandes Consumidores</option>
</select>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Estado</label>
<select
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
value={gatewayForm["Antenna Placement"]}
onChange={(e) =>
setGatewayForm({
...gatewayForm,
"Antenna Placement": e.target.value as "Indoor" | "Outdoor",
})
}
value={form.status ?? "ACTIVE"}
onChange={(e) => setForm({ ...form, status: e.target.value })}
>
<option value="Indoor">Indoor</option>
<option value="Outdoor">Outdoor</option>
<option value="ACTIVE">Activo</option>
<option value="INACTIVE">Inactivo</option>
<option value="MAINTENANCE">Mantenimiento</option>
<option value="OFFLINE">Sin conexión</option>
</select>
</div>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Dirección IP</label>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Gateway Description"] ? "border-red-500" : ""
}`}
placeholder="Gateway Description *"
value={gatewayForm["Gateway Description"]}
onChange={(e) => {
setGatewayForm({
...gatewayForm,
"Gateway Description": e.target.value,
});
if (errors["Gateway Description"])
setErrors({ ...errors, "Gateway Description": false });
}}
required
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="192.168.1.100"
value={form.ipAddress ?? ""}
onChange={(e) => setForm({ ...form, ipAddress: e.target.value || undefined })}
/>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Versión de Firmware</label>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="v1.0.0"
value={form.firmwareVersion ?? ""}
onChange={(e) => setForm({ ...form, firmwareVersion: e.target.value || undefined })}
/>
{errors["Gateway Description"] && (
<p className="text-red-500 text-xs mt-1">
This field is required
</p>
)}
</div>
</div>
{/* ACTIONS */}
<div className="flex justify-end gap-2 pt-3 border-t">
<button
onClick={onClose}
className="px-4 py-2 rounded hover:bg-gray-100"
>
Cancel
<button onClick={onClose} className="px-4 py-2 rounded hover:bg-gray-100">
Cancelar
</button>
<button
onClick={onSave}
className="bg-[#4c5f9e] text-white px-4 py-2 rounded hover:bg-[#3d4d7e]"
>
Save
Guardar
</button>
</div>
</div>

View File

@@ -1,23 +1,23 @@
// src/pages/concentrators/ConcentratorsPage.tsx
import { useMemo, useState } from "react";
import { Plus, Trash2, Pencil, RefreshCcw } from "lucide-react";
import ConfirmModal from "../../components/layout/common/ConfirmModal";
import { createConcentrator, deleteConcentrator, updateConcentrator, type Concentrator } from "../../api/concentrators";
// ✅ hook es named export y pide currentUser
import {
createConcentrator,
deleteConcentrator,
updateConcentrator,
type Concentrator,
type ConcentratorInput,
} from "../../api/concentrators";
import { useConcentrators } from "./useConcentrators";
// ✅ UI pieces
import ConcentratorsSidebar from "./ConcentratorsSidebar";
import ConcentratorsTable from "./ConcentratorsTable";
import ConcentratorsModal from "./ConcentratorsModal";
export type SampleView = "GENERAL" | "LORA" | "LORAWAN" | "GRANDES";
export type ProjectStatus = "ACTIVO" | "INACTIVO";
export type ProjectCard = {
id: string;
name: string;
region: string;
projects: number;
@@ -33,91 +33,53 @@ type User = {
project?: string;
};
export type GatewayData = {
"Gateway ID": number;
"Gateway EUI": string;
"Gateway Name": string;
"Gateway Description": string;
"Antenna Placement": "Indoor" | "Outdoor";
concentratorId?: string;
};
export default function ConcentratorsPage() {
// ✅ Simulación de usuario actual
const currentUser: User = {
role: "SUPER_ADMIN",
project: "CESPT",
};
// ✅ Hook (solo cubre: projects + fetch + sampleView + selectedProject + loading + projectsData)
const c = useConcentrators(currentUser);
const [typesMenuOpen, setTypesMenuOpen] = useState(false);
const [search, setSearch] = useState("");
const [activeConcentrator, setActiveConcentrator] = useState<Concentrator | null>(null);
const [confirmOpen, setConfirmOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const [showModal, setShowModal] = useState(false);
const [editingSerial, setEditingSerial] = useState<string | null>(null);
const [editingId, setEditingId] = useState<string | null>(null);
const getEmptyConcentrator = (): Omit<Concentrator, "id"> => ({
"Area Name": c.selectedProject,
"Device S/N": "",
"Device Name": "",
"Device Time": new Date().toISOString(),
"Device Status": "ACTIVE",
Operator: "",
"Installed Time": new Date().toISOString().slice(0, 10),
"Communication Time": new Date().toISOString(),
"Instruction Manual": "",
const getEmptyForm = (): ConcentratorInput => ({
serialNumber: "",
name: "",
projectId: "",
location: "",
type: "LORA",
status: "ACTIVE",
ipAddress: "",
firmwareVersion: "",
});
const getEmptyGatewayData = (): GatewayData => ({
"Gateway ID": 0,
"Gateway EUI": "",
"Gateway Name": "",
"Gateway Description": "",
"Antenna Placement": "Indoor",
});
const [form, setForm] = useState<ConcentratorInput>(getEmptyForm());
const [errors, setErrors] = useState<Record<string, boolean>>({});
const [form, setForm] = useState<Omit<Concentrator, "id">>(getEmptyConcentrator());
const [gatewayForm, setGatewayForm] = useState<GatewayData>(getEmptyGatewayData());
const [errors, setErrors] = useState<{ [key: string]: boolean }>({});
// ✅ Tabla filtrada por search (usa lo que YA filtró el hook por proyecto)
const searchFiltered = useMemo(() => {
if (!c.isGeneral) return [];
return c.filteredConcentrators.filter((row) => {
const q = search.trim().toLowerCase();
if (!q) return true;
const name = (row["Device Name"] ?? "").toLowerCase();
const sn = (row["Device S/N"] ?? "").toLowerCase();
const name = (row.name ?? "").toLowerCase();
const sn = (row.serialNumber ?? "").toLowerCase();
return name.includes(q) || sn.includes(q);
});
}, [c.filteredConcentrators, c.isGeneral, search]);
// =========================
// CRUD (solo GENERAL)
// =========================
const validateForm = () => {
const next: { [key: string]: boolean } = {};
const next: Record<string, boolean> = {};
if (!form["Device Name"].trim()) next["Device Name"] = true;
if (!form["Device S/N"].trim()) next["Device S/N"] = true;
if (!form["Operator"].trim()) next["Operator"] = true;
if (!form["Instruction Manual"].trim()) next["Instruction Manual"] = true;
if (!form["Installed Time"]) next["Installed Time"] = true;
if (!form["Device Time"]) next["Device Time"] = true;
if (!form["Communication Time"]) next["Communication Time"] = true;
if (!gatewayForm["Gateway ID"] || gatewayForm["Gateway ID"] === 0) next["Gateway ID"] = true;
if (!gatewayForm["Gateway EUI"].trim()) next["Gateway EUI"] = true;
if (!gatewayForm["Gateway Name"].trim()) next["Gateway Name"] = true;
if (!gatewayForm["Gateway Description"].trim()) next["Gateway Description"] = true;
if (!form.name.trim()) next["name"] = true;
if (!form.serialNumber.trim()) next["serialNumber"] = true;
if (!form.projectId.trim()) next["projectId"] = true;
setErrors(next);
return Object.keys(next).length === 0;
@@ -128,23 +90,17 @@ export default function ConcentratorsPage() {
if (!validateForm()) return;
try {
if (editingSerial) {
const toUpdate = c.concentrators.find((x) => x["Device S/N"] === editingSerial);
if (!toUpdate) throw new Error("Concentrator not found");
const updated = await updateConcentrator(toUpdate.id, form);
// actualiza en memoria (el hook expone setConcentrators)
c.setConcentrators((prev) => prev.map((x) => (x.id === toUpdate.id ? updated : x)));
if (editingId) {
const updated = await updateConcentrator(editingId, form);
c.setConcentrators((prev) => prev.map((x) => (x.id === editingId ? updated : x)));
} else {
const created = await createConcentrator(form);
c.setConcentrators((prev) => [...prev, created]);
}
setShowModal(false);
setEditingSerial(null);
setForm({ ...getEmptyConcentrator(), "Area Name": c.selectedProject });
setGatewayForm(getEmptyGatewayData());
setEditingId(null);
setForm(getEmptyForm());
setErrors({});
setActiveConcentrator(null);
} catch (err) {
@@ -167,28 +123,32 @@ export default function ConcentratorsPage() {
}
};
// =========================
// Date helpers para modal
// =========================
function toDatetimeLocalValue(value?: string) {
if (!value) return "";
const d = new Date(value);
if (Number.isNaN(d.getTime())) return "";
const pad = (n: number) => String(n).padStart(2, "0");
const yyyy = d.getFullYear();
const mm = pad(d.getMonth() + 1);
const dd = pad(d.getDate());
const hh = pad(d.getHours());
const mi = pad(d.getMinutes());
return `${yyyy}-${mm}-${dd}T${hh}:${mi}`;
}
const openEditModal = () => {
if (!c.isGeneral || !activeConcentrator) return;
function fromDatetimeLocalValue(value: string) {
if (!value) return "";
const d = new Date(value);
if (Number.isNaN(d.getTime())) return "";
return d.toISOString();
}
setEditingId(activeConcentrator.id);
setForm({
serialNumber: activeConcentrator.serialNumber,
name: activeConcentrator.name,
projectId: activeConcentrator.projectId,
location: activeConcentrator.location ?? "",
type: activeConcentrator.type ?? "LORA",
status: activeConcentrator.status,
ipAddress: activeConcentrator.ipAddress ?? "",
firmwareVersion: activeConcentrator.firmwareVersion ?? "",
});
setErrors({});
setShowModal(true);
};
const openCreateModal = () => {
if (!c.isGeneral) return;
setForm(getEmptyForm());
setErrors({});
setEditingId(null);
setShowModal(true);
};
return (
<div className="flex gap-6 p-6 w-full bg-gray-100">
@@ -202,8 +162,6 @@ export default function ConcentratorsPage() {
onChangeSampleView={(next: SampleView) => {
c.setSampleView(next);
setTypesMenuOpen(false);
// resets UI
c.setSelectedProject("");
setActiveConcentrator(null);
setSearch("");
@@ -238,46 +196,15 @@ export default function ConcentratorsPage() {
<div className="flex gap-3">
<button
onClick={() => {
if (!c.isGeneral) return;
if (!c.selectedProject) return;
setForm({ ...getEmptyConcentrator(), "Area Name": c.selectedProject });
setGatewayForm(getEmptyGatewayData());
setErrors({});
setEditingSerial(null);
setShowModal(true);
}}
disabled={!c.isGeneral || !c.selectedProject}
onClick={openCreateModal}
disabled={!c.isGeneral || c.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"
>
<Plus size={16} /> Agregar
</button>
<button
onClick={() => {
if (!c.isGeneral) return;
if (!activeConcentrator) return;
const a = activeConcentrator;
setEditingSerial(a["Device S/N"]);
setForm({
"Area Name": a["Area Name"],
"Device S/N": a["Device S/N"],
"Device Name": a["Device Name"],
"Device Time": a["Device Time"],
"Device Status": a["Device Status"],
Operator: a["Operator"],
"Installed Time": a["Installed Time"],
"Communication Time": a["Communication Time"],
"Instruction Manual": a["Instruction Manual"],
});
setGatewayForm(getEmptyGatewayData());
setErrors({});
setShowModal(true);
}}
onClick={openEditModal}
disabled={!c.isGeneral || !activeConcentrator}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"
>
@@ -304,7 +231,7 @@ export default function ConcentratorsPage() {
<input
className="bg-white rounded-lg shadow px-4 py-2 text-sm"
placeholder={c.isGeneral ? "Search concentrator..." : "Search disabled in mock views"}
placeholder={c.isGeneral ? "Buscar concentrador..." : "Search disabled in mock views"}
value={search}
onChange={(e) => setSearch(e.target.value)}
disabled={!c.isGeneral || !c.selectedProject}
@@ -320,10 +247,10 @@ export default function ConcentratorsPage() {
!c.isGeneral
? `Vista "${c.sampleViewLabel}" está en modo mock (sin backend todavía).`
: !c.selectedProject
? "Select a project to view concentrators."
? "Selecciona un proyecto para ver los concentradores."
: c.loadingConcentrators
? "Loading concentrators..."
: "No concentrators found. Click 'Add' to create your first concentrator."
? "Cargando concentradores..."
: "No hay concentradores. Haz clic en 'Agregar' para crear uno."
}
/>
</div>
@@ -332,8 +259,8 @@ export default function ConcentratorsPage() {
open={confirmOpen}
title="Eliminar concentrador"
message={`¿Estás seguro que quieres eliminar "${
activeConcentrator?.["Device Name"] ?? "este concentrador"
}"? Esta acción no se puede deshacer.`}
activeConcentrator?.name ?? "este concentrador"
}" (${activeConcentrator?.serialNumber ?? "—"})? Esta acción no se puede deshacer.`}
confirmText="Eliminar"
cancelText="Cancelar"
danger
@@ -354,18 +281,14 @@ export default function ConcentratorsPage() {
{showModal && c.isGeneral && (
<ConcentratorsModal
editingSerial={editingSerial}
editingId={editingId}
form={form}
setForm={setForm}
gatewayForm={gatewayForm}
setGatewayForm={setGatewayForm}
errors={errors}
setErrors={setErrors}
toDatetimeLocalValue={toDatetimeLocalValue}
fromDatetimeLocalValue={fromDatetimeLocalValue}
allProjects={c.allProjects}
onClose={() => {
setShowModal(false);
setGatewayForm(getEmptyGatewayData());
setErrors({});
}}
onSave={handleSave}

View File

@@ -59,7 +59,9 @@ export default function ConcentratorsSidebar({
Tipo: <span className="font-semibold">{sampleViewLabel}</span>
{" • "}
Seleccionado:{" "}
<span className="font-semibold">{selectedProject || "—"}</span>
<span className="font-semibold">
{projects.find((p) => p.id === selectedProject)?.name || "—"}
</span>
</p>
</div>
@@ -132,12 +134,12 @@ export default function ConcentratorsSidebar({
</div>
) : (
projects.map((p) => {
const active = p.name === selectedProject;
const active = p.id === selectedProject;
return (
<div
key={p.name}
onClick={() => onSelectProject(p.name)}
key={p.id}
onClick={() => onSelectProject(p.id)}
className={[
"rounded-xl border p-4 transition cursor-pointer",
active
@@ -211,7 +213,7 @@ export default function ConcentratorsSidebar({
].join(" ")}
onClick={(e) => {
e.stopPropagation();
onSelectProject(p.name);
onSelectProject(p.id);
}}
>
{active ? "Seleccionado" : "Seleccionar"}

View File

@@ -23,45 +23,69 @@ export default function ConcentratorsTable({
isLoading={isLoading}
columns={[
{
title: "Device Name",
field: "Device Name",
render: (rowData: any) => rowData["Device Name"] || "-",
title: "Serial",
field: "serialNumber",
render: (rowData: Concentrator) => rowData.serialNumber || "-",
},
{
title: "Device S/N",
field: "Device S/N",
render: (rowData: any) => rowData["Device S/N"] || "-",
title: "Nombre",
field: "name",
render: (rowData: Concentrator) => rowData.name || "-",
},
{
title: "Device Status",
field: "Device Status",
render: (rowData: any) => (
title: "Tipo",
field: "type",
render: (rowData: Concentrator) => {
const typeLabels: Record<string, string> = {
LORA: "LoRa",
LORAWAN: "LoRaWAN",
GRANDES: "Grandes Consumidores",
};
const typeColors: Record<string, string> = {
LORA: "text-green-600 border-green-600",
LORAWAN: "text-purple-600 border-purple-600",
GRANDES: "text-orange-600 border-orange-600",
};
const type = rowData.type || "LORA";
return (
<span
className={`px-3 py-1 rounded-full text-xs font-semibold border ${typeColors[type] || "text-gray-600 border-gray-600"}`}
>
{typeLabels[type] || type}
</span>
);
},
},
{
title: "Estado",
field: "status",
render: (rowData: Concentrator) => (
<span
className={`px-3 py-1 rounded-full text-xs font-semibold border ${
rowData["Device Status"] === "ACTIVE"
rowData.status === "ACTIVE"
? "text-blue-600 border-blue-600"
: "text-red-600 border-red-600"
}`}
>
{rowData["Device Status"] || "-"}
{rowData.status || "-"}
</span>
),
},
{
title: "Operator",
field: "Operator",
render: (rowData: any) => rowData["Operator"] || "-",
title: "Ubicación",
field: "location",
render: (rowData: Concentrator) => rowData.location || "-",
},
{
title: "Area Name",
field: "Area Name",
render: (rowData: any) => rowData["Area Name"] || "-",
title: "IP",
field: "ipAddress",
render: (rowData: Concentrator) => rowData.ipAddress || "-",
},
{
title: "Installed Time",
field: "Installed Time",
type: "date",
render: (rowData: any) => rowData["Installed Time"] || "-",
title: "Última Comunicación",
field: "lastCommunication",
type: "datetime",
render: (rowData: Concentrator) => rowData.lastCommunication ? new Date(rowData.lastCommunication).toLocaleString() : "-",
},
]}
data={data}

View File

@@ -3,6 +3,7 @@ import {
fetchConcentrators,
type Concentrator,
} from "../../api/concentrators";
import { fetchProjects, type Project } from "../../api/projects";
import type { ProjectCard, SampleView } from "./ConcentratorsPage";
type User = {
@@ -16,6 +17,7 @@ export function useConcentrators(currentUser: User) {
const [loadingProjects, setLoadingProjects] = useState(true);
const [loadingConcentrators, setLoadingConcentrators] = useState(true);
const [projects, setProjects] = useState<Project[]>([]);
const [allProjects, setAllProjects] = useState<string[]>([]);
const [selectedProject, setSelectedProject] = useState("");
@@ -51,58 +53,49 @@ export function useConcentrators(currentUser: User) {
[allProjects, currentUser.role, currentUser.project]
);
const loadConcentrators = async () => {
if (!isGeneral) return;
setLoadingConcentrators(true);
const loadProjects = async () => {
setLoadingProjects(true);
try {
const raw = await fetchConcentrators();
const normalized = raw.map((c: any) => {
const preferredName =
c["Device Alias"] ||
c["Device Label"] ||
c["Device Display Name"] ||
c.deviceName ||
c.name ||
c["Device Name"] ||
"";
return {
...c,
"Device Name": preferredName,
};
});
const projectsArray = [
...new Set(normalized.map((r: any) => r["Area Name"])),
].filter(Boolean) as string[];
setAllProjects(projectsArray);
setConcentrators(normalized);
const projectsData = await fetchProjects();
setProjects(projectsData);
const projectIds = projectsData.map((p) => p.id);
setAllProjects(projectIds);
setSelectedProject((prev) => {
if (prev) return prev;
if (currentUser.role !== "SUPER_ADMIN" && currentUser.project) {
return currentUser.project;
}
return projectsArray[0] ?? "";
return projectIds[0] ?? "";
});
} catch (err) {
console.error("Error loading concentrators:", err);
console.error("Error loading projects:", err);
setProjects([]);
setAllProjects([]);
setConcentrators([]);
setSelectedProject("");
} finally {
setLoadingConcentrators(false);
setLoadingProjects(false);
}
};
// init
const loadConcentrators = async () => {
if (!isGeneral) return;
setLoadingConcentrators(true);
try {
const data = await fetchConcentrators();
setConcentrators(data);
} catch (err) {
console.error("Error loading concentrators:", err);
setConcentrators([]);
} finally {
setLoadingConcentrators(false);
}
};
// init - load projects and concentrators
useEffect(() => {
loadProjects();
loadConcentrators();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -110,6 +103,7 @@ export function useConcentrators(currentUser: User) {
// view changes
useEffect(() => {
if (isGeneral) {
loadProjects();
loadConcentrators();
} else {
setLoadingProjects(false);
@@ -136,7 +130,7 @@ export function useConcentrators(currentUser: User) {
if (selectedProject) {
setFilteredConcentrators(
concentrators.filter((c) => c["Area Name"] === selectedProject)
concentrators.filter((c) => c.projectId === selectedProject)
);
} else {
setFilteredConcentrators(concentrators);
@@ -146,8 +140,13 @@ export function useConcentrators(currentUser: User) {
// sidebar cards (general)
const projectsDataGeneral: ProjectCard[] = useMemo(() => {
const counts = concentrators.reduce<Record<string, number>>((acc, c) => {
const area = c["Area Name"] ?? "SIN PROYECTO";
acc[area] = (acc[area] ?? 0) + 1;
const project = c.projectId ?? "SIN PROYECTO";
acc[project] = (acc[project] ?? 0) + 1;
return acc;
}, {});
const projectNameMap = projects.reduce<Record<string, string>>((acc, p) => {
acc[p.id] = p.name;
return acc;
}, {});
@@ -155,17 +154,18 @@ export function useConcentrators(currentUser: User) {
const baseContact = "Operaciones";
const baseLastSync = "Hace 1 h";
return visibleProjects.map((name) => ({
name,
return visibleProjects.map((projectId) => ({
id: projectId,
name: projectNameMap[projectId] ?? projectId,
region: baseRegion,
projects: 1,
concentrators: counts[name] ?? 0,
concentrators: counts[projectId] ?? 0,
activeAlerts: 0,
lastSync: baseLastSync,
contact: baseContact,
status: "ACTIVO",
status: "ACTIVO" as const,
}));
}, [concentrators, visibleProjects]);
}, [concentrators, visibleProjects, projects]);
// sidebar cards (mock)
const projectsDataMock: Record<Exclude<SampleView, "GENERAL">, ProjectCard[]> =
@@ -173,6 +173,7 @@ export function useConcentrators(currentUser: User) {
() => ({
LORA: [
{
id: "mock-lora-centro",
name: "LoRa - Zona Centro",
region: "Baja California",
projects: 1,
@@ -183,6 +184,7 @@ export function useConcentrators(currentUser: User) {
status: "ACTIVO",
},
{
id: "mock-lora-este",
name: "LoRa - Zona Este",
region: "Baja California",
projects: 1,
@@ -195,6 +197,7 @@ export function useConcentrators(currentUser: User) {
],
LORAWAN: [
{
id: "mock-lorawan-industrial",
name: "LoRaWAN - Industrial",
region: "Baja California",
projects: 1,
@@ -207,6 +210,7 @@ export function useConcentrators(currentUser: User) {
],
GRANDES: [
{
id: "mock-grandes-convenios",
name: "Grandes - Convenios",
region: "Baja California",
projects: 1,

View File

@@ -0,0 +1,560 @@
import { useEffect, useState, useMemo } from "react";
import {
RefreshCcw,
Download,
Search,
Droplets,
TrendingUp,
Zap,
Clock,
ChevronLeft,
ChevronRight,
Filter,
X,
Activity,
} from "lucide-react";
import {
fetchReadings,
fetchConsumptionSummary,
type MeterReading,
type ConsumptionSummary,
type Pagination,
} from "../../api/readings";
import { fetchProjects, type Project } from "../../api/projects";
export default function ConsumptionPage() {
const [readings, setReadings] = useState<MeterReading[]>([]);
const [summary, setSummary] = useState<ConsumptionSummary | null>(null);
const [projects, setProjects] = useState<Project[]>([]);
const [pagination, setPagination] = useState<Pagination>({
page: 1,
pageSize: 100,
total: 0,
totalPages: 0,
});
const [loadingReadings, setLoadingReadings] = useState(false);
const [loadingSummary, setLoadingSummary] = useState(false);
const [selectedProject, setSelectedProject] = useState<string>("");
const [startDate, setStartDate] = useState<string>("");
const [endDate, setEndDate] = useState<string>("");
const [search, setSearch] = useState<string>("");
const [showFilters, setShowFilters] = useState(false);
useEffect(() => {
const loadProjects = async () => {
try {
const data = await fetchProjects();
setProjects(data);
} catch (error) {
console.error("Error loading projects:", error);
}
};
loadProjects();
}, []);
const loadData = async (page = 1) => {
setLoadingReadings(true);
setLoadingSummary(true);
try {
const [readingsResult, summaryResult] = await Promise.all([
fetchReadings({
projectId: selectedProject || undefined,
startDate: startDate || undefined,
endDate: endDate || undefined,
page,
pageSize: 100,
}),
fetchConsumptionSummary(selectedProject || undefined),
]);
setReadings(readingsResult.data);
setPagination(readingsResult.pagination);
setSummary(summaryResult);
} catch (error) {
console.error("Error loading data:", error);
} finally {
setLoadingReadings(false);
setLoadingSummary(false);
}
};
useEffect(() => {
loadData(1);
}, [selectedProject, startDate, endDate]);
const filteredReadings = useMemo(() => {
if (!search.trim()) return readings;
const q = search.toLowerCase();
return readings.filter(
(r) =>
(r.meterSerialNumber ?? "").toLowerCase().includes(q) ||
(r.meterName ?? "").toLowerCase().includes(q) ||
(r.areaName ?? "").toLowerCase().includes(q) ||
String(r.readingValue).includes(q)
);
}, [readings, search]);
const formatDate = (dateStr: string | null): string => {
if (!dateStr) return "—";
const date = new Date(dateStr);
return date.toLocaleString("es-MX", {
day: "2-digit",
month: "short",
hour: "2-digit",
minute: "2-digit",
});
};
const formatFullDate = (dateStr: string | null): string => {
if (!dateStr) return "Sin datos";
const date = new Date(dateStr);
return date.toLocaleString("es-MX", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
};
const exportToCSV = () => {
const headers = ["Fecha", "Medidor", "Serial", "Área", "Valor", "Tipo", "Batería", "Señal"];
const rows = filteredReadings.map((r) => [
formatFullDate(r.receivedAt),
r.meterName || "—",
r.meterSerialNumber || "—",
r.areaName || "—",
r.readingValue.toFixed(2),
r.readingType || "—",
r.batteryLevel !== null ? `${r.batteryLevel}%` : "—",
r.signalStrength !== null ? `${r.signalStrength} dBm` : "—",
]);
const csv = [headers, ...rows].map((row) => row.join(",")).join("\n");
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `consumo_${new Date().toISOString().split("T")[0]}.csv`;
link.click();
};
const clearFilters = () => {
setSelectedProject("");
setStartDate("");
setEndDate("");
setSearch("");
};
const hasFilters = selectedProject || startDate || endDate;
const activeFiltersCount = [selectedProject, startDate, endDate].filter(Boolean).length;
return (
<div className="min-h-full bg-gradient-to-br from-slate-50 via-blue-50/30 to-indigo-50/50 p-6">
<div className="max-w-[1600px] mx-auto space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-slate-800">Consumo de Agua</h1>
<p className="text-slate-500 text-sm mt-0.5">
Monitoreo en tiempo real de lecturas
</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => loadData(pagination.page)}
className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-xl hover:bg-slate-50 hover:border-slate-300 transition-all shadow-sm"
>
<RefreshCcw size={16} />
Actualizar
</button>
<button
onClick={exportToCSV}
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"
>
<Download size={16} />
Exportar
</button>
</div>
</div>
{/* Stats Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<StatCard
icon={<Activity />}
label="Total Lecturas"
value={summary?.totalReadings.toLocaleString() ?? "0"}
trend="+12%"
loading={loadingSummary}
gradient="from-blue-500 to-blue-600"
/>
<StatCard
icon={<Zap />}
label="Medidores Activos"
value={summary?.totalMeters.toLocaleString() ?? "0"}
loading={loadingSummary}
gradient="from-emerald-500 to-teal-600"
/>
<StatCard
icon={<Droplets />}
label="Consumo Promedio"
value={`${summary?.avgReading.toFixed(1) ?? "0"}`}
loading={loadingSummary}
gradient="from-violet-500 to-purple-600"
/>
<StatCard
icon={<Clock />}
label="Última Lectura"
value={summary?.lastReadingDate ? formatDate(summary.lastReadingDate) : "Sin datos"}
loading={loadingSummary}
gradient="from-amber-500 to-orange-600"
/>
</div>
{/* Table Card */}
<div className="bg-white rounded-2xl shadow-sm shadow-slate-200/50 border border-slate-200/60 overflow-hidden">
{/* Table Header */}
<div className="px-5 py-4 border-b border-slate-100 flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-3">
<div className="relative">
<Search
size={18}
className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"
/>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Buscar lecturas..."
className="w-64 pl-10 pr-4 py-2 text-sm bg-slate-50 border-0 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:bg-white transition-all"
/>
</div>
<button
onClick={() => setShowFilters(!showFilters)}
className={`inline-flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-xl transition-all ${
showFilters || hasFilters
? "bg-blue-50 text-blue-600 border border-blue-200"
: "text-slate-600 bg-slate-50 hover:bg-slate-100"
}`}
>
<Filter size={16} />
Filtros
{activeFiltersCount > 0 && (
<span className="inline-flex items-center justify-center w-5 h-5 text-xs font-bold text-white bg-blue-600 rounded-full">
{activeFiltersCount}
</span>
)}
</button>
{hasFilters && (
<button
onClick={clearFilters}
className="inline-flex items-center gap-1 px-2 py-1 text-xs text-slate-500 hover:text-slate-700"
>
<X size={14} />
Limpiar
</button>
)}
</div>
<div className="flex items-center gap-4 text-sm text-slate-500">
<span>
<span className="font-semibold text-slate-700">{filteredReadings.length}</span>{" "}
{pagination.total > filteredReadings.length && `de ${pagination.total} `}
lecturas
</span>
{pagination.totalPages > 1 && (
<div className="flex items-center gap-1 bg-slate-50 rounded-lg p-1">
<button
onClick={() => loadData(pagination.page - 1)}
disabled={pagination.page === 1}
className="p-1.5 rounded-md hover:bg-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
>
<ChevronLeft size={16} />
</button>
<span className="px-2 text-xs font-medium">
{pagination.page} / {pagination.totalPages}
</span>
<button
onClick={() => loadData(pagination.page + 1)}
disabled={pagination.page === pagination.totalPages}
className="p-1.5 rounded-md hover:bg-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
>
<ChevronRight size={16} />
</button>
</div>
)}
</div>
</div>
{/* Filters Panel */}
{showFilters && (
<div className="px-5 py-4 bg-slate-50/50 border-b border-slate-100 flex flex-wrap items-center gap-4">
<div className="flex items-center gap-2">
<label className="text-xs font-medium text-slate-500 uppercase tracking-wide">
Proyecto
</label>
<select
value={selectedProject}
onChange={(e) => setSelectedProject(e.target.value)}
className="px-3 py-1.5 text-sm bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20"
>
<option value="">Todos</option>
{projects.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
<div className="flex items-center gap-2">
<label className="text-xs font-medium text-slate-500 uppercase tracking-wide">
Desde
</label>
<input
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
className="px-3 py-1.5 text-sm bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20"
/>
</div>
<div className="flex items-center gap-2">
<label className="text-xs font-medium text-slate-500 uppercase tracking-wide">
Hasta
</label>
<input
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
className="px-3 py-1.5 text-sm bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20"
/>
</div>
</div>
)}
{/* Table */}
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="bg-slate-50/80">
<th className="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">
Fecha
</th>
<th className="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">
Medidor
</th>
<th className="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">
Serial
</th>
<th className="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">
Área
</th>
<th className="px-5 py-3 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">
Consumo
</th>
<th className="px-5 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
Tipo
</th>
<th className="px-5 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">
Estado
</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{loadingReadings ? (
Array.from({ length: 8 }).map((_, i) => (
<tr key={i}>
{Array.from({ length: 7 }).map((_, j) => (
<td key={j} className="px-5 py-4">
<div className="h-4 bg-slate-100 rounded-md animate-pulse" />
</td>
))}
</tr>
))
) : filteredReadings.length === 0 ? (
<tr>
<td colSpan={7} className="px-5 py-16 text-center">
<div className="flex flex-col items-center">
<div className="w-16 h-16 bg-slate-100 rounded-2xl flex items-center justify-center mb-4">
<Droplets size={32} className="text-slate-400" />
</div>
<p className="text-slate-600 font-medium">No hay lecturas disponibles</p>
<p className="text-slate-400 text-sm mt-1">
{hasFilters
? "Intenta ajustar los filtros de búsqueda"
: "Las lecturas aparecerán aquí cuando se reciban datos"}
</p>
</div>
</td>
</tr>
) : (
filteredReadings.map((reading, idx) => (
<tr
key={reading.id}
className={`group hover:bg-blue-50/40 transition-colors ${
idx % 2 === 0 ? "bg-white" : "bg-slate-50/30"
}`}
>
<td className="px-5 py-3.5">
<span className="text-sm text-slate-600">{formatDate(reading.receivedAt)}</span>
</td>
<td className="px-5 py-3.5">
<span className="text-sm font-medium text-slate-800">
{reading.meterName || "—"}
</span>
</td>
<td className="px-5 py-3.5">
<code className="text-xs text-slate-500 bg-slate-100 px-2 py-0.5 rounded">
{reading.meterSerialNumber || "—"}
</code>
</td>
<td className="px-5 py-3.5">
<span className="text-sm text-slate-600">{reading.areaName || "—"}</span>
</td>
<td className="px-5 py-3.5 text-right">
<span className="text-sm font-semibold text-slate-800 tabular-nums">
{reading.readingValue.toFixed(2)}
</span>
<span className="text-xs text-slate-400 ml-1">m³</span>
</td>
<td className="px-5 py-3.5 text-center">
<TypeBadge type={reading.readingType} />
</td>
<td className="px-5 py-3.5">
<div className="flex items-center justify-center gap-2">
<BatteryIndicator level={reading.batteryLevel} />
<SignalIndicator strength={reading.signalStrength} />
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}
function StatCard({
icon,
label,
value,
trend,
loading,
gradient,
}: {
icon: React.ReactNode;
label: string;
value: string;
trend?: string;
loading?: boolean;
gradient: string;
}) {
return (
<div className="relative bg-white rounded-2xl p-5 shadow-sm shadow-slate-200/50 border border-slate-200/60 overflow-hidden group hover:shadow-md hover:shadow-slate-200/50 transition-all">
<div className="flex items-start justify-between">
<div className="space-y-2">
<p className="text-sm font-medium text-slate-500">{label}</p>
{loading ? (
<div className="h-8 w-24 bg-slate-100 rounded-lg animate-pulse" />
) : (
<p className="text-2xl font-bold text-slate-800">{value}</p>
)}
{trend && !loading && (
<div className="inline-flex items-center gap-1 text-xs font-medium text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full">
<TrendingUp size={12} />
{trend}
</div>
)}
</div>
<div
className={`w-12 h-12 rounded-xl bg-gradient-to-br ${gradient} flex items-center justify-center text-white shadow-lg group-hover:scale-110 transition-transform`}
>
{icon}
</div>
</div>
<div
className={`absolute -right-8 -bottom-8 w-32 h-32 rounded-full bg-gradient-to-br ${gradient} opacity-5`}
/>
</div>
);
}
function TypeBadge({ type }: { type: string | null }) {
if (!type) return <span className="text-slate-400"></span>;
const styles: Record<string, { bg: string; text: string; dot: string }> = {
AUTOMATIC: { bg: "bg-emerald-50", text: "text-emerald-700", dot: "bg-emerald-500" },
MANUAL: { bg: "bg-blue-50", text: "text-blue-700", dot: "bg-blue-500" },
SCHEDULED: { bg: "bg-violet-50", text: "text-violet-700", dot: "bg-violet-500" },
};
const style = styles[type] || { bg: "bg-slate-50", text: "text-slate-700", dot: "bg-slate-500" };
return (
<span
className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-full ${style.bg} ${style.text}`}
>
<span className={`w-1.5 h-1.5 rounded-full ${style.dot}`} />
{type}
</span>
);
}
function BatteryIndicator({ level }: { level: number | null }) {
if (level === null) return null;
const getColor = () => {
if (level > 50) return "bg-emerald-500";
if (level > 20) return "bg-amber-500";
return "bg-red-500";
};
return (
<div className="flex items-center gap-1" title={`Batería: ${level}%`}>
<div className="w-6 h-3 border border-slate-300 rounded-sm relative overflow-hidden">
<div
className={`absolute left-0 top-0 bottom-0 ${getColor()} transition-all`}
style={{ width: `${level}%` }}
/>
</div>
<span className="text-[10px] text-slate-500 font-medium">{level}%</span>
</div>
);
}
function SignalIndicator({ strength }: { strength: number | null }) {
if (strength === null) return null;
const getBars = () => {
if (strength >= -70) return 4;
if (strength >= -85) return 3;
if (strength >= -100) return 2;
return 1;
};
const bars = getBars();
return (
<div className="flex items-end gap-0.5 h-3" title={`Señal: ${strength} dBm`}>
{[1, 2, 3, 4].map((i) => (
<div
key={i}
className={`w-1 rounded-sm transition-colors ${
i <= bars ? "bg-emerald-500" : "bg-slate-200"
}`}
style={{ height: `${i * 2 + 4}px` }}
/>
))}
</div>
);
}

View File

@@ -1,6 +1,6 @@
import { useMemo, useState } from "react";
import { Plus, Trash2, Pencil, RefreshCcw } from "lucide-react";
import type { Meter } from "../../api/meters";
import { Plus, Trash2, Pencil, RefreshCcw, Upload } from "lucide-react";
import type { Meter, MeterInput } from "../../api/meters";
import { createMeter, deleteMeter, updateMeter } from "../../api/meters";
import ConfirmModal from "../../components/layout/common/ConfirmModal";
@@ -8,16 +8,9 @@ import { useMeters } from "./useMeters";
import MetersSidebar from "./MetersSidebar";
import MetersTable from "./MetersTable";
import MetersModal from "./MetersModal";
import MetersBulkUploadModal from "./MetersBulkUploadModal";
/* ================= TYPES (exportables para otros componentes) ================= */
export interface DeviceData {
"Device ID": number;
"Device EUI": string;
"Join EUI": string;
AppKey: string;
meterId?: string;
}
/* ================= TYPES ================= */
export type ProjectStatus = "ACTIVO" | "INACTIVO";
@@ -34,20 +27,6 @@ export type ProjectCard = {
export type TakeType = "GENERAL" | "LORA" | "LORAWAN" | "GRANDES";
/* ================= MOCKS (sin backend) ================= */
const MOCK_PROJECTS_BY_TYPE: Record<
Exclude<TakeType, "GENERAL">,
Array<{ name: string; meters?: number }>
> = {
LORA: [
{ name: "LoRa - Demo 01", meters: 12 },
{ name: "LoRa - Demo 02", meters: 7 },
],
LORAWAN: [{ name: "LoRaWAN - Demo 01", meters: 4 }],
GRANDES: [{ name: "Grandes - Demo 01", meters: 2 }],
};
/* ================= COMPONENT ================= */
export default function MetersPage({
@@ -68,46 +47,27 @@ export default function MetersPage({
const [confirmOpen, setConfirmOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const emptyMeter: Omit<Meter, "id"> = useMemo(
const [showBulkUpload, setShowBulkUpload] = useState(false);
// Form state for creating/editing meters
const emptyForm: MeterInput = useMemo(
() => ({
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
areaName: "",
accountNumber: null,
userName: null,
userAddress: null,
meterSerialNumber: "",
meterName: "",
meterStatus: "Installed",
protocolType: "",
priceNo: null,
priceName: null,
dmaPartition: null,
supplyTypes: "",
deviceId: "",
deviceName: "",
deviceType: "",
usageAnalysisType: "",
installedTime: new Date().toISOString(),
serialNumber: "",
meterId: "",
name: "",
concentratorId: "",
location: "",
type: "LORA",
status: "ACTIVE",
installationDate: new Date().toISOString(),
}),
[]
);
const emptyDeviceData: DeviceData = useMemo(
() => ({
"Device ID": 0,
"Device EUI": "",
"Join EUI": "",
AppKey: "",
}),
[]
);
const [form, setForm] = useState<Omit<Meter, "id">>(emptyMeter);
const [deviceForm, setDeviceForm] = useState<DeviceData>(emptyDeviceData);
const [form, setForm] = useState<MeterInput>(emptyForm);
const [errors, setErrors] = useState<Record<string, boolean>>({});
// Projects cards (real)
// Projects cards (from real data)
const projectsDataReal: ProjectCard[] = useMemo(() => {
const baseRegion = "Baja California";
const baseContact = "Operaciones";
@@ -121,32 +81,13 @@ export default function MetersPage({
activeAlerts: 0,
lastSync: baseLastSync,
contact: baseContact,
status: "ACTIVO",
status: "ACTIVO" as ProjectStatus,
}));
}, [m.allProjects, m.projectsCounts]);
// Projects cards (mock)
const projectsDataMock: ProjectCard[] = useMemo(() => {
const baseRegion = "Baja California";
const baseContact = "Operaciones";
const baseLastSync = "Hace 1 h";
const sidebarProjects = isMockMode ? [] : projectsDataReal;
const mocks = MOCK_PROJECTS_BY_TYPE[takeType as Exclude<TakeType, "GENERAL">] ?? [];
return mocks.map((x) => ({
name: x.name,
region: baseRegion,
projects: 1,
meters: x.meters ?? 0,
activeAlerts: 0,
lastSync: baseLastSync,
contact: baseContact,
status: "ACTIVO",
}));
}, [takeType]);
const sidebarProjects = isMockMode ? projectsDataMock : projectsDataReal;
// Search filtered
// Search filtered meters
const searchFiltered = useMemo(() => {
if (isMockMode) return [];
const q = search.trim().toLowerCase();
@@ -154,76 +95,43 @@ export default function MetersPage({
return m.filteredMeters.filter((x) => {
return (
(x.meterName ?? "").toLowerCase().includes(q) ||
(x.meterSerialNumber ?? "").toLowerCase().includes(q) ||
(x.deviceId ?? "").toLowerCase().includes(q) ||
(x.areaName ?? "").toLowerCase().includes(q)
(x.name ?? "").toLowerCase().includes(q) ||
(x.serialNumber ?? "").toLowerCase().includes(q) ||
(x.location ?? "").toLowerCase().includes(q) ||
(x.concentratorName ?? "").toLowerCase().includes(q)
);
});
}, [isMockMode, search, m.filteredMeters]);
// Device config mock
const createOrUpdateDevice = async (deviceData: DeviceData): Promise<void> => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Device data that would be sent to API:", deviceData);
resolve();
}, 500);
});
};
// Validation
const validateForm = (): boolean => {
const next: Record<string, boolean> = {};
if (!form.meterName.trim()) next["meterName"] = true;
if (!form.meterSerialNumber.trim()) next["meterSerialNumber"] = true;
if (!form.areaName.trim()) next["areaName"] = true;
if (!form.deviceName.trim()) next["deviceName"] = true;
if (!form.protocolType.trim()) next["protocolType"] = true;
if (!deviceForm["Device ID"] || deviceForm["Device ID"] === 0) next["Device ID"] = true;
if (!deviceForm["Device EUI"].trim()) next["Device EUI"] = true;
if (!deviceForm["Join EUI"].trim()) next["Join EUI"] = true;
if (!deviceForm["AppKey"].trim()) next["AppKey"] = true;
if (!form.name.trim()) next["name"] = true;
if (!form.serialNumber.trim()) next["serialNumber"] = true;
if (!form.concentratorId.trim()) next["concentratorId"] = true;
setErrors(next);
return Object.keys(next).length === 0;
};
// CRUD
// CRUD handlers
const handleSave = async () => {
if (isMockMode) return;
if (!validateForm()) return;
try {
let savedMeter: Meter;
if (editingId) {
const meterToUpdate = m.meters.find((x) => x.id === editingId);
if (!meterToUpdate) throw new Error("Meter to update not found");
const updatedMeter = await updateMeter(editingId, form);
m.setMeters((prev) => prev.map((x) => (x.id === editingId ? updatedMeter : x)));
savedMeter = updatedMeter;
} else {
const newMeter = await createMeter(form);
m.setMeters((prev) => [...prev, newMeter]);
savedMeter = newMeter;
}
try {
const deviceDataWithRef = { ...deviceForm, meterId: savedMeter.id };
await createOrUpdateDevice(deviceDataWithRef);
} catch (deviceError) {
console.error("Error saving device data:", deviceError);
alert("Meter saved, but there was an error saving device data.");
}
setShowModal(false);
setEditingId(null);
setForm(emptyMeter);
setDeviceForm(emptyDeviceData);
setForm(emptyForm);
setErrors({});
setActiveMeter(null);
} catch (error) {
@@ -260,6 +168,33 @@ export default function MetersPage({
setSearch("");
};
const openEditModal = () => {
if (isMockMode || !activeMeter) return;
setEditingId(activeMeter.id);
setForm({
serialNumber: activeMeter.serialNumber,
meterId: activeMeter.meterId ?? "",
name: activeMeter.name,
concentratorId: activeMeter.concentratorId,
location: activeMeter.location ?? "",
type: activeMeter.type,
status: activeMeter.status,
installationDate: activeMeter.installationDate ?? "",
});
setErrors({});
setShowModal(true);
};
const openCreateModal = () => {
if (isMockMode) return;
setForm(emptyForm);
setErrors({});
setEditingId(null);
setShowModal(true);
};
return (
<div className="flex gap-6 p-6 w-full bg-gray-100">
{/* SIDEBAR */}
@@ -296,55 +231,23 @@ export default function MetersPage({
<div className="flex gap-3">
<button
onClick={() => {
if (isMockMode) return;
const base = { ...emptyMeter };
if (m.selectedProject) base.areaName = m.selectedProject;
setForm(base);
setDeviceForm(emptyDeviceData);
setErrors({});
setEditingId(null);
setShowModal(true);
}}
disabled={isMockMode || !m.selectedProject || m.allProjects.length === 0}
onClick={openCreateModal}
disabled={isMockMode || 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"
>
<Plus size={16} /> Agregar
</button>
<button
onClick={() => {
if (isMockMode) return;
if (!activeMeter) return;
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"
>
<Upload size={16} /> Carga Masiva
</button>
setEditingId(activeMeter.id);
setForm({
createdAt: activeMeter.createdAt,
updatedAt: activeMeter.updatedAt,
areaName: activeMeter.areaName,
accountNumber: activeMeter.accountNumber,
userName: activeMeter.userName,
userAddress: activeMeter.userAddress,
meterSerialNumber: activeMeter.meterSerialNumber,
meterName: activeMeter.meterName,
meterStatus: activeMeter.meterStatus,
protocolType: activeMeter.protocolType,
priceNo: activeMeter.priceNo,
priceName: activeMeter.priceName,
dmaPartition: activeMeter.dmaPartition,
supplyTypes: activeMeter.supplyTypes,
deviceId: activeMeter.deviceId,
deviceName: activeMeter.deviceName,
deviceType: activeMeter.deviceType,
usageAnalysisType: activeMeter.usageAnalysisType,
installedTime: activeMeter.installedTime,
});
setDeviceForm(emptyDeviceData);
setErrors({});
setShowModal(true);
}}
<button
onClick={openEditModal}
disabled={isMockMode || !activeMeter}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"
>
@@ -373,7 +276,7 @@ export default function MetersPage({
<input
className="bg-white rounded-lg shadow px-4 py-2 text-sm"
placeholder="Search by meter name, serial number, device ID, area, device type, or meter status..."
placeholder="Buscar por nombre, serial, ubicación o concentrador..."
value={search}
onChange={(e) => setSearch(e.target.value)}
disabled={isMockMode || !m.selectedProject}
@@ -392,8 +295,8 @@ export default function MetersPage({
open={confirmOpen}
title="Eliminar medidor"
message={`¿Estás seguro que quieres eliminar "${
activeMeter?.meterName ?? "este medidor"
}" (${activeMeter?.meterSerialNumber ?? "—"})? Esta acción no se puede deshacer.`}
activeMeter?.name ?? "este medidor"
}" (${activeMeter?.serialNumber ?? "—"})? Esta acción no se puede deshacer.`}
confirmText="Eliminar"
cancelText="Cancelar"
danger
@@ -416,18 +319,25 @@ export default function MetersPage({
editingId={editingId}
form={form}
setForm={setForm}
deviceForm={deviceForm}
setDeviceForm={setDeviceForm}
errors={errors}
setErrors={setErrors}
onClose={() => {
setShowModal(false);
setDeviceForm(emptyDeviceData);
setErrors({});
}}
onSave={handleSave}
/>
)}
{showBulkUpload && (
<MetersBulkUploadModal
onClose={() => setShowBulkUpload(false)}
onSuccess={() => {
m.loadMeters();
setShowBulkUpload(false);
}}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,210 @@
import { useState, useRef } from "react";
import { Upload, Download, X, AlertCircle, CheckCircle } from "lucide-react";
import { bulkUploadMeters, downloadMeterTemplate, type BulkUploadResult } from "../../api/meters";
type Props = {
onClose: () => void;
onSuccess: () => void;
};
export default function MetersBulkUploadModal({ onClose, onSuccess }: Props) {
const [file, setFile] = useState<File | null>(null);
const [uploading, setUploading] = useState(false);
const [result, setResult] = useState<BulkUploadResult | null>(null);
const [error, setError] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0];
if (selectedFile) {
// Validate file type
const validTypes = [
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-excel",
];
if (!validTypes.includes(selectedFile.type)) {
setError("Solo se permiten archivos Excel (.xlsx, .xls)");
return;
}
setFile(selectedFile);
setError(null);
setResult(null);
}
};
const handleUpload = async () => {
if (!file) return;
setUploading(true);
setError(null);
setResult(null);
try {
const uploadResult = await bulkUploadMeters(file);
setResult(uploadResult);
if (uploadResult.data.inserted > 0) {
onSuccess();
}
} catch (err) {
setError(err instanceof Error ? err.message : "Error en la carga");
} finally {
setUploading(false);
}
};
const handleDownloadTemplate = async () => {
try {
await downloadMeterTemplate();
} catch (err) {
setError(err instanceof Error ? err.message : "Error descargando plantilla");
}
};
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
<div className="bg-white rounded-xl p-6 w-[600px] max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-center mb-4">
<h2 className="text-lg font-semibold">Carga Masiva de Medidores</h2>
<button onClick={onClose} className="text-gray-500 hover:text-gray-700">
<X size={20} />
</button>
</div>
{/* Instructions */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
<h3 className="font-medium text-blue-800 mb-2">Instrucciones:</h3>
<ol className="text-sm text-blue-700 space-y-1 list-decimal list-inside">
<li>Descarga la plantilla Excel con el formato correcto</li>
<li>Llena los datos de los medidores (serial_number, name y concentrator_serial son obligatorios)</li>
<li>El concentrator_serial debe coincidir con un concentrador existente</li>
<li>Sube el archivo Excel completado</li>
</ol>
</div>
{/* Download Template Button */}
<button
onClick={handleDownloadTemplate}
className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 mb-4"
>
<Download size={16} />
Descargar Plantilla Excel
</button>
{/* File Input */}
<div className="border-2 border-dashed border-gray-300 rounded-lg p-6 mb-4 text-center">
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
accept=".xlsx,.xls"
className="hidden"
/>
{file ? (
<div className="flex items-center justify-center gap-2">
<CheckCircle className="text-green-500" size={20} />
<span className="text-gray-700">{file.name}</span>
<button
onClick={() => {
setFile(null);
setResult(null);
if (fileInputRef.current) fileInputRef.current.value = "";
}}
className="text-red-500 hover:text-red-700 ml-2"
>
<X size={16} />
</button>
</div>
) : (
<div>
<Upload className="mx-auto text-gray-400 mb-2" size={32} />
<p className="text-gray-600 mb-2">
Arrastra un archivo Excel aquí o
</p>
<button
onClick={() => fileInputRef.current?.click()}
className="text-blue-600 hover:text-blue-800 font-medium"
>
selecciona un archivo
</button>
</div>
)}
</div>
{/* Error Message */}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4 flex items-start gap-2">
<AlertCircle className="text-red-500 shrink-0" size={20} />
<p className="text-red-700 text-sm">{error}</p>
</div>
)}
{/* Upload Result */}
{result && (
<div
className={`border rounded-lg p-4 mb-4 ${
result.success
? "bg-green-50 border-green-200"
: "bg-yellow-50 border-yellow-200"
}`}
>
<h4 className="font-medium mb-2">
{result.success ? "Carga completada" : "Carga completada con errores"}
</h4>
<div className="text-sm space-y-1">
<p>Total de filas: {result.data.totalRows}</p>
<p className="text-green-600">Insertados: {result.data.inserted}</p>
{result.data.failed > 0 && (
<p className="text-red-600">Fallidos: {result.data.failed}</p>
)}
</div>
{/* Error Details */}
{result.data.errors.length > 0 && (
<div className="mt-3">
<h5 className="font-medium text-sm mb-2">Errores:</h5>
<div className="max-h-40 overflow-y-auto bg-white rounded border p-2">
{result.data.errors.map((err, idx) => (
<div key={idx} className="text-xs text-red-600 py-1 border-b last:border-0">
Fila {err.row}: {err.error}
</div>
))}
</div>
</div>
)}
</div>
)}
{/* Actions */}
<div className="flex justify-end gap-2 pt-3 border-t">
<button
onClick={onClose}
className="px-4 py-2 rounded hover:bg-gray-100"
>
{result ? "Cerrar" : "Cancelar"}
</button>
{!result && (
<button
onClick={handleUpload}
disabled={!file || uploading}
className="flex items-center gap-2 bg-[#4c5f9e] text-white px-4 py-2 rounded hover:bg-[#3d4d7e] disabled:opacity-50 disabled:cursor-not-allowed"
>
{uploading ? (
<>
<span className="animate-spin"></span>
Cargando...
</>
) : (
<>
<Upload size={16} />
Cargar Medidores
</>
)}
</button>
)}
</div>
</div>
</div>
);
}

View File

@@ -1,15 +1,13 @@
import type React from "react";
import type { Meter } from "../../api/meters";
import type { DeviceData } from "./MeterPage";
import { useEffect, useState } from "react";
import type { MeterInput } from "../../api/meters";
import { fetchConcentrators, type Concentrator } from "../../api/concentrators";
type Props = {
editingId: string | null;
form: Omit<Meter, "id">;
setForm: React.Dispatch<React.SetStateAction<Omit<Meter, "id">>>;
deviceForm: DeviceData;
setDeviceForm: React.Dispatch<React.SetStateAction<DeviceData>>;
form: MeterInput;
setForm: React.Dispatch<React.SetStateAction<MeterInput>>;
errors: Record<string, boolean>;
setErrors: React.Dispatch<React.SetStateAction<Record<string, boolean>>>;
@@ -22,245 +20,183 @@ export default function MetersModal({
editingId,
form,
setForm,
deviceForm,
setDeviceForm,
errors,
setErrors,
onClose,
onSave,
}: Props) {
const title = editingId ? "Edit Meter" : "Add Meter";
const title = editingId ? "Editar Medidor" : "Agregar Medidor";
const [concentrators, setConcentrators] = useState<Concentrator[]>([]);
const [loadingConcentrators, setLoadingConcentrators] = useState(true);
// Load concentrators for the dropdown
useEffect(() => {
const load = async () => {
try {
const data = await fetchConcentrators();
setConcentrators(data);
} catch (error) {
console.error("Error loading concentrators:", error);
} finally {
setLoadingConcentrators(false);
}
};
load();
}, []);
return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
<div className="bg-white rounded-xl p-6 w-[700px] max-h-[90vh] overflow-y-auto space-y-4">
<div className="bg-white rounded-xl p-6 w-[500px] max-h-[90vh] overflow-y-auto space-y-4">
<h2 className="text-lg font-semibold">{title}</h2>
{/* FORM */}
<div className="space-y-3">
<h3 className="text-sm font-semibold text-gray-700 border-b pb-2">
Meter Information
Información del Medidor
</h3>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm text-gray-600 mb-1">Serial *</label>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["areaName"] ? "border-red-500" : ""
errors["serialNumber"] ? "border-red-500" : ""
}`}
placeholder="Area Name *"
value={form.areaName}
placeholder="Número de serie"
value={form.serialNumber}
onChange={(e) => {
setForm({ ...form, areaName: e.target.value });
if (errors["areaName"]) setErrors({ ...errors, areaName: false });
setForm({ ...form, serialNumber: e.target.value });
if (errors["serialNumber"]) setErrors({ ...errors, serialNumber: false });
}}
required
/>
{errors["areaName"] && <p className="text-red-500 text-xs mt-1">This field is required</p>}
</div>
<div>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Account Number (optional)"
value={form.accountNumber ?? ""}
onChange={(e) =>
setForm({ ...form, accountNumber: e.target.value || null })
}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="User Name (optional)"
value={form.userName ?? ""}
onChange={(e) =>
setForm({ ...form, userName: e.target.value || null })
}
/>
</div>
<div>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="User Address (optional)"
value={form.userAddress ?? ""}
onChange={(e) =>
setForm({ ...form, userAddress: e.target.value || null })
}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["meterSerialNumber"] ? "border-red-500" : ""
}`}
placeholder="Meter S/N *"
value={form.meterSerialNumber}
onChange={(e) => {
setForm({ ...form, meterSerialNumber: e.target.value });
if (errors["meterSerialNumber"])
setErrors({ ...errors, meterSerialNumber: false });
}}
required
/>
{errors["meterSerialNumber"] && (
<p className="text-red-500 text-xs mt-1">This field is required</p>
{errors["serialNumber"] && (
<p className="text-red-500 text-xs mt-1">Campo requerido</p>
)}
</div>
<div>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["meterName"] ? "border-red-500" : ""
}`}
placeholder="Meter Name *"
value={form.meterName}
onChange={(e) => {
setForm({ ...form, meterName: e.target.value });
if (errors["meterName"]) setErrors({ ...errors, meterName: false });
}}
required
/>
{errors["meterName"] && <p className="text-red-500 text-xs mt-1">This field is required</p>}
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["protocolType"] ? "border-red-500" : ""
}`}
placeholder="Protocol Type *"
value={form.protocolType}
onChange={(e) => {
setForm({ ...form, protocolType: e.target.value });
if (errors["protocolType"]) setErrors({ ...errors, protocolType: false });
}}
required
/>
{errors["protocolType"] && <p className="text-red-500 text-xs mt-1">This field is required</p>}
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Meter ID</label>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Device ID (optional)"
value={form.deviceId ?? ""}
onChange={(e) => setForm({ ...form, deviceId: e.target.value || "" })}
placeholder="ID del medidor (opcional)"
value={form.meterId ?? ""}
onChange={(e) => setForm({ ...form, meterId: e.target.value || undefined })}
/>
</div>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Nombre *</label>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["deviceName"] ? "border-red-500" : ""
errors["name"] ? "border-red-500" : ""
}`}
placeholder="Device Name *"
value={form.deviceName}
placeholder="Nombre del medidor"
value={form.name}
onChange={(e) => {
setForm({ ...form, deviceName: e.target.value });
if (errors["deviceName"]) setErrors({ ...errors, deviceName: false });
setForm({ ...form, name: e.target.value });
if (errors["name"]) setErrors({ ...errors, name: false });
}}
required
/>
{errors["deviceName"] && <p className="text-red-500 text-xs mt-1">This field is required</p>}
{errors["name"] && <p className="text-red-500 text-xs mt-1">Campo requerido</p>}
</div>
</div>
{/* DEVICE CONFIG */}
<div className="space-y-3 pt-4">
<h3 className="text-sm font-semibold text-gray-700 border-b pb-2">
Device Configuration
</h3>
<div>
<label className="block text-sm text-gray-600 mb-1">Concentrador *</label>
<select
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["concentratorId"] ? "border-red-500" : ""
}`}
value={form.concentratorId}
onChange={(e) => {
setForm({ ...form, concentratorId: e.target.value });
if (errors["concentratorId"]) setErrors({ ...errors, concentratorId: false });
}}
disabled={loadingConcentrators}
required
>
<option value="">
{loadingConcentrators ? "Cargando..." : "Selecciona un concentrador"}
</option>
{concentrators.map((c) => (
<option key={c.id} value={c.id}>
{c.name} ({c.serialNumber})
</option>
))}
</select>
{errors["concentratorId"] && (
<p className="text-red-500 text-xs mt-1">Selecciona un concentrador</p>
)}
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Ubicación</label>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Ubicación del medidor (opcional)"
value={form.location ?? ""}
onChange={(e) => setForm({ ...form, location: e.target.value || undefined })}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<input
type="number"
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Device ID"] ? "border-red-500" : ""
}`}
placeholder="Device ID *"
value={deviceForm["Device ID"] || ""}
onChange={(e) => {
setDeviceForm({ ...deviceForm, "Device ID": parseInt(e.target.value) || 0 });
if (errors["Device ID"]) setErrors({ ...errors, "Device ID": false });
}}
required
min={1}
/>
{errors["Device ID"] && <p className="text-red-500 text-xs mt-1">This field is required</p>}
<label className="block text-sm text-gray-600 mb-1">Tipo</label>
<select
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
value={form.type ?? "LORA"}
onChange={(e) => setForm({ ...form, type: e.target.value })}
>
<option value="LORA">LoRa</option>
<option value="LORAWAN">LoRaWAN</option>
<option value="GRANDES">Grandes Consumidores</option>
</select>
</div>
<div>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Device EUI"] ? "border-red-500" : ""
}`}
placeholder="Device EUI *"
value={deviceForm["Device EUI"]}
onChange={(e) => {
setDeviceForm({ ...deviceForm, "Device EUI": e.target.value });
if (errors["Device EUI"]) setErrors({ ...errors, "Device EUI": false });
}}
required
/>
{errors["Device EUI"] && <p className="text-red-500 text-xs mt-1">This field is required</p>}
<label className="block text-sm text-gray-600 mb-1">Estado</label>
<select
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
value={form.status ?? "ACTIVE"}
onChange={(e) => setForm({ ...form, status: e.target.value })}
>
<option value="ACTIVE">Activo</option>
<option value="INACTIVE">Inactivo</option>
<option value="MAINTENANCE">Mantenimiento</option>
<option value="FAULTY">Averiado</option>
<option value="REPLACED">Reemplazado</option>
</select>
</div>
</div>
<div>
<label className="block text-sm text-gray-600 mb-1">Fecha de Instalación</label>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["Join EUI"] ? "border-red-500" : ""
}`}
placeholder="Join EUI *"
value={deviceForm["Join EUI"]}
onChange={(e) => {
setDeviceForm({ ...deviceForm, "Join EUI": e.target.value });
if (errors["Join EUI"]) setErrors({ ...errors, "Join EUI": false });
}}
required
type="date"
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
value={form.installationDate?.split("T")[0] ?? ""}
onChange={(e) =>
setForm({
...form,
installationDate: e.target.value ? new Date(e.target.value).toISOString() : undefined,
})
}
/>
{errors["Join EUI"] && <p className="text-red-500 text-xs mt-1">This field is required</p>}
</div>
<div>
<input
className={`w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
errors["AppKey"] ? "border-red-500" : ""
}`}
placeholder="AppKey *"
value={deviceForm["AppKey"]}
onChange={(e) => {
setDeviceForm({ ...deviceForm, AppKey: e.target.value });
if (errors["AppKey"]) setErrors({ ...errors, AppKey: false });
}}
required
/>
{errors["AppKey"] && <p className="text-red-500 text-xs mt-1">This field is required</p>}
</div>
</div>
{/* ACTIONS */}
<div className="flex justify-end gap-2 pt-3 border-t">
<button onClick={onClose} className="px-4 py-2 rounded hover:bg-gray-100">
Cancel
Cancelar
</button>
<button
onClick={onSave}
className="bg-[#4c5f9e] text-white px-4 py-2 rounded hover:bg-[#3d4d7e]"
>
Save
Guardar
</button>
</div>
</div>

View File

@@ -28,15 +28,51 @@ export default function MetersTable({
title="Meters"
isLoading={isLoading}
columns={[
{ title: "Area Name", field: "areaName", render: (r: any) => r.areaName || "-" },
{ title: "Account Number", field: "accountNumber", render: (r: any) => r.accountNumber || "-" },
{ title: "User Name", field: "userName", render: (r: any) => r.userName || "-" },
{ title: "User Address", field: "userAddress", render: (r: any) => r.userAddress || "-" },
{ title: "Meter S/N", field: "meterSerialNumber", render: (r: any) => r.meterSerialNumber || "-" },
{ title: "Meter Name", field: "meterName", render: (r: any) => r.meterName || "-" },
{ title: "Protocol Type", field: "protocolType", render: (r: any) => r.protocolType || "-" },
{ title: "Device ID", field: "deviceId", render: (r: any) => r.deviceId || "-" },
{ title: "Device Name", field: "deviceName", render: (r: any) => r.deviceName || "-" },
{ title: "Serial", field: "serialNumber", render: (r: Meter) => r.serialNumber || "-" },
{ title: "Meter ID", field: "meterId", render: (r: Meter) => r.meterId || "-" },
{ title: "Nombre", field: "name", render: (r: Meter) => r.name || "-" },
{ title: "Ubicación", field: "location", render: (r: Meter) => r.location || "-" },
{
title: "Tipo",
field: "type",
render: (r: Meter) => {
const typeLabels: Record<string, string> = {
LORA: "LoRa",
LORAWAN: "LoRaWAN",
GRANDES: "Grandes Consumidores",
};
const typeColors: Record<string, string> = {
LORA: "text-green-600 border-green-600",
LORAWAN: "text-purple-600 border-purple-600",
GRANDES: "text-orange-600 border-orange-600",
};
const type = r.type || "LORA";
return (
<span
className={`px-3 py-1 rounded-full text-xs font-semibold border ${typeColors[type] || "text-gray-600 border-gray-600"}`}
>
{typeLabels[type] || type}
</span>
);
},
},
{
title: "Estado",
field: "status",
render: (r: Meter) => (
<span
className={`px-3 py-1 rounded-full text-xs font-semibold border ${
r.status === "ACTIVE"
? "text-blue-600 border-blue-600"
: "text-red-600 border-red-600"
}`}
>
{r.status || "-"}
</span>
),
},
{ title: "Concentrador", field: "concentratorName", render: (r: Meter) => r.concentratorName || "-" },
{ title: "Última Lectura", field: "lastReadingValue", render: (r: Meter) => r.lastReadingValue?.toFixed(2) ?? "-" },
]}
data={disabled ? [] : data}
onRowClick={(_, rowData) => onRowClick(rowData as Meter)}

View File

@@ -1,5 +1,6 @@
import { useEffect, useMemo, useState } from "react";
import { fetchMeters, type Meter } from "../../api/meters";
import { fetchProjects } from "../../api/projects";
type UseMetersArgs = {
initialProject?: string;
@@ -15,37 +16,43 @@ export function useMeters({ initialProject }: UseMetersArgs) {
const [filteredMeters, setFilteredMeters] = useState<Meter[]>([]);
const [loadingMeters, setLoadingMeters] = useState(true);
const loadMeters = async () => {
setLoadingMeters(true);
const loadProjects = async () => {
setLoadingProjects(true);
try {
const data = await fetchMeters();
const projectsArray = [...new Set(data.map((r) => r.areaName))]
.filter(Boolean) as string[];
setAllProjects(projectsArray);
setMeters(data);
const projects = await fetchProjects();
const projectNames = projects.map((p) => p.name);
setAllProjects(projectNames);
setSelectedProject((prev) => {
if (prev) return prev;
if (initialProject) return initialProject;
return projectsArray[0] ?? "";
return projectNames[0] ?? "";
});
} catch (error) {
console.error("Error loading meters:", error);
console.error("Error loading projects:", error);
setAllProjects([]);
setMeters([]);
setSelectedProject("");
} finally {
setLoadingMeters(false);
setLoadingProjects(false);
}
};
// init
const loadMeters = async () => {
setLoadingMeters(true);
try {
const data = await fetchMeters();
setMeters(data);
} catch (error) {
console.error("Error loading meters:", error);
setMeters([]);
} finally {
setLoadingMeters(false);
}
};
// init - load projects and meters
useEffect(() => {
loadProjects();
loadMeters();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -61,13 +68,13 @@ export function useMeters({ initialProject }: UseMetersArgs) {
setFilteredMeters([]);
return;
}
setFilteredMeters(meters.filter((m) => m.areaName === selectedProject));
setFilteredMeters(meters.filter((m) => m.projectName === selectedProject));
}, [selectedProject, meters]);
const projectsCounts = useMemo(() => {
return meters.reduce<Record<string, number>>((acc, m) => {
const area = m.areaName ?? "SIN PROYECTO";
acc[area] = (acc[area] ?? 0) + 1;
const project = m.projectName ?? "SIN PROYECTO";
acc[project] = (acc[project] ?? 0) + 1;
return acc;
}, {});
}, [meters]);

View File

@@ -3,13 +3,13 @@ import { Plus, Trash2, Pencil, RefreshCcw } from "lucide-react";
import MaterialTable from "@material-table/core";
import {
Project,
ProjectInput,
fetchProjects,
createProject as apiCreateProject,
updateProject as apiUpdateProject,
deleteProject as apiDeleteProject,
} from "../../api/projects";
/* ================= COMPONENT ================= */
export default function ProjectsPage() {
const [projects, setProjects] = useState<Project[]>([]);
const [loading, setLoading] = useState(true);
@@ -19,20 +19,16 @@ export default function ProjectsPage() {
const [showModal, setShowModal] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null);
const emptyProject: Omit<Project, "id"> = {
const emptyForm: ProjectInput = {
name: "",
description: "",
areaName: "",
deviceSN: "",
deviceName: "",
deviceType: "",
deviceStatus: "ACTIVE",
operator: "",
installedTime: "",
communicationTime: "",
location: "",
status: "ACTIVE",
};
const [form, setForm] = useState<Omit<Project, "id">>(emptyProject);
const [form, setForm] = useState<ProjectInput>(emptyForm);
/* ================= LOAD ================= */
const loadProjects = async () => {
setLoading(true);
try {
@@ -50,7 +46,6 @@ export default function ProjectsPage() {
loadProjects();
}, []);
const handleSave = async () => {
try {
if (editingId) {
@@ -65,7 +60,7 @@ export default function ProjectsPage() {
setShowModal(false);
setEditingId(null);
setForm(emptyProject);
setForm(emptyForm);
setActiveProject(null);
} catch (error) {
console.error("Error saving project:", error);
@@ -81,7 +76,7 @@ export default function ProjectsPage() {
if (!activeProject) return;
const confirmDelete = window.confirm(
`Are you sure you want to delete the project "${activeProject.deviceName}"?`
`¿Estás seguro que quieres eliminar el proyecto "${activeProject.name}"?`
);
if (!confirmDelete) return;
@@ -100,14 +95,31 @@ export default function ProjectsPage() {
}
};
/* ================= FILTER ================= */
const openEditModal = () => {
if (!activeProject) return;
setEditingId(activeProject.id);
setForm({
name: activeProject.name,
description: activeProject.description ?? "",
areaName: activeProject.areaName,
location: activeProject.location ?? "",
status: activeProject.status,
});
setShowModal(true);
};
const openCreateModal = () => {
setForm(emptyForm);
setEditingId(null);
setShowModal(true);
};
const filtered = projects.filter((p) =>
`${p.areaName} ${p.deviceName} ${p.deviceSN}`
`${p.name} ${p.areaName} ${p.description ?? ""}`
.toLowerCase()
.includes(search.toLowerCase())
);
/* ================= UI ================= */
return (
<div className="flex gap-6 p-6 w-full bg-gray-100">
<div className="flex-1 flex flex-col gap-6">
@@ -120,41 +132,23 @@ export default function ProjectsPage() {
>
<div>
<h1 className="text-2xl font-bold">Project Management</h1>
<p className="text-sm text-blue-100">Projects registered</p>
<p className="text-sm text-blue-100">Proyectos registrados</p>
</div>
<div className="flex gap-3">
<button
onClick={() => {
setForm(emptyProject);
setEditingId(null);
setShowModal(true);
}}
onClick={openCreateModal}
className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg"
>
<Plus size={16} /> Add
<Plus size={16} /> Agregar
</button>
<button
onClick={() => {
if (!activeProject) return;
setEditingId(activeProject.id);
setForm({
areaName: activeProject.areaName,
deviceSN: activeProject.deviceSN,
deviceName: activeProject.deviceName,
deviceType: activeProject.deviceType,
deviceStatus: activeProject.deviceStatus,
operator: activeProject.operator,
installedTime: activeProject.installedTime,
communicationTime: activeProject.communicationTime,
});
setShowModal(true);
}}
onClick={openEditModal}
disabled={!activeProject}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"
>
<Pencil size={16} /> Edit
<Pencil size={16} /> Editar
</button>
<button
@@ -162,14 +156,14 @@ export default function ProjectsPage() {
disabled={!activeProject}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"
>
<Trash2 size={16} /> Delete
<Trash2 size={16} /> Eliminar
</button>
<button
onClick={loadProjects}
className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg"
>
<RefreshCcw size={16} /> Refresh
<RefreshCcw size={16} /> Actualizar
</button>
</div>
</div>
@@ -177,38 +171,40 @@ export default function ProjectsPage() {
{/* SEARCH */}
<input
className="bg-white rounded-lg shadow px-4 py-2 text-sm"
placeholder="Search project..."
placeholder="Buscar proyecto..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
{/* TABLE */}
<MaterialTable
title="Projects"
title="Proyectos"
isLoading={loading}
columns={[
{ title: "Area Name", field: "areaName" },
{ title: "Device S/N", field: "deviceSN" },
{ title: "Device Name", field: "deviceName" },
{ title: "Device Type", field: "deviceType" },
{ title: "Nombre", field: "name" },
{ title: "Area", field: "areaName" },
{ title: "Descripción", field: "description", render: (rowData: Project) => rowData.description || "-" },
{ title: "Ubicación", field: "location", render: (rowData: Project) => rowData.location || "-" },
{
title: "Status",
field: "deviceStatus",
render: (rowData) => (
title: "Estado",
field: "status",
render: (rowData: Project) => (
<span
className={`px-3 py-1 rounded-full text-xs font-semibold border ${
rowData.deviceStatus === "ACTIVE"
rowData.status === "ACTIVE"
? "text-blue-600 border-blue-600"
: "text-red-600 border-red-600"
}`}
>
{rowData.deviceStatus}
{rowData.status}
</span>
),
},
{ title: "Operator", field: "operator" },
{ title: "Installed Time", field: "installedTime" },
{ title: "Communication Name", field: "communicationTime" },
{
title: "Creado",
field: "createdAt",
render: (rowData: Project) => new Date(rowData.createdAt).toLocaleDateString(),
},
]}
data={filtered}
onRowClick={(_, rowData) => setActiveProject(rowData as Project)}
@@ -226,8 +222,8 @@ export default function ProjectsPage() {
localization={{
body: {
emptyDataSourceMessage: loading
? "Loading projects..."
: "No projects found. Click 'Add' to create your first project.",
? "Cargando proyectos..."
: "No hay proyectos. Haz clic en 'Agregar' para crear uno.",
},
}}
/>
@@ -235,85 +231,78 @@ export default function ProjectsPage() {
{/* MODAL */}
{showModal && (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center">
<div className="bg-white rounded-xl p-6 w-96 space-y-3">
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
<div className="bg-white rounded-xl p-6 w-[450px] space-y-4">
<h2 className="text-lg font-semibold">
{editingId ? "Edit Project" : "Add Project"}
{editingId ? "Editar Proyecto" : "Agregar Proyecto"}
</h2>
<input
className="w-full border px-3 py-2 rounded"
placeholder="Area Name"
value={form.areaName}
onChange={(e) => setForm({ ...form, areaName: e.target.value })}
/>
<div>
<label className="block text-sm text-gray-600 mb-1">Nombre *</label>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Nombre del proyecto"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
/>
</div>
<input
className="w-full border px-3 py-2 rounded"
placeholder="Device S/N"
value={form.deviceSN}
onChange={(e) => setForm({ ...form, deviceSN: e.target.value })}
/>
<div>
<label className="block text-sm text-gray-600 mb-1">Area *</label>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Nombre del area"
value={form.areaName}
onChange={(e) => setForm({ ...form, areaName: e.target.value })}
/>
</div>
<input
className="w-full border px-3 py-2 rounded"
placeholder="Device Name"
value={form.deviceName}
onChange={(e) => setForm({ ...form, deviceName: e.target.value })}
/>
<div>
<label className="block text-sm text-gray-600 mb-1">Descripción</label>
<textarea
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Descripción del proyecto (opcional)"
rows={3}
value={form.description ?? ""}
onChange={(e) => setForm({ ...form, description: e.target.value || undefined })}
/>
</div>
<input
className="w-full border px-3 py-2 rounded"
placeholder="Device Type"
value={form.deviceType}
onChange={(e) => setForm({ ...form, deviceType: e.target.value })}
/>
<div>
<label className="block text-sm text-gray-600 mb-1">Ubicación</label>
<input
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Ubicación (opcional)"
value={form.location ?? ""}
onChange={(e) => setForm({ ...form, location: e.target.value || undefined })}
/>
</div>
<input
className="w-full border px-3 py-2 rounded"
placeholder="Operator"
value={form.operator}
onChange={(e) => setForm({ ...form, operator: e.target.value })}
/>
<div>
<label className="block text-sm text-gray-600 mb-1">Estado</label>
<select
className="w-full border px-3 py-2 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent"
value={form.status ?? "ACTIVE"}
onChange={(e) => setForm({ ...form, status: e.target.value })}
>
<option value="ACTIVE">Activo</option>
<option value="INACTIVE">Inactivo</option>
<option value="SUSPENDED">Suspendido</option>
</select>
</div>
<input
className="w-full border px-3 py-2 rounded"
placeholder="Installed Time"
value={form.installedTime}
onChange={(e) =>
setForm({ ...form, installedTime: e.target.value })
}
/>
<input
className="w-full border px-3 py-2 rounded"
placeholder="Communication Time"
value={form.communicationTime}
onChange={(e) =>
setForm({ ...form, communicationTime: e.target.value })
}
/>
<button
onClick={() =>
setForm({
...form,
deviceStatus:
form.deviceStatus === "ACTIVE" ? "INACTIVE" : "ACTIVE",
})
}
className="w-full border rounded px-3 py-2"
>
Status: {form.deviceStatus}
</button>
<div className="flex justify-end gap-2 pt-3">
<button onClick={() => setShowModal(false)}>Cancel</button>
<div className="flex justify-end gap-2 pt-3 border-t">
<button
onClick={() => setShowModal(false)}
className="px-4 py-2 rounded hover:bg-gray-100"
>
Cancelar
</button>
<button
onClick={handleSave}
className="bg-[#4c5f9e] text-white px-4 py-2 rounded"
className="bg-[#4c5f9e] text-white px-4 py-2 rounded hover:bg-[#3d4d7e]"
>
Save
Guardar
</button>
</div>
</div>