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
@@ -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