feat: private session history, own-permissions view, plug-gated start button

- non-admins now see ONLY their own sessions in /api/sessions (own app
  starts + own linked cards); gun scopes grant control, not visibility;
  admins see everything
- Account page shows the logged-in user's permissions in plain words
  (Administrator badge, or the guns/relays they control), built solely
  from data already visible to them
- Start button arms only when the gun reports Preparing (cable in the
  car); idle unplugged gun shows an explanatory hint instead
- keep owner's app rename to 'Art IoT'
- smoke test: 59 checks (gun-scoped user sees no foreign sessions)
This commit is contained in:
2026-07-12 09:04:06 +02:00
parent 3387f8689e
commit 069d544bb5
12 changed files with 98 additions and 17 deletions
+6 -4
View File
@@ -221,10 +221,12 @@ async def charger_probe(cp: Optional[str] = None, user: dict = Depends(current_u
# ---- session history: who charged when and how many kWh ---- # ---- session history: who charged when and how many kWh ----
def _may_see_session(user: dict, s: dict) -> bool: def _may_see_session(user: dict, s: dict) -> bool:
"""Own sessions (own app starts or own cards), sessions on guns you """Transactions are private: admins see everything, everyone else sees
control, or everything for admin. Card ownership is looked up live, so ONLY their own sessions (their app starts + their linked cards). Card
linking a card to a user retroactively shows them its history.""" ownership is looked up live, so linking a card to a user retroactively
if users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}"): shows them its history. (Gun scopes grant CONTROL, not visibility —
owner decision 2026-07-12.)"""
if users.allowed(user["scopes"], "admin"):
return True return True
if s["id_tag"] == user.get("id_tag"): if s["id_tag"] == user.get("id_tag"):
return True return True
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="theme-color" content="#171d1b" /> <meta name="theme-color" content="#171d1b" />
<link rel="icon" href="/icon.svg" type="image/svg+xml" /> <link rel="icon" href="/icon.svg" type="image/svg+xml" />
<link rel="manifest" href="/manifest.json" /> <link rel="manifest" href="/manifest.json" />
<title>Charge Control</title> <title>Art IoT</title>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"name": "Charge Control", "name": "Art IoT",
"short_name": "Charge", "short_name": "Charge",
"description": "Home EV charger and relay control", "description": "Home EV charger and relay control",
"start_url": "/", "start_url": "/",
+1 -1
View File
@@ -32,7 +32,7 @@ export default function Layout() {
<path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" /> <path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" />
</svg> </svg>
<div> <div>
<span className="brand__name">Charge Control</span> <span className="brand__name">Art IoT</span>
<span className="brand__sub">private CSMS</span> <span className="brand__sub">private CSMS</span>
</div> </div>
</div> </div>
+63 -1
View File
@@ -1,7 +1,66 @@
import { FormEvent, useState } from "react"; import { FormEvent, useState } from "react";
import { api } from "../api"; import { api, isAdmin, scopeAllowed } from "../api";
import { useStatus } from "../queries";
import { useApp } from "../store"; import { useApp } from "../store";
/** The logged-in user's own permissions, in plain words. Built purely from
* data this user may already see (status carries charger gun labels for
* everyone, and only the relays they control). */
function MyPermissions() {
const me = useApp((s) => s.me)!;
const { data: status } = useStatus();
if (isAdmin(me.scopes)) {
return (
<section className="panel" style={{ maxWidth: 440 }}>
<header className="panel__head">
<h2>Your permissions</h2>
</header>
<span className="chip chip--card">Administrator</span>
<p className="dim" style={{ marginTop: 8, fontSize: 14 }}>
Full access: both guns, all relays, cards, users and history of everyone.
</p>
</section>
);
}
const guns: string[] = [];
for (const [cp, meta] of Object.entries(status?.chargers ?? {}))
for (const [conn, label] of Object.entries(meta.guns ?? {}))
if (scopeAllowed(me.scopes, `charger:${cp}:${conn}`))
guns.push(`${meta.label ?? cp} — ${label}`);
const relays = Object.values(status?.relays ?? {}).map((r) => r.label);
return (
<section className="panel" style={{ maxWidth: 440 }}>
<header className="panel__head">
<h2>Your permissions</h2>
</header>
{guns.length + relays.length === 0 ? (
<p className="dim" style={{ fontSize: 14 }}>
No device permissions yet — ask an admin to grant you a gun or a relay.
</p>
) : (
<ul className="permlist">
{guns.map((g) => (
<li key={g}>
<span className="chip chip--plugged">Gun</span> {g}
</li>
))}
{relays.map((r) => (
<li key={r}>
<span className="chip chip--app">Relay</span> {r}
</li>
))}
</ul>
)}
<p className="dim" style={{ marginTop: 8, fontSize: 13 }}>
History shows only your own charging sessions.
</p>
</section>
);
}
export default function Account() { export default function Account() {
const me = useApp((s) => s.me)!; const me = useApp((s) => s.me)!;
const toast = useApp((s) => s.toast); const toast = useApp((s) => s.toast);
@@ -31,6 +90,8 @@ export default function Account() {
} }
return ( return (
<>
<MyPermissions />
<section className="panel" style={{ maxWidth: 440 }}> <section className="panel" style={{ maxWidth: 440 }}>
<header className="panel__head"> <header className="panel__head">
<h2>Account</h2> <h2>Account</h2>
@@ -75,5 +136,6 @@ export default function Account() {
</div> </div>
</form> </form>
</section> </section>
</>
); );
} }
+6 -1
View File
@@ -93,7 +93,9 @@ function gunState(gun: Gun): { label: string; cls: string } {
function GunBay({ gun, scopes }: { gun: Gun; scopes: string[] }) { function GunBay({ gun, scopes }: { gun: Gun; scopes: string[] }) {
const toast = useApp((s) => s.toast); const toast = useApp((s) => s.toast);
const may = scopeAllowed(scopes, `charger:${gun.cp}:${gun.connector}`); const may = scopeAllowed(scopes, `charger:${gun.cp}:${gun.connector}`);
const ready = !gun.tx && (gun.ocppStatus === "Preparing" || gun.ocppStatus === "Available"); // Start arms ONLY with a cable in the car (Preparing / pulsing blue) —
// an idle, unplugged gun keeps the button disabled (owner, 2026-07-12)
const ready = !gun.tx && gun.ocppStatus === "Preparing";
const start = useAction( const start = useAction(
() => () =>
@@ -160,6 +162,9 @@ function GunBay({ gun, scopes }: { gun: Gun; scopes: string[] }) {
</button> </button>
)} )}
{!may && <span className="bay__hint">no permission for this gun</span>} {!may && <span className="bay__hint">no permission for this gun</span>}
{may && !gun.tx && !ready && gun.ocppStatus === "Available" && (
<span className="bay__hint">plug the cable into the car to enable</span>
)}
</footer> </footer>
</article> </article>
); );
+8 -3
View File
@@ -1,4 +1,6 @@
import { isAdmin } from "../api";
import { useSessions, useStatus } from "../queries"; import { useSessions, useStatus } from "../queries";
import { useApp } from "../store";
import type { Session } from "../types"; import type { Session } from "../types";
const fmtKwh = (wh: number | null) => (wh == null ? "—" : (wh / 1000).toFixed(2)); const fmtKwh = (wh: number | null) => (wh == null ? "—" : (wh / 1000).toFixed(2));
@@ -23,6 +25,8 @@ function gunLabel(s: Session, chargers: Record<string, { label?: string; guns?:
} }
export default function History() { export default function History() {
const me = useApp((s) => s.me)!;
const admin = isAdmin(me.scopes);
const { data: sessions, isLoading } = useSessions(); const { data: sessions, isLoading } = useSessions();
const { data: status } = useStatus(); const { data: status } = useStatus();
@@ -30,8 +34,9 @@ export default function History() {
if (!sessions?.length) if (!sessions?.length)
return ( return (
<p className="empty"> <p className="empty">
No charging sessions yet. The first card tap or in-app start will appear here with who, {admin
when, how, and how many kWh. ? "No charging sessions yet. The first card tap or in-app start will appear here with who, when, how, and how many kWh."
: "No charging sessions of yours yet. Sessions you start — by card or in-app — appear here."}
</p> </p>
); );
@@ -40,7 +45,7 @@ export default function History() {
return ( return (
<section className="panel"> <section className="panel">
<header className="panel__head"> <header className="panel__head">
<h2>Charging sessions</h2> <h2>{admin ? "All charging sessions" : "Your charging sessions"}</h2>
<span className="panel__meta"> <span className="panel__meta">
{sessions.length} session{sessions.length === 1 ? "" : "s"} ·{" "} {sessions.length} session{sessions.length === 1 ? "" : "s"} ·{" "}
<strong className="mono">{totalKwh.toFixed(1)} kWh</strong> total <strong className="mono">{totalKwh.toFixed(1)} kWh</strong> total
+1 -1
View File
@@ -31,7 +31,7 @@ export default function Login() {
<svg viewBox="0 0 100 100" className="login__mark" aria-hidden> <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" /> <path d="M55 12 L28 56 L46 56 L41 88 L72 42 L52 42 Z" />
</svg> </svg>
<h1>Charge Control</h1> <h1>Art IoT</h1>
<p>Private charging backend — sign in to operate.</p> <p>Private charging backend — sign in to operate.</p>
</div> </div>
<label className="field"> <label className="field">
+4 -1
View File
@@ -1,5 +1,5 @@
/* ============================================================ /* ============================================================
Charge Control — instrument-panel design system Art IoT — instrument-panel design system
Surfaces like enameled switchgear, copper-busbar accent, Surfaces like enameled switchgear, copper-busbar accent,
indicator lamps as the signature element. indicator lamps as the signature element.
Type: Archivo (UI) + IBM Plex Mono (telemetry & identifiers). Type: Archivo (UI) + IBM Plex Mono (telemetry & identifiers).
@@ -335,6 +335,9 @@ button, input, select { font: inherit; color: inherit; }
.cardform__actions { display: flex; gap: 10px; } .cardform__actions { display: flex; gap: 10px; }
.gunpicker, .matrix { display: flex; flex-direction: column; gap: 6px; } .gunpicker, .matrix { display: flex; flex-direction: column; gap: 6px; }
.permlist { list-style: none; padding: 0; display: flex; flex-direction: column; gap: 8px; }
.permlist li { display: flex; align-items: center; gap: 10px; font-weight: 500; }
.matrix__group { margin-top: 8px; } .matrix__group { margin-top: 8px; }
/* ---------- tables & lists ---------- */ /* ---------- tables & lists ---------- */
+1 -1
View File
@@ -27,7 +27,7 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
- `ws://<host>:9000/<ChargerID>` — OCPP WebSocket (catch-all path, the JC-6620 dials in) - `ws://<host>:9000/<ChargerID>` — OCPP WebSocket (catch-all path, the JC-6620 dials in)
- `GET /` — **the [[frontend|React panel]]** served from `../frontend/dist/` with SPA fallback (deep links land on index.html; `/api/*` + `/docs` excluded; 503 with instructions if not built) - `GET /` — **the [[frontend|React panel]]** served from `../frontend/dist/` with SPA fallback (deep links land on index.html; `/api/*` + `/docs` excluded; 503 with instructions if not built)
- `POST /api/login|logout`, `GET /api/me`, `POST /api/me/password` (self-service change, current password required) — username/password → 30-day session (cookie + bearer) - `POST /api/login|logout`, `GET /api/me`, `POST /api/me/password` (self-service change, current password required) — username/password → 30-day session (cookie + bearer)
- `GET /api/sessions?limit&cp&connector` — **charging history: who / when / kWh** (visibility: own sessions + guns within scope; admin sees all); `GET /api/sessions/{tx}/samples` — per-minute energy/power/SoC for charts - `GET /api/sessions?limit&cp&connector` — **charging history: who / when / kWh** (visibility: PRIVATE — own sessions only, i.e. own app starts + own linked cards; admin sees all; gun scopes grant control, not visibility); `GET /api/sessions/{tx}/samples` — per-minute energy/power/SoC for charts
- `GET /api/status` — connected chargers, gun states, active transactions, auth events + pending-card count (admin), relays (filtered to what the caller may control) - `GET /api/status` — connected chargers, gun states, active transactions, auth events + pending-card count (admin), relays (filtered to what the caller may control)
- `GET /api/events?limit&event=` — tail the journal (admin) - `GET /api/events?limit&event=` — tail the journal (admin)
- `POST /api/charger/start|stop[/{tx}]|unlock/{n}` — gun-scoped; `trigger/{...}|setconfig|probe` — admin - `POST /api/charger/start|stop[/{tx}]|unlock/{n}` — gun-scoped; `trigger/{...}|setconfig|probe` — admin
+2 -2
View File
@@ -19,8 +19,8 @@ The React control panel (built 2026-07-11, replacing the single-file vanilla-JS
| Route | Who | What | | Route | Who | What |
|---|---|---| |---|---|---|
| `/` (Control) | all | one "bay" card per gun — **every registry-declared gun always renders**, even offline; status lamp, Start/Stop gated by scope **and** gun readiness; live session shows who/via/duration; relay toggles with on-demand live read | | `/` (Control) | all | one "bay" card per gun — **every registry-declared gun always renders**, even offline; status lamp, Start/Stop gated by scope **and** gun readiness; live session shows who/via/duration; relay toggles with on-demand live read |
| `/account` | all | self-service password change (current password required) | | `/account` | all | **your permissions in plain words** (admin badge, or the guns/relays you may control) + self-service password change (current password required) |
| `/history` | all (filtered by scope) | the audit table: **who charged, via Card or In-app, which gun, when, duration, kWh**; total kWh; live sessions flagged | | `/history` | all | admins: the full audit table (**who charged, via Card or In-app, which gun, when, duration, kWh**); everyone else: **only their own sessions** |
| `/cards` | admin | **pending cards awaiting review** (approve → name + owner + gun restrictions in one step; reject → silenced), enrolled cards with owner/guns editing, rejected list with un-reject | | `/cards` | admin | **pending cards awaiting review** (approve → name + owner + gun restrictions in one step; reject → silenced), enrolled cards with owner/guns editing, rejected list with un-reject |
| `/users` | admin | user CRUD with the **permission matrix** — admin toggle, per-gun and per-relay checkboxes rendered from `GET /api/permissions` (no raw scope strings in the UI) | | `/users` | admin | user CRUD with the **permission matrix** — admin toggle, per-gun and per-relay checkboxes rendered from `GET /api/permissions` (no raw scope strings in the UI) |
+4
View File
@@ -87,3 +87,7 @@ Owner: full frontend revision (React + routing + zustand + TanStack Query, Vite
## [2026-07-12] meta | Panel live on the owner's phone; gun state language; password self-service ## [2026-07-12] meta | Panel live on the owner's phone; gun state language; password self-service
Owner confirmed the React panel loads on the phone after backend restart. Changes on request: (1) both guns ALWAYS render on Control — gun cards come from the chargers registry, live reports only overlay state (offline/no-status shown gray); (2) new lamp/chip language: gray=idle, pulsing blue=cable plugged, green=charging; (3) POST /api/me/password + /account page — any user changes their own password (current password required; admin reset via PUT /api/users stays). Smoke: 58 checks. Updated [[frontend]], [[backend]]. Owner confirmed the React panel loads on the phone after backend restart. Changes on request: (1) both guns ALWAYS render on Control — gun cards come from the chargers registry, live reports only overlay state (offline/no-status shown gray); (2) new lamp/chip language: gray=idle, pulsing blue=cable plugged, green=charging; (3) POST /api/me/password + /account page — any user changes their own password (current password required; admin reset via PUT /api/users stays). Smoke: 58 checks. Updated [[frontend]], [[backend]].
## [2026-07-12] meta | Private history; permissions on Account; Start only when plugged; "Art IoT" rename
Owner (testing on the phone, second user created): (1) transactions are now PRIVATE — non-admins see only their own sessions (app starts + linked cards); gun scopes grant control, not visibility; admins see all. (2) Account page shows the user's own permissions in plain words (admin badge, or gun/relay list built from data they already see). (3) Start button arms ONLY when the cable is plugged (Preparing) — an idle unplugged gun shows "plug the cable into the car to enable". Owner also renamed the app to "Art IoT" (login, topbar, manifest, title) — kept. Smoke: 59 checks. Updated [[backend]], [[frontend]].