Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] Employee weekly schedule planning #8741

Open
wants to merge 19 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
e00c602
Implementation of employee weekly schedule planning
samuelmbabhazi Jan 22, 2025
7c4e4f5
Feedback integration
samuelmbabhazi Jan 23, 2025
ff2bacb
Merge branch 'develop' into feat/#5293-weekly-schedule-planning
samuelmbabhazi Jan 23, 2025
c369a13
Feedback integration
samuelmbabhazi Jan 23, 2025
f7eb738
Feedback integration
samuelmbabhazi Jan 23, 2025
96052b1
Feedback integration
samuelmbabhazi Jan 23, 2025
6c3ba54
Fix deepscan
samuelmbabhazi Jan 23, 2025
49d09b7
Merge branch 'develop' into feat/#5293-weekly-schedule-planning
rahul-rocket Jan 24, 2025
2b926a6
refactor: updated employee availability feature
rahul-rocket Jan 24, 2025
55092e8
fix: entity metadata for Employee#availabilities was not found
rahul-rocket Jan 24, 2025
a6a6e4c
Integration of requested changes
samuelmbabhazi Jan 24, 2025
b1dd009
Merge branch 'develop' into feat/#5293-weekly-schedule-planning
rahul-rocket Jan 26, 2025
39e500f
fix: #5293 bulk insert method for employee availability
rahul-rocket Jan 26, 2025
9037f32
fix: #5293 bulk insert method for employee availability
rahul-rocket Jan 26, 2025
413bf4e
fix: #5293 apply validation and permissions guard
rahul-rocket Jan 26, 2025
043f77f
fix: property 'tenantId' does not exist on type 'IEmployeeAvailabilit…
rahul-rocket Jan 26, 2025
fdab334
feat: #5293 added permission for Employee Availability
rahul-rocket Jan 26, 2025
d51f3f7
feat: #5293 added permission for Employee Availability
rahul-rocket Jan 27, 2025
d8ece61
feat: [table migration] for employee availability for all DB types.
rahul-rocket Jan 27, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/contracts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export * from './lib/email-reset.model';
export * from './lib/email-template.model';
export * from './lib/email.model';
export * from './lib/employee-appointment.model';
export * from './lib/employee-availability.model';
export * from './lib/employee-award.model';
export * from './lib/employee-job.model';
export * from './lib/employee-phone.model';
Expand Down
55 changes: 55 additions & 0 deletions packages/contracts/src/lib/employee-availability.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { IBasePerTenantAndOrganizationEntityModel, ID } from './base-entity.model';
import { IEmployee } from './employee.model';

/**
* Enum representing the availability status of an employee.
*/
export enum AvailabilityStatusEnum {
Available = 'Available',
Partial = 'Partial',
Unavailable = 'Unavailable'
}

export interface IEmployeeAvailability extends IBasePerTenantAndOrganizationEntityModel {
employee: IEmployee;
employeeId: ID;
startDate: Date;
endDate: Date;
dayOfWeek: number; // 0 = Sunday, 6 = Saturday
availabilityStatus: AvailabilityStatusEnum;
availabilityNotes?: string;
}

/**
* Input interface for finding Employee Availability records.
*/
export interface IEmployeeAvailabilityFindInput {
employeeId?: ID;
availabilityStatus?: AvailabilityStatusEnum;
startDate?: Date;
endDate?: Date;
}

/**
* Input interface for creating new Employee Availability records.
*/
export interface IEmployeeAvailabilityCreateInput extends IBasePerTenantAndOrganizationEntityModel {
employeeId: ID;
startDate: Date;
endDate: Date;
dayOfWeek: number; // 0 = Sunday, 6 = Saturday
availabilityStatus: AvailabilityStatusEnum;
availabilityNotes?: string;
}

/**
* Input interface for updating Employee Availability records.
*/
export interface IEmployeeAvailabilityUpdateInput extends IBasePerTenantAndOrganizationEntityModel {
employeeId?: ID;
startDate?: Date;
endDate?: Date;
dayOfWeek?: number; // 0 = Sunday, 6 = Saturday
availabilityStatus?: AvailabilityStatusEnum;
availabilityNotes?: string;
}
1 change: 1 addition & 0 deletions packages/core/src/lib/core/entities/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export * from '../../email-history/email-history.entity';
export * from '../../email-reset/email-reset.entity';
export * from '../../email-template/email-template.entity';
export * from '../../employee-appointment/employee-appointment.entity';
export * from '../../employee-availability/employee-availability.entity';
export * from '../../employee-award/employee-award.entity';
export * from '../../employee-level/employee-level.entity';
export * from '../../employee-phone/employee-phone.entity';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { ICommand } from '@nestjs/cqrs';
import { IEmployeeAvailabilityCreateInput } from '@gauzy/contracts';

export class EmployeeAvailabilityBulkCreateCommand implements ICommand {
static readonly type = '[Employee Bulk Availability ] Create';

constructor(public readonly input: IEmployeeAvailabilityCreateInput[]) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { ICommand } from '@nestjs/cqrs';
import { IEmployeeAvailabilityCreateInput } from '@gauzy/contracts';

export class EmployeeAvailabilityCreateCommand implements ICommand {
static readonly type = '[EmployeeAvailability] Create';

constructor(public readonly input: IEmployeeAvailabilityCreateInput) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { CommandBus, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { IEmployeeAvailability } from '@gauzy/contracts';
import { RequestContext } from '../../../core/context';
import { EmployeeAvailabilityBulkCreateCommand } from '../employee-availability.bulk.create.command';
import { EmployeeAvailability } from '../../employee-availability.entity';
import { EmployeeAvailabilityCreateCommand } from '../employee-availability.create.command';

@CommandHandler(EmployeeAvailabilityBulkCreateCommand)
export class EmployeeAvailabilityBulkCreateHandler implements ICommandHandler<EmployeeAvailabilityBulkCreateCommand> {
constructor(private readonly commandBus: CommandBus) {}

public async execute(command: EmployeeAvailabilityBulkCreateCommand): Promise<IEmployeeAvailability[]> {
const { input } = command;
const allAvailability: IEmployeeAvailability[] = [];
const tenantId = RequestContext.currentTenantId();
samuelmbabhazi marked this conversation as resolved.
Show resolved Hide resolved

for (const item of input) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@samuelmbabhazi Again same, we don't want to insert EmployeeAvailability one by one using EmployeeAvailabilityCreateCommand command.

let availability = new EmployeeAvailability({
...item,
tenantId
});
availability = await this.commandBus.execute(new EmployeeAvailabilityCreateCommand(availability));
allAvailability.push(availability);
}
samuelmbabhazi marked this conversation as resolved.
Show resolved Hide resolved
return allAvailability;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { IEmployeeAvailability } from '@gauzy/contracts';
import { RequestContext } from '../../../core/context';
import { EmployeeAvailabilityService } from '../../employee-availability.service';
import { EmployeeAvailability } from '../../employee-availability.entity';
import { EmployeeAvailabilityCreateCommand } from '../employee-availability.create.command';
import { BadRequestException } from '@nestjs/common';

@CommandHandler(EmployeeAvailabilityCreateCommand)
export class EmployeeAvailabilityCreateHandler implements ICommandHandler<EmployeeAvailabilityCreateCommand> {
constructor(private readonly availabilityService: EmployeeAvailabilityService) {}

public async execute(command: EmployeeAvailabilityCreateCommand): Promise<IEmployeeAvailability> {
const { input } = command;
const { startDate, endDate } = input;
if (!startDate || !endDate) {
throw new BadRequestException('Start date and end date are required.');
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add date range validation.

Validate that the end date is after the start date to ensure a valid date range.

 if (!startDate || !endDate) {
   throw new BadRequestException('Start date and end date are required.');
 }
+if (new Date(endDate) <= new Date(startDate)) {
+  throw new BadRequestException('End date must be after start date.');
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!startDate || !endDate) {
throw new BadRequestException('Start date and end date are required.');
}
if (!startDate || !endDate) {
throw new BadRequestException('Start date and end date are required.');
}
if (new Date(endDate) <= new Date(startDate)) {
throw new BadRequestException('End date must be after start date.');
}

samuelmbabhazi marked this conversation as resolved.
Show resolved Hide resolved
const tenantId = RequestContext.currentTenantId();

const availability = new EmployeeAvailability({
...input,
tenantId
});

return await this.availabilityService.create(availability);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './employee-availability.bulk.create.handler';
export * from './employee-availability.create.handler';
4 changes: 4 additions & 0 deletions packages/core/src/lib/employee-availability/commands/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './employee-availability.bulk.create.command';
export * from './employee-availability.create.command';
export * from './handlers/employee-availability.bulk.create.handler';
export * from './handlers/employee-availability.create.handler';
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { UpdateResult } from 'typeorm';
import { Body, Controller, Get, HttpCode, HttpStatus, Param, Post, Put, Query, UseGuards } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { ID, IEmployeeAvailability, IEmployeeAvailabilityCreateInput, IPagination } from '@gauzy/contracts';
import { EmployeeAvailabilityService } from './employee-availability.service';
import { EmployeeAvailability } from './employee-availability.entity';
import { CrudController, PaginationParams } from '../core';
import { TenantPermissionGuard, UUIDValidationPipe } from '../shared';
import { EmployeeAvailabilityBulkCreateCommand, EmployeeAvailabilityCreateCommand } from './commands';

@ApiTags('EmployeeAvailability')
@UseGuards(TenantPermissionGuard)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@samuelmbabhazi Permission Gurad is missing and also permissions missing for API routes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding role-based access control.

The controller only uses TenantPermissionGuard. Consider adding role-based access control for finer-grained permissions.

+@UseGuards(TenantPermissionGuard, RolesGuard)
+@Roles(RolesEnum.ADMIN, RolesEnum.MANAGER)
 @UseGuards(TenantPermissionGuard)

Committable suggestion skipped: line range outside the PR's diff.

@Controller('/employee-availability')
export class EmployeeAvailabilityController extends CrudController<EmployeeAvailability> {
constructor(
private readonly availabilityService: EmployeeAvailabilityService,
private readonly commandBus: CommandBus
) {
super(availabilityService);
}

/**
* Create multiple employee availability records in bulk.
*
* @param entities List of availability records to create
* @returns The created availability records
*/
@ApiOperation({ summary: 'Create multiple availability records' })
@ApiResponse({
status: HttpStatus.CREATED,
description: 'The records have been successfully created.'
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description: 'Invalid input. The response body may contain clues as to what went wrong.'
})
@HttpCode(HttpStatus.CREATED)
@Post('/bulk')
async createBulk(@Body() entities: IEmployeeAvailabilityCreateInput[]): Promise<IEmployeeAvailability[]> {
return await this.commandBus.execute(new EmployeeAvailabilityBulkCreateCommand(entities));
}
samuelmbabhazi marked this conversation as resolved.
Show resolved Hide resolved

/**
* Retrieve all employee availability records.
*
* @param data Query parameters, including relations and filters
* @returns A paginated list of availability records
*/
@ApiOperation({ summary: 'Retrieve all availability records' })
@ApiResponse({
status: HttpStatus.OK,
description: 'Successfully retrieved availability records.'
})
@ApiResponse({
status: HttpStatus.NOT_FOUND,
description: 'No availability records found.'
})
@Get()
async findAll(
@Query() filter: PaginationParams<EmployeeAvailability>
): Promise<IPagination<IEmployeeAvailability>> {
return this.availabilityService.findAll(filter);
}

/**
* Create a new employee availability record.
*
* @param entity The data for the new availability record
* @returns The created availability record
*/
@ApiOperation({ summary: 'Create a new availability record' })
@ApiResponse({
status: HttpStatus.CREATED,
description: 'The record has been successfully created.'
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description: 'Invalid input. The response body may contain clues as to what went wrong.'
})
@HttpCode(HttpStatus.CREATED)
@Post()
async create(@Body() entity: IEmployeeAvailabilityCreateInput): Promise<IEmployeeAvailability> {
return await this.commandBus.execute(new EmployeeAvailabilityCreateCommand(entity));
}
samuelmbabhazi marked this conversation as resolved.
Show resolved Hide resolved

/**
* Update an existing employee availability record by its ID.
*
* @param id The ID of the availability record
* @param entity The updated data for the record
* @returns The updated availability record
*/
@ApiOperation({ summary: 'Update an existing availability record' })
@ApiResponse({
status: HttpStatus.ACCEPTED,
description: 'The record has been successfully updated.'
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description: 'Invalid input. The response body may contain clues as to what went wrong.'
})
@HttpCode(HttpStatus.ACCEPTED)
@Put(':id')
async update(
@Param('id', UUIDValidationPipe) id: ID,
@Body() entity: IEmployeeAvailability
): Promise<IEmployeeAvailability | UpdateResult> {
return this.availabilityService.update(id, { ...entity });
}
samuelmbabhazi marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsDate, IsInt, IsOptional, IsEnum } from 'class-validator';
import { JoinColumn, RelationId } from 'typeorm';
import { AvailabilityStatusEnum, ID, IEmployeeAvailability } from '@gauzy/contracts';
import { Employee, TenantOrganizationBaseEntity } from '../core/entities/internal';
import { MultiORMColumn, MultiORMEntity, MultiORMManyToOne } from './../core/decorators/entity';
import { AvailabilityStatusTransformer } from '../shared/pipes/employee-availability-status.pipe';

@MultiORMEntity('employee_availability')
export class EmployeeAvailability extends TenantOrganizationBaseEntity implements IEmployeeAvailability {
@ApiProperty({ type: () => Date })
@IsDate()
@IsNotEmpty()
@MultiORMColumn()
startDate: Date;

@ApiProperty({ type: () => Date })
@IsDate()
@IsNotEmpty()
@MultiORMColumn()
endDate: Date;

@ApiProperty({ type: () => Number, description: 'Day of the week (0 = Sunday, 6 = Saturday)' })
@IsInt()
@IsNotEmpty()
@MultiORMColumn({ check: 'day_of_week BETWEEN 0 AND 6' })
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@samuelmbabhazi Is this property supporting into Mikro-ORM?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about micro-orm, so we can do it in the migration

dayOfWeek: number;

@ApiProperty({ enum: AvailabilityStatusEnum })
@IsOptional()
@IsEnum(AvailabilityStatusEnum)
@MultiORMColumn({
type: 'int',
transformer: new AvailabilityStatusTransformer()
})
availabilityStatus: AvailabilityStatusEnum;

@ApiPropertyOptional({
type: () => String,
description: 'Optional notes (e.g., "Available until 2 PM")',
required: false
})
@IsString()
@IsOptional()
@MultiORMColumn({ nullable: true })
availabilityNotes?: string;

/*
|--------------------------------------------------------------------------
| @ManyToOne
|--------------------------------------------------------------------------
*/

/**
* Employee
*/
@MultiORMManyToOne(() => Employee, {
onDelete: 'CASCADE'
})
@JoinColumn()
employee: Employee;

@ApiProperty({ type: () => String })
@RelationId((it: EmployeeAvailability) => it.employee)
@MultiORMColumn()
employeeId: ID;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { EmployeeAvailabilityService } from './employee-availability.service';
import { EmployeeAvailabilityController } from './employee-availability.controller';

@Module({
providers: [EmployeeAvailabilityService],
controllers: [EmployeeAvailabilityController]
})
samuelmbabhazi marked this conversation as resolved.
Show resolved Hide resolved
export class EmployeeAvailabilityModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Injectable } from '@nestjs/common';
import { TypeOrmEmployeeAvailabilityRepository } from './repository/type-orm-employee-availability.repository';
import { MikroOrmEmployeeAvailabilityRepository } from './repository/micro-orm-employee-availability.repository';
import { TenantAwareCrudService } from './../core/crud';
import { EmployeeAvailability } from './employee-availability.entity';

@Injectable()
export class EmployeeAvailabilityService extends TenantAwareCrudService<EmployeeAvailability> {
constructor(
typeOrmEmployeeAvailabilityRepository: TypeOrmEmployeeAvailabilityRepository,
mikroOrmEmployeeAvailabilityRepository: MikroOrmEmployeeAvailabilityRepository
) {
super(typeOrmEmployeeAvailabilityRepository, mikroOrmEmployeeAvailabilityRepository);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add essential business logic methods for availability management.

The service should include methods for:

  1. Validating scheduling conflicts
  2. Checking employee availability for a given time period
  3. Handling overlapping availability records

Consider adding these methods:

async validateAvailabilityConflicts(
  employeeId: string,
  startDate: Date,
  endDate: Date,
  excludeId?: string
): Promise<boolean> {
  const conflicts = await this.repository.find({
    where: {
      employeeId,
      startDate: LessThanOrEqual(endDate),
      endDate: MoreThanOrEqual(startDate),
      ...(excludeId && { id: Not(excludeId) })
    }
  });
  return conflicts.length > 0;
}

async getEmployeeAvailability(
  employeeId: string,
  date: Date
): Promise<EmployeeAvailability | null> {
  const dayOfWeek = date.getDay();
  return this.repository.findOne({
    where: {
      employeeId,
      dayOfWeek,
      startDate: LessThanOrEqual(date),
      endDate: MoreThanOrEqual(date)
    }
  });
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 9-14: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

3 changes: 3 additions & 0 deletions packages/core/src/lib/employee-availability/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { EmployeeAvailability } from './employee-availability.entity';
export { EmployeeAvailabilityModule } from './employee-availability.module';
export { EmployeeAvailabilityService } from './employee-availability.service';
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { MikroOrmBaseEntityRepository } from '../../core/repository/mikro-orm-base-entity.repository';
import { EmployeeAvailability } from '../employee-availability.entity';

export class MikroOrmEmployeeAvailabilityRepository extends MikroOrmBaseEntityRepository<EmployeeAvailability> {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { EmployeeAvailability } from '../employee-availability.entity';

@Injectable()
export class TypeOrmEmployeeAvailabilityRepository extends Repository<EmployeeAvailability> {
constructor(@InjectRepository(EmployeeAvailability) readonly repository: Repository<EmployeeAvailability>) {
super(repository.target, repository.manager, repository.queryRunner);
}
}
Loading
Loading