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
+69 -70
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);
}
}
}
@@ -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,
);
}
}
}