fernando-bold commited on
Commit
fab0b39
·
verified ·
1 Parent(s): b094fef

"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

Browse files
Files changed (2) hide show
  1. README.md +6 -4
  2. index.html +336 -19
README.md CHANGED
@@ -1,10 +1,12 @@
1
  ---
2
- title: Src App Auth Onboard Consumo Page Tsx
3
- emoji: 🌍
4
- colorFrom: gray
5
  colorTo: purple
6
  sdk: static
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: src-app-auth-onboard-consumo-page-tsx
3
+ emoji: 🐳
4
+ colorFrom: blue
5
  colorTo: purple
6
  sdk: static
7
  pinned: false
8
+ tags:
9
+ - deepsite
10
  ---
11
 
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
index.html CHANGED
@@ -1,19 +1,336 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Perfil de Consumo</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
9
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
10
+ <style>
11
+ body {
12
+ font-family: 'Inter', sans-serif;
13
+ }
14
+ .chart-container {
15
+ position: relative;
16
+ height: 300px;
17
+ width: 100%;
18
+ }
19
+ .fade-in {
20
+ animation: fadeIn 0.3s ease-in-out;
21
+ }
22
+ @keyframes fadeIn {
23
+ from { opacity: 0; transform: translateY(10px); }
24
+ to { opacity: 1; transform: translateY(0); }
25
+ }
26
+ .month-input::-webkit-calendar-picker-indicator {
27
+ filter: invert(0.5);
28
+ }
29
+ .month-input::-webkit-datetime-edit-text {
30
+ color: #6b7280;
31
+ }
32
+ </style>
33
+ </head>
34
+ <body class="bg-gray-50 min-h-screen">
35
+ <div class="container max-w-3xl mx-auto py-8 px-4">
36
+ <div class="mb-6">
37
+ <h1 class="text-2xl font-semibold text-gray-800 mb-2">Perfil de Consumo</h1>
38
+ <p class="text-gray-500">
39
+ Forneça informações sobre seu consumo mensal para análise personalizada.
40
+ </p>
41
+ </div>
42
+
43
+ <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
44
+ <div class="p-6">
45
+ <form id="consumptionForm" class="space-y-6">
46
+ <!-- Average Consumption -->
47
+ <div class="space-y-2">
48
+ <label for="averageKwh" class="block text-sm font-medium text-gray-700">Consumo médio mensal (kWh)</label>
49
+ <input
50
+ type="number"
51
+ id="averageKwh"
52
+ 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"
53
+ placeholder="Ex: 250"
54
+ min="0"
55
+ required
56
+ >
57
+ <p class="text-xs text-gray-500">
58
+ Este valor pode ser encontrado em sua conta de energia
59
+ </p>
60
+ </div>
61
+
62
+ <!-- Consumption History -->
63
+ <div class="space-y-3">
64
+ <div class="flex justify-between items-center">
65
+ <label class="block text-sm font-medium text-gray-700">Histórico de consumo (opcional)</label>
66
+ <button
67
+ type="button"
68
+ id="addReadingBtn"
69
+ 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"
70
+ >
71
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
72
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
73
+ </svg>
74
+ Adicionar
75
+ </button>
76
+ </div>
77
+
78
+ <div id="readingsContainer" class="space-y-3">
79
+ <!-- Readings will be added here -->
80
+ </div>
81
+
82
+ <div id="noReadingsMessage" class="text-sm text-gray-500">
83
+ Adicione leituras de consumo para uma análise mais precisa
84
+ </div>
85
+ </div>
86
+
87
+ <!-- Chart Visualization -->
88
+ <div id="chartContainer" class="pt-4 hidden">
89
+ <label class="block text-sm font-medium text-gray-700 mb-2">Visualização do consumo</label>
90
+ <div class="chart-container">
91
+ <canvas id="consumptionChart"></canvas>
92
+ </div>
93
+ </div>
94
+
95
+ <!-- Buttons -->
96
+ <div class="flex justify-between pt-6 border-t border-gray-200">
97
+ <button
98
+ type="button"
99
+ id="backBtn"
100
+ 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"
101
+ >
102
+ Voltar
103
+ </button>
104
+ <button
105
+ type="submit"
106
+ id="submitBtn"
107
+ 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"
108
+ >
109
+ Analisar Perfil de Consumo
110
+ </button>
111
+ </div>
112
+ </form>
113
+ </div>
114
+ </div>
115
+ </div>
116
+
117
+ <script>
118
+ document.addEventListener('DOMContentLoaded', function() {
119
+ // State
120
+ let readings = [];
121
+ let chart = null;
122
+
123
+ // Elements
124
+ const form = document.getElementById('consumptionForm');
125
+ const addReadingBtn = document.getElementById('addReadingBtn');
126
+ const readingsContainer = document.getElementById('readingsContainer');
127
+ const noReadingsMessage = document.getElementById('noReadingsMessage');
128
+ const chartContainer = document.getElementById('chartContainer');
129
+ const averageKwhInput = document.getElementById('averageKwh');
130
+ const submitBtn = document.getElementById('submitBtn');
131
+ const backBtn = document.getElementById('backBtn');
132
+
133
+ // Initialize with sample data if needed
134
+ // averageKwhInput.value = '250';
135
+
136
+ // Add new reading entry
137
+ addReadingBtn.addEventListener('click', function() {
138
+ const now = new Date();
139
+ const currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
140
+
141
+ const readingId = `reading-${Date.now()}`;
142
+ readings.push({
143
+ id: readingId,
144
+ month: currentMonth,
145
+ value: ''
146
+ });
147
+
148
+ renderReadings();
149
+ updateChart();
150
+ });
151
+
152
+ // Render all readings
153
+ function renderReadings() {
154
+ readingsContainer.innerHTML = '';
155
+
156
+ if (readings.length === 0) {
157
+ noReadingsMessage.classList.remove('hidden');
158
+ return;
159
+ }
160
+
161
+ noReadingsMessage.classList.add('hidden');
162
+
163
+ readings.forEach(reading => {
164
+ const readingElement = document.createElement('div');
165
+ readingElement.className = 'flex gap-3 items-center fade-in';
166
+ readingElement.innerHTML = `
167
+ <div class="flex-1">
168
+ <input
169
+ type="month"
170
+ 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"
171
+ value="${reading.month}"
172
+ onchange="updateReading('${reading.id}', 'month', this.value)"
173
+ required
174
+ >
175
+ </div>
176
+ <div class="flex-1">
177
+ <input
178
+ type="number"
179
+ 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"
180
+ value="${reading.value}"
181
+ placeholder="kWh"
182
+ min="0"
183
+ onchange="updateReading('${reading.id}', 'value', this.value)"
184
+ required
185
+ >
186
+ </div>
187
+ <button
188
+ type="button"
189
+ 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"
190
+ onclick="removeReading('${reading.id}')"
191
+ >
192
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
193
+ <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" />
194
+ </svg>
195
+ </button>
196
+ `;
197
+ readingsContainer.appendChild(readingElement);
198
+ });
199
+ }
200
+
201
+ // Update reading value
202
+ window.updateReading = function(id, field, value) {
203
+ readings = readings.map(r => r.id === id ? { ...r, [field]: value } : r);
204
+ updateChart();
205
+ };
206
+
207
+ // Remove reading
208
+ window.removeReading = function(id) {
209
+ readings = readings.filter(r => r.id !== id);
210
+ renderReadings();
211
+ updateChart();
212
+ };
213
+
214
+ // Update chart with current data
215
+ function updateChart() {
216
+ const validReadings = readings
217
+ .filter(r => r.month && r.value !== '' && !isNaN(Number(r.value)))
218
+ .map(r => ({
219
+ month: r.month,
220
+ value: Number(r.value)
221
+ }))
222
+ .sort((a, b) => a.month.localeCompare(b.month));
223
+
224
+ if (validReadings.length >= 2) {
225
+ chartContainer.classList.remove('hidden');
226
+
227
+ const ctx = document.getElementById('consumptionChart').getContext('2d');
228
+ const labels = validReadings.map(r => {
229
+ const [year, month] = r.month.split('-');
230
+ const monthNames = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
231
+ return `${monthNames[parseInt(month) - 1]}/${year.slice(2)}`;
232
+ });
233
+ const data = validReadings.map(r => r.value);
234
+
235
+ if (chart) {
236
+ chart.destroy();
237
+ }
238
+
239
+ chart = new Chart(ctx, {
240
+ type: 'line',
241
+ data: {
242
+ labels: labels,
243
+ datasets: [{
244
+ label: 'Consumo (kWh)',
245
+ data: data,
246
+ backgroundColor: 'rgba(99, 102, 241, 0.1)',
247
+ borderColor: 'rgba(99, 102, 241, 1)',
248
+ borderWidth: 2,
249
+ tension: 0.3,
250
+ pointBackgroundColor: 'rgba(99, 102, 241, 1)',
251
+ pointRadius: 4,
252
+ pointHoverRadius: 6
253
+ }]
254
+ },
255
+ options: {
256
+ responsive: true,
257
+ maintainAspectRatio: false,
258
+ scales: {
259
+ y: {
260
+ beginAtZero: true,
261
+ title: {
262
+ display: true,
263
+ text: 'kWh'
264
+ }
265
+ }
266
+ },
267
+ plugins: {
268
+ tooltip: {
269
+ callbacks: {
270
+ label: function(context) {
271
+ return `${context.parsed.y} kWh`;
272
+ }
273
+ }
274
+ }
275
+ }
276
+ }
277
+ });
278
+ } else {
279
+ chartContainer.classList.add('hidden');
280
+ if (chart) {
281
+ chart.destroy();
282
+ chart = null;
283
+ }
284
+ }
285
+ }
286
+
287
+ // Form submission
288
+ form.addEventListener('submit', function(e) {
289
+ e.preventDefault();
290
+
291
+ // Validate average consumption
292
+ if (!averageKwhInput.value || isNaN(Number(averageKwhInput.value)) || Number(averageKwhInput.value) < 0) {
293
+ showToast('Erro de validação', 'Consumo médio deve ser um número positivo', 'error');
294
+ return;
295
+ }
296
+
297
+ // Simulate loading
298
+ submitBtn.disabled = true;
299
+ submitBtn.innerHTML = `
300
+ <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">
301
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
302
+ <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>
303
+ </svg>
304
+ Processando...
305
+ `;
306
+
307
+ // Simulate API call
308
+ setTimeout(() => {
309
+ showToast('Perfil de consumo analisado', 'Sua análise de consumo foi concluída com sucesso', 'success');
310
+
311
+ // Reset button
312
+ submitBtn.disabled = false;
313
+ submitBtn.textContent = 'Analisar Perfil de Consumo';
314
+
315
+ // In a real app, you would redirect here
316
+ // window.location.href = '/onboard/resumo';
317
+ }, 2000);
318
+ });
319
+
320
+ // Back button
321
+ backBtn.addEventListener('click', function() {
322
+ // In a real app, you would go back
323
+ // window.history.back();
324
+ console.log('Back button clicked');
325
+ });
326
+
327
+ // Show toast notification
328
+ function showToast(title, message, type) {
329
+ // In a real app, you would use a proper toast library
330
+ console.log(`${type.toUpperCase()}: ${title} - ${message}`);
331
+ alert(`${title}\n${message}`);
332
+ }
333
+ });
334
+ </script>
335
+ <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>
336
+ </html>