Merge feature/firma-loeschen: Superadmin kann deaktivierte Firma endgueltig loeschen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jonny 2026-11-07 12:08:55 +01:00
commit 97e3b5cd5d
10 changed files with 505 additions and 6 deletions

View File

@ -0,0 +1,96 @@
-- Firma endgueltig loeschen (Superadmin). Spec: docs/superpowers/specs/2026-11-06-firma-loeschen-design.md
--
-- Storage-Dateien loescht vorher die Server Action ueber die Storage-API
-- (storage.objects ist per Trigger protect_objects_delete gegen direktes
-- SQL-Loeschen geschuetzt). Diese Funktion entfernt alle Datenbankdaten der
-- Firma atomar -- inklusive Logins (auth.users) und Audit-Log -- und
-- hinterlaesst genau einen Audit-Eintrag "firma/geloescht".
-- Audit-Log bleibt unveraenderlich. Einzige Ausnahme: DELETE von Zeilen genau
-- der Firma, die firma_endgueltig_loeschen() in dieser Transaktion loescht
-- (transaktionslokale Einstellung app.firma_loeschen). authenticated und
-- service_role haben weiterhin kein DELETE-Grant auf audit_log; die Ausnahme
-- ist also nur aus security-definer-Code des Eigentuemers erreichbar.
create or replace function public.audit_log_unveraenderlich()
returns trigger
language plpgsql
set search_path = public
as $$
begin
if tg_op = 'DELETE'
and old.firma_id is not null
and current_setting('app.firma_loeschen', true) = old.firma_id::text then
return old;
end if;
raise exception 'Audit-Log-Eintraege sind unveraenderlich' using errcode = '42501';
end;
$$;
create or replace function public.firma_endgueltig_loeschen(p_firma_id uuid, p_akteur_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = public
as $$
declare
v_name text;
v_aktiv boolean;
v_zaehler jsonb;
begin
select name, aktiv into v_name, v_aktiv from public.firmen where id = p_firma_id for update;
if not found then
raise exception 'Firma nicht gefunden';
end if;
if v_aktiv then
raise exception 'Firma ist noch aktiv';
end if;
v_zaehler := jsonb_build_object(
'nutzer', (select count(*) from public.profiles where firma_id = p_firma_id),
'auftraege', (select count(*) from public.auftraege where firma_id = p_firma_id),
'fotos', (select count(*) from public.auftrag_fotos where firma_id = p_firma_id),
'orte', (select count(*) from public.orte where firma_id = p_firma_id),
'fahrzeuge', (select count(*) from public.fahrzeuge where firma_id = p_firma_id),
'arbeitszeiten', (select count(*) from public.arbeitszeiten where firma_id = p_firma_id)
);
perform set_config('app.firma_loeschen', p_firma_id::text, true);
-- Reihenfolge folgt den Fremdschluesseln (alle ohne Cascade ausser
-- auftrag_fotos->auftraege, nutzer_details->profiles, profiles->auth.users,
-- firmen_smtp->firmen).
delete from public.auftrag_fotos where firma_id = p_firma_id;
delete from public.notification_outbox where firma_id = p_firma_id;
update public.auftraege set vorgaenger_auftrag_id = null
where firma_id = p_firma_id and vorgaenger_auftrag_id is not null;
delete from public.auftraege where firma_id = p_firma_id;
delete from public.arbeitszeiten where firma_id = p_firma_id;
delete from public.orte where firma_id = p_firma_id;
delete from public.fahrzeuge where firma_id = p_firma_id;
delete from public.auftragsnummer_zaehler where firma_id = p_firma_id;
delete from public.nutzer_details where firma_id = p_firma_id;
-- Firmenfremde Verweise auf Nutzer dieser Firma leeren (per RLS nicht
-- ausgeschlossen, z.B. orte.created_by); sonst blockiert der FK das Loeschen.
update public.orte set created_by = null
where created_by in (select id from public.profiles where firma_id = p_firma_id);
update public.auftrag_fotos set uploaded_by = null
where uploaded_by in (select id from public.profiles where firma_id = p_firma_id);
update public.arbeitszeiten set korrigiert_von = null
where korrigiert_von in (select id from public.profiles where firma_id = p_firma_id);
delete from auth.users where id in (select id from public.profiles where firma_id = p_firma_id);
delete from public.firmen where id = p_firma_id;
-- Inklusive der Eintraege, die die Audit-Trigger beim Loeschen eben erzeugt haben.
delete from public.audit_log where firma_id = p_firma_id;
perform public.audit_schreiben(
p_firma_id, p_akteur_id, 'firma', 'geloescht', p_firma_id::text, null,
jsonb_build_object('name', v_name) || v_zaehler
);
return v_zaehler;
end;
$$;
revoke execute on function public.firma_endgueltig_loeschen(uuid, uuid) from public, anon, authenticated;
grant execute on function public.firma_endgueltig_loeschen(uuid, uuid) to service_role;

View File

@ -0,0 +1,152 @@
begin;
select plan(25);
-- Firma A (deaktiviert, wird geloescht) und Firma B (aktiv, muss bleiben)
insert into public.firmen (id, name, aktiv) values
('00000000-0000-0000-0000-0000000fa001', 'Loesch A', false),
('00000000-0000-0000-0000-0000000fb001', 'Bleibt B', true);
insert into auth.users (id, email) values
('aa000000-0000-0000-0000-000000000001', 'admin-a@loeschen.test.local'),
('aa000000-0000-0000-0000-000000000002', 'fahrer-a@loeschen.test.local'),
('bb000000-0000-0000-0000-000000000001', 'admin-b@loeschen.test.local'),
('5a000000-0000-0000-0000-0000000005a1', 'super@loeschen.test.local');
update public.profiles set firma_id = '00000000-0000-0000-0000-0000000fa001', role = 'admin'
where id = 'aa000000-0000-0000-0000-000000000001';
update public.profiles set firma_id = '00000000-0000-0000-0000-0000000fa001', role = 'fahrer'
where id = 'aa000000-0000-0000-0000-000000000002';
update public.profiles set firma_id = '00000000-0000-0000-0000-0000000fb001', role = 'admin'
where id = 'bb000000-0000-0000-0000-000000000001';
update public.profiles set role = 'superadmin' where id = '5a000000-0000-0000-0000-0000000005a1';
insert into public.nutzer_details (user_id, firma_id) values
('aa000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-0000000fa001');
insert into public.orte (id, adresse, ansprechpartner, firma_id, created_by) values
('aa000000-0000-0000-0000-0000000000c1', 'Ort A1', 'Herr A', '00000000-0000-0000-0000-0000000fa001', 'aa000000-0000-0000-0000-000000000001'),
('aa000000-0000-0000-0000-0000000000c2', 'Ort A2', 'Frau A', '00000000-0000-0000-0000-0000000fa001', 'aa000000-0000-0000-0000-000000000001'),
('bb000000-0000-0000-0000-0000000000c1', 'Ort B1', 'Herr B', '00000000-0000-0000-0000-0000000fb001', null),
('bb000000-0000-0000-0000-0000000000c2', 'Ort B2', 'Frau B', '00000000-0000-0000-0000-0000000fb001', null);
insert into public.fahrzeuge (id, kennzeichen, firma_id) values
('aa000000-0000-0000-0000-0000000000d1', 'LA-A 1', '00000000-0000-0000-0000-0000000fa001'),
('bb000000-0000-0000-0000-0000000000d1', 'LB-B 1', '00000000-0000-0000-0000-0000000fb001');
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, zugewiesen_an, status, firma_id) values
('aa000000-0000-0000-0000-0000000000e1', 'aa000000-0000-0000-0000-0000000000c1', 'aa000000-0000-0000-0000-0000000000c2',
'aa000000-0000-0000-0000-0000000000d1', 'aa000000-0000-0000-0000-000000000001', 'aa000000-0000-0000-0000-000000000002',
'zugewiesen', '00000000-0000-0000-0000-0000000fa001'),
('bb000000-0000-0000-0000-0000000000e1', 'bb000000-0000-0000-0000-0000000000c1', 'bb000000-0000-0000-0000-0000000000c2',
'bb000000-0000-0000-0000-0000000000d1', 'bb000000-0000-0000-0000-000000000001', null,
'offen', '00000000-0000-0000-0000-0000000fb001');
-- Folgeauftrag in A (Selbstreferenz)
insert into public.auftraege (abholort_id, zielort_id, fahrzeug_id, erstellt_von, vorgaenger_auftrag_id, firma_id) values
('aa000000-0000-0000-0000-0000000000c2', 'aa000000-0000-0000-0000-0000000000c1', 'aa000000-0000-0000-0000-0000000000d1',
'aa000000-0000-0000-0000-000000000001', 'aa000000-0000-0000-0000-0000000000e1', '00000000-0000-0000-0000-0000000fa001');
insert into public.auftrag_fotos (auftrag_id, position, storage_path, uploaded_by, firma_id) values
('aa000000-0000-0000-0000-0000000000e1', 'front', 'aa000000-0000-0000-0000-0000000000e1/front.jpg',
'aa000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-0000000fa001');
insert into public.arbeitszeiten (fahrer_id, kommt_um, firma_id) values
('aa000000-0000-0000-0000-000000000002', now() - interval '2 hours', '00000000-0000-0000-0000-0000000fa001');
-- Firmenfremde Verweise aus B auf Nutzer von A (per RLS fuer B-Nutzer
-- moeglich, z.B. PATCH orte.created_by / auftrag_fotos.uploaded_by).
insert into public.orte (id, adresse, ansprechpartner, firma_id, created_by) values
('bb000000-0000-0000-0000-0000000000c3', 'Ort B3', 'Herr C', '00000000-0000-0000-0000-0000000fb001', 'aa000000-0000-0000-0000-000000000001');
insert into public.auftrag_fotos (auftrag_id, position, storage_path, uploaded_by, firma_id) values
('bb000000-0000-0000-0000-0000000000e1', 'front', 'bb000000-0000-0000-0000-0000000000e1/front.jpg',
'aa000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-0000000fb001');
create temp table b_vorher as select
(select array_agg(id order by id) from public.audit_log where firma_id = '00000000-0000-0000-0000-0000000fb001') as audit,
(select count(*) from public.fahrzeuge where firma_id = '00000000-0000-0000-0000-0000000fb001') as fahrzeuge,
(select count(*) from public.auftrag_fotos where firma_id = '00000000-0000-0000-0000-0000000fb001') as fotos,
(select count(*) from auth.users where id in ('bb000000-0000-0000-0000-000000000001', '5a000000-0000-0000-0000-0000000005a1')) as logins;
-- 1) aktive Firma laesst sich nicht loeschen
select throws_ok(
$$ select public.firma_endgueltig_loeschen('00000000-0000-0000-0000-0000000fb001', '5a000000-0000-0000-0000-0000000005a1') $$,
'P0001', 'Firma ist noch aktiv',
'Aktive Firma wird nicht geloescht'
);
-- 2) unbekannte Firma
select throws_ok(
$$ select public.firma_endgueltig_loeschen(gen_random_uuid(), '5a000000-0000-0000-0000-0000000005a1') $$,
'P0001', 'Firma nicht gefunden',
'Unbekannte Firma meldet Fehler'
);
-- 3) Rechte
select ok(not has_function_privilege('authenticated', 'public.firma_endgueltig_loeschen(uuid, uuid)', 'execute'),
'authenticated darf die Funktion nicht ausfuehren');
select ok(not has_function_privilege('anon', 'public.firma_endgueltig_loeschen(uuid, uuid)', 'execute'),
'anon darf die Funktion nicht ausfuehren');
select ok(has_function_privilege('service_role', 'public.firma_endgueltig_loeschen(uuid, uuid)', 'execute'),
'service_role darf die Funktion ausfuehren');
-- 4) Audit-Log bleibt ohne Einstellung unveraenderlich
select throws_ok(
$$ delete from public.audit_log where firma_id = '00000000-0000-0000-0000-0000000fb001' $$,
'42501', null,
'Audit-Log-Eintraege bleiben ohne Loesch-Einstellung unveraenderlich'
);
-- 5) Loeschen von A
create temp table ergebnis as
select public.firma_endgueltig_loeschen('00000000-0000-0000-0000-0000000fa001', '5a000000-0000-0000-0000-0000000005a1') as z;
select is((select (z ->> 'nutzer')::int from ergebnis), 2, 'Zaehler Nutzer');
select is((select (z ->> 'auftraege')::int from ergebnis), 2, 'Zaehler Auftraege');
select is((select (z ->> 'fotos')::int from ergebnis), 1, 'Zaehler Fotos');
select is((select count(*)::int from public.firmen where id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Firma A weg');
select is((select count(*)::int from public.auftraege where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Auftraege A weg');
select is((select count(*)::int from public.auftrag_fotos where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Fotos A weg');
select is((select count(*)::int from public.orte where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Orte A weg');
select is((select count(*)::int from public.fahrzeuge where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Fahrzeuge A weg');
select is((select count(*)::int from public.arbeitszeiten where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Arbeitszeiten A weg');
select is((select count(*)::int from public.nutzer_details where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Nutzerdetails A weg');
select is((select count(*)::int from public.notification_outbox where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Outbox A weg');
select is((select count(*)::int from public.auftragsnummer_zaehler where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Nummernzaehler A weg');
select is((select count(*)::int from public.profiles where firma_id = '00000000-0000-0000-0000-0000000fa001'), 0, 'Profile A weg');
select is((select count(*)::int from auth.users where id in ('aa000000-0000-0000-0000-000000000001', 'aa000000-0000-0000-0000-000000000002')), 0,
'Logins A weg');
-- 6) B unveraendert
select is(
(select count(*)::int from public.auftraege where firma_id = '00000000-0000-0000-0000-0000000fb001')
+ (select count(*)::int from public.orte where firma_id = '00000000-0000-0000-0000-0000000fb001')
+ (select count(*)::int from public.profiles where firma_id = '00000000-0000-0000-0000-0000000fb001')
+ (select count(*)::int from public.firmen where id = '00000000-0000-0000-0000-0000000fb001'),
6, 'Firma B bleibt vollstaendig erhalten'
);
select is(
(select row(
(select array_agg(id order by id) from public.audit_log where firma_id = '00000000-0000-0000-0000-0000000fb001'
and id in (select unnest(audit) from b_vorher)),
(select count(*) from public.fahrzeuge where firma_id = '00000000-0000-0000-0000-0000000fb001'),
(select count(*) from public.auftrag_fotos where firma_id = '00000000-0000-0000-0000-0000000fb001'),
(select count(*) from auth.users where id in ('bb000000-0000-0000-0000-000000000001', '5a000000-0000-0000-0000-0000000005a1'))
)::text),
(select row(audit, fahrzeuge, fotos, logins)::text from b_vorher),
'Bestehende Audit-Eintraege, Fahrzeuge, Fotos und Logins von B sowie der Superadmin bleiben'
);
select is(
(select created_by from public.orte where id = 'bb000000-0000-0000-0000-0000000000c3'),
null::uuid,
'Firmenfremder Verweis auf geloeschten Nutzer wird geleert'
);
-- 7) genau ein Loesch-Eintrag im Audit-Log
select is((select count(*)::int from public.audit_log where firma_id = '00000000-0000-0000-0000-0000000fa001'), 1,
'Nur der Loesch-Eintrag bleibt im Audit-Log');
select is(
(select bereich || '/' || aktion || '/' || akteur_rolle from public.audit_log where firma_id = '00000000-0000-0000-0000-0000000fa001'),
'firma/geloescht/superadmin', 'Loesch-Eintrag mit Superadmin als Akteur'
);
select * from finish();
rollback;

View File

@ -5,7 +5,9 @@ import { loadProfile } from "@/lib/auth/profile";
import { pruefeSuperadmin } from "@/lib/plattform/superadmin";
import { ladeFirmaFuerPlattform, listFirmenAdmins } from "@/lib/plattform/queries";
import { formatiereRollen } from "@/lib/plattform/rollen";
import { legeFirmenAdminAn, setzeAdminPasswort, setzeFirmaAktiv } from "../actions";
import { ladeLoeschUmfang } from "@/lib/plattform/firma-loeschen";
import { legeFirmenAdminAn, loescheFirma, setzeAdminPasswort, setzeFirmaAktiv } from "../actions";
import { FirmaLoeschenFormular } from "@/components/plattform/FirmaLoeschenFormular";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
@ -26,7 +28,10 @@ export default async function PlattformFirmaPage({
const admin = createAdminClient();
const firma = await ladeFirmaFuerPlattform(admin, id);
if (!firma) notFound();
const admins = await listFirmenAdmins(admin, id);
const [admins, umfang] = await Promise.all([
listFirmenAdmins(admin, id),
firma.aktiv ? Promise.resolve(null) : ladeLoeschUmfang(admin, id),
]);
return (
<div className="mx-auto flex max-w-2xl flex-col gap-6 p-4 md:p-8">
@ -85,6 +90,28 @@ export default async function PlattformFirmaPage({
<Button type="submit">Admin anlegen</Button>
</form>
</Card>
<Card>
<h2 className="mb-4 font-semibold text-status-danger">Firma endgültig löschen</h2>
{firma.aktiv || !umfang ? (
<p className="text-asphalt-grey">Zum Löschen die Firma zuerst deaktivieren.</p>
) : (
<>
<p className="mb-2 text-asphalt-grey">
Das löscht alle Daten, Dateien und Logins dieser Firma unwiderruflich:
</p>
<ul className="mb-4 list-disc pl-5 text-asphalt-grey">
<li>{umfang.nutzer} Nutzer</li>
<li>{umfang.auftraege} Aufträge</li>
<li>{umfang.fotos} Fotos</li>
<li>{umfang.orte} Orte</li>
<li>{umfang.fahrzeuge} Fahrzeuge</li>
<li>{umfang.arbeitszeiten} Arbeitszeiten</li>
</ul>
<FirmaLoeschenFormular firmenname={firma.name} aktion={loescheFirma.bind(null, firma.id)} />
</>
)}
</Card>
</div>
);
}

View File

@ -8,7 +8,9 @@ import { validatePasswort } from "@/lib/auth/passwort";
import { protokolliere } from "@/lib/audit/protokollieren";
import { legeNutzerInFirmaAn } from "@/lib/nutzerverwaltung/nutzer-anlegen";
import { pruefeSuperadmin } from "@/lib/plattform/superadmin";
import { validateFirmaAnlegen, validateFirmenAdmin } from "@/lib/plattform/validate";
import { pruefeLoeschBestaetigung, validateFirmaAnlegen, validateFirmenAdmin } from "@/lib/plattform/validate";
import { ladeFirmaFuerPlattform } from "@/lib/plattform/queries";
import { loescheFirmenDateien } from "@/lib/plattform/firma-loeschen";
function zurueck(pfad: string, fehler?: string): never {
redirect(fehler ? `${pfad}?error=${encodeURIComponent(fehler)}` : pfad);
@ -56,6 +58,36 @@ export async function setzeFirmaAktiv(firmaId: string, aktiv: boolean): Promise<
zurueck(`/plattform/${firmaId}`, error ? "Status konnte nicht geändert werden." : undefined);
}
// Endgueltiges Loeschen einer deaktivierten Firma. Erst die Storage-Dateien
// (solange die Auftrags-IDs noch existieren), dann atomar alle DB-Daten. Scheitert
// der DB-Teil, bleibt die Firma deaktiviert bestehen und das Loeschen laesst
// sich wiederholen.
export async function loescheFirma(firmaId: string, formData: FormData): Promise<void> {
const superadminId = await sicherSuperadmin();
const admin = createAdminClient(superadminId);
const firma = await ladeFirmaFuerPlattform(admin, firmaId);
if (!firma) zurueck("/plattform", "Firma nicht gefunden.");
if (firma.aktiv) zurueck(`/plattform/${firmaId}`, "Zum Löschen die Firma zuerst deaktivieren.");
if (!pruefeLoeschBestaetigung(formData.get("bestaetigung"), firma.name)) {
zurueck(`/plattform/${firmaId}`, "Der eingegebene Name stimmt nicht.");
}
const dateien = await loescheFirmenDateien(admin, firmaId);
if (!dateien.ok) {
console.error(`Firma ${firmaId}: Dateien loeschen fehlgeschlagen: ${dateien.fehler}`);
zurueck(`/plattform/${firmaId}`, "Dateien konnten nicht gelöscht werden. Bitte erneut versuchen.");
}
const { error } = await admin.rpc("firma_endgueltig_loeschen", { p_firma_id: firmaId, p_akteur_id: superadminId });
if (error) {
console.error(`Firma ${firmaId}: Loeschen fehlgeschlagen: ${error.message}`);
zurueck(`/plattform/${firmaId}`, "Firma konnte nicht gelöscht werden.");
}
revalidatePath("/plattform");
redirect(`/plattform?hinweis=${encodeURIComponent(`Firma ${firma.name} wurde gelöscht.`)}`);
}
export async function legeFirmenAdminAn(firmaId: string, formData: FormData): Promise<void> {
const superadminId = await sicherSuperadmin();
const v = validateFirmenAdmin({ name: formData.get("name"), email: formData.get("email"), passwort: formData.get("passwort") });

View File

@ -12,11 +12,15 @@ 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 }> }) {
export default async function PlattformPage({
searchParams,
}: {
searchParams: Promise<{ error?: string; hinweis?: string }>;
}) {
if (!pruefeSuperadmin(await loadProfile())) {
redirect("/dashboard");
}
const { error } = await searchParams;
const { error, hinweis } = await searchParams;
const firmen = await listFirmen(createAdminClient());
return (
@ -24,6 +28,11 @@ export default async function PlattformPage({ searchParams }: { searchParams: Pr
<InstallHinweis />
<h1 className="text-xl font-semibold text-asphalt-grey">Plattform-Verwaltung</h1>
{error && <Alert>{error}</Alert>}
{hinweis && (
<p role="status" className="rounded-md border border-status-success bg-green-50 px-4 py-3 text-asphalt-grey">
{hinweis}
</p>
)}
<Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">Firmen</h2>

View File

@ -0,0 +1,36 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/Button";
import { FIELD_CLASSES, FormField } from "@/components/ui/FormField";
// Rueckfrage vor dem endgueltigen Loeschen: Button erst aktiv, wenn der
// Firmenname exakt eingetippt ist. Die Server Action prueft das erneut.
export function FirmaLoeschenFormular({
firmenname,
aktion,
}: {
firmenname: string;
aktion: (formData: FormData) => Promise<void>;
}) {
const [eingabe, setEingabe] = useState("");
const passt = eingabe.trim() !== "" && eingabe.trim() === firmenname.trim();
return (
<form action={aktion}>
<FormField label={`Zum Bestätigen den Firmennamen eingeben: ${firmenname}`} htmlFor="loeschen-bestaetigung">
<input
id="loeschen-bestaetigung"
name="bestaetigung"
autoComplete="off"
value={eingabe}
onChange={(e) => setEingabe(e.target.value)}
className={FIELD_CLASSES}
/>
</FormField>
<Button type="submit" variant="destructive" disabled={!passt}>
Endgültig löschen
</Button>
</form>
);
}

View File

@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { inBloecken, loescheFirmenDateien } from "./firma-loeschen";
describe("inBloecken", () => {
it("teilt in Bloecke der angegebenen Groesse", () => {
expect(inBloecken([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
});
it("liefert fuer eine leere Liste keine Bloecke", () => {
expect(inBloecken([], 1000)).toEqual([]);
});
});
describe("loescheFirmenDateien", () => {
it("listet die Ordner aller Auftraege, auch ueber 1000 hinaus", async () => {
const ids = Array.from({ length: 1500 }, (_, i) => `a${String(i).padStart(4, "0")}`);
const gelistet = new Set<string>();
const admin = {
from: () => {
const q = {
select: () => q,
eq: () => q,
order: () => q,
// Wie PostgREST mit max_rows=1000: ohne range nur die ersten 1000.
range: (von: number, bis: number) =>
Promise.resolve({ data: ids.slice(von, Math.min(bis + 1, von + 1000)).map((id) => ({ id })), error: null }),
then: (ok: (r: unknown) => unknown) =>
Promise.resolve({ data: ids.slice(0, 1000).map((id) => ({ id })), error: null }).then(ok),
};
return q;
},
storage: {
from: (bucket: string) => ({
list: (ordner: string) => {
if (bucket === "auftrag-fotos") gelistet.add(ordner);
return Promise.resolve({ data: [], error: null });
},
remove: () => Promise.resolve({ error: null }),
}),
},
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const ergebnis = await loescheFirmenDateien(admin as any, "f1");
expect(ergebnis).toEqual({ ok: true });
expect(gelistet.size).toBe(1500);
});
});

View File

@ -0,0 +1,81 @@
import type { SupabaseClient } from "@supabase/supabase-js";
import { ladeInBloecken } from "@/lib/supabase/in-bloecken";
export type LoeschUmfang = {
nutzer: number;
auftraege: number;
fotos: number;
orte: number;
fahrzeuge: number;
arbeitszeiten: number;
};
export function inBloecken<T>(liste: T[], groesse: number): T[][] {
const bloecke: T[][] = [];
for (let i = 0; i < liste.length; i += groesse) bloecke.push(liste.slice(i, i + groesse));
return bloecke;
}
async function zaehle(admin: SupabaseClient, tabelle: string, firmaId: string): Promise<number> {
const { count, error } = await admin.from(tabelle).select("*", { count: "exact", head: true }).eq("firma_id", firmaId);
if (error) throw new Error(`Zaehlen ${tabelle} fehlgeschlagen: ${error.message}`);
return count ?? 0;
}
// Nur mit dem Service-Client aufrufen.
export async function ladeLoeschUmfang(admin: SupabaseClient, firmaId: string): Promise<LoeschUmfang> {
const [nutzer, auftraege, fotos, orte, fahrzeuge, arbeitszeiten] = await Promise.all(
["profiles", "auftraege", "auftrag_fotos", "orte", "fahrzeuge", "arbeitszeiten"].map((t) => zaehle(admin, t, firmaId))
);
return { nutzer, auftraege, fotos, orte, fahrzeuge, arbeitszeiten };
}
const SEITE = 1000;
const AUFTRAGS_BUCKETS = ["auftrag-fotos", "auftrag-unterschriften"] as const;
async function listeOrdner(admin: SupabaseClient, bucket: string, ordner: string): Promise<string[]> {
const pfade: string[] = [];
for (let offset = 0; ; offset += SEITE) {
const { data, error } = await admin.storage.from(bucket).list(ordner, { limit: SEITE, offset });
if (error) throw new Error(`${bucket}/${ordner}: ${error.message}`);
// Ordner-Platzhalter (id === null) ueberspringen; die Pfade liegen flach.
for (const objekt of data ?? []) if (objekt.id) pfade.push(`${ordner}/${objekt.name}`);
if (!data || data.length < SEITE) return pfade;
}
}
async function entferne(admin: SupabaseClient, bucket: string, pfade: string[]): Promise<void> {
for (const block of inBloecken(pfade, SEITE)) {
const { error } = await admin.storage.from(bucket).remove(block);
if (error) throw new Error(`${bucket} loeschen: ${error.message}`);
}
}
// Loescht alle Storage-Dateien der Firma: Fotos und Unterschriften je Auftrag
// (Ordner <auftragId>/) sowie Logo und App-Icon (Ordner <firmaId>/).
// Muss VOR firma_endgueltig_loeschen laufen, solange die Auftrags-IDs noch
// existieren. Nur mit dem Service-Client aufrufen.
export async function loescheFirmenDateien(
admin: SupabaseClient,
firmaId: string
): Promise<{ ok: true } | { ok: false; fehler: string }> {
try {
// In Bloecken laden: PostgREST liefert hoechstens max_rows Zeilen je Anfrage.
const auftraege = await ladeInBloecken<{ id: string }>((von, bis) =>
admin.from("auftraege").select("id").eq("firma_id", firmaId).order("id").range(von, bis)
);
if (auftraege.error) throw new Error("Auftraege laden fehlgeschlagen");
const ids = auftraege.data.map((a) => a.id);
for (const bucket of AUFTRAGS_BUCKETS) {
for (const block of inBloecken(ids, 10)) {
const pfade = (await Promise.all(block.map((id) => listeOrdner(admin, bucket, id)))).flat();
await entferne(admin, bucket, pfade);
}
}
await entferne(admin, "firmen-logos", await listeOrdner(admin, "firmen-logos", firmaId));
return { ok: true };
} catch (e) {
return { ok: false, fehler: e instanceof Error ? e.message : String(e) };
}
}

View File

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { validateFirmaAnlegen, validateFirmenAdmin } from "./validate";
import { pruefeLoeschBestaetigung, validateFirmaAnlegen, validateFirmenAdmin } from "./validate";
describe("validateFirmenAdmin", () => {
it("uebernimmt gueltige Werte", () => {
@ -35,3 +35,16 @@ describe("validateFirmaAnlegen", () => {
expect(e).toEqual({ valid: true, firmenname: "Firma B", admin: { name: "A", email: "a@b.de", passwort: "Passwort123!" } });
});
});
describe("pruefeLoeschBestaetigung", () => {
it("akzeptiert den exakten Namen mit Leerzeichen am Rand", () => {
expect(pruefeLoeschBestaetigung(" Firma A ", "Firma A")).toBe(true);
});
it("verlangt exakte Gross-/Kleinschreibung", () => {
expect(pruefeLoeschBestaetigung("firma a", "Firma A")).toBe(false);
});
it("lehnt leere oder fehlende Eingaben ab", () => {
expect(pruefeLoeschBestaetigung("", "Firma A")).toBe(false);
expect(pruefeLoeschBestaetigung(null, "Firma A")).toBe(false);
});
});

View File

@ -32,3 +32,10 @@ export function validateFirmaAnlegen(
if (!admin.valid) return admin;
return { valid: true, firmenname, admin: { name: admin.name, email: admin.email, passwort: admin.passwort } };
}
// Rueckfrage beim Loeschen einer Firma: der Firmenname muss exakt (nur
// Leerzeichen am Rand werden ignoriert) eingetippt werden.
export function pruefeLoeschBestaetigung(eingabe: unknown, firmenname: string): boolean {
const wert = text(eingabe);
return wert !== "" && wert === firmenname.trim();
}