fixed create space model

This commit is contained in:
hannathkadher
2025-02-21 21:22:48 +04:00
parent 394dd0dd6d
commit d13da50fd7
6 changed files with 257 additions and 205 deletions

View File

@ -1,7 +1,7 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsArray, IsNotEmpty, IsString, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
import { CreateTagDto, ProcessTagDto } from 'src/tags/dtos';
import { ProcessTagDto } from 'src/tags/dtos';
export class CreateSubspaceModelDto {
@ApiProperty({

View File

@ -50,8 +50,6 @@ export class SpaceModelService {
createSpaceModelDto: CreateSpaceModelDto,
params: ProjectParam,
): Promise<BaseResponseDto> {
console.log('[START] createSpaceModel', { createSpaceModelDto, params });
const { modelName, subspaceModels, tags } = createSpaceModelDto;
const queryRunner = this.dataSource.createQueryRunner();
@ -59,86 +57,60 @@ export class SpaceModelService {
await queryRunner.startTransaction();
try {
console.log('[STEP 1] Validating Project:', params.projectUuid);
const project = await this.projectService.findOne(params.projectUuid);
if (!project) {
console.error('[ERROR] Project not found', params.projectUuid);
throw new HttpException('Project not found', HttpStatus.NOT_FOUND);
}
console.log('[STEP 1 SUCCESS] Project found:', project);
console.log('[STEP 2] Validating model name:', modelName);
await this.validateNameUsingQueryRunner(
modelName,
params.projectUuid,
queryRunner,
);
console.log('[STEP 2 SUCCESS] Model name validated');
console.log('[STEP 3] Creating SpaceModel entity');
const spaceModel = this.spaceModelRepository.create({
modelName,
project,
});
console.log('[STEP 3 SUCCESS] SpaceModel entity created:', spaceModel);
console.log('[STEP 4] Saving SpaceModel');
const savedSpaceModel = await queryRunner.manager.save(spaceModel);
console.log('[STEP 4 SUCCESS] SpaceModel saved:', savedSpaceModel);
console.log('[STEP 5] Validating unique tags');
this.validateUniqueTags(
tags,
this.subSpaceModelService.extractSubspaceTags(subspaceModels),
);
console.log('[STEP 5 SUCCESS] Unique tags validated');
if (subspaceModels?.length) {
console.log('[STEP 6] Creating Subspace Models');
savedSpaceModel.subspaceModels =
await this.subSpaceModelService.createModels(
savedSpaceModel,
subspaceModels,
queryRunner,
);
console.log(
'[STEP 6 SUCCESS] Subspace Models created:',
savedSpaceModel.subspaceModels,
);
}
if (tags?.length) {
console.log('[STEP 7] Processing tags');
const processedTags = await this.tagService.processTags(
tags,
params.projectUuid,
queryRunner,
);
await this.createProductAllocations(
spaceModel,
processedTags,
queryRunner,
);
console.log('[STEP 7 SUCCESS] Tags processed:', processedTags);
console.log('[STEP 8] Creating product allocations');
await this.createProductAllocations(spaceModel, processedTags);
console.log('[STEP 8 SUCCESS] Product allocations created');
}
console.log('[STEP 9] Committing transaction');
await queryRunner.commitTransaction();
console.log('[STEP 9 SUCCESS] Transaction committed');
console.log(
'[COMPLETE] Successfully created space model',
savedSpaceModel,
);
return new SuccessResponseDto({
message: `Successfully created new space model with uuid ${savedSpaceModel.uuid}`,
data: savedSpaceModel,
statusCode: HttpStatus.CREATED,
});
} catch (error) {
console.error('[ERROR] Exception occurred:', error);
await queryRunner.rollbackTransaction();
console.log('[ROLLBACK] Transaction rolled back due to error');
const errorMessage =
error instanceof HttpException
@ -151,7 +123,6 @@ export class SpaceModelService {
throw new HttpException(errorMessage, statusCode);
} finally {
console.log('[CLEANUP] Releasing query runner');
await queryRunner.release();
}
}
@ -451,50 +422,76 @@ export class SpaceModelService {
private async createProductAllocations(
spaceModel: SpaceModelEntity,
tags: NewTagEntity[],
queryRunner?: QueryRunner,
): Promise<void> {
const productAllocations: SpaceModelProductAllocationEntity[] = [];
try {
const productAllocations: SpaceModelProductAllocationEntity[] = [];
for (const tag of tags) {
const product = await this.productRepository.findOne({
where: { uuid: tag.product.uuid },
});
for (const tag of tags) {
const existingAllocation = await (queryRunner
? queryRunner.manager.findOne(SpaceModelProductAllocationEntity, {
where: { spaceModel, product: tag.product },
relations: ['tags'],
})
: this.spaceModelProductAllocationRepository.findOne({
where: { spaceModel, product: tag.product },
relations: ['tags'],
}));
if (!product) {
throw new HttpException(
`Product with UUID ${tag.product.uuid} not found.`,
HttpStatus.NOT_FOUND,
);
if (!existingAllocation) {
const productAllocation = queryRunner
? queryRunner.manager.create(SpaceModelProductAllocationEntity, {
spaceModel,
product: tag.product,
tags: [tag],
})
: this.spaceModelProductAllocationRepository.create({
spaceModel,
product: tag.product,
tags: [tag],
});
productAllocations.push(productAllocation);
} else {
if (
!existingAllocation.tags.some(
(existingTag) => existingTag.uuid === tag.uuid,
)
) {
existingAllocation.tags.push(tag);
if (queryRunner) {
await queryRunner.manager.save(
SpaceModelProductAllocationEntity,
existingAllocation,
);
} else {
await this.spaceModelProductAllocationRepository.save(
existingAllocation,
);
}
}
}
}
const existingAllocation =
await this.spaceModelProductAllocationRepository.findOne({
where: { spaceModel, product },
});
if (!existingAllocation) {
const productAllocation =
this.spaceModelProductAllocationRepository.create({
spaceModel,
product,
tags: [tag],
});
productAllocations.push(productAllocation);
} else {
if (
!existingAllocation.tags.some(
(existingTag) => existingTag.uuid === tag.uuid,
)
) {
existingAllocation.tags.push(tag);
if (productAllocations.length > 0) {
if (queryRunner) {
await queryRunner.manager.save(
SpaceModelProductAllocationEntity,
productAllocations,
);
} else {
await this.spaceModelProductAllocationRepository.save(
existingAllocation,
productAllocations,
);
}
}
}
if (productAllocations.length > 0) {
await this.spaceModelProductAllocationRepository.save(productAllocations);
} catch (error) {
console.error('[ERROR] Failed to create product allocations:', error);
throw new HttpException(
'An unexpected error occurred while creating product allocations',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
@ -515,6 +512,7 @@ export class SpaceModelService {
HttpStatus.BAD_REQUEST,
);
}
tagUuidSet.add(tag.uuid);
} else {
const tagKey = `${tag.name}-${tag.productUuid}`;
if (tagNameProductSet.has(tagKey)) {
@ -523,6 +521,7 @@ export class SpaceModelService {
HttpStatus.BAD_REQUEST,
);
}
tagNameProductSet.add(tagKey);
}
}
}

View File

@ -36,63 +36,51 @@ export class SubSpaceModelService {
dtos: CreateSubspaceModelDto[],
queryRunner: QueryRunner,
) {
console.log('[START] createModels - Creating Subspace Models', { dtos });
try {
this.validateNamesInDTO(dtos.map((dto) => dto.subspaceName));
this.validateNamesInDTO(dtos.map((dto) => dto.subspaceName));
console.log('[STEP 1 SUCCESS] Validated Subspace Names');
const subspaceEntities: SubspaceModelEntity[] = [];
for (const dto of dtos) {
console.log('[STEP 2] Creating Subspace Model Entity', {
subspaceName: dto.subspaceName,
});
const subspaceModel = queryRunner.manager.create(
this.subspaceModelRepository.target,
{
const subspaceEntities: SubspaceModelEntity[] = dtos.map((dto) =>
queryRunner.manager.create(this.subspaceModelRepository.target, {
subspaceName: dto.subspaceName,
spaceModel,
},
);
console.log(
'[STEP 2 SUCCESS] Subspace Model Entity Created:',
subspaceModel,
}),
);
subspaceEntities.push(subspaceModel);
const savedSubspaces = await queryRunner.manager.save(subspaceEntities);
for (const [index, dto] of dtos.entries()) {
const subspaceModel = savedSubspaces[index];
const processedTags = await this.tagService.processTags(
dto.tags,
spaceModel.project.uuid,
queryRunner,
);
await this.createSubspaceProductAllocations(
subspaceModel,
processedTags,
queryRunner,
);
}
return savedSubspaces;
} catch (error) {
throw new HttpException(
error instanceof HttpException
? error.message
: 'An unexpected error occurred while creating subspace models',
error instanceof HttpException
? error.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR,
);
}
console.log('[STEP 3] Saving Subspace Models:', subspaceEntities);
const savedSubspaces = await queryRunner.manager.save(subspaceEntities);
console.log('[STEP 3 SUCCESS] Subspace Models Saved:', savedSubspaces);
for (const [index, dto] of dtos.entries()) {
const subspaceModel = savedSubspaces[index];
console.log('[STEP 4] Processing Tags for Subspace Model', {
subspaceName: dto.subspaceName,
});
const processedTags = await this.tagService.processTags(
dto.tags,
spaceModel.project.uuid,
);
console.log('[STEP 4 SUCCESS] Tags Processed:', processedTags);
await this.createSubspaceProductAllocations(subspaceModel, processedTags);
console.log('[STEP 5 SUCCESS] Subspace Product Allocations Created');
}
console.log('[COMPLETE] Successfully Created Subspace Models');
return savedSubspaces;
}
async createSubSpaceModels(
subSpaceModelDtos: CreateSubspaceModelDto[],
spaceModel: SpaceModelEntity,
queryRunner: QueryRunner,
otherTags?: ProcessTagDto[],
): Promise<SubspaceModelEntity[]> {
try {
await this.validateInputDtos(subSpaceModelDtos, spaceModel);
@ -108,11 +96,6 @@ export class SubSpaceModelService {
await Promise.all(
subSpaceModelDtos.map(async (dto, index) => {
const subspace = savedSubspaces[index];
const otherDtoTags = subSpaceModelDtos
.filter((_, i) => i !== index)
.flatMap((otherDto) => otherDto.tags || []);
if (dto.tags && dto.tags.length > 0) {
/* subspace.tags = await this.tagModelService.createTags(
dto.tags,
@ -446,41 +429,70 @@ export class SubSpaceModelService {
private async createSubspaceProductAllocations(
subspaceModel: SubspaceModelEntity,
tags: NewTagEntity[],
queryRunner?: QueryRunner,
): Promise<void> {
const allocations: SubspaceModelProductAllocationEntity[] = [];
try {
const allocations: SubspaceModelProductAllocationEntity[] = [];
for (const tag of tags) {
const existingAllocation =
await this.subspaceModelProductAllocationRepository.findOne({
where: { subspaceModel, product: tag.product },
});
for (const tag of tags) {
const existingAllocation = await (queryRunner
? queryRunner.manager.findOne(SubspaceModelProductAllocationEntity, {
where: { subspaceModel, product: tag.product },
})
: this.subspaceModelProductAllocationRepository.findOne({
where: { subspaceModel, product: tag.product },
}));
if (!existingAllocation) {
const allocation = this.subspaceModelProductAllocationRepository.create(
{
subspaceModel,
product: tag.product,
tags: [tag],
},
);
if (!existingAllocation) {
const allocation = queryRunner
? queryRunner.manager.create(SubspaceModelProductAllocationEntity, {
subspaceModel,
product: tag.product,
tags: [tag],
})
: this.subspaceModelProductAllocationRepository.create({
subspaceModel,
product: tag.product,
tags: [tag],
});
allocations.push(allocation);
} else {
if (
!existingAllocation.tags.some(
(existingTag) => existingTag.uuid === tag.uuid,
)
) {
existingAllocation.tags.push(tag);
await this.subspaceModelProductAllocationRepository.save(
existingAllocation,
);
allocations.push(allocation);
} else {
if (
!existingAllocation.tags.some(
(existingTag) => existingTag.uuid === tag.uuid,
)
) {
existingAllocation.tags.push(tag);
if (queryRunner) {
await queryRunner.manager.save(
SubspaceModelProductAllocationEntity,
existingAllocation,
);
} else {
await this.subspaceModelProductAllocationRepository.save(
existingAllocation,
);
}
}
}
}
}
if (allocations.length > 0) {
await this.subspaceModelProductAllocationRepository.save(allocations);
if (allocations.length > 0) {
if (queryRunner) {
await queryRunner.manager.save(
SubspaceModelProductAllocationEntity,
allocations,
);
} else {
await this.subspaceModelProductAllocationRepository.save(allocations);
}
}
} catch (error) {
throw new HttpException(
'An unexpected error occurred while creating subspace product allocations',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
}

View File

@ -18,14 +18,6 @@ export class ProcessTagDto {
@IsOptional()
productUuid: string;
@ApiProperty({
description: 'UUID of the project associated with the tag',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@IsUUID()
@IsOptional()
projectUuid: string;
@ApiProperty({
description: 'UUID of the tag',
example: '123e4567-e89b-12d3-a456-426614174000',

View File

@ -15,7 +15,7 @@ import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { NewTagEntity } from '@app/common/modules/tag';
import { BulkCreateTagsDto, ProcessTagDto } from '../dtos';
import { In } from 'typeorm';
import { In, QueryRunner } from 'typeorm';
import { ProjectParam } from '@app/common/dto/project-param.dto';
@Injectable()
@ -69,67 +69,117 @@ export class TagService {
async processTags(
tags: ProcessTagDto[],
projectUuid: string,
queryRunner?: QueryRunner,
): Promise<NewTagEntity[]> {
if (!tags || tags.length === 0) return [];
try {
if (!tags || tags.length === 0) return [];
const newTags: CreateTagDto[] = [];
const existingTagUuids: string[] = [];
const newTags: CreateTagDto[] = [];
const existingTagUuids: string[] = [];
for (const tag of tags) {
if (tag.uuid) {
existingTagUuids.push(tag.uuid);
} else {
newTags.push(tag);
for (const tag of tags) {
tag.uuid ? existingTagUuids.push(tag.uuid) : newTags.push(tag);
}
}
const existingTags = await this.tagRepository.find({
where: { uuid: In(existingTagUuids), project: { uuid: projectUuid } },
relations: ['product'],
});
const existingTags = existingTagUuids.length
? await (queryRunner
? queryRunner.manager.find(NewTagEntity, {
where: {
uuid: In(existingTagUuids),
project: { uuid: projectUuid },
},
relations: ['product'],
})
: this.tagRepository.find({
where: {
uuid: In(existingTagUuids),
project: { uuid: projectUuid },
},
relations: ['product'],
}))
: [];
if (existingTags.length !== existingTagUuids.length) {
if (existingTags.length !== existingTagUuids.length) {
const foundUuids = new Set(existingTags.map((tag) => tag.uuid));
const missingUuids = existingTagUuids.filter(
(uuid) => !foundUuids.has(uuid),
);
throw new HttpException(
`Some provided tag UUIDs do not exist in the project: ${missingUuids.join(', ')}`,
HttpStatus.NOT_FOUND,
);
}
const createdTags =
newTags.length > 0
? await this.bulkCreateTags(
{ projectUuid, tags: newTags },
queryRunner,
)
: [];
return [...existingTags, ...createdTags];
} catch (error) {
throw new HttpException(
`Some provided tag UUIDs do not exist in the project.`,
HttpStatus.NOT_FOUND,
error instanceof HttpException
? error.message
: 'An unexpected error occurred while processing tags',
error instanceof HttpException
? error.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const createdTags = newTags.length
? (await this.bulkCreateTags({ projectUuid, tags: newTags })).data
: [];
return [...existingTags, ...createdTags];
}
async bulkCreateTags(dto: BulkCreateTagsDto): Promise<BaseResponseDto> {
const { projectUuid, tags } = dto;
async bulkCreateTags(
dto: BulkCreateTagsDto,
queryRunner?: QueryRunner,
): Promise<NewTagEntity[]> {
try {
const { projectUuid, tags } = dto;
const project = await this.getProjectByUuid(projectUuid);
const project = await this.getProjectByUuid(projectUuid);
const productUuids = tags.map((tag) => tag.productUuid);
const productMap = await this.getProductMap(productUuids);
const existingTagNames = await this.getExistingTagNames(projectUuid);
const newTags: NewTagEntity[] = tags
.filter((tag) => !existingTagNames.has(tag.name))
.map((tag) =>
this.tagRepository.create({
name: tag.name,
product: productMap.get(tag.productUuid),
project,
}),
const productUuids = Array.from(
new Set(tags.map((tag) => tag.productUuid)),
);
if (newTags.length > 0) {
await this.tagRepository.save(newTags);
}
const productMap = await this.getProductMap(productUuids);
return new SuccessResponseDto({
message: `Tags processed successfully`,
data: newTags,
});
const existingTagNames = new Set(
await this.getExistingTagNames(projectUuid),
);
const newTags: NewTagEntity[] = tags
.filter((tag) => !existingTagNames.has(tag.name))
.map((tag) =>
this.tagRepository.create({
name: tag.name,
product: productMap.get(tag.productUuid),
project,
}),
);
if (newTags.length > 0) {
if (queryRunner) {
await queryRunner.manager.save(NewTagEntity, newTags);
} else {
await this.tagRepository.save(newTags);
}
}
return newTags;
} catch (error) {
throw new HttpException(
error instanceof HttpException
? error.message
: 'An unexpected error occurred while creating tags',
error instanceof HttpException
? error.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
private async getProductByUuid(uuid: string): Promise<ProductEntity> {
@ -178,7 +228,7 @@ export class TagService {
);
}
return;
return new Map(products.map((product) => [product.uuid, product]));
}
private async getExistingTagNames(projectUuid: string): Promise<Set<string>> {

View File

@ -258,7 +258,6 @@ export class UserSpaceService {
.where('space.uuid = :spaceUuid', { spaceUuid })
.execute();
} catch (error) {
console.error(`Error deleting user-space associations: ${error.message}`);
throw new HttpException(
`Failed to delete user-space associations: ${error.message}`,
HttpStatus.INTERNAL_SERVER_ERROR,