# יסודות הפלטפורמה

> תיעוד היסטורי. מקור: docs/platform/architecture.md · 6a466bf.

Status: implemented source and local verification; cloud database connection pending access to the user's **LinkNodes Energy** Supabase organization. This is not a production charging/payment launch.

## Product boundaries

- `/` and existing driver routes retain the approved Visual System 2.0 and local driver demo.
- `/platform`: onboarding, sign-in when configured, personal/business tenant creation and workspace selection.
- `/platform/:tenantId/:section`: authenticated API-backed portal. It fails closed when configuration or authorization is unavailable; it never substitutes demo data.
- `/fleet-demo/:tenantId/:section`: explicitly local demo, separate storage per tenant, two business examples and a personal example. It is not a security boundary or evidence of production isolation.
- Sections: dashboard, vehicles, drivers, credentials, policy, sessions, analytics, billing, team, settings, audit.

Vehicle/driver/center CRUD, policies, pending charging credentials, member roles, invitation links, date-filtered analytics, CSV exports, and onboarding are implemented. Billing shows masked method/invoice records only. Demo edits persist in the browser. The connected counterpart is implemented but not live-verified.

## Stack and identity

Next.js App Router + TypeScript on Vercel; Clerk identity; Supabase PostgreSQL and RLS. Application membership in PostgreSQL is the source of truth for authorization. A Clerk native Organization is not a substitute for an LinkNodes Energy tenant membership. `clerk_org_id` is reserved for optional mapping and is not trusted for access.

Each request verifies the Clerk session and uses its JWT with Supabase native third-party authentication. Supabase must be configured to trust the specific Clerk issuer and its authenticated role. JWT `sub` identifies the user; the browser does not supply trusted owner/user identities. RLS reads active membership and active tenant state on each database request, so suspended membership does not retain access through stale organization claims.

Ordinary API reads and metadata updates use the user's token and publishable key. Narrow server-only RPCs handle invitation acceptance and trusted email synchronization after Clerk `currentUser()` verification, and registered vehicle identity writes after a government lookup. These operations recheck active tenant membership and relevant business constraints in the database. Authenticated clients cannot write vehicle registration facts directly. Invitation hashes are private, single-use, expire after seven days, and are atomically redeemed; owners can revoke a pending invitation. Links use a URL fragment to keep the token out of normal server URL logs. No emails are automatically sent. See `production-integrity-release.md` for the compatible rollout order.

| Role          | Fleet                              | Drivers/policy                 | Billing/assumptions    | Members                 | Audit |
| ------------- | ---------------------------------- | ------------------------------ | ---------------------- | ----------------------- | ----- |
| Owner         | Read/write                         | Read/write                     | Read/write assumptions | Invite/change non-owner | Read  |
| Admin         | Read/write                         | Read/write                     | Read/write assumptions | Read                    | Read  |
| Fleet manager | Read/write                         | Read/write                     | No payment data        | No                      | No    |
| Finance       | Read                               | Read drivers, read policy      | Read/write assumptions | Own membership only     | No    |
| Driver        | Assigned vehicles and own sessions | Own driver record; read policy | No payment data        | Own membership only     | No    |

All customer roles are read-only for charger facts, invoices, payments and masked payment methods. A driver profile's suspended status and a membership suspension are distinct: profile status prevents future operational eligibility; membership suspension revokes portal access. No role can demote the owner through the provided API.

## Database

Migration `20261107211048_platform_foundation.sql` adds 14 public and five private tables without replacing legacy tables. Every new table has RLS. Composite tenant/resource foreign keys prevent cross-tenant assignment; tenant and resource IDs are immutable even when a user belongs to both tenants. Writes are audited by database triggers; financial/provider secrets stay private. Analytics is security-invoker and aggregates only readable rows.

Amounts are integer agorot, energy is integer Wh. Charging states are constrained, terminal sessions cannot reopen, active vehicle/connector uniqueness and provider/idempotency uniqueness are enforced. Financial facts cannot be fabricated by the browser. Vehicle consumption and fuel-reference values are snapshotted on sessions to preserve historical calculations after vehicle changes.

`ev1_create_tenant` provisions tenant, owner and policy atomically. Provisioning uses a per-user transaction lock and idempotency key; one personal tenant and up to ten owned tenants. API body schemas reject extra fields, enforce finite bounds and same-origin JSON mutations. Responses are private/no-store.

The portal currently loads up to 1,000 records per inventory collection and 500 latest sessions. Truncation is disclosed; exports contain displayed/filtered records. SQL analytics runs over the entire selected date range, limited to 366 days. Cursor pagination and large asynchronous exports are follow-up work before large-fleet rollout.

## Reporting assumptions

Completed sessions only, grouped by end date in Asia/Jerusalem. Estimated kilometres = energy Wh / model consumption Wh/km. Reference fuel litres = estimated km × reference L/100km / 100. Fuel comparison uses the tenant's current reference price; savings may be negative. CO₂ comparison subtracts estimated electricity emissions from reference fuel emissions. These are planning estimates, not odometer or certified emissions measurements. Updating tenant assumptions recalculates historical comparisons. Cost-center budgets are stored for planning; cumulative enforcement/reporting by department is not implemented yet.

## External integrations and next milestones

1. **Connect LinkNodes Energy Supabase organization:** list organizations, identify LinkNodes Energy, create a dedicated project subject to actual cost confirmation if requested by Supabase, inspect it, apply migrations, configure native Clerk trust, and set Vercel preview secrets. Do not use the unrelated digitalops / Car Dealers BMS database.
2. **Identity integration verification:** separate live test users in tenants A/B; sign-in/out, invitation acceptance, revoked membership and all direct API/RLS denial paths using actual issued JWTs. Local JWT-claim simulation is not proof of cloud authentication.
3. **Charging provider:** select network/protocol (e.g. OCPI roaming or dedicated OCPP gateway), implement provider reconciliation, signed webhooks, atomic budget reservations, command outbox publishing, retry/deduplication, tariff snapshots, timeout handling and stale-meter handling. No public API currently starts/stops a real charger.
4. **Payments:** choose PSP; provider-hosted setup (never raw PAN/CVV), authorization/capture/refund lifecycle, signed webhooks, invoice/tax integration, payment reconciliation and dispute handling. No real charge occurs in this release.
5. **Operations:** RabbitMQ worker runtime, rate limits, Grafana traces/alerts, PostHog tenant-safe analytics, backup/restore exercise, load tests, role matrix cloud tests and tenant offboarding/retention. No production readiness claim until these are verified.

A Clerk LinkNodes Energy development application was created during this work. Credentials are outside the repository and have not been enabled in the preview while the LinkNodes Energy database is inaccessible.

## Local verification

`pnpm typecheck`, `pnpm lint`, `pnpm test`, `pnpm test:e2e`, `pnpm build`.
`node scripts/test-tenant-isolation.mjs` requires the isolated local PostgreSQL 17 database (`ev1_test`, loopback only). `scripts/platform-db-bootstrap.sql` is a test-only Supabase role/JWT shim, never a cloud migration. Tests run in a transaction and roll back fixtures.

See `verification.md` for executed results and known gaps. The baseline commit is `6934afc`; the new work is isolated on `feature/multitenant-platform`.
