From c9d3f3d1dc4e1e68593b3a1f7658fca197469f80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Tue, 25 Aug 2026 01:28:34 +0200 Subject: [PATCH] feat: reset editorial usage data; fix hard delete FK order Admins can now wipe an editorial's usage footprint (usages, download events, billing reports incl. items and related audit rows) so test accounts no longer pollute dashboard statistics. Grants, price, status and login stay untouched; the action is confirmed by typing the editorial name. Hard delete previously failed with FK violations as soon as a usage had ever been billed or an address saved: - billing_report_items (restrict -> usages) were never deleted - billing_address_versions were deleted before the referencing current_billing_address_version_id and their self-referencing superseded_by_id, both restrict Both are now handled in correct FK order inside the transaction; the audit trail of the deleted editorial is purged and verification tokens are removed. --- src/app/admin/redaktionen/[id]/actions.ts | 28 ++++ src/modules/editorials/ResetUsageCard.tsx | 73 +++++++++++ src/modules/editorials/admin-detail.tsx | 3 + src/modules/editorials/service.test.ts | 13 ++ src/modules/editorials/service.ts | 150 +++++++++++++++++++++- 5 files changed, 262 insertions(+), 5 deletions(-) create mode 100644 src/modules/editorials/ResetUsageCard.tsx diff --git a/src/app/admin/redaktionen/[id]/actions.ts b/src/app/admin/redaktionen/[id]/actions.ts index 3a1403a..0589617 100644 --- a/src/app/admin/redaktionen/[id]/actions.ts +++ b/src/app/admin/redaktionen/[id]/actions.ts @@ -62,6 +62,34 @@ export async function hardDeleteEditorialAction(editorialId: string): Promise { + const admin = await requireAdmin(new Headers(await headers())); + const safeEditorialId = requiredId(editorialId); + + try { + const result = await editorialService.resetUsageData({ + editorialId: safeEditorialId, + adminUserId: admin.userId, + }); + revalidatePath(`/admin/redaktionen/${safeEditorialId}`); + revalidatePath("/admin/redaktionen"); + revalidatePath("/admin"); + revalidatePath("/admin/abrechnungen"); + return { + ok: true, + message: `${result.deletedUsages} Nutzung(en) und ${result.deletedReports} Abrechnung(en) gelöscht.`, + }; + } catch (error) { + if (error instanceof EditorialServiceError && error.code === "EDITORIAL_NOT_FOUND") { + return { ok: false, message: "Redaktion nicht gefunden." }; + } + console.error("Failed to reset usage data:", error); + return { ok: false, message: "Das Zurücksetzen ist fehlgeschlagen." }; + } +} + export async function suspendEditorialAction(editorialId: string): Promise { const admin = await requireAdmin(new Headers(await headers())); await editorialService.transitionEditorialStatus({ diff --git a/src/modules/editorials/ResetUsageCard.tsx b/src/modules/editorials/ResetUsageCard.tsx new file mode 100644 index 0000000..0ddcca6 --- /dev/null +++ b/src/modules/editorials/ResetUsageCard.tsx @@ -0,0 +1,73 @@ +"use client"; + +import { useState, useTransition } from "react"; + +import { resetUsageDataAction } from "@/app/admin/redaktionen/[id]/actions"; +import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Button } from "@/components/ui/button"; + +type ResetUsageCardProps = { + editorialId: string; + editorialName: string; +}; + +export function ResetUsageCard({ editorialId, editorialName }: ResetUsageCardProps) { + const [confirmText, setConfirmText] = useState(""); + const [isPending, startTransition] = useTransition(); + const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null); + const isConfirmed = confirmText === editorialName; + + function handleReset() { + if (!isConfirmed || isPending) return; + startTransition(async () => { + const actionResult = await resetUsageDataAction(editorialId); + setResult(actionResult); + if (actionResult.ok) { + setConfirmText(""); + } + }); + } + + return ( + + + Nutzungsdaten zurücksetzen + + Entfernt sämtliche Nutzungen, Downloads und Abrechnungen dieser Redaktion aus dem Portal + und der Statistik – z. B. für einen Test-Account. Albumrechte, Login und Einstellungen + bleiben unverändert. + + + +
+ + setConfirmText(e.target.value)} + placeholder={editorialName} + disabled={isPending} + /> +
+
+ + {result && ( +

+ {result.message} +

+ )} +
+
+
+ ); +} diff --git a/src/modules/editorials/admin-detail.tsx b/src/modules/editorials/admin-detail.tsx index 822db1c..2715c16 100644 --- a/src/modules/editorials/admin-detail.tsx +++ b/src/modules/editorials/admin-detail.tsx @@ -4,6 +4,7 @@ import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction, updateFlatrateAction } from "@/app/admin/redaktionen/[id]/actions"; import { DangerZone } from "./DangerZone"; +import { ResetUsageCard } from "./ResetUsageCard"; import { ApproveForm } from "./ApproveForm"; export type EditorialDetail = { @@ -179,6 +180,8 @@ export function EditorialDetailContent({ )} + + {!editorial.archivedAt && ( )} diff --git a/src/modules/editorials/service.test.ts b/src/modules/editorials/service.test.ts index 9fa5069..169e5d9 100644 --- a/src/modules/editorials/service.test.ts +++ b/src/modules/editorials/service.test.ts @@ -14,6 +14,7 @@ function createRepository(): EditorialServiceRepository & { transitionStatus: ReturnType; claimApprovalNotice: ReturnType; archiveEditorial: ReturnType; + resetUsageData: ReturnType; } { return { prepareApproval: vi.fn().mockResolvedValue({ @@ -28,6 +29,7 @@ function createRepository(): EditorialServiceRepository & { claimApprovalNotice: vi.fn().mockResolvedValue(true), archiveEditorial: vi.fn().mockResolvedValue(undefined), hardDeleteEditorial: vi.fn().mockResolvedValue(undefined), + resetUsageData: vi.fn().mockResolvedValue({ deletedUsages: 0, deletedReports: 0 }), }; } @@ -174,3 +176,14 @@ test("documents the shared editorial lock order for grant revocation", () => { "album_grants FOR UPDATE", ]); }); + +test("resetUsageData delegates to the repository with the acting admin", async () => { + const repository = createRepository(); + const service = createEditorialService({ repository, mailer: { sendApprovalNotice: vi.fn() } }); + repository.resetUsageData.mockResolvedValue({ deletedUsages: 7, deletedReports: 2 }); + + await expect( + service.resetUsageData({ editorialId: "e1", adminUserId: "a1" }), + ).resolves.toEqual({ deletedUsages: 7, deletedReports: 2 }); + expect(repository.resetUsageData).toHaveBeenCalledWith({ editorialId: "e1", adminUserId: "a1" }); +}); diff --git a/src/modules/editorials/service.ts b/src/modules/editorials/service.ts index 645a41a..09b6d5e 100644 --- a/src/modules/editorials/service.ts +++ b/src/modules/editorials/service.ts @@ -13,6 +13,7 @@ import { usages, lightboxItems, billingReports, + billingReportItems, albumAutoRules, } from "@/db/schema"; import type * as schema from "@/db/schema"; @@ -57,6 +58,10 @@ export type EditorialServiceRepository = { }): Promise; archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise; hardDeleteEditorial(editorialId: string): Promise; + resetUsageData(input: { + editorialId: string; + adminUserId: string; + }): Promise<{ deletedUsages: number; deletedReports: number }>; }; /** @@ -166,6 +171,10 @@ export function createEditorialService({ async hardDeleteEditorial(editorialId: string): Promise { await repository.hardDeleteEditorial(editorialId); }, + + async resetUsageData(input: { editorialId: string; adminUserId: string }) { + return repository.resetUsageData(input); + }, }; } @@ -526,30 +535,161 @@ export function createEditorialServiceRepository( await lockEditorialForMutation(transaction, editorialId); const [editorial] = await transaction - .select({ userId: editorialAccounts.userId }) + .select({ userId: editorialAccounts.userId, loginEmail: editorialAccounts.loginEmail }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)); if (!editorial) return; - // Cascade deletions manually due to restrict constraints + // Capture IDs for audit-trail cleanup before the referenced rows go + // away. + const usageIds = ( + await transaction + .select({ id: usages.id }) + .from(usages) + .where(eq(usages.editorialAccountId, editorialId)) + ).map((row) => row.id); + const reportIds = ( + await transaction + .select({ id: billingReports.id }) + .from(billingReports) + .where(eq(billingReports.editorialAccountId, editorialId)) + ).map((row) => row.id); + + // Cascade deletions manually due to restrict constraints. Order is + // dictated by the FK graph: + // billing_report_items -> usages (restrict) + // download_events -> usages (restrict) + // usages.billing_report_id -> billing_reports (child side) + if (reportIds.length > 0) { + await transaction + .delete(billingReportItems) + .where(inArray(billingReportItems.billingReportId, reportIds)); + } await transaction.delete(downloadEvents).where(eq(downloadEvents.editorialAccountId, editorialId)); await transaction.delete(usages).where(eq(usages.editorialAccountId, editorialId)); await transaction.delete(lightboxItems).where(eq(lightboxItems.editorialAccountId, editorialId)); - await transaction.delete(billingReports).where(eq(billingReports.editorialAccountId, editorialId)); + if (reportIds.length > 0) { + await transaction.delete(billingReports).where(inArray(billingReports.id, reportIds)); + } await transaction.delete(albumAutoRules).where(eq(albumAutoRules.editorialAccountId, editorialId)); await transaction.delete(albumGrants).where(eq(albumGrants.editorialAccountId, editorialId)); + + // billing_address_versions is referenced by + // editorial_accounts.current_billing_address_version_id and + // self-references via superseded_by_id — clear both before deleting. + await transaction + .update(editorialAccounts) + .set({ currentBillingAddressVersionId: null }) + .where(eq(editorialAccounts.id, editorialId)); + await transaction + .update(billingAddressVersions) + .set({ supersededById: null }) + .where(eq(billingAddressVersions.editorialAccountId, editorialId)); await transaction.delete(billingAddressVersions).where(eq(billingAddressVersions.editorialAccountId, editorialId)); - await transaction.delete(auditEvents).where(and(eq(auditEvents.entityId, editorialId), eq(auditEvents.entityType, "editorial_account"))); - + + // Purge the audit trail entries that point at this editorial's data; + // leftover rows would dangle after the account is gone. + const { verifications } = await import("@/db/schema/auth"); + await transaction.delete(auditEvents).where(and(eq(auditEvents.entityType, "editorial_account"), eq(auditEvents.entityId, editorialId))); + if (usageIds.length > 0) { + await transaction.delete(auditEvents).where(and(eq(auditEvents.entityType, "usage"), inArray(auditEvents.entityId, usageIds))); + } + if (reportIds.length > 0) { + await transaction.delete(auditEvents).where(and(eq(auditEvents.entityType, "billing_report"), inArray(auditEvents.entityId, reportIds))); + } + await transaction.delete(auditEvents).where( + and( + eq(auditEvents.entityType, "album_grant"), + sql`lower(${auditEvents.newValues}->>'editorialId') = lower(${editorialId})`, + ), + ); + await transaction.delete(editorialAccounts).where(eq(editorialAccounts.id, editorialId)); if (editorial.userId) { + // Safety net: any remaining audit row attributed to the editorial + // user would block user deletion via the restrict FK. + await transaction.delete(auditEvents).where(eq(auditEvents.actorUserId, editorial.userId)); const { accounts, sessions, users } = await import("@/db/schema/auth"); await transaction.delete(accounts).where(eq(accounts.userId, editorial.userId)); await transaction.delete(sessions).where(eq(sessions.userId, editorial.userId)); await transaction.delete(users).where(eq(users.id, editorial.userId)); } + + // Better Auth verification tokens are keyed by e-mail, not FK-linked. + await transaction.delete(verifications).where(eq(verifications.identifier, editorial.loginEmail)); + }); + }, + + /** + * Removes every usage/billing artifact of ONE editorial (downloads, + * usages, reports incl. items + related audit rows) so the account no + * longer appears in statistics. Intended to clean up test accounts; + * grants, price, status and login stay untouched. + */ + async resetUsageData(input: { editorialId: string; adminUserId: string }) { + return db.transaction(async (transaction) => { + await lockEditorialForMutation(transaction, input.editorialId); + + const [editorial] = await transaction + .select({ id: editorialAccounts.id }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, input.editorialId)) + .for("update") + .limit(1); + if (!editorial) { + throw new EditorialServiceError("EDITORIAL_NOT_FOUND"); + } + + const usageIds = ( + await transaction + .select({ id: usages.id }) + .from(usages) + .where(eq(usages.editorialAccountId, editorial.id)) + ).map((row) => row.id); + const reportIds = ( + await transaction + .select({ id: billingReports.id }) + .from(billingReports) + .where(eq(billingReports.editorialAccountId, editorial.id)) + ).map((row) => row.id); + + // Same FK order as hardDelete: items -> downloads -> usages -> reports. + if (reportIds.length > 0) { + await transaction + .delete(billingReportItems) + .where(inArray(billingReportItems.billingReportId, reportIds)); + } + await transaction + .delete(downloadEvents) + .where(eq(downloadEvents.editorialAccountId, editorial.id)); + await transaction.delete(usages).where(eq(usages.editorialAccountId, editorial.id)); + if (reportIds.length > 0) { + await transaction.delete(billingReports).where(inArray(billingReports.id, reportIds)); + await transaction + .delete(auditEvents) + .where(and(eq(auditEvents.entityType, "billing_report"), inArray(auditEvents.entityId, reportIds))); + } + if (usageIds.length > 0) { + await transaction + .delete(auditEvents) + .where(and(eq(auditEvents.entityType, "usage"), inArray(auditEvents.entityId, usageIds))); + } + + const changedAt = new Date(); + await transaction.insert(auditEvents).values({ + eventType: "editorial_usage_reset", + actorUserId: input.adminUserId, + actorType: "admin", + entityType: "editorial_account", + entityId: editorial.id, + previousValues: { usages: usageIds.length, reports: reportIds.length }, + newValues: { usages: 0, reports: 0 }, + occurredAt: changedAt, + }); + + return { deletedUsages: usageIds.length, deletedReports: reportIds.length }; }); }, };