1
0
Fork 0

Merge feature/mandanten: Mandantenfähigkeit (Firmen, RLS pro Firma, Plattform-Bereich, Branding, SMTP pro Firma)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jonny 2026-10-12 14:54:51 +02:00
commit 07625e1728
92 changed files with 3905 additions and 202 deletions

View File

@ -32,7 +32,6 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=
# Dispatch-Route antwortet dann 200 { uebersprungen: true } und sendet nichts.
WHATSAPP_ACCESS_TOKEN=
WHATSAPP_PHONE_NUMBER_ID=
WHATSAPP_RECIPIENT=
WHATSAPP_TEMPLATE_NAME=neuer_auftrag
WHATSAPP_TEMPLATE_LANG=de
WHATSAPP_GRAPH_VERSION=
@ -52,3 +51,7 @@ SMTP_SECURE=false
SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM=
# 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=

View File

@ -86,6 +86,17 @@ Ein Admin muss die Rolle danach explizit setzen:
select name, role from public.profiles;
```
## 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=<SERVICE_ROLE_KEY aus .env> \
node scripts/superadmin-anlegen.mjs superadmin@example.de '<Passwort>' '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.
## 7. Lokale Entwicklung ohne Docker fuer `web/` (Alternative zu Schritt 4)
Der `web`-Service kann auch ausserhalb von Docker laufen, waehrend der

View File

@ -185,7 +185,6 @@ services:
# fuenf WHATSAPP_*-Pflichtvariablen, ueberspringt der Dispatcher sauber.
WHATSAPP_ACCESS_TOKEN: ${WHATSAPP_ACCESS_TOKEN}
WHATSAPP_PHONE_NUMBER_ID: ${WHATSAPP_PHONE_NUMBER_ID}
WHATSAPP_RECIPIENT: ${WHATSAPP_RECIPIENT}
WHATSAPP_TEMPLATE_NAME: ${WHATSAPP_TEMPLATE_NAME}
WHATSAPP_TEMPLATE_LANG: ${WHATSAPP_TEMPLATE_LANG}
WHATSAPP_GRAPH_VERSION: ${WHATSAPP_GRAPH_VERSION}
@ -199,3 +198,4 @@ services:
SMTP_USER: ${SMTP_USER}
SMTP_PASSWORD: ${SMTP_PASSWORD}
SMTP_FROM: ${SMTP_FROM}
SMTP_VERSCHLUESSELUNG_KEY: ${SMTP_VERSCHLUESSELUNG_KEY}

View File

@ -0,0 +1,3 @@
-- 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';

View File

@ -0,0 +1,411 @@
-- 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;
$$;

View File

@ -0,0 +1,418 @@
-- 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 <auftrag_id>/...: 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
);

View File

@ -0,0 +1,6 @@
-- Das Logo muss im Ordner der eigenen Firma liegen: der PDF-Versand laedt es
-- mit dem Service-Client, ein fremder Pfad wuerde das Logo einer anderen
-- Firma ins eigene Protokoll holen.
alter table public.firmen
add constraint firmen_logo_pfad_eigener_ordner
check (logo_pfad is null or logo_pfad like id::text || '/%');

View File

@ -0,0 +1,8 @@
-- Der LIKE-Check aus 20261012090300 liess "<id>/../<fremde-id>/logo-1.png" zu.
-- Der Pfad muss exakt dem Muster aus logoPfad() (web/lib/firma/logo.ts) entsprechen.
alter table public.firmen
drop constraint firmen_logo_pfad_eigener_ordner;
alter table public.firmen
add constraint firmen_logo_pfad_eigener_ordner
check (logo_pfad is null or logo_pfad ~ ('^' || id::text || '/logo-[0-9]+\.(png|jpg|svg)$'));

View File

@ -8,6 +8,7 @@ insert into auth.users (id, email) values
('aa444444-4444-4444-4444-444444444444', 'fahrer-zwei@arbeitszeiten.test.local'),
('aa555555-5555-5555-5555-555555555555', 'readonly@arbeitszeiten.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = 'aa111111-1111-1111-1111-111111111111';
update public.profiles set role = 'disponent' where id = 'aa222222-2222-2222-2222-222222222222';
update public.profiles set role = 'fahrer' where id = 'aa333333-3333-3333-3333-333333333333';
@ -74,8 +75,8 @@ select throws_ok(
reset role;
insert into public.arbeitszeiten (id, fahrer_id, kommt_um) values
('b2222222-2222-2222-2222-222222222222', 'aa444444-4444-4444-4444-444444444444', '2026-07-13 07:00:00+00');
insert into public.arbeitszeiten (id, fahrer_id, kommt_um, firma_id) values
('b2222222-2222-2222-2222-222222222222', 'aa444444-4444-4444-4444-444444444444', '2026-07-13 07:00:00+00', '00000000-0000-0000-0000-00000000f001');
set local role authenticated;
set local request.jwt.claims to '{"sub": "aa333333-3333-3333-3333-333333333333", "role": "authenticated"}';

View File

@ -8,6 +8,7 @@ insert into auth.users (id, email) values
('f4444444-4444-4444-4444-444444444444', 'fahrer-zwei@auftraege.test.local'),
('05555555-5555-5555-5555-555555555555', 'readonly@auftraege.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111';
update public.profiles set role = 'disponent' where id = 'd2222222-2222-2222-2222-222222222222';
update public.profiles set role = 'fahrer' where id = 'f3333333-3333-3333-3333-333333333333';
@ -15,13 +16,13 @@ update public.profiles set role = 'fahrer' where id = 'f4444444-4444-4444-4444-4
-- readonly bleibt auf dem Trigger-Default 'readonly' (siehe Fundament,
-- handle_new_user()), kein explizites update noetig.
insert into public.orte (id, adresse, ansprechpartner) values
('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'),
('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel');
insert into public.orte (id, adresse, ansprechpartner, firma_id) values
('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'),
('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001');
insert into public.fahrzeuge (id, kennzeichen) values
('f0000000-0000-0000-0000-000000000001', 'M-AB 123'),
('f0000000-0000-0000-0000-000000000002', 'M-CD 456');
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001'),
('f0000000-0000-0000-0000-000000000002', 'M-CD 456', '00000000-0000-0000-0000-00000000f001');
set local role authenticated;
set local request.jwt.claims to '{"sub": "d2222222-2222-2222-2222-222222222222", "role": "authenticated"}';

View File

@ -7,23 +7,24 @@ insert into auth.users (id, email) values
('ff333333-3333-3333-3333-333333333333', 'fahrer-eins-fotos@auftraege.test.local'),
('ff444444-4444-4444-4444-444444444444', 'fahrer-zwei-fotos@auftraege.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = 'aa111111-1111-1111-1111-111111111111';
update public.profiles set role = 'disponent' where id = 'dd222222-2222-2222-2222-222222222222';
update public.profiles set role = 'fahrer' where id = 'ff333333-3333-3333-3333-333333333333';
update public.profiles set role = 'fahrer' where id = 'ff444444-4444-4444-4444-444444444444';
insert into public.orte (id, adresse, ansprechpartner) values
('20111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'),
('20222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel');
insert into public.orte (id, adresse, ansprechpartner, firma_id) values
('20111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'),
('20222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001');
insert into public.fahrzeuge (id, kennzeichen) values
('20333333-0000-0000-0000-000000000001', 'M-EF 789');
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('20333333-0000-0000-0000-000000000001', 'M-EF 789', '00000000-0000-0000-0000-00000000f001');
-- Auftrag A: dem Fahrer "eins" zugewiesen, status = 'zugewiesen' -- fuer die
-- "eigener, noch nicht gestarteter Auftrag"-Faelle (Pflichtfoto UND
-- Schadensfoto duerfen hier hochgeladen werden).
insert into public.auftraege (
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id
) values (
'20000000-0000-0000-0000-000000000001',
'20111111-1111-1111-1111-111111111111',
@ -32,13 +33,14 @@ insert into public.auftraege (
'dd222222-2222-2222-2222-222222222222',
'zugewiesen',
'ff333333-3333-3333-3333-333333333333',
1000
1000,
'00000000-0000-0000-0000-00000000f001'
);
-- Auftrag B: dem Fahrer "zwei" zugewiesen -- aus Sicht von Fahrer "eins" ein
-- fremder Auftrag, fuer die SELECT- und INSERT-RLS-Blockade-Faelle.
insert into public.auftraege (
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id
) values (
'20000000-0000-0000-0000-000000000002',
'20111111-1111-1111-1111-111111111111',
@ -47,7 +49,8 @@ insert into public.auftraege (
'dd222222-2222-2222-2222-222222222222',
'zugewiesen',
'ff444444-4444-4444-4444-444444444444',
500
500,
'00000000-0000-0000-0000-00000000f001'
);
-- Auftrag C: dem Fahrer "eins" zugewiesen, aber direkt mit status =
@ -58,7 +61,7 @@ insert into public.auftraege (
-- unabhaengig von auftraege_rls_test.sql und fokussiert sie ausschliesslich
-- auf die auftrag_fotos/storage.objects-Policies statt auf den Trigger.
insert into public.auftraege (
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id
) values (
'20000000-0000-0000-0000-000000000003',
'20111111-1111-1111-1111-111111111111',
@ -67,7 +70,8 @@ insert into public.auftraege (
'dd222222-2222-2222-2222-222222222222',
'unterwegs',
'ff333333-3333-3333-3333-333333333333',
2000
2000,
'00000000-0000-0000-0000-00000000f001'
);
-- Ein Foto + ein Storage-Objekt fuer Auftrag B, als postgres (RLS-frei)

View File

@ -6,20 +6,21 @@ insert into auth.users (id, email) values
('ff666666-6666-6666-6666-666666666666', 'fahrer-eins-unterschrift@auftraege.test.local'),
('ff777777-7777-7777-7777-777777777777', 'fahrer-zwei-unterschrift@auftraege.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = 'aa555555-5555-5555-5555-555555555555';
update public.profiles set role = 'fahrer' where id = 'ff666666-6666-6666-6666-666666666666';
update public.profiles set role = 'fahrer' where id = 'ff777777-7777-7777-7777-777777777777';
insert into public.orte (id, adresse, ansprechpartner) values
('21111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'),
('21222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel');
insert into public.orte (id, adresse, ansprechpartner, firma_id) values
('21111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'),
('21222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001');
insert into public.fahrzeuge (id, kennzeichen) values
('21333333-0000-0000-0000-000000000001', 'M-UN 001');
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('21333333-0000-0000-0000-000000000001', 'M-UN 001', '00000000-0000-0000-0000-00000000f001');
-- Auftrag A: Fahrer "eins", status 'unterwegs' -- Upload muss hier gelingen.
insert into public.auftraege (
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id
) values (
'21000000-0000-0000-0000-000000000001',
'21111111-1111-1111-1111-111111111111',
@ -28,13 +29,14 @@ insert into public.auftraege (
'aa555555-5555-5555-5555-555555555555',
'unterwegs',
'ff666666-6666-6666-6666-666666666666',
1000
1000,
'00000000-0000-0000-0000-00000000f001'
);
-- Auftrag B: Fahrer "eins", status 'zugewiesen' -- Upload muss hier verboten
-- bleiben (Unterschrift ist nur bei Fahrtende/status='unterwegs' erlaubt).
insert into public.auftraege (
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id
) values (
'21000000-0000-0000-0000-000000000002',
'21111111-1111-1111-1111-111111111111',
@ -43,13 +45,14 @@ insert into public.auftraege (
'aa555555-5555-5555-5555-555555555555',
'zugewiesen',
'ff666666-6666-6666-6666-666666666666',
1000
1000,
'00000000-0000-0000-0000-00000000f001'
);
-- Auftrag C: Fahrer "zwei", status 'unterwegs' -- aus Sicht von Fahrer
-- "eins" ein fremder Auftrag.
insert into public.auftraege (
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km
id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id
) values (
'21000000-0000-0000-0000-000000000003',
'21111111-1111-1111-1111-111111111111',
@ -58,7 +61,8 @@ insert into public.auftraege (
'aa555555-5555-5555-5555-555555555555',
'unterwegs',
'ff777777-7777-7777-7777-777777777777',
500
500,
'00000000-0000-0000-0000-00000000f001'
);
insert into storage.buckets (id, name, public) values ('auftrag-unterschriften', 'auftrag-unterschriften', false)

View File

@ -3,14 +3,15 @@ select plan(5);
insert into auth.users (id, email) values
('a1111111-1111-1111-1111-111111111111', 'admin@auftragsnummer.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111';
insert into public.orte (id, adresse, ansprechpartner) values
('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'),
('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel');
insert into public.orte (id, adresse, ansprechpartner, firma_id) values
('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'),
('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001');
insert into public.fahrzeuge (id, kennzeichen) values
('f0000000-0000-0000-0000-000000000001', 'M-AB 123');
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001');
set local role authenticated;
set local request.jwt.claims to '{"sub": "a1111111-1111-1111-1111-111111111111", "role": "authenticated"}';
@ -55,7 +56,7 @@ select throws_ok(
('30000000-0000-0000-0000-000000000004', '01111111-1111-1111-1111-111111111111', '02222222-2222-2222-2222-222222222222', 'f0000000-0000-0000-0000-000000000001', 'a1111111-1111-1111-1111-111111111111', 'MEINE-EIGENE-NUMMER')
$$,
'23505',
'duplicate key value violates unique constraint "auftraege_auftragsnummer_key"',
'duplicate key value violates unique constraint "auftraege_firma_auftragsnummer_key"',
'Doppelte, manuell eingegebene Auftragsnummer wird durch den Unique-Constraint abgelehnt'
);

View File

@ -8,27 +8,29 @@ insert into auth.users (id, email) values
('f1a00000-0000-0000-0000-000000000004', 'fahrer-zwei-fin@test.local'),
('f1a00000-0000-0000-0000-000000000005', 'readonly-fin@test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001';
update public.profiles set role = 'admin' where id = 'f1a00000-0000-0000-0000-000000000001';
update public.profiles set role = 'disponent' where id = 'f1a00000-0000-0000-0000-000000000002';
update public.profiles set role = 'fahrer' where id = 'f1a00000-0000-0000-0000-000000000003';
update public.profiles set role = 'fahrer' where id = 'f1a00000-0000-0000-0000-000000000004';
-- readonly bleibt auf dem Trigger-Default.
insert into public.orte (id, adresse, ansprechpartner) values
('f1b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster'),
('f1b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel');
insert into public.orte (id, adresse, ansprechpartner, firma_id) values
('f1b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'),
('f1b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001');
-- F1: nur Kennzeichen (FIN wird nachgetragen)
-- F2: FIN A hinterlegt
-- F3: nur Kennzeichen (Fahrer gibt FIN von F2 ein)
insert into public.fahrzeuge (id, kennzeichen, fin) values
('f1c00000-0000-0000-0000-000000000001', 'M-FN 001', null),
('f1c00000-0000-0000-0000-000000000002', 'M-FN 002', 'WDB9066331S123456'),
('f1c00000-0000-0000-0000-000000000003', 'M-FN 003', null);
insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values
('f1c00000-0000-0000-0000-000000000001', 'M-FN 001', null, '00000000-0000-0000-0000-00000000f001'),
('f1c00000-0000-0000-0000-000000000002', 'M-FN 002', 'WDB9066331S123456', '00000000-0000-0000-0000-00000000f001'),
('f1c00000-0000-0000-0000-000000000003', 'M-FN 003', null, '00000000-0000-0000-0000-00000000f001');
-- 1) Format-Check
select throws_ok(
$$ insert into public.fahrzeuge (kennzeichen, fin) values ('M-FN 010', 'WDB906633IS12345X') $$,
$$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values ('M-FN 010', 'WDB906633IS12345X', '00000000-0000-0000-0000-00000000f001') $$,
'23514',
null,
'FIN mit I wird vom Format-Check abgelehnt'
@ -36,7 +38,7 @@ select throws_ok(
-- 2) Kennzeichen oder FIN
select throws_ok(
$$ insert into public.fahrzeuge (kennzeichen, fin) values (null, null) $$,
$$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values (null, null, '00000000-0000-0000-0000-00000000f001') $$,
'23514',
null,
'Fahrzeug ohne Kennzeichen und ohne FIN wird abgelehnt'
@ -44,27 +46,27 @@ select throws_ok(
-- 3) Nur FIN ist erlaubt
select lives_ok(
$$ insert into public.fahrzeuge (id, kennzeichen, fin) values ('f1c00000-0000-0000-0000-000000000004', null, 'VF1RFB00X12345678') $$,
$$ insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values ('f1c00000-0000-0000-0000-000000000004', null, 'VF1RFB00X12345678', '00000000-0000-0000-0000-00000000f001') $$,
'Fahrzeug nur mit FIN kann angelegt werden'
);
-- 4) FIN eindeutig
select throws_ok(
$$ insert into public.fahrzeuge (kennzeichen, fin) values ('M-FN 011', 'WDB9066331S123456') $$,
$$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values ('M-FN 011', 'WDB9066331S123456', '00000000-0000-0000-0000-00000000f001') $$,
'23505',
null,
'Doppelte FIN wird abgelehnt'
);
-- Auftraege (als postgres angelegt)
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km) values
('f1d00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000001', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null),
('f1d00000-0000-0000-0000-000000000002', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null),
('f1d00000-0000-0000-0000-000000000003', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null),
('f1d00000-0000-0000-0000-000000000004', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000003', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null),
('f1d00000-0000-0000-0000-000000000005', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000004', null),
('f1d00000-0000-0000-0000-000000000006', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'unterwegs', 'f1a00000-0000-0000-0000-000000000003', 1000),
('f1d00000-0000-0000-0000-000000000007', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000004', 'f1a00000-0000-0000-0000-000000000001', 'offen', null, null);
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id) values
('f1d00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000001', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'),
('f1d00000-0000-0000-0000-000000000002', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'),
('f1d00000-0000-0000-0000-000000000003', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'),
('f1d00000-0000-0000-0000-000000000004', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000003', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'),
('f1d00000-0000-0000-0000-000000000005', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000004', null, '00000000-0000-0000-0000-00000000f001'),
('f1d00000-0000-0000-0000-000000000006', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'unterwegs', 'f1a00000-0000-0000-0000-000000000003', 1000, '00000000-0000-0000-0000-00000000f001'),
('f1d00000-0000-0000-0000-000000000007', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000004', 'f1a00000-0000-0000-0000-000000000001', 'offen', null, null, '00000000-0000-0000-0000-00000000f001');
-- 5) Outbox: Fahrzeug ohne Kennzeichen -> FIN im Payload
select is(

View File

@ -0,0 +1,34 @@
begin;
select plan(4);
insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B');
select throws_ok(
$$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f001/logo-1.png'
where id = '00000000-0000-0000-0000-00000000f002' $$,
'23514', null,
'Logo-Pfad im Ordner einer fremden Firma wird abgelehnt'
);
select throws_ok(
$$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/../00000000-0000-0000-0000-00000000f001/logo-1.png'
where id = '00000000-0000-0000-0000-00000000f002' $$,
'23514', null,
'Pfad mit ../ in den Ordner einer fremden Firma wird abgelehnt'
);
select throws_ok(
$$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/x.png'
where id = '00000000-0000-0000-0000-00000000f002' $$,
'23514', null,
'Pfad im eigenen Ordner, aber nicht im Format logo-<zahl>.<endung>, wird abgelehnt'
);
select lives_ok(
$$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/logo-1.png'
where id = '00000000-0000-0000-0000-00000000f002' $$,
'Logo-Pfad im eigenen Firmenordner ist erlaubt'
);
select * from finish();
rollback;

View File

@ -0,0 +1,147 @@
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_empty(
$$ update public.orte set adresse = 'x' where id = 'a0000000-0000-0000-0000-0000000000c1' returning 1 $$,
'Admin B kann keinen Ort von A aendern');
select is_empty(
$$ update public.auftraege set status = 'storniert' where id = 'a0000000-0000-0000-0000-0000000000e2' returning 1 $$,
'Admin B kann keinen Auftrag von A aendern');
select is_empty(
$$ update public.profiles set name = 'x' where id = 'a0000000-0000-0000-0000-0000000000a3' returning 1 $$,
'Admin B kann kein Profil von A aendern');
select is_empty(
$$ update public.firmen set name = 'x' where id = '00000000-0000-0000-0000-00000000f001' returning 1 $$,
'Admin B kann Firma A nicht umbenennen');
select isnt_empty(
$$ update public.firmen set name = 'Firma B neu' where id = '00000000-0000-0000-0000-00000000f002' returning 1 $$,
'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_empty(
$$ update public.auftraege set zugewiesen_an = 'b0000000-0000-0000-0000-0000000000b3', status = 'zugewiesen' where id = 'a0000000-0000-0000-0000-0000000000e2' returning 1 $$,
'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;

View File

@ -0,0 +1,223 @@
begin;
select plan(20);
-- 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'
);
-- 14a) FIN ist pro Firma eindeutig: gleiche FIN in f001 und f002 ist erlaubt
update public.fahrzeuge set fin = 'WVWZZZ1KZAW000002' where id = 'a0000000-0000-0000-0000-0000000000d1';
select lives_ok(
$$ update public.fahrzeuge set fin = 'WVWZZZ1KZAW000002' where id = 'b0000000-0000-0000-0000-0000000000d1' $$,
'Gleiche FIN in einer anderen Firma ist erlaubt'
);
-- 14b) doppelte FIN in derselben Firma nicht
select throws_ok(
$$ insert into public.fahrzeuge (kennzeichen, fin, firma_id)
values ('MT-AB 9', 'WVWZZZ1KZAW000002', '00000000-0000-0000-0000-00000000f001') $$,
'23505', null,
'Doppelte FIN in derselben Firma scheitert'
);
-- 14c) fin_bei_fahrtbeginn sucht nur in der eigenen Firma: eine FIN, die nur in
-- Firma B existiert, wird in Firma A nachgetragen und nicht als abweichend gemeldet.
insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values
('b0000000-0000-0000-0000-0000000000d2', 'MT-BB 2', 'WDB9066331S555555', '00000000-0000-0000-0000-00000000f002');
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('a0000000-0000-0000-0000-0000000000d2', 'MT-AB 2', '00000000-0000-0000-0000-00000000f001');
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, zugewiesen_an, status, firma_id) values
('a0000000-0000-0000-0000-0000000000e2', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1',
'a0000000-0000-0000-0000-0000000000d2', 'a0000000-0000-0000-0000-0000000000a1',
'a0000000-0000-0000-0000-0000000000a3', 'zugewiesen', '00000000-0000-0000-0000-00000000f001');
set local role authenticated;
set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a3", "role": "authenticated"}';
select is(
public.fin_bei_fahrtbeginn('a0000000-0000-0000-0000-0000000000e2', 'WDB9066331S555555'),
'nachgetragen'::public.app_fin_abgleich,
'FIN-Abgleich ignoriert FINs fremder Firmen (nachgetragen statt abweichend)'
);
reset role;
reset request.jwt.claims;
select is(
(select fin from public.fahrzeuge where id = 'a0000000-0000-0000-0000-0000000000d2'),
'WDB9066331S555555',
'FIN steht am Fahrzeug der eigenen Firma'
);
-- 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;

View File

@ -5,15 +5,17 @@ insert into auth.users (id, email) values
('c1111111-1111-1111-1111-111111111111', 'admin-outbox@auftraege.test.local'),
('c2222222-2222-2222-2222-222222222222', 'disponent-outbox@auftraege.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001';
update public.profiles set role = 'admin' where id = 'c1111111-1111-1111-1111-111111111111';
update public.profiles set role = 'disponent' where id = 'c2222222-2222-2222-2222-222222222222';
insert into public.orte (id, adresse, ansprechpartner) values
('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A'),
('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B');
insert into public.orte (id, adresse, ansprechpartner, firma_id) values
('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A', '00000000-0000-0000-0000-00000000f001'),
('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B', '00000000-0000-0000-0000-00000000f001');
insert into public.fahrzeuge (id, kennzeichen) values
('c3333333-0000-0000-0000-000000000001', 'S-WA 42');
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('c3333333-0000-0000-0000-000000000001', 'S-WA 42', '00000000-0000-0000-0000-00000000f001');
set local role authenticated;
set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}';
@ -105,20 +107,20 @@ delete from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a';
insert into public.notification_outbox
(id, event_type, status, payload, naechster_versuch_ab, updated_at)
(id, event_type, status, payload, naechster_versuch_ab, updated_at, firma_id)
values
-- faellig: pending, Zeitpunkt erreicht
('c5000000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb,
now() - interval '1 minute', now()),
now() - interval '1 minute', now(), '00000000-0000-0000-0000-00000000f001'),
-- nicht faellig: failed, Backoff noch in der Zukunft
('c5000000-0000-0000-0000-000000000002', 'auftrag_erstellt', 'failed', '{}'::jsonb,
now() + interval '1 hour', now()),
now() + interval '1 hour', now(), '00000000-0000-0000-0000-00000000f001'),
-- nicht reclaimt: sending, erst vor 2 Minuten uebernommen
('c5000000-0000-0000-0000-000000000003', 'auftrag_erstellt', 'sending', '{}'::jsonb,
now(), now() - interval '2 minutes'),
now(), now() - interval '2 minutes', '00000000-0000-0000-0000-00000000f001'),
-- reclaimt: sending, seit 20 Minuten haengengeblieben
('c5000000-0000-0000-0000-000000000004', 'auftrag_erstellt', 'sending', '{}'::jsonb,
now(), now() - interval '20 minutes');
now(), now() - interval '20 minutes', '00000000-0000-0000-0000-00000000f001');
select results_eq(
$$ select id::text from public.claim_notification_batch(10, array['auftrag_erstellt']) order by id $$,
@ -135,7 +137,7 @@ set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222",
-- wuerde die Beschreibung als erwartete Fehlermeldung interpretieren. Geprueft wird
-- nur, dass der INSERT in SQLSTATE 42501 (RLS: keine INSERT-Policy) laeuft.
select throws_ok(
$$ insert into public.notification_outbox (event_type, payload) values ('x', '{}'::jsonb) $$,
$$ insert into public.notification_outbox (event_type, payload, firma_id) values ('x', '{}'::jsonb, '00000000-0000-0000-0000-00000000f001') $$,
'42501'
);

View File

@ -7,6 +7,7 @@ insert into auth.users (id, email) values
('33333333-3333-3333-3333-333333333333', 'fahrer-a@test.local'),
('44444444-4444-4444-4444-444444444444', 'fahrer-b@test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111';
update public.profiles set role = 'disponent' where id = '22222222-2222-2222-2222-222222222222';
update public.profiles set role = 'fahrer' where id = '33333333-3333-3333-3333-333333333333';

View File

@ -7,6 +7,7 @@ insert into auth.users (id, email) values
('f3333333-3333-3333-3333-333333333333', 'fahrer@stammdaten.test.local'),
('05555555-5555-5555-5555-555555555555', 'readonly@stammdaten.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111';
update public.profiles set role = 'disponent' where id = 'd2222222-2222-2222-2222-222222222222';
update public.profiles set role = 'fahrer' where id = 'f3333333-3333-3333-3333-333333333333';

View File

@ -5,6 +5,7 @@ insert into auth.users (id, email) values
('11111111-1111-1111-1111-111111111111', 'admin@test.local'),
('22222222-2222-2222-2222-222222222222', 'fahrer@test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111';
update public.profiles set role = 'fahrer' where id = '22222222-2222-2222-2222-222222222222';
@ -80,6 +81,9 @@ select is(
-- Admin-Update zu 'disponent' geaendert).
insert into auth.users (id, email) values
('44444444-4444-4444-4444-444444444444', 'fahrer2@test.local');
-- Firmenzuordnung neuer Fixture-Nutzer: nur ohne JWT-Kontext erlaubt (Trigger firma_id_unveraenderlich)
reset request.jwt.claims;
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'fahrer' where id = '44444444-4444-4444-4444-444444444444';
set local role authenticated;

View File

@ -7,23 +7,24 @@ insert into auth.users (id, email, raw_user_meta_data) values
('e5a00000-0000-0000-0000-000000000001', 'dispo-mail@test.local', '{}'::jsonb),
('e5a00000-0000-0000-0000-000000000002', null, '{"name": "Dispo ohne Mail"}'::jsonb);
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'disponent' where id = 'e5a00000-0000-0000-0000-000000000001';
update public.profiles set role = 'disponent' where id = 'e5a00000-0000-0000-0000-000000000002';
insert into public.orte (id, adresse, ansprechpartner) values
('e5b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster'),
('e5b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel');
insert into public.orte (id, adresse, ansprechpartner, firma_id) values
('e5b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'),
('e5b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001');
insert into public.fahrzeuge (id, kennzeichen) values
('e5c00000-0000-0000-0000-000000000001', 'M-ML 001');
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('e5c00000-0000-0000-0000-000000000001', 'M-ML 001', '00000000-0000-0000-0000-00000000f001');
-- A: Ersteller mit E-Mail, unterwegs
-- B: Ersteller ohne E-Mail, unterwegs
-- C: Ersteller mit E-Mail, zugewiesen (wird nur storniert)
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, start_km) values
('e5d00000-0000-0000-0000-00000000000a', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'unterwegs', 100),
('e5d00000-0000-0000-0000-00000000000b', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000002', 'unterwegs', 100),
('e5d00000-0000-0000-0000-00000000000c', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'zugewiesen', null);
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, start_km, firma_id) values
('e5d00000-0000-0000-0000-00000000000a', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'unterwegs', 100, '00000000-0000-0000-0000-00000000f001'),
('e5d00000-0000-0000-0000-00000000000b', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000002', 'unterwegs', 100, '00000000-0000-0000-0000-00000000f001'),
('e5d00000-0000-0000-0000-00000000000c', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'zugewiesen', null, '00000000-0000-0000-0000-00000000f001');
-- 1) Abschluss legt genau eine Zeile an
update public.auftraege
@ -88,9 +89,9 @@ select is(
-- 6) claim_notification_batch claimt nur die angefragten Ereignis-Arten
delete from public.notification_outbox;
insert into public.notification_outbox (id, event_type, status, payload, naechster_versuch_ab) values
('e5e00000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, now() - interval '1 minute'),
('e5e00000-0000-0000-0000-000000000002', 'protokoll_abgeschlossen', 'pending', '{}'::jsonb, now() - interval '1 minute');
insert into public.notification_outbox (id, event_type, status, payload, naechster_versuch_ab, firma_id) values
('e5e00000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, now() - interval '1 minute', '00000000-0000-0000-0000-00000000f001'),
('e5e00000-0000-0000-0000-000000000002', 'protokoll_abgeschlossen', 'pending', '{}'::jsonb, now() - interval '1 minute', '00000000-0000-0000-0000-00000000f001');
select results_eq(
$$ select id::text from public.claim_notification_batch(10, array['protokoll_abgeschlossen']) $$,

View File

@ -3,14 +3,15 @@ select plan(5);
insert into auth.users (id, email) values
('a1111111-1111-1111-1111-111111111111', 'admin@zeitplanung.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null;
update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111';
insert into public.orte (id, adresse, ansprechpartner) values
('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'),
('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel');
insert into public.orte (id, adresse, ansprechpartner, firma_id) values
('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'),
('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001');
insert into public.fahrzeuge (id, kennzeichen) values
('f0000000-0000-0000-0000-000000000001', 'M-AB 123');
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001');
set local role authenticated;
set local request.jwt.claims to '{"sub": "a1111111-1111-1111-1111-111111111111", "role": "authenticated"}';

View File

@ -18,7 +18,6 @@ SUPABASE_SERVICE_ROLE_KEY=
WHATSAPP_ACCESS_TOKEN=
WHATSAPP_PHONE_NUMBER_ID=
# Feste Empfaenger-Sammelnummer, E.164 ohne fuehrendes "+" (z.B. 4915112345678).
WHATSAPP_RECIPIENT=
# Name + Sprache des genehmigten Message-Templates.
WHATSAPP_TEMPLATE_NAME=neuer_auftrag
WHATSAPP_TEMPLATE_LANG=de
@ -28,3 +27,8 @@ WHATSAPP_GRAPH_VERSION=
# /api/notifications/dispatch. MUSS mit dem DB-Setting
# app.notification_dispatch_secret uebereinstimmen (siehe unten).
NOTIFICATION_DISPATCH_SECRET=
# --- Uebergabeprotokoll per E-Mail (SMTP) ---
# 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=

15
web/app/abmelden/route.ts Normal file
View File

@ -0,0 +1,15 @@
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<Response> {
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);
}

View File

@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/supabase/admin", () => ({ createAdminClient: vi.fn(() => ({})) }));
vi.mock("@/lib/notifications/config", () => ({ getWhatsAppConfig: vi.fn() }));
vi.mock("@/lib/notifications/dispatch", () => ({ verarbeiteOutbox: vi.fn() }));
vi.mock("@/lib/notifications/email-config", () => ({ getEmailConfig: vi.fn() }));
vi.mock("@/lib/notifications/handler", () => ({
whatsappHandler: vi.fn(() => "wa-handler"),
protokollMailHandler: vi.fn(() => "mail-handler"),
@ -11,13 +10,11 @@ vi.mock("@/lib/notifications/handler", () => ({
import { getWhatsAppConfig } from "@/lib/notifications/config";
import { verarbeiteOutbox } from "@/lib/notifications/dispatch";
import { getEmailConfig } from "@/lib/notifications/email-config";
import { POST } from "./route";
const CFG = {
accessToken: "tok",
phoneNumberId: "PN1",
recipient: "4915100000000",
templateName: "neuer_auftrag",
templateLang: "de",
graphVersion: "v21.0",
@ -35,7 +32,6 @@ beforeEach(() => {
altSecret = process.env.NOTIFICATION_DISPATCH_SECRET;
process.env.NOTIFICATION_DISPATCH_SECRET = "geheim";
vi.mocked(getWhatsAppConfig).mockReset();
vi.mocked(getEmailConfig).mockReset();
vi.mocked(verarbeiteOutbox).mockReset();
fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {});
warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
@ -78,18 +74,8 @@ describe("POST /api/notifications/dispatch", () => {
expect(await res.json()).toEqual({ fehler: "Unauthorized" });
});
it("antwortet 200 uebersprungen, wenn kein Kanal konfiguriert ist", async () => {
vi.mocked(getWhatsAppConfig).mockReturnValue(null);
vi.mocked(getEmailConfig).mockReturnValue(null);
const res = await POST(req({ Authorization: "Bearer geheim" }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ verarbeitet: 0, uebersprungen: true });
expect(verarbeiteOutbox).not.toHaveBeenCalled();
});
it("ruft verarbeiteOutbox und gibt dessen Ergebnis als 200 zurueck", async () => {
vi.mocked(getWhatsAppConfig).mockReturnValue(CFG);
vi.mocked(getEmailConfig).mockReturnValue(null);
vi.mocked(verarbeiteOutbox).mockResolvedValue({
verarbeitet: 2,
gesendet: 1,
@ -100,12 +86,14 @@ describe("POST /api/notifications/dispatch", () => {
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ verarbeitet: 2, gesendet: 1, fehlgeschlagen: 1, tot: 0 });
expect(verarbeiteOutbox).toHaveBeenCalledOnce();
expect(verarbeiteOutbox).toHaveBeenCalledWith({}, { auftrag_erstellt: "wa-handler" });
expect(verarbeiteOutbox).toHaveBeenCalledWith({}, {
protokoll_abgeschlossen: "mail-handler",
auftrag_erstellt: "wa-handler",
});
});
it("verarbeitet Protokoll-Mails auch ohne WhatsApp-Config", async () => {
vi.mocked(getWhatsAppConfig).mockReturnValue(null);
vi.mocked(getEmailConfig).mockReturnValue({ host: "smtp", port: 587, secure: false, from: "x@y.de", auth: null });
vi.mocked(verarbeiteOutbox).mockResolvedValue({ verarbeitet: 1, gesendet: 1, fehlgeschlagen: 0, tot: 0 });
const res = await POST(req({ Authorization: "Bearer geheim" }));

View File

@ -2,7 +2,6 @@ import { NextResponse } from "next/server";
import { timingSafeEqual } from "node:crypto";
import { createAdminClient } from "@/lib/supabase/admin";
import { getWhatsAppConfig } from "@/lib/notifications/config";
import { getEmailConfig } from "@/lib/notifications/email-config";
import { verarbeiteOutbox, type Handler } from "@/lib/notifications/dispatch";
import { protokollMailHandler, whatsappHandler } from "@/lib/notifications/handler";
@ -38,20 +37,14 @@ export async function POST(request: Request): Promise<Response> {
const handler: Record<string, Handler> = {};
const waCfg = getWhatsAppConfig();
const mailCfg = getEmailConfig();
if (!waCfg && !mailCfg) {
console.warn("[notifications] kein Kanal konfiguriert – Outbox wird nicht verarbeitet");
return NextResponse.json({ verarbeitet: 0, uebersprungen: true });
}
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(waCfg);
}
if (mailCfg) {
handler.protokoll_abgeschlossen = protokollMailHandler(admin, mailCfg);
handler.auftrag_erstellt = whatsappHandler(admin, waCfg);
}
const ergebnis = await verarbeiteOutbox(admin, handler);
return NextResponse.json(ergebnis);

72
web/app/firma/actions.ts Normal file
View File

@ -0,0 +1,72 @@
"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<ActionResult> {
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<ActionResult> {
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<ActionResult> {
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 };
}

View File

@ -0,0 +1,27 @@
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<Response> {
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,
},
});
}

47
web/app/firma/page.tsx Normal file
View File

@ -0,0 +1,47 @@
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 (
<div className="mx-auto flex max-w-2xl flex-col gap-6 p-4 md:p-8">
<h1 className="text-xl font-semibold text-asphalt-grey">Firma</h1>
<Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">Allgemein</h2>
<FirmaEinstellungenForm firma={kontext.firma} />
</Card>
<Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">Logo</h2>
<LogoForm hatLogo={Boolean(kontext.firma.logo_pfad)} />
</Card>
<Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">E-Mail-Versand (SMTP)</h2>
<SmtpForm smtp={smtp} />
</Card>
</div>
);
}

View File

@ -0,0 +1,120 @@
"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 {
SMTP_ZIEL_NICHT_ERLAUBT,
SmtpZielFehler,
firmenSmtpZuConfig,
ladeFirmenSmtp,
pinneSmtpZiel,
validateSmtpEingabe,
} from "@/lib/firma/smtp";
import { verschluessele } from "@/lib/firma/smtp-crypto";
import { pruefeSmtpZiel } from "@/lib/firma/smtp-ziel";
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<ActionResult> {
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"),
},
bestehend
);
if (!validation.valid) return { success: false, error: validation.error };
const w = validation.werte;
const ziel = await pruefeSmtpZiel(w.host);
if (!ziel.ok) return { success: false, error: `${SMTP_ZIEL_NICHT_ERLAUBT}.` };
let passwortVerschluesselt: string | null = null;
if (w.benutzer) {
try {
passwortVerschluesselt = w.neuesPasswort
? verschluessele(w.neuesPasswort)
: w.passwortBehalten
? (bestehend?.passwort_verschluesselt ?? null)
: 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<ActionResult> {
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<ActionResult> {
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 = await pinneSmtpZiel(firmenSmtpZuConfig(zeile));
} catch (fehler) {
if (fehler instanceof SmtpZielFehler) return { success: false, error: `${SMTP_ZIEL_NICHT_ERLAUBT}.` };
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: [],
});
if (ergebnis.ok) return { success: true };
// Kein Rohtext an den Admin: Fehlermeldungen koennten interne Ziele verraten.
console.error("Testmail fehlgeschlagen:", ergebnis.fehler);
return { success: false, error: "Verbindung zum SMTP-Server fehlgeschlagen." };
}

View File

@ -1,8 +1,11 @@
import Image from "next/image";
import Link from "next/link";
import { redirect } from "next/navigation";
import { Inter } from "next/font/google";
import "./globals.css";
import { loadProfile } from "@/lib/auth/profile";
import { ladeEigeneFirma } from "@/lib/firma/eigene-firma";
import { themeVariablen } from "@/lib/firma/farben";
import { FirmenLogo } from "@/components/FirmenLogo";
import { NavLinks } from "@/components/NavLinks";
import { LogoutButton } from "@/components/LogoutButton";
import { MobileNav } from "@/components/MobileNav";
@ -17,6 +20,12 @@ export default async function RootLayout({
children,
}: Readonly<{ children: React.ReactNode }>) {
const result = await loadProfile();
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;
if (result.status === "missing-profile") {
return (
@ -36,12 +45,12 @@ export default async function RootLayout({
}
return (
<html lang="de" className={inter.variable}>
<html lang="de" className={inter.variable} style={themeStyle}>
<body className="flex min-h-screen flex-col font-sans">
{result.status === "ok" && (
<header className="flex h-16 items-center justify-between border-b border-aluminium-grey px-4 lg:px-8">
<Link href="/dashboard" className="flex items-center">
<Image src="/brand/widmann-logo.svg" alt="Widmann" width={140} height={21} priority />
<Link href={result.profile.role === "superadmin" ? "/plattform" : "/dashboard"} className="flex items-center">
<FirmenLogo firma={firma} />
</Link>
<div className="hidden items-center gap-6 lg:flex">

View File

@ -4,9 +4,12 @@ import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { createAdminClient } from "@/lib/supabase/admin";
import { PASSWORT_AENDERN_PFAD, hatPasswortAenderPflicht } from "@/lib/auth/passwort";
import { pruefeFirmenzugang } from "@/lib/firma/queries";
import { FIRMA_GESPERRT } from "@/lib/firma/eigene-firma";
import { validateLogin } from "@/lib/validate-login";
const LOGIN_FEHLER = "E-Mail oder Passwort ist falsch.";
const LOGIN_NICHT_MOEGLICH = "Anmeldung derzeit nicht möglich. Bitte später erneut versuchen.";
export async function login(formData: FormData): Promise<void> {
const validation = validateLogin({
@ -57,7 +60,25 @@ export async function login(formData: FormData): Promise<void> {
redirect(`/login?error=${encodeURIComponent(LOGIN_FEHLER)}`);
}
redirect(hatPasswortAenderPflicht(data.user) ? PASSWORT_AENDERN_PFAD : "/dashboard");
let zugang: Awaited<ReturnType<typeof pruefeFirmenzugang>> | null = null;
try {
zugang = await pruefeFirmenzugang(supabase, data.user.id);
} catch (e) {
console.error("Firmenzugang beim Login nicht pruefbar:", e);
}
if (zugang === null) {
await supabase.auth.signOut();
redirect(`/login?error=${encodeURIComponent(LOGIN_NICHT_MOEGLICH)}`);
}
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");
}
export async function logout(): Promise<void> {

View File

@ -4,6 +4,7 @@ import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { createAdminClient } from "@/lib/supabase/admin";
import { loadProfile } from "@/lib/auth/profile";
import { ladeAdminKontext } from "@/lib/firma/admin-kontext";
import { canManageUsers } from "@/lib/auth/roles";
import {
validateNutzerErstellen,
@ -13,15 +14,19 @@ import {
import { validatePasswort } from "@/lib/auth/passwort";
import { validateNutzerDetails, leseDetailsAusFormData } from "@/lib/nutzerverwaltung/details";
import { speichereDetails } from "@/lib/nutzerverwaltung/details-queries";
import { legeNutzerInFirmaAn } from "@/lib/nutzerverwaltung/nutzer-anlegen";
import { pruefeZielNutzer } from "@/lib/nutzerverwaltung/ziel-pruefen";
export type ActionResult = { success: true } | { success: false; error: string };
const USERNAME_VERGEBEN = "Dieser Benutzername ist bereits vergeben.";
const NICHT_GEFUNDEN = "Nutzer nicht gefunden.";
export async function erstelleNutzer(formData: FormData): Promise<void> {
const profileResult = await loadProfile();
if (profileResult.status !== "ok" || !canManageUsers(profileResult.profile.role)) {
redirect(`/nutzerverwaltung?error=${encodeURIComponent("Nur Admin darf Nutzer anlegen.")}`);
// Aktive Firma ueber den RLS-Client; deaktivierte Firmen koennen keine Nutzer anlegen.
const kontext = await ladeAdminKontext();
if (!kontext.ok) {
redirect(`/nutzerverwaltung?error=${encodeURIComponent(kontext.error)}`);
}
const validation = validateNutzerErstellen({
@ -35,33 +40,19 @@ export async function erstelleNutzer(formData: FormData): Promise<void> {
redirect(`/nutzerverwaltung?error=${encodeURIComponent(validation.error)}`);
}
const adminClient = createAdminClient();
const { data: erstellt, error: erstellFehler } = await adminClient.auth.admin.createUser({
const ergebnis = await legeNutzerInFirmaAn(createAdminClient(), {
firmaId: kontext.firma.id,
name: validation.name,
email: validation.email,
password: validation.passwort,
email_confirm: true,
user_metadata: { name: validation.name },
app_metadata: { must_change_password: true },
passwort: validation.passwort,
rolle: validation.rolle as "admin" | "disponent" | "fahrer" | "readonly",
username: validation.username,
});
if (erstellFehler || !erstellt.user) {
redirect(
`/nutzerverwaltung?error=${encodeURIComponent(`Nutzer anlegen fehlgeschlagen: ${erstellFehler?.message ?? "Unbekannter Fehler"}`)}`
);
if (!ergebnis.ok) {
redirect(`/nutzerverwaltung?error=${encodeURIComponent(ergebnis.fehler)}`);
}
const supabase = await createClient();
const { error: profilFehler } = await supabase
.from("profiles")
.update({ role: validation.rolle, username: validation.username })
.eq("id", erstellt.user.id);
if (profilFehler) {
const nachricht =
profilFehler.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, Rolle/Benutzername konnten aber nicht gesetzt werden: ${profilFehler.message}`;
redirect(`/nutzerverwaltung?error=${encodeURIComponent(nachricht)}`);
if (ergebnis.usernameHinweis) {
redirect(`/nutzerverwaltung?error=${encodeURIComponent(ergebnis.usernameHinweis)}`);
}
redirect("/nutzerverwaltung");
@ -89,9 +80,9 @@ export async function aktualisiereNutzer(nutzerId: string, formData: FormData):
}
const supabase = await createClient();
const { data: aktuellesProfil } = await supabase.from("profiles").select("role").eq("id", nutzerId).single();
const aktuellesProfil = await pruefeZielNutzer(supabase, nutzerId);
if (!aktuellesProfil) {
return { success: false, error: "Nutzer nicht gefunden." };
return { success: false, error: NICHT_GEFUNDEN };
}
if (istSelbstschutzVerletzt(profileResult.profile.id, nutzerId) && validation.rolle !== aktuellesProfil.role) {
@ -146,6 +137,11 @@ export async function sperreNutzer(nutzerId: string): Promise<ActionResult> {
return { success: false, error: "Der eigene Account kann nicht selbst gesperrt werden." };
}
const supabase = await createClient();
if (!(await pruefeZielNutzer(supabase, nutzerId))) {
return { success: false, error: NICHT_GEFUNDEN };
}
const adminClient = createAdminClient();
const { error } = await adminClient.auth.admin.updateUserById(nutzerId, { ban_duration: "876000h" });
if (error) {
@ -161,6 +157,11 @@ export async function entsperreNutzer(nutzerId: string): Promise<ActionResult> {
return { success: false, error: "Nur Admin darf Nutzer entsperren." };
}
const supabase = await createClient();
if (!(await pruefeZielNutzer(supabase, nutzerId))) {
return { success: false, error: NICHT_GEFUNDEN };
}
const adminClient = createAdminClient();
const { error } = await adminClient.auth.admin.updateUserById(nutzerId, { ban_duration: "none" });
if (error) {
@ -185,6 +186,11 @@ export async function setzePasswort(nutzerId: string, formData: FormData): Promi
return { success: false, error: validation.error };
}
const supabase = await createClient();
if (!(await pruefeZielNutzer(supabase, nutzerId))) {
return { success: false, error: NICHT_GEFUNDEN };
}
const adminClient = createAdminClient();
const { error } = await adminClient.auth.admin.updateUserById(nutzerId, {
password: validation.passwort,

View File

@ -0,0 +1,88 @@
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 (
<div className="mx-auto flex max-w-2xl flex-col gap-6 p-4 md:p-8">
<Link href="/plattform" className="flex min-h-11 items-center text-performance-blue">
← Alle Firmen
</Link>
<h1 className="text-xl font-semibold text-asphalt-grey">{firma.name}</h1>
{error && <Alert>{error}</Alert>}
<Card>
<p className="mb-4 text-asphalt-grey">
Status: {firma.aktiv ? "aktiv" : <span className="text-status-danger">deaktiviert</span>}
</p>
<form action={setzeFirmaAktiv.bind(null, firma.id, !firma.aktiv)}>
<Button type="submit" variant={firma.aktiv ? "destructive" : "primary"}>
{firma.aktiv ? "Firma deaktivieren" : "Firma aktivieren"}
</Button>
</form>
</Card>
<Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">Admins</h2>
<ul className="flex flex-col gap-6">
{admins.map((a) => (
<li key={a.id}>
<p className="font-medium text-asphalt-grey">{a.name}</p>
<p className="mb-2 text-sm text-asphalt-grey">
{a.email ?? "-"} · {a.username}
</p>
<form action={setzeAdminPasswort.bind(null, firma.id, a.id)}>
<FormField label="Neues Passwort" htmlFor={`pw-${a.id}`}>
<input id={`pw-${a.id}`} name="passwort" type="password" required autoComplete="new-password" className={FIELD_CLASSES} />
</FormField>
<Button type="submit" variant="secondary">
Passwort setzen
</Button>
</form>
</li>
))}
</ul>
</Card>
<Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">Weiteren Admin anlegen</h2>
<form action={legeFirmenAdminAn.bind(null, firma.id)}>
<FormField label="Name" htmlFor="admin-name">
<input id="admin-name" name="name" required className={FIELD_CLASSES} />
</FormField>
<FormField label="E-Mail" htmlFor="admin-email">
<input id="admin-email" name="email" type="email" required className={FIELD_CLASSES} />
</FormField>
<FormField label="Startpasswort" htmlFor="admin-passwort">
<input id="admin-passwort" name="passwort" type="password" required autoComplete="new-password" className={FIELD_CLASSES} />
</FormField>
<Button type="submit">Admin anlegen</Button>
</form>
</Card>
</div>
);
}

View File

@ -0,0 +1,91 @@
"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<void> {
if (!pruefeSuperadmin(await loadProfile())) {
redirect("/login");
}
}
export async function legeFirmaAn(formData: FormData): Promise<void> {
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.
const { error: loeschFehler } = await admin.from("firmen").delete().eq("id", firma.id);
if (loeschFehler) {
console.error(`Rollback: Firma ${firma.id} konnte nicht geloescht werden: ${loeschFehler.message}`);
}
zurueck("/plattform", nutzer.fehler);
}
revalidatePath("/plattform");
zurueck(`/plattform/${firma.id}`);
}
export async function setzeFirmaAktiv(firmaId: string, aktiv: boolean): Promise<void> {
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<void> {
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<void> {
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);
}

View File

@ -0,0 +1,61 @@
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 (
<div className="mx-auto flex max-w-2xl flex-col gap-6 p-4 md:p-8">
<h1 className="text-xl font-semibold text-asphalt-grey">Plattform-Verwaltung</h1>
{error && <Alert>{error}</Alert>}
<Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">Firmen</h2>
<ul className="flex flex-col divide-y divide-aluminium-grey">
{firmen.map((f) => (
<li key={f.id}>
<Link href={`/plattform/${f.id}`} className="flex min-h-11 items-center justify-between gap-4 py-2 text-asphalt-grey hover:text-performance-blue">
<span className="font-medium">{f.name}</span>
<span className="text-sm">
{f.nutzerAnzahl} Nutzer · {f.aktiv ? "aktiv" : <span className="text-status-danger">deaktiviert</span>}
</span>
</Link>
</li>
))}
</ul>
</Card>
<Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">Neue Firma anlegen</h2>
<form action={legeFirmaAn}>
<FormField label="Firmenname" htmlFor="neu-firmenname">
<input id="neu-firmenname" name="firmenname" required maxLength={100} className={FIELD_CLASSES} />
</FormField>
<FormField label="Name des ersten Admins" htmlFor="neu-name">
<input id="neu-name" name="name" required className={FIELD_CLASSES} />
</FormField>
<FormField label="E-Mail des Admins" htmlFor="neu-email">
<input id="neu-email" name="email" type="email" required className={FIELD_CLASSES} />
</FormField>
<FormField label="Startpasswort (muss beim ersten Login geändert werden)" htmlFor="neu-passwort">
<input id="neu-passwort" name="passwort" type="password" required autoComplete="new-password" className={FIELD_CLASSES} />
</FormField>
<Button type="submit">Firma anlegen</Button>
</form>
</Card>
</div>
);
}

View File

@ -14,6 +14,10 @@ export async function speichereMeineDaten(formData: FormData): Promise<ActionRes
return { success: false, error: "Bitte neu anmelden." };
}
if (profileResult.profile.role === "superadmin") {
return { success: false, error: "Für den Plattform-Zugang gibt es keine Kontaktdaten." };
}
const validation = validateNutzerDetails(leseDetailsAusFormData(formData));
if (!validation.valid) {
return { success: false, error: validation.error };

View File

@ -10,14 +10,19 @@ export default async function ProfilPage() {
redirect("/login");
}
const details = await ladeDetails(profileResult.profile.id);
const istSuperadmin = profileResult.profile.role === "superadmin";
const details = istSuperadmin ? undefined : await ladeDetails(profileResult.profile.id);
return (
<div className="mx-auto max-w-2xl p-4 md:p-8">
<h1 className="mb-1 text-xl font-semibold text-asphalt-grey">Mein Profil</h1>
<p className="mb-6 text-asphalt-grey">{profileResult.profile.name}</p>
<Card>
{!details ? (
<p className="text-asphalt-grey">Für den Plattform-Zugang gibt es keine Kontaktdaten.</p>
) : (
<ProfilForm details={details} />
)}
</Card>
</div>
);

View File

@ -0,0 +1,22 @@
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 <span className="font-semibold text-night-blue">Plattform-Verwaltung</span>;
}
if (firma.logo_pfad) {
return (
// eslint-disable-next-line @next/next/no-img-element -- Logo kommt aus einer eigenen Route mit Session-Cookie
<img
src={`/firma/logo?v=${encodeURIComponent(firma.logo_pfad)}`}
alt={firma.name}
className="h-8 w-auto max-w-[180px] object-contain"
/>
);
}
if (firma.id === WIDMANN_FIRMA_ID) {
return <Image src="/brand/widmann-logo.svg" alt="Widmann" width={140} height={21} priority />;
}
return <span className="font-semibold text-night-blue">{firma.name}</span>;
}

View File

@ -1,5 +1,5 @@
import Link from "next/link";
import { canManageUsers, kannAuslastungSehen, kannFahrerdetailsSehen, kannStammdatenPflegen, kannZeiterfassungNutzen, type Role } from "@/lib/auth/roles";
import { canManageUsers, istSuperadmin, kannFirmaVerwalten, kannAuslastungSehen, kannFahrerdetailsSehen, kannStammdatenPflegen, kannZeiterfassungNutzen, type Role } from "@/lib/auth/roles";
export function NavLinks({
role,
@ -10,6 +10,22 @@ export function NavLinks({
}) {
const layoutClass = orientation === "horizontal" ? "flex flex-row items-center gap-6" : "flex flex-col gap-4";
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 (
<nav className={layoutClass}>
<Link href="/plattform" className={linkClass}>
Plattform
</Link>
<Link href="/profil" className={linkClass}>
Mein Profil
</Link>
</nav>
);
}
return (
<nav className={layoutClass}>
<Link
@ -72,6 +88,11 @@ export function NavLinks({
Nutzerverwaltung
</Link>
)}
{kannFirmaVerwalten(role) && (
<Link href="/firma" className={linkClass}>
Firma
</Link>
)}
<Link
href="/profil"
className="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"

View File

@ -0,0 +1,93 @@
"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<string | null>(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<HTMLFormElement>) {
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 (
<form onSubmit={handleSubmit}>
{fehler && (
<div className="mb-4">
<Alert>{fehler}</Alert>
</div>
)}
<FormField label="Firmenname" htmlFor="firma-name">
<input id="firma-name" name="name" required maxLength={100} defaultValue={firma.name} className={FIELD_CLASSES} />
</FormField>
<FormField label="WhatsApp-Empfänger für neue Aufträge (optional)" htmlFor="firma-whatsapp">
<input
id="firma-whatsapp"
name="whatsapp_empfaenger"
type="tel"
inputMode="tel"
placeholder="+49 151 2345678"
defaultValue={firma.whatsapp_empfaenger ?? ""}
className={FIELD_CLASSES}
/>
</FormField>
<label className="mb-4 flex min-h-11 items-center gap-3 text-asphalt-grey">
<input
type="checkbox"
name="standard_farben"
checked={standard}
onChange={(e) => setStandard(e.target.checked)}
className="h-5 w-5"
/>
Standardfarben verwenden
</label>
{!standard && (
<div className="grid grid-cols-2 gap-4">
<FormField label="Hauptfarbe" htmlFor="firma-farbe-primaer">
<input
id="firma-farbe-primaer"
name="farbe_primaer"
type="color"
defaultValue={firma.farbe_primaer ?? STANDARD_FARBE_PRIMAER}
className="h-11 w-full rounded-md border border-aluminium-grey"
/>
</FormField>
<FormField label="Dunkle Farbe" htmlFor="firma-farbe-dunkel">
<input
id="firma-farbe-dunkel"
name="farbe_dunkel"
type="color"
defaultValue={firma.farbe_dunkel ?? STANDARD_FARBE_DUNKEL}
className="h-11 w-full rounded-md border border-aluminium-grey"
/>
</FormField>
</div>
)}
<p className="mb-4 text-sm text-asphalt-grey">
Beide Farben brauchen genug Kontrast zu weißer Schrift (mindestens 4,5:1).
</p>
{gespeichert && (
<p role="status" className="mb-4 text-status-success">
Gespeichert.
</p>
)}
<Button type="submit" disabled={isPending}>
Speichern
</Button>
</form>
);
}

View File

@ -0,0 +1,64 @@
"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<string | null>(null);
const [isPending, startTransition] = useTransition();
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
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 (
<form onSubmit={handleSubmit}>
{fehler && (
<div className="mb-4">
<Alert>{fehler}</Alert>
</div>
)}
{hatLogo && (
// eslint-disable-next-line @next/next/no-img-element -- eigene Logo-Route mit Session-Cookie
<img src="/firma/logo" alt="Aktuelles Logo" className="mb-4 h-12 w-auto max-w-[220px] object-contain" />
)}
<FormField label="Logo (PNG, JPG oder SVG, max. 1 MB)" htmlFor="firma-logo">
<input
id="firma-logo"
name="logo"
type="file"
accept="image/png,image/jpeg,image/svg+xml"
required
className={FIELD_CLASSES}
/>
</FormField>
<div className="flex flex-col gap-3">
<Button type="submit" disabled={isPending}>
Logo hochladen
</Button>
{hatLogo && (
<Button type="button" variant="secondary" disabled={isPending} onClick={handleEntfernen}>
Logo entfernen
</Button>
)}
</div>
</form>
);
}

View File

@ -0,0 +1,118 @@
"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<string | null>(null);
const [meldung, setMeldung] = useState<string | null>(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<HTMLFormElement>) {
event.preventDefault();
const formData = new FormData(event.currentTarget);
startTransition(async () => zeige(await speichereSmtp(formData), "Gespeichert."));
}
return (
<form onSubmit={handleSubmit}>
<p className="mb-4 text-sm text-asphalt-grey">
Ohne eigenen Server gehen Protokoll-Mails über den Absender der Plattform raus.
</p>
{fehler && (
<div className="mb-4">
<Alert>{fehler}</Alert>
</div>
)}
<FormField label="SMTP-Server" htmlFor="smtp-host">
<input id="smtp-host" name="host" required defaultValue={smtp?.host ?? ""} className={FIELD_CLASSES} />
</FormField>
<FormField label="Port" htmlFor="smtp-port">
<input
id="smtp-port"
name="port"
type="number"
inputMode="numeric"
min={1}
max={65535}
required
defaultValue={smtp?.port ?? 587}
className={FIELD_CLASSES}
/>
</FormField>
<label className="mb-4 flex min-h-11 items-center gap-3 text-asphalt-grey">
<input type="checkbox" name="secure" defaultChecked={smtp?.secure ?? false} className="h-5 w-5" />
TLS ab Verbindungsbeginn (meist Port 465)
</label>
<FormField label="Benutzer (optional)" htmlFor="smtp-benutzer">
<input
id="smtp-benutzer"
name="benutzer"
autoComplete="off"
defaultValue={smtp?.benutzer ?? ""}
className={FIELD_CLASSES}
/>
</FormField>
<FormField label={smtp?.passwortGesetzt ? "Passwort (gesetzt – leer lassen zum Beibehalten)" : "Passwort"} htmlFor="smtp-passwort">
<input id="smtp-passwort" name="passwort" type="password" autoComplete="new-password" className={FIELD_CLASSES} />
</FormField>
<FormField label="Absenderadresse" htmlFor="smtp-absender">
<input
id="smtp-absender"
name="absender_adresse"
type="email"
required
defaultValue={smtp?.absender_adresse ?? ""}
className={FIELD_CLASSES}
/>
</FormField>
<FormField label="Absendername (optional)" htmlFor="smtp-absender-name">
<input
id="smtp-absender-name"
name="absender_name"
defaultValue={smtp?.absender_name ?? ""}
className={FIELD_CLASSES}
/>
</FormField>
{meldung && (
<p role="status" className="mb-4 text-status-success">
{meldung}
</p>
)}
<div className="flex flex-col gap-3">
<Button type="submit" disabled={isPending}>
Speichern
</Button>
{smtp && (
<>
<Button
type="button"
variant="secondary"
disabled={isPending}
onClick={() => startTransition(async () => zeige(await sendeTestmail(), "Testmail verschickt."))}
>
Testmail senden
</Button>
<Button
type="button"
variant="destructive"
disabled={isPending}
onClick={() => startTransition(async () => zeige(await entferneSmtp(), "SMTP-Einstellungen entfernt."))}
>
SMTP entfernen
</Button>
</>
)}
</div>
</form>
);
}

View File

@ -3,6 +3,9 @@ import type { ProtokollProps } from "./protokoll";
const styles = StyleSheet.create({
page: { padding: 32, fontSize: 11 },
kopf: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 12 },
logo: { height: 32, maxWidth: 160, objectFit: "contain" },
firmenname: { fontSize: 10 },
h1: { fontSize: 16, marginBottom: 12, fontWeight: 700 },
row: { flexDirection: "row", justifyContent: "space-between", marginBottom: 4 },
fotoGrid: { flexDirection: "row", flexWrap: "wrap", gap: 8, marginTop: 12 },
@ -23,7 +26,15 @@ export function ProtokollDocument({ props }: { props: ProtokollProps }) {
return (
<Document>
<Page size="A4" style={styles.page}>
<Text style={styles.h1}>Übergabeprotokoll {props.auftragsnummer}</Text>
<View style={styles.kopf}>
{props.firma.logo ? (
<Image style={styles.logo} src={{ data: props.firma.logo.buffer, format: props.firma.logo.format }} />
) : (
<Text style={[styles.firmenname, { color: props.firma.farbe }]}>{props.firma.name}</Text>
)}
{props.firma.logo && <Text style={styles.firmenname}>{props.firma.name}</Text>}
</View>
<Text style={[styles.h1, { color: props.firma.farbe }]}>Übergabeprotokoll {props.auftragsnummer}</Text>
<View style={styles.row}>
<Text>Fahrzeug</Text>
<Text>{props.fahrzeug}</Text>

View File

@ -1,4 +1,7 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
vi.mock("@react-pdf/renderer", () => ({ renderToBuffer: vi.fn(async () => Buffer.from("%PDF")) }));
vi.mock("./ProtokollDocument", () => ({ ProtokollDocument: () => null }));
import type { SupabaseClient } from "@supabase/supabase-js";
import { erzeugeProtokollPdf } from "./protokoll-pdf";
import { loadAuftragFotoBuffers, loadUnterschriftBuffer } from "./fotos";
@ -56,6 +59,26 @@ describe("erzeugeProtokollPdf (Fehlerunterscheidung)", () => {
expect(await erzeugeProtokollPdf(client, "a1")).toBeNull();
});
it("liefert die Firma des Auftrags mit", async () => {
const client = fakeClient({
auftraege: {
data: {
id: "a1",
status: "abgeschlossen",
auftragsnummer: "26-09-01-0001",
abholort: { adresse: "A", ansprechpartner: "" },
zielort: { adresse: "B", ansprechpartner: "" },
fahrzeug: { id: "f1", kennzeichen: "M-AB 123", fin: null, marke: null, modell: null },
firma: { name: "Firma B", logo_pfad: null, farbe_primaer: "#112233" },
},
error: null,
},
});
const res = await erzeugeProtokollPdf(client, "a1");
expect(res?.firma.name).toBe("Firma B");
expect(res?.firma.farbe_primaer).toBe("#112233");
});
it("wirft bei Lesefehler des Auftrags (kein null)", async () => {
await expect(
erzeugeProtokollPdf(fakeClient({ auftraege: { data: null, error: FEHLER } }), "a1")

View File

@ -6,6 +6,8 @@ import { loadAuftragFotoBuffers, loadUnterschriftBuffer } from "./fotos";
import { buildProtokollBasisdaten } from "./protokoll";
import { ProtokollDocument } from "./ProtokollDocument";
import { verkleinereFoto } from "./foto-verkleinern";
import { ladeFirmaZumAuftrag, type FirmaBranding } from "@/lib/firma/queries";
import { STANDARD_FARBE_PRIMAER } from "@/lib/firma/farben";
// Gemeinsam fuer PDF-Download (Nutzer-Client, RLS) und Mailversand
// (Admin-Client im Dispatcher). null = Auftrag fehlt oder ist nicht
@ -14,22 +16,47 @@ import { verkleinereFoto } from "./foto-verkleinern";
export async function erzeugeProtokollPdf(
client: SupabaseClient,
auftragId: string
): Promise<{ auftrag: Auftrag; buffer: Buffer } | null> {
): Promise<{ auftrag: Auftrag; buffer: Buffer; firma: FirmaBranding } | null> {
const auftrag = await loadAuftragStrikt(auftragId, client);
if (!auftrag || auftrag.status !== "abgeschlossen") {
return null;
}
const [fotos, unterschriftBuffer] = await Promise.all([
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 };
const props = {
...buildProtokollBasisdaten(auftrag),
fotos: verkleinert,
unterschriftBuffer,
firma: { name: firma.name, farbe: firma.farbe_primaer ?? STANDARD_FARBE_PRIMAER, logo },
};
// @react-pdf/renderer v4 typt ProtokollDocument nicht als ReactElement<DocumentProps>,
// obwohl es einen <Document>-Baum liefert -- bekannte Typluecke der Lib.
const element = createElement(ProtokollDocument, { props }) as unknown as ReactElement<DocumentProps>;
const buffer = await renderToBuffer(element);
return { auftrag, buffer };
return { auftrag, buffer, firma };
}
// 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 };
}

View File

@ -24,9 +24,10 @@ export type ProtokollProps = {
empfaengerName: string | null;
fotos: ProtokollFoto[];
unterschriftBuffer: Buffer | null;
firma: { name: string; farbe: string; logo: { buffer: Buffer; format: "png" | "jpg" } | null };
};
export function buildProtokollBasisdaten(auftrag: Auftrag): Omit<ProtokollProps, "fotos" | "unterschriftBuffer"> {
export function buildProtokollBasisdaten(auftrag: Auftrag): Omit<ProtokollProps, "fotos" | "unterschriftBuffer" | "firma"> {
return {
auftragsnummer: auftrag.auftragsnummer,
abholort: { adresse: auftrag.abholort.adresse, ansprechpartner: auftrag.abholort.ansprechpartner },

View File

@ -95,6 +95,10 @@ describe("mussPasswortAendern", () => {
expect(mussPasswortAendern(MIT_PFLICHT, `${PASSWORT_AENDERN_PFAD}/`)).toBe(false);
});
it("leitet /abmelden nicht um (sonst Redirect-Schleife)", () => {
expect(mussPasswortAendern(MIT_PFLICHT, "/abmelden")).toBe(false);
});
it("leitet bei einem Pfad mit ähnlichem Präfix trotzdem um", () => {
expect(mussPasswortAendern(MIT_PFLICHT, "/passwort-aendern-x")).toBe(true);
});

View File

@ -38,6 +38,11 @@ export function mussPasswortAendern(user: AuthUserLike, pathname: string): boole
if (!hatPasswortAenderPflicht(user)) {
return false;
}
// /abmelden muss erreichbar bleiben, sonst entsteht eine Redirect-Schleife
// (Layout: keine aktive Firma -> /abmelden -> Middleware -> /passwort-aendern).
if (pathname === "/abmelden") {
return false;
}
const aufPasswortSeite = pathname === PASSWORT_AENDERN_PFAD || pathname.startsWith(`${PASSWORT_AENDERN_PFAD}/`);
return !aufPasswortSeite;
}

View File

@ -6,6 +6,7 @@ export type Profile = {
id: string;
name: string;
role: Role;
firma_id: string | null;
};
export type ProfileResult =
@ -25,7 +26,7 @@ export const loadProfile = cache(async (): Promise<ProfileResult> => {
const { data, error } = await supabase
.from("profiles")
.select("id, name, role")
.select("id, name, role, firma_id")
.eq("id", user.id)
.single();

View File

@ -1,4 +1,12 @@
export type Role = "admin" | "disponent" | "fahrer" | "readonly";
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";
}
export function canManageUsers(role: Role): boolean {
return role === "admin";

View File

@ -0,0 +1,20 @@
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<AdminKontext> {
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 };
}

View File

@ -0,0 +1,23 @@
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<EigeneFirmaResult> => {
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" };
});

View File

@ -0,0 +1,48 @@
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\)\.$/);
});
});

View File

@ -0,0 +1,65 @@
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 },
};
}

View File

@ -0,0 +1,47 @@
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({});
});
});

33
web/lib/firma/farben.ts Normal file
View File

@ -0,0 +1,33 @@
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 <html> ueberschreibt.
export function themeVariablen(f: { farbe_primaer: string | null; farbe_dunkel: string | null }): Record<string, string> {
const variablen: Record<string, string> = {};
if (f.farbe_primaer) variablen["--color-performance-blue"] = f.farbe_primaer;
if (f.farbe_dunkel) variablen["--color-night-blue"] = f.farbe_dunkel;
return variablen;
}

View File

@ -0,0 +1,40 @@
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");
});
});

42
web/lib/firma/logo.ts Normal file
View File

@ -0,0 +1,42 @@
export const LOGO_MAX_BYTES = 1024 * 1024;
export type LogoEndung = "png" | "jpg" | "svg";
const ENDUNG_NACH_TYP: Record<string, LogoEndung> = {
"image/png": "png",
"image/jpeg": "jpg",
"image/svg+xml": "svg",
};
const TYP_NACH_ENDUNG: Record<LogoEndung, string> = {
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 <img> 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;

View File

@ -0,0 +1,54 @@
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;
fehler?: "profiles" | "firmen";
};
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: a.fehler === tabelle ? null : daten,
error: a.fehler === tabelle ? { message: "db weg" } : 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("wirft bei profiles-Fehler", async () => {
await expect(
pruefeFirmenzugang(fakeClient({ profil: null, firma: null, fehler: "profiles" }), "u"),
).rejects.toThrow("Profil laden fehlgeschlagen");
});
it("wirft bei firmen-Fehler", async () => {
await expect(
pruefeFirmenzugang(fakeClient({ profil: { role: "fahrer", firma_id: "f" }, firma: null, fehler: "firmen" }), "u"),
).rejects.toThrow("Firma laden fehlgeschlagen");
});
it("kein Profil", async () => {
expect(await pruefeFirmenzugang(fakeClient({ profil: null, firma: null }), "u")).toBe("gesperrt");
});
});

54
web/lib/firma/queries.ts Normal file
View File

@ -0,0 +1,54 @@
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<Firma | null> {
const { data, error } = await client.from("firmen").select(FIRMA_SELECT).eq("id", firmaId).maybeSingle();
if (error) {
throw new Error(`Firma laden fehlgeschlagen: ${error.message}`);
}
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<FirmaBranding | null> {
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<Firmenzugang> {
const { data: profil, error } = await client.from("profiles").select("role, firma_id").eq("id", userId).maybeSingle();
if (error) {
throw new Error(`Profil laden fehlgeschlagen: ${error.message}`);
}
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";
}

View File

@ -0,0 +1,58 @@
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("gekuerzter Auth-Tag scheitert", () => {
const [v, iv, tag, ct] = verschluessele("geheim").split(":");
const kurz = Buffer.from(tag, "base64").subarray(0, 4).toString("base64");
expect(() => entschluessele([v, iv, kurz, ct].join(":"))).toThrow("Unbekanntes Format");
});
it("falsche IV-Laenge scheitert", () => {
const [v, iv, tag, ct] = verschluessele("geheim").split(":");
const kurz = Buffer.from(iv, "base64").subarray(0, 8).toString("base64");
expect(() => entschluessele([v, kurz, tag, ct].join(":"))).toThrow("Unbekanntes Format");
});
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");
});
});

View File

@ -0,0 +1,44 @@
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
const ALGORITHMUS = "aes-256-gcm";
const IV_LAENGE = 12;
const TAG_LAENGE = 16;
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:<iv>:<tag>:<ciphertext>, alles base64. Die Version erlaubt einen
// spaeteren Schluesselwechsel ohne Raten.
export function verschluessele(klartext: string): string {
const iv = randomBytes(IV_LAENGE);
const cipher = createCipheriv(ALGORITHMUS, schluessel(), iv, { authTagLength: TAG_LAENGE });
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 ivBytes = Buffer.from(iv, "base64");
const tagBytes = Buffer.from(tag, "base64");
// Node akzeptiert sonst gekuerzte GCM-Tags; Laengen daher fest vorgeben.
if (ivBytes.length !== IV_LAENGE || tagBytes.length !== TAG_LAENGE) {
throw new Error("Unbekanntes Format des verschluesselten SMTP-Passworts");
}
const decipher = createDecipheriv(ALGORITHMUS, schluessel(), ivBytes, { authTagLength: TAG_LAENGE });
decipher.setAuthTag(tagBytes);
return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8");
}

View File

@ -0,0 +1,71 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("node:dns/promises", () => ({ lookup: vi.fn() }));
import { lookup } from "node:dns/promises";
import { pruefeSmtpZiel } from "./smtp-ziel";
const lookupMock = vi.mocked(lookup) as unknown as ReturnType<typeof vi.fn>;
describe("pruefeSmtpZiel", () => {
beforeEach(() => {
lookupMock.mockReset();
});
it.each([
"127.0.0.1",
"10.0.0.1",
"0.0.0.0",
"100.64.0.1",
"169.254.169.254",
"172.16.5.4",
"192.168.1.1",
"198.18.0.1",
"224.0.0.1",
"255.255.255.255",
"::",
"::1",
"fc00::1",
"fd12:3456::1",
"fe80::1",
"ff02::1",
"::ffff:127.0.0.1",
"::ffff:7f00:1",
"::ffff:169.254.169.254",
])("lehnt das IP-Literal %s ab", async (ip) => {
expect(await pruefeSmtpZiel(ip)).toEqual({ ok: false });
expect(lookupMock).not.toHaveBeenCalled();
});
it("akzeptiert eine oeffentliche IP direkt und pinnt sie", async () => {
expect(await pruefeSmtpZiel("93.184.216.34")).toEqual({ ok: true, ip: "93.184.216.34" });
expect(await pruefeSmtpZiel("2606:4700::1111")).toEqual({ ok: true, ip: "2606:4700::1111" });
expect(lookupMock).not.toHaveBeenCalled();
});
it("lehnt einen Namen ab, der privat aufloest", async () => {
lookupMock.mockResolvedValue([{ address: "10.1.2.3", family: 4 }]);
expect(await pruefeSmtpZiel("intern.example.de")).toEqual({ ok: false });
expect(lookupMock).toHaveBeenCalledWith("intern.example.de", { all: true });
});
it("lehnt ab, wenn nur eine von mehreren Adressen privat ist", async () => {
lookupMock.mockResolvedValue([
{ address: "93.184.216.34", family: 4 },
{ address: "127.0.0.1", family: 4 },
]);
expect(await pruefeSmtpZiel("mix.example.de")).toEqual({ ok: false });
});
it("akzeptiert einen Namen mit oeffentlicher Adresse und liefert die erste IP", async () => {
lookupMock.mockResolvedValue([{ address: "93.184.216.34", family: 4 }]);
expect(await pruefeSmtpZiel("smtp.example.de")).toEqual({ ok: true, ip: "93.184.216.34" });
});
it("lehnt ab, wenn die Aufloesung scheitert oder nichts liefert", async () => {
lookupMock.mockRejectedValueOnce(new Error("ENOTFOUND"));
expect(await pruefeSmtpZiel("gibt-es-nicht.example.de")).toEqual({ ok: false });
lookupMock.mockResolvedValueOnce([]);
expect(await pruefeSmtpZiel("leer.example.de")).toEqual({ ok: false });
});
});

View File

@ -0,0 +1,65 @@
import { lookup } from "node:dns/promises";
import { BlockList, isIP } from "node:net";
// Nicht oeffentliche Ziele (SSRF-Schutz fuer den firmeneigenen SMTP-Server).
const GESPERRT = new BlockList();
for (const [netz, laenge] of [
["0.0.0.0", 8],
["10.0.0.0", 8],
["100.64.0.0", 10],
["127.0.0.0", 8],
["169.254.0.0", 16],
["172.16.0.0", 12],
["192.0.0.0", 24],
["192.168.0.0", 16],
["198.18.0.0", 15],
["224.0.0.0", 4],
["240.0.0.0", 4],
] as const) {
GESPERRT.addSubnet(netz, laenge, "ipv4");
}
GESPERRT.addAddress("::", "ipv6");
GESPERRT.addAddress("::1", "ipv6");
GESPERRT.addSubnet("fc00::", 7, "ipv6");
GESPERRT.addSubnet("fe80::", 10, "ipv6");
GESPERRT.addSubnet("ff00::", 8, "ipv6");
// ::ffff:a.b.c.d bzw. ::ffff:xxxx:yyyy auf die eingebettete IPv4-Adresse abbilden.
function normalisiere(ip: string): string {
const punkt = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(ip);
if (punkt) return punkt[1];
const hex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(ip);
if (hex) {
const hoch = parseInt(hex[1], 16);
const tief = parseInt(hex[2], 16);
return `${hoch >> 8}.${hoch & 255}.${tief >> 8}.${tief & 255}`;
}
return ip;
}
function istOeffentlich(ip: string): boolean {
const norm = normalisiere(ip);
const art = isIP(norm);
if (art === 0) return false;
return !GESPERRT.check(norm, art === 4 ? "ipv4" : "ipv6");
}
export type SmtpZielErgebnis = { ok: true; ip: string } | { ok: false };
// Loest den Host auf und liefert die zu verwendende (gepinnte) IP. Alle Adressen
// muessen oeffentlich sein; sonst ok:false (ohne Grund, kein Orakel fuer Admins).
export async function pruefeSmtpZiel(host: string): Promise<SmtpZielErgebnis> {
if (isIP(host) !== 0) {
return istOeffentlich(host) ? { ok: true, ip: host } : { ok: false };
}
let adressen: { address: string }[];
try {
adressen = await lookup(host, { all: true });
} catch {
return { ok: false };
}
if (adressen.length === 0 || !adressen.every((a) => istOeffentlich(a.address))) {
return { ok: false };
}
return { ok: true, ip: adressen[0].address };
}

174
web/lib/firma/smtp.test.ts Normal file
View File

@ -0,0 +1,174 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("node:dns/promises", () => ({ lookup: vi.fn() }));
import { lookup } from "node:dns/promises";
import type { SupabaseClient } from "@supabase/supabase-js";
import {
SmtpZielFehler,
ermittleEmailConfig,
firmenSmtpZuConfig,
validateSmtpEingabe,
type BestehendSmtp,
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",
};
const BESTEHEND: BestehendSmtp = {
host: "smtp.firma.de",
port: 587,
benutzer: "mailer",
passwort_verschluesselt: "v1:x:y:z",
};
describe("validateSmtpEingabe", () => {
it("uebernimmt gueltige Werte", () => {
expect(validateSmtpEingabe(EINGABE, null)).toEqual({
valid: true,
werte: {
host: "smtp.firma.de",
port: 587,
secure: false,
benutzer: "mailer",
neuesPasswort: "geheim",
passwortBehalten: false,
absender_adresse: "noreply@firma.de",
absender_name: "Firma B",
},
});
});
it("Host ist Pflicht", () => {
expect(validateSmtpEingabe({ ...EINGABE, host: " " }, null)).toEqual({ valid: false, error: "Bitte den SMTP-Server angeben." });
});
it.each(["70000", "22", "80", "abc", "587.5", ""])("Port %s ist nicht erlaubt", (port) => {
expect(validateSmtpEingabe({ ...EINGABE, port }, null)).toEqual({
valid: false,
error: "Bitte einen gültigen Port (25, 465, 587 oder 2525) angeben.",
});
});
it.each(["25", "465", "587", "2525"])("Port %s ist erlaubt", (port) => {
expect(validateSmtpEingabe({ ...EINGABE, port }, null).valid).toBe(true);
});
it("Absenderadresse muss eine E-Mail sein", () => {
expect(validateSmtpEingabe({ ...EINGABE, absenderAdresse: "kein mail" }, null)).toEqual({
valid: false,
error: "Bitte eine gültige Absenderadresse angeben.",
});
});
it("Benutzer ohne neues und ohne gespeichertes Passwort scheitert", () => {
expect(validateSmtpEingabe({ ...EINGABE, passwort: "" }, null)).toEqual({ valid: false, error: "Bitte ein Passwort eingeben." });
});
it("gleiches Ziel + leeres Passwort: gespeichertes Passwort bleibt", () => {
const e = validateSmtpEingabe({ ...EINGABE, passwort: "" }, BESTEHEND);
expect(e.valid && e.werte.neuesPasswort).toBeNull();
expect(e.valid && e.werte.passwortBehalten).toBe(true);
});
it("geaenderter Host + leeres Passwort scheitert", () => {
expect(validateSmtpEingabe({ ...EINGABE, host: "evil.example.de", passwort: "" }, BESTEHEND)).toEqual({
valid: false,
error: "Bitte ein Passwort eingeben.",
});
});
it("geaenderter Port + leeres Passwort scheitert", () => {
expect(validateSmtpEingabe({ ...EINGABE, port: "465", passwort: "" }, BESTEHEND).valid).toBe(false);
});
it("geaenderter Benutzer + leeres Passwort scheitert", () => {
expect(validateSmtpEingabe({ ...EINGABE, benutzer: "anderer", passwort: "" }, BESTEHEND).valid).toBe(false);
});
it("geaenderter Host mit neuem Passwort ist gueltig", () => {
const e = validateSmtpEingabe({ ...EINGABE, host: "neu.example.de", passwort: "neu" }, BESTEHEND);
expect(e.valid && e.werte.neuesPasswort).toBe("neu");
expect(e.valid && e.werte.passwortBehalten).toBe(false);
});
it("bestehende Zeile ohne gespeichertes Passwort zaehlt nicht", () => {
expect(
validateSmtpEingabe({ ...EINGABE, passwort: "" }, { ...BESTEHEND, passwort_verschluesselt: null }).valid
).toBe(false);
});
it("ohne Benutzer wird das Passwort ignoriert", () => {
const e = validateSmtpEingabe({ ...EINGABE, benutzer: "", passwort: "x" }, null);
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;
(lookup as unknown as ReturnType<typeof vi.fn>).mockReset();
(lookup as unknown as ReturnType<typeof vi.fn>).mockResolvedValue([{ address: "93.184.216.34", family: 4 }]);
});
afterEach(() => {
if (alt === undefined) {
delete process.env.SMTP_VERSCHLUESSELUNG_KEY;
} else {
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" <noreply@firma.de>',
auth: { user: "mailer", pass: "geheim" },
});
});
it("nimmt den Firmen-SMTP vor dem Fallback und pinnt die geprueft aufgeloeste IP", async () => {
const fallback = () => ({ host: "global", port: 25, secure: false, from: "g@x.de", auth: null });
const cfg = await ermittleEmailConfig(fakeAdmin(zeile()), "f2", fallback);
expect(cfg?.host).toBe("93.184.216.34");
expect(cfg?.servername).toBe("smtp.firma.de");
});
it("wirft SmtpZielFehler, wenn der Firmen-SMTP privat aufloest", async () => {
(lookup as unknown as ReturnType<typeof vi.fn>).mockResolvedValue([{ address: "10.0.0.5", family: 4 }]);
await expect(ermittleEmailConfig(fakeAdmin(zeile()), "f2", () => null)).rejects.toBeInstanceOf(SmtpZielFehler);
});
it("prueft den globalen Fallback nicht", async () => {
const fallback = () => ({ host: "127.0.0.1", port: 1025, secure: false, from: "g@x.de", auth: null });
expect((await ermittleEmailConfig(fakeAdmin(null), "f2", fallback))?.host).toBe("127.0.0.1");
});
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();
});
});

146
web/lib/firma/smtp.ts Normal file
View File

@ -0,0 +1,146 @@
import type { SupabaseClient } from "@supabase/supabase-js";
import { getEmailConfig, type EmailConfig } from "@/lib/notifications/email-config";
import { entschluessele } from "./smtp-crypto";
import { pruefeSmtpZiel } from "./smtp-ziel";
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<FirmenSmtpZeile, "firma_id" | "passwort_verschluesselt"> & { passwortGesetzt: boolean };
export type SmtpWerte = {
host: string;
port: number;
secure: boolean;
benutzer: string | null;
neuesPasswort: string | null;
// true: kein neues Passwort, das gespeicherte bleibt (Ziel und Benutzer unveraendert).
passwortBehalten: boolean;
absender_adresse: string;
absender_name: string | null;
};
export type BestehendSmtp = {
host: string;
port: number;
benutzer: string | null;
passwort_verschluesselt: string | null;
};
export const ERLAUBTE_SMTP_PORTS = [25, 465, 587, 2525];
export const SMTP_ZIEL_NICHT_ERLAUBT = "SMTP-Ziel nicht erlaubt";
export class SmtpZielFehler extends Error {
constructor() {
super(SMTP_ZIEL_NICHT_ERLAUBT);
this.name = "SmtpZielFehler";
}
}
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,
bestehend: BestehendSmtp | null
): { 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 (!ERLAUBTE_SMTP_PORTS.includes(port)) {
return { valid: false, error: "Bitte einen gültigen Port (25, 465, 587 oder 2525) 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;
// Das gespeicherte Passwort gilt nur fuer genau dieses Ziel und diesen Benutzer;
// sonst koennte es an einen anderen Server geschickt werden.
const zielGleich =
bestehend !== null && bestehend.host === host && bestehend.port === port && bestehend.benutzer === benutzer;
const passwortBehalten = Boolean(benutzer && !passwort && zielGleich && bestehend?.passwort_verschluesselt);
if (benutzer && !passwort && !passwortBehalten) {
return { valid: false, error: "Bitte ein Passwort eingeben." };
}
return {
valid: true,
werte: {
host,
port,
secure: input.secure,
benutzer,
neuesPasswort: benutzer ? passwort : null,
passwortBehalten,
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<FirmenSmtpZeile | null> {
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,
};
}
// Prueft das Ziel und pinnt die Verbindung auf die geprueft aufgeloeste IP
// (verhindert DNS-Rebinding zwischen Pruefung und Verbindungsaufbau).
export async function pinneSmtpZiel(cfg: EmailConfig): Promise<EmailConfig> {
const ziel = await pruefeSmtpZiel(cfg.host);
if (!ziel.ok) throw new SmtpZielFehler();
return { ...cfg, host: ziel.ip, servername: cfg.host };
}
// 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<EmailConfig | null> {
const zeile = await ladeFirmenSmtp(admin, firmaId);
// Nur der Firmen-SMTP wird geprueft; der globale Fallback kommt vom Betreiber (.env).
return zeile ? pinneSmtpZiel(firmenSmtpZuConfig(zeile)) : fallback();
}

View File

@ -4,7 +4,6 @@ import { getWhatsAppConfig } from "./config";
const PFLICHT = {
WHATSAPP_ACCESS_TOKEN: "tok",
WHATSAPP_PHONE_NUMBER_ID: "123",
WHATSAPP_RECIPIENT: "4915100000000",
WHATSAPP_TEMPLATE_NAME: "neuer_auftrag",
WHATSAPP_TEMPLATE_LANG: "de",
};
@ -32,7 +31,6 @@ describe("getWhatsAppConfig", () => {
expect(getWhatsAppConfig()).toEqual({
accessToken: "tok",
phoneNumberId: "123",
recipient: "4915100000000",
templateName: "neuer_auftrag",
templateLang: "de",
graphVersion: "v21.0",

View File

@ -1,7 +1,6 @@
export type WhatsAppConfig = {
accessToken: string;
phoneNumberId: string;
recipient: string;
templateName: string;
templateLang: string;
graphVersion: string;
@ -10,21 +9,20 @@ export type WhatsAppConfig = {
// Liest die WhatsApp-Cloud-API-Konfiguration aus den Umgebungsvariablen.
// Gibt null zurueck, sobald eine Pflichtvariable fehlt oder leer ist -- der
// Dispatcher behandelt null als "Feature aus" und verarbeitet keine Zeilen.
// Der Empfaenger kommt pro Firma aus firmen.whatsapp_empfaenger.
export function getWhatsAppConfig(): WhatsAppConfig | null {
const accessToken = process.env.WHATSAPP_ACCESS_TOKEN;
const phoneNumberId = process.env.WHATSAPP_PHONE_NUMBER_ID;
const recipient = process.env.WHATSAPP_RECIPIENT;
const templateName = process.env.WHATSAPP_TEMPLATE_NAME;
const templateLang = process.env.WHATSAPP_TEMPLATE_LANG;
if (!accessToken || !phoneNumberId || !recipient || !templateName || !templateLang) {
if (!accessToken || !phoneNumberId || !templateName || !templateLang) {
return null;
}
return {
accessToken,
phoneNumberId,
recipient,
templateName,
templateLang,
graphVersion: process.env.WHATSAPP_GRAPH_VERSION || "v21.0",

View File

@ -6,6 +6,7 @@ function row(over: Partial<OutboxRow> = {}): OutboxRow {
id: "r1",
event_type: "auftrag_erstellt",
auftrag_id: "a1",
firma_id: "f1",
payload: {},
versuche: 0,
max_versuche: 5,

View File

@ -4,6 +4,7 @@ export type OutboxRow = {
id: string;
event_type: string;
auftrag_id: string | null;
firma_id: string;
payload: Record<string, unknown>;
versuche: number;
max_versuche: number;

View File

@ -4,11 +4,13 @@ export type EmailConfig = {
secure: boolean;
from: string;
auth: { user: string; pass: string } | null;
// Gesetzt, wenn host auf eine geprueft aufgeloeste IP gepinnt wurde: TLS prueft
// das Zertifikat dann gegen den urspruenglichen Namen.
servername?: string;
};
// Liest die SMTP-Konfiguration aus den Umgebungsvariablen. null = E-Mail-Kanal
// aus (gleiches Muster wie getWhatsAppConfig): die Outbox-Zeilen bleiben dann
// pending, bis SMTP konfiguriert ist.
// Liest die SMTP-Konfiguration aus den Umgebungsvariablen. null = kein globaler SMTP;
// Firmen ohne eigenen SMTP bekommen dann keine Mail (Outbox: failed/Retry).
export function getEmailConfig(): EmailConfig | null {
const host = process.env.SMTP_HOST;
const portRoh = process.env.SMTP_PORT;

View File

@ -36,9 +36,9 @@ const PDF = Buffer.from("%PDF-test");
describe("baueProtokollMail", () => {
it("setzt Empfaenger, Betreff und Anhang", () => {
const mail = baueProtokollMail({ empfaenger: "dispo@example.de", auftrag: makeAuftrag(), pdf: PDF });
const mail = baueProtokollMail({ empfaenger: "dispo@example.de", auftrag: makeAuftrag(), pdf: PDF, firmenname: "Firma B" });
expect(mail.to).toBe("dispo@example.de");
expect(mail.subject).toBe("Übergabeprotokoll 26-09-01-0001 – M-AB 123");
expect(mail.subject).toBe("Übergabeprotokoll 26-09-01-0001 – M-AB 123 (Firma B)");
expect(mail.attachments).toEqual([
{ filename: "protokoll-26-09-01-0001.pdf", content: PDF, contentType: "application/pdf" },
]);
@ -49,12 +49,13 @@ describe("baueProtokollMail", () => {
empfaenger: "d@example.de",
auftrag: makeAuftrag({ fahrzeug: { id: "f1", kennzeichen: null, fin: "WDB9066331S123456", marke: null, modell: null } }),
pdf: PDF,
firmenname: "Firma B",
});
expect(mail.subject).toBe("Übergabeprotokoll 26-09-01-0001 – FIN WDB9066331S123456");
expect(mail.subject).toBe("Übergabeprotokoll 26-09-01-0001 – FIN WDB9066331S123456 (Firma B)");
});
it("enthaelt die Eckdaten im Text (Uhrzeit Europe/Berlin)", () => {
const { text } = baueProtokollMail({ empfaenger: "d@example.de", auftrag: makeAuftrag(), pdf: PDF });
const { text } = baueProtokollMail({ empfaenger: "d@example.de", auftrag: makeAuftrag(), pdf: PDF, firmenname: "Firma B" });
expect(text).toContain("Abholort: Hauptstr. 1, Musterstadt");
expect(text).toContain("Zielort: Nebenweg 2, Musterstadt");
expect(text).toContain("Fahrzeug: M-AB 123");
@ -69,6 +70,7 @@ describe("baueProtokollMail", () => {
empfaenger: "d@example.de",
auftrag: makeAuftrag({ empfaenger_name: null, zugewiesen_an_profil: null }),
pdf: PDF,
firmenname: "Firma B",
});
expect(text).not.toContain("Empfänger:");
expect(text).toContain("Fahrer: -");
@ -79,6 +81,7 @@ describe("baueProtokollMail", () => {
empfaenger: "d@example.de",
auftrag: makeAuftrag({ start_fin: "WVWZZZ1KZAW999999", start_fin_status: "abweichend" }),
pdf: PDF,
firmenname: "Firma B",
});
expect(text).toContain("FIN-Abgleich bei Fahrtbeginn: abweichend – vor Ort: WVWZZZ1KZAW999999");
});
@ -90,13 +93,14 @@ describe("FIN-Zeile", () => {
empfaenger: "d@example.de",
auftrag: makeAuftrag({ start_fin: "WVWZZZ1KZAW999999", start_fin_status: "bestaetigt" }),
pdf: PDF,
firmenname: "Firma B",
});
expect(text).not.toContain("FIN-Abgleich");
});
});
describe("sendeProtokollMail", () => {
const mail = baueProtokollMail({ empfaenger: "d@example.de", auftrag: makeAuftrag(), pdf: PDF });
const mail = baueProtokollMail({ empfaenger: "d@example.de", auftrag: makeAuftrag(), pdf: PDF, firmenname: "Firma B" });
const cfg = { host: "h", port: 587, secure: false, from: "f@example.de", auth: { user: "u", pass: "p" } };
const sendMail = vi.fn();
const close = vi.fn();
@ -127,6 +131,21 @@ describe("sendeProtokollMail", () => {
expect(createTransport.mock.calls[0][0]).toMatchObject({ requireTLS: true, auth: { user: "u", pass: "p" } });
});
it("pinnt auf die IP und prueft das Zertifikat gegen den urspruenglichen Namen", async () => {
sendMail.mockResolvedValue({ messageId: "m" });
await sendeProtokollMail({ ...cfg, host: "93.184.216.34", servername: "smtp.firma.de" }, mail);
expect(createTransport.mock.calls[0][0]).toMatchObject({
host: "93.184.216.34",
tls: { servername: "smtp.firma.de" },
});
});
it("ohne servername keine tls-Option", async () => {
sendMail.mockResolvedValue({ messageId: "m" });
await sendeProtokollMail(cfg, mail);
expect((createTransport.mock.calls[0][0] as { tls?: unknown }).tls).toBeUndefined();
});
it("ohne Auth: kein auth, kein requireTLS", async () => {
sendMail.mockResolvedValue({ messageId: "m" });
await sendeProtokollMail({ ...cfg, auth: null }, mail);

View File

@ -20,7 +20,7 @@ const DATUM = new Intl.DateTimeFormat("de-DE", {
const TIMEOUT_MS = 10_000;
export function baueProtokollMail(daten: { empfaenger: string; auftrag: Auftrag; pdf: Buffer }): ProtokollMail {
export function baueProtokollMail(daten: { empfaenger: string; auftrag: Auftrag; pdf: Buffer; firmenname: string }): ProtokollMail {
const { auftrag } = daten;
const fahrzeug = fahrzeugBezeichnung(auftrag.fahrzeug);
const zeilen = [
@ -46,7 +46,7 @@ export function baueProtokollMail(daten: { empfaenger: string; auftrag: Auftrag;
return {
to: daten.empfaenger,
subject: `Übergabeprotokoll ${auftrag.auftragsnummer} – ${fahrzeug}`,
subject: `Übergabeprotokoll ${auftrag.auftragsnummer} – ${fahrzeug} (${daten.firmenname})`,
text: zeilen.join("\n"),
attachments: [
{ filename: `protokoll-${auftrag.auftragsnummer}.pdf`, content: daten.pdf, contentType: "application/pdf" },
@ -60,6 +60,7 @@ export async function sendeProtokollMail(cfg: EmailConfig, mail: ProtokollMail):
port: cfg.port,
secure: cfg.secure,
auth: cfg.auth ?? undefined,
tls: cfg.servername ? { servername: cfg.servername } : undefined,
// Mit Zugangsdaten niemals im Klartext senden: STARTTLS erzwingen, sonst
// koennte ein Angreifer STARTTLS entfernen und die Credentials mitlesen.
requireTLS: cfg.auth !== null && !cfg.secure,

View File

@ -1,25 +1,33 @@
import { describe, expect, it, vi } from "vitest";
import type { SupabaseClient } from "@supabase/supabase-js";
import { protokollMailHandler, whatsappHandler } from "./handler";
import { SmtpZielFehler } from "@/lib/firma/smtp";
import type { OutboxRow } from "./dispatch";
import type { EmailConfig } from "./email-config";
import type { WhatsAppConfig } from "./config";
import type { Auftrag } from "@/lib/auftraege/queries";
const MAIL_CFG: EmailConfig = { host: "smtp", port: 587, secure: false, from: "noreply@example.de", auth: null };
const FIRMA = { name: "Firma B", logo_pfad: null, farbe_primaer: null };
const WA_CFG: WhatsAppConfig = {
accessToken: "tok",
phoneNumberId: "PN1",
recipient: "4915100000000",
templateName: "neuer_auftrag",
templateLang: "de",
graphVersion: "v21.0",
};
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;
}
function row(over: Partial<OutboxRow> = {}): OutboxRow {
return {
id: "r1",
event_type: "protokoll_abgeschlossen",
auftrag_id: "a1",
firma_id: "f2",
payload: { auftragsnummer: "26-09-01-0001", empfaenger: "dispo@example.de" },
versuche: 0,
max_versuche: 5,
@ -42,18 +50,22 @@ const AUFTRAG = {
describe("protokollMailHandler", () => {
it("erzeugt das PDF mit dem Admin-Client und sendet an payload.empfaenger", async () => {
const admin = {} as never;
const erzeugePdf = vi.fn(async () => ({ auftrag: AUFTRAG, buffer: Buffer.from("%PDF") }));
const erzeugePdf = vi.fn(async () => ({ auftrag: AUFTRAG, buffer: Buffer.from("%PDF"), firma: FIRMA }));
const sender = vi.fn(async () => ({ ok: true as const, messageId: "<m1>" }));
const ergebnis = await protokollMailHandler(admin, MAIL_CFG, { erzeugePdf, sender })(row());
const ergebnis = await protokollMailHandler(admin, { erzeugePdf, sender, ladeConfig: async () => MAIL_CFG })(row());
expect(ergebnis).toEqual({ ok: true });
expect(erzeugePdf).toHaveBeenCalledWith(admin, "a1");
expect(sender).toHaveBeenCalledWith(MAIL_CFG, expect.objectContaining({ to: "dispo@example.de" }));
expect(sender).toHaveBeenCalledWith(
MAIL_CFG,
expect.objectContaining({ to: "dispo@example.de", subject: expect.stringContaining("(Firma B)") })
);
});
it("ist endgueltig fehlgeschlagen, wenn der Auftrag nicht (mehr) abgeschlossen ist", async () => {
const ergebnis = await protokollMailHandler({} as never, MAIL_CFG, {
const ergebnis = await protokollMailHandler({} as never, {
ladeConfig: async () => MAIL_CFG,
erzeugePdf: vi.fn(async () => null),
sender: vi.fn(),
})(row());
@ -61,12 +73,12 @@ describe("protokollMailHandler", () => {
});
it("ist endgueltig fehlgeschlagen ohne Empfaenger oder ohne auftrag_id", async () => {
const deps = { erzeugePdf: vi.fn(), sender: vi.fn() };
expect(await protokollMailHandler({} as never, MAIL_CFG, deps)(row({ payload: {} }))).toMatchObject({
const deps = { erzeugePdf: vi.fn(), sender: vi.fn(), ladeConfig: async () => MAIL_CFG };
expect(await protokollMailHandler({} as never, deps)(row({ payload: {} }))).toMatchObject({
ok: false,
endgueltig: true,
});
expect(await protokollMailHandler({} as never, MAIL_CFG, deps)(row({ auftrag_id: null }))).toMatchObject({
expect(await protokollMailHandler({} as never, deps)(row({ auftrag_id: null }))).toMatchObject({
ok: false,
endgueltig: true,
});
@ -74,7 +86,8 @@ describe("protokollMailHandler", () => {
});
it("meldet einen PDF-Fehler als wiederholbaren Fehler", async () => {
const ergebnis = await protokollMailHandler({} as never, MAIL_CFG, {
const ergebnis = await protokollMailHandler({} as never, {
ladeConfig: async () => MAIL_CFG,
erzeugePdf: vi.fn(async () => {
throw new Error("render kaputt");
}),
@ -84,8 +97,9 @@ describe("protokollMailHandler", () => {
});
it("reicht einen SMTP-Fehler als wiederholbaren Fehler durch", async () => {
const ergebnis = await protokollMailHandler({} as never, MAIL_CFG, {
erzeugePdf: vi.fn(async () => ({ auftrag: AUFTRAG, buffer: Buffer.from("%PDF") })),
const ergebnis = await protokollMailHandler({} as never, {
ladeConfig: async () => MAIL_CFG,
erzeugePdf: vi.fn(async () => ({ auftrag: AUFTRAG, buffer: Buffer.from("%PDF"), firma: FIRMA })),
sender: vi.fn(async () => ({ ok: false as const, fehler: "ECONNREFUSED" })),
})(row());
expect(ergebnis).toEqual({ ok: false, fehler: "ECONNREFUSED" });
@ -96,16 +110,63 @@ describe("whatsappHandler", () => {
it("reicht die Meta-Message-ID als waMessageId durch", async () => {
const sender = vi.fn(async () => ({ ok: true as const, messageId: "wamid.1" }));
const payload = { auftragsnummer: "1", abholort_adresse: "A", zielort_adresse: "B", kennzeichen: "K" };
const ergebnis = await whatsappHandler(WA_CFG, sender)(row({ event_type: "auftrag_erstellt", payload }));
const ergebnis = await whatsappHandler(fakeAdminMitFirma({ whatsapp_empfaenger: "+4915100000009" }), WA_CFG, sender)(
row({ event_type: "auftrag_erstellt", payload })
);
expect(ergebnis).toEqual({ ok: true, waMessageId: "wamid.1" });
expect(sender).toHaveBeenCalledWith(WA_CFG, payload);
expect(sender).toHaveBeenCalledWith(WA_CFG, "+4915100000009", payload);
});
it("reicht Sendefehler durch", async () => {
const sender = vi.fn(async () => ({ ok: false as const, fehler: "500" }));
expect(await whatsappHandler(WA_CFG, sender)(row({ event_type: "auftrag_erstellt" }))).toEqual({
expect(await whatsappHandler(fakeAdminMitFirma({ whatsapp_empfaenger: "+4915100000009" }), WA_CFG, sender)(
row({ event_type: "auftrag_erstellt" })
)).toEqual({
ok: false,
fehler: "500",
});
});
});
describe("whatsappHandler (Empfaenger pro Firma)", () => {
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, WA_CFG, sender)(row({ event_type: "auftrag_erstellt", firma_id: "f2" }));
expect(res).toEqual({ ok: true, waMessageId: "wamid.1" });
expect(sender).toHaveBeenCalledWith(WA_CFG, "+4915100000009", expect.anything());
});
it("verwirft endgueltig, wenn die Firma keinen Empfaenger hat", async () => {
const res = await whatsappHandler(fakeAdminMitFirma({ whatsapp_empfaenger: null }), WA_CFG, vi.fn())(
row({ event_type: "auftrag_erstellt", firma_id: "f2" })
);
expect(res).toEqual({ ok: false, fehler: "Firma hat keinen WhatsApp-Empfaenger", endgueltig: true });
});
});
describe("protokollMailHandler mit geblocktem SMTP-Ziel", () => {
it("meldet nur den generischen Text und erzeugt kein PDF", async () => {
const erzeugePdf = vi.fn();
const res = await protokollMailHandler({} as never, {
erzeugePdf,
ladeConfig: async () => {
throw new SmtpZielFehler();
},
})(row());
expect(res).toEqual({ ok: false, fehler: "SMTP-Ziel nicht erlaubt" });
expect(erzeugePdf).not.toHaveBeenCalled();
});
});
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,
})(row({ payload: { empfaenger: "d@x.de" } }));
expect(res).toEqual({ ok: false, fehler: "Kein SMTP konfiguriert" });
expect(erzeugePdf).not.toHaveBeenCalled();
});
});

View File

@ -1,25 +1,43 @@
import type { SupabaseClient } from "@supabase/supabase-js";
import { erzeugeProtokollPdf } from "@/lib/auftraege/protokoll-pdf";
import { ermittleEmailConfig, SMTP_ZIEL_NICHT_ERLAUBT, SmtpZielFehler } 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";
export function whatsappHandler(cfg: WhatsAppConfig, sender = sendWhatsAppTemplate): Handler {
// 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 res = await sender(cfg, row.payload as AuftragErstelltPayload);
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,
cfg: EmailConfig,
deps: { erzeugePdf?: typeof erzeugeProtokollPdf; sender?: typeof sendeProtokollMail } = {}
deps: {
erzeugePdf?: typeof erzeugeProtokollPdf;
sender?: typeof sendeProtokollMail;
ladeConfig?: (admin: SupabaseClient, firmaId: string) => Promise<EmailConfig | null>;
} = {}
): 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 : "";
@ -27,6 +45,23 @@ export function protokollMailHandler(
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) {
// Admins lesen notification_outbox: bei geblocktem Ziel kein Rohtext (kein Orakel).
if (fehler instanceof SmtpZielFehler) {
return { ok: false, fehler: SMTP_ZIEL_NICHT_ERLAUBT };
}
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<ReturnType<typeof erzeugeProtokollPdf>>;
try {
pdf = await erzeugePdf(admin, row.auftrag_id);
@ -40,7 +75,10 @@ export function protokollMailHandler(
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 }));
const res = await sender(
cfg,
baueProtokollMail({ empfaenger, auftrag: pdf.auftrag, pdf: pdf.buffer, firmenname: pdf.firma.name })
);
return res.ok ? { ok: true } : res;
};
}

View File

@ -5,7 +5,6 @@ import { buildTemplateComponents, sendWhatsAppTemplate } from "./whatsapp";
const CFG: WhatsAppConfig = {
accessToken: "tok",
phoneNumberId: "PN1",
recipient: "4915100000000",
templateName: "neuer_auftrag",
templateLang: "de",
graphVersion: "v21.0",
@ -44,7 +43,7 @@ describe("sendWhatsAppTemplate", () => {
new Response(JSON.stringify({ messages: [{ id: "wamid.ABC" }] }), { status: 200 })
);
const res = await sendWhatsAppTemplate(CFG, PAYLOAD);
const res = await sendWhatsAppTemplate(CFG, "+4915100000000", PAYLOAD);
expect(res).toEqual({ ok: true, messageId: "wamid.ABC" });
const [url, init] = fetchMock.mock.calls[0];
@ -65,7 +64,7 @@ describe("sendWhatsAppTemplate", () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(JSON.stringify({ error: { message: "Template not found" } }), { status: 404 })
);
const res = await sendWhatsAppTemplate(CFG, PAYLOAD);
const res = await sendWhatsAppTemplate(CFG, "+4915100000000", PAYLOAD);
expect(res.ok).toBe(false);
expect(res).toMatchObject({ ok: false });
if (!res.ok) expect(res.fehler).toContain("404");
@ -74,7 +73,7 @@ describe("sendWhatsAppTemplate", () => {
it("gibt bei einer fetch-Exception ok:false zurueck", async () => {
vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("ECONNRESET"));
const res = await sendWhatsAppTemplate(CFG, PAYLOAD);
const res = await sendWhatsAppTemplate(CFG, "+4915100000000", PAYLOAD);
expect(res).toEqual({ ok: false, fehler: "ECONNRESET" });
});
});

View File

@ -33,6 +33,7 @@ const TIMEOUT_MS = 10_000;
export async function sendWhatsAppTemplate(
cfg: WhatsAppConfig,
empfaenger: string,
payload: AuftragErstelltPayload
): Promise<SendErgebnis> {
const url = `https://graph.facebook.com/${cfg.graphVersion}/${cfg.phoneNumberId}/messages`;
@ -48,7 +49,7 @@ export async function sendWhatsAppTemplate(
},
body: JSON.stringify({
messaging_product: "whatsapp",
to: cfg.recipient,
to: empfaenger.replace(/^\+/, ""),
type: "template",
template: {
name: cfg.templateName,

View File

@ -0,0 +1,75 @@
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<string, unknown>[] = [];
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<string, unknown>) => ({
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" }]);
});
});

View File

@ -0,0 +1,60 @@
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<NutzerAnlegenErgebnis> {
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}`,
};
}

View File

@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import type { SupabaseClient } from "@supabase/supabase-js";
import { pruefeZielNutzer } from "./ziel-pruefen";
function fakeClient(zeile: unknown, error: { message: string } | null = null): SupabaseClient {
const kette = { select: () => kette, eq: () => kette, maybeSingle: async () => ({ data: zeile, error }) };
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();
});
it("wirft bei DB-Fehler", async () => {
await expect(pruefeZielNutzer(fakeClient(null, { message: "db down" }), "u1")).rejects.toThrow("db down");
});
});

View File

@ -0,0 +1,17 @@
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.
// DB-Fehler werden geworfen, nie als "nicht gefunden" maskiert.
export async function pruefeZielNutzer(
client: SupabaseClient,
nutzerId: string
): Promise<{ id: string; role: Role } | null> {
const { data, error } = await client.from("profiles").select("id, role").eq("id", nutzerId).maybeSingle();
if (error) {
throw new Error(`Zielnutzer konnte nicht geprueft werden: ${error.message}`);
}
return (data as { id: string; role: Role } | null) ?? null;
}

View File

@ -0,0 +1,16 @@
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.");
});
});

View File

@ -55,9 +55,10 @@ export async function updateOrtZeile(input: {
}
// Beide Unique-Constraints liefern 23505; unterschieden wird am
// Constraint-Namen in der Postgres-Meldung.
function duplikatFehler(error: { message: string }): string {
return error.message.includes("fahrzeuge_fin_key")
// 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.";
}

View File

@ -0,0 +1,40 @@
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<FirmaUebersicht[]> {
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<FirmenAdmin[]> {
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 };
})
);
}

View File

@ -0,0 +1,10 @@
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);
});
});

View File

@ -0,0 +1,8 @@
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";
}

View File

@ -0,0 +1,37 @@
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!" } });
});
});

View File

@ -0,0 +1,34 @@
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 } };
}

View File

@ -3,6 +3,12 @@ import type { NextConfig } from "next";
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",
},
},
};
export default nextConfig;

View File

@ -0,0 +1,40 @@
// Legt den Plattform-Betreiber (Rolle superadmin, ohne Firma) an.
// Aufruf: SUPABASE_URL=http://localhost:8000 SUPABASE_SERVICE_ROLE_KEY=... \
// node scripts/superadmin-anlegen.mjs <email> <passwort> <name>
// 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 <email> <passwort> <name>");
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})`);