fix: Nested drafts deleted when parent document is permanently deleted (#13453)

The parentDocumentId clear in documentPermanentDeleter inherited the Document
default scope, so draft, template, and trial children were never detached and
the foreign key cascade removed them along with the parent.
This commit is contained in:
Tom Moor authored and GitHub committed 2026-08-15 20:21:35 -04:00
1 parent fcae7b3c57
commit 94dbdccccd
2 files changed
+25 -2

No files matched your search

@@ -1,7 +1,11 @@
import { subDays } from "date-fns";
import { errToString } from "@shared/utils/error";
import { Attachment, Document } from "@server/models";
import { buildAttachment, buildDocument } from "@server/test/factories";
import {
buildAttachment,
buildDocument,
buildDraftDocument,
} from "@server/test/factories";
import { mockTaskSchedule } from "@server/test/support";
import documentPermanentDeleter from "./documentPermanentDeleter";
@@ -154,6 +158,23 @@ describe("documentPermanentDeleter", () => {
expect(child.parentDocumentId).toEqual(parent.id);
});
it("should detach draft children rather than cascade delete them", async () => {
const parent = await buildDocument({
publishedAt: subDays(new Date(), 90),
deletedAt: subDays(new Date(), 60),
});
const child = await buildDraftDocument({
teamId: parent.teamId,
parentDocumentId: parent.id,
});
const countDeletedDoc = await documentPermanentDeleter([parent]);
expect(countDeletedDoc).toEqual(1);
const reloaded = await Document.unscoped().findByPk(child.id);
expect(reloaded?.parentDocumentId).toEqual(null);
});
it("should not destroy attachments referenced in other documents", async () => {
const document1 = await buildDocument();
const document = await buildDocument({
+3 -1
View File
@@ -93,7 +93,9 @@ export default async function documentPermanentDeleter(documents: Document[]) {
const deletedIds = stillDeleted.map((document) => document.id);
for (const batch of chunk(deletedIds, 100)) {
await Document.update(
// Unscoped so that drafts and templates are detached too, otherwise the
// destroy below cascades and removes them.
await Document.unscoped().update(
{
parentDocumentId: null,
},