diff --git a/src/space/services/space-product-allocation.service.ts b/src/space/services/space-product-allocation.service.ts index f29d36c..05efcbe 100644 --- a/src/space/services/space-product-allocation.service.ts +++ b/src/space/services/space-product-allocation.service.ts @@ -331,4 +331,30 @@ export class SpaceProductAllocationService { : HttpStatus.INTERNAL_SERVER_ERROR, ); } + async clearAllAllocations(spaceUuid: string, queryRunner: QueryRunner) { + try { + await queryRunner.manager + .createQueryBuilder() + .delete() + .from('space_product_tags') + .where('space_product_allocation_uuid IN (:...allocationUuids)', { + allocationUuids: await queryRunner.manager + .createQueryBuilder(SpaceProductAllocationEntity, 'allocation') + .select('allocation.uuid') + .where('allocation.spaceUuid = :spaceUuid', { spaceUuid }) + .getRawMany() + .then((results) => results.map((r) => r.allocation_uuid)), + }) + .execute(); + + await queryRunner.manager + .createQueryBuilder() + .delete() + .from(SpaceProductAllocationEntity) + .where('spaceUuid = :spaceUuid', { spaceUuid }) + .execute(); + } catch (error) { + throw this.handleError(error, 'Failed to clear all allocations'); + } + } } diff --git a/src/space/services/space.service.ts b/src/space/services/space.service.ts index 74523f5..65ea08a 100644 --- a/src/space/services/space.service.ts +++ b/src/space/services/space.service.ts @@ -37,6 +37,7 @@ import { SpaceEntity } from '@app/common/modules/space/entities/space.entity'; import { ProcessTagDto } from 'src/tags/dtos'; import { SpaceProductAllocationService } from './space-product-allocation.service'; import { SubspaceProductAllocationService } from './subspace/subspace-product-allocation.service'; +import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity'; @Injectable() export class SpaceService { constructor( @@ -379,8 +380,35 @@ export class SpaceService { spaceName: ORPHAN_SPACE_NAME, }, }); + const queryRunner = this.dataSource.createQueryRunner(); + await queryRunner.connect(); + await queryRunner.startTransaction(); - await this.disableSpace(space, orphanSpace); + try { + await this.spaceProductAllocationService.clearAllAllocations( + spaceUuid, + queryRunner, + ); + + const subspaces = await queryRunner.manager.find(SubspaceEntity, { + where: { space: { uuid: spaceUuid } }, + }); + + const subspaceUuids = subspaces.map((subspace) => subspace.uuid); + + if (subspaceUuids.length > 0) { + await this.subSpaceService.clearSubspaces(subspaceUuids, queryRunner); + } + + await this.disableSpace(space, orphanSpace); + + await queryRunner.commitTransaction(); + } catch (error) { + await queryRunner.rollbackTransaction(); + throw error; + } finally { + await queryRunner.release(); + } return new SuccessResponseDto({ message: `Space with ID ${spaceUuid} successfully deleted`,