58 lines
2.2 KiB
TypeScript
58 lines
2.2 KiB
TypeScript
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { CreateEmployeeDto } from './dto/create-employee.dto';
|
|
import { UpdateEmployeeDto } from './dto/update-employee.dto';
|
|
|
|
@Injectable()
|
|
export class EmployeeService {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
async findAll(tenantId: string) {
|
|
return this.prisma.employee.findMany({
|
|
where: { tenantId },
|
|
include: { _count: { select: { assets: true } } },
|
|
orderBy: { createdAt: 'desc' },
|
|
});
|
|
}
|
|
|
|
async findById(tenantId: string, id: string) {
|
|
const employee = await this.prisma.employee.findFirst({
|
|
where: { id, tenantId },
|
|
include: { assets: true },
|
|
});
|
|
if (!employee) throw new NotFoundException('Employee not found');
|
|
return employee;
|
|
}
|
|
|
|
async create(tenantId: string, dto: CreateEmployeeDto) {
|
|
const count = await this.prisma.employee.count({ where: { tenantId } });
|
|
const employeeNo = `E-${String(count + 1).padStart(4, '0')}`;
|
|
|
|
return this.prisma.employee.create({
|
|
data: { tenantId, employeeNo, ...dto, salary: dto.salary || null },
|
|
});
|
|
}
|
|
|
|
async update(tenantId: string, id: string, dto: UpdateEmployeeDto) {
|
|
const existing = await this.prisma.employee.findFirst({ where: { id, tenantId } });
|
|
if (!existing) throw new NotFoundException('Employee not found');
|
|
|
|
return this.prisma.employee.update({
|
|
where: { id },
|
|
data: {
|
|
...(dto.firstName && { firstName: dto.firstName }),
|
|
...(dto.lastName && { lastName: dto.lastName }),
|
|
...(dto.email !== undefined && { email: dto.email }),
|
|
...(dto.phone !== undefined && { phone: dto.phone }),
|
|
...(dto.position && { position: dto.position }),
|
|
...(dto.department !== undefined && { department: dto.department }),
|
|
...(dto.status && { status: dto.status }),
|
|
...(dto.salary !== undefined && { salary: dto.salary }),
|
|
...(dto.notes !== undefined && { notes: dto.notes }),
|
|
...(dto.userId !== undefined && { userId: dto.userId || null }),
|
|
...(dto.status === 'terminated' && { terminatedAt: new Date() }),
|
|
},
|
|
});
|
|
}
|
|
}
|