Agregar carga masiva de lecturas y corregir manejo de respuestas paginadas
- Implementar carga masiva de lecturas via Excel (backend y frontend) - Corregir cliente API para manejar respuestas con paginación - Eliminar referencias a device_id (columna inexistente) - Cambiar areaName por meterLocation en lecturas - Actualizar fetchProjects y fetchConcentrators para paginación - Agregar documentación del estado actual y cambios Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,6 +12,7 @@ import {
|
||||
Filter,
|
||||
X,
|
||||
Activity,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
fetchReadings,
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
type Pagination,
|
||||
} from "../../api/readings";
|
||||
import { fetchProjects, type Project } from "../../api/projects";
|
||||
import ReadingsBulkUploadModal from "./ReadingsBulkUploadModal";
|
||||
|
||||
export default function ConsumptionPage() {
|
||||
const [readings, setReadings] = useState<MeterReading[]>([]);
|
||||
@@ -41,6 +43,7 @@ export default function ConsumptionPage() {
|
||||
const [endDate, setEndDate] = useState<string>("");
|
||||
const [search, setSearch] = useState<string>("");
|
||||
const [showFilters, setShowFilters] = useState(false);
|
||||
const [showBulkUpload, setShowBulkUpload] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const loadProjects = async () => {
|
||||
@@ -92,7 +95,7 @@ export default function ConsumptionPage() {
|
||||
(r) =>
|
||||
(r.meterSerialNumber ?? "").toLowerCase().includes(q) ||
|
||||
(r.meterName ?? "").toLowerCase().includes(q) ||
|
||||
(r.areaName ?? "").toLowerCase().includes(q) ||
|
||||
(r.meterLocation ?? "").toLowerCase().includes(q) ||
|
||||
String(r.readingValue).includes(q)
|
||||
);
|
||||
}, [readings, search]);
|
||||
@@ -121,12 +124,12 @@ export default function ConsumptionPage() {
|
||||
};
|
||||
|
||||
const exportToCSV = () => {
|
||||
const headers = ["Fecha", "Medidor", "Serial", "Área", "Valor", "Tipo", "Batería", "Señal"];
|
||||
const headers = ["Fecha", "Medidor", "Serial", "Ubicación", "Valor", "Tipo", "Batería", "Señal"];
|
||||
const rows = filteredReadings.map((r) => [
|
||||
formatFullDate(r.receivedAt),
|
||||
r.meterName || "—",
|
||||
r.meterSerialNumber || "—",
|
||||
r.areaName || "—",
|
||||
r.meterLocation || "—",
|
||||
r.readingValue.toFixed(2),
|
||||
r.readingType || "—",
|
||||
r.batteryLevel !== null ? `${r.batteryLevel}%` : "—",
|
||||
@@ -162,6 +165,13 @@ export default function ConsumptionPage() {
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setShowBulkUpload(true)}
|
||||
className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-emerald-500 to-teal-600 rounded-xl hover:from-emerald-600 hover:to-teal-700 transition-all shadow-sm shadow-emerald-500/25"
|
||||
>
|
||||
<Upload size={16} />
|
||||
Carga Masiva
|
||||
</button>
|
||||
<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"
|
||||
@@ -353,7 +363,7 @@ export default function ConsumptionPage() {
|
||||
Serial
|
||||
</th>
|
||||
<th className="px-5 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">
|
||||
Área
|
||||
Ubicación
|
||||
</th>
|
||||
<th className="px-5 py-3 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">
|
||||
Consumo
|
||||
@@ -415,7 +425,7 @@ export default function ConsumptionPage() {
|
||||
</code>
|
||||
</td>
|
||||
<td className="px-5 py-3.5">
|
||||
<span className="text-sm text-slate-600">{reading.areaName || "—"}</span>
|
||||
<span className="text-sm text-slate-600">{reading.meterLocation || "—"}</span>
|
||||
</td>
|
||||
<td className="px-5 py-3.5 text-right">
|
||||
<span className="text-sm font-semibold text-slate-800 tabular-nums">
|
||||
@@ -440,6 +450,16 @@ export default function ConsumptionPage() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showBulkUpload && (
|
||||
<ReadingsBulkUploadModal
|
||||
onClose={() => setShowBulkUpload(false)}
|
||||
onSuccess={() => {
|
||||
loadData(1);
|
||||
setShowBulkUpload(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
210
src/pages/consumption/ReadingsBulkUploadModal.tsx
Normal file
210
src/pages/consumption/ReadingsBulkUploadModal.tsx
Normal file
@@ -0,0 +1,210 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { Upload, Download, X, AlertCircle, CheckCircle } from "lucide-react";
|
||||
import { bulkUploadReadings, downloadReadingTemplate, type BulkUploadResult } from "../../api/readings";
|
||||
|
||||
type Props = {
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
};
|
||||
|
||||
export default function ReadingsBulkUploadModal({ 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 bulkUploadReadings(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 downloadReadingTemplate();
|
||||
} 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 Lecturas</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 las lecturas (meter_serial y reading_value son obligatorios)</li>
|
||||
<li>El meter_serial debe coincidir con un medidor 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">Insertadas: {result.data.inserted}</p>
|
||||
{result.data.failed > 0 && (
|
||||
<p className="text-red-600">Fallidas: {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 Lecturas
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user