Skip to content

Commit

Permalink
Merge pull request #7977 from ever-co/refactor/task-status-reorder
Browse files Browse the repository at this point in the history
[Refactor] Task Status Re Order Logging
  • Loading branch information
rahul-rocket authored Jul 18, 2024
2 parents fd06a06 + 270ff43 commit a847253
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 46 deletions.
12 changes: 6 additions & 6 deletions packages/core/src/core/crud/crud.factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Body, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, Query, UsePi
import { ApiOperation, ApiResponse } from '@nestjs/swagger';
import { DeepPartial, DeleteResult, FindOptionsWhere, UpdateResult } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { IPagination } from '@gauzy/contracts';
import { ID, IPagination } from '@gauzy/contracts';
import { Type } from '@gauzy/common';
import { BaseEntity } from './../../core/entities/base.entity';
import { TenantOrganizationBaseDTO } from '../../core/dto';
Expand Down Expand Up @@ -100,7 +100,7 @@ export function CrudFactory<BaseType, QueryType, CreateType, UpdateType, CountQu
})
@HttpCode(HttpStatus.OK)
@Get(':id')
async findById(@Param('id', UUIDValidationPipe) id: BaseType['id'], ...options: any[]): Promise<BaseType> {
async findById(@Param('id', UUIDValidationPipe) id: ID, ...options: any[]): Promise<BaseType> {
return await this.crudService.findOneByIdString(id);
}

Expand Down Expand Up @@ -148,7 +148,7 @@ export function CrudFactory<BaseType, QueryType, CreateType, UpdateType, CountQu
@Put(':id')
@UsePipes(new AbstractValidationPipe({ transform: true, whitelist: true }, { body: updateDTO }))
async update(
@Param('id', UUIDValidationPipe) id: BaseType['id'],
@Param('id', UUIDValidationPipe) id: ID,
@Body() entity: QueryDeepPartialEntity<BaseType>
): Promise<BaseType | UpdateResult> {
return await this.crudService.update(id, entity);
Expand All @@ -170,7 +170,7 @@ export function CrudFactory<BaseType, QueryType, CreateType, UpdateType, CountQu
})
@HttpCode(HttpStatus.ACCEPTED)
@Delete(':id')
async delete(@Param('id', UUIDValidationPipe) id: BaseType['id']): Promise<DeleteResult> {
async delete(@Param('id', UUIDValidationPipe) id: ID): Promise<DeleteResult> {
return await this.crudService.delete(id);
}

Expand All @@ -195,7 +195,7 @@ export function CrudFactory<BaseType, QueryType, CreateType, UpdateType, CountQu
@Delete(':id/soft')
@HttpCode(HttpStatus.ACCEPTED)
@UsePipes(new AbstractValidationPipe({ whitelist: true }, { query: TenantOrganizationBaseDTO }))
async softRemove(@Param('id', UUIDValidationPipe) id: BaseType['id'], ...options: any[]): Promise<BaseType> {
async softRemove(@Param('id', UUIDValidationPipe) id: ID, ...options: any[]): Promise<BaseType> {
// Soft delete the record
return await this.crudService.softRemove(id, options);
}
Expand All @@ -221,7 +221,7 @@ export function CrudFactory<BaseType, QueryType, CreateType, UpdateType, CountQu
@Put(':id/recover')
@HttpCode(HttpStatus.ACCEPTED)
@UsePipes(new AbstractValidationPipe({ whitelist: true }, { query: TenantOrganizationBaseDTO }))
async softRecover(@Param('id', UUIDValidationPipe) id: BaseType['id'], ...options: any[]): Promise<BaseType> {
async softRecover(@Param('id', UUIDValidationPipe) id: ID, ...options: any[]): Promise<BaseType> {
// Restore the soft-deleted record
return await this.crudService.softRecover(id, options);
}
Expand Down
31 changes: 15 additions & 16 deletions packages/core/src/tasks/statuses/dto/reorder.dto.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { ArrayMinSize, IsArray, IsNotEmpty, IsNumber, IsUUID, ValidateNested } from 'class-validator';
import { IReorderDTO, IReorderRequestDTO } from '@gauzy/contracts';
import { ID, IReorderDTO, IReorderRequestDTO } from '@gauzy/contracts';
import { TenantOrganizationBaseDTO } from '../../../core/dto';

/**
* DTO for individual reorder request item.
*/
export class ReorderDTO implements IReorderDTO {
@ApiProperty({ type: String, description: 'UUID of the record to reorder' })
@IsNotEmpty() // It should have a value
@IsUUID() // Must be a UUID
readonly id: string;
@ApiProperty({ type: String, description: 'UUID of the record to reorder' })
@IsNotEmpty() // It should have a value
@IsUUID() // Must be a UUID
readonly id: ID;

@ApiProperty({ type: Number, description: 'New order for the record' })
@IsNotEmpty() // It should have a value
@IsNumber() // Must be a number
readonly order: number;
@ApiProperty({ type: Number, description: 'New order for the record' })
@IsNotEmpty() // It should have a value
@IsNumber() // Must be a number
readonly order: number;
}

/**
* DTO for the entire reorder request containing multiple items.
*/
export class ReorderRequestDTO extends TenantOrganizationBaseDTO implements IReorderRequestDTO {

@ApiProperty({ type: () => [ReorderDTO], description: 'List of reordering instructions' })
@IsArray() // Should be an array
@ArrayMinSize(1) // Requires at least one item in the array
@ValidateNested({ each: true }) // Validate each item in the array
@Type(() => ReorderDTO) // Transform to ReorderDTO
reorder: ReorderDTO[];
@ApiProperty({ type: () => [ReorderDTO], description: 'List of reordering instructions' })
@IsArray() // Should be an array
@ArrayMinSize(1) // Requires at least one item in the array
@ValidateNested({ each: true }) // Validate each item in the array
@Type(() => ReorderDTO) // Transform to ReorderDTO
reorder: ReorderDTO[];
}
30 changes: 16 additions & 14 deletions packages/core/src/tasks/statuses/status.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { QueryBus } from '@nestjs/cqrs';
import { Body, Controller, Get, HttpCode, HttpStatus, Patch, Query, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, HttpStatus, Patch, Query, UseGuards } from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import {
IPagination,
Expand Down Expand Up @@ -29,10 +29,7 @@ export class TaskStatusController extends CrudFactory<
ITaskStatusUpdateInput,
ITaskStatusFindInput
>(PaginationParams, CreateStatusDTO, UpdatesStatusDTO, CountQueryDTO) {
constructor(
private readonly queryBus: QueryBus,
protected readonly taskStatusService: TaskStatusService
) {
constructor(private readonly queryBus: QueryBus, protected readonly taskStatusService: TaskStatusService) {
super(taskStatusService);
}

Expand All @@ -44,17 +41,17 @@ export class TaskStatusController extends CrudFactory<
@ApiOperation({ summary: 'Reorder records based on given input' }) // Corrects the summary
@ApiResponse({
status: HttpStatus.OK,
description: 'Reordering was successful.', // Description for successful response
description: 'Reordering was successful.' // Description for successful response
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description: 'Invalid input. Check your request body.', // Description for bad request
description: 'Invalid input. Check your request body.' // Description for bad request
})
@ApiResponse({
status: HttpStatus.INTERNAL_SERVER_ERROR,
description: 'An error occurred during reordering.', // Description for internal server error
description: 'An error occurred during reordering.' // Description for internal server error
})
@Patch('reorder')
@Patch('/reorder')
@UseValidationPipe({ whitelist: true })
async reorder(@Body() { reorder }: ReorderRequestDTO) {
return await this.taskStatusService.reorder(reorder);
Expand All @@ -72,12 +69,17 @@ export class TaskStatusController extends CrudFactory<
status: HttpStatus.OK,
description: 'Found task statuses by filters.'
})
@HttpCode(HttpStatus.OK)
@Get()
@ApiResponse({
status: HttpStatus.INTERNAL_SERVER_ERROR,
description: 'An error occurred during retrieving task statuses.'
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description: 'Invalid input. Check your request body.'
})
@Get('/')
@UseValidationPipe({ whitelist: true })
async findTaskStatuses(@Query() params: StatusQueryDTO): Promise<IPagination<ITaskStatus>> {
return await this.queryBus.execute(
new FindStatusesQuery(params)
);
return await this.queryBus.execute(new FindStatusesQuery(params));
}
}
19 changes: 9 additions & 10 deletions packages/core/src/tasks/statuses/status.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Knex as KnexConnection } from 'knex';
import { InjectConnection } from 'nest-knexjs';
import { v4 as uuidv4 } from 'uuid';
import {
ID,
IOrganization,
IPagination,
IReorderDTO,
Expand All @@ -23,6 +24,9 @@ import { MikroOrmTaskStatusRepository, TypeOrmTaskStatusRepository } from './rep

@Injectable()
export class TaskStatusService extends TaskStatusPrioritySizeService<TaskStatus> {
// Logger for tracking operations
logger = new Logger('TaskStatusService'); // Update with your service name

constructor(
@InjectRepository(TaskStatus)
readonly typeOrmTaskStatusRepository: TypeOrmTaskStatusRepository,
Expand Down Expand Up @@ -68,11 +72,9 @@ export class TaskStatusService extends TaskStatusPrioritySizeService<TaskStatus>
* @param id
* @returns
*/
async delete(id: ITaskStatus['id']): Promise<DeleteResult> {
async delete(id: ID): Promise<DeleteResult> {
return await super.delete(id, {
where: {
isSystem: false
}
where: { isSystem: false }
});
}

Expand Down Expand Up @@ -227,25 +229,22 @@ export class TaskStatusService extends TaskStatusPrioritySizeService<TaskStatus>
* @throws BadRequestException if an error occurs during reordering.
*/
async reorder(list: IReorderDTO[]): Promise<{ success: boolean; list?: IReorderDTO[] }> {
// Logger for tracking operations
const logger = new Logger('TaskStatusService'); // Update with your service name

try {
// Loop through the list and update each item's order
for await (const item of list) {
logger.log(`Updating item with ID: ${item.id} to order: ${item.order}`); // Logging operation
this.logger.log(`Updating item with ID: ${item.id} to order: ${item.order}`); // Logging operation

// Update the entity with the new order value
if (item.id) {
await this.update({ id: item.id, isSystem: false }, { order: item.order });
await super.update({ id: item.id, isSystem: false }, { order: item.order });
}
}

// Return a success status and the updated list
return { success: true, list };
} catch (error) {
// Handle errors during reordering
logger.error('Error during reordering of task statues:', error); // Log the error for debugging
this.logger.error('Error during reordering of task statues:', error); // Log the error for debugging
throw new BadRequestException('An error occurred while reordering task statues. Please try again.', error); // Return error
}
}
Expand Down

0 comments on commit a847253

Please sign in to comment.