feat: React control panel; pending-card review workflow; auth-method audit

Frontend rewrite (frontend/, replacing backend/static/):
- Vite + TypeScript + React 19, React Router 7, zustand, TanStack Query 5
- dev: vite proxy /api -> :9000; prod: npm run build -> dist/, served by
  the backend with SPA fallback
- pages: Control (gun bays w/ scope+readiness-gated start/stop, relays),
  History (who/via/gun/when/duration/kWh audit), Cards (pending review,
  enrolled, rejected), Users (permission checkbox matrix)
- self-contained: fonts bundled, no CDN; light/dark; reduced-motion safe

Backend:
- learn mode removed: unknown cards are always refused and queued in
  pending_cards; admin approves (name + owner + gun restrictions in one
  step) or rejects (denied_cards, silent, un-rejectable); pending count
  rides /api/status as the notification signal
- sessions record the auth method (card tap vs in-app button) for audit
- GET /api/permissions: grantable-permission catalog driving the UI matrix
- SPA static serving with path-traversal guard; 503 hint when not built

Smoke test: 54 checks incl. approve/reject round-trips over a fake charge
point and method audit assertions.
This commit is contained in:
2026-07-11 20:52:20 +02:00
parent 56c9020d9f
commit 75869364b0
41 changed files with 4057 additions and 610 deletions
+2
View File
@@ -0,0 +1,2 @@
node_modules/
dist/
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#171d1b" />
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
<link rel="manifest" href="/manifest.json" />
<title>Charge Control</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1958
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "charging-station-panel",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@fontsource/archivo": "^5.1.0",
"@fontsource/ibm-plex-mono": "^5.1.0",
"@tanstack/react-query": "^5.62.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.1.0",
"zustand": "^5.0.2"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2",
"vite": "^6.0.5"
}
}
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect width="100" height="100" rx="22" fill="#171d1b"/>
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" fill="#c9773d"/>
</svg>

After

Width:  |  Height:  |  Size: 201 B

+12
View File
@@ -0,0 +1,12 @@
{
"name": "Charge Control",
"short_name": "Charge",
"description": "Home EV charger and relay control",
"start_url": "/",
"display": "standalone",
"background_color": "#171d1b",
"theme_color": "#171d1b",
"icons": [
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
]
}
+55
View File
@@ -0,0 +1,55 @@
import { useEffect } from "react";
import { Navigate, Route, Routes, useLocation } from "react-router-dom";
import { api, ApiError, isAdmin } from "./api";
import { useApp } from "./store";
import type { Me } from "./types";
import Layout from "./components/Layout";
import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard";
import History from "./pages/History";
import Cards from "./pages/Cards";
import Users from "./pages/Users";
export default function App() {
const { me, authChecked, setMe } = useApp();
const location = useLocation();
useEffect(() => {
api
.get<Me>("/me")
.then(setMe)
.catch((e) => {
if (e instanceof ApiError && e.status === 401) setMe(null);
else setMe(null);
});
}, [setMe]);
if (!authChecked) {
return (
<div className="boot">
<span className="lamp lamp--amber" /> Connecting…
</div>
);
}
if (!me) {
return (
<Routes>
<Route path="*" element={<Login />} />
</Routes>
);
}
const admin = isAdmin(me.scopes);
return (
<Routes>
<Route element={<Layout />}>
<Route path="/" element={<Dashboard />} />
<Route path="/history" element={<History />} />
{admin && <Route path="/cards" element={<Cards />} />}
{admin && <Route path="/users" element={<Users />} />}
<Route path="*" element={<Navigate to="/" replace state={{ from: location }} />} />
</Route>
</Routes>
);
}
+52
View File
@@ -0,0 +1,52 @@
export class ApiError extends Error {
status: number;
constructor(status: number, detail: string) {
super(detail);
this.status = status;
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`/api${path}`, {
headers: init?.body ? { "Content-Type": "application/json" } : undefined,
...init,
});
if (!res.ok) {
let detail = res.statusText;
try {
detail = (await res.json()).detail ?? detail;
} catch {
/* non-JSON error body */
}
throw new ApiError(res.status, detail);
}
return res.json() as Promise<T>;
}
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) =>
request<T>(path, { method: "POST", body: body ? JSON.stringify(body) : undefined }),
put: <T>(path: string, body: unknown) =>
request<T>(path, { method: "PUT", body: JSON.stringify(body) }),
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
};
/** Mirrors backend/users.py `allowed()` — fnmatch-lite scope check. */
export function scopeAllowed(scopes: string[], needed: string): boolean {
return scopes.some((grant) => {
if (grant === "*" || grant === "admin") return true;
const re = new RegExp(
"^" +
grant
.split("*")
.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
.join(".*") +
"$",
);
return re.test(needed);
});
}
export const isAdmin = (scopes: string[]) =>
scopes.some((s) => s === "admin" || s === "*");
+34
View File
@@ -0,0 +1,34 @@
/** The signature element: a physical indicator lamp, like the ones on the
* charger cabinet itself. Tone encodes state everywhere in the app. */
export type LampTone = "off" | "green" | "amber" | "red" | "pulse";
const TONE_CLASS: Record<LampTone, string> = {
off: "lamp",
green: "lamp lamp--green",
amber: "lamp lamp--amber",
red: "lamp lamp--red",
pulse: "lamp lamp--green lamp--pulse",
};
export function Lamp({ tone, title }: { tone: LampTone; title?: string }) {
return <span className={TONE_CLASS[tone]} title={title} aria-hidden />;
}
export function statusTone(ocppStatus: string, charging: boolean): LampTone {
if (charging) return "pulse";
switch (ocppStatus) {
case "Charging":
return "pulse";
case "Preparing":
case "Finishing":
case "Reserved":
return "amber";
case "Available":
return "green";
case "Faulted":
case "Unavailable":
return "red";
default:
return "off";
}
}
+86
View File
@@ -0,0 +1,86 @@
import { NavLink, Outlet } from "react-router-dom";
import { api, isAdmin } from "../api";
import { useApp } from "../store";
import { useStatus } from "../queries";
const NAV = [
{ to: "/", label: "Control", exact: true },
{ to: "/history", label: "History" },
];
const ADMIN_NAV = [
{ to: "/cards", label: "Cards" },
{ to: "/users", label: "Users" },
];
export default function Layout() {
const { me, setMe, toasts } = useApp();
const { data: status } = useStatus();
const admin = me ? isAdmin(me.scopes) : false;
const pending = status?.pending_cards ?? 0;
async function logout() {
await api.post("/logout").catch(() => undefined);
setMe(null);
}
return (
<div className="shell">
<header className="topbar">
<div className="brand">
<svg viewBox="0 0 100 100" className="brand__mark" aria-hidden>
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" />
</svg>
<div>
<span className="brand__name">Charge Control</span>
<span className="brand__sub">private CSMS</span>
</div>
</div>
<nav className="nav" aria-label="Main">
{NAV.map((n) => (
<NavLink key={n.to} to={n.to} end={n.exact} className="nav__link">
{n.label}
</NavLink>
))}
{admin &&
ADMIN_NAV.map((n) => (
<NavLink key={n.to} to={n.to} className="nav__link">
{n.label}
{n.to === "/cards" && pending > 0 && (
<span className="badge" title={`${pending} card(s) awaiting review`}>
{pending}
</span>
)}
</NavLink>
))}
</nav>
<div className="topbar__user">
<span className="topbar__who">{me?.name}</span>
<button className="btn btn--ghost btn--sm" onClick={logout}>
Log out
</button>
</div>
</header>
{admin && pending > 0 && (
<NavLink to="/cards" className="alert">
<span className="lamp lamp--amber" />
{pending === 1 ? "An unknown card was presented" : `${pending} unknown cards were presented`}
&nbsp;— review and approve or reject.
</NavLink>
)}
<main className="content">
<Outlet />
</main>
<div className="toasts" role="status">
{toasts.map((t) => (
<div key={t.id} className={`toast toast--${t.tone}`}>
{t.text}
</div>
))}
</div>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
import "@fontsource/archivo/400.css";
import "@fontsource/archivo/500.css";
import "@fontsource/archivo/600.css";
import "@fontsource/archivo/700.css";
import "@fontsource/ibm-plex-mono/400.css";
import "@fontsource/ibm-plex-mono/500.css";
import "@fontsource/ibm-plex-mono/600.css";
import "./styles.css";
const queryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: 3000, refetchOnWindowFocus: true },
},
});
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
</BrowserRouter>
</QueryClientProvider>
</React.StrictMode>,
);
+318
View File
@@ -0,0 +1,318 @@
import { useState } from "react";
import { api } from "../api";
import { Lamp } from "../components/Lamp";
import {
useAction,
useAllowlist,
useDenied,
usePending,
usePermissions,
useUsers,
} from "../queries";
import { useApp } from "../store";
import type { CardEntry, PermissionCatalog } from "../types";
const fmtTime = (iso?: string | null) =>
iso ? new Date(iso).toLocaleString([], { dateStyle: "medium", timeStyle: "short" }) : "—";
/** Checkbox list of every gun in the system -> ["eu092025:2", ...]; empty = all guns. */
function GunPicker({
catalog,
value,
onChange,
}: {
catalog: PermissionCatalog | undefined;
value: string[];
onChange: (guns: string[]) => void;
}) {
if (!catalog) return null;
const toggle = (gun: string) =>
onChange(value.includes(gun) ? value.filter((g) => g !== gun) : [...value, gun]);
return (
<div className="gunpicker">
<span className="field__label">Allowed guns (none checked = all)</span>
{Object.entries(catalog.chargers).map(([cp, meta]) => (
<div key={cp} className="gunpicker__charger">
{Object.entries(meta.guns).map(([conn, label]) => {
const gun = `${cp}:${conn}`;
return (
<label key={gun} className="check">
<input
type="checkbox"
checked={value.includes(gun)}
onChange={() => toggle(gun)}
/>
<span>
{meta.label} — {label}
</span>
</label>
);
})}
</div>
))}
</div>
);
}
function CardForm({
initial,
submitLabel,
busy,
onSubmit,
onCancel,
}: {
initial: CardEntry;
submitLabel: string;
busy: boolean;
onSubmit: (entry: CardEntry) => void;
onCancel?: () => void;
}) {
const { data: users } = useUsers();
const { data: catalog } = usePermissions();
const [name, setName] = useState(initial.name);
const [owner, setOwner] = useState(initial.user ?? "");
const [guns, setGuns] = useState<string[]>(initial.guns ?? []);
return (
<form
className="cardform"
onSubmit={(e) => {
e.preventDefault();
onSubmit({
name: name.trim(),
kind: initial.kind || "card",
...(owner ? { user: owner } : {}),
...(guns.length ? { guns } : {}),
});
}}
>
<label className="field">
<span>Card name</span>
<input value={name} onChange={(e) => setName(e.target.value)} required placeholder="e.g. Blue keyfob" />
</label>
<label className="field">
<span>Belongs to</span>
<select value={owner} onChange={(e) => setOwner(e.target.value)}>
<option value="">Nobody (unassigned)</option>
{users?.map((u) => (
<option key={u.name} value={u.name}>
{u.name}
</option>
))}
</select>
</label>
<GunPicker catalog={catalog} value={guns} onChange={setGuns} />
<div className="cardform__actions">
<button className="btn btn--primary btn--sm" disabled={busy}>
{submitLabel}
</button>
{onCancel && (
<button type="button" className="btn btn--ghost btn--sm" onClick={onCancel}>
Cancel
</button>
)}
</div>
</form>
);
}
function PendingSection() {
const toast = useApp((s) => s.toast);
const { data: pending } = usePending();
const [open, setOpen] = useState<string | null>(null);
const approve = useAction(
({ tag, entry }: { tag: string; entry: CardEntry }) =>
api.post(`/cards/pending/${encodeURIComponent(tag)}/approve`, entry),
[["pending"], ["allowlist"], ["status"]],
() => {
toast("Card approved and enrolled");
setOpen(null);
},
);
const reject = useAction(
(tag: string) => api.post(`/cards/pending/${encodeURIComponent(tag)}/reject`),
[["pending"], ["denied"], ["status"]],
() => toast("Card rejected — it will be silently refused from now on"),
);
const entries = Object.entries(pending ?? {});
if (!entries.length) return null;
return (
<section className="panel panel--attention">
<header className="panel__head">
<h2>
<Lamp tone="amber" /> Awaiting review
</h2>
<span className="panel__meta">
unknown cards presented at a charger — approve to enroll, reject to silence
</span>
</header>
<ul className="pending-list">
{entries.map(([tag, meta]) => (
<li key={tag} className="pending">
<div className="pending__row">
<div>
<span className="mono strong">{tag}</span>
<span className="pending__meta">
tapped ×{meta.count} · last {fmtTime(meta.last_seen)}
{meta.cp ? ` · at ${meta.cp}${meta.connector ? ` gun ${meta.connector}` : ""}` : ""}
</span>
</div>
<div className="pending__actions">
<button
className="btn btn--primary btn--sm"
onClick={() => setOpen(open === tag ? null : tag)}
>
Approve…
</button>
<button
className="btn btn--danger btn--sm"
disabled={reject.isPending}
onClick={() => reject.mutate(tag)}
>
Reject
</button>
</div>
</div>
{open === tag && (
<CardForm
initial={{ name: "", kind: "card" }}
submitLabel="Approve & enroll"
busy={approve.isPending}
onSubmit={(entry) => approve.mutate({ tag, entry })}
onCancel={() => setOpen(null)}
/>
)}
</li>
))}
</ul>
</section>
);
}
function AuthorizedSection() {
const toast = useApp((s) => s.toast);
const { data } = useAllowlist();
const [editing, setEditing] = useState<string | null>(null);
const save = useAction(
({ tag, entry }: { tag: string; entry: CardEntry }) =>
api.put(`/allowlist/${encodeURIComponent(tag)}`, entry),
[["allowlist"]],
() => {
toast("Card updated");
setEditing(null);
},
);
const remove = useAction(
(tag: string) => api.delete(`/allowlist/${encodeURIComponent(tag)}`),
[["allowlist"]],
() => toast("Card removed"),
);
const entries = Object.entries(data?.authorized ?? {});
return (
<section className="panel">
<header className="panel__head">
<h2>Enrolled cards &amp; tokens</h2>
<span className="panel__meta">what may authorize a charge, and who it belongs to</span>
</header>
{!entries.length && <p className="empty">Nothing enrolled yet.</p>}
<div className="table-wrap">
<table className="table">
<tbody>
{entries.map(([tag, entry]) => (
<tr key={tag}>
<td className="mono">{tag}</td>
<td className="strong">{entry.name}</td>
<td>
<span className={`chip chip--${entry.kind === "app" ? "app" : "card"}`}>
{entry.kind}
</span>
</td>
<td>{entry.user ?? <span className="dim">unassigned</span>}</td>
<td className="dim">{entry.guns?.join(", ") ?? "all guns"}</td>
<td className="num">
<button className="btn btn--ghost btn--sm" onClick={() => setEditing(tag)}>
Edit
</button>
<button
className="btn btn--ghost btn--sm btn--dangertext"
onClick={() => {
if (confirm(`Remove ${entry.name} (${tag})?`)) remove.mutate(tag);
}}
>
Remove
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{editing && data?.authorized[editing] && (
<div className="panel__inset">
<h3 className="mono">{editing}</h3>
<CardForm
initial={data.authorized[editing]}
submitLabel="Save changes"
busy={save.isPending}
onSubmit={(entry) =>
save.mutate({ tag: editing, entry: { ...entry, kind: data.authorized[editing].kind } })
}
onCancel={() => setEditing(null)}
/>
</div>
)}
</section>
);
}
function DeniedSection() {
const toast = useApp((s) => s.toast);
const { data: denied } = useDenied();
const undeny = useAction(
(tag: string) => api.delete(`/cards/denied/${encodeURIComponent(tag)}`),
[["denied"]],
() => toast("Card un-rejected — it pends again on its next tap"),
);
const entries = Object.entries(denied ?? {});
if (!entries.length) return null;
return (
<section className="panel">
<header className="panel__head">
<h2>Rejected cards</h2>
<span className="panel__meta">silently refused; un-reject to reconsider</span>
</header>
<ul className="relay-list">
{entries.map(([tag, meta]) => (
<li key={tag} className="relay">
<Lamp tone="red" />
<span className="mono relay__label">{tag}</span>
<span className="relay__state">
by {meta.by} · {fmtTime(meta.rejected_at)}
</span>
<button className="btn btn--ghost btn--sm" onClick={() => undeny.mutate(tag)}>
Un-reject
</button>
</li>
))}
</ul>
</section>
);
}
export default function Cards() {
return (
<>
<PendingSection />
<AuthorizedSection />
<DeniedSection />
</>
);
}
+199
View File
@@ -0,0 +1,199 @@
import { api, scopeAllowed } from "../api";
import { Lamp, statusTone } from "../components/Lamp";
import { useAction, useLiveRelays, useStatus } from "../queries";
import { useApp } from "../store";
import type { ActiveTx, Status } from "../types";
function fmtSince(iso: string): string {
const mins = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 60000));
return mins >= 60 ? `${Math.floor(mins / 60)} h ${mins % 60} min` : `${mins} min`;
}
interface Gun {
cp: string;
connector: number;
label: string;
chargerLabel: string;
ocppStatus: string;
tx: (ActiveTx & { txId: string }) | null;
}
function gunsFrom(status: Status): Gun[] {
const txByGun = new Map<string, ActiveTx & { txId: string }>();
for (const [txId, tx] of Object.entries(status.active_transactions))
txByGun.set(`${tx.cp}/${tx.connector}`, { ...tx, txId });
return Object.entries(status.connectors)
.map(([key, ocppStatus]) => {
const [cp, conn] = [key.slice(0, key.lastIndexOf("/")), key.slice(key.lastIndexOf("/") + 1)];
return { cp, connector: Number(conn), ocppStatus };
})
.filter((g) => g.connector > 0)
.sort((a, b) => a.cp.localeCompare(b.cp) || a.connector - b.connector)
.map((g) => {
const meta = status.chargers[g.cp] ?? {};
return {
...g,
label: meta.guns?.[String(g.connector)] ?? `Gun ${g.connector}`,
chargerLabel: meta.label ?? g.cp,
tx: txByGun.get(`${g.cp}/${g.connector}`) ?? null,
};
});
}
function GunBay({ gun, scopes }: { gun: Gun; scopes: string[] }) {
const toast = useApp((s) => s.toast);
const may = scopeAllowed(scopes, `charger:${gun.cp}:${gun.connector}`);
const ready = !gun.tx && (gun.ocppStatus === "Preparing" || gun.ocppStatus === "Available");
const start = useAction(
() =>
api.post<{ remote_start: string }>(
`/charger/start?connector=${gun.connector}&cp=${encodeURIComponent(gun.cp)}`,
),
[["status"], ["sessions"]],
(r) => toast(`Start command: ${r.remote_start}`),
);
const stop = useAction(
() => api.post<{ remote_stop: string }>(`/charger/stop/${gun.tx!.txId}`),
[["status"], ["sessions"]],
(r) => toast(`Stop command: ${r.remote_stop}`),
);
return (
<article className="bay">
<header className="bay__head">
<span className="bay__eyebrow">{gun.chargerLabel}</span>
<Lamp tone={statusTone(gun.ocppStatus, !!gun.tx)} title={gun.ocppStatus} />
</header>
<h2 className="bay__title">{gun.label}</h2>
<div className="bay__status">
<span className={`chip chip--${gun.tx ? "live" : gun.ocppStatus.toLowerCase()}`}>
{gun.tx ? "Charging" : gun.ocppStatus}
</span>
{gun.ocppStatus === "Preparing" && !gun.tx && (
<span className="bay__hint">cable plugged — ready to start</span>
)}
</div>
{gun.tx && (
<dl className="bay__telemetry">
<div>
<dt>By</dt>
<dd>{gun.tx.who || gun.tx.id_tag}</dd>
</div>
<div>
<dt>Via</dt>
<dd>{gun.tx.method === "app" ? "In-app" : gun.tx.method === "card" ? "Card" : gun.tx.method}</dd>
</div>
<div>
<dt>Running</dt>
<dd>{fmtSince(gun.tx.started)}</dd>
</div>
</dl>
)}
<footer className="bay__actions">
{gun.tx ? (
<button
className="btn btn--danger"
disabled={!may || stop.isPending}
onClick={() => stop.mutate()}
>
{stop.isPending ? "Stopping…" : "Stop charging"}
</button>
) : (
<button
className="btn btn--primary"
disabled={!may || !ready || start.isPending}
onClick={() => start.mutate()}
>
{start.isPending ? "Starting…" : "Start charging"}
</button>
)}
{!may && <span className="bay__hint">no permission for this gun</span>}
</footer>
</article>
);
}
function Relays({ status, scopes }: { status: Status; scopes: string[] }) {
const toast = useApp((s) => s.toast);
const live = useLiveRelays();
const names = Object.keys(status.relays);
const toggle = useAction(
(name: string) => api.post<{ relay: string; on: boolean }>(`/relays/${encodeURIComponent(name)}/toggle`),
[["relays-live"]],
(r) => toast(`${r.relay}: ${r.on ? "on" : "off"}`),
);
if (!names.length) return null;
return (
<section className="panel">
<header className="panel__head">
<h2>Relays</h2>
<button
className="btn btn--ghost btn--sm"
onClick={() => live.refetch()}
disabled={live.isFetching}
>
{live.isFetching ? "Reading…" : "Read states"}
</button>
</header>
<ul className="relay-list">
{names.map((name) => {
const state = live.data?.[name];
const on = state && "on" in state ? state.on : undefined;
return (
<li key={name} className="relay">
<Lamp tone={on === undefined ? "off" : on ? "green" : "off"} />
<span className="relay__label">{status.relays[name].label}</span>
<span className="relay__state">
{state?.error ? "unreachable" : on === undefined ? "—" : on ? "on" : "off"}
</span>
<button
className="btn btn--ghost btn--sm"
disabled={!scopeAllowed(scopes, `relay:${name}`) || toggle.isPending}
onClick={() => toggle.mutate(name)}
>
Toggle
</button>
</li>
);
})}
</ul>
</section>
);
}
export default function Dashboard() {
const me = useApp((s) => s.me)!;
const { data: status, isLoading, error } = useStatus();
if (isLoading) return <p className="empty">Reading charger status…</p>;
if (error || !status) return <p className="empty">Status unavailable: {(error as Error)?.message}</p>;
const guns = gunsFrom(status);
const offline = Object.keys(status.connected).length === 0;
return (
<>
{offline && (
<div className="panel panel--offline">
<Lamp tone="red" />
<div>
<h2>Charger offline</h2>
<p>Waiting for the charge point to dial in. Guns appear here as soon as it connects.</p>
</div>
</div>
)}
<div className="bays">
{guns.map((g) => (
<GunBay key={`${g.cp}/${g.connector}`} gun={g} scopes={me.scopes} />
))}
</div>
<Relays status={status} scopes={me.scopes} />
</>
);
}
+85
View File
@@ -0,0 +1,85 @@
import { useSessions, useStatus } from "../queries";
import type { Session } from "../types";
const fmtKwh = (wh: number | null) => (wh == null ? "—" : (wh / 1000).toFixed(2));
const fmtTime = (iso: string | null) =>
iso ? new Date(iso).toLocaleString([], { dateStyle: "medium", timeStyle: "short" }) : "—";
function fmtDuration(a: string, b: string | null): string {
if (!b) return "";
const mins = Math.max(0, Math.round((new Date(b).getTime() - new Date(a).getTime()) / 60000));
return mins >= 60 ? `${Math.floor(mins / 60)} h ${String(mins % 60).padStart(2, "0")} min` : `${mins} min`;
}
function MethodChip({ method }: { method: string | null }) {
if (method === "card") return <span className="chip chip--card">Card</span>;
if (method === "app") return <span className="chip chip--app">In-app</span>;
return <span className="chip">{method ?? "—"}</span>;
}
function gunLabel(s: Session, chargers: Record<string, { label?: string; guns?: Record<string, string> }>) {
const meta = chargers[s.cp];
return meta?.guns?.[String(s.connector)] ?? `${s.cp} · gun ${s.connector}`;
}
export default function History() {
const { data: sessions, isLoading } = useSessions();
const { data: status } = useStatus();
if (isLoading) return <p className="empty">Loading history…</p>;
if (!sessions?.length)
return (
<p className="empty">
No charging sessions yet. The first card tap or in-app start will appear here with who,
when, how, and how many kWh.
</p>
);
const totalKwh = sessions.reduce((acc, s) => acc + (s.wh ?? 0), 0) / 1000;
return (
<section className="panel">
<header className="panel__head">
<h2>Charging sessions</h2>
<span className="panel__meta">
{sessions.length} session{sessions.length === 1 ? "" : "s"} ·{" "}
<strong className="mono">{totalKwh.toFixed(1)} kWh</strong> total
</span>
</header>
<div className="table-wrap">
<table className="table">
<thead>
<tr>
<th>Who</th>
<th>Via</th>
<th>Gun</th>
<th>Started</th>
<th>Duration</th>
<th className="num">kWh</th>
</tr>
</thead>
<tbody>
{sessions.map((s) => (
<tr key={s.tx}>
<td className="strong">{s.who || s.id_tag}</td>
<td>
<MethodChip method={s.method} />
</td>
<td>{gunLabel(s, status?.chargers ?? {})}</td>
<td className="mono">{fmtTime(s.started)}</td>
<td>
{s.ended ? (
fmtDuration(s.started, s.ended)
) : (
<span className="chip chip--live">charging</span>
)}
</td>
<td className="num mono strong">{fmtKwh(s.wh)}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { FormEvent, useState } from "react";
import { api } from "../api";
import { useApp } from "../store";
import type { Me } from "../types";
export default function Login() {
const setMe = useApp((s) => s.setMe);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const r = await api.post<{ user: Me }>("/login", { username, password });
setMe(r.user);
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}
return (
<div className="login">
<form className="login__panel" onSubmit={submit}>
<div className="login__head">
<svg viewBox="0 0 100 100" className="login__mark" aria-hidden>
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" />
</svg>
<h1>Charge Control</h1>
<p>Private charging backend — sign in to operate.</p>
</div>
<label className="field">
<span>Username</span>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
autoComplete="username"
autoFocus
required
/>
</label>
<label className="field">
<span>Password</span>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
required
/>
</label>
{error && <p className="field-error">{error}</p>}
<button className="btn btn--primary btn--block" disabled={busy}>
{busy ? "Signing in…" : "Sign in"}
</button>
</form>
</div>
);
}
+275
View File
@@ -0,0 +1,275 @@
import { useMemo, useState } from "react";
import { api, isAdmin, scopeAllowed } from "../api";
import { useAction, usePermissions, useUsers } from "../queries";
import { useApp } from "../store";
import type { Me, PermissionCatalog } from "../types";
/** The permission matrix: scopes rendered as checkboxes instead of raw strings. */
interface Matrix {
admin: boolean;
guns: string[]; // "cp:conn"
allRelays: boolean;
relays: string[];
}
function toMatrix(scopes: string[], catalog: PermissionCatalog): Matrix {
const nonAdmin = scopes.filter((s) => s !== "admin" && s !== "*");
const guns: string[] = [];
for (const [cp, meta] of Object.entries(catalog.chargers))
for (const conn of Object.keys(meta.guns))
if (scopeAllowed(nonAdmin, `charger:${cp}:${conn}`)) guns.push(`${cp}:${conn}`);
const allRelays = nonAdmin.includes("relay:*");
const relays = allRelays
? []
: Object.keys(catalog.relays).filter((r) => scopeAllowed(nonAdmin, `relay:${r}`));
return { admin: isAdmin(scopes), guns, allRelays, relays };
}
function toScopes(m: Matrix): string[] {
if (m.admin) return ["admin"];
return [
...m.guns.map((g) => `charger:${g}`),
...(m.allRelays ? ["relay:*"] : m.relays.map((r) => `relay:${r}`)),
];
}
function MatrixEditor({
catalog,
value,
onChange,
}: {
catalog: PermissionCatalog;
value: Matrix;
onChange: (m: Matrix) => void;
}) {
const toggleList = (list: string[], item: string) =>
list.includes(item) ? list.filter((x) => x !== item) : [...list, item];
return (
<div className="matrix">
<label className="check check--strong">
<input
type="checkbox"
checked={value.admin}
onChange={() => onChange({ ...value, admin: !value.admin })}
/>
<span>Administrator — everything, including cards, users and settings</span>
</label>
{!value.admin && (
<>
<div className="matrix__group">
<span className="field__label">Charging guns</span>
{Object.entries(catalog.chargers).map(([cp, meta]) =>
Object.entries(meta.guns).map(([conn, label]) => {
const gun = `${cp}:${conn}`;
return (
<label key={gun} className="check">
<input
type="checkbox"
checked={value.guns.includes(gun)}
onChange={() => onChange({ ...value, guns: toggleList(value.guns, gun) })}
/>
<span>
{meta.label} — {label}
</span>
</label>
);
}),
)}
{!Object.keys(catalog.chargers).length && (
<span className="dim">no chargers known yet</span>
)}
</div>
<div className="matrix__group">
<span className="field__label">Relays</span>
<label className="check">
<input
type="checkbox"
checked={value.allRelays}
onChange={() => onChange({ ...value, allRelays: !value.allRelays })}
/>
<span>All relays (including future ones)</span>
</label>
{!value.allRelays &&
Object.entries(catalog.relays).map(([name, meta]) => (
<label key={name} className="check">
<input
type="checkbox"
checked={value.relays.includes(name)}
onChange={() =>
onChange({ ...value, relays: toggleList(value.relays, name) })
}
/>
<span>{meta.label}</span>
</label>
))}
{!value.allRelays && !Object.keys(catalog.relays).length && (
<span className="dim">no relays registered yet</span>
)}
</div>
</>
)}
</div>
);
}
function UserEditor({
user,
catalog,
onClose,
}: {
user: Me | null; // null = create new
catalog: PermissionCatalog;
onClose: () => void;
}) {
const toast = useApp((s) => s.toast);
const [name, setName] = useState(user?.name ?? "");
const [password, setPassword] = useState("");
const [matrix, setMatrix] = useState<Matrix>(() =>
user ? toMatrix(user.scopes, catalog) : { admin: false, guns: [], allRelays: false, relays: [] },
);
const save = useAction(
() =>
api.put(`/users/${encodeURIComponent(name.trim())}`, {
...(password ? { password } : {}),
scopes: toScopes(matrix),
}),
[["users"]],
() => {
toast(user ? "User updated" : "User created");
onClose();
},
);
return (
<form
className="panel__inset"
onSubmit={(e) => {
e.preventDefault();
save.mutate();
}}
>
<h3>{user ? `Edit ${user.name}` : "New user"}</h3>
<div className="formrow">
<label className="field">
<span>Username</span>
<input
value={name}
onChange={(e) => setName(e.target.value)}
disabled={!!user}
required
placeholder="e.g. maria"
/>
</label>
<label className="field">
<span>{user ? "New password (empty = keep)" : "Password"}</span>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required={!user}
autoComplete="new-password"
/>
</label>
</div>
<MatrixEditor catalog={catalog} value={matrix} onChange={setMatrix} />
<div className="cardform__actions">
<button className="btn btn--primary btn--sm" disabled={save.isPending}>
{user ? "Save changes" : "Create user"}
</button>
<button type="button" className="btn btn--ghost btn--sm" onClick={onClose}>
Cancel
</button>
</div>
</form>
);
}
function describeScopes(scopes: string[], catalog: PermissionCatalog): string {
if (isAdmin(scopes)) return "Administrator";
const m = toMatrix(scopes, catalog);
const parts: string[] = [];
for (const gun of m.guns) {
const [cp, conn] = gun.split(":");
const meta = catalog.chargers[cp];
parts.push(meta ? `${meta.label} ${meta.guns[conn] ?? `gun ${conn}`}` : gun);
}
if (m.allRelays) parts.push("all relays");
else parts.push(...m.relays.map((r) => catalog.relays[r]?.label ?? r));
return parts.length ? parts.join(" · ") : "No permissions";
}
export default function Users() {
const me = useApp((s) => s.me)!;
const toast = useApp((s) => s.toast);
const { data: users } = useUsers();
const { data: catalog } = usePermissions();
const [editing, setEditing] = useState<Me | null | "new">(null);
const remove = useAction(
(name: string) => api.delete(`/users/${encodeURIComponent(name)}`),
[["users"]],
() => toast("User deleted (their sessions are now invalid)"),
);
const sorted = useMemo(
() => [...(users ?? [])].sort((a, b) => a.name.localeCompare(b.name)),
[users],
);
if (!catalog) return <p className="empty">Loading permission catalog…</p>;
return (
<section className="panel">
<header className="panel__head">
<h2>Users</h2>
<button className="btn btn--primary btn--sm" onClick={() => setEditing("new")}>
Add user
</button>
</header>
{!sorted.length && (
<p className="empty">
No users yet — the API is open until the first account exists. Create the admin account
now.
</p>
)}
<div className="table-wrap">
<table className="table">
<tbody>
{sorted.map((u) => (
<tr key={u.name}>
<td className="strong">{u.name}</td>
<td className="dim">{describeScopes(u.scopes, catalog)}</td>
<td className="num">
<button className="btn btn--ghost btn--sm" onClick={() => setEditing(u)}>
Edit
</button>
<button
className="btn btn--ghost btn--sm btn--dangertext"
disabled={u.name === me.name}
title={u.name === me.name ? "You cannot delete your own account" : undefined}
onClick={() => {
if (confirm(`Delete user ${u.name}?`)) remove.mutate(u.name);
}}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{editing !== null && (
<UserEditor
user={editing === "new" ? null : editing}
catalog={catalog}
onClose={() => setEditing(null)}
/>
)}
</section>
);
}
+95
View File
@@ -0,0 +1,95 @@
import {
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import { api, ApiError } from "./api";
import { useApp } from "./store";
import type {
CardEntry,
DeniedCard,
Me,
PendingCard,
PermissionCatalog,
RelayState,
Session,
Status,
} from "./types";
export function useStatus() {
const setMe = useApp((s) => s.setMe);
return useQuery({
queryKey: ["status"],
queryFn: async () => {
try {
return await api.get<Status>("/status");
} catch (e) {
if (e instanceof ApiError && e.status === 401) setMe(null);
throw e;
}
},
refetchInterval: 5000,
retry: false,
});
}
export const useSessions = () =>
useQuery({
queryKey: ["sessions"],
queryFn: () => api.get<Session[]>("/sessions?limit=200"),
refetchInterval: 15000,
});
export const usePending = () =>
useQuery({
queryKey: ["pending"],
queryFn: () => api.get<Record<string, PendingCard>>("/cards/pending"),
refetchInterval: 10000,
});
export const useDenied = () =>
useQuery({
queryKey: ["denied"],
queryFn: () => api.get<Record<string, DeniedCard>>("/cards/denied"),
});
export const useAllowlist = () =>
useQuery({
queryKey: ["allowlist"],
queryFn: () => api.get<{ authorized: Record<string, CardEntry> }>("/allowlist"),
});
export const useUsers = () =>
useQuery({ queryKey: ["users"], queryFn: () => api.get<Me[]>("/users") });
export const usePermissions = () =>
useQuery({
queryKey: ["permissions"],
queryFn: () => api.get<PermissionCatalog>("/permissions"),
});
export const useLiveRelays = () =>
useQuery({
queryKey: ["relays-live"],
queryFn: () => api.get<Record<string, RelayState>>("/relays?live=true"),
enabled: false, // fetched on demand (each poll talks to real hardware)
retry: false,
});
/** Mutation wrapper: toast on error, invalidate the given query keys on success. */
export function useAction<TArgs = void, TResult = unknown>(
fn: (args: TArgs) => Promise<TResult>,
invalidate: string[][],
onDone?: (result: TResult) => void,
) {
const qc = useQueryClient();
const toast = useApp((s) => s.toast);
return useMutation({
mutationFn: fn,
onSuccess: (result) => {
for (const key of invalidate) qc.invalidateQueries({ queryKey: key });
onDone?.(result);
},
onError: (e: Error) => toast(e.message, "error"),
});
}
+31
View File
@@ -0,0 +1,31 @@
import { create } from "zustand";
import type { Me } from "./types";
/** Auth + app-shell state (zustand). Server data lives in TanStack Query. */
interface AppState {
me: Me | null;
authChecked: boolean; // finished the initial /api/me probe
setMe: (me: Me | null) => void;
toasts: { id: number; text: string; tone: "info" | "error" }[];
toast: (text: string, tone?: "info" | "error") => void;
dismissToast: (id: number) => void;
}
let toastId = 0;
export const useApp = create<AppState>((set) => ({
me: null,
authChecked: false,
setMe: (me) => set({ me, authChecked: true }),
toasts: [],
toast: (text, tone = "info") => {
const id = ++toastId;
set((s) => ({ toasts: [...s.toasts, { id, text, tone }] }));
setTimeout(
() => set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
4000,
);
},
dismissToast: (id) =>
set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
}));
+368
View File
@@ -0,0 +1,368 @@
/* ============================================================
Charge Control — instrument-panel design system
Surfaces like enameled switchgear, copper-busbar accent,
indicator lamps as the signature element.
Type: Archivo (UI) + IBM Plex Mono (telemetry & identifiers).
============================================================ */
:root {
--paper: #eef0ef; /* porcelain enamel */
--panel: #f9faf9;
--panel-inset: #f1f3f2;
--ink: #1d2523; /* deep green-black, like cabinet paint */
--ink-dim: #5d6b67;
--line: #d8ddda;
--copper: #b25c28; /* busbar copper — the accent */
--copper-deep: #8f4a20;
--live: #178a5c; /* DC-on green */
--amber: #c07f00;
--red: #bf3527;
--lamp-off: #c4ccc8;
--shadow: 0 1px 2px rgb(29 37 35 / 0.06), 0 4px 16px rgb(29 37 35 / 0.05);
--radius: 10px;
--font-ui: "Archivo", "Segoe UI", system-ui, sans-serif;
--font-mono: "IBM Plex Mono", ui-monospace, Consolas, monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #131816;
--panel: #1b211f;
--panel-inset: #161c1a;
--ink: #e4e9e7;
--ink-dim: #93a09b;
--line: #2c3531;
--copper: #d07a3e;
--copper-deep: #b25c28;
--live: #2fae7c;
--amber: #d99a1b;
--red: #d8503f;
--lamp-off: #39433f;
--shadow: 0 1px 2px rgb(0 0 0 / 0.4), 0 4px 18px rgb(0 0 0 / 0.35);
}
}
* { box-sizing: border-box; margin: 0; }
html { color-scheme: light dark; }
body {
background: var(--paper);
color: var(--ink);
font-family: var(--font-ui);
font-size: 15.5px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
button, input, select { font: inherit; color: inherit; }
:focus-visible {
outline: 2px solid var(--copper);
outline-offset: 2px;
border-radius: 4px;
}
.mono { font-family: var(--font-mono); font-size: 0.92em; }
.strong { font-weight: 600; }
.dim { color: var(--ink-dim); }
.num { text-align: right; }
/* ---------- indicator lamp (signature element) ---------- */
.lamp {
display: inline-block;
width: 11px; height: 11px;
border-radius: 50%;
background: radial-gradient(circle at 35% 30%, color-mix(in srgb, var(--lamp-off) 60%, white 25%), var(--lamp-off) 70%);
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.35);
vertical-align: baseline;
flex: none;
}
.lamp--green {
background: radial-gradient(circle at 35% 30%, #8fe8c2, var(--live) 70%);
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 8px color-mix(in srgb, var(--live) 55%, transparent);
}
.lamp--amber {
background: radial-gradient(circle at 35% 30%, #ffd98a, var(--amber) 70%);
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 8px color-mix(in srgb, var(--amber) 55%, transparent);
}
.lamp--red {
background: radial-gradient(circle at 35% 30%, #ff9d8f, var(--red) 70%);
box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 8px color-mix(in srgb, var(--red) 55%, transparent);
}
.lamp--pulse { animation: lamp-pulse 1.6s ease-in-out infinite; }
@keyframes lamp-pulse {
0%, 100% { box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 4px color-mix(in srgb, var(--live) 40%, transparent); }
50% { box-shadow: inset 0 0 2px rgb(0 0 0 / 0.25), 0 0 14px color-mix(in srgb, var(--live) 85%, transparent); }
}
@media (prefers-reduced-motion: reduce) {
.lamp--pulse { animation: none; }
* { transition: none !important; }
}
/* ---------- app shell ---------- */
.shell { min-height: 100dvh; display: flex; flex-direction: column; }
.topbar {
display: flex; align-items: center; gap: 20px;
padding: 10px clamp(14px, 4vw, 32px);
background: var(--panel);
border-bottom: 1px solid var(--line);
position: sticky; top: 0; z-index: 10;
}
.brand { display: flex; align-items: center; gap: 10px; }
.brand__mark { width: 30px; height: 30px; }
.brand__mark path { fill: var(--copper); }
.brand__name { display: block; font-weight: 700; letter-spacing: 0.01em; line-height: 1.15; }
.brand__sub {
display: block; font-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim);
}
.nav { display: flex; gap: 4px; flex: 1; overflow-x: auto; }
.nav__link {
display: inline-flex; align-items: center; gap: 7px;
padding: 7px 13px;
border-radius: 8px;
color: var(--ink-dim);
text-decoration: none;
font-weight: 500;
white-space: nowrap;
}
.nav__link:hover { color: var(--ink); background: var(--panel-inset); }
.nav__link.active { color: var(--copper-deep); background: color-mix(in srgb, var(--copper) 12%, transparent); font-weight: 600; }
.badge {
background: var(--amber); color: #fff;
font-family: var(--font-mono); font-size: 11px; font-weight: 600;
border-radius: 999px; padding: 1px 7px;
}
.topbar__user { display: flex; align-items: center; gap: 10px; }
.topbar__who { font-family: var(--font-mono); font-size: 13px; color: var(--ink-dim); }
.alert {
display: flex; align-items: center; gap: 10px;
margin: 14px clamp(14px, 4vw, 32px) 0;
padding: 11px 16px;
border: 1px solid color-mix(in srgb, var(--amber) 45%, var(--line));
background: color-mix(in srgb, var(--amber) 9%, var(--panel));
border-radius: var(--radius);
color: var(--ink);
text-decoration: none;
font-weight: 500;
}
.alert:hover { border-color: var(--amber); }
.content {
width: min(1060px, 100%);
margin: 0 auto;
padding: 22px clamp(14px, 4vw, 32px) 60px;
display: flex; flex-direction: column; gap: 18px;
}
.boot, .empty {
display: flex; align-items: center; justify-content: center; gap: 10px;
padding: 48px 20px; color: var(--ink-dim); text-align: center;
}
/* ---------- login ---------- */
.login {
min-height: 100dvh; display: grid; place-items: center;
padding: 20px;
background:
radial-gradient(800px 400px at 80% -10%, color-mix(in srgb, var(--copper) 9%, transparent), transparent),
var(--paper);
}
.login__panel {
width: min(380px, 100%);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 14px;
box-shadow: var(--shadow);
padding: 30px 28px;
display: flex; flex-direction: column; gap: 14px;
}
.login__head { text-align: center; margin-bottom: 6px; }
.login__mark { width: 44px; height: 44px; margin-bottom: 10px; }
.login__mark path { fill: var(--copper); }
.login__head h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.01em; }
.login__head p { color: var(--ink-dim); font-size: 13.5px; margin-top: 4px; }
/* ---------- panels & bays ---------- */
.panel {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 18px 20px;
}
.panel--attention { border-color: color-mix(in srgb, var(--amber) 50%, var(--line)); }
.panel--offline { display: flex; gap: 14px; align-items: center; }
.panel--offline p { color: var(--ink-dim); font-size: 14px; }
.panel__head {
display: flex; align-items: baseline; justify-content: space-between; gap: 12px;
margin-bottom: 12px; flex-wrap: wrap;
}
.panel__head h2 { font-size: 16px; font-weight: 700; display: flex; align-items: center; gap: 9px; }
.panel__meta { color: var(--ink-dim); font-size: 13px; }
.panel__inset {
margin-top: 14px; padding: 16px;
background: var(--panel-inset);
border: 1px solid var(--line);
border-radius: 8px;
}
.panel__inset h3 { font-size: 14px; margin-bottom: 10px; }
.bays {
display: grid; gap: 18px;
grid-template-columns: repeat(auto-fit, minmax(290px, 1fr));
}
.bay {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 18px 20px;
display: flex; flex-direction: column; gap: 10px;
border-top: 3px solid var(--copper);
}
.bay__head { display: flex; justify-content: space-between; align-items: center; }
.bay__eyebrow {
font-family: var(--font-mono); font-size: 11px;
text-transform: uppercase; letter-spacing: 0.14em; color: var(--ink-dim);
}
.bay__title { font-size: 21px; font-weight: 700; letter-spacing: -0.01em; }
.bay__status { display: flex; align-items: center; gap: 10px; min-height: 26px; }
.bay__hint { color: var(--ink-dim); font-size: 13px; }
.bay__telemetry {
display: flex; gap: 22px;
padding: 10px 12px;
background: var(--panel-inset);
border-radius: 8px;
}
.bay__telemetry dt {
font-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
}
.bay__telemetry dd { font-weight: 600; font-size: 14px; }
.bay__actions { display: flex; align-items: center; gap: 12px; margin-top: 2px; }
/* ---------- chips ---------- */
.chip {
display: inline-block;
font-family: var(--font-mono); font-size: 11.5px; font-weight: 600;
text-transform: uppercase; letter-spacing: 0.07em;
padding: 3px 9px; border-radius: 999px;
background: var(--panel-inset); color: var(--ink-dim);
border: 1px solid var(--line);
}
.chip--live, .chip--charging { background: color-mix(in srgb, var(--live) 14%, transparent); color: var(--live); border-color: color-mix(in srgb, var(--live) 40%, transparent); }
.chip--preparing, .chip--finishing { background: color-mix(in srgb, var(--amber) 14%, transparent); color: var(--amber); border-color: color-mix(in srgb, var(--amber) 40%, transparent); }
.chip--faulted, .chip--unavailable { background: color-mix(in srgb, var(--red) 12%, transparent); color: var(--red); border-color: color-mix(in srgb, var(--red) 40%, transparent); }
.chip--card { background: color-mix(in srgb, var(--copper) 13%, transparent); color: var(--copper-deep); border-color: color-mix(in srgb, var(--copper) 40%, transparent); }
.chip--app { background: color-mix(in srgb, var(--live) 12%, transparent); color: var(--live); border-color: color-mix(in srgb, var(--live) 35%, transparent); }
/* ---------- buttons ---------- */
.btn {
border: 1px solid transparent;
border-radius: 8px;
padding: 9px 18px;
font-weight: 600;
cursor: pointer;
background: var(--panel-inset);
transition: background 0.15s, border-color 0.15s, transform 0.05s;
}
.btn:active:not(:disabled) { transform: translateY(1px); }
.btn:disabled { opacity: 0.45; cursor: default; }
.btn--primary { background: var(--copper); color: #fff; }
.btn--primary:hover:not(:disabled) { background: var(--copper-deep); }
.btn--danger { background: var(--red); color: #fff; }
.btn--danger:hover:not(:disabled) { background: color-mix(in srgb, var(--red) 85%, black); }
.btn--ghost { background: transparent; border-color: var(--line); color: var(--ink); }
.btn--ghost:hover:not(:disabled) { background: var(--panel-inset); }
.btn--sm { padding: 5px 12px; font-size: 13.5px; }
.btn--block { width: 100%; }
.btn--dangertext { color: var(--red); }
/* ---------- forms ---------- */
.field { display: flex; flex-direction: column; gap: 5px; }
.field > span, .field__label {
font-family: var(--font-mono); font-size: 11px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
}
.field input, .field select {
background: var(--paper);
border: 1px solid var(--line);
border-radius: 8px;
padding: 9px 12px;
width: 100%;
}
.field input:focus, .field select:focus { border-color: var(--copper); outline: none; }
.field-error { color: var(--red); font-size: 13.5px; }
.formrow { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); margin-bottom: 12px; }
.check { display: flex; align-items: center; gap: 9px; padding: 4px 0; cursor: pointer; }
.check input { accent-color: var(--copper); width: 16px; height: 16px; }
.check--strong { font-weight: 600; }
.cardform { display: flex; flex-direction: column; gap: 12px; margin-top: 12px; }
.cardform__actions { display: flex; gap: 10px; }
.gunpicker, .matrix { display: flex; flex-direction: column; gap: 6px; }
.matrix__group { margin-top: 8px; }
/* ---------- tables & lists ---------- */
.table-wrap { overflow-x: auto; }
.table { width: 100%; border-collapse: collapse; font-size: 14px; }
.table th {
text-align: left; padding: 8px 10px;
font-family: var(--font-mono); font-size: 10.5px;
text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-dim);
border-bottom: 1px solid var(--line);
}
.table th.num { text-align: right; }
.table td { padding: 9px 10px; border-bottom: 1px solid var(--line); vertical-align: middle; }
.table tr:last-child td { border-bottom: none; }
.relay-list, .pending-list { list-style: none; padding: 0; display: flex; flex-direction: column; }
.relay {
display: flex; align-items: center; gap: 12px;
padding: 10px 2px; border-bottom: 1px solid var(--line);
}
.relay:last-child { border-bottom: none; }
.relay__label { font-weight: 600; flex: 1; min-width: 0; }
.relay__state { font-family: var(--font-mono); font-size: 12.5px; color: var(--ink-dim); }
.pending { padding: 12px 2px; border-bottom: 1px solid var(--line); }
.pending:last-child { border-bottom: none; }
.pending__row { display: flex; justify-content: space-between; gap: 12px; align-items: center; flex-wrap: wrap; }
.pending__meta { display: block; color: var(--ink-dim); font-size: 13px; }
.pending__actions { display: flex; gap: 8px; }
/* ---------- toasts ---------- */
.toasts {
position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%);
display: flex; flex-direction: column; gap: 8px; z-index: 50;
width: min(480px, calc(100vw - 28px));
}
.toast {
background: var(--ink); color: var(--paper);
border-radius: 9px; padding: 11px 16px;
font-size: 14px; box-shadow: var(--shadow);
}
.toast--error { background: var(--red); color: #fff; }
/* ---------- responsive ---------- */
@media (max-width: 640px) {
.topbar { flex-wrap: wrap; row-gap: 6px; }
.nav { order: 3; width: 100%; }
.bay__telemetry { flex-wrap: wrap; gap: 12px 20px; }
.content { padding-top: 14px; }
}
+89
View File
@@ -0,0 +1,89 @@
export interface Me {
name: string;
scopes: string[];
id_tag: string | null;
}
export interface ActiveTx {
cp: string;
connector: number;
id_tag: string;
who: string;
method: string;
meter_start: number;
started: string;
}
export interface ChargerMeta {
label?: string;
guns?: Record<string, string>;
}
export interface Status {
connected: Record<string, Record<string, unknown> | null>;
connectors: Record<string, string>; // "cpId/connector" -> OCPP status
active_transactions: Record<string, ActiveTx>;
recent_auth_events: AuthEvent[];
relays: Record<string, { label: string; ip: string }>;
chargers: Record<string, ChargerMeta>;
pending_cards: number;
}
export interface AuthEvent {
time: string;
id_tag: string;
context: string;
connector: number | null;
result: string;
known: boolean;
}
export interface Session {
tx: number;
cp: string;
connector: number;
id_tag: string;
who: string | null;
started: string;
ended: string | null;
meter_start: number;
meter_stop: number | null;
wh: number | null;
reason: string | null;
method: string | null;
}
export interface CardEntry {
name: string;
kind: string;
user?: string;
guns?: string[];
}
export interface PendingCard {
first_seen: string;
last_seen: string;
count: number;
cp: string | null;
connector: number | null;
}
export interface DeniedCard {
rejected_at: string;
by: string;
first_seen?: string;
count?: number;
}
export interface PermissionCatalog {
chargers: Record<string, { label: string; guns: Record<string, string> }>;
relays: Record<string, { label: string; ip: string }>;
admin_scope: string;
}
export interface RelayState {
relay: string;
on?: boolean;
error?: string;
label?: string;
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"isolatedModules": true,
"noEmit": true,
"useDefineForClassFields": true
},
"include": ["src"]
}
+1
View File
@@ -0,0 +1 @@
{"root":["./src/app.tsx","./src/api.ts","./src/main.tsx","./src/queries.ts","./src/store.ts","./src/types.ts","./src/components/lamp.tsx","./src/components/layout.tsx","./src/pages/cards.tsx","./src/pages/dashboard.tsx","./src/pages/history.tsx","./src/pages/login.tsx","./src/pages/users.tsx"],"version":"5.9.3"}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// Dev: `npm run dev` serves on :5173 and proxies /api to the running backend.
// Prod: `npm run build` -> dist/, served as static files by the backend on :9000.
export default defineConfig({
plugins: [react()],
server: {
proxy: {
"/api": "http://localhost:9000",
},
},
});