Skip to content

Commit

Permalink
fix: updated queries
Browse files Browse the repository at this point in the history
  • Loading branch information
rahul-rocket committed May 7, 2024
1 parent b88ea6e commit 8ac1d69
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 68 deletions.
6 changes: 4 additions & 2 deletions packages/core/src/tasks/daily-plan/daily-plan.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,10 @@ export class DailyPlanController extends CrudController<DailyPlan> {
@HttpCode(HttpStatus.CREATED)
@Post()
@UseValidationPipe({ transform: true, whitelist: true })
async create(@Body() entity: CreateDailyPlanDTO): Promise<IDailyPlan> {
return await this.dailyPlanService.createDailyPlan(entity, entity.taskId);
async create(
@Body() entity: CreateDailyPlanDTO
): Promise<IDailyPlan> {
return await this.dailyPlanService.createDailyPlan(entity);
}

/**
Expand Down
118 changes: 52 additions & 66 deletions packages/core/src/tasks/daily-plan/daily-plan.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Brackets, DeepPartial, SelectQueryBuilder, UpdateResult, WhereExpressionBuilder } from 'typeorm';
import { IDailyPlan, IEmployee, IPagination, ITask } from '@gauzy/contracts';
import { DeepPartial, SelectQueryBuilder, UpdateResult } from 'typeorm';
import { IDailyPlan, IDailyPlanCreateInput, IEmployee, IPagination, ITask } from '@gauzy/contracts';
import { isNotEmpty } from '@gauzy/common';
import { isPostgres } from '@gauzy/config';
import { prepareSQLQuery as p } from '../../database/database.helper';
Expand All @@ -24,70 +24,59 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {
}

/**
* Create daily plan
* @param entity
* @param params
* @param options
* Create or update a DailyPlan. If the given day already has a DailyPlan,
* update it with the provided task. Otherwise, create a new DailyPlan.
*
* @param partialEntity - Data to create or update the DailyPlan
* @returns The created or updated DailyPlan
*/
async createDailyPlan(partialEntity: DeepPartial<IDailyPlan>, taskId?: ITask['id']): Promise<IDailyPlan> {
async createDailyPlan(partialEntity: IDailyPlanCreateInput): Promise<IDailyPlan> {
try {
const { employeeId, organizationId } = partialEntity;
const tenantId = RequestContext.currentTenantId();
const { employeeId, organizationId, taskId } = partialEntity;

const dailyPlanDate = new Date(partialEntity.date).toISOString().split('T')[0];
const likeOperator = isPostgres() ? '::text LIKE' : ' LIKE';

// Validate employee existence
const employee = await this.employeeService.findOneByIdString(employeeId);
if (!employee) {
throw new NotFoundException('Cannot found employee');
throw new NotFoundException('Employee not found');
}

let wantCreatePlan: DailyPlan;
const likeOperator = isPostgres() ? '::text LIKE' : ' LIKE';
// Check for existing DailyPlan
const query = this.typeOrmRepository.createQueryBuilder('dailyPlan');
query.setFindOptions({ relations: { tasks: true } });
query.where('"dailyPlan"."tenantId" = :tenantId', { tenantId });
query.andWhere('"dailyPlan"."organizationId" = :organizationId', { organizationId });
query.andWhere(`"dailyPlan"."date" ${likeOperator} :dailyPlanDate`, { dailyPlanDate: `${dailyPlanDate}%` });
query.andWhere('"dailyPlan"."employeeId" = :employeeId', { employeeId });
let dailyPlan = await query.getOne();

const query = this.typeOrmRepository.createQueryBuilder(this.tableName);

query.setFindOptions({
relations: ['tasks']
});

query.andWhere(p(`"${query.alias}"."tenantId" = :tenantId`), { tenantId });
query.andWhere(p(`"${query.alias}"."organizationId" = :organizationId`), { organizationId });
query.andWhere(
new Brackets((qb: WhereExpressionBuilder) => {
qb.andWhere(p(`"${query.alias}"."date" ${likeOperator} :incomingDate`), {
incomingDate: `${new Date(partialEntity.date as Date).toISOString().split('T')[0]}%`
});
})
);
query.andWhere(
new Brackets((qb: WhereExpressionBuilder) => {
const employeeId = RequestContext.currentEmployeeId();
qb.andWhere(p(`"${query.alias}"."employeeId" = :employeeId`), { employeeId });
})
);

const result = await query.getOne();

if (result) {
wantCreatePlan = result;
} else {
wantCreatePlan = new DailyPlan({
// Create or update DailyPlan
if (!dailyPlan) {
dailyPlan = new DailyPlan({
...partialEntity,
employeeId: employee.id,
employee: { id: employee.id },
tasks: []
});
}

// If a taskId is provided, add the task to the DailyPlan
if (taskId) {
const wantCreatePlannedTask = await this.taskService.findOneByIdString(taskId);
if (!wantCreatePlannedTask) {
throw new BadRequestException('Cannot found the plan requested to plan');
const task = await this.taskService.findOneByIdString(taskId);
if (!task) {
throw new BadRequestException('Cannot found the task');
}
wantCreatePlan.tasks = [...wantCreatePlan.tasks, wantCreatePlannedTask];
await this.save(wantCreatePlan);
dailyPlan.tasks.push(task);
await this.save(dailyPlan); // Save changes
}
return wantCreatePlan;

return dailyPlan; // Return the created/updated DailyPlan
} catch (error) {
console.log(error);
throw new BadRequestException(error.message);
console.error(error); // Improved logging
throw new BadRequestException(error.message); // Clearer error messaging
}
}

Expand All @@ -98,7 +87,6 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {
* @returns A promise that resolves to an object containing the list of daily plans and the total count.
* @throws BadRequestException - If there's an error during the query.
*/

async getAllPlans(
options: PaginationParams<DailyPlan>,
employeeId?: IEmployee['id']
Expand All @@ -117,14 +105,12 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {

// Apply optional find options if provided
query.setFindOptions({
...(isNotEmpty(options) &&
isNotEmpty(options.where) && {
where: options.where
}),
...(isNotEmpty(options) &&
isNotEmpty(options.relations) && {
relations: options.relations
})
...(isNotEmpty(options) && isNotEmpty(options.where) && {
where: options.where
}),
...(isNotEmpty(options) && isNotEmpty(options.relations) && {
relations: options.relations
})
});

query.andWhere(p(`"${query.alias}"."tenantId" = :tenantId`), { tenantId });
Expand All @@ -136,7 +122,6 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {

// Retrieve results and total count
const [items, total] = await query.getManyAndCount();

// Return the pagination result
return { items, total };
} catch (error) {
Expand All @@ -152,7 +137,6 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {
* @returns A promise that resolves to an object containing the list of daily plans and the total count.
* @throws BadRequestException - If there's an error during the query.
*/

async getDailyPlansByEmployee(
options: PaginationParams,
employeeId?: IEmployee['id']
Expand Down Expand Up @@ -202,12 +186,14 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {
const currentEmployeeId = RequestContext.currentEmployeeId();

const query = this.typeOrmRepository.createQueryBuilder(this.tableName);

query.setFindOptions({
...(isNotEmpty(options) && isNotEmpty(options.where) && { where: options.where }),
...(isNotEmpty(options) && isNotEmpty(options.relations) && { relations: options.relations })
...(isNotEmpty(options) && isNotEmpty(options.where) && {
where: options.where
}),
...(isNotEmpty(options) && isNotEmpty(options.relations) && {
relations: options.relations
})
});

query.andWhere(p(`"${query.alias}"."employeeId" = :employeeId`), { employeeId: currentEmployeeId });
query.andWhere(p(`"${query.alias}".tenantId = :tenantId`), { tenantId });
query.andWhere(p(`"${query.alias}"."id" = :planId`), { planId });
Expand Down Expand Up @@ -289,7 +275,7 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {

/**
* Retrieves daily plans for a specific task including employee
* @param options pagination and additionnal query options
* @param options pagination and additional query options
* @param taskId - The ID of the task for whom to retrieve daily plans.
* @returns A promise that resolves to an object containing the list of plans and total count
*/
Expand All @@ -308,8 +294,8 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {
query.leftJoinAndSelect('employee.user', 'user');

// Conditions
query.andWhere(`"${query.alias}"."tenantId" = :tenantId`, { tenantId });
query.andWhere(`"${query.alias}"."organizationId" = :organizationId`, { organizationId });
query.andWhere(p(`"${query.alias}".tenantId = :tenantId`), { tenantId });
query.andWhere(p(`"${query.alias}".organizationId = :organizationId`), { organizationId });

query.andWhere((qb: SelectQueryBuilder<any>) => {
const subQuery = qb.subQuery();
Expand All @@ -319,7 +305,7 @@ export class DailyPlanService extends TenantAwareCrudService<DailyPlan> {
return p(`${query.alias}.id IN `) + subQuery.distinct(true).getQuery();
});

// Retrive results and total count
// Retrieves results and total count
const [items, total] = await query.getManyAndCount();

return { items, total };
Expand Down

0 comments on commit 8ac1d69

Please sign in to comment.