# Mandantenfähigkeit Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Mehrere eigenständige Überführungsfirmen nutzen eine Installation, strikt per RLS getrennt, mit Superadmin-Plattformbereich und pro Firma einstellbarem Namen, Logo, Farben, WhatsApp-Empfänger und SMTP-Absender. **Architecture:** Neue Tabellen `firmen` und `firmen_smtp`; `firma_id` in allen Fachtabellen, gesetzt und geschützt durch `before`-Trigger; jede RLS-Policy prüft zusätzlich `firma_id = public.user_firma_id()`. Service-Client-Pfade (Nutzerverwaltung, Plattform, SMTP) prüfen vorher über den RLS-Client. Branding über CSS-Variablen am `` und eine Logo-Route. **Tech Stack:** Supabase (Postgres 15, RLS, Storage, pgTAP), Next.js 16 App Router + Server Actions, Vitest, nodemailer 7, @react-pdf/renderer, Node `crypto` (AES-256-GCM). **Spec:** `docs/superpowers/specs/2026-10-12-mandantenfaehigkeit-design.md` ## Global Constraints - RLS ist die Sicherheitsgrenze; App-Prüfungen sind Defense-in-Depth (CLAUDE.md). - Feste ID der Bestandsfirma: `00000000-0000-0000-0000-00000000f001`, Name `Widmann`. - Standardfarben: Hauptfarbe `#0071ed`, dunkle Farbe `#0a185c`; Mindestkontrast zu Weiß **4,5:1**. - Farbformat in der DB: `^#[0-9a-f]{6}$` (klein geschrieben). - WhatsApp-Empfänger: E.164 `^\+[1-9][0-9]{7,14}$`. - Logo: PNG, JPG oder SVG, max. **1 MB** (1 048 576 Byte), Pfad `/logo-.` im privaten Bucket `firmen-logos`. - SMTP-Passwort: AES-256-GCM, Format `v1:::`, Schlüssel `SMTP_VERSCHLUESSELUNG_KEY` (32 Byte, base64). - Fremder Nutzer in Nutzerverwaltung → Meldung exakt `Nutzer nicht gefunden.` - Deaktivierte Firma / kein Firmenzugang → Meldung exakt `Ihre Firma ist deaktiviert oder Ihr Zugang ist keiner Firma zugeordnet.` - Kein SMTP (weder Firma noch global) → Outbox-Fehlertext exakt `Kein SMTP konfiguriert` (Retry, nicht endgültig). - Mail-Betreff: `Übergabeprotokoll – ()`. - Supabase-CLI-Befehle vom Repo-Root, Frontend-Befehle aus `web/`. - UI: Mobile first, Touch-Ziele `min-h-11`, deutsche Texte mit Umlauten. - Keine neuen npm-Abhängigkeiten. ## Review Focus 1. **Service-Client umgeht RLS** — jede Action, die `createAdminClient()` für einen fremden Datensatz benutzt (Nutzerverwaltung, Plattform, SMTP), muss vorher die Berechtigung über den RLS-Client oder die Superadmin-Rolle prüfen. Test: Task 5 (`pruefeZielNutzer`), Task 8 (`pruefeSuperadmin`), Live-Check Task 10. 2. **Offene Session nach Deaktivierung** — ein angemeldeter Nutzer einer gerade deaktivierten Firma darf beim nächsten Seitenaufruf nichts mehr sehen und wird abgemeldet. Test: Task 2 (pgTAP: `user_firma_id()` null, keine Daten), Task 4 (`pruefeFirmenzugang`). 3. **Hochgeladenes SVG mit Script** — direkt geöffnet darf es kein Script im App-Origin ausführen. Test: Task 4 (Logo-Route-Header-Test). 4. **Doppeltes Kennzeichen/FIN nach Constraint-Umbenennung** — Meldung muss weiter korrekt „FIN“ vs. „Kennzeichen“ unterscheiden. Test: Task 1 (Vitest für `duplikatFehler`). 5. **Bestandsdaten nach Migration** — alle Zeilen gehören zu Widmann, die Auftragsnummer zählt am Migrationstag nahtlos weiter. Test: Task 1 (pgTAP Zähler, keine `firma_id is null`). ## Modellwahl (Vorgabe des Nutzers: einfache Aufgaben an kleinere Modelle) | Task | Inhalt | Implementer | Reviewer | |---|---|---|---| | 1 | DB-Struktur + Bestandstests | sonnet | opus | | 2 | RLS + Storage | sonnet | opus | | 3 | Farben + Krypto (pure) | haiku | sonnet | | 4 | Auth/Layout/Login/Logo-Route | sonnet | sonnet | | 5 | Nutzerverwaltung | sonnet | sonnet | | 6 | /firma Einstellungen + Logo | sonnet | sonnet | | 7 | /firma SMTP | sonnet | sonnet | | 8 | Plattform | sonnet | sonnet | | 9 | Benachrichtigungen + PDF | sonnet | sonnet | | 10 | Skript, Env, README | haiku | sonnet | --- ### Task 1: Datenbank-Struktur (Firmen, firma_id, Trigger, Eindeutigkeit) **Files:** - Create: `supabase/migrations/20261012090000_superadmin_rolle.sql` - Create: `supabase/migrations/20261012090100_mandanten_struktur.sql` - Create: `supabase/tests/mandanten_struktur_test.sql` - Modify: alle bestehenden `supabase/tests/*.sql` (Testnutzer einer Firma zuordnen, `firma_id` bei Inserts ohne Session) - Modify: `web/lib/orte-fahrzeuge/mutations.ts:57-62` (`duplikatFehler`) - Test: `web/lib/orte-fahrzeuge/mutations.test.ts` (neu oder ergänzt) **Interfaces:** - Produces: Tabellen `public.firmen`, `public.firmen_smtp`; Spalte `firma_id` in `profiles`, `orte`, `fahrzeuge`, `auftraege`, `auftrag_fotos`, `arbeitszeiten`, `nutzer_details`, `notification_outbox`, `auftragsnummer_zaehler`; Funktion `public.user_firma_id() returns uuid`; Enum-Wert `superadmin`. - Trigger-Regel für spätere Tasks: Inserts **mit** Nutzer-Session bekommen `firma_id` aus `user_firma_id()`; Inserts **ohne** Session (Service-Client, Tests als `postgres`) müssen `firma_id` mitgeben (Ausnahme: `auftrag_fotos`, `notification_outbox` → aus Auftrag; `nutzer_details` → aus Profil). `firma_id` darf nur `null → Wert` ohne Session geändert werden. - [ ] **Step 1: Enum-Migration anlegen** `supabase/migrations/20261012090000_superadmin_rolle.sql`: ```sql -- Eigene Migration: ein neuer Enum-Wert ist erst nach dem Commit der -- Transaktion verwendbar, die ihn anlegt (die Folgemigration nutzt ihn). alter type public.app_role add value if not exists 'superadmin'; ``` - [ ] **Step 2: Failing pgTAP-Test schreiben** `supabase/tests/mandanten_struktur_test.sql`: ```sql begin; select plan(16); -- Firma B neben der Bestandsfirma Widmann (f001) insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); insert into auth.users (id, email) values ('a0000000-0000-0000-0000-0000000000a1', 'admin-a@mandant.test.local'), ('a0000000-0000-0000-0000-0000000000a3', 'fahrer-a@mandant.test.local'), ('b0000000-0000-0000-0000-0000000000b1', 'admin-b@mandant.test.local'), ('b0000000-0000-0000-0000-0000000000b3', 'fahrer-b@mandant.test.local'), ('5a000000-0000-0000-0000-000000000001', 'superadmin@mandant.test.local'); -- 1) Neues Profil hat keine Firma (handle_new_user bleibt unveraendert) select is( (select firma_id from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a1'), null::uuid, 'Neues Profil startet ohne Firma' ); update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'admin' where id = 'a0000000-0000-0000-0000-0000000000a1'; update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'fahrer' where id = 'a0000000-0000-0000-0000-0000000000a3'; update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'admin' where id = 'b0000000-0000-0000-0000-0000000000b1'; update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'fahrer' where id = 'b0000000-0000-0000-0000-0000000000b3'; update public.profiles set role = 'superadmin' where id = '5a000000-0000-0000-0000-000000000001'; -- 2) Superadmin mit Firma ist verboten select throws_ok( $$ update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where id = '5a000000-0000-0000-0000-000000000001' $$, '23514', null, 'Superadmin darf keiner Firma angehoeren' ); -- 3) Firmenwechsel eines Profils ist verboten (auch ohne Session, wenn schon gesetzt) select throws_ok( $$ update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002' where id = 'a0000000-0000-0000-0000-0000000000a3' $$, '42501', 'firma_id darf nicht geaendert werden', 'firma_id eines Profils ist unveraenderlich' ); -- Stammdaten ohne Session: firma_id explizit insert into public.orte (id, adresse, ansprechpartner, firma_id) values ('a0000000-0000-0000-0000-0000000000c1', 'Ort A', 'Herr A', '00000000-0000-0000-0000-00000000f001'), ('b0000000-0000-0000-0000-0000000000c1', 'Ort B', 'Frau B', '00000000-0000-0000-0000-00000000f002'); insert into public.fahrzeuge (id, kennzeichen, firma_id) values ('a0000000-0000-0000-0000-0000000000d1', 'MT-AB 1', '00000000-0000-0000-0000-00000000f001'); -- 4) Ohne Session und ohne firma_id: Fehler select throws_ok( $$ insert into public.orte (adresse, ansprechpartner) values ('X', 'Y') $$, '23502', 'firma_id fehlt', 'Insert ohne Session braucht eine firma_id' ); -- 5) Gleiches Kennzeichen in zwei Firmen ist erlaubt select lives_ok( $$ insert into public.fahrzeuge (id, kennzeichen, firma_id) values ('b0000000-0000-0000-0000-0000000000d1', 'MT-AB 1', '00000000-0000-0000-0000-00000000f002') $$, 'Gleiches Kennzeichen in einer anderen Firma ist erlaubt' ); -- 6) Doppeltes Kennzeichen in derselben Firma nicht select throws_ok( $$ insert into public.fahrzeuge (kennzeichen, firma_id) values ('MT-AB 1', '00000000-0000-0000-0000-00000000f001') $$, '23505', null, 'Doppeltes Kennzeichen in derselben Firma scheitert' ); -- Session als Admin B set local role authenticated; set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; -- 7) Mitgeschickte fremde firma_id wird ueberschrieben select is( (select public.user_firma_id()), '00000000-0000-0000-0000-00000000f002'::uuid, 'user_firma_id liefert die Firma des angemeldeten Nutzers' ); reset role; reset request.jwt.claims; -- Insert mit Session, Rueckgabe ueber eine Hilfstabelle (RLS-Policies sind in Task 1 noch rollenbasiert) set local role authenticated; set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; insert into public.orte (id, adresse, ansprechpartner, firma_id) values ('b0000000-0000-0000-0000-0000000000c2', 'Ort B2', 'Herr B2', '00000000-0000-0000-0000-00000000f001'); reset role; reset request.jwt.claims; select is( (select firma_id from public.orte where id = 'b0000000-0000-0000-0000-0000000000c2'), '00000000-0000-0000-0000-00000000f002'::uuid, 'Mitgeschickte fremde firma_id wird durch die eigene Firma ersetzt' ); -- 9) Auftrag mit Ort einer fremden Firma: Exception select throws_ok( $$ insert into public.auftraege (abholort_id, zielort_id, fahrzeug_id, erstellt_von, firma_id) values ('a0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', '00000000-0000-0000-0000-00000000f002') $$, '42501', 'Firmenfremder Verweis', 'Auftrag mit Ort einer fremden Firma scheitert' ); -- 10) Auftrag mit Fahrer einer fremden Firma: Exception select throws_ok( $$ insert into public.auftraege (abholort_id, zielort_id, fahrzeug_id, erstellt_von, zugewiesen_an, status, firma_id) values ('b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', 'a0000000-0000-0000-0000-0000000000a3', 'zugewiesen', '00000000-0000-0000-0000-00000000f002') $$, '42501', 'Firmenfremder Verweis', 'Auftrag mit Fahrer einer fremden Firma scheitert' ); -- Je ein gueltiger Auftrag pro Firma update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, firma_id) values ('a0000000-0000-0000-0000-0000000000e1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', '00000000-0000-0000-0000-00000000f001'), ('b0000000-0000-0000-0000-0000000000e1', 'b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', '00000000-0000-0000-0000-00000000f002'); -- 11) Auftragsnummer zaehlt pro Firma: der erste B-Auftrag des Tages endet auf -0001 select is( (select right(auftragsnummer, 4) from public.auftraege where id = 'b0000000-0000-0000-0000-0000000000e1'), '0001', 'Auftragsnummer zaehlt pro Firma' ); -- 12) firma_id eines Auftrags ist unveraenderlich select throws_ok( $$ update public.auftraege set firma_id = '00000000-0000-0000-0000-00000000f002' where id = 'a0000000-0000-0000-0000-0000000000e1' $$, '42501', 'firma_id darf nicht geaendert werden', 'firma_id eines Auftrags ist unveraenderlich' ); -- 13) WhatsApp-Outbox nur fuer Firma mit Empfaenger, mit firma_id aus dem Auftrag select is( (select count(*) from public.notification_outbox where event_type = 'auftrag_erstellt' and auftrag_id = 'a0000000-0000-0000-0000-0000000000e1' and firma_id = '00000000-0000-0000-0000-00000000f001'), 1::bigint, 'Firma mit WhatsApp-Empfaenger bekommt eine Outbox-Zeile mit ihrer firma_id' ); select is( (select count(*) from public.notification_outbox where auftrag_id = 'b0000000-0000-0000-0000-0000000000e1'), 0::bigint, 'Firma ohne WhatsApp-Empfaenger bekommt keine Outbox-Zeile' ); -- 15) Mit Nutzer-Session kann aktiv nicht geaendert werden. Nur Claims setzen, -- Rolle bleibt postgres: in Task 1 gibt es noch keine Policy auf firmen, der -- Trigger soll aber trotzdem greifen. set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; select throws_ok( $$ update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f002' $$, '42501', 'Status und ID einer Firma kann nur der Plattform-Betreiber aendern', 'Admin kann seine Firma nicht deaktivieren' ); reset request.jwt.claims; -- 16) Deaktivierte Firma: user_firma_id() liefert null update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f002'; set local role authenticated; set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; select is((select public.user_firma_id()), null::uuid, 'Deaktivierte Firma: user_firma_id() ist null'); reset role; reset request.jwt.claims; select * from finish(); rollback; ``` - [ ] **Step 3: Test laufen lassen, Fehlschlag prüfen** Run (Repo-Root): `npx supabase db reset && npx supabase test db` Expected: FAIL in `mandanten_struktur_test.sql` (`relation "public.firmen" does not exist`). - [ ] **Step 4: Struktur-Migration schreiben** `supabase/migrations/20261012090100_mandanten_struktur.sql`: ```sql -- Mandantenfaehigkeit, Teil 1: Firmen, firma_id in allen Fachtabellen, -- Trigger zum Setzen/Schuetzen der firma_id, Eindeutigkeit pro Firma. -- Die RLS-Policies folgen in 20261012090200_mandanten_rls.sql. -- ---------------------------------------------------------------- firmen create table public.firmen ( id uuid primary key default gen_random_uuid(), name text not null, aktiv boolean not null default true, logo_pfad text, whatsapp_empfaenger text, farbe_primaer text, farbe_dunkel text, created_at timestamptz not null default now(), constraint firmen_name_nicht_leer check (length(btrim(name)) > 0), constraint firmen_whatsapp_e164 check (whatsapp_empfaenger is null or whatsapp_empfaenger ~ '^\+[1-9][0-9]{7,14}$'), constraint firmen_farbe_primaer_hex check (farbe_primaer is null or farbe_primaer ~ '^#[0-9a-f]{6}$'), constraint firmen_farbe_dunkel_hex check (farbe_dunkel is null or farbe_dunkel ~ '^#[0-9a-f]{6}$') ); alter table public.firmen enable row level security; -- Supabase vergibt per Default-Privileges alle Rechte an anon/authenticated -- (siehe information_schema.role_table_grants). Explizit entziehen und nur -- das Noetige granten. revoke all on public.firmen from anon, authenticated; grant select, update on public.firmen to authenticated; -- Feste ID, damit Tests und das Layout (Standard-Logo) die Bestandsfirma kennen. insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f001', 'Widmann'); -- Status und ID einer Firma aendert nur der Service-Client (Plattform-Actions). create or replace function public.schuetze_firmen_status() returns trigger language plpgsql as $$ begin if auth.uid() is not null and (new.aktiv is distinct from old.aktiv or new.id is distinct from old.id) then raise exception 'Status und ID einer Firma kann nur der Plattform-Betreiber aendern' using errcode = '42501'; end if; return new; end; $$; create trigger schuetze_firmen_status before update on public.firmen for each row execute function public.schuetze_firmen_status(); -- ---------------------------------------------------------- firmen_smtp -- Kein Grant, keine Policy: nur der Service-Client kommt heran, das -- (verschluesselte) Passwort verlaesst die REST-API also nie. create table public.firmen_smtp ( firma_id uuid primary key references public.firmen (id) on delete cascade, host text not null, port int not null, secure boolean not null default false, benutzer text, passwort_verschluesselt text, absender_adresse text not null, absender_name text, updated_at timestamptz not null default now(), constraint firmen_smtp_port check (port between 1 and 65535) ); alter table public.firmen_smtp enable row level security; revoke all on public.firmen_smtp from anon, authenticated; -- --------------------------------------------------------------- profiles alter table public.profiles add column firma_id uuid references public.firmen (id); update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where role <> 'superadmin'; alter table public.profiles add constraint profiles_superadmin_ohne_firma check (role <> 'superadmin' or firma_id is null); create index profiles_firma_id_idx on public.profiles (firma_id); -- Firma des angemeldeten Nutzers, nur wenn die Firma aktiv ist. null = kein -- Zugriff auf Fachdaten (Superadmin, deaktivierte Firma, nicht zugeordnet). create or replace function public.user_firma_id() returns uuid language sql stable security definer set search_path = public as $$ select p.firma_id from public.profiles p join public.firmen f on f.id = p.firma_id where p.id = auth.uid() and f.aktiv; $$; -- ------------------------------------------------- firma_id in Fachtabellen alter table public.orte add column firma_id uuid references public.firmen (id); alter table public.fahrzeuge add column firma_id uuid references public.firmen (id); alter table public.auftraege add column firma_id uuid references public.firmen (id); alter table public.auftrag_fotos add column firma_id uuid references public.firmen (id); alter table public.arbeitszeiten add column firma_id uuid references public.firmen (id); alter table public.nutzer_details add column firma_id uuid references public.firmen (id); alter table public.notification_outbox add column firma_id uuid references public.firmen (id); alter table public.auftragsnummer_zaehler add column firma_id uuid references public.firmen (id); update public.orte set firma_id = '00000000-0000-0000-0000-00000000f001'; update public.fahrzeuge set firma_id = '00000000-0000-0000-0000-00000000f001'; update public.auftraege set firma_id = '00000000-0000-0000-0000-00000000f001'; update public.auftrag_fotos set firma_id = '00000000-0000-0000-0000-00000000f001'; update public.arbeitszeiten set firma_id = '00000000-0000-0000-0000-00000000f001'; update public.nutzer_details set firma_id = '00000000-0000-0000-0000-00000000f001'; update public.notification_outbox set firma_id = '00000000-0000-0000-0000-00000000f001'; update public.auftragsnummer_zaehler set firma_id = '00000000-0000-0000-0000-00000000f001'; alter table public.orte alter column firma_id set not null; alter table public.fahrzeuge alter column firma_id set not null; alter table public.auftraege alter column firma_id set not null; alter table public.auftrag_fotos alter column firma_id set not null; alter table public.arbeitszeiten alter column firma_id set not null; alter table public.nutzer_details alter column firma_id set not null; alter table public.notification_outbox alter column firma_id set not null; alter table public.auftragsnummer_zaehler alter column firma_id set not null; create index orte_firma_id_idx on public.orte (firma_id); create index fahrzeuge_firma_id_idx on public.fahrzeuge (firma_id); create index auftraege_firma_id_idx on public.auftraege (firma_id); create index auftrag_fotos_firma_id_idx on public.auftrag_fotos (firma_id); create index arbeitszeiten_firma_id_idx on public.arbeitszeiten (firma_id); create index nutzer_details_firma_id_idx on public.nutzer_details (firma_id); create index notification_outbox_firma_id_idx on public.notification_outbox (firma_id); -- ---------------------------------------------------- Trigger: firma_id setzen -- Mit Nutzer-Session: immer die eigene Firma (ueberschreibt jeden -- mitgeschickten Wert). Ohne Session (Service-Client, Migrationen, Tests als -- postgres): firma_id muss mitgegeben werden. create or replace function public.firma_aus_sitzung_setzen() returns trigger language plpgsql security definer set search_path = public as $$ begin if auth.uid() is not null then new.firma_id := public.user_firma_id(); if new.firma_id is null then raise exception 'Keine aktive Firma fuer den angemeldeten Nutzer' using errcode = '42501'; end if; elsif new.firma_id is null then raise exception 'firma_id fehlt' using errcode = '23502'; end if; return new; end; $$; create or replace function public.firma_aus_auftrag_setzen() returns trigger language plpgsql security definer set search_path = public as $$ begin if new.auftrag_id is not null then new.firma_id := (select a.firma_id from public.auftraege a where a.id = new.auftrag_id); end if; if new.firma_id is null then raise exception 'firma_id fehlt' using errcode = '23502'; end if; return new; end; $$; create or replace function public.firma_aus_profil_setzen() returns trigger language plpgsql security definer set search_path = public as $$ begin new.firma_id := (select p.firma_id from public.profiles p where p.id = new.user_id); if new.firma_id is null then raise exception 'firma_id fehlt' using errcode = '23502'; end if; return new; end; $$; -- Nur der Erstzuordnung null -> Wert ohne Session (Service-Client nach -- auth.admin.createUser) ist erlaubt; jede andere Aenderung wirft. create or replace function public.firma_id_unveraenderlich() returns trigger language plpgsql as $$ begin if new.firma_id is distinct from old.firma_id and not (old.firma_id is null and auth.uid() is null) then raise exception 'firma_id darf nicht geaendert werden' using errcode = '42501'; end if; return new; end; $$; -- Trigger-Namen mit Praefix a0_/a1_: Postgres feuert gleichartige Trigger -- alphabetisch, die firma_id muss vor auftragsnummer_generieren stehen. create trigger a0_firma_setzen before insert on public.orte for each row execute function public.firma_aus_sitzung_setzen(); create trigger a0_firma_setzen before insert on public.fahrzeuge for each row execute function public.firma_aus_sitzung_setzen(); create trigger a0_firma_setzen before insert on public.auftraege for each row execute function public.firma_aus_sitzung_setzen(); create trigger a0_firma_setzen before insert on public.arbeitszeiten for each row execute function public.firma_aus_sitzung_setzen(); create trigger a0_firma_setzen before insert on public.auftrag_fotos for each row execute function public.firma_aus_auftrag_setzen(); create trigger a0_firma_setzen before insert on public.notification_outbox for each row execute function public.firma_aus_auftrag_setzen(); create trigger a0_firma_setzen before insert on public.nutzer_details for each row execute function public.firma_aus_profil_setzen(); create trigger a0_firma_fix before update on public.profiles for each row execute function public.firma_id_unveraenderlich(); create trigger a0_firma_fix before update on public.orte for each row execute function public.firma_id_unveraenderlich(); create trigger a0_firma_fix before update on public.fahrzeuge for each row execute function public.firma_id_unveraenderlich(); create trigger a0_firma_fix before update on public.auftraege for each row execute function public.firma_id_unveraenderlich(); create trigger a0_firma_fix before update on public.arbeitszeiten for each row execute function public.firma_id_unveraenderlich(); create trigger a0_firma_fix before update on public.auftrag_fotos for each row execute function public.firma_id_unveraenderlich(); create trigger a0_firma_fix before update on public.notification_outbox for each row execute function public.firma_id_unveraenderlich(); create trigger a0_firma_fix before update on public.nutzer_details for each row execute function public.firma_id_unveraenderlich(); -- ------------------------------------------- Trigger: firmenfremde Verweise create or replace function public.auftrag_firma_konsistenz() returns trigger language plpgsql security definer set search_path = public as $$ begin if exists (select 1 from public.orte o where o.id in (new.abholort_id, new.zielort_id) and o.firma_id <> new.firma_id) or exists (select 1 from public.fahrzeuge f where f.id = new.fahrzeug_id and f.firma_id <> new.firma_id) or exists (select 1 from public.profiles p where p.id in (new.zugewiesen_an, new.erstellt_von) and p.firma_id is distinct from new.firma_id) or exists (select 1 from public.auftraege v where v.id = new.vorgaenger_auftrag_id and v.firma_id <> new.firma_id) then raise exception 'Firmenfremder Verweis' using errcode = '42501'; end if; return new; end; $$; create trigger a1_firma_konsistenz before insert or update on public.auftraege for each row execute function public.auftrag_firma_konsistenz(); create or replace function public.arbeitszeit_firma_konsistenz() returns trigger language plpgsql security definer set search_path = public as $$ begin if exists (select 1 from public.profiles p where p.id in (new.fahrer_id, new.korrigiert_von) and p.firma_id is distinct from new.firma_id) then raise exception 'Firmenfremder Verweis' using errcode = '42501'; end if; return new; end; $$; create trigger a1_firma_konsistenz before insert or update on public.arbeitszeiten for each row execute function public.arbeitszeit_firma_konsistenz(); -- ------------------------------------------------- Eindeutigkeit pro Firma alter table public.fahrzeuge drop constraint fahrzeuge_kennzeichen_key, drop constraint fahrzeuge_fin_key, add constraint fahrzeuge_firma_kennzeichen_key unique (firma_id, kennzeichen), add constraint fahrzeuge_firma_fin_key unique (firma_id, fin); alter table public.auftraege drop constraint auftraege_auftragsnummer_key, add constraint auftraege_firma_auftragsnummer_key unique (firma_id, auftragsnummer); alter table public.auftragsnummer_zaehler drop constraint auftragsnummer_zaehler_pkey; alter table public.auftragsnummer_zaehler add primary key (firma_id, tag); create or replace function public.generiere_auftragsnummer() returns trigger language plpgsql security definer set search_path = public as $$ declare naechste int; begin if new.auftragsnummer is null or new.auftragsnummer = '' then insert into public.auftragsnummer_zaehler (firma_id, tag, letzte_nummer) values (new.firma_id, current_date, 1) on conflict (firma_id, tag) do update set letzte_nummer = auftragsnummer_zaehler.letzte_nummer + 1 returning letzte_nummer into naechste; new.auftragsnummer := to_char(current_date, 'YY-MM-DD') || '-' || lpad(naechste::text, 4, '0'); end if; return new; end; $$; -- ------------------------------------------- FIN-Abgleich nur innerhalb der Firma create or replace function public.fin_bei_fahrtbeginn(p_auftrag_id uuid, p_fin text) returns public.app_fin_abgleich language plpgsql security definer set search_path = '' as $$ declare v_fin text := upper(btrim(coalesce(p_fin, ''))); v_fahrzeug_id uuid; v_firma_id uuid; v_hinterlegt text; v_alt_fin text; v_alt_status public.app_fin_abgleich; v_status public.app_fin_abgleich; begin if public.user_role() is distinct from 'fahrer'::public.app_role then raise exception 'Nur Fahrer duerfen den FIN-Abgleich durchfuehren'; end if; if v_fin !~ '^[A-HJ-NPR-Z0-9]{17}$' then raise exception 'Die FIN muss 17 Zeichen lang sein (A–Z, 0–9, ohne I, O, Q).'; end if; select a.fahrzeug_id, a.firma_id, a.start_fin, a.start_fin_status into v_fahrzeug_id, v_firma_id, v_alt_fin, v_alt_status from public.auftraege a where a.id = p_auftrag_id and a.zugewiesen_an = auth.uid() and a.firma_id = public.user_firma_id() and a.status = 'zugewiesen'::public.app_auftrag_status for update; if not found then raise exception 'Auftrag nicht gefunden oder nicht im Status zugewiesen'; end if; select f.fin into v_hinterlegt from public.fahrzeuge f where f.id = v_fahrzeug_id for update; if v_alt_status = 'abweichend' then -- Sticky: ein einmal vermerkter Abweichungs-Nachweis wird nicht -- ueberschrieben (auch nicht durch erneuten Aufruf mit der hinterlegten FIN). return v_alt_status; end if; if v_alt_status = 'nachgetragen' and v_alt_fin = v_fin then -- Wiederholter Aufruf mit derselben FIN: Ergebnis bleibt 'nachgetragen'. v_status := 'nachgetragen'; elsif v_hinterlegt is null then if exists (select 1 from public.fahrzeuge f where f.fin = v_fin and f.id <> v_fahrzeug_id and f.firma_id = v_firma_id) then v_status := 'abweichend'; else begin update public.fahrzeuge set fin = v_fin where id = v_fahrzeug_id; v_status := 'nachgetragen'; exception when unique_violation then -- Race: parallel wurde dieselbe FIN einem anderen Fahrzeug gegeben. v_status := 'abweichend'; end; end if; elsif v_hinterlegt = v_fin then v_status := 'bestaetigt'; else v_status := 'abweichend'; end if; perform set_config('app.fin_abgleich', 'an', true); update public.auftraege set start_fin = v_fin, start_fin_status = v_status where id = p_auftrag_id; perform set_config('app.fin_abgleich', '', true); return v_status; end; $$; -- ------------------------------------- WhatsApp nur bei Firma mit Empfaenger create or replace function public.auftrag_notification_enqueue() returns trigger language plpgsql security definer set search_path = public as $$ begin insert into public.notification_outbox (event_type, auftrag_id, payload) select 'auftrag_erstellt', new.id, jsonb_build_object( 'auftragsnummer', new.auftragsnummer, 'abholort_adresse', abhol.adresse, 'zielort_adresse', ziel.adresse, 'kennzeichen', coalesce(fz.kennzeichen, fz.fin)) from public.orte abhol join public.orte ziel on ziel.id = new.zielort_id join public.fahrzeuge fz on fz.id = new.fahrzeug_id join public.firmen fi on fi.id = new.firma_id where abhol.id = new.abholort_id and fi.whatsapp_empfaenger is not null; return new; end; $$; ``` Hinweis: Vor dem Schreiben mit `grep -n "grant\|revoke" supabase/migrations/20261009090000_fahrzeug_fin.sql` prüfen, ob `fin_bei_fahrtbeginn` besondere Grants hat; `create or replace` behält bestehende Grants. - [ ] **Step 5: Bestehende pgTAP-Tests anpassen** Run: `npx supabase db reset && npx supabase test db`. Die neuen Trigger brechen bestehende Testdateien. In **jeder** Datei unter `supabase/tests/` (außer `mandanten_struktur_test.sql`): 1. Direkt nach den `insert into auth.users ...`-Zeilen einfügen: ```sql update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; ``` 2. Jedes `insert into public.orte|fahrzeuge|auftraege|arbeitszeiten (...)`, das **als `postgres`** (also nicht nach `set local role authenticated`) läuft, bekommt die Spalte `firma_id` mit `'00000000-0000-0000-0000-00000000f001'`. 3. Tests, die eine `auftrag_erstellt`-Outbox-Zeile erwarten (`notification_outbox_rls_test.sql` u. a.), setzen vorher: ```sql update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; ``` 4. Erwartete Fehlermeldungen, die einen alten Constraint-Namen nennen (`fahrzeuge_fin_key`, `fahrzeuge_kennzeichen_key`, `auftraege_auftragsnummer_key`), auf die neuen Namen umstellen. Die **Erwartungen** der Tests (was erlaubt/verboten ist) bleiben unverändert. Wiederholen, bis alles grün ist. - [ ] **Step 6: Failing Vitest für `duplikatFehler`** `duplikatFehler` ist modulintern; exportieren und testen. In `web/lib/orte-fahrzeuge/mutations.test.ts` (anlegen, falls nicht vorhanden; sonst ergänzen): ```ts import { describe, expect, it } from "vitest"; import { duplikatFehler } from "./mutations"; describe("duplikatFehler", () => { it("erkennt den FIN-Constraint pro Firma", () => { expect( duplikatFehler({ message: 'duplicate key value violates unique constraint "fahrzeuge_firma_fin_key"' }) ).toBe("Diese FIN ist bereits vergeben."); }); it("meldet sonst ein doppeltes Kennzeichen", () => { expect( duplikatFehler({ message: 'duplicate key value violates unique constraint "fahrzeuge_firma_kennzeichen_key"' }) ).toBe("Dieses Kennzeichen ist bereits vergeben."); }); }); ``` Run (aus `web/`): `npx vitest run lib/orte-fahrzeuge/mutations.test.ts` → FAIL (`duplikatFehler` nicht exportiert bzw. erster Test liefert Kennzeichen-Text). - [ ] **Step 7: `duplikatFehler` anpassen** In `web/lib/orte-fahrzeuge/mutations.ts`: ```ts // Beide Unique-Constraints liefern 23505; unterschieden wird am // Constraint-Namen in der Postgres-Meldung (fahrzeuge_firma_fin_key / // fahrzeuge_firma_kennzeichen_key, eindeutig pro Firma). export function duplikatFehler(error: { message: string }): string { return error.message.includes("_fin_key") ? "Diese FIN ist bereits vergeben." : "Dieses Kennzeichen ist bereits vergeben."; } ``` - [ ] **Step 8: Alles grün prüfen** Run (Repo-Root): `npx supabase db reset && npx supabase test db` → alle Dateien PASS. Run (`web/`): `npm test && npx tsc --noEmit` → PASS. Zusätzlich: `docker exec supabase_db_fundament-auth-rollen psql -U postgres -d postgres -Atc "select count(*) from public.auftraege where firma_id is null"` → `0`. - [ ] **Step 9: Commit** ```bash git add supabase/migrations/20261012090000_superadmin_rolle.sql supabase/migrations/20261012090100_mandanten_struktur.sql supabase/tests web/lib/orte-fahrzeuge git commit -m "feat: Firmen, firma_id in allen Fachtabellen, Trigger und Eindeutigkeit pro Firma" ``` --- ### Task 2: RLS-Policies und Storage pro Firma **Files:** - Create: `supabase/migrations/20261012090200_mandanten_rls.sql` - Create: `supabase/tests/mandanten_rls_test.sql` **Interfaces:** - Consumes: `public.user_firma_id()`, `firma_id`-Spalten, Firma `f001` (Task 1). - Produces: Bucket `firmen-logos` (Pfad `/…`); `firmen` lesbar für eigene Firma, änderbar durch deren Admin; alle Fachdaten nur innerhalb der eigenen aktiven Firma. - [ ] **Step 1: Failing pgTAP-Test schreiben** `supabase/tests/mandanten_rls_test.sql`: ```sql begin; select plan(30); insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); insert into auth.users (id, email) values ('a0000000-0000-0000-0000-0000000000a1', 'admin-a@rls.test.local'), ('a0000000-0000-0000-0000-0000000000a2', 'dispo-a@rls.test.local'), ('a0000000-0000-0000-0000-0000000000a3', 'fahrer-a@rls.test.local'), ('b0000000-0000-0000-0000-0000000000b1', 'admin-b@rls.test.local'), ('b0000000-0000-0000-0000-0000000000b2', 'dispo-b@rls.test.local'), ('b0000000-0000-0000-0000-0000000000b3', 'fahrer-b@rls.test.local'), ('5a000000-0000-0000-0000-000000000001', 'superadmin@rls.test.local'); update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'admin' where id = 'a0000000-0000-0000-0000-0000000000a1'; update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'disponent' where id = 'a0000000-0000-0000-0000-0000000000a2'; update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'fahrer' where id = 'a0000000-0000-0000-0000-0000000000a3'; update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'admin' where id = 'b0000000-0000-0000-0000-0000000000b1'; update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'disponent' where id = 'b0000000-0000-0000-0000-0000000000b2'; update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'fahrer' where id = 'b0000000-0000-0000-0000-0000000000b3'; update public.profiles set role = 'superadmin' where id = '5a000000-0000-0000-0000-000000000001'; update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; -- Daten Firma A insert into public.orte (id, adresse, ansprechpartner, firma_id) values ('a0000000-0000-0000-0000-0000000000c1', 'Ort A', 'Herr A', '00000000-0000-0000-0000-00000000f001'); insert into public.fahrzeuge (id, kennzeichen, firma_id) values ('a0000000-0000-0000-0000-0000000000d1', 'MT-A 1', '00000000-0000-0000-0000-00000000f001'); insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, firma_id) values ('a0000000-0000-0000-0000-0000000000e1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', 'zugewiesen', 'a0000000-0000-0000-0000-0000000000a3', '00000000-0000-0000-0000-00000000f001'), ('a0000000-0000-0000-0000-0000000000e2', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', 'offen', null, '00000000-0000-0000-0000-00000000f001'); insert into public.auftrag_fotos (auftrag_id, position, storage_path, uploaded_by) values ('a0000000-0000-0000-0000-0000000000e1', 'front', 'a0000000-0000-0000-0000-0000000000e1/front.jpg', 'a0000000-0000-0000-0000-0000000000a3'); insert into public.arbeitszeiten (fahrer_id, kommt_um, firma_id) values ('a0000000-0000-0000-0000-0000000000a3', now(), '00000000-0000-0000-0000-00000000f001'); insert into public.nutzer_details (user_id, telefon) values ('a0000000-0000-0000-0000-0000000000a3', '+4915100000002'); insert into storage.objects (bucket_id, name, owner) values ('auftrag-fotos', 'a0000000-0000-0000-0000-0000000000e1/front.jpg', 'a0000000-0000-0000-0000-0000000000a3'), ('auftrag-unterschriften', 'a0000000-0000-0000-0000-0000000000e1/unterschrift.png', 'a0000000-0000-0000-0000-0000000000a3'), ('firmen-logos', '00000000-0000-0000-0000-00000000f001/logo-1.png', 'a0000000-0000-0000-0000-0000000000a1'); -- Daten Firma B insert into public.orte (id, adresse, ansprechpartner, firma_id) values ('b0000000-0000-0000-0000-0000000000c1', 'Ort B', 'Frau B', '00000000-0000-0000-0000-00000000f002'); -- ====================== Admin B set local role authenticated; set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; select ok(not exists (select 1 from public.orte where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Orte von A'); select ok(exists (select 1 from public.orte where id = 'b0000000-0000-0000-0000-0000000000c1'), 'Admin B sieht eigene Orte'); select ok(not exists (select 1 from public.fahrzeuge where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Fahrzeuge von A'); select ok(not exists (select 1 from public.auftraege where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Auftraege von A'); select ok(not exists (select 1 from public.auftrag_fotos), 'Admin B sieht keine Auftragsfotos von A'); select ok(not exists (select 1 from public.arbeitszeiten), 'Admin B sieht keine Arbeitszeiten von A'); select ok(not exists (select 1 from public.nutzer_details), 'Admin B sieht keine Nutzer-Details von A'); select ok(not exists (select 1 from public.profiles where firma_id = '00000000-0000-0000-0000-00000000f001'), 'Admin B sieht keine Profile von A'); select ok(not exists (select 1 from public.notification_outbox), 'Admin B sieht keine Outbox-Zeilen von A'); select is((select array_agg(id) from public.firmen), array['00000000-0000-0000-0000-00000000f002'::uuid], 'Admin B sieht nur die eigene Firma'); select ok(not exists (select 1 from storage.objects where name like 'a0000000-0000-0000-0000-0000000000e1/%' or name like '00000000-0000-0000-0000-00000000f001/%'), 'Admin B sieht keine Storage-Objekte von A'); select is( (with u as (update public.orte set adresse = 'x' where id = 'a0000000-0000-0000-0000-0000000000c1' returning 1) select count(*) from u), 0::bigint, 'Admin B kann keinen Ort von A aendern'); select is( (with u as (update public.auftraege set status = 'storniert' where id = 'a0000000-0000-0000-0000-0000000000e2' returning 1) select count(*) from u), 0::bigint, 'Admin B kann keinen Auftrag von A aendern'); select is( (with u as (update public.profiles set name = 'x' where id = 'a0000000-0000-0000-0000-0000000000a3' returning 1) select count(*) from u), 0::bigint, 'Admin B kann kein Profil von A aendern'); select is( (with u as (update public.firmen set name = 'x' where id = '00000000-0000-0000-0000-00000000f001' returning 1) select count(*) from u), 0::bigint, 'Admin B kann Firma A nicht umbenennen'); select is( (with u as (update public.firmen set name = 'Firma B neu' where id = '00000000-0000-0000-0000-00000000f002' returning 1) select count(*) from u), 1::bigint, 'Admin B kann die eigene Firma umbenennen'); select throws_ok( $$ update public.profiles set role = 'superadmin' where id = 'b0000000-0000-0000-0000-0000000000b3' $$, null, null, 'Admin B kann niemanden zum Superadmin machen'); select throws_ok( $$ insert into public.nutzer_details (user_id, telefon) values ('a0000000-0000-0000-0000-0000000000a1', '+4915100000003') $$, '42501', 'new row violates row-level security policy for table "nutzer_details"', 'Admin B kann keine Details fuer Nutzer von A anlegen'); select throws_ok( $$ insert into storage.objects (bucket_id, name, owner) values ('firmen-logos', '00000000-0000-0000-0000-00000000f001/logo-2.png', 'b0000000-0000-0000-0000-0000000000b1') $$, '42501', 'new row violates row-level security policy for table "objects"', 'Admin B kann kein Logo fuer Firma A hochladen'); select lives_ok( $$ insert into storage.objects (bucket_id, name, owner) values ('firmen-logos', '00000000-0000-0000-0000-00000000f002/logo-1.png', 'b0000000-0000-0000-0000-0000000000b1') $$, 'Admin B kann ein Logo fuer die eigene Firma hochladen'); select throws_ok( $$ select * from public.firmen_smtp $$, '42501', null, 'firmen_smtp ist fuer angemeldete Nutzer gesperrt'); reset role; reset request.jwt.claims; -- ====================== Fahrer B set local role authenticated; set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b3", "role": "authenticated"}'; select ok(not exists (select 1 from public.auftraege where id = 'a0000000-0000-0000-0000-0000000000e2'), 'Fahrer B sieht den offenen Auftrag von A nicht'); select is( (with u as (update public.auftraege set zugewiesen_an = 'b0000000-0000-0000-0000-0000000000b3', status = 'zugewiesen' where id = 'a0000000-0000-0000-0000-0000000000e2' returning 1) select count(*) from u), 0::bigint, 'Fahrer B kann den offenen Auftrag von A nicht uebernehmen'); reset role; reset request.jwt.claims; -- ====================== Disponent A set local role authenticated; set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a2", "role": "authenticated"}'; select ok( exists (select 1 from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a3') and not exists (select 1 from public.profiles where id = 'b0000000-0000-0000-0000-0000000000b3'), 'Disponent A sieht nur Fahrer der eigenen Firma'); select ok(exists (select 1 from public.auftraege where id = 'a0000000-0000-0000-0000-0000000000e1'), 'Disponent A sieht eigene Auftraege'); reset role; reset request.jwt.claims; -- ====================== Superadmin set local role authenticated; set local request.jwt.claims to '{"sub": "5a000000-0000-0000-0000-000000000001", "role": "authenticated"}'; select ok(not exists (select 1 from public.auftraege), 'Superadmin sieht keine Auftraege'); select ok(not exists (select 1 from public.firmen), 'Superadmin sieht ueber RLS keine Firmen'); select ok(exists (select 1 from public.profiles where id = '5a000000-0000-0000-0000-000000000001'), 'Superadmin sieht sein eigenes Profil'); reset role; reset request.jwt.claims; -- ====================== Firma A deaktiviert update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f001'; set local role authenticated; set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a1", "role": "authenticated"}'; select ok(not exists (select 1 from public.auftraege), 'Deaktivierte Firma: Admin sieht keine Auftraege mehr'); select ok(exists (select 1 from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a1'), 'Deaktivierte Firma: eigenes Profil bleibt lesbar'); reset role; reset request.jwt.claims; select * from finish(); rollback; ``` - [ ] **Step 2: Fehlschlag prüfen** Run (Repo-Root): `npx supabase test db` → FAIL in `mandanten_rls_test.sql` (u. a. Bucket `firmen-logos` fehlt, Admin B sieht Daten von A). - [ ] **Step 3: RLS-Migration schreiben** `supabase/migrations/20261012090200_mandanten_rls.sql`: ```sql -- Mandantenfaehigkeit, Teil 2: jede Policy prueft zusaetzlich die Firma. -- Rollenlogik unveraendert; der Superadmin hat keine Policy auf Fachdaten. -- Ausnahme: "Nutzer sehen ihr eigenes Profil" bleibt ohne Firmenbedingung -- (Login-Pruefung, Layout, Superadmin). -- ------------------------------------------------------------------ firmen create policy "Nutzer sehen die eigene Firma" on public.firmen for select using (id = public.user_firma_id()); create policy "Admin aktualisiert die eigene Firma" on public.firmen for update using (id = public.user_firma_id() and public.user_role() = 'admin') with check (id = public.user_firma_id() and public.user_role() = 'admin'); -- ---------------------------------------------------------------- profiles drop policy "Admins sehen alle Profile" on public.profiles; create policy "Admins sehen alle Profile" on public.profiles for select using (public.user_role() = 'admin' and firma_id = public.user_firma_id()); drop policy "Admins aktualisieren alle Profile" on public.profiles; create policy "Admins aktualisieren alle Profile" on public.profiles for update using (public.user_role() = 'admin' and firma_id = public.user_firma_id()) with check (public.user_role() = 'admin' and firma_id = public.user_firma_id() and role <> 'superadmin'); drop policy "Disponent sieht Fahrer-Profile" on public.profiles; create policy "Disponent sieht Fahrer-Profile" on public.profiles for select using (public.user_role() = 'disponent' and role = 'fahrer' and firma_id = public.user_firma_id()); drop policy "Fahrer und Readonly sehen Admin/Disponent-Profile" on public.profiles; create policy "Fahrer und Readonly sehen Admin/Disponent-Profile" on public.profiles for select using ( public.user_role() in ('fahrer', 'readonly') and role in ('admin', 'disponent') and firma_id = public.user_firma_id() ); -- -------------------------------------------------------------------- orte drop policy "Eingeloggte Nutzer sehen alle Orte" on public.orte; create policy "Eingeloggte Nutzer sehen alle Orte" on public.orte for select using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'fahrer', 'readonly')); drop policy "Disponent und Admin legen Orte an" on public.orte; create policy "Disponent und Admin legen Orte an" on public.orte for insert with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); drop policy "Disponent und Admin bearbeiten Orte" on public.orte; create policy "Disponent und Admin bearbeiten Orte" on public.orte for update using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); -- --------------------------------------------------------------- fahrzeuge drop policy "Eingeloggte Nutzer sehen alle Fahrzeuge" on public.fahrzeuge; create policy "Eingeloggte Nutzer sehen alle Fahrzeuge" on public.fahrzeuge for select using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'fahrer', 'readonly')); drop policy "Disponent und Admin legen Fahrzeuge an" on public.fahrzeuge; create policy "Disponent und Admin legen Fahrzeuge an" on public.fahrzeuge for insert with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); drop policy "Disponent und Admin bearbeiten Fahrzeuge" on public.fahrzeuge; create policy "Disponent und Admin bearbeiten Fahrzeuge" on public.fahrzeuge for update using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); -- --------------------------------------------------------------- auftraege drop policy "Sichtbarkeit von Auftraegen nach Rolle" on public.auftraege; create policy "Sichtbarkeit von Auftraegen nach Rolle" on public.auftraege for select using ( firma_id = public.user_firma_id() and ( public.user_role() in ('admin', 'disponent', 'readonly') or zugewiesen_an = auth.uid() or status = 'offen' ) ); drop policy "Disponent und Admin legen Auftraege an" on public.auftraege; create policy "Disponent und Admin legen Auftraege an" on public.auftraege for insert with check ( firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent') and erstellt_von = auth.uid() ); drop policy "Disponent und Admin bearbeiten alle Auftraege" on public.auftraege; create policy "Disponent und Admin bearbeiten alle Auftraege" on public.auftraege for update using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); drop policy "Fahrer uebernimmt offene oder bearbeitet eigene Auftraege" on public.auftraege; create policy "Fahrer uebernimmt offene oder bearbeitet eigene Auftraege" on public.auftraege for update using ( firma_id = public.user_firma_id() and public.user_role() = 'fahrer' and (zugewiesen_an = auth.uid() or status = 'offen') ) with check ( firma_id = public.user_firma_id() and public.user_role() = 'fahrer' and (zugewiesen_an = auth.uid() or zugewiesen_an is null) ); -- ----------------------------------------------------------- auftrag_fotos drop policy "Disponent Admin Readonly sehen alle Auftragsfotos" on public.auftrag_fotos; create policy "Disponent Admin Readonly sehen alle Auftragsfotos" on public.auftrag_fotos for select using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'readonly')); drop policy "Fahrer sieht Fotos des eigenen zugewiesenen Auftrags" on public.auftrag_fotos; create policy "Fahrer sieht Fotos des eigenen zugewiesenen Auftrags" on public.auftrag_fotos for select using ( firma_id = public.user_firma_id() and exists ( select 1 from public.auftraege where auftraege.id = auftrag_fotos.auftrag_id and auftraege.zugewiesen_an = auth.uid() ) ); drop policy "Fahrer laedt Fotos fuer eigenen zugewiesenen Auftrag hoch" on public.auftrag_fotos; create policy "Fahrer laedt Fotos fuer eigenen zugewiesenen Auftrag hoch" on public.auftrag_fotos for insert with check ( firma_id = public.user_firma_id() and public.user_role() = 'fahrer' and uploaded_by = auth.uid() and exists ( select 1 from public.auftraege where auftraege.id = auftrag_fotos.auftrag_id and auftraege.zugewiesen_an = auth.uid() and ( (auftrag_fotos.position <> 'schaden' and auftraege.status = 'zugewiesen') or (auftrag_fotos.position = 'schaden' and auftraege.status in ('zugewiesen', 'unterwegs')) ) ) ); drop policy "Admin aktualisiert Auftragsfotos" on public.auftrag_fotos; create policy "Admin aktualisiert Auftragsfotos" on public.auftrag_fotos for update using (firma_id = public.user_firma_id() and public.user_role() = 'admin') with check (firma_id = public.user_firma_id() and public.user_role() = 'admin'); drop policy "Admin loescht Auftragsfotos" on public.auftrag_fotos; create policy "Admin loescht Auftragsfotos" on public.auftrag_fotos for delete using (firma_id = public.user_firma_id() and public.user_role() = 'admin'); -- ----------------------------------------------------------- arbeitszeiten drop policy "Fahrer sieht eigene Arbeitszeiten, Disponent/Admin sehen alle" on public.arbeitszeiten; create policy "Fahrer sieht eigene Arbeitszeiten, Disponent/Admin sehen alle" on public.arbeitszeiten for select using ( firma_id = public.user_firma_id() and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) ); drop policy "Fahrer stempelt sich selbst ein" on public.arbeitszeiten; create policy "Fahrer stempelt sich selbst ein" on public.arbeitszeiten for insert with check ( firma_id = public.user_firma_id() and public.user_role() = 'fahrer' and fahrer_id = auth.uid() and geht_um is null and korrigiert_von is null and korrigiert_am is null ); drop policy "Fahrer schliesst Schicht, Disponent/Admin korrigieren" on public.arbeitszeiten; create policy "Fahrer schliesst Schicht, Disponent/Admin korrigieren" on public.arbeitszeiten for update using ( firma_id = public.user_firma_id() and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) ) with check ( firma_id = public.user_firma_id() and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) ); -- ---------------------------------------------------------- nutzer_details drop policy "Admin und Disponent sehen alle Details" on public.nutzer_details; create policy "Admin und Disponent sehen alle Details" on public.nutzer_details for select using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); drop policy "Nutzer und Admin legen Details an" on public.nutzer_details; create policy "Nutzer und Admin legen Details an" on public.nutzer_details for insert with check (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')); drop policy "Nutzer und Admin aktualisieren Details" on public.nutzer_details; create policy "Nutzer und Admin aktualisieren Details" on public.nutzer_details for update using (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')) with check (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')); -- "Nutzer sehen ihre eigenen Details" (auth.uid() = user_id) bleibt unveraendert. -- ----------------------------------------------------- notification_outbox drop policy "Admin liest notification_outbox" on public.notification_outbox; create policy "Admin liest notification_outbox" on public.notification_outbox for select using (firma_id = public.user_firma_id() and public.user_role() = 'admin'); -- ================================================================ Storage -- Pfade /...: Zugriff nur, wenn der Auftrag zur eigenen Firma gehoert. drop policy "Fahrer liest Fotos des eigenen zugewiesenen Auftrags" on storage.objects; create policy "Fahrer liest Fotos des eigenen zugewiesenen Auftrags" on storage.objects for select using ( bucket_id = 'auftrag-fotos' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.zugewiesen_an = auth.uid() and a.firma_id = public.user_firma_id() ) ); drop policy "Disponent Admin Readonly lesen alle Auftragsfotos im Storage" on storage.objects; create policy "Disponent Admin Readonly lesen alle Auftragsfotos im Storage" on storage.objects for select using ( bucket_id = 'auftrag-fotos' and public.user_role() in ('admin', 'disponent', 'readonly') and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() ) ); drop policy "Fahrer laedt Auftragsfotos hoch" on storage.objects; create policy "Fahrer laedt Auftragsfotos hoch" on storage.objects for insert with check ( bucket_id = 'auftrag-fotos' and public.user_role() = 'fahrer' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.zugewiesen_an = auth.uid() and a.firma_id = public.user_firma_id() and ( (split_part(name, '/', 2) not like 'schaden-%' and a.status = 'zugewiesen') or (split_part(name, '/', 2) like 'schaden-%' and a.status in ('zugewiesen', 'unterwegs')) ) ) ); drop policy "Admin aktualisiert Auftragsfotos im Storage" on storage.objects; create policy "Admin aktualisiert Auftragsfotos im Storage" on storage.objects for update using ( bucket_id = 'auftrag-fotos' and public.user_role() = 'admin' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() ) ); drop policy "Admin loescht Auftragsfotos im Storage" on storage.objects; create policy "Admin loescht Auftragsfotos im Storage" on storage.objects for delete using ( bucket_id = 'auftrag-fotos' and public.user_role() = 'admin' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() ) ); drop policy "Fahrer liest Unterschrift des eigenen zugewiesenen Auftrags" on storage.objects; create policy "Fahrer liest Unterschrift des eigenen zugewiesenen Auftrags" on storage.objects for select using ( bucket_id = 'auftrag-unterschriften' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.zugewiesen_an = auth.uid() and a.firma_id = public.user_firma_id() ) ); drop policy "Disponent Admin Readonly lesen alle Unterschriften im Storage" on storage.objects; create policy "Disponent Admin Readonly lesen alle Unterschriften im Storage" on storage.objects for select using ( bucket_id = 'auftrag-unterschriften' and public.user_role() in ('admin', 'disponent', 'readonly') and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() ) ); drop policy "Fahrer laedt Unterschrift bei Fahrtende hoch" on storage.objects; create policy "Fahrer laedt Unterschrift bei Fahrtende hoch" on storage.objects for insert with check ( bucket_id = 'auftrag-unterschriften' and public.user_role() = 'fahrer' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.zugewiesen_an = auth.uid() and a.firma_id = public.user_firma_id() and a.status = 'unterwegs' ) ); drop policy "Fahrer aktualisiert eigene Unterschrift bei Fahrtende" on storage.objects; create policy "Fahrer aktualisiert eigene Unterschrift bei Fahrtende" on storage.objects for update using ( bucket_id = 'auftrag-unterschriften' and public.user_role() = 'fahrer' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.zugewiesen_an = auth.uid() and a.firma_id = public.user_firma_id() and a.status = 'unterwegs' ) ) with check ( bucket_id = 'auftrag-unterschriften' and public.user_role() = 'fahrer' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.zugewiesen_an = auth.uid() and a.firma_id = public.user_firma_id() and a.status = 'unterwegs' ) ); drop policy "Admin aktualisiert Unterschriften im Storage" on storage.objects; create policy "Admin aktualisiert Unterschriften im Storage" on storage.objects for update using ( bucket_id = 'auftrag-unterschriften' and public.user_role() = 'admin' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() ) ); drop policy "Admin loescht Unterschriften im Storage" on storage.objects; create policy "Admin loescht Unterschriften im Storage" on storage.objects for delete using ( bucket_id = 'auftrag-unterschriften' and public.user_role() = 'admin' and exists ( select 1 from public.auftraege a where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() ) ); -- ------------------------------------------------------------ firmen-logos insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types) values ('firmen-logos', 'firmen-logos', false, 1048576, array['image/png', 'image/jpeg', 'image/svg+xml']) on conflict (id) do nothing; create policy "Nutzer lesen das Logo der eigenen Firma" on storage.objects for select using (bucket_id = 'firmen-logos' and (storage.foldername(name))[1] = public.user_firma_id()::text); create policy "Admin laedt das Logo der eigenen Firma hoch" on storage.objects for insert with check ( bucket_id = 'firmen-logos' and public.user_role() = 'admin' and (storage.foldername(name))[1] = public.user_firma_id()::text ); create policy "Admin aktualisiert das Logo der eigenen Firma" on storage.objects for update using ( bucket_id = 'firmen-logos' and public.user_role() = 'admin' and (storage.foldername(name))[1] = public.user_firma_id()::text ) with check ( bucket_id = 'firmen-logos' and public.user_role() = 'admin' and (storage.foldername(name))[1] = public.user_firma_id()::text ); create policy "Admin loescht das Logo der eigenen Firma" on storage.objects for delete using ( bucket_id = 'firmen-logos' and public.user_role() = 'admin' and (storage.foldername(name))[1] = public.user_firma_id()::text ); ``` Vor dem Schreiben: mit `grep -n "create policy" -A12 supabase/migrations/*.sql` jede alte Policy gegen die neue Fassung oben abgleichen (gleiche Rollenlogik, nur `firma_id`-Bedingung ergänzt). Weicht eine alte Policy von der hier zitierten Fassung ab, gilt die alte Rollenlogik plus Firmenbedingung. - [ ] **Step 4: Alles grün prüfen** Run (Repo-Root): `npx supabase db reset && npx supabase test db` → alle Dateien PASS (inkl. der bestehenden RLS-Tests). Run: `docker exec supabase_db_fundament-auth-rollen psql -U postgres -d postgres -Atc "select count(*) from pg_policies where schemaname in ('public','storage')"` vor und nach der Migration → nachher genau **6 mehr** (+2 `firmen`, +4 Logos; alle anderen nur ersetzt). - [ ] **Step 5: Commit** ```bash git add supabase/migrations/20261012090200_mandanten_rls.sql supabase/tests/mandanten_rls_test.sql git commit -m "feat: RLS und Storage pro Firma, Bucket firmen-logos" ``` --- ### Task 3: Reine Helfer — Farben und SMTP-Verschlüsselung **Files:** - Create: `web/lib/firma/farben.ts`, `web/lib/firma/farben.test.ts` - Create: `web/lib/firma/smtp-crypto.ts`, `web/lib/firma/smtp-crypto.test.ts` **Interfaces:** - Produces: - `STANDARD_FARBE_PRIMAER = "#0071ed"`, `STANDARD_FARBE_DUNKEL = "#0a185c"`, `MIN_KONTRAST = 4.5` - `normalisiereFarbe(eingabe: string): string | null` - `kontrastZuWeiss(hex: string): number` - `themeVariablen(f: { farbe_primaer: string | null; farbe_dunkel: string | null }): Record` - `verschluessele(klartext: string): string`, `entschluessele(wert: string): string` - [ ] **Step 1: Failing Tests schreiben** `web/lib/firma/farben.test.ts`: ```ts import { describe, expect, it } from "vitest"; import { MIN_KONTRAST, STANDARD_FARBE_DUNKEL, STANDARD_FARBE_PRIMAER, kontrastZuWeiss, normalisiereFarbe, themeVariablen, } from "./farben"; describe("normalisiereFarbe", () => { it("akzeptiert #rrggbb und schreibt klein", () => { expect(normalisiereFarbe(" #0A185C ")).toBe("#0a185c"); }); it("lehnt andere Formate ab", () => { expect(normalisiereFarbe("#abc")).toBeNull(); expect(normalisiereFarbe("0071ed")).toBeNull(); expect(normalisiereFarbe("#gggggg")).toBeNull(); expect(normalisiereFarbe("")).toBeNull(); }); }); describe("kontrastZuWeiss", () => { it("liefert 21 fuer Schwarz und 1 fuer Weiss", () => { expect(kontrastZuWeiss("#000000")).toBeCloseTo(21, 1); expect(kontrastZuWeiss("#ffffff")).toBeCloseTo(1, 5); }); it("Standardfarben bestehen den Mindestkontrast", () => { expect(kontrastZuWeiss(STANDARD_FARBE_PRIMAER)).toBeGreaterThanOrEqual(MIN_KONTRAST); expect(kontrastZuWeiss(STANDARD_FARBE_DUNKEL)).toBeGreaterThanOrEqual(MIN_KONTRAST); }); it("Gelb faellt durch", () => { expect(kontrastZuWeiss("#ffff00")).toBeLessThan(MIN_KONTRAST); }); }); describe("themeVariablen", () => { it("setzt nur vorhandene Farben", () => { expect(themeVariablen({ farbe_primaer: "#112233", farbe_dunkel: null })).toEqual({ "--color-performance-blue": "#112233", }); expect(themeVariablen({ farbe_primaer: null, farbe_dunkel: "#000000" })).toEqual({ "--color-night-blue": "#000000", }); expect(themeVariablen({ farbe_primaer: null, farbe_dunkel: null })).toEqual({}); }); }); ``` `web/lib/firma/smtp-crypto.test.ts`: ```ts import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { entschluessele, verschluessele } from "./smtp-crypto"; const KEY = Buffer.alloc(32, 7).toString("base64"); describe("smtp-crypto", () => { const alt = process.env.SMTP_VERSCHLUESSELUNG_KEY; beforeEach(() => { process.env.SMTP_VERSCHLUESSELUNG_KEY = KEY; }); afterEach(() => { process.env.SMTP_VERSCHLUESSELUNG_KEY = alt; }); it("Roundtrip liefert den Klartext", () => { const wert = verschluessele("geheim-äöü"); expect(wert.startsWith("v1:")).toBe(true); expect(wert).not.toContain("geheim"); expect(entschluessele(wert)).toBe("geheim-äöü"); }); it("zwei Verschluesselungen desselben Texts unterscheiden sich (zufaelliger IV)", () => { expect(verschluessele("x")).not.toBe(verschluessele("x")); }); it("manipulierter Ciphertext scheitert", () => { const [v, iv, tag, ct] = verschluessele("geheim").split(":"); const kaputt = Buffer.from(ct, "base64"); kaputt[0] ^= 1; expect(() => entschluessele([v, iv, tag, kaputt.toString("base64")].join(":"))).toThrow(); }); it("unbekanntes Format scheitert", () => { expect(() => entschluessele("klartext")).toThrow("Unbekanntes Format"); }); it("fehlender Schluessel scheitert mit klarer Meldung", () => { delete process.env.SMTP_VERSCHLUESSELUNG_KEY; expect(() => verschluessele("x")).toThrow("SMTP_VERSCHLUESSELUNG_KEY ist nicht gesetzt"); }); it("Schluessel falscher Laenge scheitert", () => { process.env.SMTP_VERSCHLUESSELUNG_KEY = Buffer.alloc(16).toString("base64"); expect(() => verschluessele("x")).toThrow("32 Byte"); }); }); ``` - [ ] **Step 2: Fehlschlag prüfen** Run (`web/`): `npx vitest run lib/firma` → FAIL (Module fehlen). - [ ] **Step 3: Implementieren** `web/lib/firma/farben.ts`: ```ts export const STANDARD_FARBE_PRIMAER = "#0071ed"; export const STANDARD_FARBE_DUNKEL = "#0a185c"; // WCAG AA fuer normalen Text: Buttons tragen weisse Schrift auf der Hauptfarbe. export const MIN_KONTRAST = 4.5; const HEX_REGEX = /^#[0-9a-f]{6}$/; export function normalisiereFarbe(eingabe: string): string | null { const wert = eingabe.trim().toLowerCase(); return HEX_REGEX.test(wert) ? wert : null; } function kanal(wert: number): number { const c = wert / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; } // Kontrastverhaeltnis nach WCAG 2.x zwischen der Farbe und Weiss. export function kontrastZuWeiss(hex: string): number { const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const b = parseInt(hex.slice(5, 7), 16); const luminanz = 0.2126 * kanal(r) + 0.7152 * kanal(g) + 0.0722 * kanal(b); return 1.05 / (luminanz + 0.05); } // CSS-Variablen aus globals.css (@theme), die das Layout am ueberschreibt. export function themeVariablen(f: { farbe_primaer: string | null; farbe_dunkel: string | null }): Record { const variablen: Record = {}; if (f.farbe_primaer) variablen["--color-performance-blue"] = f.farbe_primaer; if (f.farbe_dunkel) variablen["--color-night-blue"] = f.farbe_dunkel; return variablen; } ``` `web/lib/firma/smtp-crypto.ts`: ```ts import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; const ALGORITHMUS = "aes-256-gcm"; function schluessel(): Buffer { const roh = process.env.SMTP_VERSCHLUESSELUNG_KEY; if (!roh) { throw new Error("SMTP_VERSCHLUESSELUNG_KEY ist nicht gesetzt"); } const key = Buffer.from(roh, "base64"); if (key.length !== 32) { throw new Error("SMTP_VERSCHLUESSELUNG_KEY muss 32 Byte (base64) lang sein"); } return key; } // Format v1:::, alles base64. Die Version erlaubt einen // spaeteren Schluesselwechsel ohne Raten. export function verschluessele(klartext: string): string { const iv = randomBytes(12); const cipher = createCipheriv(ALGORITHMUS, schluessel(), iv); const ciphertext = Buffer.concat([cipher.update(klartext, "utf8"), cipher.final()]); const tag = cipher.getAuthTag(); return ["v1", iv.toString("base64"), tag.toString("base64"), ciphertext.toString("base64")].join(":"); } export function entschluessele(wert: string): string { const teile = wert.split(":"); if (teile.length !== 4 || teile[0] !== "v1") { throw new Error("Unbekanntes Format des verschluesselten SMTP-Passworts"); } const [, iv, tag, ciphertext] = teile; const decipher = createDecipheriv(ALGORITHMUS, schluessel(), Buffer.from(iv, "base64")); decipher.setAuthTag(Buffer.from(tag, "base64")); return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8"); } ``` - [ ] **Step 4: Grün prüfen** Run (`web/`): `npx vitest run lib/firma && npx tsc --noEmit` → PASS. - [ ] **Step 5: Commit** ```bash git add web/lib/firma git commit -m "feat: Farb-Kontrastpruefung und SMTP-Passwort-Verschluesselung" ``` --- ### Task 4: Rollen, Firma laden, Login-Prüfung, Layout-Branding, Logo-Route **Files:** - Modify: `web/lib/auth/roles.ts`, `web/lib/auth/profile.ts` - Create: `web/lib/firma/queries.ts`, `web/lib/firma/queries.test.ts` - Create: `web/lib/firma/eigene-firma.ts` - Create: `web/lib/firma/logo.ts`, `web/lib/firma/logo.test.ts` - Create: `web/app/firma/logo/route.ts` - Create: `web/app/abmelden/route.ts` - Create: `web/components/FirmenLogo.tsx` - Modify: `web/app/login/actions.ts`, `web/app/layout.tsx`, `web/components/NavLinks.tsx` **Interfaces:** - Consumes: `themeVariablen` (Task 3); Tabelle `firmen`, Bucket `firmen-logos` (Tasks 1–2). - Produces: - `Role` enthält `"superadmin"`; `istSuperadmin(role)`, `kannFirmaVerwalten(role)`. - `Profile` hat `firma_id: string | null`. - `WIDMANN_FIRMA_ID`, `type Firma`, `ladeFirma(client, firmaId): Promise`, `type FirmaBranding`, `ladeFirmaZumAuftrag(client, auftragId): Promise`, `pruefeFirmenzugang(client, userId): Promise<"ok" | "superadmin" | "gesperrt">` (alle in `lib/firma/queries.ts`). - `FIRMA_GESPERRT` (Text), `ladeEigeneFirma()` (in `lib/firma/eigene-firma.ts`). - `LOGO_MAX_BYTES`, `validateLogo`, `logoPfad`, `logoContentType`, `LOGO_SICHERHEITS_HEADER` (in `lib/firma/logo.ts`). - [ ] **Step 1: Failing Tests schreiben** `web/lib/firma/queries.test.ts`: ```ts import { describe, expect, it } from "vitest"; import type { SupabaseClient } from "@supabase/supabase-js"; import { pruefeFirmenzugang } from "./queries"; type Antworten = { profil: { role: string; firma_id: string | null } | null; firma: { id: string } | null }; function fakeClient(a: Antworten): SupabaseClient { return { from(tabelle: string) { const daten = tabelle === "profiles" ? a.profil : a.firma; const kette = { select: () => kette, eq: () => kette, maybeSingle: async () => ({ data: daten, error: null }), }; return kette; }, } as unknown as SupabaseClient; } describe("pruefeFirmenzugang", () => { it("Superadmin", async () => { expect(await pruefeFirmenzugang(fakeClient({ profil: { role: "superadmin", firma_id: null }, firma: null }), "u")).toBe("superadmin"); }); it("aktive Firma", async () => { expect(await pruefeFirmenzugang(fakeClient({ profil: { role: "fahrer", firma_id: "f" }, firma: { id: "f" } }), "u")).toBe("ok"); }); it("deaktivierte Firma (RLS liefert keine Zeile)", async () => { expect(await pruefeFirmenzugang(fakeClient({ profil: { role: "fahrer", firma_id: "f" }, firma: null }), "u")).toBe("gesperrt"); }); it("Nutzer ohne Firma", async () => { expect(await pruefeFirmenzugang(fakeClient({ profil: { role: "readonly", firma_id: null }, firma: null }), "u")).toBe("gesperrt"); }); it("kein Profil", async () => { expect(await pruefeFirmenzugang(fakeClient({ profil: null, firma: null }), "u")).toBe("gesperrt"); }); }); ``` `web/lib/firma/logo.test.ts`: ```ts import { describe, expect, it } from "vitest"; import { LOGO_MAX_BYTES, LOGO_SICHERHEITS_HEADER, logoContentType, logoPfad, validateLogo } from "./logo"; describe("validateLogo", () => { it("akzeptiert PNG, JPG und SVG bis 1 MB", () => { expect(validateLogo({ type: "image/png", size: 1000 })).toEqual({ valid: true, endung: "png" }); expect(validateLogo({ type: "image/jpeg", size: LOGO_MAX_BYTES })).toEqual({ valid: true, endung: "jpg" }); expect(validateLogo({ type: "image/svg+xml", size: 10 })).toEqual({ valid: true, endung: "svg" }); }); it("lehnt leere, zu grosse und falsche Dateien ab", () => { expect(validateLogo({ type: "image/png", size: 0 })).toEqual({ valid: false, error: "Bitte eine Datei auswählen." }); expect(validateLogo({ type: "image/png", size: LOGO_MAX_BYTES + 1 })).toEqual({ valid: false, error: "Das Logo darf höchstens 1 MB groß sein.", }); expect(validateLogo({ type: "image/gif", size: 10 })).toEqual({ valid: false, error: "Bitte ein PNG-, JPG- oder SVG-Bild hochladen.", }); }); }); describe("logoPfad / logoContentType", () => { it("baut den Pfad im Firmenordner mit Zeitstempel", () => { expect(logoPfad("f1", "png", 123)).toBe("f1/logo-123.png"); }); it("leitet den Content-Type aus der Endung ab", () => { expect(logoContentType("f1/logo-1.svg")).toBe("image/svg+xml"); expect(logoContentType("f1/logo-1.jpg")).toBe("image/jpeg"); expect(logoContentType("f1/logo-1.png")).toBe("image/png"); }); }); describe("LOGO_SICHERHEITS_HEADER", () => { it("verhindert Script-Ausfuehrung in direkt geoeffneten SVGs", () => { expect(LOGO_SICHERHEITS_HEADER["Content-Security-Policy"]).toContain("sandbox"); expect(LOGO_SICHERHEITS_HEADER["Content-Security-Policy"]).toContain("default-src 'none'"); expect(LOGO_SICHERHEITS_HEADER["X-Content-Type-Options"]).toBe("nosniff"); }); }); ``` - [ ] **Step 2: Fehlschlag prüfen** Run (`web/`): `npx vitest run lib/firma` → FAIL (Module `queries`, `logo` fehlen). - [ ] **Step 3: Rollen und Profil** `web/lib/auth/roles.ts` — Typ und zwei Helfer ergänzen (Rest unverändert): ```ts export type Role = "admin" | "disponent" | "fahrer" | "readonly" | "superadmin"; export function istSuperadmin(role: Role): boolean { return role === "superadmin"; } export function kannFirmaVerwalten(role: Role): boolean { return role === "admin"; } ``` `GUELTIGE_ROLLEN` in `lib/nutzerverwaltung/validate-nutzer.ts` bleibt **ohne** `superadmin` — damit lehnt `validateRolle` ihn ab. `web/lib/auth/profile.ts`: `Profile` um `firma_id: string | null` erweitern und `.select("id, name, role, firma_id")`. - [ ] **Step 4: `lib/firma/queries.ts`, `eigene-firma.ts`, `logo.ts`** `web/lib/firma/queries.ts`: ```ts import type { SupabaseClient } from "@supabase/supabase-js"; export const WIDMANN_FIRMA_ID = "00000000-0000-0000-0000-00000000f001"; export type Firma = { id: string; name: string; logo_pfad: string | null; whatsapp_empfaenger: string | null; farbe_primaer: string | null; farbe_dunkel: string | null; }; const FIRMA_SELECT = "id, name, logo_pfad, whatsapp_empfaenger, farbe_primaer, farbe_dunkel"; // Mit dem Nutzer-Client liefert RLS nur die eigene, aktive Firma: null heisst // fremd, deaktiviert oder nicht vorhanden. export async function ladeFirma(client: SupabaseClient, firmaId: string): Promise { const { data } = await client.from("firmen").select(FIRMA_SELECT).eq("id", firmaId).maybeSingle(); return (data as Firma | null) ?? null; } export type FirmaBranding = { name: string; logo_pfad: string | null; farbe_primaer: string | null }; // Firma des Auftrags fuer PDF und Mail. Wirft bei DB-Fehlern (Dispatcher: Retry). export async function ladeFirmaZumAuftrag(client: SupabaseClient, auftragId: string): Promise { const { data, error } = await client .from("auftraege") .select("firma:firmen(name, logo_pfad, farbe_primaer)") .eq("id", auftragId) .maybeSingle(); if (error) { throw new Error(`Firma zum Auftrag laden fehlgeschlagen: ${error.message}`); } return ((data as { firma: FirmaBranding | null } | null)?.firma ?? null) as FirmaBranding | null; } export type Firmenzugang = "ok" | "superadmin" | "gesperrt"; export async function pruefeFirmenzugang(client: SupabaseClient, userId: string): Promise { const { data: profil } = await client.from("profiles").select("role, firma_id").eq("id", userId).maybeSingle(); const p = profil as { role: string; firma_id: string | null } | null; if (!p) return "gesperrt"; if (p.role === "superadmin") return "superadmin"; if (!p.firma_id) return "gesperrt"; const firma = await ladeFirma(client, p.firma_id); return firma ? "ok" : "gesperrt"; } ``` `web/lib/firma/eigene-firma.ts`: ```ts import { cache } from "react"; import { createClient } from "@/lib/supabase/server"; import { loadProfile } from "@/lib/auth/profile"; import { ladeFirma, type Firma } from "./queries"; export const FIRMA_GESPERRT = "Ihre Firma ist deaktiviert oder Ihr Zugang ist keiner Firma zugeordnet."; export type EigeneFirmaResult = | { status: "unauthenticated" } | { status: "missing-profile" } | { status: "superadmin" } | { status: "keine-firma" } | { status: "ok"; firma: Firma }; export const ladeEigeneFirma = cache(async (): Promise => { const profil = await loadProfile(); if (profil.status !== "ok") return { status: profil.status }; if (profil.profile.role === "superadmin") return { status: "superadmin" }; if (!profil.profile.firma_id) return { status: "keine-firma" }; const supabase = await createClient(); const firma = await ladeFirma(supabase, profil.profile.firma_id); return firma ? { status: "ok", firma } : { status: "keine-firma" }; }); ``` `web/lib/firma/logo.ts`: ```ts export const LOGO_MAX_BYTES = 1024 * 1024; export type LogoEndung = "png" | "jpg" | "svg"; const ENDUNG_NACH_TYP: Record = { "image/png": "png", "image/jpeg": "jpg", "image/svg+xml": "svg", }; const TYP_NACH_ENDUNG: Record = { png: "image/png", jpg: "image/jpeg", svg: "image/svg+xml", }; export function validateLogo(datei: { type: string; size: number }): | { valid: true; endung: LogoEndung } | { valid: false; error: string } { if (datei.size === 0) return { valid: false, error: "Bitte eine Datei auswählen." }; const endung = ENDUNG_NACH_TYP[datei.type]; if (!endung) return { valid: false, error: "Bitte ein PNG-, JPG- oder SVG-Bild hochladen." }; if (datei.size > LOGO_MAX_BYTES) return { valid: false, error: "Das Logo darf höchstens 1 MB groß sein." }; return { valid: true, endung }; } // Zeitstempel im Namen: ein neues Logo hat eine neue URL und kommt nicht aus dem Cache. export function logoPfad(firmaId: string, endung: LogoEndung, jetzt: number = Date.now()): string { return `${firmaId}/logo-${jetzt}.${endung}`; } export function logoContentType(pfad: string): string { const endung = pfad.split(".").pop() as LogoEndung; return TYP_NACH_ENDUNG[endung] ?? "application/octet-stream"; } // Ein hochgeladenes SVG kann Script enthalten. Als laeuft es nie, direkt // geoeffnet verhindert die Sandbox-CSP die Ausfuehrung im App-Origin. export const LOGO_SICHERHEITS_HEADER = { "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "X-Content-Type-Options": "nosniff", } as const; ``` - [ ] **Step 5: Tests grün** Run (`web/`): `npx vitest run lib/firma` → PASS. - [ ] **Step 6: Logo-Route und Abmelde-Route** `web/app/firma/logo/route.ts`: ```ts import { createClient } from "@/lib/supabase/server"; import { ladeEigeneFirma } from "@/lib/firma/eigene-firma"; import { LOGO_SICHERHEITS_HEADER, logoContentType } from "@/lib/firma/logo"; export const dynamic = "force-dynamic"; // Signierte Storage-URLs scheiden aus: im Docker-Stack enthielten sie die // interne Kong-Adresse. Die Datei wird mit dem Nutzer-Client geladen (RLS). export async function GET(): Promise { const ergebnis = await ladeEigeneFirma(); if (ergebnis.status !== "ok" || !ergebnis.firma.logo_pfad) { return new Response(null, { status: 404 }); } const pfad = ergebnis.firma.logo_pfad; const supabase = await createClient(); const { data, error } = await supabase.storage.from("firmen-logos").download(pfad); if (error || !data) { return new Response(null, { status: 404 }); } return new Response(await data.arrayBuffer(), { headers: { "Content-Type": logoContentType(pfad), "Cache-Control": "private, max-age=86400", ...LOGO_SICHERHEITS_HEADER, }, }); } ``` `web/app/abmelden/route.ts`: ```ts import { NextResponse } from "next/server"; import { createClient } from "@/lib/supabase/server"; import { FIRMA_GESPERRT } from "@/lib/firma/eigene-firma"; // Server Components koennen keine Cookies loeschen; das Layout leitet bei // gesperrter Firma hierher um. export async function GET(request: Request): Promise { const supabase = await createClient(); await supabase.auth.signOut(); const ziel = new URL("/login", request.url); if (new URL(request.url).searchParams.get("grund") === "firma") { ziel.searchParams.set("error", FIRMA_GESPERRT); } return NextResponse.redirect(ziel); } ``` - [ ] **Step 7: Login prüft den Firmenzugang** In `web/app/login/actions.ts` die Imports ergänzen: ```ts import { pruefeFirmenzugang } from "@/lib/firma/queries"; import { FIRMA_GESPERRT } from "@/lib/firma/eigene-firma"; ``` und den Block nach `signInWithPassword` ersetzen: ```ts if (error) { redirect(`/login?error=${encodeURIComponent(LOGIN_FEHLER)}`); } const zugang = await pruefeFirmenzugang(supabase, data.user.id); if (zugang === "gesperrt") { await supabase.auth.signOut(); redirect(`/login?error=${encodeURIComponent(FIRMA_GESPERRT)}`); } if (hatPasswortAenderPflicht(data.user)) { redirect(PASSWORT_AENDERN_PFAD); } redirect(zugang === "superadmin" ? "/plattform" : "/dashboard"); ``` - [ ] **Step 8: Logo-Komponente, Layout, Navigation** `web/components/FirmenLogo.tsx`: ```tsx import Image from "next/image"; import { WIDMANN_FIRMA_ID, type Firma } from "@/lib/firma/queries"; export function FirmenLogo({ firma }: { firma: Firma | null }) { if (!firma) { return Plattform-Verwaltung; } if (firma.logo_pfad) { return ( // eslint-disable-next-line @next/next/no-img-element -- Logo kommt aus einer eigenen Route mit Session-Cookie {firma.name} ); } if (firma.id === WIDMANN_FIRMA_ID) { return Widmann; } return {firma.name}; } ``` `web/app/layout.tsx` — Änderungen: - Imports: `redirect` aus `next/navigation`, `ladeEigeneFirma` aus `@/lib/firma/eigene-firma`, `themeVariablen` aus `@/lib/firma/farben`, `FirmenLogo` aus `@/components/FirmenLogo`; `Image`-Import entfernen. - Nach `const result = await loadProfile();`: ```tsx const firmaErgebnis = await ladeEigeneFirma(); if (result.status === "ok" && firmaErgebnis.status === "keine-firma") { redirect("/abmelden?grund=firma"); } const firma = firmaErgebnis.status === "ok" ? firmaErgebnis.firma : null; const themeStyle = firma ? (themeVariablen(firma) as React.CSSProperties) : undefined; ``` - Im zweiten `return`: ``. - Das `` im Header durch `` ersetzen; den Link-`href` auf `result.profile.role === "superadmin" ? "/plattform" : "/dashboard"` setzen. `web/components/NavLinks.tsx`: - Import `istSuperadmin`, `kannFirmaVerwalten` ergänzen. - Am Anfang der Komponente (nach `layoutClass`): ```tsx const linkClass = "flex min-h-11 items-center text-asphalt-grey hover:text-performance-blue focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-performance-blue"; if (istSuperadmin(role)) { return ( ); } ``` - Nach dem Nutzerverwaltungs-Link: ```tsx {kannFirmaVerwalten(role) && ( Firma )} ``` - [ ] **Step 9: Prüfen** Run (`web/`): `npm test && npx tsc --noEmit && npm run lint` → PASS. Test-Fixtures, die ein `Profile` bauen, meldet `tsc`; dort `firma_id: "00000000-0000-0000-0000-00000000f001"` ergänzen. - [ ] **Step 10: Commit** ```bash git add web/lib/auth web/lib/firma web/app/firma/logo web/app/abmelden web/app/login/actions.ts web/app/layout.tsx web/components/NavLinks.tsx web/components/FirmenLogo.tsx git commit -m "feat: Firmenzugang beim Login, Branding im Layout, Logo-Route, Superadmin-Navigation" ``` --- ### Task 5: Nutzerverwaltung mandantensicher **Files:** - Create: `web/lib/nutzerverwaltung/nutzer-anlegen.ts`, `web/lib/nutzerverwaltung/nutzer-anlegen.test.ts` - Create: `web/lib/nutzerverwaltung/ziel-pruefen.ts`, `web/lib/nutzerverwaltung/ziel-pruefen.test.ts` - Modify: `web/app/nutzerverwaltung/actions.ts` **Interfaces:** - Consumes: `Profile.firma_id` (Task 4), Trigger-Regel „null → Wert ohne Session“ (Task 1). - Produces: - `legeNutzerInFirmaAn(admin: SupabaseClient, e: NutzerAnlegenEingabe): Promise` - `NutzerAnlegenEingabe = { firmaId: string; name: string; email: string; passwort: string; rolle: "admin" | "disponent" | "fahrer" | "readonly"; username?: string }` - `NutzerAnlegenErgebnis = { ok: true; id: string; usernameHinweis: string | null } | { ok: false; fehler: string }` - `pruefeZielNutzer(client: SupabaseClient, nutzerId: string): Promise<{ id: string; role: Role } | null>` - [ ] **Step 1: Failing Tests** `web/lib/nutzerverwaltung/ziel-pruefen.test.ts`: ```ts import { describe, expect, it } from "vitest"; import type { SupabaseClient } from "@supabase/supabase-js"; import { pruefeZielNutzer } from "./ziel-pruefen"; function fakeClient(zeile: unknown): SupabaseClient { const kette = { select: () => kette, eq: () => kette, maybeSingle: async () => ({ data: zeile, error: null }) }; return { from: () => kette } as unknown as SupabaseClient; } describe("pruefeZielNutzer", () => { it("liefert das Profil, wenn RLS es zeigt", async () => { expect(await pruefeZielNutzer(fakeClient({ id: "u1", role: "fahrer" }), "u1")).toEqual({ id: "u1", role: "fahrer" }); }); it("liefert null fuer fremde oder unbekannte Nutzer", async () => { expect(await pruefeZielNutzer(fakeClient(null), "u1")).toBeNull(); }); }); ``` `web/lib/nutzerverwaltung/nutzer-anlegen.test.ts`: ```ts import { describe, expect, it, vi } from "vitest"; import type { SupabaseClient } from "@supabase/supabase-js"; import { legeNutzerInFirmaAn } from "./nutzer-anlegen"; type Fehler = { code?: string; message: string } | null; function fakeAdmin(opts: { createFehler?: string; zuordnungFehler?: Fehler; usernameFehler?: Fehler }) { const updates: Record[] = []; const deleteUser = vi.fn(async () => ({ error: null })); const client = { auth: { admin: { createUser: vi.fn(async () => opts.createFehler ? { data: { user: null }, error: { message: opts.createFehler } } : { data: { user: { id: "neu" } }, error: null } ), deleteUser, }, }, from: () => ({ update: (felder: Record) => ({ eq: async () => { updates.push(felder); const fehler = "username" in felder ? opts.usernameFehler ?? null : opts.zuordnungFehler ?? null; return { error: fehler }; }, }), }), } as unknown as SupabaseClient; return { client, updates, deleteUser }; } const EINGABE = { firmaId: "f2", name: "Neu", email: "neu@test.local", passwort: "Passwort123!", rolle: "fahrer" as const, username: "neu.fahrer", }; describe("legeNutzerInFirmaAn", () => { it("legt an, ordnet Firma und Rolle zu, setzt Benutzernamen", async () => { const { client, updates } = fakeAdmin({}); expect(await legeNutzerInFirmaAn(client, EINGABE)).toEqual({ ok: true, id: "neu", usernameHinweis: null }); expect(updates).toEqual([{ firma_id: "f2", role: "fahrer" }, { username: "neu.fahrer" }]); }); it("meldet den Fehler von createUser", async () => { const { client } = fakeAdmin({ createFehler: "exists" }); expect(await legeNutzerInFirmaAn(client, EINGABE)).toEqual({ ok: false, fehler: "Nutzer anlegen fehlgeschlagen: exists" }); }); it("loescht den Auth-Nutzer, wenn die Firmenzuordnung scheitert", async () => { const { client, deleteUser } = fakeAdmin({ zuordnungFehler: { message: "kaputt" } }); expect(await legeNutzerInFirmaAn(client, EINGABE)).toEqual({ ok: false, fehler: "Nutzer konnte keiner Firma zugeordnet werden: kaputt", }); expect(deleteUser).toHaveBeenCalledWith("neu"); }); it("gibt einen Hinweis bei vergebenem Benutzernamen", async () => { const { client } = fakeAdmin({ usernameFehler: { code: "23505", message: "dup" } }); const ergebnis = await legeNutzerInFirmaAn(client, EINGABE); expect(ergebnis.ok && ergebnis.usernameHinweis).toContain("bereits vergeben"); }); it("setzt keinen Benutzernamen, wenn keiner angegeben ist", async () => { const { client, updates } = fakeAdmin({}); await legeNutzerInFirmaAn(client, { ...EINGABE, username: undefined }); expect(updates).toEqual([{ firma_id: "f2", role: "fahrer" }]); }); }); ``` - [ ] **Step 2: Fehlschlag prüfen** Run (`web/`): `npx vitest run lib/nutzerverwaltung` → FAIL (Module fehlen). - [ ] **Step 3: Implementieren** `web/lib/nutzerverwaltung/ziel-pruefen.ts`: ```ts import type { SupabaseClient } from "@supabase/supabase-js"; import type { Role } from "@/lib/auth/roles"; // Vor jeder Service-Client-Aktion auf einen anderen Nutzer: Sieht der // RLS-Client des Aufrufers das Profil nicht (fremde Firma, unbekannt), ist die // Aktion nicht erlaubt. So entscheidet auch hier RLS ueber die Firmengrenze. export async function pruefeZielNutzer( client: SupabaseClient, nutzerId: string ): Promise<{ id: string; role: Role } | null> { const { data } = await client.from("profiles").select("id, role").eq("id", nutzerId).maybeSingle(); return (data as { id: string; role: Role } | null) ?? null; } ``` `web/lib/nutzerverwaltung/nutzer-anlegen.ts`: ```ts import type { SupabaseClient } from "@supabase/supabase-js"; export type NutzerAnlegenEingabe = { firmaId: string; name: string; email: string; passwort: string; rolle: "admin" | "disponent" | "fahrer" | "readonly"; username?: string; }; export type NutzerAnlegenErgebnis = | { ok: true; id: string; usernameHinweis: string | null } | { ok: false; fehler: string }; // GoTrue setzt app_metadata erst nach dem INSERT in auth.users, der Trigger // handle_new_user sieht es nicht (geprueft 2026-10-12). Die Firma wird deshalb // hier per Service-Client zugeordnet; scheitert das, wird der Nutzer geloescht, // damit kein firmenloser Login uebrig bleibt. export async function legeNutzerInFirmaAn( admin: SupabaseClient, e: NutzerAnlegenEingabe ): Promise { const { data, error } = await admin.auth.admin.createUser({ email: e.email, password: e.passwort, email_confirm: true, user_metadata: { name: e.name }, app_metadata: { must_change_password: true }, }); if (error || !data.user) { return { ok: false, fehler: `Nutzer anlegen fehlgeschlagen: ${error?.message ?? "Unbekannter Fehler"}` }; } const id = data.user.id; const { error: zuordnungFehler } = await admin .from("profiles") .update({ firma_id: e.firmaId, role: e.rolle }) .eq("id", id); if (zuordnungFehler) { await admin.auth.admin.deleteUser(id); return { ok: false, fehler: `Nutzer konnte keiner Firma zugeordnet werden: ${zuordnungFehler.message}` }; } if (!e.username) { return { ok: true, id, usernameHinweis: null }; } const { error: usernameFehler } = await admin.from("profiles").update({ username: e.username }).eq("id", id); if (!usernameFehler) { return { ok: true, id, usernameHinweis: null }; } return { ok: true, id, usernameHinweis: usernameFehler.code === "23505" ? "Nutzer wurde angelegt, der gewaehlte Benutzername ist aber bereits vergeben. Der neue Nutzer erscheint mit einem automatisch vergebenen Platzhalter-Benutzernamen in der Liste unten, dort kann er angepasst werden." : `Nutzer wurde angelegt, der Benutzername konnte aber nicht gesetzt werden: ${usernameFehler.message}`, }; } ``` - [ ] **Step 4: Actions umstellen** In `web/app/nutzerverwaltung/actions.ts`: - Imports ergänzen: `import { legeNutzerInFirmaAn } from "@/lib/nutzerverwaltung/nutzer-anlegen";` und `import { pruefeZielNutzer } from "@/lib/nutzerverwaltung/ziel-pruefen";`. Konstante `const NICHT_GEFUNDEN = "Nutzer nicht gefunden.";`. - `erstelleNutzer`: alles ab `const adminClient = createAdminClient();` bis vor `redirect("/nutzerverwaltung");` ersetzen durch: ```ts const firmaId = profileResult.profile.firma_id; if (!firmaId) { redirect(`/nutzerverwaltung?error=${encodeURIComponent("Ihr Zugang ist keiner Firma zugeordnet.")}`); } const ergebnis = await legeNutzerInFirmaAn(createAdminClient(), { firmaId, name: validation.name, email: validation.email, passwort: validation.passwort, rolle: validation.rolle as "admin" | "disponent" | "fahrer" | "readonly", username: validation.username, }); if (!ergebnis.ok) { redirect(`/nutzerverwaltung?error=${encodeURIComponent(ergebnis.fehler)}`); } if (ergebnis.usernameHinweis) { redirect(`/nutzerverwaltung?error=${encodeURIComponent(ergebnis.usernameHinweis)}`); } ``` - `aktualisiereNutzer`: die Zeilen ```ts const { data: aktuellesProfil } = await supabase.from("profiles").select("role").eq("id", nutzerId).single(); if (!aktuellesProfil) { return { success: false, error: "Nutzer nicht gefunden." }; } ``` ersetzen durch ```ts const aktuellesProfil = await pruefeZielNutzer(supabase, nutzerId); if (!aktuellesProfil) { return { success: false, error: NICHT_GEFUNDEN }; } ``` - `sperreNutzer`, `entsperreNutzer`, `setzePasswort`: jeweils direkt **vor** `const adminClient = createAdminClient();` einfügen: ```ts const supabase = await createClient(); if (!(await pruefeZielNutzer(supabase, nutzerId))) { return { success: false, error: NICHT_GEFUNDEN }; } ``` - [ ] **Step 5: Prüfen** Run (`web/`): `npm test && npx tsc --noEmit && npm run lint` → PASS. - [ ] **Step 6: Commit** ```bash git add web/lib/nutzerverwaltung web/app/nutzerverwaltung/actions.ts git commit -m "feat: Nutzerverwaltung ordnet Firma zu und prueft Zielnutzer per RLS" ``` --- ### Task 6: Firmen-Einstellungen `/firma` (Name, WhatsApp, Farben, Logo) **Files:** - Create: `web/lib/firma/einstellungen.ts`, `web/lib/firma/einstellungen.test.ts` - Create: `web/lib/firma/admin-kontext.ts` - Create: `web/app/firma/actions.ts`, `web/app/firma/page.tsx` - Create: `web/components/firma/FirmaEinstellungenForm.tsx`, `web/components/firma/LogoForm.tsx` - Modify: `web/next.config.ts` (Server-Action-Body-Limit) **Interfaces:** - Consumes: `normalisiereFarbe`, `kontrastZuWeiss`, `MIN_KONTRAST`, `STANDARD_FARBE_*` (Task 3); `ladeFirma`, `Firma`, `validateLogo`, `logoPfad` (Task 4); `normalisiereTelefon` (`lib/nutzerverwaltung/details.ts`). - Produces: - `validateFirmaEinstellungen(input): { valid: true; werte: FirmaEinstellungen } | { valid: false; error: string }` mit `FirmaEinstellungen = { name: string; whatsapp_empfaenger: string | null; farbe_primaer: string | null; farbe_dunkel: string | null }` - `ladeAdminKontext(): Promise<{ ok: true; firma: Firma; profilId: string } | { ok: false; error: string }>` - `app/firma/page.tsx`, die Task 7 um den SMTP-Block erweitert. - [ ] **Step 1: Failing Test** `web/lib/firma/einstellungen.test.ts`: ```ts import { describe, expect, it } from "vitest"; import { validateFirmaEinstellungen } from "./einstellungen"; const BASIS = { name: "Firma B", whatsapp: "", standardFarben: false, farbePrimaer: "#0071ed", farbeDunkel: "#0a185c" }; describe("validateFirmaEinstellungen", () => { it("uebernimmt gueltige Werte", () => { expect(validateFirmaEinstellungen({ ...BASIS, whatsapp: "0151 2345678" })).toEqual({ valid: true, werte: { name: "Firma B", whatsapp_empfaenger: "+491512345678", farbe_primaer: "#0071ed", farbe_dunkel: "#0a185c" }, }); }); it("Standardfarben setzen beide Farben auf null", () => { const e = validateFirmaEinstellungen({ ...BASIS, standardFarben: true, farbePrimaer: "#ffff00" }); expect(e.valid && e.werte.farbe_primaer).toBeNull(); expect(e.valid && e.werte.farbe_dunkel).toBeNull(); }); it("leerer WhatsApp-Empfaenger wird null", () => { const e = validateFirmaEinstellungen(BASIS); expect(e.valid && e.werte.whatsapp_empfaenger).toBeNull(); }); it("lehnt leeren Namen ab", () => { expect(validateFirmaEinstellungen({ ...BASIS, name: " " })).toEqual({ valid: false, error: "Bitte einen Firmennamen eingeben." }); }); it("lehnt ungueltige WhatsApp-Nummer ab", () => { expect(validateFirmaEinstellungen({ ...BASIS, whatsapp: "abc" })).toEqual({ valid: false, error: "Bitte eine gültige WhatsApp-Nummer eingeben (z. B. +49 151 2345678).", }); }); it("lehnt ungueltiges Farbformat ab", () => { expect(validateFirmaEinstellungen({ ...BASIS, farbePrimaer: "blau" })).toEqual({ valid: false, error: "Bitte für die Hauptfarbe eine Farbe im Format #rrggbb wählen.", }); }); it("lehnt zu wenig Kontrast mit dem erreichten Wert ab", () => { const e = validateFirmaEinstellungen({ ...BASIS, farbeDunkel: "#ffff00" }); expect(e.valid).toBe(false); expect(!e.valid && e.error).toMatch(/^Die dunkle Farbe hat zu wenig Kontrast zu Weiß \(1,\d\d:1, mindestens 4,5:1 nötig\)\.$/); }); }); ``` - [ ] **Step 2: Fehlschlag prüfen** Run (`web/`): `npx vitest run lib/firma/einstellungen.test.ts` → FAIL. - [ ] **Step 3: Validierung und Admin-Kontext** `web/lib/firma/einstellungen.ts`: ```ts import { normalisiereTelefon } from "@/lib/nutzerverwaltung/details"; import { MIN_KONTRAST, kontrastZuWeiss, normalisiereFarbe } from "./farben"; export type FirmaEinstellungen = { name: string; whatsapp_empfaenger: string | null; farbe_primaer: string | null; farbe_dunkel: string | null; }; type Eingabe = { name: unknown; whatsapp: unknown; standardFarben: boolean; farbePrimaer: unknown; farbeDunkel: unknown; }; function text(wert: unknown): string { return typeof wert === "string" ? wert.trim() : ""; } function pruefeFarbe(roh: unknown, bezeichnung: string): { ok: true; farbe: string } | { ok: false; error: string } { const farbe = normalisiereFarbe(text(roh)); if (!farbe) { return { ok: false, error: `Bitte für die ${bezeichnung} eine Farbe im Format #rrggbb wählen.` }; } const kontrast = kontrastZuWeiss(farbe); if (kontrast < MIN_KONTRAST) { const wert = kontrast.toFixed(2).replace(".", ","); return { ok: false, error: `Die ${bezeichnung} hat zu wenig Kontrast zu Weiß (${wert}:1, mindestens 4,5:1 nötig).` }; } return { ok: true, farbe }; } export function validateFirmaEinstellungen( input: Eingabe ): { valid: true; werte: FirmaEinstellungen } | { valid: false; error: string } { const name = text(input.name); if (!name) return { valid: false, error: "Bitte einen Firmennamen eingeben." }; if (name.length > 100) return { valid: false, error: "Der Firmenname darf höchstens 100 Zeichen lang sein." }; const whatsappRoh = text(input.whatsapp); let whatsapp: string | null = null; if (whatsappRoh) { whatsapp = normalisiereTelefon(whatsappRoh); if (!whatsapp) { return { valid: false, error: "Bitte eine gültige WhatsApp-Nummer eingeben (z. B. +49 151 2345678)." }; } } if (input.standardFarben) { return { valid: true, werte: { name, whatsapp_empfaenger: whatsapp, farbe_primaer: null, farbe_dunkel: null } }; } const primaer = pruefeFarbe(input.farbePrimaer, "Hauptfarbe"); if (!primaer.ok) return { valid: false, error: primaer.error }; const dunkel = pruefeFarbe(input.farbeDunkel, "dunkle Farbe"); if (!dunkel.ok) return { valid: false, error: dunkel.error }; return { valid: true, werte: { name, whatsapp_empfaenger: whatsapp, farbe_primaer: primaer.farbe, farbe_dunkel: dunkel.farbe }, }; } ``` `web/lib/firma/admin-kontext.ts`: ```ts import { createClient } from "@/lib/supabase/server"; import { loadProfile } from "@/lib/auth/profile"; import { ladeFirma, type Firma } from "./queries"; export type AdminKontext = { ok: true; firma: Firma; profilId: string } | { ok: false; error: string }; // Rolle aus dem eigenen Profil, Firma ueber den RLS-Client (aktiv + eigene). // Alle Firmen-Actions nehmen die firma_id ausschliesslich von hier, nie aus dem Formular. export async function ladeAdminKontext(): Promise { const profil = await loadProfile(); if (profil.status !== "ok" || profil.profile.role !== "admin" || !profil.profile.firma_id) { return { ok: false, error: "Nur Admins einer Firma dürfen das." }; } const supabase = await createClient(); const firma = await ladeFirma(supabase, profil.profile.firma_id); if (!firma) { return { ok: false, error: "Firma nicht gefunden oder deaktiviert." }; } return { ok: true, firma, profilId: profil.profile.id }; } ``` - [ ] **Step 4: Test grün** Run (`web/`): `npx vitest run lib/firma` → PASS. - [ ] **Step 5: Actions** `web/app/firma/actions.ts`: ```ts "use server"; import { revalidatePath } from "next/cache"; import { createClient } from "@/lib/supabase/server"; import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; import { validateFirmaEinstellungen } from "@/lib/firma/einstellungen"; import { logoPfad, validateLogo } from "@/lib/firma/logo"; export type ActionResult = { success: true } | { success: false; error: string }; export async function speichereFirmaEinstellungen(formData: FormData): Promise { const kontext = await ladeAdminKontext(); if (!kontext.ok) return { success: false, error: kontext.error }; const validation = validateFirmaEinstellungen({ name: formData.get("name"), whatsapp: formData.get("whatsapp_empfaenger"), standardFarben: formData.get("standard_farben") === "on", farbePrimaer: formData.get("farbe_primaer"), farbeDunkel: formData.get("farbe_dunkel"), }); if (!validation.valid) return { success: false, error: validation.error }; const supabase = await createClient(); const { data, error } = await supabase.from("firmen").update(validation.werte).eq("id", kontext.firma.id).select("id"); if (error || !data || data.length === 0) { return { success: false, error: "Speichern fehlgeschlagen." }; } revalidatePath("/", "layout"); return { success: true }; } export async function ladeLogoHoch(formData: FormData): Promise { const kontext = await ladeAdminKontext(); if (!kontext.ok) return { success: false, error: kontext.error }; const datei = formData.get("logo"); if (!(datei instanceof File)) return { success: false, error: "Bitte eine Datei auswählen." }; const validation = validateLogo({ type: datei.type, size: datei.size }); if (!validation.valid) return { success: false, error: validation.error }; const supabase = await createClient(); const pfad = logoPfad(kontext.firma.id, validation.endung); const { error: uploadFehler } = await supabase.storage .from("firmen-logos") .upload(pfad, datei, { contentType: datei.type }); if (uploadFehler) return { success: false, error: "Logo-Upload fehlgeschlagen." }; const { error } = await supabase.from("firmen").update({ logo_pfad: pfad }).eq("id", kontext.firma.id); if (error) { await supabase.storage.from("firmen-logos").remove([pfad]); return { success: false, error: "Logo konnte nicht gespeichert werden." }; } if (kontext.firma.logo_pfad) { await supabase.storage.from("firmen-logos").remove([kontext.firma.logo_pfad]); } revalidatePath("/", "layout"); return { success: true }; } export async function entferneLogo(): Promise { const kontext = await ladeAdminKontext(); if (!kontext.ok) return { success: false, error: kontext.error }; if (!kontext.firma.logo_pfad) return { success: true }; const supabase = await createClient(); const { error } = await supabase.from("firmen").update({ logo_pfad: null }).eq("id", kontext.firma.id); if (error) return { success: false, error: "Logo konnte nicht entfernt werden." }; await supabase.storage.from("firmen-logos").remove([kontext.firma.logo_pfad]); revalidatePath("/", "layout"); return { success: true }; } ``` - [ ] **Step 6: Body-Limit für den Logo-Upload** `web/next.config.ts`: ```ts const nextConfig: NextConfig = { output: "standalone", serverExternalPackages: ["@react-pdf/renderer", "sharp"], // Logo-Upload: Datei bis 1 MB plus Multipart-Overhead (Default-Limit 1 MB). experimental: { serverActions: { bodySizeLimit: "2mb", }, }, }; ``` Mit `npx tsc --noEmit` prüfen, dass der Schlüssel in Next 16 so heißt; meldet tsc einen unbekannten Schlüssel, in `node_modules/next/dist/server/config-shared.d.ts` nach `bodySizeLimit` suchen und die dortige Position verwenden. - [ ] **Step 7: Formulare und Seite** `web/components/firma/FirmaEinstellungenForm.tsx`: ```tsx "use client"; import { useState, useTransition } from "react"; import { speichereFirmaEinstellungen } from "@/app/firma/actions"; import { Alert } from "@/components/ui/Alert"; import { Button } from "@/components/ui/Button"; import { FIELD_CLASSES, FormField } from "@/components/ui/FormField"; import { STANDARD_FARBE_DUNKEL, STANDARD_FARBE_PRIMAER } from "@/lib/firma/farben"; import type { Firma } from "@/lib/firma/queries"; export function FirmaEinstellungenForm({ firma }: { firma: Firma }) { const [fehler, setFehler] = useState(null); const [gespeichert, setGespeichert] = useState(false); const [standard, setStandard] = useState(!firma.farbe_primaer && !firma.farbe_dunkel); const [isPending, startTransition] = useTransition(); function handleSubmit(event: React.FormEvent) { event.preventDefault(); const formData = new FormData(event.currentTarget); startTransition(async () => { const ergebnis = await speichereFirmaEinstellungen(formData); setGespeichert(ergebnis.success); setFehler(ergebnis.success ? null : ergebnis.error); }); } return (
{fehler && (
{fehler}
)} {!standard && (
)}

Beide Farben brauchen genug Kontrast zu weißer Schrift (mindestens 4,5:1).

{gespeichert && (

Gespeichert.

)}
); } ``` `web/components/firma/LogoForm.tsx`: ```tsx "use client"; import { useState, useTransition } from "react"; import { entferneLogo, ladeLogoHoch } from "@/app/firma/actions"; import { Alert } from "@/components/ui/Alert"; import { Button } from "@/components/ui/Button"; import { FIELD_CLASSES, FormField } from "@/components/ui/FormField"; export function LogoForm({ hatLogo }: { hatLogo: boolean }) { const [fehler, setFehler] = useState(null); const [isPending, startTransition] = useTransition(); function handleSubmit(event: React.FormEvent) { event.preventDefault(); const form = event.currentTarget; const formData = new FormData(form); startTransition(async () => { const ergebnis = await ladeLogoHoch(formData); setFehler(ergebnis.success ? null : ergebnis.error); if (ergebnis.success) form.reset(); }); } function handleEntfernen() { startTransition(async () => { const ergebnis = await entferneLogo(); setFehler(ergebnis.success ? null : ergebnis.error); }); } return (
{fehler && (
{fehler}
)} {hatLogo && ( // eslint-disable-next-line @next/next/no-img-element -- eigene Logo-Route mit Session-Cookie Aktuelles Logo )}
{hatLogo && ( )}
); } ``` `web/app/firma/page.tsx`: ```tsx import { redirect } from "next/navigation"; import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; import { FirmaEinstellungenForm } from "@/components/firma/FirmaEinstellungenForm"; import { LogoForm } from "@/components/firma/LogoForm"; import { Card } from "@/components/ui/Card"; export default async function FirmaPage() { const kontext = await ladeAdminKontext(); if (!kontext.ok) { redirect("/dashboard"); } return (

Firma

Allgemein

Logo

); } ``` - [ ] **Step 8: Prüfen** Run (`web/`): `npm test && npx tsc --noEmit && npm run lint` → PASS. - [ ] **Step 9: Commit** ```bash git add web/lib/firma web/app/firma web/components/firma web/next.config.ts git commit -m "feat: Firmen-Einstellungen mit Kontrastpruefung und Logo-Upload" ``` --- ### Task 7: SMTP pro Firma auf `/firma` **Files:** - Create: `web/lib/firma/smtp.ts`, `web/lib/firma/smtp.test.ts` - Create: `web/app/firma/smtp-actions.ts` - Create: `web/components/firma/SmtpForm.tsx` - Modify: `web/app/firma/page.tsx` **Interfaces:** - Consumes: `verschluessele`, `entschluessele` (Task 3); `ladeAdminKontext` (Task 6); `EmailConfig`, `getEmailConfig` (`lib/notifications/email-config.ts`); `sendeProtokollMail`, `ProtokollMail` (`lib/notifications/email.ts`). - Produces: - `type FirmenSmtpZeile = { firma_id: string; host: string; port: number; secure: boolean; benutzer: string | null; passwort_verschluesselt: string | null; absender_adresse: string; absender_name: string | null }` - `type SmtpAnzeige = { host: string; port: number; secure: boolean; benutzer: string | null; absender_adresse: string; absender_name: string | null; passwortGesetzt: boolean }` - `validateSmtpEingabe(input, passwortGespeichert: boolean)` - `ladeFirmenSmtp(admin, firmaId): Promise` - `firmenSmtpZuConfig(zeile): EmailConfig` - `ermittleEmailConfig(admin, firmaId, fallback = getEmailConfig): Promise` — von Task 9 im Dispatcher genutzt. - [ ] **Step 1: Failing Tests** `web/lib/firma/smtp.test.ts`: ```ts import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { SupabaseClient } from "@supabase/supabase-js"; import { ermittleEmailConfig, firmenSmtpZuConfig, validateSmtpEingabe, type FirmenSmtpZeile } from "./smtp"; import { verschluessele } from "./smtp-crypto"; const KEY = Buffer.alloc(32, 3).toString("base64"); const EINGABE = { host: "smtp.firma.de", port: "587", secure: false, benutzer: "mailer", passwort: "geheim", absenderAdresse: "noreply@firma.de", absenderName: "Firma B", }; describe("validateSmtpEingabe", () => { it("uebernimmt gueltige Werte", () => { expect(validateSmtpEingabe(EINGABE, false)).toEqual({ valid: true, werte: { host: "smtp.firma.de", port: 587, secure: false, benutzer: "mailer", neuesPasswort: "geheim", absender_adresse: "noreply@firma.de", absender_name: "Firma B", }, }); }); it("Host ist Pflicht", () => { expect(validateSmtpEingabe({ ...EINGABE, host: " " }, false)).toEqual({ valid: false, error: "Bitte den SMTP-Server angeben." }); }); it("Port muss 1 bis 65535 sein", () => { expect(validateSmtpEingabe({ ...EINGABE, port: "70000" }, false)).toEqual({ valid: false, error: "Bitte einen gültigen Port (1–65535) angeben.", }); }); it("Absenderadresse muss eine E-Mail sein", () => { expect(validateSmtpEingabe({ ...EINGABE, absenderAdresse: "kein mail" }, false)).toEqual({ valid: false, error: "Bitte eine gültige Absenderadresse angeben.", }); }); it("Benutzer ohne neues und ohne gespeichertes Passwort scheitert", () => { expect(validateSmtpEingabe({ ...EINGABE, passwort: "" }, false)).toEqual({ valid: false, error: "Bitte ein Passwort eingeben." }); }); it("leeres Passwort mit gespeichertem Passwort bleibt unveraendert (null)", () => { const e = validateSmtpEingabe({ ...EINGABE, passwort: "" }, true); expect(e.valid && e.werte.neuesPasswort).toBeNull(); }); it("ohne Benutzer wird das Passwort ignoriert", () => { const e = validateSmtpEingabe({ ...EINGABE, benutzer: "", passwort: "x" }, false); expect(e.valid && e.werte.benutzer).toBeNull(); expect(e.valid && e.werte.neuesPasswort).toBeNull(); }); }); describe("firmenSmtpZuConfig / ermittleEmailConfig", () => { const alt = process.env.SMTP_VERSCHLUESSELUNG_KEY; beforeEach(() => { process.env.SMTP_VERSCHLUESSELUNG_KEY = KEY; }); afterEach(() => { process.env.SMTP_VERSCHLUESSELUNG_KEY = alt; }); function zeile(): FirmenSmtpZeile { return { firma_id: "f2", host: "smtp.firma.de", port: 465, secure: true, benutzer: "mailer", passwort_verschluesselt: verschluessele("geheim"), absender_adresse: "noreply@firma.de", absender_name: 'Firma "B"', }; } function fakeAdmin(z: FirmenSmtpZeile | null): SupabaseClient { const kette = { select: () => kette, eq: () => kette, maybeSingle: async () => ({ data: z, error: null }) }; return { from: () => kette } as unknown as SupabaseClient; } it("baut die Config mit entschluesseltem Passwort und bereinigtem Namen", () => { expect(firmenSmtpZuConfig(zeile())).toEqual({ host: "smtp.firma.de", port: 465, secure: true, from: '"Firma B" ', auth: { user: "mailer", pass: "geheim" }, }); }); it("nimmt den Firmen-SMTP vor dem Fallback", async () => { const fallback = () => ({ host: "global", port: 25, secure: false, from: "g@x.de", auth: null }); expect((await ermittleEmailConfig(fakeAdmin(zeile()), "f2", fallback))?.host).toBe("smtp.firma.de"); }); it("faellt ohne Firmen-SMTP auf den globalen zurueck", async () => { const fallback = () => ({ host: "global", port: 25, secure: false, from: "g@x.de", auth: null }); expect((await ermittleEmailConfig(fakeAdmin(null), "f2", fallback))?.host).toBe("global"); }); it("liefert null ohne Firmen- und globalen SMTP", async () => { expect(await ermittleEmailConfig(fakeAdmin(null), "f2", () => null)).toBeNull(); }); }); ``` - [ ] **Step 2: Fehlschlag prüfen** Run (`web/`): `npx vitest run lib/firma/smtp.test.ts` → FAIL. - [ ] **Step 3: Implementieren** `web/lib/firma/smtp.ts`: ```ts import type { SupabaseClient } from "@supabase/supabase-js"; import { getEmailConfig, type EmailConfig } from "@/lib/notifications/email-config"; import { entschluessele } from "./smtp-crypto"; export type FirmenSmtpZeile = { firma_id: string; host: string; port: number; secure: boolean; benutzer: string | null; passwort_verschluesselt: string | null; absender_adresse: string; absender_name: string | null; }; export type SmtpAnzeige = Omit & { passwortGesetzt: boolean }; export type SmtpWerte = { host: string; port: number; secure: boolean; benutzer: string | null; neuesPasswort: string | null; absender_adresse: string; absender_name: string | null; }; type Eingabe = { host: unknown; port: unknown; secure: boolean; benutzer: unknown; passwort: unknown; absenderAdresse: unknown; absenderName: unknown; }; function text(wert: unknown): string { return typeof wert === "string" ? wert.trim() : ""; } export function validateSmtpEingabe( input: Eingabe, passwortGespeichert: boolean ): { valid: true; werte: SmtpWerte } | { valid: false; error: string } { const host = text(input.host); if (!host) return { valid: false, error: "Bitte den SMTP-Server angeben." }; const port = Number(text(input.port)); if (!Number.isInteger(port) || port < 1 || port > 65535) { return { valid: false, error: "Bitte einen gültigen Port (1–65535) angeben." }; } const absender = text(input.absenderAdresse); if (!/^[^\s@]+@[^\s@]+$/.test(absender)) { return { valid: false, error: "Bitte eine gültige Absenderadresse angeben." }; } const benutzer = text(input.benutzer) || null; // Passwort nicht trimmen: Leerzeichen koennen Teil des Passworts sein. const passwort = typeof input.passwort === "string" && input.passwort !== "" ? input.passwort : null; if (benutzer && !passwort && !passwortGespeichert) { return { valid: false, error: "Bitte ein Passwort eingeben." }; } return { valid: true, werte: { host, port, secure: input.secure, benutzer, neuesPasswort: benutzer ? passwort : null, absender_adresse: absender, absender_name: text(input.absenderName) || null, }, }; } const SMTP_SELECT = "firma_id, host, port, secure, benutzer, passwort_verschluesselt, absender_adresse, absender_name"; // Nur mit dem Service-Client aufrufen (firmen_smtp hat keine Grants fuer authenticated). export async function ladeFirmenSmtp(admin: SupabaseClient, firmaId: string): Promise { const { data, error } = await admin.from("firmen_smtp").select(SMTP_SELECT).eq("firma_id", firmaId).maybeSingle(); if (error) { throw new Error(`SMTP-Konfiguration laden fehlgeschlagen: ${error.message}`); } return (data as FirmenSmtpZeile | null) ?? null; } export function firmenSmtpZuConfig(zeile: FirmenSmtpZeile): EmailConfig { const name = zeile.absender_name?.replace(/["\r\n]/g, "").trim(); const pass = zeile.benutzer && zeile.passwort_verschluesselt ? entschluessele(zeile.passwort_verschluesselt) : null; return { host: zeile.host, port: zeile.port, secure: zeile.secure, from: name ? `"${name}" <${zeile.absender_adresse}>` : zeile.absender_adresse, auth: zeile.benutzer && pass ? { user: zeile.benutzer, pass } : null, }; } // Firmen-SMTP vor globalem Fallback (SMTP_* aus der .env); null = keiner vorhanden. export async function ermittleEmailConfig( admin: SupabaseClient, firmaId: string, fallback: () => EmailConfig | null = getEmailConfig ): Promise { const zeile = await ladeFirmenSmtp(admin, firmaId); return zeile ? firmenSmtpZuConfig(zeile) : fallback(); } ``` - [ ] **Step 4: Tests grün** Run (`web/`): `npx vitest run lib/firma` → PASS. - [ ] **Step 5: Actions** `web/app/firma/smtp-actions.ts`: ```ts "use server"; import { revalidatePath } from "next/cache"; import { createClient } from "@/lib/supabase/server"; import { createAdminClient } from "@/lib/supabase/admin"; import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; import { firmenSmtpZuConfig, ladeFirmenSmtp, validateSmtpEingabe } from "@/lib/firma/smtp"; import { verschluessele } from "@/lib/firma/smtp-crypto"; import { sendeProtokollMail } from "@/lib/notifications/email"; export type ActionResult = { success: true } | { success: false; error: string }; // firmen_smtp ist nur per Service-Client erreichbar. Deshalb vorher ueber den // RLS-Client pruefen (ladeAdminKontext), die firma_id kommt nur von dort. export async function speichereSmtp(formData: FormData): Promise { const kontext = await ladeAdminKontext(); if (!kontext.ok) return { success: false, error: kontext.error }; const admin = createAdminClient(); const bestehend = await ladeFirmenSmtp(admin, kontext.firma.id); const validation = validateSmtpEingabe( { host: formData.get("host"), port: formData.get("port"), secure: formData.get("secure") === "on", benutzer: formData.get("benutzer"), passwort: formData.get("passwort"), absenderAdresse: formData.get("absender_adresse"), absenderName: formData.get("absender_name"), }, Boolean(bestehend?.passwort_verschluesselt) ); if (!validation.valid) return { success: false, error: validation.error }; const w = validation.werte; let passwortVerschluesselt: string | null = null; if (w.benutzer) { try { passwortVerschluesselt = w.neuesPasswort ? verschluessele(w.neuesPasswort) : bestehend?.passwort_verschluesselt ?? null; } catch (fehler) { return { success: false, error: fehler instanceof Error ? fehler.message : "Verschlüsselung fehlgeschlagen." }; } } const { error } = await admin.from("firmen_smtp").upsert( { firma_id: kontext.firma.id, host: w.host, port: w.port, secure: w.secure, benutzer: w.benutzer, passwort_verschluesselt: passwortVerschluesselt, absender_adresse: w.absender_adresse, absender_name: w.absender_name, updated_at: new Date().toISOString(), }, { onConflict: "firma_id" } ); if (error) return { success: false, error: "SMTP-Einstellungen konnten nicht gespeichert werden." }; revalidatePath("/firma"); return { success: true }; } export async function entferneSmtp(): Promise { const kontext = await ladeAdminKontext(); if (!kontext.ok) return { success: false, error: kontext.error }; const { error } = await createAdminClient().from("firmen_smtp").delete().eq("firma_id", kontext.firma.id); if (error) return { success: false, error: "SMTP-Einstellungen konnten nicht entfernt werden." }; revalidatePath("/firma"); return { success: true }; } export async function sendeTestmail(): Promise { const kontext = await ladeAdminKontext(); if (!kontext.ok) return { success: false, error: kontext.error }; const supabase = await createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user?.email) return { success: false, error: "Für Ihren Zugang ist keine E-Mail-Adresse hinterlegt." }; const zeile = await ladeFirmenSmtp(createAdminClient(), kontext.firma.id); if (!zeile) return { success: false, error: "Es ist noch kein eigener SMTP-Server gespeichert." }; let cfg; try { cfg = firmenSmtpZuConfig(zeile); } catch (fehler) { return { success: false, error: fehler instanceof Error ? fehler.message : "Konfiguration ungültig." }; } const ergebnis = await sendeProtokollMail(cfg, { to: user.email, subject: `Testmail ${kontext.firma.name}`, text: "Diese Testmail bestätigt, dass der SMTP-Versand Ihrer Firma funktioniert.", attachments: [], }); return ergebnis.ok ? { success: true } : { success: false, error: ergebnis.fehler.slice(0, 500) }; } ``` - [ ] **Step 6: Formular und Seite** `web/components/firma/SmtpForm.tsx`: ```tsx "use client"; import { useState, useTransition } from "react"; import { entferneSmtp, sendeTestmail, speichereSmtp } from "@/app/firma/smtp-actions"; import { Alert } from "@/components/ui/Alert"; import { Button } from "@/components/ui/Button"; import { FIELD_CLASSES, FormField } from "@/components/ui/FormField"; import type { SmtpAnzeige } from "@/lib/firma/smtp"; export function SmtpForm({ smtp }: { smtp: SmtpAnzeige | null }) { const [fehler, setFehler] = useState(null); const [meldung, setMeldung] = useState(null); const [isPending, startTransition] = useTransition(); function zeige(ergebnis: { success: true } | { success: false; error: string }, erfolg: string) { setFehler(ergebnis.success ? null : ergebnis.error); setMeldung(ergebnis.success ? erfolg : null); } function handleSubmit(event: React.FormEvent) { event.preventDefault(); const formData = new FormData(event.currentTarget); startTransition(async () => zeige(await speichereSmtp(formData), "Gespeichert.")); } return (

Ohne eigenen Server gehen Protokoll-Mails über den Absender der Plattform raus.

{fehler && (
{fehler}
)} {meldung && (

{meldung}

)}
{smtp && ( <> )}
); } ``` `web/app/firma/page.tsx` — vollständige neue Fassung: ```tsx import { redirect } from "next/navigation"; import { createAdminClient } from "@/lib/supabase/admin"; import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; import { ladeFirmenSmtp, type SmtpAnzeige } from "@/lib/firma/smtp"; import { FirmaEinstellungenForm } from "@/components/firma/FirmaEinstellungenForm"; import { LogoForm } from "@/components/firma/LogoForm"; import { SmtpForm } from "@/components/firma/SmtpForm"; import { Card } from "@/components/ui/Card"; export default async function FirmaPage() { const kontext = await ladeAdminKontext(); if (!kontext.ok) { redirect("/dashboard"); } // Das Passwort verlaesst den Server nie, nur ob eins gesetzt ist. const zeile = await ladeFirmenSmtp(createAdminClient(), kontext.firma.id); const smtp: SmtpAnzeige | null = zeile ? { host: zeile.host, port: zeile.port, secure: zeile.secure, benutzer: zeile.benutzer, absender_adresse: zeile.absender_adresse, absender_name: zeile.absender_name, passwortGesetzt: Boolean(zeile.passwort_verschluesselt), } : null; return (

Firma

Allgemein

Logo

E-Mail-Versand (SMTP)

); } ``` - [ ] **Step 7: Prüfen** Run (`web/`): `npm test && npx tsc --noEmit && npm run lint` → PASS. - [ ] **Step 8: Commit** ```bash git add web/lib/firma web/app/firma web/components/firma git commit -m "feat: SMTP-Absender pro Firma mit verschluesseltem Passwort und Testmail" ``` --- ### Task 8: Plattform-Bereich für den Superadmin **Files:** - Create: `web/lib/plattform/validate.ts`, `web/lib/plattform/validate.test.ts` - Create: `web/lib/plattform/queries.ts` - Create: `web/lib/plattform/superadmin.ts`, `web/lib/plattform/superadmin.test.ts` - Create: `web/app/plattform/actions.ts`, `web/app/plattform/page.tsx`, `web/app/plattform/[id]/page.tsx` **Interfaces:** - Consumes: `legeNutzerInFirmaAn` (Task 5), `validatePasswort` (`lib/auth/passwort.ts`), `loadProfile`. - Produces: `/plattform`, `/plattform/[id]`; `pruefeSuperadmin(profil: ProfileResult): boolean`. - [ ] **Step 1: Failing Tests** `web/lib/plattform/validate.test.ts`: ```ts import { describe, expect, it } from "vitest"; import { validateFirmaAnlegen, validateFirmenAdmin } from "./validate"; describe("validateFirmenAdmin", () => { it("uebernimmt gueltige Werte", () => { expect(validateFirmenAdmin({ name: " Anna ", email: "anna@b.de", passwort: "Passwort123!" })).toEqual({ valid: true, name: "Anna", email: "anna@b.de", passwort: "Passwort123!", }); }); it("verlangt Name, E-Mail und Passwort", () => { expect(validateFirmenAdmin({ name: "", email: "a@b.de", passwort: "Passwort123!" })).toEqual({ valid: false, error: "Bitte einen Namen für den Admin eingeben.", }); expect(validateFirmenAdmin({ name: "A", email: "ab.de", passwort: "Passwort123!" })).toEqual({ valid: false, error: "Bitte eine gültige E-Mail-Adresse eingeben.", }); expect(validateFirmenAdmin({ name: "A", email: "a@b.de", passwort: "kurz" }).valid).toBe(false); }); }); describe("validateFirmaAnlegen", () => { it("verlangt einen Firmennamen", () => { expect(validateFirmaAnlegen({ firmenname: " ", name: "A", email: "a@b.de", passwort: "Passwort123!" })).toEqual({ valid: false, error: "Bitte einen Firmennamen eingeben.", }); }); it("liefert Firmenname und Admin", () => { const e = validateFirmaAnlegen({ firmenname: "Firma B", name: "A", email: "a@b.de", passwort: "Passwort123!" }); expect(e).toEqual({ valid: true, firmenname: "Firma B", admin: { name: "A", email: "a@b.de", passwort: "Passwort123!" } }); }); }); ``` `web/lib/plattform/superadmin.test.ts`: ```ts import { describe, expect, it } from "vitest"; import { pruefeSuperadmin } from "./superadmin"; describe("pruefeSuperadmin", () => { it("nur Rolle superadmin", () => { expect(pruefeSuperadmin({ status: "ok", profile: { id: "1", name: "S", role: "superadmin", firma_id: null } })).toBe(true); expect(pruefeSuperadmin({ status: "ok", profile: { id: "1", name: "A", role: "admin", firma_id: "f" } })).toBe(false); expect(pruefeSuperadmin({ status: "unauthenticated" })).toBe(false); }); }); ``` - [ ] **Step 2: Fehlschlag prüfen** Run (`web/`): `npx vitest run lib/plattform` → FAIL. - [ ] **Step 3: Validierung, Guard, Queries** Vorher `web/lib/auth/passwort.ts:11-17` lesen: `validatePasswort` liefert `{ valid: true; passwort } | { valid: false; error }`. `web/lib/plattform/validate.ts`: ```ts import { validatePasswort } from "@/lib/auth/passwort"; type Eingabe = { name: unknown; email: unknown; passwort: unknown }; export type FirmenAdminValidation = | { valid: true; name: string; email: string; passwort: string } | { valid: false; error: string }; function text(wert: unknown): string { return typeof wert === "string" ? wert.trim() : ""; } export function validateFirmenAdmin(input: Eingabe): FirmenAdminValidation { const name = text(input.name); if (!name) return { valid: false, error: "Bitte einen Namen für den Admin eingeben." }; const email = text(input.email); if (!/^[^\s@]+@[^\s@]+$/.test(email)) return { valid: false, error: "Bitte eine gültige E-Mail-Adresse eingeben." }; const passwort = validatePasswort(typeof input.passwort === "string" ? input.passwort : null); if (!passwort.valid) return { valid: false, error: passwort.error }; return { valid: true, name, email, passwort: passwort.passwort }; } export function validateFirmaAnlegen( input: Eingabe & { firmenname: unknown } ): | { valid: true; firmenname: string; admin: { name: string; email: string; passwort: string } } | { valid: false; error: string } { const firmenname = text(input.firmenname); if (!firmenname) return { valid: false, error: "Bitte einen Firmennamen eingeben." }; if (firmenname.length > 100) return { valid: false, error: "Der Firmenname darf höchstens 100 Zeichen lang sein." }; const admin = validateFirmenAdmin(input); if (!admin.valid) return admin; return { valid: true, firmenname, admin: { name: admin.name, email: admin.email, passwort: admin.passwort } }; } ``` `web/lib/plattform/superadmin.ts`: ```ts import type { ProfileResult } from "@/lib/auth/profile"; // Die Plattform-Actions arbeiten ausschliesslich mit dem Service-Client (der // Superadmin hat keine RLS-Policies auf Fachdaten). Diese Pruefung ist deshalb // die einzige Schranke und steht am Anfang jeder Plattform-Action und -Seite. export function pruefeSuperadmin(profil: ProfileResult): boolean { return profil.status === "ok" && profil.profile.role === "superadmin"; } ``` `web/lib/plattform/queries.ts`: ```ts import type { SupabaseClient } from "@supabase/supabase-js"; export type FirmaUebersicht = { id: string; name: string; aktiv: boolean; nutzerAnzahl: number }; export type FirmenAdmin = { id: string; name: string; username: string; email: string | null }; // Nur mit dem Service-Client aufrufen. export async function listFirmen(admin: SupabaseClient): Promise { const { data, error } = await admin.from("firmen").select("id, name, aktiv, profiles(count)").order("name"); if (error) throw new Error(`Firmen laden fehlgeschlagen: ${error.message}`); return (data ?? []).map((f) => ({ id: f.id as string, name: f.name as string, aktiv: f.aktiv as boolean, nutzerAnzahl: ((f.profiles as { count: number }[] | null)?.[0]?.count ?? 0) as number, })); } export async function ladeFirmaFuerPlattform( admin: SupabaseClient, firmaId: string ): Promise<{ id: string; name: string; aktiv: boolean } | null> { const { data } = await admin.from("firmen").select("id, name, aktiv").eq("id", firmaId).maybeSingle(); return (data as { id: string; name: string; aktiv: boolean } | null) ?? null; } export async function listFirmenAdmins(admin: SupabaseClient, firmaId: string): Promise { const { data, error } = await admin .from("profiles") .select("id, name, username") .eq("firma_id", firmaId) .eq("role", "admin") .order("name"); if (error) throw new Error(`Admins laden fehlgeschlagen: ${error.message}`); return Promise.all( (data ?? []).map(async (p) => { const { data: auth } = await admin.auth.admin.getUserById(p.id as string); return { id: p.id as string, name: p.name as string, username: p.username as string, email: auth.user?.email ?? null }; }) ); } ``` - [ ] **Step 4: Tests grün** Run (`web/`): `npx vitest run lib/plattform` → PASS. - [ ] **Step 5: Actions** `web/app/plattform/actions.ts`: ```ts "use server"; import { redirect } from "next/navigation"; import { revalidatePath } from "next/cache"; import { createAdminClient } from "@/lib/supabase/admin"; import { loadProfile } from "@/lib/auth/profile"; import { validatePasswort } from "@/lib/auth/passwort"; import { legeNutzerInFirmaAn } from "@/lib/nutzerverwaltung/nutzer-anlegen"; import { pruefeSuperadmin } from "@/lib/plattform/superadmin"; import { validateFirmaAnlegen, validateFirmenAdmin } from "@/lib/plattform/validate"; function zurueck(pfad: string, fehler?: string): never { redirect(fehler ? `${pfad}?error=${encodeURIComponent(fehler)}` : pfad); } async function sicherSuperadmin(): Promise { if (!pruefeSuperadmin(await loadProfile())) { redirect("/login"); } } export async function legeFirmaAn(formData: FormData): Promise { await sicherSuperadmin(); const v = validateFirmaAnlegen({ firmenname: formData.get("firmenname"), name: formData.get("name"), email: formData.get("email"), passwort: formData.get("passwort"), }); if (!v.valid) zurueck("/plattform", v.error); const admin = createAdminClient(); const { data: firma, error } = await admin.from("firmen").insert({ name: v.firmenname }).select("id").single(); if (error || !firma) zurueck("/plattform", "Firma konnte nicht angelegt werden."); const nutzer = await legeNutzerInFirmaAn(admin, { firmaId: firma.id, rolle: "admin", ...v.admin }); if (!nutzer.ok) { // Keine Firma ohne Admin zuruecklassen. await admin.from("firmen").delete().eq("id", firma.id); zurueck("/plattform", nutzer.fehler); } revalidatePath("/plattform"); zurueck(`/plattform/${firma.id}`); } export async function setzeFirmaAktiv(firmaId: string, aktiv: boolean): Promise { await sicherSuperadmin(); const { error } = await createAdminClient().from("firmen").update({ aktiv }).eq("id", firmaId); revalidatePath("/plattform"); zurueck(`/plattform/${firmaId}`, error ? "Status konnte nicht geändert werden." : undefined); } export async function legeFirmenAdminAn(firmaId: string, formData: FormData): Promise { await sicherSuperadmin(); const v = validateFirmenAdmin({ name: formData.get("name"), email: formData.get("email"), passwort: formData.get("passwort") }); if (!v.valid) zurueck(`/plattform/${firmaId}`, v.error); const nutzer = await legeNutzerInFirmaAn(createAdminClient(), { firmaId, rolle: "admin", name: v.name, email: v.email, passwort: v.passwort, }); zurueck(`/plattform/${firmaId}`, nutzer.ok ? undefined : nutzer.fehler); } export async function setzeAdminPasswort(firmaId: string, nutzerId: string, formData: FormData): Promise { await sicherSuperadmin(); const v = validatePasswort(formData.get("passwort")); if (!v.valid) zurueck(`/plattform/${firmaId}`, v.error); const admin = createAdminClient(); // Nur Admins der angegebenen Firma, nie andere Rollen oder Superadmins. const { data: ziel } = await admin .from("profiles") .select("id") .eq("id", nutzerId) .eq("firma_id", firmaId) .eq("role", "admin") .maybeSingle(); if (!ziel) zurueck(`/plattform/${firmaId}`, "Nutzer nicht gefunden."); const { error } = await admin.auth.admin.updateUserById(nutzerId, { password: v.passwort, app_metadata: { must_change_password: true }, }); zurueck(`/plattform/${firmaId}`, error ? `Passwort setzen fehlgeschlagen: ${error.message}` : undefined); } ``` - [ ] **Step 6: Seiten** `web/app/plattform/page.tsx`: ```tsx import Link from "next/link"; import { redirect } from "next/navigation"; import { createAdminClient } from "@/lib/supabase/admin"; import { loadProfile } from "@/lib/auth/profile"; import { pruefeSuperadmin } from "@/lib/plattform/superadmin"; import { listFirmen } from "@/lib/plattform/queries"; import { legeFirmaAn } from "./actions"; import { Alert } from "@/components/ui/Alert"; import { Button } from "@/components/ui/Button"; import { Card } from "@/components/ui/Card"; import { FIELD_CLASSES, FormField } from "@/components/ui/FormField"; export default async function PlattformPage({ searchParams }: { searchParams: Promise<{ error?: string }> }) { if (!pruefeSuperadmin(await loadProfile())) { redirect("/dashboard"); } const { error } = await searchParams; const firmen = await listFirmen(createAdminClient()); return (

Plattform-Verwaltung

{error && {error}}

Firmen

    {firmen.map((f) => (
  • {f.name} {f.nutzerAnzahl} Nutzer · {f.aktiv ? "aktiv" : deaktiviert}
  • ))}

Neue Firma anlegen

); } ``` `web/app/plattform/[id]/page.tsx`: ```tsx import Link from "next/link"; import { notFound, redirect } from "next/navigation"; import { createAdminClient } from "@/lib/supabase/admin"; import { loadProfile } from "@/lib/auth/profile"; import { pruefeSuperadmin } from "@/lib/plattform/superadmin"; import { ladeFirmaFuerPlattform, listFirmenAdmins } from "@/lib/plattform/queries"; import { legeFirmenAdminAn, setzeAdminPasswort, setzeFirmaAktiv } from "../actions"; import { Alert } from "@/components/ui/Alert"; import { Button } from "@/components/ui/Button"; import { Card } from "@/components/ui/Card"; import { FIELD_CLASSES, FormField } from "@/components/ui/FormField"; export default async function PlattformFirmaPage({ params, searchParams, }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string }>; }) { if (!pruefeSuperadmin(await loadProfile())) { redirect("/dashboard"); } const { id } = await params; const { error } = await searchParams; const admin = createAdminClient(); const firma = await ladeFirmaFuerPlattform(admin, id); if (!firma) notFound(); const admins = await listFirmenAdmins(admin, id); return (
← Alle Firmen

{firma.name}

{error && {error}}

Status: {firma.aktiv ? "aktiv" : deaktiviert}

Admins

    {admins.map((a) => (
  • {a.name}

    {a.email ?? "-"} · {a.username}

  • ))}

Weiteren Admin anlegen

); } ``` - [ ] **Step 7: Prüfen** Run (`web/`): `npm test && npx tsc --noEmit && npm run lint` → PASS. - [ ] **Step 8: Commit** ```bash git add web/lib/plattform web/app/plattform git commit -m "feat: Plattform-Bereich zum Anlegen und Verwalten von Firmen" ``` --- ### Task 9: Benachrichtigungen und PDF pro Firma **Files:** - Modify: `web/lib/notifications/config.ts`, `config.test.ts`, `whatsapp.ts`, `whatsapp.test.ts`, `handler.ts`, `handler.test.ts`, `dispatch.ts`, `email.ts`, `email.test.ts` - Modify: `web/app/api/notifications/dispatch/route.ts` - Modify: `web/lib/auftraege/protokoll.ts`, `protokoll-pdf.ts`, `protokoll-pdf.test.ts`, `ProtokollDocument.tsx` (+ Tests, die `ProtokollProps` bauen) - Modify: `.env.example`, `docker-compose.yaml` (nur `WHATSAPP_RECIPIENT` entfernen) **Interfaces:** - Consumes: `ermittleEmailConfig` (Task 7), `ladeFirmaZumAuftrag`, `FirmaBranding` (Task 4), `STANDARD_FARBE_PRIMAER` (Task 3). - Produces: - `WhatsAppConfig` **ohne** `recipient`; `sendWhatsAppTemplate(cfg, empfaenger: string, payload)`. - `OutboxRow.firma_id: string`. - `whatsappHandler(admin: SupabaseClient, cfg: WhatsAppConfig, sender = sendWhatsAppTemplate): Handler` - `protokollMailHandler(admin, deps?: { erzeugePdf?; sender?; ladeConfig?: (admin, firmaId) => Promise }): Handler` - `baueProtokollMail({ empfaenger, auftrag, pdf, firmenname })` - `erzeugeProtokollPdf(client, auftragId): Promise<{ auftrag; buffer; firma: FirmaBranding } | null>` - `ProtokollProps.firma: { name: string; farbe: string; logo: { buffer: Buffer; format: "png" | "jpg" } | null }` - [ ] **Step 1: Failing Tests anpassen/ergänzen** In `web/lib/notifications/email.test.ts` den bestehenden Betreff-Test auf den neuen Parameter umstellen und erwarten: ```ts expect(mail.subject).toBe(`Übergabeprotokoll ${auftrag.auftragsnummer} – ${fahrzeugBezeichnung(auftrag.fahrzeug)} (Firma B)`); ``` (alle Aufrufe von `baueProtokollMail` bekommen `firmenname: "Firma B"`). In `web/lib/notifications/handler.test.ts` ergänzen (Fake-Admin-Muster der Datei weiterverwenden; jede Test-Zeile bekommt `firma_id: "f2"`): ```ts describe("whatsappHandler", () => { it("sendet an den WhatsApp-Empfaenger der Firma", async () => { const sender = vi.fn(async () => ({ ok: true as const, messageId: "wamid.1" })); const admin = fakeAdminMitFirma({ whatsapp_empfaenger: "+4915100000009" }); const res = await whatsappHandler(admin, CFG, sender)(zeile({ event_type: "auftrag_erstellt", firma_id: "f2" })); expect(res).toEqual({ ok: true, waMessageId: "wamid.1" }); expect(sender).toHaveBeenCalledWith(CFG, "+4915100000009", expect.anything()); }); it("verwirft endgueltig, wenn die Firma keinen Empfaenger hat", async () => { const res = await whatsappHandler(fakeAdminMitFirma({ whatsapp_empfaenger: null }), CFG, vi.fn())( zeile({ event_type: "auftrag_erstellt", firma_id: "f2" }) ); expect(res).toEqual({ ok: false, fehler: "Firma hat keinen WhatsApp-Empfaenger", endgueltig: true }); }); }); describe("protokollMailHandler ohne SMTP", () => { it("meldet Kein SMTP konfiguriert (Retry, nicht endgueltig) und erzeugt kein PDF", async () => { const erzeugePdf = vi.fn(); const res = await protokollMailHandler(fakeAdminMitFirma({ whatsapp_empfaenger: null }), { erzeugePdf, ladeConfig: async () => null, })(zeile({ event_type: "protokoll_abgeschlossen", firma_id: "f2", payload: { empfaenger: "d@x.de" }, auftrag_id: "a1" })); expect(res).toEqual({ ok: false, fehler: "Kein SMTP konfiguriert" }); expect(erzeugePdf).not.toHaveBeenCalled(); }); }); ``` mit dem Helfer (in der Testdatei): ```ts function fakeAdminMitFirma(firma: { whatsapp_empfaenger: string | null }): SupabaseClient { const kette = { select: () => kette, eq: () => kette, maybeSingle: async () => ({ data: firma, error: null }) }; return { from: () => kette } as unknown as SupabaseClient; } ``` Bestehende Handler-Tests anpassen: `whatsappHandler(admin, cfg, sender)`, `protokollMailHandler(admin, { …, ladeConfig: async () => MAIL_CFG })`, PDF-Fakes liefern zusätzlich `firma: { name: "Firma B", logo_pfad: null, farbe_primaer: null }`. `recipient` aus allen `WhatsAppConfig`-Fixtures (`config.test.ts`, `handler.test.ts`, `whatsapp.test.ts`) entfernen; in `whatsapp.test.ts` den Aufruf auf `sendWhatsAppTemplate(cfg, "+4915100000000", payload)` umstellen und erwarten, dass der Request-Body `to: "4915100000000"` enthält (führendes `+` entfernt). In `web/lib/auftraege/protokoll-pdf.test.ts` ergänzen: der Fake-Client liefert für `auftraege … firma:firmen(...)` `{ firma: { name: "Firma B", logo_pfad: null, farbe_primaer: "#112233" } }`, und das Ergebnis enthält `firma.name === "Firma B"`. Run (`web/`): `npx vitest run lib/notifications lib/auftraege` → FAIL. - [ ] **Step 2: WhatsApp** `web/lib/notifications/config.ts`: `recipient` aus Typ, Lesen, Pflichtprüfung und Rückgabe entfernen. Kommentar ergänzen: `// Der Empfaenger kommt pro Firma aus firmen.whatsapp_empfaenger.` `web/lib/notifications/whatsapp.ts`: Signatur ```ts export async function sendWhatsAppTemplate( cfg: WhatsAppConfig, empfaenger: string, payload: AuftragErstelltPayload ): Promise { ``` und im Body `to: empfaenger.replace(/^\+/, ""),` (die Graph-API erwartet die Nummer ohne `+`). - [ ] **Step 3: Dispatcher und Handler** `web/lib/notifications/dispatch.ts`: in `OutboxRow` `firma_id: string;` ergänzen (`claim_notification_batch` liefert `setof notification_outbox`, die Spalte kommt automatisch mit). `web/lib/notifications/handler.ts` — vollständige Fassung: ```ts import type { SupabaseClient } from "@supabase/supabase-js"; import { erzeugeProtokollPdf } from "@/lib/auftraege/protokoll-pdf"; import { ermittleEmailConfig } from "@/lib/firma/smtp"; import type { WhatsAppConfig } from "./config"; import type { Handler } from "./dispatch"; import type { EmailConfig } from "./email-config"; import { baueProtokollMail, sendeProtokollMail } from "./email"; import { sendWhatsAppTemplate, type AuftragErstelltPayload } from "./whatsapp"; // Empfaenger beim Versand frisch lesen: eine Aenderung auf /firma gilt sofort. export function whatsappHandler(admin: SupabaseClient, cfg: WhatsAppConfig, sender = sendWhatsAppTemplate): Handler { return async (row) => { const { data, error } = await admin .from("firmen") .select("whatsapp_empfaenger") .eq("id", row.firma_id) .maybeSingle(); if (error) { return { ok: false, fehler: `Firma laden fehlgeschlagen: ${error.message}` }; } const empfaenger = (data as { whatsapp_empfaenger: string | null } | null)?.whatsapp_empfaenger; if (!empfaenger) { return { ok: false, fehler: "Firma hat keinen WhatsApp-Empfaenger", endgueltig: true }; } const res = await sender(cfg, empfaenger, row.payload as AuftragErstelltPayload); return res.ok ? { ok: true, waMessageId: res.messageId } : res; }; } export function protokollMailHandler( admin: SupabaseClient, deps: { erzeugePdf?: typeof erzeugeProtokollPdf; sender?: typeof sendeProtokollMail; ladeConfig?: (admin: SupabaseClient, firmaId: string) => Promise; } = {} ): Handler { const erzeugePdf = deps.erzeugePdf ?? erzeugeProtokollPdf; const sender = deps.sender ?? sendeProtokollMail; const ladeConfig = deps.ladeConfig ?? ((a, firmaId) => ermittleEmailConfig(a, firmaId)); return async (row) => { const empfaenger = typeof row.payload.empfaenger === "string" ? row.payload.empfaenger : ""; if (!empfaenger || !row.auftrag_id) { return { ok: false, fehler: "Empfaenger oder Auftrag fehlt in der Outbox-Zeile", endgueltig: true }; } let cfg: EmailConfig | null; try { cfg = await ladeConfig(admin, row.firma_id); } catch (fehler) { return { ok: false, fehler: `SMTP-Konfiguration fehlerhaft: ${fehler instanceof Error ? fehler.message : String(fehler)}`, }; } if (!cfg) { return { ok: false, fehler: "Kein SMTP konfiguriert" }; } let pdf: Awaited>; try { pdf = await erzeugePdf(admin, row.auftrag_id); } catch (fehler) { return { ok: false, fehler: `PDF-Erzeugung fehlgeschlagen: ${fehler instanceof Error ? fehler.message : String(fehler)}`, }; } if (!pdf) { return { ok: false, fehler: "Auftrag nicht gefunden oder nicht abgeschlossen", endgueltig: true }; } const res = await sender( cfg, baueProtokollMail({ empfaenger, auftrag: pdf.auftrag, pdf: pdf.buffer, firmenname: pdf.firma.name }) ); return res.ok ? { ok: true } : res; }; } ``` `web/lib/notifications/email.ts`: `baueProtokollMail(daten: { empfaenger: string; auftrag: Auftrag; pdf: Buffer; firmenname: string })`, Betreff ```ts subject: `Übergabeprotokoll ${auftrag.auftragsnummer} – ${fahrzeug} (${daten.firmenname})`, ``` Kommentar in `email-config.ts` aktualisieren: `null = kein globaler SMTP; Firmen ohne eigenen SMTP bekommen dann keine Mail (Outbox: failed/Retry).` `web/app/api/notifications/dispatch/route.ts` — der Block ab `const handler …` bis vor `catch`: ```ts const handler: Record = {}; const waCfg = getWhatsAppConfig(); try { const admin = createAdminClient(); // Protokoll-Mails werden immer geclaimt: ob ein SMTP existiert, steht erst // pro Zeile fest (Firmen-SMTP oder globaler Fallback). handler.protokoll_abgeschlossen = protokollMailHandler(admin); if (waCfg) { handler.auftrag_erstellt = whatsappHandler(admin, waCfg); } const ergebnis = await verarbeiteOutbox(admin, handler); return NextResponse.json(ergebnis); ``` Import von `getEmailConfig` entfernen. - [ ] **Step 4: PDF mit Firmenbranding** `web/lib/auftraege/protokoll.ts`: in `ProtokollProps` ergänzen ```ts firma: { name: string; farbe: string; logo: { buffer: Buffer; format: "png" | "jpg" } | null }; ``` und `buildProtokollBasisdaten` gibt `Omit` zurück. `web/lib/auftraege/protokoll-pdf.ts` — Imports `ladeFirmaZumAuftrag`, `type FirmaBranding` aus `@/lib/firma/queries` und `STANDARD_FARBE_PRIMAER` aus `@/lib/firma/farben`; Rückgabetyp `Promise<{ auftrag: Auftrag; buffer: Buffer; firma: FirmaBranding } | null>`; nach dem Status-Check: ```ts const firma = (await ladeFirmaZumAuftrag(client, auftragId)) ?? { name: "", logo_pfad: null, farbe_primaer: null }; const [fotos, unterschriftBuffer, logo] = await Promise.all([ loadAuftragFotoBuffers(auftragId, client), loadUnterschriftBuffer(auftrag.unterschrift_storage_path, client), ladeLogoFuerPdf(client, firma.logo_pfad), ]); const verkleinert = await Promise.all(fotos.map(verkleinereFoto)); const props = { ...buildProtokollBasisdaten(auftrag), fotos: verkleinert, unterschriftBuffer, firma: { name: firma.name, farbe: firma.farbe_primaer ?? STANDARD_FARBE_PRIMAER, logo }, }; ``` …und am Ende `return { auftrag, buffer, firma };`. Neue Hilfsfunktion in derselben Datei: ```ts // Das Logo ist Schmuck: fehlt es oder ist es ein SVG (von @react-pdf nicht // zuverlaessig darstellbar), wird es weggelassen statt das Protokoll scheitern zu lassen. async function ladeLogoFuerPdf( client: SupabaseClient, pfad: string | null ): Promise<{ buffer: Buffer; format: "png" | "jpg" } | null> { if (!pfad) return null; const format = pfad.endsWith(".png") ? "png" : pfad.endsWith(".jpg") ? "jpg" : null; if (!format) return null; const { data, error } = await client.storage.from("firmen-logos").download(pfad); if (error || !data) { console.warn("[protokoll] Firmenlogo nicht ladbar, PDF ohne Logo:", pfad, error?.message); return null; } return { buffer: Buffer.from(await data.arrayBuffer()), format }; } ``` `web/lib/auftraege/ProtokollDocument.tsx` — Stil `kopf: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }`, `logo: { height: 32, maxWidth: 160, objectFit: "contain" }`, `firmenname: { fontSize: 10 }` ergänzen; die Zeile `Übergabeprotokoll {props.auftragsnummer}` ersetzen durch: ```tsx {props.firma.logo ? ( ) : ( {props.firma.name} )} {props.firma.logo && {props.firma.name}} Übergabeprotokoll {props.auftragsnummer} ``` Vorher prüfen, wie Fotos in derselben Datei an `` übergeben werden, und für das Logo dasselbe `src`-Format verwenden. Alle Tests/Fixtures, die `ProtokollProps` direkt bauen, bekommen `firma: { name: "Firma B", farbe: "#0071ed", logo: null }`. - [ ] **Step 5: `WHATSAPP_RECIPIENT` entfernen** `.env.example`: Zeile `WHATSAPP_RECIPIENT=` löschen. `docker-compose.yaml`: Zeile `WHATSAPP_RECIPIENT: ${WHATSAPP_RECIPIENT}` löschen. `grep -rn WHATSAPP_RECIPIENT --exclude-dir=node_modules .` → nur noch Treffer in `docs/`. - [ ] **Step 6: Prüfen** Run (`web/`): `npm test && npx tsc --noEmit && npm run lint` → PASS. - [ ] **Step 7: Commit** ```bash git add web/lib/notifications web/lib/auftraege web/app/api/notifications .env.example docker-compose.yaml git commit -m "feat: WhatsApp-Empfaenger, SMTP und PDF-Branding pro Firma" ``` --- ### Task 10: Superadmin-Skript, Umgebungsvariable, README **Files:** - Create: `web/scripts/superadmin-anlegen.mjs` - Modify: `.env.example`, `docker-compose.yaml`, `README.md` - Modify: `web/.env.local` nur wenn vorhanden (lokaler Schlüssel, nicht committen — Datei ist gitignored) **Interfaces:** - Consumes: Rolle `superadmin`, Check `profiles_superadmin_ohne_firma` (Task 1). - [ ] **Step 1: Skript** `web/scripts/superadmin-anlegen.mjs`: ```js // Legt den Plattform-Betreiber (Rolle superadmin, ohne Firma) an. // Aufruf: SUPABASE_URL=http://localhost:8000 SUPABASE_SERVICE_ROLE_KEY=... \ // node scripts/superadmin-anlegen.mjs // Nur fetch, keine Abhaengigkeiten: laeuft auch ausserhalb von web/node_modules. const [email, passwort, name] = process.argv.slice(2); const url = process.env.SUPABASE_URL; const key = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!email || !passwort || !name || !url || !key) { console.error("Aufruf: SUPABASE_URL=... SUPABASE_SERVICE_ROLE_KEY=... node scripts/superadmin-anlegen.mjs "); process.exit(1); } const headers = { apikey: key, Authorization: `Bearer ${key}`, "Content-Type": "application/json" }; const antwort = await fetch(`${url}/auth/v1/admin/users`, { method: "POST", headers, body: JSON.stringify({ email, password: passwort, email_confirm: true, user_metadata: { name } }), }); const nutzer = await antwort.json(); if (!antwort.ok) { console.error("Nutzer anlegen fehlgeschlagen:", nutzer); process.exit(1); } const profil = await fetch(`${url}/rest/v1/profiles?id=eq.${nutzer.id}`, { method: "PATCH", headers: { ...headers, Prefer: "return=representation" }, body: JSON.stringify({ role: "superadmin" }), }); const zeilen = await profil.json(); if (!profil.ok || !Array.isArray(zeilen) || zeilen.length !== 1) { console.error("Rolle setzen fehlgeschlagen, Nutzer wird wieder geloescht:", zeilen); await fetch(`${url}/auth/v1/admin/users/${nutzer.id}`, { method: "DELETE", headers }); process.exit(1); } console.log(`Superadmin angelegt: ${email} (${nutzer.id})`); ``` - [ ] **Step 2: Umgebungsvariable** `.env.example` — beim SMTP-Block ergänzen: ``` # Schluessel fuer die SMTP-Passwoerter der Firmen (AES-256-GCM, 32 Byte base64). # Erzeugen: openssl rand -base64 32 (Aendern macht gespeicherte Passwoerter unlesbar) SMTP_VERSCHLUESSELUNG_KEY= ``` `docker-compose.yaml` — im `web`-Service unter den `SMTP_*`-Variablen: ```yaml SMTP_VERSCHLUESSELUNG_KEY: ${SMTP_VERSCHLUESSELUNG_KEY} ``` Falls `web/.env.local` existiert und keinen Schlüssel hat: `echo "SMTP_VERSCHLUESSELUNG_KEY=$(openssl rand -base64 32)" >> web/.env.local` (nicht committen). - [ ] **Step 3: README** Nach Abschnitt „## 6. Ersten Admin-Nutzer anlegen“ einen Abschnitt einfügen: ```markdown ## 6a. Plattform-Betreiber (Superadmin) anlegen Der Superadmin legt Firmen und deren erste Admins an (`/plattform`), sieht aber keine Aufträge. Einmalig aus `web/`: SUPABASE_URL=http://localhost:8000 SUPABASE_SERVICE_ROLE_KEY= \ node scripts/superadmin-anlegen.mjs superadmin@example.de '' 'Plattform' Für die SMTP-Zugänge der Firmen muss `SMTP_VERSCHLUESSELUNG_KEY` in der `.env` gesetzt sein (`openssl rand -base64 32`). Der WhatsApp-Empfänger wird pro Firma unter `/firma` eingetragen. ``` - [ ] **Step 4: Prüfen** Run (`web/`): `node --check scripts/superadmin-anlegen.mjs && npm test && npx tsc --noEmit` → PASS. - [ ] **Step 5: Commit** ```bash git add web/scripts/superadmin-anlegen.mjs .env.example docker-compose.yaml README.md git commit -m "docs: Superadmin-Skript und SMTP_VERSCHLUESSELUNG_KEY" ``` --- ## Abschluss-Verifikation (Controller, nach Task 10) Gegen den Dev-Stack (lokaler CLI-Stack + `npm run dev` aus `web/`, Mailpit/Inbucket des CLI-Stacks), per curl nach `.claude/skills/curl-server-action/SKILL.md`: 1. Superadmin per Skript anlegen, einloggen → Redirect `/plattform`; Firma „Testfirma B“ mit Admin anlegen. 2. Admin B einloggen: sieht keine Aufträge/Orte von Widmann; `/firma` speichert Farben (Kontrastfehler bei `#ffff00`), Logo-Upload, SMTP auf Inbucket, Testmail kommt an. 3. Admin B ruft `sperreNutzer()` → `Nutzer nicht gefunden.` 4. Auftrag in Firma B anlegen, abschließen → Protokoll-Mail über Firmen-SMTP mit Betreff `(Testfirma B)`. 5. Superadmin deaktiviert Firma B → Login von Admin B: `Ihre Firma ist deaktiviert oder Ihr Zugang ist keiner Firma zugeordnet.`; eine offene Session landet beim nächsten Aufruf auf `/login`. 6. `GET /firma/logo` mit SVG-Logo liefert die Header `Content-Security-Policy: …sandbox` und `X-Content-Type-Options: nosniff`. 7. Rollback beim Firma-Anlegen: Firma mit bereits vergebener Admin-E-Mail anlegen → Fehlermeldung, Firma erscheint **nicht** in der Liste. Danach Master-Stack nach `.claude/skills/rebuild-master-stack/SKILL.md` (Reihenfolge laut Spec Abschnitt 6): Image bauen, `SMTP_VERSCHLUESSELUNG_KEY` in die Root-`.env`, drei Migrationen einzeln einspielen und eintragen, `web` neu starten, Superadmin per Skript anlegen; der Nutzer trägt danach den WhatsApp-Empfänger von Widmann auf `/firma` ein.