This commit is contained in:
2025-06-17 17:46:21 +01:00
parent efc4fdb4c0
commit 4a8395a307
38 changed files with 12370 additions and 1 deletions

4
.gitignore vendored Normal file → Executable file
View File

@@ -404,3 +404,7 @@ FodyWeavers.xsd
# JetBrains Rider # JetBrains Rider
*.sln.iml *.sln.iml
node_modules/
dist/

178
Chargers copy.jsx Normal file
View File

@@ -0,0 +1,178 @@
import React, { useState, useEffect } from 'react';
import { Plus, Loader2, X, Trash2 } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
export default function ChargersPage() {
const [chargers, setChargers] = useState([]);
const [selectedCharger, setSelectedCharger] = useState(null);
const [deletingId, setDeletingId] = useState(null);
const [showAdd, setShowAdd] = useState(false);
const navigate = useNavigate();
// Carregar os carregadores ao montar o componente
useEffect(() => {
async function fetchChargers() {
try {
const res = await fetch('/api/chargers');
const json = await res.json();
if (res.ok) {
setChargers(json.data || []);
} else {
throw new Error('Falha ao carregar carregadores');
}
} catch (err) {
console.error(err.message);
}
}
fetchChargers();
}, []);
const handleOpenAdd = () => setShowAdd(true);
const handleCloseAdd = () => setShowAdd(false);
const handleSelect = (id) => {
setSelectedCharger(id); // Atualiza o carregador selecionado
navigate(`/charger/${id}`); // Navega para a página do carregador
};
const handleDelete = async (id) => {
if (window.confirm('Excluir este carregador? Esta ação não pode ser desfeita.')) {
setDeletingId(id);
try {
const res = await fetch(`/api/chargers/${id}`, { method: 'DELETE' });
if (res.ok) {
setChargers((prevChargers) => prevChargers.filter(c => c.id !== id));
} else {
throw new Error('Erro ao excluir carregador');
}
} catch (err) {
console.error('Erro ao deletar carregador', err);
} finally {
setDeletingId(null);
}
}
};
return (
<div className="max-w-2xl mx-auto p-4 pb-24">
<div className="flex items-center justify-between mb-5">
<h1 className="text-2xl font-bold">Meus Carregadores</h1>
<button
className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg shadow hover:bg-blue-700 transition"
onClick={handleOpenAdd}
>
<Plus size={20} /> Novo
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{chargers.length > 0 ? (
chargers.map((charger) => (
<motion.div
key={charger.id}
className={`bg-white rounded-xl shadow-md border p-5 flex flex-col gap-2 cursor-pointer transition relative ${selectedCharger === charger.id ? 'border-blue-500 bg-blue-50' : ''}`}
onClick={() => handleSelect(charger.id)}
>
<button
className="absolute top-3 right-3 text-gray-400 hover:text-red-500 transition z-10"
onClick={(e) => {
e.stopPropagation();
handleDelete(charger.id);
}}
disabled={deletingId === charger.id}
>
{deletingId === charger.id ? <Loader2 className="animate-spin" size={18} /> : <Trash2 size={18} />}
</button>
<div className="flex items-center gap-2 mb-1">
<span className={`inline-block w-2 h-2 rounded-full ${charger.status === 'online' ? 'bg-green-500' : charger.status === 'standby' ? 'bg-yellow-400' : 'bg-gray-400'}`} />
<span className="font-semibold text-lg">{charger.nome}</span>
</div>
<div className="text-xs text-gray-500">Código: <span className="font-mono">{charger.codigoEmparelhamento}</span></div>
<div className="text-xs text-gray-500">Local: {charger.local}</div>
<div className="text-xs text-gray-400">Última atividade: {charger.ultimaAtividade}</div>
</motion.div>
))
) : (
<p className="text-gray-500">Nenhum carregador encontrado</p>
)}
</div>
<AnimatePresence>
{showAdd && <AddChargerModal onClose={handleCloseAdd} />}
</AnimatePresence>
</div>
);
}
function AddChargerModal({ onClose }) {
const [nome, setNome] = useState('');
const [local, setLocal] = useState('');
const [saving, setSaving] = useState(false);
async function handleSubmit(e) {
e.preventDefault();
setSaving(true);
try {
const res = await fetch('/api/chargers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nome, local })
});
const json = await res.json();
onClose();
} catch (err) {
console.error('Erro ao adicionar carregador', err);
} finally {
setSaving(false);
}
}
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black bg-opacity-40 z-50 flex items-center justify-center"
>
<motion.div
initial={{ scale: 0.94, y: 40, opacity: 0 }}
animate={{ scale: 1, y: 0, opacity: 1 }}
exit={{ scale: 0.92, y: 40, opacity: 0 }}
className="bg-white rounded-2xl shadow-xl p-8 w-full max-w-sm relative"
>
<button className="absolute top-3 right-3 text-gray-500 hover:text-gray-800" onClick={onClose} aria-label="Fechar">
<X />
</button>
<h2 className="text-xl font-bold mb-4">Novo Carregador</h2>
<form className="space-y-4" onSubmit={handleSubmit}>
<div>
<label className="block text-sm font-medium mb-1">Nome</label>
<input
type="text"
value={nome}
onChange={(e) => setNome(e.target.value)}
required
className="w-full border border-gray-300 rounded-lg px-3 py-2"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Localização</label>
<input
type="text"
value={local}
onChange={(e) => setLocal(e.target.value)}
required
className="w-full border border-gray-300 rounded-lg px-3 py-2"
/>
</div>
<button
type="submit"
disabled={saving}
className="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg transition flex items-center justify-center gap-2"
>
{saving && <Loader2 className="animate-spin" size={18} />} Salvar
</button>
</form>
</motion.div>
</motion.div>
);
}

281
Dashboard copy.jsx Normal file
View File

@@ -0,0 +1,281 @@
import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
Play,
Square,
Zap,
BatteryCharging,
Clock,
Activity,
Loader2,
ArrowLeft,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { SectionCard } from '@/components/ui/SectionCard';
import { getAuthHeader } from '@/utils/apiAuthHeader';
import { useToast } from '@/components/ToastContext';
export default function ChargerDashboard() {
const { chargerId } = useParams(); // Obter o chargerId da URL
const [dados, setDados] = useState(null);
const [ampLimit, setAmpLimit] = useState(6);
const [maxAmps, setMaxAmps] = useState(32);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const navigate = useNavigate();
const showToast = useToast();
// Buscar status do carregador
useEffect(() => {
if (!chargerId) {
setError("Carregador não encontrado!");
setLoading(false);
return;
}
let cancelado = false;
async function fetchStatus() {
setLoading(true);
setError('');
try {
const res = await fetch(`/api/chargers/${chargerId}/status`, {
headers: getAuthHeader(),
});
const json = await res.json();
if (!res.ok || !json.success) throw new Error(json.message || 'Erro ao obter status');
if (!cancelado) {
setDados(json.data);
setAmpLimit(json.data.ampLimit ?? 6);
setMaxAmps(json.data.maxAmps ?? 32);
}
} catch (err) {
if (!cancelado) setError(err.message || 'Falha ao buscar status');
} finally {
if (!cancelado) setLoading(false);
}
}
fetchStatus();
const interval = setInterval(fetchStatus, 8000);
return () => {
cancelado = true;
clearInterval(interval);
};
}, [chargerId]); // Atualizar a requisição sempre que o chargerId mudar
// Enviar comandos (iniciar/parar carregamento)
async function handleAction(action) {
if (!chargerId) return; // Adicionar verificação extra para chargerId
setBusy(true);
try {
const res = await fetch(`/api/chargers/${chargerId}/${action}`, {
method: 'POST',
headers: {
...getAuthHeader(),
'Content-Type': 'application/json',
},
body: JSON.stringify({ ampLimit }),
});
const json = await res.json();
if (!res.ok || !json.success) throw new Error(json.message || 'Erro ao enviar comando');
setDados(json.data);
showToast(
action === 'start' ? 'Carregamento iniciado' : 'Carregamento parado',
'success'
);
setError('');
} catch (err) {
setError(err.message);
showToast(err.message, 'error');
} finally {
setBusy(false);
}
}
return (
<div className="max-w-2xl mx-auto p-4 pb-24">
<button
className="mb-2 flex items-center gap-2 text-blue-600 hover:underline focus:outline-none"
onClick={() => navigate(-1)}
>
<ArrowLeft size={18} /> Voltar
</button>
<SectionCard
title={dados?.nome ? `Carregador: ${dados.nome}` : 'Carregador'}
icon={<Zap className="text-blue-600" />}
>
{error && (
<motion.p
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-red-500 text-sm mb-4"
aria-live="polite"
>
{error}
</motion.p>
)}
{(loading || busy) ? (
<div className="flex flex-col items-center justify-center py-8">
<Loader2 className="animate-spin text-blue-500" size={40} />
<span className="text-blue-600 mt-2">
{busy ? 'Enviando comando...' : 'Carregando status...'}
</span>
</div>
) : (
dados && (
<>
{/* Potência em destaque */}
<AnimatePresence mode="wait">
<motion.div
key={dados.potenciaAtual}
initial={{ scale: 0.85, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.85, opacity: 0 }}
transition={{ duration: 0.5 }}
className="relative w-40 h-40 mx-auto mb-8 select-none"
>
<div
className={`absolute inset-0 rounded-full border-8
${dados.potenciaAtual > 7
? 'border-yellow-400 opacity-60'
: 'border-blue-200 opacity-30'}`}
/>
<div
className={`absolute inset-2 rounded-full border-8
${dados.currentPower > 7
? 'border-yellow-500'
: 'border-blue-600'}
flex flex-col items-center justify-center text-blue-700`}
>
<motion.div
initial={{ rotate: -10 }}
animate={{ rotate: [0, 12, -12, 0] }}
transition={{
duration: 1,
repeat: Infinity,
repeatType: 'mirror',
ease: 'easeInOut',
}}
className={`mb-1 ${
dados.currentPower > 7
? 'text-yellow-500'
: 'text-blue-600'
}`}
>
<Zap size={32} />
</motion.div>
<span className="text-4xl font-extrabold drop-shadow">
{dados.currentPower} kW
</span>
<span className="text-xs text-gray-400 font-medium mt-1 tracking-wide">
Potência
</span>
</div>
</motion.div>
</AnimatePresence>
{/* Informações detalhadas */}
<div className="grid gap-5 text-sm text-gray-700 mb-8">
<InfoItem
icon={<BatteryCharging className="text-blue-500" />}
label="Estado"
value={dados.status}
valueClass="text-blue-600"
/>
<InfoItem
icon={<Clock className="text-gray-500" />}
label="Tempo de carregamento"
value={dados.timeRemaining}
/>
<InfoItem
icon={<Zap className="text-yellow-500" />}
label="Potência"
value={
<span className="text-lg font-bold text-yellow-600">
{dados.potenciaAtual} kW
</span>
}
/>
<InfoItem
icon={<Activity className="text-indigo-500" />}
label="Modo"
value={dados.modo?.toUpperCase()}
valueClass="text-indigo-600 font-bold"
/>
</div>
{/* Slider para Amperagem */}
<div className="mb-10">
<label
htmlFor="amp-range"
className="flex items-center gap-3 text-base font-medium text-gray-800 mb-4"
>
<Zap className="text-gray-600" size={20} />
Corrente máxima:{' '}
<span className="text-blue-700 font-semibold">
{ampLimit} A
</span>
</label>
<input
id="amp-range"
type="range"
min={6}
max={maxAmps}
value={ampLimit}
onChange={(e) => setAmpLimit(Number(e.target.value))}
className="w-full accent-blue-600"
aria-valuenow={ampLimit}
aria-valuemin={6}
aria-valuemax={maxAmps}
disabled={busy}
/>
<div className="flex justify-between text-xs text-gray-500 mt-1">
<span>6 A</span>
<span>{maxAmps} A</span>
</div>
</div>
{/* Botões */}
<div className="flex justify-center gap-4 mt-8">
<motion.button
whileTap={{ scale: 0.95 }}
onClick={() => handleAction('start')}
className="bg-green-600 hover:bg-green-700 text-white px-5 py-2 rounded-xl shadow font-medium transition flex items-center gap-2 active:scale-95 focus:outline-none focus:ring-2 focus:ring-green-400"
disabled={busy}
aria-label="Iniciar carregamento"
>
<Play size={18} /> Iniciar
</motion.button>
<motion.button
whileTap={{ scale: 0.95 }}
onClick={() => handleAction('stop')}
className="bg-red-500 hover:bg-red-600 text-white px-5 py-2 rounded-xl shadow font-medium transition flex items-center gap-2 active:scale-95 focus:outline-none focus:ring-2 focus:ring-red-400"
disabled={busy}
aria-label="Parar carregamento"
>
<Square size={18} /> Parar
</motion.button>
</div>
</>
)
)}
</SectionCard>
</div>
);
}
function InfoItem({ icon, label, value, valueClass = '' }) {
return (
<div className="grid grid-cols-2 items-center gap-2 py-1.5">
<div className="flex items-center gap-2 text-gray-600 font-medium">
{icon}
<span>{label}</span>
</div>
<div className={`text-right text-base font-semibold ${valueClass}`}>
{value}
</div>
</div>
);
}

13
README.md Normal file → Executable file
View File

@@ -1 +1,12 @@
# ev-pwa # React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.

33
eslint.config.js Executable file
View File

@@ -0,0 +1,33 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
export default [
{ ignores: ['dist'] },
{
files: ['**/*.{js,jsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...js.configs.recommended.rules,
...reactHooks.configs.recommended.rules,
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
]

25
index.html Executable file
View File

@@ -0,0 +1,25 @@
<!doctype html>
<html lang="pt">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EV Station Controller</title>
<meta name="description" content="Gestão de estação de carregamento EV via PWA" />
<meta name="theme-color" content="#0f172a" />
<!-- Favicon e ícones -->
<link rel="icon" href="/icons/icon-192.png" sizes="192x192" />
<link rel="apple-touch-icon" href="/icons/icon-512.png" sizes="512x512" />
<!-- Manifest PWA -->
<link rel="manifest" href="/manifest.webmanifest" />
</head>
<body class="bg-gray-100 text-gray-900">
<!-- Ponto de entrada React -->
<div id="root"></div>
<!-- Script principal Vite -->
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

8648
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
package.json Executable file
View File

@@ -0,0 +1,37 @@
{
"name": "ev-pwa",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"framer-motion": "^12.18.1",
"lucide-react": "^0.515.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.6.2",
"recharts": "^2.15.3"
},
"devDependencies": {
"@eslint/js": "^9.25.0",
"@tailwindcss/cli": "^4.1.10",
"@tailwindcss/vite": "^4.1.10",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"@vitejs/plugin-react": "^4.4.1",
"autoprefixer": "^10.4.21",
"eslint": "^9.25.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^16.0.0",
"postcss": "^8.5.5",
"tailwindcss": "^4.1.10",
"vite": "^6.3.5",
"vite-plugin-pwa": "^1.0.0"
}
}

1587
projeto_parte1.c Normal file

File diff suppressed because it is too large Load Diff

BIN
public/icons/icon-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

BIN
public/icons/icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

1
public/vite.svg Executable file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

78
readproject.py Normal file
View File

@@ -0,0 +1,78 @@
import os
TAMANHO_MAX = 100000 # Limite por arquivo
EXCLUIR_PASTAS = {"node_modules", "dist", "build", ".git", ".vite"}
def coletar_arquivos(diretorios, extensoes=(".js", ".ts", ".tsx", ".jsx", ".css", ".html", ".json", ".md")):
arquivos = []
for diretorio in diretorios:
for raiz, pastas, nomes_arquivos in os.walk(diretorio):
pastas[:] = [p for p in pastas if p not in EXCLUIR_PASTAS]
for nome in nomes_arquivos:
if nome.endswith(extensoes):
caminho_completo = os.path.join(raiz, nome)
arquivos.append(caminho_completo)
return arquivos
def unir_em_partes(arquivos, prefixo="projeto_parte", limite=TAMANHO_MAX):
parte = 1
conteudo_atual = ""
total_arquivos = 0
for arquivo in arquivos:
try:
with open(arquivo, "r", encoding="utf-8") as f_origem:
conteudo = f_origem.read()
except Exception as e:
print(f"⚠️ Erro ao ler {arquivo}: {e}")
continue
bloco = f"\n\n// === Início de: {arquivo} ===\n{conteudo}\n// === Fim de: {arquivo} ===\n"
if len(conteudo_atual) + len(bloco) > limite:
nome_saida = f"{prefixo}{parte}.c"
with open(nome_saida, "w", encoding="utf-8") as f_saida:
f_saida.write(conteudo_atual)
print(f"✅ Criado: {nome_saida}")
parte += 1
conteudo_atual = ""
conteudo_atual += bloco
total_arquivos += 1
if conteudo_atual:
nome_saida = f"{prefixo}{parte}.c"
with open(nome_saida, "w", encoding="utf-8") as f_saida:
f_saida.write(conteudo_atual)
print(f"✅ Criado: {nome_saida}")
print(f"\n🔹 {total_arquivos} arquivos de código processados.")
print(f"🔹 Arquivos gerados: {parte}")
def main():
diretorio_base = "."
# Subpastas principais que queremos incluir (se existirem)
componentes_escolhidos = ["src", "public", "config", "utils"]
diretorios_para_incluir = [os.path.join(diretorio_base, nome)
for nome in componentes_escolhidos
if os.path.exists(os.path.join(diretorio_base, nome))]
# Arquivos individuais importantes na raiz do projeto
arquivos_extras = []
for nome in ["vite.config.js", "vite.config.ts", "package.json", "tsconfig.json"]:
caminho = os.path.join(diretorio_base, nome)
if os.path.isfile(caminho):
arquivos_extras.append(caminho)
# Coleta os arquivos das pastas
arquivos_das_pastas = coletar_arquivos(diretorios_para_incluir)
# Junta tudo
arquivos = arquivos_das_pastas + arquivos_extras
unir_em_partes(arquivos)
if __name__ == "__main__":
main()

42
src/App.css Executable file
View File

@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

18
src/App.jsx Executable file
View File

@@ -0,0 +1,18 @@
import { Outlet } from 'react-router-dom';
import BottomNav from './components/BottomNav';
function AppLayout() {
return (
<main
className="min-h-screen bg-gray-100 dark:bg-slate-900 pb-24 pt-4 px-2 sm:px-4"
role="main"
>
<div className="max-w-2xl mx-auto w-full">
<Outlet />
</div>
<BottomNav />
</main>
);
}
export default AppLayout;

1
src/assets/react.svg Executable file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,58 @@
import { Link, useMatch, useResolvedPath } from 'react-router-dom';
import { Zap, Calendar, Settings, BatteryCharging } from 'lucide-react';
import { motion } from 'framer-motion';
const tabs = [
{ label: 'Carregador', to: '/dashboard', icon: Zap },
{ label: 'Histórico', to: '/history', icon: Calendar },
{ label: 'Configuração', to: '/settings', icon: Settings },
{ label: 'Carregadores', to: '/', icon: BatteryCharging },
];
export default function BottomNav() {
return (
<motion.nav
initial={{ y: 40, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ type: 'spring', bounce: 0.16, duration: 0.55 }}
className="fixed bottom-0 left-0 right-0 bg-white dark:bg-slate-900 border-t border-gray-100 dark:border-slate-800 shadow-md flex z-50"
aria-label="Navegação principal"
>
{tabs.map(({ label, to, icon: Icon }) => {
const resolved = useResolvedPath(to);
const match = useMatch({ path: resolved.pathname, end: true });
return (
<Link
key={to}
to={to}
aria-label={label}
className={`flex flex-1 flex-col items-center justify-center py-2.5 px-2 transition font-medium group
${match ? 'text-blue-700 dark:text-blue-400 font-semibold' : 'text-gray-400 dark:text-gray-500'}
active:bg-gray-100 dark:active:bg-slate-800`}
tabIndex={0}
>
<motion.div
whileTap={{ scale: 0.85 }}
className={`rounded-full flex items-center justify-center mb-0.5
${match ? 'bg-blue-50 dark:bg-blue-950' : ''}
transition`}
style={{ width: 38, height: 38 }}
>
<Icon
size={match ? 26 : 22}
className={match ? 'stroke-2' : 'stroke-1.5'}
/>
</motion.div>
<span
className={`text-[13px] transition
${match ? 'font-semibold text-blue-600 dark:text-blue-400' : 'text-gray-500 dark:text-gray-400'}`}
>
{label}
</span>
</Link>
);
})}
</motion.nav>
);
}

View File

@@ -0,0 +1,15 @@
import { useAuth } from '@/contexts/AuthContext';
import { Navigate, useLocation } from 'react-router-dom';
// Uso: <ProtectedRoute> <ComponentePrivado /> </ProtectedRoute>
export default function ProtectedRoute({ children }) {
const { isAuthenticated } = useAuth();
const location = useLocation();
if (!isAuthenticated) {
// redireciona para /login, guardando a rota atual para possível redirect pós-login
return <Navigate to="/login" replace state={{ from: location }} />;
}
return children;
}

View File

@@ -0,0 +1,28 @@
// src/components/ToastContext.jsx
import { createContext, useContext, useState } from 'react';
const ToastContext = createContext();
export function ToastProvider({ children }) {
const [toast, setToast] = useState(null);
function showToast(message, type = 'success') {
setToast({ message, type });
setTimeout(() => setToast(null), 2500);
}
return (
<ToastContext.Provider value={showToast}>
{children}
{toast && (
<div className={`fixed bottom-6 right-6 px-4 py-3 rounded shadow-xl z-50 text-white ${toast.type === 'error' ? 'bg-red-600' : 'bg-blue-600'}`}>
{toast.message}
</div>
)}
</ToastContext.Provider>
);
}
export function useToast() {
return useContext(ToastContext);
}

View File

@@ -0,0 +1,21 @@
// src/components/ui/SectionCard.jsx
import { motion } from 'framer-motion';
export function SectionCard({ title, icon, children }) {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4 }}
className="bg-white rounded-2xl shadow-xl border border-gray-200 p-6"
>
<div className="flex items-center gap-2 mb-5">
{icon && <div className="text-blue-600">{icon}</div>}
<h2 className="text-xl font-bold text-gray-800">{title}</h2>
</div>
<div className="space-y-4">
{children}
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,83 @@
import { createContext, useContext, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
// Utilitário para decodificar JWT sem biblioteca externa
function parseJwt(token) {
try {
return JSON.parse(atob(token.split('.')[1]));
} catch {
return null;
}
}
const AuthContext = createContext();
export function AuthProvider({ children }) {
const navigate = useNavigate();
const [token, setToken] = useState(() => localStorage.getItem('token') || '');
const [user, setUser] = useState(() => {
const stored = localStorage.getItem('token');
return stored ? parseJwt(stored) : null;
});
useEffect(() => {
if (!token) return;
const payload = parseJwt(token);
if (!payload) {
logout();
return;
}
setUser(payload);
// Expiração do token
const expiresAt = payload.exp * 1000;
const now = Date.now();
const timeout = expiresAt - now;
if (timeout <= 0) {
logout();
} else {
const timer = setTimeout(() => {
logout();
}, timeout);
return () => clearTimeout(timer);
}
}, [token]);
const login = (newToken) => {
const payload = parseJwt(newToken);
if (!payload) {
console.error("Token inválido");
return;
}
localStorage.setItem('token', newToken);
setToken(newToken);
setUser(payload);
navigate('/');
};
const logout = () => {
localStorage.removeItem('token');
setToken('');
setUser(null);
navigate('/login');
};
const isAuthenticated = !!token;
return (
<AuthContext.Provider value={{ token, user, login, logout, isAuthenticated }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
return ctx;
}

View File

@@ -0,0 +1,53 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import useApi from '@/hooks/useApi';
const ChargersContext = createContext();
export function ChargersProvider({ children }) {
const { request, loading: apiLoading, error: apiError } = useApi();
const [chargers, setChargers] = useState([]);
const [selectedCharger, setSelectedCharger] = useState(null);
// Busca lista de carregadores e seleciona o primeiro se necessário
const fetchChargers = async () => {
try {
const response = await request('/api/chargers');
const list = response.data || [];
setChargers(list);
if (!selectedCharger && list.length > 0) {
setSelectedCharger(list[0]);
}
} catch (err) {
console.error('Error fetching chargers:', err);
}
};
useEffect(() => {
fetchChargers();
}, []);
// Seleciona um carregador por ID
const selectChargerById = (id) => {
const charger = chargers.find(c => c.id === id) || null;
setSelectedCharger(charger);
};
return (
<ChargersContext.Provider value={{
chargers,
selectedCharger,
selectChargerById,
fetchChargers,
loading: apiLoading,
error: apiError,
}}>
{children}
</ChargersContext.Provider>
);
}
export function useChargersContext() {
const context = useContext(ChargersContext);
if (!context) throw new Error('useChargersContext must be used within a ChargersProvider');
return context;
}

40
src/hooks/useApi.js Normal file
View File

@@ -0,0 +1,40 @@
// src/hooks/useApi.js
import { useState } from 'react';
import { getAuthHeader } from '@/utils/apiAuthHeader';
export default function useApi() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const request = async (url, options = {}) => {
setLoading(true);
setError('');
try {
const res = await fetch(url, {
...options,
headers: {
...getAuthHeader(),
...(options.headers || {})
},
});
if (res.status === 401 || res.status === 403) {
setError('Sessão expirada. Faça login novamente.');
throw new Error('Sessão expirada');
}
const data = await res.json();
if (!res.ok) throw new Error(data.message || 'Erro na API');
return data;
} catch (err) {
setError(err.message);
throw err;
} finally {
setLoading(false);
}
};
return { request, loading, error };
}

37
src/hooks/useCharger.js Normal file
View File

@@ -0,0 +1,37 @@
// src/hooks/useCharger.js
import { useState, useEffect } from 'react';
import { getAuthHeader } from '@/utils/apiAuthHeader';
export function useCharger(chargerId) {
const [chargerData, setChargerData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
if (!chargerId) return;
const fetchCharger = async () => {
setLoading(true);
try {
const res = await fetch(`/api/chargers/${chargerId}/status`, {
headers: getAuthHeader(),
});
if (!res.ok) throw new Error('Failed to fetch charger data');
const json = await res.json();
setChargerData(json.data);
setError('');
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchCharger();
}, [chargerId]);
return { chargerData, loading, error };
}

View File

@@ -0,0 +1,35 @@
import { useEffect, useState } from 'react';
import { getAuthHeader } from '@/utils/apiAuthHeader';
export function useChargerStatus(chargerId) {
const [charger, setCharger] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const fetchStatus = async () => {
setLoading(true);
setError('');
try {
const res = await fetch(`/api/chargers/${chargerId}/status`, {
headers: getAuthHeader(),
});
const json = await res.json();
if (!res.ok || !json.success) {
throw new Error(json.message || 'Erro ao buscar status');
}
setCharger(json.data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
if (chargerId) fetchStatus();
}, [chargerId]);
return { charger, loading, error, refresh: fetchStatus };
}

28
src/hooks/useChargers.js Normal file
View File

@@ -0,0 +1,28 @@
// src/hooks/useChargers.js
import { useEffect, useState } from "react";
import { getAuthHeader } from "@/utils/apiAuthHeader";
export function useChargers() {
const [chargers, setChargers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
setLoading(true);
fetch("/api/chargers", {
headers: getAuthHeader(),
})
.then(res => {
if (!res.ok) throw new Error("Erro ao buscar carregadores");
return res.json();
})
.then(json => {
setChargers(json.data || []);
setError("");
})
.catch(() => setError("Falha ao carregar carregadores"))
.finally(() => setLoading(false));
}, []);
return { chargers, setChargers, loading, error };
}

33
src/hooks/useHistory.js Normal file
View File

@@ -0,0 +1,33 @@
// src/hooks/useHistory.js
import { useState, useEffect } from 'react';
import { getAuthHeader } from '@/utils/apiAuthHeader';
// Agora recebe chargerId!
export function useHistory(chargerId) {
const [histories, setHistory] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
if (!chargerId) return; // Só busca se houver carregador selecionado
setLoading(true);
fetch(`/api/chargers/${chargerId}/history`, {
headers: getAuthHeader(),
})
.then(res => {
if (res.status === 401 || res.status === 403) {
setError('Sessão expirada. Faça login novamente.');
return { data: [] };
}
return res.json();
})
.then(json => {
setHistory(json.data || []);
setError('');
})
.catch(() => setError('Falha ao carregar agendamentos'))
.finally(() => setLoading(false));
}, [chargerId]); // <-- Atualiza quando o chargerId mudar
return { histories, setHistory, loading, error };
}

33
src/hooks/useSchedules.js Normal file
View File

@@ -0,0 +1,33 @@
// src/hooks/useSchedules.js
import { useState, useEffect } from 'react';
import { getAuthHeader } from '@/utils/apiAuthHeader';
// Agora recebe chargerId!
export function useSchedules(chargerId) {
const [schedules, setSchedules] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
if (!chargerId) return; // Só busca se houver carregador selecionado
setLoading(true);
fetch(`/api/chargers/${chargerId}/schedule`, {
headers: getAuthHeader(),
})
.then(res => {
if (res.status === 401 || res.status === 403) {
setError('Sessão expirada. Faça login novamente.');
return { data: [] };
}
return res.json();
})
.then(json => {
setSchedules(json.data || []);
setError('');
})
.catch(() => setError('Falha ao carregar agendamentos'))
.finally(() => setLoading(false));
}, [chargerId]); // <-- Atualiza quando o chargerId mudar
return { schedules, setSchedules, loading, error };
}

1
src/index.css Executable file
View File

@@ -0,0 +1 @@
@import "tailwindcss";

79
src/main.jsx Executable file
View File

@@ -0,0 +1,79 @@
import React, { Suspense, lazy } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import AppLayout from './App';
import './index.css';
import { AuthProvider } from './contexts/AuthContext';
import { ToastProvider } from './components/ToastContext';
import { ChargersProvider } from './contexts/ChargersContext';
import ProtectedRoute from './components/ProtectedRoute';
const PageLoading = () => (
<div className="min-h-screen flex items-center justify-center text-gray-500">
<span className="animate-pulse">Loading...</span>
</div>
);
// Lazy-loaded pages
const ChargersPage = lazy(() => import('./pages/ChargersPage'));
const ChargerDashboardPage = lazy(() => import('./pages/ChargerDashboardPage'));
const HistoryPage = lazy(() => import('./pages/HistoryPage'));
const SettingsPage = lazy(() => import('./pages/SettingsPage'));
const LoginPage = lazy(() => import('./pages/LoginPage'));
// Root container
const container = document.getElementById('root');
if (!container) throw new Error('Root element not found');
const root = createRoot(container);
root.render(
<React.StrictMode>
<BrowserRouter>
<AuthProvider>
<ToastProvider>
<ChargersProvider>
<Suspense fallback={<PageLoading />}>
<Routes>
{/* Rota pública */}
<Route path="/login" element={<LoginPage />} />
{/* Rotas protegidas */}
<Route
path="/"
element={
<ProtectedRoute>
<AppLayout />
</ProtectedRoute>
}
>
<Route index element={<ChargersPage />} />
<Route path="dashboard" element={<ChargerDashboardPage />} />
<Route path="charger/:chargerId" element={<ChargerDashboardPage />} />
<Route path="history" element={<HistoryPage />} />
<Route path="settings" element={<SettingsPage />} />
</Route>
{/* Redirecionamento para rota protegida padrão */}
<Route path="chargers" element={<Navigate to="/" replace />} />
{/* Fallback 404 */}
<Route
path="*"
element={
<div className="min-h-screen flex flex-col items-center justify-center text-gray-400">
<h1 className="text-4xl font-bold mb-2">404</h1>
<p>Página não encontrada</p>
<a href="/" className="mt-3 text-blue-500 underline">Voltar para início</a>
</div>
}
/>
</Routes>
</Suspense>
</ChargersProvider>
</ToastProvider>
</AuthProvider>
</BrowserRouter>
</React.StrictMode>
);

View File

@@ -0,0 +1,239 @@
import React, { useState, useEffect } from 'react';
import {
Play,
Square,
Zap,
BatteryCharging,
Clock,
Activity,
Loader2,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { SectionCard } from '@/components/ui/SectionCard';
import { useToast } from '@/components/ToastContext';
import { useChargersContext } from '@/contexts/ChargersContext';
import { getAuthHeader } from '@/utils/apiAuthHeader';
import { useChargerStatus } from '@/hooks/useChargerStatus';
export default function ChargerDashboardPage() {
const { selectedCharger } = useChargersContext();
const chargerId = selectedCharger?.id;
const toast = useToast();
const { charger, loading, error, refresh } = useChargerStatus(chargerId);
const [ampLimit, setAmpLimit] = useState(6);
const [maxAmps, setMaxAmps] = useState(32);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (charger) {
setAmpLimit(charger.ampLimit ?? 6);
setMaxAmps(charger.maxAmps ?? 32);
}
}, [charger]);
const handleAction = async (action) => {
if (!chargerId) return;
setBusy(true);
try {
const res = await fetch(`/api/chargers/${chargerId}/${action}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeader(),
},
body: JSON.stringify({ ampLimit }),
});
const json = await res.json();
if (!res.ok || !json.success) {
throw new Error(json.message || 'Failed to send command');
}
toast(action === 'start' ? 'Charging started' : 'Charging stopped', 'success');
refresh(); // Atualiza o status
} catch (err) {
toast(err.message, 'error');
} finally {
setBusy(false);
}
};
const statusColor = {
online: 'bg-green-100 text-green-800',
carregando: 'bg-yellow-100 text-yellow-800',
offline: 'bg-red-100 text-red-800',
}[charger?.status || 'offline'];
return (
<div className="max-w-2xl mx-auto p-4 pb-24">
<SectionCard
title={charger?.name ? `Charger: ${charger.name}` : 'Charger'}
icon={<Zap className="text-blue-600" />}
>
{error && (
<motion.p
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-red-500 text-sm mb-4"
aria-live="polite"
>
{error}
</motion.p>
)}
{loading || busy ? (
<div className="flex flex-col items-center justify-center py-8">
<Loader2 className="animate-spin text-blue-500" size={40} />
<span className="text-blue-600 mt-2">
{busy ? 'Sending command...' : 'Loading status...'}
</span>
</div>
) : (
charger && (
<>
{/* Status visual */}
<div className={`inline-block px-3 py-1 rounded-full text-sm font-semibold mb-4 ${statusColor}`}>
{charger.status.toUpperCase()}
</div>
<AnimatePresence mode="wait">
<motion.div
key={charger.currentPower}
initial={{ scale: 0.85, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.85, opacity: 0 }}
transition={{ duration: 0.5 }}
className="relative w-40 h-40 mx-auto mb-8 select-none"
>
<div
className={`absolute inset-0 rounded-full border-8 ${
charger.currentPower > 7
? 'border-yellow-400 opacity-60'
: 'border-blue-200 opacity-30'
}`}
/>
<div
className={`absolute inset-2 rounded-full border-8 ${
charger.currentPower > 7
? 'border-yellow-500'
: 'border-blue-600'
} flex flex-col items-center justify-center text-blue-700`}
>
<motion.div
initial={{ rotate: -10 }}
animate={{ rotate: [0, 12, -12, 0] }}
transition={{
duration: 1,
repeat: Infinity,
repeatType: 'mirror',
ease: 'easeInOut',
}}
className={`mb-1 ${
charger.currentPower > 7 ? 'text-yellow-500' : 'text-blue-600'
}`}
>
<Zap size={32} />
</motion.div>
<span className="text-4xl font-extrabold drop-shadow">
{charger.currentPower} kW
</span>
<span className="text-xs text-gray-400 font-medium mt-1 tracking-wide">
Power
</span>
</div>
</motion.div>
</AnimatePresence>
<div className="grid gap-5 text-sm text-gray-700 mb-8">
<InfoItem
icon={<BatteryCharging className="text-blue-500" />}
label="Status"
value={charger.status}
/>
<InfoItem
icon={<Clock className="text-gray-500" />}
label="Time Remaining"
value={charger.timeRemaining}
/>
<InfoItem
icon={<Zap className="text-yellow-500" />}
label="Power"
value={<span className="text-lg font-bold text-yellow-600">{charger.currentPower} kW</span>}
/>
<InfoItem
icon={<Activity className="text-indigo-500" />}
label="Mode"
value={charger.mode?.toUpperCase()}
/>
<InfoItem
icon={<Clock className="text-gray-500" />}
label="Última atividade"
value={new Date(charger.ultimaAtividade).toLocaleTimeString('pt-BR', {
hour: '2-digit',
minute: '2-digit',
})}
/>
</div>
<div className="mb-10">
<label
htmlFor="amp-range"
className="flex items-center gap-3 text-base font-medium text-gray-800 mb-4"
>
<Zap className="text-gray-600" size={20} />
Max Current: <span className="text-blue-700 font-semibold">{ampLimit} A</span>
</label>
<input
id="amp-range"
type="range"
min={6}
max={maxAmps}
value={ampLimit}
onChange={(e) => setAmpLimit(Number(e.target.value))}
className="w-full accent-blue-600"
disabled={busy}
/>
<div className="flex justify-between text-xs text-gray-500 mt-1">
<span>6 A</span>
<span>{maxAmps} A</span>
</div>
</div>
<div className="flex justify-center gap-4 mt-8">
<motion.button
whileTap={{ scale: 0.95 }}
onClick={() => handleAction('start')}
disabled={busy}
className="bg-green-600 hover:bg-green-700 text-white px-5 py-2 rounded-xl shadow font-medium flex items-center gap-2"
>
<Play size={18} /> Start
</motion.button>
<motion.button
whileTap={{ scale: 0.95 }}
onClick={() => handleAction('stop')}
disabled={busy}
className="bg-red-500 hover:bg-red-600 text-white px-5 py-2 rounded-xl shadow font-medium flex items-center gap-2"
>
<Square size={18} /> Stop
</motion.button>
</div>
</>
)
)}
</SectionCard>
</div>
);
}
function InfoItem({ icon, label, value }) {
return (
<div className="grid grid-cols-2 items-center gap-2 py-1.5">
<div className="flex items-center gap-2 text-gray-600 font-medium">
{icon}
<span>{label}</span>
</div>
<div className="text-right text-base font-semibold">{value}</div>
</div>
);
}

187
src/pages/ChargersPage.jsx Normal file
View File

@@ -0,0 +1,187 @@
// src/pages/ChargersPage.jsx
import React, { useState } from 'react';
import { Plus, Loader2, X, Trash2 } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useChargersContext } from '@/contexts/ChargersContext';
import { useToast } from '@/components/ToastContext';
export default function ChargersPage() {
const { chargers, selectedCharger, selectChargerById, fetchChargers, loading, error } = useChargersContext();
const [deletingId, setDeletingId] = useState(null);
const [showAdd, setShowAdd] = useState(false);
const toast = useToast();
const handleOpenAdd = () => setShowAdd(true);
const handleCloseAdd = () => setShowAdd(false);
const handleSelect = (charger) => {
selectChargerById(charger.id);
};
const handleDelete = async (id) => {
if (!window.confirm('Are you sure you want to delete this charger? This action cannot be undone.')) return;
setDeletingId(id);
try {
const res = await fetch(`/api/chargers/${id}`, { method: 'DELETE' });
if (!res.ok) throw new Error('Failed to delete charger');
toast('Charger deleted', 'success');
await fetchChargers();
} catch (err) {
console.error(err);
toast(err.message, 'error');
} finally {
setDeletingId(null);
}
};
if (loading) {
return (
<div className="flex items-center justify-center py-10">
<Loader2 className="animate-spin text-blue-500" size={32} />
</div>
);
}
if (error) {
return <p className="text-red-500">{error}</p>;
}
return (
<div className="max-w-2xl mx-auto p-4 pb-24">
<div className="flex items-center justify-between mb-5">
<h1 className="text-2xl font-bold">My Chargers</h1>
<button
className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg shadow hover:bg-blue-700 transition"
onClick={handleOpenAdd}
>
<Plus size={20} /> New Charger
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{chargers.length > 0 ? (
chargers.map((charger) => (
<motion.div
key={charger.id}
className={`bg-white rounded-xl shadow-md border p-5 flex flex-col gap-2 cursor-pointer relative transition ${
selectedCharger?.id === charger.id ? 'border-blue-500 bg-blue-50' : ''
}`}
onClick={() => handleSelect(charger)}
>
<button
className="absolute top-3 right-3 text-gray-400 hover:text-red-500 z-10"
onClick={(e) => { e.stopPropagation(); handleDelete(charger.id); }}
disabled={deletingId === charger.id}
>
{deletingId === charger.id ? <Loader2 className="animate-spin" size={18} /> : <Trash2 size={18} />}
</button>
<div className="flex items-center gap-2 mb-1">
<span
className={`inline-block w-2 h-2 rounded-full ${
charger.status === 'online'
? 'bg-green-500'
: charger.status === 'standby'
? 'bg-yellow-400'
: 'bg-gray-400'
}`}
/>
<span className="font-semibold text-lg">{charger.name}</span>
</div>
<div className="text-xs text-gray-500">
Pairing code: <span className="font-mono">{charger.pairingCode}</span>
</div>
<div className="text-xs text-gray-500">Location: {charger.location}</div>
<div className="text-xs text-gray-400">Last activity: {charger.lastActivity}</div>
</motion.div>
))
) : (
<p className="text-gray-500">No chargers found</p>
)}
</div>
<AnimatePresence>
{showAdd && <AddChargerModal onClose={handleCloseAdd} onSaved={fetchChargers} />}
</AnimatePresence>
</div>
);
}
function AddChargerModal({ onClose, onSaved }) {
const [name, setName] = useState('');
const [location, setLocation] = useState('');
const [saving, setSaving] = useState(false);
const toast = useToast();
const handleSubmit = async (e) => {
e.preventDefault();
setSaving(true);
try {
const res = await fetch('/api/chargers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, location }),
});
if (!res.ok) throw new Error('Failed to add charger');
toast('Charger added', 'success');
onSaved();
onClose();
} catch (err) {
console.error(err);
toast(err.message, 'error');
} finally {
setSaving(false);
}
};
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black bg-opacity-40 z-50 flex items-center justify-center"
>
<motion.div
initial={{ scale: 0.94, y: 40, opacity: 0 }}
animate={{ scale: 1, y: 0, opacity: 1 }}
exit={{ scale: 0.92, y: 40, opacity: 0 }}
className="bg-white rounded-2xl shadow-xl p-8 w-full max-w-sm relative"
>
<button
className="absolute top-3 right-3 text-gray-500 hover:text-gray-800"
onClick={onClose}
aria-label="Close modal"
>
<X />
</button>
<h2 className="text-xl font-bold mb-4">New Charger</h2>
<form className="space-y-4" onSubmit={handleSubmit}>
<div>
<label className="block text-sm font-medium mb-1">Name</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
className="w-full border border-gray-300 rounded-lg px-3 py-2"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Location</label>
<input
type="text"
value={location}
onChange={(e) => setLocation(e.target.value)}
required
className="w-full border border-gray-300 rounded-lg px-3 py-2"
/>
</div>
<button
type="submit"
disabled={saving}
className="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg transition flex items-center justify-center gap-2"
>
{saving && <Loader2 className="animate-spin" size={18} />} Save
</button>
</form>
</motion.div>
</motion.div>
);
}

98
src/pages/HistoryPage.jsx Normal file
View File

@@ -0,0 +1,98 @@
// src/pages/HistoryPage.jsx
import React, { useState, useEffect } from 'react';
import { History } from 'lucide-react';
import { SectionCard } from '@/components/ui/SectionCard';
import { useHistory } from '@/hooks/useHistory';
import { useChargersContext } from '@/contexts/ChargersContext';
import {
BarChart,
Bar,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
ReferenceLine,
} from 'recharts';
export default function HistoryPage() {
const { selectedCharger } = useChargersContext();
const chargerId = selectedCharger?.id;
const { histories, loading, error } = useHistory(chargerId);
// History/demo state
const [viewMode, setViewMode] = useState('Week');
const [chartData] = useState([
{ day: 'Mon', kwh: 12 },
{ day: 'Tue', kwh: 15 },
{ day: 'Wed', kwh: 13 },
{ day: 'Thu', kwh: 0 },
{ day: 'Fri', kwh: 14 },
{ day: 'Sat', kwh: 18 },
{ day: 'Sun', kwh: 12 },
]);
const [sessions] = useState([
{ date: '27 Oct', time: '19:30', kwh: 12, duration: '2h 03m', cost: '€2,40' },
{ date: '25 Oct', time: '07:15', kwh: 8, duration: '1h 20m', cost: '€1,60' },
]);
const totalKwh = chartData.reduce((sum, d) => sum + d.kwh, 0).toFixed(2);
const totalCost = (totalKwh * 0.2).toFixed(2);
return (
<div className="max-w-md mx-auto p-4 space-y-6">
{/* === Histórico === */}
<SectionCard title="Histórico" icon={<History size={20} />}>
<div className="flex gap-2 mb-4">
{['Week', 'Month', 'Year'].map(mode => (
<button
key={mode}
type="button"
onClick={() => setViewMode(mode)}
className={`px-3 py-1 rounded-full border text-sm transition ${viewMode === mode ? 'bg-green-600 text-white border-green-600' : 'bg-white text-gray-700 border-gray-300'}`}
>{mode}</button>
))}
</div>
<div className="mb-4">
<div className="text-sm text-gray-500">Total energy</div>
<div className="text-2xl font-bold">{totalKwh} kWh</div>
<div className="text-sm text-gray-500">Spent {totalCost}</div>
</div>
<div style={{ width: '100%', height: 160 }}>
<ResponsiveContainer>
<BarChart data={chartData}>
<XAxis dataKey="day" tickLine={false} />
<YAxis hide />
<Tooltip formatter={val => `${val} kWh`} />
<ReferenceLine y={chartData.reduce((s, d) => s + d.kwh, 0) / chartData.length} stroke="#999" strokeDasharray="3 3" />
<Bar dataKey="kwh" fill="#2563EB" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
<div className="flex items-center justify-center mt-2 text-sm text-gray-500 gap-4">
<button type="button"></button>
<span>23 29 Oct 2023</span>
<button type="button"></button>
</div>
<div className="mt-6 flex justify-between items-center">
<span className="font-medium text-gray-800">Recent sessions</span>
<button className="text-green-600 text-sm">View all</button>
</div>
<ul className="mt-2 space-y-2">
{sessions.map((s, i) => (
<li key={i} className="flex justify-between items-center">
<div className="text-sm">
<div>{s.date} · {s.time}</div>
<div className="text-gray-500 text-xs">{s.kwh} kWh · {s.duration}</div>
</div>
<div className="font-medium">{s.cost}</div>
</li>
))}
</ul>
</SectionCard>
</div>
);
}

96
src/pages/LoginPage.jsx Normal file
View File

@@ -0,0 +1,96 @@
import { useState, useRef } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useToast } from '@/components/ToastContext';
import { Loader2 } from 'lucide-react';
export default function Login() {
const { login } = useAuth();
const showToast = useToast();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const userInput = useRef(null);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (!res.ok) throw new Error(data?.error || 'Erro ao fazer login');
login(data.token); // ✅ usa o token corretamente
} catch (err) {
showToast(err.message, 'error');
setLoading(false);
userInput.current?.focus();
}
};
function handleForgotPassword(e) {
e.preventDefault();
showToast('Link de recuperação em breve!', 'success');
// Aqui você pode abrir modal, redirecionar, ou acionar fluxo real de recuperação
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="bg-white shadow-xl rounded-2xl p-8 w-full max-w-md">
<h1 className="text-2xl font-bold text-center mb-6 text-gray-800">EV Station Login</h1>
<form onSubmit={handleSubmit} className="space-y-5">
<div>
<label htmlFor="username" className="block text-sm font-medium mb-1 text-gray-700">Usuário</label>
<input
id="username"
ref={userInput}
type="text"
placeholder="Digite seu usuário"
value={username}
onChange={e => setUsername(e.target.value)}
className="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
required
autoFocus
/>
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium mb-1 text-gray-700">Senha</label>
<input
id="password"
type="password"
placeholder="Digite sua senha"
value={password}
onChange={e => setPassword(e.target.value)}
className="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
required
/>
</div>
<div className="flex justify-between items-center text-sm mt-1">
<button
type="button"
onClick={handleForgotPassword}
className="text-blue-600 hover:underline focus:outline-none"
tabIndex={0}
>
Esqueci a senha?
</button>
</div>
<button
type="submit"
disabled={loading}
className={`w-full flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 ${
loading ? 'opacity-70 cursor-not-allowed' : ''
}`}
>
{loading && <Loader2 className="animate-spin" size={20} />}
Entrar
</button>
</form>
</div>
</div>
);
}

185
src/pages/SettingsPage.jsx Normal file
View File

@@ -0,0 +1,185 @@
import React, { useState } from 'react';
import { Settings as SettingsIcon, Power, Loader2, CalendarDays } from 'lucide-react';
import { SectionCard } from '@/components/ui/SectionCard';
import { motion } from 'framer-motion';
import { useAuth } from '@/contexts/AuthContext';
import { useSchedules } from '@/hooks/useSchedules';
import { useToast } from '@/components/ToastContext';
import { useChargersContext } from '@/contexts/ChargersContext';
const dayLabels = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
export default function SettingsPage() {
const { logout } = useAuth();
const toast = useToast();
const [energyRate, setEnergyRate] = useState(0.5);
const [batteryCapacity, setBatteryCapacity] = useState(60);
const [chargeLimit, setChargeLimit] = useState(80);
const [theme, setTheme] = useState('light');
const [loadingDiag, setLoadingDiag] = useState(false);
const handleDiagnostic = () => {
setLoadingDiag(true);
setTimeout(() => {
setLoadingDiag(false);
toast('Diagnostic complete: Charger OK!', 'success');
}, 1200);
};
const { selectedCharger } = useChargersContext();
const chargerId = selectedCharger?.id;
const { schedules, setSchedules, loading, error } = useSchedules(chargerId);
const [start, setStart] = useState('15:30');
const [end, setEnd] = useState('20:00');
const [repeat, setRepeat] = useState('everyday');
const handleAddSchedule = (e) => {
e.preventDefault();
setSchedules([...schedules, { start, end, repeat }]);
toast('Agendamento adicionado!', 'success');
};
return (
<div className="max-w-2xl mx-auto p-4 space-y-6">
<SectionCard title="Agendamentos" icon={<CalendarDays size={20} />}>
<form onSubmit={handleAddSchedule} className="space-y-6 mb-4">
<div>
<p className="text-sm text-gray-500 mb-2">Your car ready when you need it.</p>
<div className="flex items-center gap-4">
<div className="flex flex-col items-start">
<label className="text-xs font-medium mb-1">Start</label>
<input
type="time"
value={start}
onChange={e => setStart(e.target.value)}
className="border px-4 py-2 rounded-lg text-lg"
required
/>
</div>
<div className="flex flex-col items-start">
<label className="text-xs font-medium mb-1">End</label>
<input
type="time"
value={end}
onChange={e => setEnd(e.target.value)}
className="border px-4 py-2 rounded-lg text-lg"
required
/>
</div>
</div>
</div>
<div>
<label className="block text-sm font-medium mb-2">Repeat</label>
<div className="flex gap-2 mb-3">
{['weekdays', 'weekends', 'everyday'].map(option => (
<button
key={option}
type="button"
onClick={() => setRepeat(option)}
className={`px-3 py-1 rounded-full text-sm border transition ${
repeat === option ? 'bg-emerald-600 text-white border-emerald-600' : 'bg-white text-gray-700 border-gray-300'
}`}
>
{option.charAt(0).toUpperCase() + option.slice(1)}
</button>
))}
</div>
<div className="flex justify-between">
{dayLabels.map((day, i) => (
<div
key={i}
className="w-8 h-8 rounded-full bg-emerald-600 text-white flex items-center justify-center text-sm font-medium"
>
{day}
</div>
))}
</div>
</div>
<button
type="submit"
className="w-full bg-emerald-600 text-white py-2 rounded-full text-base font-semibold mt-4"
>
Add schedule
</button>
</form>
{loading ? <p>Carregando...</p> : error ? <p className="text-red-500">{error}</p> : (
<ul className="space-y-2">
{schedules.length === 0 ? (
<li className="text-gray-500">Nenhum agendamento</li>
) : (
schedules.map((item, i) => (
<li key={i} className="bg-white p-3 shadow rounded-lg">
{item.start} - {item.end} ({item.repeat})
</li>
))
)}
</ul>
)}
</SectionCard>
<SectionCard title="Settings" icon={<SettingsIcon className="text-blue-600" /> }>
<div className="space-y-5">
<div>
<label className="block text-sm font-medium mb-1">Energy rate (USD/kWh)</label>
<input
type="number" step="0.01" min={0}
value={energyRate}
onChange={e => setEnergyRate(parseFloat(e.target.value))}
className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Battery capacity (kWh)</label>
<input
type="number" min={1}
value={batteryCapacity}
onChange={e => setBatteryCapacity(parseInt(e.target.value))}
className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Charge limit (%)</label>
<input
type="number" min={1} max={100}
value={chargeLimit}
onChange={e => setChargeLimit(Math.min(100, Math.max(1, parseInt(e.target.value))))}
className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Theme</label>
<select
value={theme}
onChange={e => setTheme(e.target.value)}
className="w-full border px-4 py-2 rounded-lg focus:ring-2 focus:ring-blue-500"
>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div>
<label className="block text-sm font-medium mb-1">Quick Diagnostic</label>
<motion.button
whileTap={{ scale: 0.96 }}
onClick={handleDiagnostic}
disabled={loadingDiag}
className="w-full bg-blue-600 text-white py-2 rounded-lg flex items-center justify-center gap-2"
>
{loadingDiag ? <Loader2 className="animate-spin" size={18}/> : 'Run Diagnostic'}
</motion.button>
</div>
<motion.button
whileTap={{ scale: 0.96 }}
onClick={logout}
className="w-full bg-red-500 text-white py-2 rounded-lg"
>Logout</motion.button>
</div>
</SectionCard>
</div>
);
}

View File

@@ -0,0 +1,5 @@
export function getAuthHeader() {
if (typeof window === 'undefined') return {};
const token = window.localStorage?.getItem('token');
return token ? { Authorization: `Bearer ${token}` } : {};
}

18
src/utils/apiFetch.js Normal file
View File

@@ -0,0 +1,18 @@
// utils/apiFetch.js
import { getAuthHeader } from './apiAuthHeader';
export async function apiFetch(url, options = {}) {
const res = await fetch(url, {
...options,
headers: {
...getAuthHeader(),
...(options.headers || {}),
},
});
const json = await res.json();
if (!res.ok || !json.success) {
throw new Error(json.message || 'Erro na requisição');
}
return json.data;
}

53
vite.config.js Executable file
View File

@@ -0,0 +1,53 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { VitePWA } from 'vite-plugin-pwa';
import path from 'path'; // 👈 necessário para resolver caminhos
export default defineConfig({
base: '/',
plugins: [
react(),
tailwindcss(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['icons/icon-192.png', 'icons/icon-512.png', 'favicon.ico'],
manifest: {
name: 'EV Station Controller',
short_name: 'EVStation',
start_url: '/',
display: 'standalone',
background_color: '#ffffff',
theme_color: '#0f172a',
icons: [
{
src: 'icons/icon-192.png',
sizes: '192x192',
type: 'image/png',
},
{
src: 'icons/icon-512.png',
sizes: '512x512',
type: 'image/png',
},
],
},
}),
],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'), // 👈 alias @ → ./src
},
},
server: {
proxy: {
'/api': 'http://localhost:4000',
},
},
build: {
sourcemap: false,
minify: 'esbuild',
target: 'esnext',
outDir: 'dist',
},
});