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.
This commit is contained in:
1 parent
c6b69eb88d
commit
c9d3f3d1dc
5 files changed
+262
-5
No files matched your search
@@ -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 (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Nutzungsdaten zurücksetzen</CardTitle>
|
||||
<CardDescription>
|
||||
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.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">
|
||||
Redaktionsname zur Bestätigung eingeben:
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
value={confirmText}
|
||||
onChange={(e) => setConfirmText(e.target.value)}
|
||||
placeholder={editorialName}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
disabled={!isConfirmed || isPending}
|
||||
onClick={handleReset}
|
||||
>
|
||||
{isPending ? "Wird zurückgesetzt…" : "Nutzungsdaten zurücksetzen"}
|
||||
</Button>
|
||||
{result && (
|
||||
<p className={`text-sm ${result.ok ? "text-muted-foreground" : "text-destructive"}`}>
|
||||
{result.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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({
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<ResetUsageCard editorialId={editorial.id} editorialName={editorial.name} />
|
||||
|
||||
{!editorial.archivedAt && (
|
||||
<DangerZone editorialId={editorial.id} editorialName={editorial.name} />
|
||||
)}
|
||||
|
||||
@@ -14,6 +14,7 @@ function createRepository(): EditorialServiceRepository & {
|
||||
transitionStatus: ReturnType<typeof vi.fn>;
|
||||
claimApprovalNotice: ReturnType<typeof vi.fn>;
|
||||
archiveEditorial: ReturnType<typeof vi.fn>;
|
||||
resetUsageData: ReturnType<typeof vi.fn>;
|
||||
} {
|
||||
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" });
|
||||
});
|
||||
@@ -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<void>;
|
||||
archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise<void>;
|
||||
hardDeleteEditorial(editorialId: string): Promise<void>;
|
||||
resetUsageData(input: {
|
||||
editorialId: string;
|
||||
adminUserId: string;
|
||||
}): Promise<{ deletedUsages: number; deletedReports: number }>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -166,6 +171,10 @@ export function createEditorialService({
|
||||
async hardDeleteEditorial(editorialId: string): Promise<void> {
|
||||
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 };
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user