diff --git a/server/models/Document.test.ts b/server/models/Document.test.ts index 7d5e2f9ffd..1a58e7d502 100644 --- a/server/models/Document.test.ts +++ b/server/models/Document.test.ts @@ -11,6 +11,7 @@ import { buildUser, buildGuestUser, } from "@server/test/factories"; +import Collection from "./Collection"; import UserMembership from "./UserMembership"; beforeEach(() => { @@ -78,6 +79,34 @@ describe("#delete", () => { expect(newDocument?.deletedAt).toBeTruthy(); }); + test("should soft delete archived document in an archived collection", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + archivedAt: new Date(), + createdById: user.id, + teamId: user.teamId, + }); + const document = await buildDocument({ + archivedAt: new Date(), + collectionId: collection.id, + userId: user.id, + teamId: user.teamId, + }); + await collection.addDocumentToStructure(document, 0); + + await document.delete(user); + const [newDocument, newCollection] = await Promise.all([ + Document.findByPk(document.id, { + paranoid: false, + }), + Collection.findByPk(collection.id), + ]); + + expect(newDocument?.lastModifiedById).toEqual(user.id); + expect(newDocument?.deletedAt).toBeTruthy(); + expect(newCollection?.documentStructure).toEqual([]); + }); + it("should delete draft without collection", async () => { const user = await buildUser(); const document = await buildDraftDocument(); diff --git a/server/models/Document.ts b/server/models/Document.ts index bc25fdabb4..719c528df8 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -1112,18 +1112,26 @@ class Document extends ArchivableModel< // Delete a document, archived or otherwise. delete = (user: User) => this.sequelize.transaction(async (transaction: Transaction) => { - if (!this.archivedAt && !this.template && this.collectionId) { - // delete any children and remove from the document structure - const collection = await Collection.findByPk(this.collectionId, { + let deleted = false; + + if (!this.template && this.collectionId) { + const collection = await Collection.findByPk(this.collectionId!, { transaction, lock: transaction.LOCK.UPDATE, paranoid: false, }); - await collection?.deleteDocument(this, { transaction }); - } else { + + if (!this.archivedAt || (this.archivedAt && collection?.archivedAt)) { + await collection?.deleteDocument(this, { transaction }); + deleted = true; + } + } + + if (!deleted) { await this.destroy({ transaction, }); + deleted = true; } this.lastModifiedById = user.id;