Add employees management module with database schema and validation

- Introduced `EmployeesModule` to manage employee data, including read and write controllers.
- Created database migrations for the `employees` table, including constraints and unique indexes.
- Implemented validation for employee fields such as name, code, and position with corresponding utility functions.
- Developed service and repository layers for handling employee data operations.
- Added unit tests for the employees service, repository, and controllers to ensure functionality and correctness.
- Updated application module to include the new `EmployeesModule` for better organization.
This commit is contained in:
shancheas
2026-08-24 15:15:52 +07:00
parent cdcc508947
commit ddbe8a9ef8
20 changed files with 3355 additions and 2 deletions
@@ -0,0 +1,290 @@
import {
ConflictException,
Inject,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { and, asc, count, eq, ilike, inArray, or, SQL } from 'drizzle-orm';
import { DateTime } from '../../../common/value-objects/date-time/date-time';
import { PhoneNumber } from '../../../common/value-objects/phone-number/phone-number';
import { Status } from '../../../common/value-objects/status/status';
import { DRIZZLE, type DrizzleDB } from '../../../database/database.module';
import { employees, type EmployeeRow } from '../../../database/employees-table';
import type { EmployeePosition } from './employee-fields';
import type {
CreateEmployeeInput,
Employee,
ListEmployeesFilters,
UpdateEmployeeInput,
} from './employee';
@Injectable()
export class EmployeesRepository {
constructor(@Inject(DRIZZLE) private readonly db: DrizzleDB) {}
async list(
filters: ListEmployeesFilters,
): Promise<{ data: Employee[]; total: number }> {
const where = this.buildListWhere(filters);
const totalRows = await this.db
.select({ total: count() })
.from(employees)
.where(where);
const totalRow = totalRows[0];
let qb = this.db.select().from(employees).$dynamic();
qb = this.extendListQuery(qb, filters);
const rows = await qb
.where(where)
.orderBy(asc(employees.code))
.limit(filters.limit)
.offset(filters.offset);
return {
data: rows.map((row) => this.toDomain(row)),
total: Number(totalRow?.total ?? 0),
};
}
/**
* Hook for modules to add joins/extra predicates without forking list.
*/
extendListQuery<T>(qb: T, filters: ListEmployeesFilters): T {
void filters;
return qb;
}
async findById(id: string): Promise<Employee | null> {
const rows: EmployeeRow[] = await this.db
.select()
.from(employees)
.where(eq(employees.id, id))
.limit(1);
const row = rows[0];
return row ? this.toDomain(row) : null;
}
async findByCode(code: string): Promise<Employee | null> {
const rows = await this.db
.select()
.from(employees)
.where(eq(employees.code, code))
.limit(1);
const row = rows[0];
return row ? this.toDomain(row) : null;
}
async create(input: CreateEmployeeInput): Promise<Employee> {
const now = DateTime.fromUnixMs(Date.now());
const status = input.status ?? Status.create(Status.DEFAULT);
try {
const inserted = await this.db
.insert(employees)
.values(this.toInsertValues(input, status, now, input.userId))
.returning();
const row = inserted[0];
return this.toDomain(row);
} catch (error) {
this.rethrowUniqueViolation(error);
}
}
async createMany(inputs: CreateEmployeeInput[]): Promise<number> {
if (inputs.length === 0) {
return 0;
}
const now = DateTime.fromUnixMs(Date.now());
try {
await this.db.transaction(async (tx) => {
for (const input of inputs) {
const status = input.status ?? Status.create(Status.DEFAULT);
await tx
.insert(employees)
.values(this.toInsertValues(input, status, now, input.userId));
}
});
return inputs.length;
} catch (error) {
this.rethrowUniqueViolation(error);
}
}
async update(id: string, input: UpdateEmployeeInput): Promise<Employee> {
const existing = await this.findById(id);
if (!existing) {
throw new NotFoundException('Employee not found');
}
const now = DateTime.fromUnixMs(Date.now());
try {
const updated = await this.db
.update(employees)
.set({
code: input.code ?? existing.code,
name: input.name ?? existing.name,
phone: input.phone?.value ?? existing.phone.value,
position: input.position ?? existing.position,
updatedAt: now.value,
updatedBy: input.userId,
})
.where(eq(employees.id, id))
.returning();
const row = updated[0];
return this.toDomain(row);
} catch (error) {
this.rethrowUniqueViolation(error);
}
}
async updateStatus(
id: string,
status: Status,
userId: string,
): Promise<Employee> {
const now = DateTime.fromUnixMs(Date.now());
const updated = await this.db
.update(employees)
.set({
status: status.value,
updatedAt: now.value,
updatedBy: userId,
})
.where(eq(employees.id, id))
.returning();
const row = updated[0];
if (!row) {
throw new NotFoundException('Employee not found');
}
return this.toDomain(row);
}
async bulkUpdateStatus(
ids: string[],
status: Status,
userId: string,
): Promise<number> {
if (ids.length === 0) {
return 0;
}
const now = DateTime.fromUnixMs(Date.now());
const rows = await this.db
.update(employees)
.set({
status: status.value,
updatedAt: now.value,
updatedBy: userId,
})
.where(inArray(employees.id, ids))
.returning({ id: employees.id });
return rows.length;
}
async delete(id: string): Promise<void> {
const deleted = await this.db
.delete(employees)
.where(eq(employees.id, id))
.returning({ id: employees.id });
if (deleted.length === 0) {
throw new NotFoundException('Employee not found');
}
}
async bulkDelete(ids: string[]): Promise<number> {
if (ids.length === 0) {
return 0;
}
const deleted = await this.db
.delete(employees)
.where(inArray(employees.id, ids))
.returning({ id: employees.id });
return deleted.length;
}
private buildListWhere(filters: ListEmployeesFilters): SQL | undefined {
const parts: SQL[] = [];
if (filters.code) {
parts.push(ilike(employees.code, `%${filters.code}%`));
}
if (filters.name) {
parts.push(ilike(employees.name, `%${filters.name}%`));
}
if (filters.phone) {
parts.push(ilike(employees.phone, `%${filters.phone}%`));
}
if (filters.position) {
parts.push(eq(employees.position, filters.position));
}
if (filters.status) {
parts.push(eq(employees.status, filters.status));
}
if (filters.search) {
const search = or(
ilike(employees.code, `%${filters.search}%`),
ilike(employees.name, `%${filters.search}%`),
);
if (search) {
parts.push(search);
}
}
if (parts.length === 0) {
return undefined;
}
return parts.length === 1 ? parts[0] : and(...parts);
}
private toInsertValues(
input: CreateEmployeeInput,
status: Status,
now: DateTime,
userId: string,
) {
return {
code: input.code,
name: input.name,
phone: input.phone.value,
position: input.position,
status: status.value,
createdAt: now.value,
updatedAt: now.value,
createdBy: userId,
updatedBy: userId,
};
}
private toDomain(row: EmployeeRow): Employee {
return {
id: row.id,
code: row.code,
name: row.name,
phone: PhoneNumber.create(row.phone),
position: row.position as EmployeePosition,
status: Status.create(row.status),
createdAt: DateTime.fromUnixMs(row.createdAt),
updatedAt: DateTime.fromUnixMs(row.updatedAt),
createdBy: row.createdBy,
updatedBy: row.updatedBy,
};
}
private rethrowUniqueViolation(error: unknown): never {
const err = this.unwrapDbError(error);
if (err.code === '23505') {
throw new ConflictException('Employee code already exists');
}
throw error;
}
private unwrapDbError(error: unknown): { code?: string } {
let current: unknown = error;
for (let i = 0; i < 5; i++) {
if (!current || typeof current !== 'object') {
break;
}
const obj = current as { code?: string; cause?: unknown };
if (obj.code === '23505' || obj.code === '23503') {
return { code: obj.code };
}
current = obj.cause;
}
return error as { code?: string };
}
}