forked from fahrPool/fahrPool
412 lines
16 KiB
PL/PgSQL
412 lines
16 KiB
PL/PgSQL
-- 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;
|
||
$$;
|