import { Body, Controller, Delete, Get, Patch, Path, Post, Request, Route, Security, Tags, } from "tsoa"; import { AppDataSource } from "../database/data-source"; import { CreateProfileSalaryEmployee, ProfileSalary, UpdateProfileSalaryEmployee, } from "../entities/ProfileSalary"; import HttpSuccess from "../interfaces/http-success"; import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; import { ProfileSalaryHistory } from "../entities/ProfileSalaryHistory"; import { RequestWithUser } from "../middlewares/user"; import { ProfileEmployee } from "../entities/ProfileEmployee"; import { LessThan, MoreThan } from "typeorm"; import permission from "../interfaces/permission"; import { setLogDataDiff } from "../interfaces/utils"; @Route("api/v1/org/profile-employee/salary") @Tags("ProfileSalary") @Security("bearerAuth") export class ProfileSalaryEmployeeController extends Controller { private profileRepo = AppDataSource.getRepository(ProfileEmployee); private salaryRepo = AppDataSource.getRepository(ProfileSalary); private salaryHistoryRepo = AppDataSource.getRepository(ProfileSalaryHistory); @Get("user") public async getSalaryUser(@Request() request: { user: Record }) { const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); if (!profile) { throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); } const record = await this.salaryRepo.find({ where: { profileEmployeeId: profile.id }, order: { order: "ASC" }, }); return new HttpSuccess(record); } @Get("position/user") public async getSalaryPositionUser(@Request() request: { user: Record }) { const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); if (!profile) { throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); } const record = await this.salaryRepo.find({ where: { profileEmployeeId: profile.id }, order: { order: "ASC" }, }); return new HttpSuccess(record); } @Get("{profileId}") public async getSalaryEmployee(@Path() profileId: string, @Request() req: RequestWithUser) { let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_EMP"); if (_workflow == false) await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileId); const record = await this.salaryRepo.find({ where: { profileEmployeeId: profileId }, order: { order: "ASC" }, }); return new HttpSuccess(record); } @Get("position/{profileId}") public async getPositionSalaryEmployee( @Path() profileId: string, @Request() req: RequestWithUser, ) { let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_EMP"); if (_workflow == false) await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileId); const record = await this.salaryRepo.find({ where: { profileEmployeeId: profileId }, order: { order: "ASC" }, }); return new HttpSuccess(record); } @Get("tenure/user") public async getPositionTenureUser(@Request() request: { user: Record }) { const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); if (!profile) { throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); } const position = await AppDataSource.query("CALL GetProfileEmployeeSalaryPosition(?)", [ profile.id, ]); const _position = position.length > 0 ? position[0] : []; const mapPosition = _position.length > 1 ? _position.slice(1).map((curr: any, index: number) => ({ days: curr.days_diff ? Number(curr.days_diff) : 0, name: _position[index]?.positionName, })) : []; const groupMapPosition = mapPosition.reduce( (acc: any, curr: any) => { let existing = acc.find((item: any) => item.name === curr.name); if (existing) { existing.days += curr.days; } else { existing = { name: curr.name, days: curr.days }; acc.push(existing); } existing.year = Math.floor(existing.days / 365.2524); existing.month = Math.floor((existing.days / 30.4375) % 12); existing.day = Math.floor(existing.days % 30.4375); return acc; }, [] as { name: string; days: number; year: number; month: number; day: number }[], ); const posLevel = await AppDataSource.query("CALL GetProfileEmployeeSalaryLevel(?)", [profile.id]); const _posLevel = posLevel.length > 0 ? posLevel[0] : []; const mapPosLevel = _posLevel.length > 1 ? _posLevel.slice(1).map((curr: any, index: number) => ({ days: curr.days_diff ? Number(curr.days_diff) : 0, name: !_posLevel[index]?.positionType && _posLevel[index]?.positionCee ? `ระดับ ${_posLevel[index]?.positionCee.trim()}` : _posLevel[index]?.positionLevel, })) : []; const groupMapPosLevel = mapPosLevel.reduce( (acc: any, curr: any) => { let existing = acc.find((item: any) => item.name === curr.name); if (existing) { existing.days += curr.days; } else { existing = { name: curr.name, days: curr.days }; acc.push(existing); } existing.year = Math.floor(existing.days / 365.2524); existing.month = Math.floor((existing.days / 30.4375) % 12); existing.day = Math.floor(existing.days % 30.4375); return acc; }, [] as { name: string; days: number; year: number; month: number; day: number }[], ); return new HttpSuccess({ position: groupMapPosition, posLevel: groupMapPosLevel, }); } @Get("tenure/{profileId}") public async getPositionTenure(@Path() profileId: string, @Request() req: RequestWithUser) { const position = await AppDataSource.query("CALL GetProfileEmployeeSalaryPosition(?)", [ profileId, ]); const _position = position.length > 0 ? position[0] : []; const mapPosition = _position.length > 1 ? _position.slice(1).map((curr: any, index: number) => ({ days: curr.days_diff ? Number(curr.days_diff) : 0, name: _position[index]?.positionName, })) : []; const groupMapPosition = mapPosition.reduce( (acc: any, curr: any) => { let existing = acc.find((item: any) => item.name === curr.name); if (existing) { existing.days += curr.days; } else { existing = { name: curr.name, days: curr.days }; acc.push(existing); } existing.year = Math.floor(existing.days / 365.2524); existing.month = Math.floor((existing.days / 30.4375) % 12); existing.day = Math.floor(existing.days % 30.4375); return acc; }, [] as { name: string; days: number; year: number; month: number; day: number }[], ); const posLevel = await AppDataSource.query("CALL GetProfileEmployeeSalaryLevel(?)", [profileId]); const _posLevel = posLevel.length > 0 ? posLevel[0] : []; const mapPosLevel = _posLevel.length > 1 ? _posLevel.slice(1).map((curr: any, index: number) => ({ days: curr.days_diff ? Number(curr.days_diff) : 0, name: !_posLevel[index]?.positionType && _posLevel[index]?.positionCee ? `ระดับ ${_posLevel[index]?.positionCee.trim()}` : _posLevel[index]?.positionLevel, })) : []; const groupMapPosLevel = mapPosLevel.reduce( (acc: any, curr: any) => { let existing = acc.find((item: any) => item.name === curr.name); if (existing) { existing.days += curr.days; } else { existing = { name: curr.name, days: curr.days }; acc.push(existing); } existing.year = Math.floor(existing.days / 365.2524); existing.month = Math.floor((existing.days / 30.4375) % 12); existing.day = Math.floor(existing.days % 30.4375); return acc; }, [] as { name: string; days: number; year: number; month: number; day: number }[], ); return new HttpSuccess({ position: groupMapPosition, posLevel: groupMapPosLevel, }); } @Get("admin/{profileId}") public async getSalaryEmployeeAdmin(@Path() profileId: string, @Request() req: RequestWithUser) { let _workflow = await new permission().Workflow(req, profileId, "SYS_WAGE"); if (_workflow == false) await new permission().PermissionGet(req, "SYS_WAGE"); const record = await this.salaryRepo.find({ where: { profileEmployeeId: profileId }, order: { order: "ASC" }, }); return new HttpSuccess(record); } @Get("admin/history/{salaryId}") public async salaryAdminHistory(@Path() salaryId: string, @Request() req: RequestWithUser) { const _record = await this.salaryRepo.findOneBy({ id: salaryId }); if (_record) { let _workflow = await new permission().Workflow(req, salaryId, "SYS_REGISTRY_EMP"); if (_workflow == false) await new permission().PermissionOrgUserGet( req, "SYS_REGISTRY_EMP", _record.profileEmployeeId, ); } const record = await this.salaryHistoryRepo.find({ where: { profileSalaryId: salaryId, }, order: { createdAt: "DESC" }, }); return new HttpSuccess(record); } @Get("history/{salaryId}") public async salaryHistory(@Path() salaryId: string) { const record = await this.salaryHistoryRepo.find({ where: { profileSalaryId: salaryId, }, order: { createdAt: "DESC" }, }); return new HttpSuccess(record); } @Post() public async newSalaryEmployee( @Request() req: RequestWithUser, @Body() body: CreateProfileSalaryEmployee, ) { if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } const profile = await this.profileRepo.findOneBy({ id: body.profileEmployeeId }); if (!profile) { throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); } await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_EMP", profile.id); const dest_item = await this.salaryRepo.findOne({ where: { profileEmployeeId: body.profileEmployeeId }, order: { order: "DESC" }, }); const before = null; const data = new ProfileSalary(); const meta = { order: dest_item == null ? 1 : dest_item.order + 1, createdUserId: req.user.sub, createdFullName: req.user.name, lastUpdateUserId: req.user.sub, lastUpdateFullName: req.user.name, createdAt: new Date(), lastUpdatedAt: new Date(), }; Object.assign(data, { ...body, ...meta }); const history = new ProfileSalaryHistory(); Object.assign(history, { ...data, id: undefined }); const _null: any = null; await this.salaryRepo.save(data, { data: req }); setLogDataDiff(req, { before, after: data }); history.profileSalaryId = data.id; await this.salaryHistoryRepo.save(history, { data: req }); profile.amount = body?.amount ?? _null; profile.positionSalaryAmount = body?.positionSalaryAmount ?? _null; profile.mouthSalaryAmount = body.mouthSalaryAmount ?? _null; await this.profileRepo.save(profile, { data: req }); return new HttpSuccess(); } @Post("update") public async updateSalaryEmployee( @Request() req: RequestWithUser, @Body() body: CreateProfileSalaryEmployee, ) { if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } const profile = await this.profileRepo.findOneBy({ id: body.profileEmployeeId }); if (!profile) { throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); } await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_EMP", profile.id); const dest_item = await this.salaryRepo.findOne({ where: { profileEmployeeId: body.profileEmployeeId }, order: { order: "DESC" }, }); const before = null; const data = new ProfileSalary(); const meta = { order: dest_item == null ? 1 : dest_item.order + 1, createdUserId: req.user.sub, createdFullName: req.user.name, lastUpdateUserId: req.user.sub, lastUpdateFullName: req.user.name, createdAt: new Date(), lastUpdatedAt: new Date(), }; Object.assign(data, { ...body, ...meta }); const history = new ProfileSalaryHistory(); Object.assign(history, { ...data, id: undefined }); await this.salaryRepo.save(data, { data: req }); setLogDataDiff(req, { before, after: data }); history.profileSalaryId = data.id; await this.salaryHistoryRepo.save(history, { data: req }); let _null: any = null; profile.amount = body.amount ?? _null; profile.amountSpecial = body.amountSpecial ?? _null; profile.positionSalaryAmount = body.positionSalaryAmount ?? _null; profile.mouthSalaryAmount = body.mouthSalaryAmount ?? _null; await this.profileRepo.save(profile); return new HttpSuccess(); } @Patch("{salaryId}") public async editSalaryEmployee( @Request() req: RequestWithUser, @Body() body: UpdateProfileSalaryEmployee, @Path() salaryId: string, ) { const record = await this.salaryRepo.findOneBy({ id: salaryId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); await new permission().PermissionOrgUserUpdate( req, "SYS_REGISTRY_EMP", record.profileEmployeeId, ); const before = structuredClone(record); const history = new ProfileSalaryHistory(); Object.assign(record, body); Object.assign(history, { ...record, id: undefined }); history.profileSalaryId = salaryId; record.lastUpdateUserId = req.user.sub; record.lastUpdateFullName = req.user.name; record.lastUpdatedAt = new Date(); history.lastUpdateUserId = req.user.sub; history.lastUpdateFullName = req.user.name; history.createdUserId = req.user.sub; history.createdFullName = req.user.name; history.createdAt = new Date(); history.lastUpdatedAt = new Date(); await Promise.all([ this.salaryRepo.save(record, { data: req }), setLogDataDiff(req, { before, after: record }), this.salaryHistoryRepo.save(history, { data: req }), ]); return new HttpSuccess(); } @Delete("{salaryId}") public async deleteSalaryEmployee(@Path() salaryId: string, @Request() req: RequestWithUser) { const _record = await this.salaryRepo.findOneBy({ id: salaryId }); if (_record) { await new permission().PermissionOrgUserDelete( req, "SYS_REGISTRY_EMP", _record.profileEmployeeId, ); } const data = await this.salaryRepo.findOneBy({ id: salaryId }); if (!data) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); if (data == null) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); const profileId = data.profileEmployeeId; await this.salaryHistoryRepo.delete({ profileSalaryId: salaryId, }); const result = await this.salaryRepo.delete({ id: salaryId }); const salaryList = await this.salaryRepo.find({ where: { profileEmployeeId: profileId, }, }); salaryList.forEach(async (p, i) => { p.order = i + 1; await this.salaryRepo.save(p); }); if (result.affected == undefined || result.affected <= 0) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); } return new HttpSuccess(); } @Get("swap/{direction}/{salaryId}") public async swapSalaryEmployee( @Path() direction: string, salaryId: string, @Request() req: RequestWithUser, ) { const _record = await this.salaryRepo.findOneBy({ id: salaryId }); if (_record) { await new permission().PermissionOrgUserGet( req, "SYS_REGISTRY_EMP", _record.profileEmployeeId, ); } const source_item = await this.salaryRepo.findOne({ where: { id: salaryId } }); if (source_item == null) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); const sourceOrder = source_item.order; if (direction.trim().toUpperCase() == "UP") { const dest_item = await this.salaryRepo.findOne({ where: { profileEmployeeId: source_item.profileEmployeeId, order: LessThan(sourceOrder) }, order: { order: "DESC" }, }); if (dest_item == null) return new HttpSuccess(); var destOrder = dest_item.order; dest_item.order = sourceOrder; source_item.order = destOrder; await Promise.all([this.salaryRepo.save(source_item), this.salaryRepo.save(dest_item)]); } else { const dest_item = await this.salaryRepo.findOne({ where: { profileEmployeeId: source_item.profileEmployeeId, order: MoreThan(sourceOrder) }, order: { order: "ASC" }, }); if (dest_item == null) return new HttpSuccess(); var destOrder = dest_item.order; dest_item.order = sourceOrder; source_item.order = destOrder; await Promise.all([this.salaryRepo.save(source_item), this.salaryRepo.save(dest_item)]); } return new HttpSuccess(); } }