1
0
Fork 0

fix: Firma loeschen bei >1000 Auftraegen und firmenfremden Nutzerverweisen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jonny 2026-11-07 11:21:39 +01:00
parent a1f292d449
commit e52fe6a51d
5 changed files with 85 additions and 7 deletions

View File

@ -69,6 +69,14 @@ begin
delete from public.fahrzeuge 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.auftragsnummer_zaehler where firma_id = p_firma_id;
delete from public.nutzer_details 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 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; delete from public.firmen where id = p_firma_id;

View File

@ -1,5 +1,5 @@
begin; begin;
select plan(23); select plan(25);
-- Firma A (deaktiviert, wird geloescht) und Firma B (aktiv, muss bleiben) -- Firma A (deaktiviert, wird geloescht) und Firma B (aktiv, muss bleiben)
insert into public.firmen (id, name, aktiv) values insert into public.firmen (id, name, aktiv) values
@ -51,6 +51,20 @@ insert into public.auftrag_fotos (auftrag_id, position, storage_path, uploaded_b
insert into public.arbeitszeiten (fahrer_id, kommt_um, firma_id) values 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'); ('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 -- 1) aktive Firma laesst sich nicht loeschen
select throws_ok( select throws_ok(
$$ select public.firma_endgueltig_loeschen('00000000-0000-0000-0000-0000000fb001', '5a000000-0000-0000-0000-0000000005a1') $$, $$ select public.firma_endgueltig_loeschen('00000000-0000-0000-0000-0000000fb001', '5a000000-0000-0000-0000-0000000005a1') $$,
@ -107,7 +121,23 @@ select is(
+ (select count(*)::int from public.orte 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.profiles where firma_id = '00000000-0000-0000-0000-0000000fb001')
+ (select count(*)::int from public.firmen where id = '00000000-0000-0000-0000-0000000fb001'), + (select count(*)::int from public.firmen where id = '00000000-0000-0000-0000-0000000fb001'),
5, 'Firma B bleibt vollstaendig erhalten' 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 -- 7) genau ein Loesch-Eintrag im Audit-Log

View File

@ -76,7 +76,8 @@ export default async function PlattformFirmaPage({
</Card> </Card>
<Card> <Card>
<h2 className="mb-4 font-semibold text-asphalt-grey">Weiteren Admin anlegen</h2> <form action={legeFirmenAdminAn.bind(null, firma.id)}> <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"> <FormField label="Name" htmlFor="admin-name">
<input id="admin-name" name="name" required className={FIELD_CLASSES} /> <input id="admin-name" name="name" required className={FIELD_CLASSES} />
</FormField> </FormField>

View File

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { inBloecken } from "./firma-loeschen"; import { inBloecken, loescheFirmenDateien } from "./firma-loeschen";
describe("inBloecken", () => { describe("inBloecken", () => {
it("teilt in Bloecke der angegebenen Groesse", () => { it("teilt in Bloecke der angegebenen Groesse", () => {
@ -9,3 +9,38 @@ describe("inBloecken", () => {
expect(inBloecken([], 1000)).toEqual([]); 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

@ -1,4 +1,5 @@
import type { SupabaseClient } from "@supabase/supabase-js"; import type { SupabaseClient } from "@supabase/supabase-js";
import { ladeInBloecken } from "@/lib/supabase/in-bloecken";
export type LoeschUmfang = { export type LoeschUmfang = {
nutzer: number; nutzer: number;
@ -59,9 +60,12 @@ export async function loescheFirmenDateien(
firmaId: string firmaId: string
): Promise<{ ok: true } | { ok: false; fehler: string }> { ): Promise<{ ok: true } | { ok: false; fehler: string }> {
try { try {
const { data: auftraege, error } = await admin.from("auftraege").select("id").eq("firma_id", firmaId); // In Bloecken laden: PostgREST liefert hoechstens max_rows Zeilen je Anfrage.
if (error) throw new Error(`Auftraege laden: ${error.message}`); const auftraege = await ladeInBloecken<{ id: string }>((von, bis) =>
const ids = (auftraege ?? []).map((a: { id: string }) => a.id); 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 bucket of AUFTRAGS_BUCKETS) {
for (const block of inBloecken(ids, 10)) { for (const block of inBloecken(ids, 10)) {