
"use client"; import { useState } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Card, CardContent } from "@/components/ui/card"; import { useToast } from "@/components/ui/use-toast"; import { useOnboardingStore } from "@/stores/workflow/onboarding"; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, } from "recharts"; import { Trash2, Plus } from "lucide-react"; import { useRouter } from "next/navigation"; interface ReadingEntry { id: string; month: string; // formato 'YYYY-MM' value: number | string; // kWh (string no form, number na API) } export default function ConsumptionProfilePage() { const [averageKwh, setAverageKwh] = useState<string>(""); const [readings, setReadings] = useState<ReadingEntry[]>([]); const [loading, setLoading] = useState(false); const { toast } = useToast(); const { setConsumptionProfile, kycData, nextStep } = useOnboardingStore(); const router = useRouter(); // Inicializar com o valor do KYC, se disponível useState(() => { if (kycData?.averageConsumptionKwh) { setAverageKwh(kycData.averageConsumptionKwh.toString()); } }); const addReadingEntry = () => { const now = new Date(); const currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`; setReadings([ ...readings, { id: `reading-${Date.now()}`, month: currentMonth, value: "" }, ]); }; const removeReading = (id: string) => { setReadings(readings.filter((r) => r.id !== id)); }; const updateReading = ( id: string, field: keyof ReadingEntry, value: string ) => { setReadings( readings.map((r) => (r.id === id ? { ...r, [field]: value } : r)) ); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { setLoading(true); // Validar consumo médio if (!averageKwh || isNaN(Number(averageKwh)) || Number(averageKwh) < 0) { toast({ title: "Erro de validação", description: "Consumo médio deve ser um número positivo", variant: "destructive", }); return; } // Preparar leituras válidas const validReadings = readings .filter((r) => r.month && r.value !== "" && !isNaN(Number(r.value))) .map((r) => ({ month: r.month, value: Number(r.value), })); // Enviar para API const res = await fetch("/api/onboard/consumption-profile", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ monthlyAverage: Number(averageKwh), readings: validReadings, }), }); const data = await res.json(); if (!data.success) { throw new Error(data.error || "Erro ao processar perfil de consumo"); } // Atualizar store com o resultado setConsumptionProfile(data.result); toast({ title: "Perfil de consumo analisado", description: "Sua análise de consumo foi concluída com sucesso", }); // Avançar para próxima etapa nextStep(); router.push("/onboard/resumo"); } catch (error: any) { toast({ title: "Erro", description: error.message || "Ocorreu um erro ao analisar o perfil de consumo", variant: "destructive", }); } finally { setLoading(false); } }; // Dados para gráfico const chartData = readings .filter((r) => r.month && r.value !== "" && !isNaN(Number(r.value))) .map((r) => ({ month: r.month, kWh: Number(r.value), })) .sort((a, b) => a.month.localeCompare(b.month)); return ( <div className="container max-w-3xl mx-auto py-8"> <h1 className="text-2xl font-semibold mb-2">Perfil de Consumo</h1> <p className="text-muted-foreground mb-6"> Forneça informações sobre seu consumo mensal para análise personalizada. </p> <Card> <CardContent className="p-6"> <form onSubmit={handleSubmit} className="space-y-6"> {/* Consumo médio */} <div className="space-y-2"> <Label htmlFor="averageKwh">Consumo médio mensal (kWh)</Label> <Input id="averageKwh" type="number" value={averageKwh} onChange={(e) => setAverageKwh(e.target.value)} placeholder="Ex: 250" min="0" required /> <p className="text-xs text-muted-foreground"> Este valor pode ser encontrado em sua conta de energia </p> </div> {/* Histórico (opcional) */} <div className="space-y-3"> <div className="flex justify-between items-center"> <Label>Histórico de consumo (opcional)</Label> <Button type="button" variant="outline" size="sm" onClick={addReadingEntry} > <Plus size={16} className="mr-1" /> Adicionar </Button> </div> {readings.length > 0 && ( <div className="space-y-3"> {readings.map((reading) => ( <div key={reading.id} className="flex gap-3 items-center"> <div className="flex-1"> <Label htmlFor={`month-${reading.id}`} className="sr-only" > Mês </Label> <Input id={`month-${reading.id}`} type="month" value={reading.month} onChange={(e) => updateReading(reading.id, "month", e.target.value) } required /> </div> <div className="flex-1"> <Label htmlFor={`value-${reading.id}`} className="sr-only" > Consumo (kWh) </Label> <Input id={`value-${reading.id}`} type="number" value={reading.value} onChange={(e) => updateReading(reading.id, "value", e.target.value) } placeholder="kWh" min="0" required /> </div> <Button type="button" variant="ghost" size="icon" onClick={() => removeReading(reading.id)} > <Trash2 size={16} /> <span className="sr-only">Remover</span> </Button> </div> ))} </div> )} {readings.length === 0 && ( <p className="text-sm text-muted-foreground"> Adicione leituras de consumo para uma análise mais precisa </p> )} </div> {/* Gráfico de visualização */} {chartData.length >= 2 && ( <div className="pt-4"> <Label className="mb-2 block">Visualização do consumo</Label> <div className="h-64 w-full"> <ResponsiveContainer width="100%" height="100%"> <LineChart data={chartData}> <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="month" tickFormatter={(value) => { const [year, month] = value.split("-"); return `${month}/${year.slice(2)}`; }} /> <YAxis unit=" kWh" /> <Tooltip formatter={(value) => [`${value} kWh`, "Consumo"]} labelFormatter={(label) => { const [year, month] = label.split("-"); const monthNames = [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez", ]; return `${monthNames[parseInt(month) - 1]}/${year}`; }} /> <Line type="monotone" dataKey="kWh" stroke="#8884d8" activeDot={{ r: 8 }} /> </LineChart> </ResponsiveContainer> </div> </div> )} {/* Botões */} <div className="flex justify-between pt-4"> <Button type="button" variant="outline" onClick={() => router.back()} > Voltar </Button> <Button type="submit" disabled={loading || !averageKwh}> {loading ? "Processando..." : "Analisar Perfil de Consumo"} </Button> </div> </form> </CardContent> </Card> </div> ); } - Initial Deployment
fab0b39
verified
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Perfil de Consumo</title> | |
<script src="https://cdn.tailwindcss.com"></script> | |
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> | |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"> | |
<style> | |
body { | |
font-family: 'Inter', sans-serif; | |
} | |
.chart-container { | |
position: relative; | |
height: 300px; | |
width: 100%; | |
} | |
.fade-in { | |
animation: fadeIn 0.3s ease-in-out; | |
} | |
@keyframes fadeIn { | |
from { opacity: 0; transform: translateY(10px); } | |
to { opacity: 1; transform: translateY(0); } | |
} | |
.month-input::-webkit-calendar-picker-indicator { | |
filter: invert(0.5); | |
} | |
.month-input::-webkit-datetime-edit-text { | |
color: #6b7280; | |
} | |
</style> | |
</head> | |
<body class="bg-gray-50 min-h-screen"> | |
<div class="container max-w-3xl mx-auto py-8 px-4"> | |
<div class="mb-6"> | |
<h1 class="text-2xl font-semibold text-gray-800 mb-2">Perfil de Consumo</h1> | |
<p class="text-gray-500"> | |
Forneça informações sobre seu consumo mensal para análise personalizada. | |
</p> | |
</div> | |
<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden"> | |
<div class="p-6"> | |
<form id="consumptionForm" class="space-y-6"> | |
<!-- Average Consumption --> | |
<div class="space-y-2"> | |
<label for="averageKwh" class="block text-sm font-medium text-gray-700">Consumo médio mensal (kWh)</label> | |
<input | |
type="number" | |
id="averageKwh" | |
class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" | |
placeholder="Ex: 250" | |
min="0" | |
required | |
> | |
<p class="text-xs text-gray-500"> | |
Este valor pode ser encontrado em sua conta de energia | |
</p> | |
</div> | |
<!-- Consumption History --> | |
<div class="space-y-3"> | |
<div class="flex justify-between items-center"> | |
<label class="block text-sm font-medium text-gray-700">Histórico de consumo (opcional)</label> | |
<button | |
type="button" | |
id="addReadingBtn" | |
class="inline-flex items-center px-3 py-1.5 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" | |
> | |
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor"> | |
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" /> | |
</svg> | |
Adicionar | |
</button> | |
</div> | |
<div id="readingsContainer" class="space-y-3"> | |
<!-- Readings will be added here --> | |
</div> | |
<div id="noReadingsMessage" class="text-sm text-gray-500"> | |
Adicione leituras de consumo para uma análise mais precisa | |
</div> | |
</div> | |
<!-- Chart Visualization --> | |
<div id="chartContainer" class="pt-4 hidden"> | |
<label class="block text-sm font-medium text-gray-700 mb-2">Visualização do consumo</label> | |
<div class="chart-container"> | |
<canvas id="consumptionChart"></canvas> | |
</div> | |
</div> | |
<!-- Buttons --> | |
<div class="flex justify-between pt-6 border-t border-gray-200"> | |
<button | |
type="button" | |
id="backBtn" | |
class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" | |
> | |
Voltar | |
</button> | |
<button | |
type="submit" | |
id="submitBtn" | |
class="px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed" | |
> | |
Analisar Perfil de Consumo | |
</button> | |
</div> | |
</form> | |
</div> | |
</div> | |
</div> | |
<script> | |
document.addEventListener('DOMContentLoaded', function() { | |
// State | |
let readings = []; | |
let chart = null; | |
// Elements | |
const form = document.getElementById('consumptionForm'); | |
const addReadingBtn = document.getElementById('addReadingBtn'); | |
const readingsContainer = document.getElementById('readingsContainer'); | |
const noReadingsMessage = document.getElementById('noReadingsMessage'); | |
const chartContainer = document.getElementById('chartContainer'); | |
const averageKwhInput = document.getElementById('averageKwh'); | |
const submitBtn = document.getElementById('submitBtn'); | |
const backBtn = document.getElementById('backBtn'); | |
// Initialize with sample data if needed | |
// averageKwhInput.value = '250'; | |
// Add new reading entry | |
addReadingBtn.addEventListener('click', function() { | |
const now = new Date(); | |
const currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`; | |
const readingId = `reading-${Date.now()}`; | |
readings.push({ | |
id: readingId, | |
month: currentMonth, | |
value: '' | |
}); | |
renderReadings(); | |
updateChart(); | |
}); | |
// Render all readings | |
function renderReadings() { | |
readingsContainer.innerHTML = ''; | |
if (readings.length === 0) { | |
noReadingsMessage.classList.remove('hidden'); | |
return; | |
} | |
noReadingsMessage.classList.add('hidden'); | |
readings.forEach(reading => { | |
const readingElement = document.createElement('div'); | |
readingElement.className = 'flex gap-3 items-center fade-in'; | |
readingElement.innerHTML = ` | |
<div class="flex-1"> | |
<input | |
type="month" | |
class="month-input block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" | |
value="${reading.month}" | |
onchange="updateReading('${reading.id}', 'month', this.value)" | |
required | |
> | |
</div> | |
<div class="flex-1"> | |
<input | |
type="number" | |
class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" | |
value="${reading.value}" | |
placeholder="kWh" | |
min="0" | |
onchange="updateReading('${reading.id}', 'value', this.value)" | |
required | |
> | |
</div> | |
<button | |
type="button" | |
class="p-2 rounded-md text-gray-400 hover:text-red-500 hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-500" | |
onclick="removeReading('${reading.id}')" | |
> | |
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"> | |
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /> | |
</svg> | |
</button> | |
`; | |
readingsContainer.appendChild(readingElement); | |
}); | |
} | |
// Update reading value | |
window.updateReading = function(id, field, value) { | |
readings = readings.map(r => r.id === id ? { ...r, [field]: value } : r); | |
updateChart(); | |
}; | |
// Remove reading | |
window.removeReading = function(id) { | |
readings = readings.filter(r => r.id !== id); | |
renderReadings(); | |
updateChart(); | |
}; | |
// Update chart with current data | |
function updateChart() { | |
const validReadings = readings | |
.filter(r => r.month && r.value !== '' && !isNaN(Number(r.value))) | |
.map(r => ({ | |
month: r.month, | |
value: Number(r.value) | |
})) | |
.sort((a, b) => a.month.localeCompare(b.month)); | |
if (validReadings.length >= 2) { | |
chartContainer.classList.remove('hidden'); | |
const ctx = document.getElementById('consumptionChart').getContext('2d'); | |
const labels = validReadings.map(r => { | |
const [year, month] = r.month.split('-'); | |
const monthNames = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']; | |
return `${monthNames[parseInt(month) - 1]}/${year.slice(2)}`; | |
}); | |
const data = validReadings.map(r => r.value); | |
if (chart) { | |
chart.destroy(); | |
} | |
chart = new Chart(ctx, { | |
type: 'line', | |
data: { | |
labels: labels, | |
datasets: [{ | |
label: 'Consumo (kWh)', | |
data: data, | |
backgroundColor: 'rgba(99, 102, 241, 0.1)', | |
borderColor: 'rgba(99, 102, 241, 1)', | |
borderWidth: 2, | |
tension: 0.3, | |
pointBackgroundColor: 'rgba(99, 102, 241, 1)', | |
pointRadius: 4, | |
pointHoverRadius: 6 | |
}] | |
}, | |
options: { | |
responsive: true, | |
maintainAspectRatio: false, | |
scales: { | |
y: { | |
beginAtZero: true, | |
title: { | |
display: true, | |
text: 'kWh' | |
} | |
} | |
}, | |
plugins: { | |
tooltip: { | |
callbacks: { | |
label: function(context) { | |
return `${context.parsed.y} kWh`; | |
} | |
} | |
} | |
} | |
} | |
}); | |
} else { | |
chartContainer.classList.add('hidden'); | |
if (chart) { | |
chart.destroy(); | |
chart = null; | |
} | |
} | |
} | |
// Form submission | |
form.addEventListener('submit', function(e) { | |
e.preventDefault(); | |
// Validate average consumption | |
if (!averageKwhInput.value || isNaN(Number(averageKwhInput.value)) || Number(averageKwhInput.value) < 0) { | |
showToast('Erro de validação', 'Consumo médio deve ser um número positivo', 'error'); | |
return; | |
} | |
// Simulate loading | |
submitBtn.disabled = true; | |
submitBtn.innerHTML = ` | |
<svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"> | |
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle> | |
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path> | |
</svg> | |
Processando... | |
`; | |
// Simulate API call | |
setTimeout(() => { | |
showToast('Perfil de consumo analisado', 'Sua análise de consumo foi concluída com sucesso', 'success'); | |
// Reset button | |
submitBtn.disabled = false; | |
submitBtn.textContent = 'Analisar Perfil de Consumo'; | |
// In a real app, you would redirect here | |
// window.location.href = '/onboard/resumo'; | |
}, 2000); | |
}); | |
// Back button | |
backBtn.addEventListener('click', function() { | |
// In a real app, you would go back | |
// window.history.back(); | |
console.log('Back button clicked'); | |
}); | |
// Show toast notification | |
function showToast(title, message, type) { | |
// In a real app, you would use a proper toast library | |
console.log(`${type.toUpperCase()}: ${title} - ${message}`); | |
alert(`${title}\n${message}`); | |
} | |
}); | |
</script> | |
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=fernando-bold/src-app-auth-onboard-consumo-page-tsx" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body> | |
</html> |