feat: unlink documents from deleted organization

This commit is contained in:
Catalin Pit
2025-08-28 09:35:31 +03:00
parent 7d257236a6
commit 8b131e42c7
2 changed files with 96 additions and 0 deletions

View File

@ -1,7 +1,9 @@
import { ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP } from '@documenso/lib/constants/organisations';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { deletedAccountServiceAccount } from '@documenso/lib/server-only/user/service-accounts/deleted-account';
import { buildOrganisationWhereQuery } from '@documenso/lib/utils/organisations';
import { prisma } from '@documenso/prisma';
import { DocumentStatus } from '@documenso/prisma/client';
import { authenticatedProcedure } from '../trpc';
import {
@ -16,6 +18,8 @@ export const deleteOrganisationRoute = authenticatedProcedure
.mutation(async ({ input, ctx }) => {
const { organisationId } = input;
const { user } = ctx;
const serviceAccount = await deletedAccountServiceAccount();
const serviceAccountTeam = serviceAccount.ownedOrganisations[0].teams[0];
ctx.logger.info({
input: {
@ -29,6 +33,24 @@ export const deleteOrganisationRoute = authenticatedProcedure
userId: user.id,
roles: ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP['DELETE_ORGANISATION'],
}),
select: {
id: true,
owner: {
select: {
id: true,
},
},
teams: {
select: {
id: true,
documents: {
select: {
id: true,
},
},
},
},
},
});
if (!organisation) {
@ -37,6 +59,66 @@ export const deleteOrganisationRoute = authenticatedProcedure
});
}
const organisationOwner = await prisma.user.findUnique({
where: {
id: organisation.owner.id,
},
include: {
ownedOrganisations: {
include: {
teams: true,
},
},
},
});
const documentIds = organisation.teams.flatMap((team) => team.documents.map((doc) => doc.id));
if (documentIds.length > 0) {
await prisma.document.deleteMany({
where: {
id: {
in: documentIds,
},
status: DocumentStatus.DRAFT,
},
});
if (organisationOwner && organisationOwner.ownedOrganisations.length > 0) {
const ownerPersonalTeam = organisationOwner.ownedOrganisations[0].teams[0];
await prisma.document.updateMany({
where: {
id: {
in: documentIds,
},
status: {
not: DocumentStatus.DRAFT,
},
},
data: {
userId: organisationOwner.id,
teamId: ownerPersonalTeam.id,
},
});
} else {
await prisma.document.updateMany({
where: {
id: {
in: documentIds,
},
status: {
not: DocumentStatus.DRAFT,
},
},
data: {
userId: serviceAccount.id,
teamId: serviceAccountTeam.id,
},
});
}
}
await prisma.organisation.delete({
where: {
id: organisation.id,