diff --git a/src/controllers/ProfileAbilityEmployeeController.ts b/src/controllers/ProfileAbilityEmployeeController.ts index d18927c5..7bac2718 100644 --- a/src/controllers/ProfileAbilityEmployeeController.ts +++ b/src/controllers/ProfileAbilityEmployeeController.ts @@ -81,7 +81,6 @@ export class ProfileAbilityEmployeeController extends Controller { return new HttpSuccess(getProfileAbilityId); } - @Get("history/{abilityId}") @Example({ status: 200, @@ -136,7 +135,7 @@ export class ProfileAbilityEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileAbilityEmployee, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -167,7 +166,7 @@ export class ProfileAbilityEmployeeController extends Controller { @Request() req: RequestWithUser, @Path() abilityId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.profileAbilityRepo.findOneBy({ id: abilityId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -190,7 +189,7 @@ export class ProfileAbilityEmployeeController extends Controller { @Delete("{abilityId}") public async deleteProfileAbility(@Path() abilityId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.profileAbilityHistoryRepo.delete({ profileAbilityId: abilityId, }); diff --git a/src/controllers/ProfileAbilityEmployeeTempController.ts b/src/controllers/ProfileAbilityEmployeeTempController.ts new file mode 100644 index 00000000..915e52a9 --- /dev/null +++ b/src/controllers/ProfileAbilityEmployeeTempController.ts @@ -0,0 +1,205 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { Profile } from "../entities/Profile"; +import { + CreateProfileAbility, + CreateProfileAbilityEmployee, + ProfileAbility, + UpdateProfileAbility, +} from "../entities/ProfileAbility"; +import { ProfileAbilityHistory } from "../entities/ProfileAbilityHistory"; +import { RequestWithUser } from "../middlewares/user"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import HttpSuccess from "../interfaces/http-success"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/ability") +@Tags("ProfileAbilityEmployee") +@Security("bearerAuth") +export class ProfileAbilityEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private profileAbilityRepo = AppDataSource.getRepository(ProfileAbility); + private profileAbilityHistoryRepo = AppDataSource.getRepository(ProfileAbilityHistory); + + @Get("user") + public async detailProfileAbilityUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileAbilityId = await this.profileAbilityRepo.find({ + where: { profileEmployeeId: profile.id }, + }); + if (!getProfileAbilityId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAbilityId); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "ad7d0955-7bcd-4ed0-911c-2edceba12579", + createdAt: "2024-03-12T21:37:35.037Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T21:37:35.037Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "test bar", + lastUpdateFullName: "test bar", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + remark: "ต้องส่งให้ทันก่อนวันที่ 15 มีนาคม", + detail: "-", + reference: "-", + dateStart: "2024-03-13T04:36:06.000Z", + dateEnd: "2024-03-13T04:36:06.000Z", + field: "ความมั่นคง", + }, + ], + }) + public async detailProfileAbility(@Path() profileEmployeeId: string) { + const getProfileAbilityId = await this.profileAbilityRepo.findBy({ profileEmployeeId }); + if (!getProfileAbilityId) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAbilityId); + } + + @Get("history/{abilityId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "1c92cd8a-e176-48af-ac00-c018fb4c9895", + createdAt: "2024-03-12T21:38:56.342Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T21:38:56.342Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "test bar", + remark: "ต้องส่งให้ทันก่อนวันที่ 15 มีนาคม", + detail: "ด่วน", + reference: "-", + dateStart: "2024-03-13T04:36:06.000Z", + dateEnd: "2024-03-13T04:36:06.000Z", + field: "ความมั่นคง", + profileAbilityId: "ad7d0955-7bcd-4ed0-911c-2edceba12579", + }, + { + id: "2fb95768-cb62-40a3-9540-5a561d640959", + createdAt: "2024-03-12T21:39:06.094Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T21:39:06.094Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "test bar", + remark: "ต้องส่งให้ทันก่อนวันที่ 15 มีนาคม", + detail: "ด่วนมากสุด", + reference: "-", + dateStart: "2024-03-13T04:36:06.000Z", + dateEnd: "2024-03-13T04:36:06.000Z", + field: "ความมั่นคง", + profileAbilityId: "ad7d0955-7bcd-4ed0-911c-2edceba12579", + }, + ], + }) + public async getProfileAbilityHistory(@Path() abilityId: string) { + const record = await this.profileAbilityHistoryRepo.findBy({ + profileAbilityId: abilityId, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Post() + public async newProfileAbility( + @Request() req: RequestWithUser, + @Body() body: CreateProfileAbilityEmployee, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileAbility(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.profileAbilityRepo.save(data); + + return new HttpSuccess(); + } + + @Patch("{abilityId}") + public async editProfileAbility( + @Body() requestBody: UpdateProfileAbility, + @Request() req: RequestWithUser, + @Path() abilityId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.profileAbilityRepo.findOneBy({ id: abilityId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileAbilityHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, requestBody); + + history.profileAbilityId = abilityId; + history.lastUpdateFullName = req.user.name; + record.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.profileAbilityRepo.save(record), + this.profileAbilityHistoryRepo.save(history), + ]); + + return new HttpSuccess(); + } + + @Delete("{abilityId}") + public async deleteProfileAbility(@Path() abilityId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.profileAbilityHistoryRepo.delete({ + profileAbilityId: abilityId, + }); + + const result = await this.profileAbilityRepo.delete({ id: abilityId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileAddressEmployeeController.ts b/src/controllers/ProfileAddressEmployeeController.ts index 04ede998..b7ac24d0 100644 --- a/src/controllers/ProfileAddressEmployeeController.ts +++ b/src/controllers/ProfileAddressEmployeeController.ts @@ -99,12 +99,12 @@ export class ProfileAddressEmployeeController extends Controller { */ @Get("history/user") public async getProfileAddressHistoryUser(@Request() request: RequestWithUser) { - const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); - if (!profile) { - throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); - } + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } const record = await this.profileAddressHistoryRepo.find({ - where: { profileEmployeeId: profile.id}, + where: { profileEmployeeId: profile.id }, relations: { registrationProvince: true, registrationDistrict: true, @@ -183,7 +183,7 @@ export class ProfileAddressEmployeeController extends Controller { @Request() req: RequestWithUser, @Path() profileId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.profileEmployeeRepo.findOneBy({ id: profileId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); diff --git a/src/controllers/ProfileAddressEmployeeTempController.ts b/src/controllers/ProfileAddressEmployeeTempController.ts new file mode 100644 index 00000000..76a24246 --- /dev/null +++ b/src/controllers/ProfileAddressEmployeeTempController.ts @@ -0,0 +1,206 @@ +import { + Controller, + Post, + Put, + Delete, + Route, + Security, + Tags, + Body, + Path, + Request, + SuccessResponse, + Response, + Get, + Query, + Patch, + Example, +} from "tsoa"; + +import HttpSuccess from "../interfaces/http-success"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import { RequestWithUser } from "../middlewares/user"; +import { Profile, ProfileAddressHistory, UpdateProfileAddress } from "../entities/Profile"; +import { AppDataSource } from "../database/data-source"; +import { Province } from "../entities/Province"; +import { District } from "../entities/District"; +import { SubDistrict } from "../entities/SubDistrict"; +import { ProfileEmployee, UpdateProfileAddressEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/address") +@Tags("ProfileAddressEmployee") +@Security("bearerAuth") +export class ProfileAddressEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private profileAddressHistoryRepo = AppDataSource.getRepository(ProfileAddressHistory); + + @Get("user") + public async detailProfileAddressUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileAddress = await this.profileEmployeeRepo.findOne({ + where: { id: profile.id }, + select: [ + "id", + "registrationAddress", + "registrationProvinceId", + "registrationDistrictId", + "registrationSubDistrictId", + "registrationZipCode", + "currentAddress", + "currentProvinceId", + "currentDistrictId", + "currentSubDistrictId", + "currentZipCode", + ], + }); + if (!getProfileAddress) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAddress); + } + + /** + * + * @summary ข้อมูลที่อยู่ + * + */ + @Get("{profileEmployeeId}") + public async detailProfileAddress(@Path() profileEmployeeId: string) { + const getProfileAddress = await this.profileEmployeeRepo.findOne({ + where: { id: profileEmployeeId }, + select: [ + "id", + "registrationAddress", + "registrationProvinceId", + "registrationDistrictId", + "registrationSubDistrictId", + "registrationZipCode", + "currentAddress", + "currentProvinceId", + "currentDistrictId", + "currentSubDistrictId", + "currentZipCode", + ], + }); + if (!getProfileAddress) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAddress); + } + + /** + * + * @summary ประวัติแก้ไขที่อยู่ by keycloak + * + */ + @Get("history/user") + public async getProfileAddressHistoryUser(@Request() request: RequestWithUser) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const record = await this.profileAddressHistoryRepo.find({ + where: { profileEmployeeId: profile.id }, + relations: { + registrationProvince: true, + registrationDistrict: true, + registrationSubDistrict: true, + currentProvince: true, + currentDistrict: true, + currentSubDistrict: true, + }, + select: [ + "registrationAddress", + "registrationProvinceId", + "registrationDistrictId", + "registrationSubDistrictId", + "registrationZipCode", + "currentAddress", + "currentProvinceId", + "currentDistrictId", + "currentSubDistrictId", + "currentZipCode", + "lastUpdateFullName", + "lastUpdatedAt", + ], + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + /** + * + * @summary ประวัติแก้ไขที่อยู่ + * + */ + @Get("history/{profileId}") + public async getProfileAddressHistory(@Path() profileId: string) { + const record = await this.profileAddressHistoryRepo.find({ + where: { profileEmployeeId: profileId }, + relations: { + registrationProvince: true, + registrationDistrict: true, + registrationSubDistrict: true, + currentProvince: true, + currentDistrict: true, + currentSubDistrict: true, + }, + select: [ + "registrationAddress", + "registrationProvinceId", + "registrationDistrictId", + "registrationSubDistrictId", + "registrationZipCode", + "currentAddress", + "currentProvinceId", + "currentDistrictId", + "currentSubDistrictId", + "currentZipCode", + "lastUpdateFullName", + "lastUpdatedAt", + ], + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + /** + * + * @summary แก้ไขที่อยู่ + * + */ + @Patch("{profileId}") + public async editProfileAddress( + @Body() requestBody: UpdateProfileAddressEmployee, + @Request() req: RequestWithUser, + @Path() profileId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.profileEmployeeRepo.findOneBy({ id: profileId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileAddressHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, requestBody); + + history.profileEmployeeId = profileId; + history.lastUpdateFullName = req.user.name; + record.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.profileEmployeeRepo.save(record), + this.profileAddressHistoryRepo.save(history), + ]); + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileAssessmentsEmployeeController.ts b/src/controllers/ProfileAssessmentsEmployeeController.ts index 3329c6c4..8642aa31 100644 --- a/src/controllers/ProfileAssessmentsEmployeeController.ts +++ b/src/controllers/ProfileAssessmentsEmployeeController.ts @@ -148,7 +148,7 @@ export class ProfileAssessmentsEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeAssessment, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -178,7 +178,7 @@ export class ProfileAssessmentsEmployeeController extends Controller { @Request() req: RequestWithUser, @Path() assessmentId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.profileAssessmentsRepository.findOneBy({ id: assessmentId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -199,8 +199,11 @@ export class ProfileAssessmentsEmployeeController extends Controller { } @Delete("{assessmentId}") - public async deleteProfileAssessment(@Path() assessmentId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + public async deleteProfileAssessment( + @Path() assessmentId: string, + @Request() req: RequestWithUser, + ) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.profileAssessmentsHistoryRepository.delete({ profileAssessmentId: assessmentId, }); diff --git a/src/controllers/ProfileAssessmentsEmployeeTempController.ts b/src/controllers/ProfileAssessmentsEmployeeTempController.ts new file mode 100644 index 00000000..9d68f241 --- /dev/null +++ b/src/controllers/ProfileAssessmentsEmployeeTempController.ts @@ -0,0 +1,218 @@ +import { + Controller, + Post, + Put, + Delete, + Route, + Security, + Tags, + Body, + Path, + Request, + SuccessResponse, + Response, + Get, + Query, + Patch, + Example, +} from "tsoa"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import HttpSuccess from "../interfaces/http-success"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileEmployeeAssessment, + ProfileAssessment, + UpdateProfileAssessment, +} from "../entities/ProfileAssessment"; +import { ProfileAssessmentHistory } from "../entities/ProfileAssessmentHistory"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { RequestWithUser } from "../middlewares/user"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/assessments") +@Tags("ProfileEmployeeAssessments") +@Security("bearerAuth") +export class ProfileAssessmentsEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private profileAssessmentsRepository = AppDataSource.getRepository(ProfileAssessment); + private profileAssessmentsHistoryRepository = + AppDataSource.getRepository(ProfileAssessmentHistory); + + @Get("user") + public async detailProfileAssessmentsUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileAssessments = await this.profileAssessmentsRepository.find({ + where: { profileEmployeeId: profile.id }, + }); + if (!getProfileAssessments) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAssessments); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "f723bf42-a61c-4af4-ba8b-0e4ad0a89a80", + createdAt: "2024-03-12T20:56:45.986Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T20:56:45.986Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "test bar", + lastUpdateFullName: "test bar", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + name: "สาวิตรี ศรีสมัย", + date: "2024-03-13T03:55:42.000Z", + point1: 0, + point1Total: 0, + point2: 0, + point2Total: 0, + pointSum: 0, + pointSumTotal: 0, + }, + ], + }) + public async detailProfileAssessments(@Path() profileEmployeeId: string) { + const getProfileAssessments = await this.profileAssessmentsRepository.findBy({ + profileEmployeeId, + }); + if (!getProfileAssessments) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileAssessments); + } + + @Get("history/{assessmentId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "47b3e370-be05-4469-a34f-e4a04747f54e", + createdAt: "2024-03-12T20:59:39.774Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T20:59:39.774Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "test bar", + name: "สาวิตรี ศรีสมัย", + date: "2024-03-13T03:55:42.000Z", + point1: 0, + point1Total: 0, + point2: 100, + point2Total: 100, + pointSum: 100, + pointSumTotal: 100, + profileAssessmentId: "f723bf42-a61c-4af4-ba8b-0e4ad0a89a80", + }, + { + id: "ecff89b1-9bef-49a9-83f5-8be3cecb8ca7", + createdAt: "2024-03-12T20:58:19.450Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T20:58:19.450Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "test bar", + name: "สาวิตรี ศรีสมัย", + date: "2024-03-13T03:55:42.000Z", + point1: 50, + point1Total: 50, + point2: 100, + point2Total: 100, + pointSum: 150, + pointSumTotal: 150, + profileAssessmentId: "f723bf42-a61c-4af4-ba8b-0e4ad0a89a80", + }, + ], + }) + public async getProfileAssessmentsHistory(@Path() assessmentId: string) { + const record = await this.profileAssessmentsHistoryRepository.findBy({ + profileAssessmentId: assessmentId, + }); + + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(record); + } + + @Post() + public async profileAssessment( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeAssessment, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileAssessment(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + Object.assign(data, { ...body, ...meta }); + + await this.profileAssessmentsRepository.save(data); + + return new HttpSuccess(); + } + + @Patch("{assessmentId}") + public async editProfileAssessment( + @Body() requestBody: UpdateProfileAssessment, + @Request() req: RequestWithUser, + @Path() assessmentId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.profileAssessmentsRepository.findOneBy({ id: assessmentId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileAssessmentHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, requestBody); + + history.profileAssessmentId = assessmentId; + history.lastUpdateFullName = req.user.name; + record.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.profileAssessmentsRepository.save(record), + this.profileAssessmentsHistoryRepository.save(history), + ]); + return new HttpSuccess(); + } + + @Delete("{assessmentId}") + public async deleteProfileAssessment( + @Path() assessmentId: string, + @Request() req: RequestWithUser, + ) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.profileAssessmentsHistoryRepository.delete({ + profileAssessmentId: assessmentId, + }); + + const result = await this.profileAssessmentsRepository.delete({ id: assessmentId }); + + if (result.affected == undefined || result.affected <= 0) + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileAvatarEmployeeController.ts b/src/controllers/ProfileAvatarEmployeeController.ts index a13a212a..587ff49b 100644 --- a/src/controllers/ProfileAvatarEmployeeController.ts +++ b/src/controllers/ProfileAvatarEmployeeController.ts @@ -54,7 +54,7 @@ export class ProfileAvatarEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeAvatar, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); const profile = await this.profileRepository.findOne({ where: { id: body.profileEmployeeId }, }); @@ -106,7 +106,7 @@ export class ProfileAvatarEmployeeController extends Controller { @Delete("{avatarId}") public async deleteAvatarEmployee(@Path() avatarId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); const result = await this.avatarRepository.delete({ id: avatarId }); if (result.affected == undefined || result.affected <= 0) { diff --git a/src/controllers/ProfileAvatarEmployeeTempController.ts b/src/controllers/ProfileAvatarEmployeeTempController.ts new file mode 100644 index 00000000..d6d7940c --- /dev/null +++ b/src/controllers/ProfileAvatarEmployeeTempController.ts @@ -0,0 +1,118 @@ +import { Body, Controller, Delete, Get, Path, Post, Request, Route, Security, Tags } from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { CreateProfileEmployeeAvatar, ProfileAvatar } from "../entities/ProfileAvatar"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/avatar") +@Tags("ProfileAvatar") +@Security("bearerAuth") +export class ProfileAvatarEmployeeController extends Controller { + private profileRepository = AppDataSource.getRepository(ProfileEmployee); + private avatarRepository = AppDataSource.getRepository(ProfileAvatar); + + @Get("{profileEmployeeId}") + public async getAvatarEmployee(@Path() profileEmployeeId: string) { + const lists = await this.avatarRepository.find({ + where: { profileEmployeeId }, + }); + return new HttpSuccess(lists); + } + + @Get("select/{profileEmployeeId}/{id}") + public async selectAvatarEmployee(@Path() profileEmployeeId: string, @Path() id: string) { + const result = await this.avatarRepository.findOneBy({ id: id }); + if (!result) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + const profile = await this.profileRepository.findOne({ + where: { id: profileEmployeeId }, + relations: ["profileAvatars"], + }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + await Promise.all( + profile.profileAvatars.map(async (item: any) => { + item.isActive = false; + await this.avatarRepository.save(item); + }), + ); + result.isActive = true; + profile.avatar = result.avatar; + profile.avatarName = result.avatarName; + await this.avatarRepository.save(result); + await this.profileRepository.save(profile); + return new HttpSuccess(); + } + + @Post() + public async newAvatarEmployee( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeAvatar, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + const profile = await this.profileRepository.findOne({ + where: { id: body.profileEmployeeId }, + }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileAvatar(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + const _profile = await this.profileRepository.findOne({ + where: { id: body.profileEmployeeId }, + relations: ["profileAvatars"], + }); + + if (!_profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + await Promise.all( + _profile.profileAvatars.map(async (item: any) => { + item.isActive = false; + await this.avatarRepository.save(item); + }), + ); + + await this.avatarRepository.save(data); + let avatar = `ทะเบียนประวัติ/โปรไฟล์/${profile.id}`; + let fileName = `profile-${data.id}`; + + data.isActive = true; + data.avatar = avatar; + data.avatarName = fileName; + await this.avatarRepository.save(data); + profile.avatar = avatar; + profile.avatarName = fileName; + await this.profileRepository.save(profile); + + return new HttpSuccess({ avatar: avatar, avatarName: fileName }); + } + + @Delete("{avatarId}") + public async deleteAvatarEmployee(@Path() avatarId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + const result = await this.avatarRepository.delete({ id: avatarId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileCertificateEmployeeController.ts b/src/controllers/ProfileCertificateEmployeeController.ts index 2a4fb61a..f7ffa8e7 100644 --- a/src/controllers/ProfileCertificateEmployeeController.ts +++ b/src/controllers/ProfileCertificateEmployeeController.ts @@ -121,7 +121,7 @@ export class ProfileCertificateEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeCertificate, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -154,7 +154,7 @@ export class ProfileCertificateEmployeeController extends Controller { @Body() body: UpdateProfileCertificate, @Path() certificateId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.certificateRepo.findOneBy({ id: certificateId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -177,7 +177,7 @@ export class ProfileCertificateEmployeeController extends Controller { @Delete("{certificateId}") public async deleteCertificate(@Path() certificateId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.certificateHistoryRepo.delete({ profileCertificateId: certificateId, }); diff --git a/src/controllers/ProfileCertificateEmployeeTempController.ts b/src/controllers/ProfileCertificateEmployeeTempController.ts new file mode 100644 index 00000000..2a07d7b9 --- /dev/null +++ b/src/controllers/ProfileCertificateEmployeeTempController.ts @@ -0,0 +1,195 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileEmployeeCertificate, + ProfileCertificate, + UpdateProfileCertificate, +} from "../entities/ProfileCertificate"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileCertificateHistory } from "../entities/ProfileCertificateHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/certificate") +@Tags("ProfileEmployeeCertificate") +@Security("bearerAuth") +export class ProfileCertificateEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private certificateRepo = AppDataSource.getRepository(ProfileCertificate); + private certificateHistoryRepo = AppDataSource.getRepository(ProfileCertificateHistory); + + @Get("user") + public async getCertificateUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const record = await this.certificateRepo.find({ + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(record); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "e1ef9c3d-079a-40d8-8332-664c3e9a5a70", + createdAt: "2024-03-12T03:02:27.532Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T03:02:27.532Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + expireDate: "2024-03-12T10:01:48.000Z", + issueDate: "2024-03-12T10:01:48.000Z", + certificateNo: "string", + certificateType: "string", + issuer: "string", + }, + ], + }) + public async getCertificate(@Path() profileEmployeeId: string) { + const record = await this.certificateRepo.findBy({ profileEmployeeId }); + return new HttpSuccess(record); + } + + @Get("history/{certificateId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "c0ecf986-b290-44ca-b45e-f4448cdd34dd", + createdAt: "2024-03-12T03:03:30.169Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T03:03:30.169Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + expireDate: "2024-03-12T10:03:05.000Z", + issueDate: "2024-03-12T10:03:05.000Z", + certificateNo: "no", + certificateType: "type", + issuer: "issuer", + profileCertificateId: "e1ef9c3d-079a-40d8-8332-664c3e9a5a70", + }, + { + id: "dc4c2800-5fc5-4ec3-b19a-c4a27beac35f", + createdAt: "2024-03-12T03:02:27.583Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T03:02:27.583Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + expireDate: "2024-03-12T10:01:48.000Z", + issueDate: "2024-03-12T10:01:48.000Z", + certificateNo: "string", + certificateType: "string", + issuer: "string", + profileCertificateId: "e1ef9c3d-079a-40d8-8332-664c3e9a5a70", + }, + ], + }) + public async certificateHistory(@Path() certificateId: string) { + const record = await this.certificateHistoryRepo.findBy({ + profileCertificateId: certificateId, + }); + return new HttpSuccess(record); + } + + @Post() + public async newCertificate( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeCertificate, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileCertificate(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.certificateRepo.save(data); + + return new HttpSuccess(); + } + + @Patch("{certificateId}") + public async editCertificate( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileCertificate, + @Path() certificateId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.certificateRepo.findOneBy({ id: certificateId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileCertificateHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileCertificateId = certificateId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.certificateRepo.save(record), + this.certificateHistoryRepo.save(history), + ]); + + return new HttpSuccess(); + } + + @Delete("{certificateId}") + public async deleteCertificate(@Path() certificateId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.certificateHistoryRepo.delete({ + profileCertificateId: certificateId, + }); + + const certificateResult = await this.certificateRepo.delete({ + id: certificateId, + }); + + if (certificateResult.affected == undefined || certificateResult.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileChangeNameEmployeeController.ts b/src/controllers/ProfileChangeNameEmployeeController.ts index 5106cab5..563f6c72 100644 --- a/src/controllers/ProfileChangeNameEmployeeController.ts +++ b/src/controllers/ProfileChangeNameEmployeeController.ts @@ -119,7 +119,7 @@ export class ProfileChangeNameEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileChangeNameEmployee, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -157,7 +157,7 @@ export class ProfileChangeNameEmployeeController extends Controller { @Body() body: UpdateProfileChangeName, @Path() changeNameId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.changeNameRepository.findOneBy({ id: changeNameId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -199,7 +199,7 @@ export class ProfileChangeNameEmployeeController extends Controller { @Delete("{changeNameId}") public async deleteTraning(@Path() changeNameId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.changeNameHistoryRepository.delete({ profileChangeNameId: changeNameId, }); diff --git a/src/controllers/ProfileChangeNameEmployeeTempController.ts b/src/controllers/ProfileChangeNameEmployeeTempController.ts new file mode 100644 index 00000000..60e08c19 --- /dev/null +++ b/src/controllers/ProfileChangeNameEmployeeTempController.ts @@ -0,0 +1,215 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileChangeNameHistory } from "../entities/ProfileChangeNameHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { Profile } from "../entities/Profile"; +import { + CreateProfileChangeName, + CreateProfileChangeNameEmployee, + ProfileChangeName, + UpdateProfileChangeName, +} from "../entities/ProfileChangeName"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/changeName") +@Tags("ProfileChangeNameEmployee") +@Security("bearerAuth") +export class ProfileChangeNameEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private changeNameRepository = AppDataSource.getRepository(ProfileChangeName); + private changeNameHistoryRepository = AppDataSource.getRepository(ProfileChangeNameHistory); + + @Get("user") + public async getChangeNameUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const lists = await this.changeNameRepository.find({ + where: { profileEmployeeId: profile.id }, + select: ["id", "prefix", "firstName", "lastName", "status"], + order: { createdAt: "ASC" }, + }); + return new HttpSuccess(lists); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "debfa8a7-83fb-4801-a940-8ae74e7638d3", + prefix: "string", + firstName: "string", + lastName: "string", + status: "string", + }, + ], + }) + public async getChangeName(@Path() profileEmployeeId: string) { + const lists = await this.changeNameRepository.find({ + where: { profileEmployeeId: profileEmployeeId }, + select: ["id", "prefix", "firstName", "lastName", "status"], + order: { createdAt: "ASC" }, + }); + return new HttpSuccess(lists); + } + + @Get("history/{changeNameId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "debfa8a7-83fb-4801-a940-8ae74e7638d3", + prefix: "string", + firstName: "string", + lastName: "string", + status: "string", + createdFullName: "string", + createdAt: "string", + }, + { + id: "debfa8a7-83fb-4801-a940-8ae74e7638d3", + prefix: "string", + firstName: "string", + lastName: "string", + status: "string", + createdFullName: "string", + createdAt: "string", + }, + ], + }) + public async changeNameHistory(@Path() changeNameId: string) { + const record = await this.changeNameHistoryRepository.find({ + where: { profileChangeNameId: changeNameId }, + select: [ + "id", + "prefix", + "firstName", + "lastName", + "status", + "lastUpdateFullName", + "lastUpdatedAt", + ], + order: { createdAt: "DESC" }, + }); + return new HttpSuccess(record); + } + + @Post() + public async newChangeName( + @Request() req: RequestWithUser, + @Body() body: CreateProfileChangeNameEmployee, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileChangeName(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.changeNameRepository.save(data); + + profile.firstName = body.firstName ?? profile.firstName; + profile.lastName = body.lastName ?? profile.lastName; + profile.prefix = body.prefix ?? profile.prefix; + await this.profileEmployeeRepo.save(profile); + + return new HttpSuccess(data.id); + } + + @Patch("{changeNameId}") + public async editChangeName( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileChangeName, + @Path() changeNameId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.changeNameRepository.findOneBy({ id: changeNameId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileChangeNameHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileChangeNameId = changeNameId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.changeNameRepository.save(record), + this.changeNameHistoryRepository.save(history), + ]); + + const chkLastRecord = await this.changeNameRepository.findOne({ + where: { + profileEmployeeId: record.profileEmployeeId, + }, + order: { + createdAt: "DESC", + }, + }); + if (!chkLastRecord) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const profile = await this.profileEmployeeRepo.findOneBy({ id: record.profileEmployeeId }); + + if (profile && chkLastRecord.id === record.id) { + profile.firstName = body.firstName ?? profile.firstName; + profile.lastName = body.lastName ?? profile.lastName; + profile.prefix = body.prefix ?? profile.prefix; + await this.profileEmployeeRepo.save(profile); + } + + return new HttpSuccess(); + } + + @Delete("{changeNameId}") + public async deleteTraning(@Path() changeNameId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.changeNameHistoryRepository.delete({ + profileChangeNameId: changeNameId, + }); + + const result = await this.changeNameRepository.delete({ id: changeNameId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileChildrenEmployeeController.ts b/src/controllers/ProfileChildrenEmployeeController.ts index 24b08d68..efee398d 100644 --- a/src/controllers/ProfileChildrenEmployeeController.ts +++ b/src/controllers/ProfileChildrenEmployeeController.ts @@ -70,7 +70,7 @@ export class ProfileChildrenEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileChildrenEmployee, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); const profile = await this.profileRepository.findOneBy({ id: body.profileEmployeeId }); if (!profile) { @@ -89,7 +89,7 @@ export class ProfileChildrenEmployeeController extends Controller { Object.assign(data, { ...body, ...meta }); data.childrenCitizenId = Extension.CheckCitizen(String(data.childrenCitizenId)); await this.childrenRepository.save(data); - if(data){ + if (data) { const history: ProfileChildrenHistory = Object.assign(new ProfileChildrenHistory(), { profileChildrenId: data.id, childrenCareer: data.childrenCareer, @@ -115,7 +115,7 @@ export class ProfileChildrenEmployeeController extends Controller { @Body() body: UpdateProfileChildren, @Path() childrenId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.childrenRepository.findOneBy({ id: childrenId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -129,11 +129,10 @@ export class ProfileChildrenEmployeeController extends Controller { history.childrenCareer = record.childrenCareer; history.childrenFirstName = record.childrenFirstName; history.childrenLastName = record.childrenLastName; - history.childrenPrefix = record.childrenPrefix; + history.childrenPrefix = record.childrenPrefix; history.childrenLive = record.childrenLive; history.childrenCitizenId = record.childrenCitizenId; - history.lastUpdateUserId = req.user.sub, - history.lastUpdateFullName = req.user.name; + (history.lastUpdateUserId = req.user.sub), (history.lastUpdateFullName = req.user.name); await Promise.all([ this.childrenRepository.save(record), @@ -145,7 +144,7 @@ export class ProfileChildrenEmployeeController extends Controller { @Delete("{childrenId}") public async deleteTraning(@Path() childrenId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.childrenHistoryRepository.delete({ profileChildrenId: childrenId, }); diff --git a/src/controllers/ProfileChildrenEmployeeTempController.ts b/src/controllers/ProfileChildrenEmployeeTempController.ts new file mode 100644 index 00000000..8d5470f8 --- /dev/null +++ b/src/controllers/ProfileChildrenEmployeeTempController.ts @@ -0,0 +1,160 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileChildrenHistory } from "../entities/ProfileChildrenHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { Profile } from "../entities/Profile"; +import { + CreateProfileChildren, + CreateProfileChildrenEmployee, + ProfileChildren, + UpdateProfileChildren, +} from "../entities/ProfileChildren"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import Extension from "../interfaces/extension"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/family/children") +@Tags("ProfileChildren") +@Security("bearerAuth") +export class ProfileChildrenEmployeeController extends Controller { + private profileRepository = AppDataSource.getRepository(ProfileEmployee); + private childrenRepository = AppDataSource.getRepository(ProfileChildren); + private childrenHistoryRepository = AppDataSource.getRepository(ProfileChildrenHistory); + + @Get("user") + public async getChildrenUser(@Request() request: { user: Record }) { + const profile = await this.profileRepository.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const lists = await this.childrenRepository.find({ + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(lists); + } + + @Get("{profileEmployeeId}") + public async getChildren(@Path() profileEmployeeId: string) { + const lists = await this.childrenRepository.find({ + where: { profileEmployeeId: profileEmployeeId }, + }); + return new HttpSuccess(lists); + } + + @Get("history/{childrenId}") + public async childrenHistory(@Path() childrenId: string) { + const record = await this.childrenHistoryRepository.find({ + where: { profileChildrenId: childrenId }, + order: { createdAt: "DESC" }, + }); + return new HttpSuccess(record); + } + + @Post() + public async newChildren( + @Request() req: RequestWithUser, + @Body() body: CreateProfileChildrenEmployee, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + const profile = await this.profileRepository.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileChildren(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + data.childrenCitizenId = Extension.CheckCitizen(String(data.childrenCitizenId)); + await this.childrenRepository.save(data); + if (data) { + const history: ProfileChildrenHistory = Object.assign(new ProfileChildrenHistory(), { + profileChildrenId: data.id, + childrenCareer: data.childrenCareer, + childrenFirstName: data.childrenFirstName, + childrenLastName: data.childrenLastName, + childrenPrefix: data.childrenPrefix, + childrenLive: data.childrenLive, + childrenCitizenId: data.childrenCitizenId, + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }); + await this.childrenHistoryRepository.save(history); + } + + return new HttpSuccess(); + } + + @Patch("{childrenId}") + public async editChildren( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileChildren, + @Path() childrenId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.childrenRepository.findOneBy({ id: childrenId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileChildrenHistory(); + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + record.lastUpdateUserId = req.user.sub; + record.lastUpdateFullName = req.user.name; + record.childrenCitizenId = Extension.CheckCitizen(String(record.childrenCitizenId)); + history.profileChildrenId = record.id; + history.childrenCareer = record.childrenCareer; + history.childrenFirstName = record.childrenFirstName; + history.childrenLastName = record.childrenLastName; + history.childrenPrefix = record.childrenPrefix; + history.childrenLive = record.childrenLive; + history.childrenCitizenId = record.childrenCitizenId; + (history.lastUpdateUserId = req.user.sub), (history.lastUpdateFullName = req.user.name); + + await Promise.all([ + this.childrenRepository.save(record), + this.childrenHistoryRepository.save(history), + ]); + + return new HttpSuccess(); + } + + @Delete("{childrenId}") + public async deleteTraning(@Path() childrenId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.childrenHistoryRepository.delete({ + profileChildrenId: childrenId, + }); + + const result = await this.childrenRepository.delete({ id: childrenId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileDisciplineEmployeeController.ts b/src/controllers/ProfileDisciplineEmployeeController.ts index daff6982..51486566 100644 --- a/src/controllers/ProfileDisciplineEmployeeController.ts +++ b/src/controllers/ProfileDisciplineEmployeeController.ts @@ -115,7 +115,7 @@ export class ProfileDisciplineEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeDiscipline, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); } @@ -148,7 +148,7 @@ export class ProfileDisciplineEmployeeController extends Controller { @Body() body: UpdateProfileDiscipline, @Path() disciplineId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.disciplineRepository.findOneBy({ id: disciplineId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -171,7 +171,7 @@ export class ProfileDisciplineEmployeeController extends Controller { @Delete("{disciplineId}") public async deleteDiscipline(@Path() disciplineId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.disciplineHistoryRepository.delete({ profileDisciplineId: disciplineId, }); diff --git a/src/controllers/ProfileDisciplineEmployeeTempController.ts b/src/controllers/ProfileDisciplineEmployeeTempController.ts new file mode 100644 index 00000000..d45acf4d --- /dev/null +++ b/src/controllers/ProfileDisciplineEmployeeTempController.ts @@ -0,0 +1,187 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileDisciplineHistory } from "../entities/ProfileDisciplineHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { + CreateProfileEmployeeDiscipline, + ProfileDiscipline, + UpdateProfileDiscipline, +} from "../entities/ProfileDiscipline"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/discipline") +@Tags("ProfileDisciplineEmployee") +@Security("bearerAuth") +export class ProfileDisciplineEmployeeController extends Controller { + private profileRepository = AppDataSource.getRepository(ProfileEmployee); + private disciplineRepository = AppDataSource.getRepository(ProfileDiscipline); + private disciplineHistoryRepository = AppDataSource.getRepository(ProfileDisciplineHistory); + + @Get("user") + public async getDisciplineUser(@Request() request: { user: Record }) { + const profile = await this.profileRepository.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const lists = await this.disciplineRepository.find({ + where: { profileEmployeeId: profile.id }, + select: [ + "id", + "date", + "level", + "detail", + "unStigma", + "refCommandNo", + "refCommandDate", + "lastUpdateFullName", + "lastUpdatedAt", + ], + }); + return new HttpSuccess(lists); + } + + @Get("{profileId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "debfa8a7-83fb-4801-a940-8ae74e7638d3", + date: "2024-03-12T10:09:47.000Z", + level: "string", + detail: "string", + unStigma: "string", + refCommandNo: "string", + refCommandDate: "2024-03-12T10:09:47.000Z", + }, + ], + }) + public async getDiscipline(@Path() profileId: string) { + const lists = await this.disciplineRepository.find({ + where: { profileEmployeeId: profileId }, + select: [ + "id", + "date", + "level", + "detail", + "unStigma", + "refCommandNo", + "refCommandDate", + "lastUpdateFullName", + "lastUpdatedAt", + ], + }); + return new HttpSuccess(lists); + } + + @Get("history/{disciplineId}") + public async disciplineHistory(@Path() disciplineId: string) { + const record = await this.disciplineHistoryRepository.find({ + where: { profileDisciplineId: disciplineId }, + select: [ + "id", + "date", + "level", + "detail", + "unStigma", + "refCommandNo", + "refCommandDate", + "lastUpdateFullName", + "lastUpdatedAt", + ], + order: { createdAt: "DESC" }, + }); + return new HttpSuccess(record); + } + + @Post() + public async newDiscipline( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeDiscipline, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); + } + + const profile = await this.profileRepository.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileDiscipline(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.disciplineRepository.save(data); + + return new HttpSuccess(); + } + + @Patch("{disciplineId}") + public async editDiscipline( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileDiscipline, + @Path() disciplineId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.disciplineRepository.findOneBy({ id: disciplineId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileDisciplineHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileDisciplineId = disciplineId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.disciplineRepository.save(record), + this.disciplineHistoryRepository.save(history), + ]); + + return new HttpSuccess(); + } + + @Delete("{disciplineId}") + public async deleteDiscipline(@Path() disciplineId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.disciplineHistoryRepository.delete({ + profileDisciplineId: disciplineId, + }); + + const result = await this.disciplineRepository.delete({ id: disciplineId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileDutyEmployeeController.ts b/src/controllers/ProfileDutyEmployeeController.ts index 8e6b6a6b..eee9bb48 100644 --- a/src/controllers/ProfileDutyEmployeeController.ts +++ b/src/controllers/ProfileDutyEmployeeController.ts @@ -89,7 +89,7 @@ export class ProfileDutyEmployeeController extends Controller { @Post() public async newDuty(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeDuty) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); } @@ -122,7 +122,7 @@ export class ProfileDutyEmployeeController extends Controller { @Body() body: UpdateProfileDuty, @Path() dutyId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.dutyRepository.findOneBy({ id: dutyId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -142,7 +142,7 @@ export class ProfileDutyEmployeeController extends Controller { @Delete("{dutyId}") public async deleteDuty(@Path() dutyId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.dutyHistoryRepository.delete({ profileDutyId: dutyId, }); diff --git a/src/controllers/ProfileDutyEmployeeTempController.ts b/src/controllers/ProfileDutyEmployeeTempController.ts new file mode 100644 index 00000000..8f09b8f1 --- /dev/null +++ b/src/controllers/ProfileDutyEmployeeTempController.ts @@ -0,0 +1,158 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileDutyHistory } from "../entities/ProfileDutyHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { CreateProfileEmployeeDuty, ProfileDuty, UpdateProfileDuty } from "../entities/ProfileDuty"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/duty") +@Tags("ProfileEmployeeDuty") +@Security("bearerAuth") +export class ProfileDutyEmployeeController extends Controller { + private profileRepository = AppDataSource.getRepository(ProfileEmployee); + private dutyRepository = AppDataSource.getRepository(ProfileDuty); + private dutyHistoryRepository = AppDataSource.getRepository(ProfileDutyHistory); + + @Get("user") + public async getDutyUser(@Request() request: { user: Record }) { + const profile = await this.profileRepository.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const lists = await this.dutyRepository.find({ + where: { profileEmployeeId: profile.id }, + select: [ + "id", + "dateStart", + "dateEnd", + "reference", + "detail", + "refCommandNo", + "refCommandDate", + ], + }); + return new HttpSuccess(lists); + } + + @Get("{profileId}") + public async getDuty(@Path() profileId: string) { + const lists = await this.dutyRepository.find({ + where: { profileEmployeeId: profileId }, + select: [ + "id", + "dateStart", + "dateEnd", + "reference", + "detail", + "refCommandNo", + "refCommandDate", + ], + }); + return new HttpSuccess(lists); + } + + @Get("history/{dutyId}") + public async dutyHistory(@Path() dutyId: string) { + const record = await this.dutyHistoryRepository.find({ + where: { profileDutyId: dutyId }, + select: [ + "id", + "dateStart", + "dateEnd", + "reference", + "detail", + "refCommandNo", + "refCommandDate", + "lastUpdateFullName", + "lastUpdatedAt", + ], + order: { createdAt: "DESC" }, + }); + return new HttpSuccess(record); + } + + @Post() + public async newDuty(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeDuty) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); + } + + const profile = await this.profileRepository.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileDuty(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.dutyRepository.save(data); + + return new HttpSuccess(); + } + + @Patch("{dutyId}") + public async editDuty( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileDuty, + @Path() dutyId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.dutyRepository.findOneBy({ id: dutyId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileDutyHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileDutyId = dutyId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([this.dutyRepository.save(record), this.dutyHistoryRepository.save(history)]); + + return new HttpSuccess(); + } + + @Delete("{dutyId}") + public async deleteDuty(@Path() dutyId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.dutyHistoryRepository.delete({ + profileDutyId: dutyId, + }); + + const result = await this.dutyRepository.delete({ id: dutyId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileEducationsEmployeeController.ts b/src/controllers/ProfileEducationsEmployeeController.ts index f2e42933..be789a8f 100644 --- a/src/controllers/ProfileEducationsEmployeeController.ts +++ b/src/controllers/ProfileEducationsEmployeeController.ts @@ -53,7 +53,7 @@ export class ProfileEducationsEmployeeController extends Controller { } return new HttpSuccess(getProfileEducation); } - + @Get("{profileEmployeeId}") @Example({ status: 200, @@ -93,8 +93,8 @@ export class ProfileEducationsEmployeeController extends Controller { }) public async detailProfileEducation(@Path() profileEmployeeId: string) { const getProfileEducation = await this.profileEducationRepo.find({ - where: { profileEmployeeId: profileEmployeeId} - }); + where: { profileEmployeeId: profileEmployeeId }, + }); if (!getProfileEducation) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); } @@ -183,7 +183,7 @@ export class ProfileEducationsEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEducationEmployee, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -214,7 +214,7 @@ export class ProfileEducationsEmployeeController extends Controller { @Request() req: RequestWithUser, @Path() educationId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.profileEducationRepo.findOneBy({ id: educationId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -236,8 +236,11 @@ export class ProfileEducationsEmployeeController extends Controller { } @Delete("{educationId}") - public async deleteProfileEducation(@Path() educationId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + public async deleteProfileEducation( + @Path() educationId: string, + @Request() req: RequestWithUser, + ) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.profileEducationHistoryRepo.delete({ profileEducationId: educationId, }); diff --git a/src/controllers/ProfileEducationsEmployeeTempController.ts b/src/controllers/ProfileEducationsEmployeeTempController.ts new file mode 100644 index 00000000..33da79d6 --- /dev/null +++ b/src/controllers/ProfileEducationsEmployeeTempController.ts @@ -0,0 +1,256 @@ +import { + Controller, + Post, + Put, + Delete, + Route, + Security, + Tags, + Body, + Path, + Request, + SuccessResponse, + Response, + Get, + Query, + Patch, + Example, +} from "tsoa"; +import HttpSuccess from "../interfaces/http-success"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import { + ProfileEducation, + CreateProfileEducation, + UpdateProfileEducation, + CreateProfileEducationEmployee, +} from "../entities/ProfileEducation"; +import { RequestWithUser } from "../middlewares/user"; +import { Profile } from "../entities/Profile"; +import { ProfileEducationHistory } from "../entities/ProfileEducationHistory"; +import { AppDataSource } from "../database/data-source"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/educations") +@Tags("ProfileEducationsEmployee") +@Security("bearerAuth") +export class ProfileEducationsEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private profileEducationRepo = AppDataSource.getRepository(ProfileEducation); + private profileEducationHistoryRepo = AppDataSource.getRepository(ProfileEducationHistory); + + @Get("user") + public async detailProfileEducationUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const getProfileEducation = await this.profileEducationRepo.find({ + where: { profileEmployeeId: profile.id }, + }); + if (!getProfileEducation) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileEducation); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "f6c693b4-1a9b-4fbe-95c5-ed4da50d35b6", + createdAt: "2024-03-12T20:26:42.621Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T20:33:09.000Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "test bar", + lastUpdateFullName: "test bar", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + isActive: true, + country: "string", + degree: "ปวส", + duration: "-", + durationYear: 0, + field: "ชางเทคนิค ชั้นสูง", + finishDate: "2024-03-13T03:23:31.000Z", + fundName: "-", + gpa: "3.64", + institute: "เทคโนเชียงใหม่", + other: "string", + startDate: "2024-03-13T03:23:31.000Z", + endDate: "2024-03-13T03:23:31.000Z", + educationLevel: "ปวส", + educationLevelId: "string", + positionPath: "string", + positionPathId: "string", + note: "string", + isDate: true, + isEducation: true, + }, + ], + }) + public async detailProfileEducation(@Path() profileEmployeeId: string) { + const getProfileEducation = await this.profileEducationRepo.find({ + where: { profileEmployeeId: profileEmployeeId }, + }); + if (!getProfileEducation) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(getProfileEducation); + } + + @Get("history/{educationId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "294aa117-6ce7-4c23-b5bd-fe1f12932c4a", + createdAt: "2024-03-12T20:29:45.251Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T20:29:45.251Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "test bar", + isActive: true, + country: "string", + degree: "ปวส", + duration: "-", + durationYear: 0, + field: "ชางเทคนิค", + finishDate: "2024-03-13T03:23:31.000Z", + fundName: "-", + gpa: "3.64", + institute: "เทคโนเชียงใหม่", + other: "string", + startDate: "2024-03-13T03:23:31.000Z", + endDate: "2024-03-13T03:23:31.000Z", + educationLevel: "ปวส", + educationLevelId: "string", + positionPath: "string", + positionPathId: "string", + note: "string", + isDate: true, + isEducation: true, + profileEducationId: "f6c693b4-1a9b-4fbe-95c5-ed4da50d35b6", + }, + { + id: "2f00bd59-be3e-46d8-92a2-c4700baabf12", + createdAt: "2024-03-12T20:33:09.128Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T20:33:09.128Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "test bar", + isActive: true, + country: "string", + degree: "ปวส", + duration: "-", + durationYear: 0, + field: "ชางเทคนิค ชั้นสูง", + finishDate: "2024-03-13T03:23:31.000Z", + fundName: "-", + gpa: "3.64", + institute: "เทคโนเชียงใหม่", + other: "string", + startDate: "2024-03-13T03:23:31.000Z", + endDate: "2024-03-13T03:23:31.000Z", + educationLevel: "ปวส", + educationLevelId: "string", + positionPath: "string", + positionPathId: "string", + note: "string", + isDate: true, + isEducation: true, + profileEducationId: "f6c693b4-1a9b-4fbe-95c5-ed4da50d35b6", + }, + ], + }) + public async getProfileEducationHistory(@Path() educationId: string) { + const record = await this.profileEducationHistoryRepo.findBy({ + profileEducationId: educationId, + }); + if (!record) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(record); + } + + @Post() + public async newProfileEducation( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEducationEmployee, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileEducation(); + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.profileEducationRepo.save(data); + + return new HttpSuccess(); + } + + @Patch("{educationId}") + public async editProfileEducation( + @Body() requestBody: UpdateProfileEducation, + @Request() req: RequestWithUser, + @Path() educationId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.profileEducationRepo.findOneBy({ id: educationId }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileEducationHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, requestBody); + + history.profileEducationId = educationId; + history.lastUpdateFullName = req.user.name; + record.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.profileEducationRepo.save(record), + this.profileEducationHistoryRepo.save(history), + ]); + + return new HttpSuccess(); + } + + @Delete("{educationId}") + public async deleteProfileEducation( + @Path() educationId: string, + @Request() req: RequestWithUser, + ) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.profileEducationHistoryRepo.delete({ + profileEducationId: educationId, + }); + + const result = await this.profileEducationRepo.delete({ id: educationId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileEmployeeController.ts b/src/controllers/ProfileEmployeeController.ts index 87214166..50faddd6 100644 --- a/src/controllers/ProfileEmployeeController.ts +++ b/src/controllers/ProfileEmployeeController.ts @@ -576,7 +576,7 @@ export class ProfileEmployeeController extends Controller { */ @Post() async createProfile(@Body() body: CreateProfileEmployee, @Request() request: RequestWithUser) { - await new permission().PermissionCreate(request,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(request, "SYS_REGISTRY_EMP"); if (await this.profileRepo.findOneBy({ citizenId: body.citizenId })) { throw new HttpError( HttpStatus.INTERNAL_SERVER_ERROR, @@ -629,7 +629,7 @@ export class ProfileEmployeeController extends Controller { @Path() id: string, @Body() body: UpdateProfileEmployee, ) { - await new permission().PermissionUpdate(request,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(request, "SYS_REGISTRY_EMP"); const exists = !!body.citizenId && (await this.profileRepo.findOne({ @@ -692,8 +692,8 @@ export class ProfileEmployeeController extends Controller { * @param {string} id Id ทะเบียนประวัติ */ @Delete("{id}") - async deleteProfile(@Path() id: string, @Request() request: RequestWithUser,) { - await new permission().PermissionDelete(request,"SYS_REGISTRY_EMP"); + async deleteProfile(@Path() id: string, @Request() request: RequestWithUser) { + await new permission().PermissionDelete(request, "SYS_REGISTRY_EMP"); const result = await this.profileRepo.findOne({ where: { id: id } }); if (!result) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); diff --git a/src/controllers/ProfileEmployeeTempController.ts b/src/controllers/ProfileEmployeeTempController.ts new file mode 100644 index 00000000..107ce19a --- /dev/null +++ b/src/controllers/ProfileEmployeeTempController.ts @@ -0,0 +1,3487 @@ +import { + Controller, + Post, + Put, + Delete, + Route, + Security, + Tags, + Body, + Path, + Request, + SuccessResponse, + Response, + Get, + Query, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { Brackets, Double, In, IsNull, Like, Not } from "typeorm"; +import { OrgRevision } from "../entities/OrgRevision"; +import { + calculateRetireDate, + calculateRetireLaw, + removeProfileInOrganize, +} from "../interfaces/utils"; +import { EmployeePosMaster } from "../entities/EmployeePosMaster"; +import { + ProfileEmployee, + CreateProfileEmployee, + UpdateProfileEmployee, + ProfileEmployeeHistory, + UpdatePositionTempProfileEmployee, + UpdateInformationProfileEmployee, +} from "../entities/ProfileEmployee"; +import { EmployeePosLevel } from "../entities/EmployeePosLevel"; +import { EmployeePosType } from "../entities/EmployeePosType"; +import { RequestWithUser } from "../middlewares/user"; +import { Province } from "../entities/Province"; +import { District } from "../entities/District"; +import { SubDistrict } from "../entities/SubDistrict"; +import { ProfileCertificate } from "../entities/ProfileCertificate"; +import { ProfileTraining } from "../entities/ProfileTraining"; +import { ProfileDiscipline } from "../entities/ProfileDiscipline"; +import { ProfileEducation } from "../entities/ProfileEducation"; +import { ProfileSalary } from "../entities/ProfileSalary"; +import { ProfileFamilyCouple } from "../entities/ProfileFamilyCouple"; +import { ProfileFamilyMother } from "../entities/ProfileFamilyMother"; +import { ProfileFamilyFather } from "../entities/ProfileFamilyFather"; +import Extension from "../interfaces/extension"; +import { OrgRoot } from "../entities/OrgRoot"; +import { OrgChild1 } from "../entities/OrgChild1"; +import { OrgChild2 } from "../entities/OrgChild2"; +import { OrgChild3 } from "../entities/OrgChild3"; +import { OrgChild4 } from "../entities/OrgChild4"; +import { ProfileEmployeeInformationHistory } from "../entities/ProfileEmployeeInformationHistory"; +import { + ProfileEmployeeEmployment, + CreateEmploymentProfileEmployee, + UpdateEmploymentProfileEmployee, +} from "../entities/ProfileEmployeeEmployment"; +import { ProfileEmployeeEmploymentHistory } from "../entities/ProfileEmployeeEmploymentHistory"; +import CallAPI from "../interfaces/call-api"; +import { EmployeePosition } from "../entities/EmployeePosition"; +import { ProfileInsignia } from "../entities/ProfileInsignia"; +import { ProfileLeave } from "../entities/ProfileLeave"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp") +@Tags("ProfileEmployee") +@Security("bearerAuth") +@Response( + HttpStatus.INTERNAL_SERVER_ERROR, + "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง", +) +@SuccessResponse(HttpStatus.OK, "สำเร็จ") +export class ProfileEmployeeController extends Controller { + private orgRevisionRepo = AppDataSource.getRepository(OrgRevision); + private posMasterRepo = AppDataSource.getRepository(EmployeePosMaster); + private profileRepo = AppDataSource.getRepository(ProfileEmployee); + private profileHistoryRepo = AppDataSource.getRepository(ProfileEmployeeHistory); + private posLevelRepo = AppDataSource.getRepository(EmployeePosLevel); + private posTypeRepo = AppDataSource.getRepository(EmployeePosType); + private positionRepository = AppDataSource.getRepository(EmployeePosition); + private provinceRepository = AppDataSource.getRepository(Province); + private districtRepository = AppDataSource.getRepository(District); + private subDistrict = AppDataSource.getRepository(SubDistrict); + private certificateRepository = AppDataSource.getRepository(ProfileCertificate); + private profileFamilyCoupleRepository = AppDataSource.getRepository(ProfileFamilyCouple); + private profileFamilyMotherRepository = AppDataSource.getRepository(ProfileFamilyMother); + private profileFamilyFatherRepository = AppDataSource.getRepository(ProfileFamilyFather); + private trainingRepository = AppDataSource.getRepository(ProfileTraining); + private disciplineRepository = AppDataSource.getRepository(ProfileDiscipline); + private educationRepository = AppDataSource.getRepository(ProfileEducation); + private salaryRepository = AppDataSource.getRepository(ProfileSalary); + private orgRootRepository = AppDataSource.getRepository(OrgRoot); + private child1Repository = AppDataSource.getRepository(OrgChild1); + private child2Repository = AppDataSource.getRepository(OrgChild2); + private child3Repository = AppDataSource.getRepository(OrgChild3); + private child4Repository = AppDataSource.getRepository(OrgChild4); + private informationHistoryRepository = AppDataSource.getRepository( + ProfileEmployeeInformationHistory, + ); + private employmentRepository = AppDataSource.getRepository(ProfileEmployeeEmployment); + private employmentHistoryRepository = AppDataSource.getRepository( + ProfileEmployeeEmploymentHistory, + ); + private profileEducationRepository = AppDataSource.getRepository(ProfileEducation); + private profileInsigniaRepo = AppDataSource.getRepository(ProfileInsignia); + private profileLeaveRepository = AppDataSource.getRepository(ProfileLeave); + /** + * report ประวัติแบบย่อ ลูกจ้าง + * + * @summary report ประวัติแบบย่อ ลูกจ้าง + * + * @param {string} id Id โปรไฟล์ + */ + @Get("kp7-short/{id}") + async kp7ShortById(@Path() id: string) { + const orgRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + + const profile = await this.profileRepo.findOne({ + relations: [ + "profileSalarys", + "profileEducations", + "current_holders", + "current_holders.orgRoot", + "current_holders.orgChild1", + "current_holders.orgChild2", + "current_holders.orgChild3", + "current_holders.orgChild4", + ], + where: { id: id }, + }); + if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const province = await this.provinceRepository.findOneBy({ + id: profile.registrationProvinceId, + }); + const district = await this.districtRepository.findOneBy({ + id: profile.registrationDistrictId, + }); + const subDistrict = await this.subDistrict.findOneBy({ id: profile.registrationSubDistrictId }); + + const root = + profile.current_holders == null || + profile.current_holders.length == 0 || + profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot; + + const child1 = + profile.current_holders == null || + profile.current_holders.length == 0 || + profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1; + + const child2 = + profile.current_holders == null || + profile.current_holders.length == 0 || + profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2; + + const child3 = + profile.current_holders == null || + profile.current_holders.length == 0 || + profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3; + + const child4 = + profile.current_holders == null || + profile.current_holders.length == 0 || + profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4; + + let _regisAddres = + profile && profile.registrationAddress != null ? profile.registrationAddress : ""; + let _subDistrict = + subDistrict && subDistrict.name != null ? `\r\nตำบล/แขวง ${province?.name}` : ""; + let _district = district && district.name != null ? `\r\nเขต/อำเภอ ${district?.name}` : ""; + let _province = province && province.name != null ? `\r\nจังหวัด ${province?.name}` : ""; + let registrationZipCode = + profile && profile.registrationZipCode != null + ? ` รหัสไปรษณีย์ ${profile.registrationZipCode}` + : ""; + let _root = root == null || root == undefined ? "" : `${root.orgRootName}`; + let _child1 = child1 == null || child1 == undefined ? "" : `${child1.orgChild1Name}/`; + let _child2 = child2 == null || child2 == undefined ? "" : `${child2.orgChild2Name}/`; + let _child3 = child3 == null || child3 == undefined ? "" : `${child3.orgChild3Name}/`; + let _child4 = child4 == null || child4 == undefined ? "" : `${child4.orgChild4Name}/`; + + const mapData = { + Id: profile.id, + CitizenId: profile.citizenId != null ? Extension.ToThaiNumber(profile.citizenId) : "", + Prefix: profile.prefix != null ? profile.prefix : "", + FirstName: profile.firstName != null ? profile.firstName : "", + LastName: profile.lastName != null ? profile.lastName : "", + DateOfBirth: + profile.birthDate != null + ? Extension.ToThaiNumber(Extension.ToThaiFullDate(profile.birthDate)) + : "", + DateRetire: + profile.dateRetire != null + ? Extension.ToThaiNumber(Extension.ToThaiFullDate(profile.dateRetire)) + : "", + RegistrationAddress: `${_regisAddres}${_subDistrict}${_district}${_province}${registrationZipCode}`, + SalaryAmount: + profile.profileSalarys.length > 0 && profile.profileSalarys[0].amount != null + ? Extension.ToThaiNumber(profile.profileSalarys[0].amount.toLocaleString()) + : "", + Education: + profile.profileEducations.length > 0 && + profile.profileEducations[profile.profileEducations.length - 1].institute != null + ? profile.profileEducations[profile.profileEducations.length - 1].institute + : "", + AppointText: profile.dateAppoint != null ? profile.dateAppoint : "", + SalaryDate: + profile.profileSalarys.length > 0 && profile.profileSalarys[0].date != null + ? Extension.ToThaiNumber(Extension.ToThaiFullDate(profile.profileSalarys[0].date)) + : "", + PositionName: profile.position != null ? profile.position : "", + OcFullPath: `${_child4}${_child3}${_child2}${_child1}${_root}`, + }; + + return new HttpSuccess(mapData); + } + + /** + * รายงาน ก.ก.1 (ลูกจ้างประจำ) + * + * @summary รายงาน ก.ก.1 (ลูกจ้างประจำ) + * + * @param {string} id Id โปรไฟล์ + */ + @Get("kk1/{id}") + public async getKk1Employee(@Path() id: string) { + const profiles = await this.profileRepo.findOne({ + // select: [ + // "citizenId", + // "prefix", + // "firstName", + // "lastName", + // "birthDate", + // "currentAddress", + // "currentDistrictId", + // "currentProvinceId", + // "telephoneNumber", + // "avatar", + // ], + relations: ["currentSubDistrict", "currentDistrict", "currentProvince"], + where: { id: id }, + }); + const profileOc = await this.profileRepo.findOne({ + relations: [ + "current_holders", + "current_holders.orgRoot", + "current_holders.orgChild1", + "current_holders.orgChild2", + "current_holders.orgChild3", + "current_holders.orgChild4", + ], + where: { id: id }, + }); + if (!profiles) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + if (!profileOc) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const orgRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + + const profileFamilyCouple = await this.profileFamilyCoupleRepository.findOne({ + where: { profileEmployeeId: id }, + select: ["couplePrefix", "coupleFirstName", "coupleLastName", "coupleLastNameOld"], + order: { lastUpdatedAt: "DESC" }, + }); + + const profileFamilyMother = await this.profileFamilyMotherRepository.findOne({ + where: { profileEmployeeId: id }, + select: ["motherPrefix", "motherFirstName", "motherLastName"], + order: { lastUpdatedAt: "DESC" }, + }); + + const profileFamilyFather = await this.profileFamilyFatherRepository.findOne({ + where: { profileEmployeeId: id }, + select: ["fatherPrefix", "fatherFirstName", "fatherLastName"], + order: { lastUpdatedAt: "DESC" }, + }); + + const root = + profileOc.current_holders == null || + profileOc.current_holders.length == 0 || + profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgRoot; + + const child1 = + profileOc.current_holders == null || + profileOc.current_holders.length == 0 || + profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild1; + + const child2 = + profileOc.current_holders == null || + profileOc.current_holders.length == 0 || + profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild2; + + const child3 = + profileOc.current_holders == null || + profileOc.current_holders.length == 0 || + profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild3; + + const child4 = + profileOc.current_holders == null || + profileOc.current_holders.length == 0 || + profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id) == null + ? null + : profileOc.current_holders.find((x) => x.orgRevisionId == orgRevision?.id)?.orgChild4; + + // Construct org path + const _root = root ? `${root.orgRootName}` : ""; + const _child1 = child1 ? `${child1.orgChild1Name}/` : ""; + const _child2 = child2 ? `${child2.orgChild2Name}/` : ""; + const _child3 = child3 ? `${child3.orgChild3Name}/` : ""; + const _child4 = child4 ? `${child4.orgChild4Name}/` : ""; + + const Profile = { + CitizenId: + profiles.citizenId != null ? Extension.ToThaiNumber(profiles.citizenId.toString()) : "", + Prefix: profiles?.prefix != null ? profiles.prefix : "", + FirstName: profiles?.firstName != null ? profiles.firstName : "", + LastName: profiles?.lastName != null ? profiles.lastName : "", + FullName: `${profiles?.prefix}${profiles?.firstName} ${profiles?.lastName}`, + BirthDay: profiles?.birthDate + ? Extension.ToThaiNumber(new Date(profiles.birthDate).getDate().toString()) + : null, + BirthDayText: + profiles.birthDate != null + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.birthDate).toString()) + : "", + BirthMonth: profiles?.birthDate + ? Extension.ToThaiNumber(new Date(profiles.birthDate).getMonth() + (1).toString()) + : null, // Months are zero-based + BirthYear: profiles?.birthDate + ? Extension.ToThaiNumber(new Date(profiles.birthDate).getFullYear().toString()) + : null, + BirthYearText: + profiles.birthDate != null + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.birthDate).toString()) + : "", + Address: "", + District: "", + Area: "", + Province: "", + Telephone: + profiles.telephoneNumber != null ? Extension.ToThaiNumber(profiles.telephoneNumber) : "", + CoupleLastNameOld: profileFamilyCouple?.coupleLastNameOld ?? null, + CouplePrefix: profileFamilyCouple?.couplePrefix ?? "", + CoupleFullName: + profileFamilyCouple?.couplePrefix || + profileFamilyCouple?.coupleFirstName || + profileFamilyCouple?.coupleLastNameOld + ? `${profileFamilyCouple?.couplePrefix ?? ""}${profileFamilyCouple?.coupleFirstName ?? ""} ${profileFamilyCouple?.coupleLastNameOld ?? ""}`.trim() + : null, + FatherPrefix: profileFamilyFather?.fatherPrefix ?? "", + FatherFullName: + profileFamilyFather?.fatherPrefix || + profileFamilyFather?.fatherFirstName || + profileFamilyFather?.fatherLastName + ? `${profileFamilyFather?.fatherPrefix ?? ""}${profileFamilyFather?.fatherFirstName ?? ""} ${profileFamilyFather?.fatherLastName ?? ""}`.trim() + : null, + MotherPrefix: profileFamilyMother?.motherPrefix ?? "", + MotherFullName: + profileFamilyMother?.motherPrefix || + profileFamilyMother?.motherFirstName || + profileFamilyMother?.motherLastName + ? `${profileFamilyMother?.motherPrefix ?? ""}${profileFamilyMother?.motherFirstName ?? ""} ${profileFamilyMother?.motherLastName ?? ""}`.trim() + : null, + OcFullPath: `${_child4}${_child3}${_child2}${_child1}${_root}`, + Division: "", + Institute: "", + StartDate: profiles?.dateStart + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateStart)) + : "", + AppointDate: profiles?.dateAppoint + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateAppoint)) + : "", + BirthDate: profiles?.birthDate + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.birthDate)) + : "", + RetireDate: + profiles.dateRetireLaw != null + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(profiles.dateRetireLaw)) + : "", + CurrentAddress: + profiles.currentAddress != null ? Extension.ToThaiNumber(profiles.currentAddress) : "", + CurrentSubDistrict: + profiles.currentSubDistrict != null + ? Extension.ToThaiNumber(profiles.currentSubDistrict.name) + : "", + CurrentDistrict: + profiles.currentDistrict != null + ? Extension.ToThaiNumber(profiles.currentDistrict.name) + : "", + CurrentProvince: + profiles.currentProvince != null + ? Extension.ToThaiNumber(profiles.currentProvince.name) + : "", + // AvatarId: profiles?.avatar ?? null, + }; + + const certs = await this.certificateRepository.find({ + where: { profileEmployeeId: id }, + select: ["certificateType", "issuer", "certificateNo", "issueDate"], + }); + const Cert = certs.map((item) => ({ + CertificateType: item.certificateType ?? null, + Issuer: item.issuer ?? null, + CertificateNo: Extension.ToThaiNumber(item.certificateNo) ?? null, + IssueDate: Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.issueDate)) ?? null, + })); + const trainings = await this.trainingRepository.find({ + select: ["startDate", "endDate", "place", "department"], + where: { profileEmployeeId: id }, + }); + const Training = trainings.map((item) => ({ + Institute: item.department ?? "", + Start: + item.startDate == null + ? "" + : Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate)), + End: + item.endDate == null ? "" : Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate)), + Date: + item.startDate && item.endDate + ? `${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate))} - ${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate))}` + : "", + Level: "", + Degree: item.name, + Field: "", + })); + + const disciplines = await this.disciplineRepository.find({ + select: ["refCommandDate", "refCommandNo", "detail"], + where: { profileEmployeeId: id }, + }); + const Discipline = disciplines.map((item) => ({ + DisciplineYear: + Extension.ToThaiNumber(new Date(item.refCommandDate).getFullYear().toString()) ?? null, + DisciplineDetail: item.detail ?? null, + RefNo: Extension.ToThaiNumber(item.refCommandNo) ?? null, + })); + + const educations = await this.educationRepository.find({ + select: ["startDate", "endDate", "educationLevel", "degree", "field", "institute"], + where: { profileEmployeeId: id }, + order: { lastUpdatedAt: "DESC" }, + }); + const Education = educations.map((item) => ({ + Institute: item.institute ?? null, + Start: + item.startDate == null + ? "" + : Extension.ToThaiNumber(new Date(item.startDate).getFullYear().toString()), + End: + item.endDate == null + ? "" + : Extension.ToThaiNumber(new Date(item.endDate).getFullYear().toString()), + Date: + item.startDate && item.endDate + ? `${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.startDate))} - ${Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.endDate))}` + : "", + Level: item.educationLevel ?? "", + Degree: item.degree && item.field ? `${item.degree} ${item.field}` : "", + Field: item.field ?? "-", + })); + const salarys = await this.salaryRepository.find({ + select: [ + "date", + "position", + "posNo", + "positionType", + "positionLevel", + "positionSalaryAmount", + "refCommandNo", + "amount", + "templateDoc", + ], + where: { profileEmployeeId: id }, + }); + + const Salary = salarys.map((item) => ({ + SalaryDate: item.date ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.date)) : null, + Position: item.position != null ? Extension.ToThaiNumber(item.position) : null, + PosNo: item.posNo != null ? Extension.ToThaiNumber(item.posNo) : null, + Salary: item.amount != null ? Extension.ToThaiNumber(item.amount.toLocaleString()) : null, + Rank: item.positionLevel != null ? Extension.ToThaiNumber(item.positionLevel) : null, + RefAll: item.templateDoc ? Extension.ToThaiNumber(item.templateDoc) : null, + PositionType: item.positionType ?? null, + PositionLevel: item.positionLevel != null ? Extension.ToThaiNumber(item.positionLevel) : null, + PositionAmount: + item.positionSalaryAmount == null + ? null + : Extension.ToThaiNumber(item.positionSalaryAmount.toLocaleString()), + FullName: `${profiles?.prefix} ${profiles?.firstName} ${profiles?.lastName}`, + OcFullPath: `${_child4}${_child3}${_child2}${_child1}${_root}`, + })); + + const insignias = await this.profileInsigniaRepo.find({ + relations: { + insignia: { + insigniaType: true, + }, + }, + where: { profileEmployeeId: id }, + order: { receiveDate: "ASC" }, + }); + const Insignia = insignias.map((item) => ({ + ReceiveDate: item.receiveDate + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.receiveDate)) + : "", + InsigniaName: item.insignia.name, + InsigniaShortName: item.insignia.shortName, + InsigniaTypeName: item.insignia.insigniaType.name, + No: item.no ? Extension.ToThaiNumber(item.no) : "", + Issue: item.issue ? item.issue : "", + VolumeNo: item.volumeNo ? Extension.ToThaiNumber(item.volumeNo) : "", + Volume: item.volume ? Extension.ToThaiNumber(item.volume) : "", + Section: item.section ? Extension.ToThaiNumber(item.section) : "", + Page: item.page ? Extension.ToThaiNumber(item.page) : "", + RefCommandDate: item.refCommandDate + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.refCommandDate)) + : "", + })); + + const leaves = await this.profileLeaveRepository.find({ + relations: { leaveType: true }, + where: { profileEmployeeId: id }, + order: { dateLeaveStart: "ASC" }, + }); + const Leave = leaves.map((item) => ({ + LeaveTypeName: item.leaveType.name, + DateLeaveStart: item.dateLeaveStart + ? Extension.ToThaiNumber(Extension.ToThaiFullDate2(item.dateLeaveStart)) + : "", + LeaveDays: item.leaveDays ? Extension.ToThaiNumber(item.leaveDays.toString()) : "", + })); + + return new HttpSuccess({ + Profile: [Profile], + Cert, + Training, + Discipline, + Education, + Salary, + Insignia, + Leave, + }); + } + + /** + * API สร้างทะเบียนประวัติ + * + * @summary ORG_065 - สร้างทะเบียนประวัติ (ADMIN) #70 + * + */ + @Post() + async createProfile(@Body() body: CreateProfileEmployee, @Request() request: RequestWithUser) { + await new permission().PermissionCreate(request, "SYS_REGISTRY_TEMP"); + if (await this.profileRepo.findOneBy({ citizenId: body.citizenId })) { + throw new HttpError( + HttpStatus.INTERNAL_SERVER_ERROR, + "รหัสบัตรประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว", + ); + } + + if (body.posLevelId === "") body.posLevelId = null; + if (body.posTypeId === "") body.posTypeId = null; + + if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้"); + } + + if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้"); + } + + if (body.employeeClass == null || body.employeeClass == undefined || body.employeeClass == "") { + body.employeeClass = "PERM"; + } + if (!["PERM", "TEMP"].includes(body.employeeClass.toLocaleUpperCase())) { + throw new HttpError(HttpStatus.NOT_FOUND, "ประเภทลูกจ้างไม่ถูกต้อง"); + } + + const profile = Object.assign(new ProfileEmployee(), body); + profile.createdUserId = request.user.sub; + profile.createdFullName = request.user.name; + profile.lastUpdateUserId = request.user.sub; + profile.lastUpdateFullName = request.user.name; + profile.dateRetire = calculateRetireDate(profile.birthDate); + profile.dateRetireLaw = calculateRetireLaw(profile.birthDate); + profile.citizenId = Extension.CheckCitizen(profile.citizenId); + profile.statusTemp = profile.employeeClass.toLocaleUpperCase() == "TEMP" ? "WAITTING" : ""; + profile.employeeClass = profile.employeeClass.toLocaleUpperCase(); + await this.profileRepo.save(profile); + return new HttpSuccess(); + } + + /** + * API แก้ไขทะเบียนประวัติ + * + * @summary ORG_065 - แก้ไขทะเบียนประวัติ (ADMIN) #70 + * + * @param {string} id Id ทะเบียนประวัติ + */ + @Put("{id}") + async updateProfileEmployee( + @Request() request: RequestWithUser, + @Path() id: string, + @Body() body: UpdateProfileEmployee, + ) { + await new permission().PermissionUpdate(request, "SYS_REGISTRY_TEMP"); + const exists = + !!body.citizenId && + (await this.profileRepo.findOne({ + where: { + id: Not(id), + citizenId: body.citizenId, + employeeClass: String(body.employeeClass), + }, + })); + + if (exists) { + throw new HttpError(HttpStatus.CONFLICT, "รหัสบัตรประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว"); + } + + if (body.posLevelId === "") body.posLevelId = null; + if (body.posTypeId === "") body.posTypeId = null; + + if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้"); + } + + if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้"); + } + + const record = await this.profileRepo.findOneBy({ id }); + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้"); + + await this.profileHistoryRepo.save( + Object.assign(new ProfileEmployeeHistory(), { + ...record, + profileEmployeeId: id, + id: undefined, + }), + ); + + if (body.employeeClass == null || body.employeeClass == undefined || body.employeeClass == "") { + body.employeeClass = "PERM"; + } + if (!["PERM", "TEMP"].includes(body.employeeClass.toLocaleUpperCase())) { + throw new HttpError(HttpStatus.NOT_FOUND, "ประเภทลูกจ้างไม่ถูกต้อง"); + } + + Object.assign(record, body); + record.lastUpdateUserId = request.user.sub; + record.lastUpdateFullName = request.user.name; + record.dateRetire = calculateRetireDate(record.birthDate); + record.dateRetireLaw = calculateRetireLaw(record.birthDate); + record.citizenId = Extension.CheckCitizen(record.citizenId); + record.employeeClass = record.employeeClass.toLocaleUpperCase(); + await this.profileRepo.save(record); + return new HttpSuccess(); + } + + /** + * API ลบทะเบียนประวัติ + * + * @summary ORG_065 - ลบทะเบียนประวัติ (ADMIN) #70 + * + * @param {string} id Id ทะเบียนประวัติ + */ + @Delete("{id}") + async deleteProfile(@Path() id: string, @Request() request: RequestWithUser) { + await new permission().PermissionDelete(request, "SYS_REGISTRY_TEMP"); + const result = await this.profileRepo.findOne({ where: { id: id } }); + if (!result) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + await this.informationHistoryRepository.delete({ profileEmployeeId: id }); + await this.profileRepo.remove(result); + return new HttpSuccess(); + } + + /** + * API รายละเอียดรายการทะเบียนประวัติ + * + * @summary ORG_065 - รายละเอียดรายการทะเบียนประวัติ (ADMIN) #70 + * + * @param {string} id Id ทะเบียนประวัติ + */ + @Get("user") + async detailProfileUser(@Request() request: RequestWithUser) { + const profile = await this.profileRepo.findOne({ + relations: { + posLevel: true, + posType: true, + // gender: true, + // relationship: true, + // bloodGroup: true, + }, + where: { keycloak: request.user.sub }, + }); + + if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + return new HttpSuccess(profile); + } + + /** + * API รายการทะเบียนประวัติลูกจ้างชั่วคราว + * + * @summary รายการทะเบียนประวัติลูกจ้างชั่วคราว (ADMIN) + * + */ + @Get("temp") + async listProfileEmp() { + const [record, total] = await this.profileRepo + .createQueryBuilder("profileEmployee") + .leftJoinAndSelect("profileEmployee.posLevel", "posLevel") + .leftJoinAndSelect("profileEmployee.posType", "posType") + .leftJoinAndSelect("profileEmployee.current_holders", "current_holders") + .leftJoinAndSelect("profileEmployee.profileEmployeeEmployment", "profileEmployeeEmployment") + .leftJoinAndSelect("current_holders.positions", "positions") + .leftJoinAndSelect("current_holders.orgRoot", "orgRoot") + .leftJoinAndSelect("current_holders.orgChild1", "orgChild1") + .leftJoinAndSelect("current_holders.orgChild2", "orgChild2") + .leftJoinAndSelect("current_holders.orgChild3", "orgChild3") + .leftJoinAndSelect("current_holders.orgChild4", "orgChild4") + .andWhere("profileEmployee.employeeClass = :employeeClass", { employeeClass: "TEMP" }) + .andWhere("profileEmployee.statusTemp = :statusTemp", { statusTemp: "PENDING" }) + .getManyAndCount(); + const data = await Promise.all( + record.map((_data) => { + const shortName = + _data.current_holders.length == 0 + ? null + : _data.current_holders[0].orgChild4 != null + ? `${_data.current_holders[0].orgChild4.orgChild4ShortName}${_data.current_holders[0].posMasterNo}` + : _data.current_holders[0].orgChild3 != null + ? `${_data.current_holders[0].orgChild3.orgChild3ShortName}${_data.current_holders[0].posMasterNo}` + : _data.current_holders[0].orgChild2 != null + ? `${_data.current_holders[0].orgChild2.orgChild2ShortName}${_data.current_holders[0].posMasterNo}` + : _data.current_holders[0].orgChild1 != null + ? `${_data.current_holders[0].orgChild1.orgChild1ShortName}${_data.current_holders[0].posMasterNo}` + : _data.current_holders[0].orgRoot != null + ? `${_data.current_holders[0].orgRoot.orgRootShortName}${_data.current_holders[0].posMasterNo}` + : null; + const dateEmployment = + _data.profileEmployeeEmployment.length == 0 + ? null + : _data.profileEmployeeEmployment.reduce((latest, current) => { + return latest.date > current.date ? latest : current; + }).date; + return { + id: _data.id, + prefix: _data.prefix, + rank: _data.rank, + firstName: _data.firstName, + lastName: _data.lastName, + citizenId: _data.citizenId, + posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName, + posType: _data.posType == null ? null : _data.posType.posTypeName, + posTypeShortName: _data.posType == null ? null : _data.posType.posTypeShortName, + posLevelId: _data.posLevel == null ? null : _data.posLevel.id, + posTypeId: _data.posType == null ? null : _data.posType.id, + positionId: _data.positionIdTemp, + posmasterId: _data.posmasterIdTemp, + position: _data.position, + posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName, + employeeClass: _data.employeeClass == null ? null : _data.employeeClass, + govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0), + age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0), + dateEmployment: dateEmployment, + dateAppoint: _data.dateAppoint, + dateStart: _data.dateStart, + createdAt: _data.createdAt, + dateRetireLaw: _data.dateRetireLaw, + draftOrganizationOrganization: + _data.nodeTemp == "0" + ? _data.rootTemp + : _data.nodeTemp == "1" + ? _data.child1Temp + : _data.nodeTemp == "2" + ? _data.child2Temp + : _data.nodeTemp == "3" + ? _data.child3Temp + : _data.nodeTemp == "4" + ? _data.child4Temp + : null, + draftPositionEmployee: _data.positionTemp, + draftOrgEmployeeStatus: _data.statusTemp, + node: _data.nodeTemp, + nodeId: _data.nodeIdTemp, + nodeName: + _data.nodeTemp == "0" + ? _data.rootTemp + : _data.nodeTemp == "1" + ? _data.child1Temp + : _data.nodeTemp == "2" + ? _data.child2Temp + : _data.nodeTemp == "3" + ? _data.child3Temp + : _data.nodeTemp == "4" + ? _data.child4Temp + : null, + nodeShortName: + _data.nodeTemp == "0" + ? _data.rootShortNameTemp + : _data.nodeTemp == "1" + ? _data.child1ShortNameTemp + : _data.nodeTemp == "2" + ? _data.child1ShortNameTemp + : _data.nodeTemp == "3" + ? _data.child3ShortNameTemp + : _data.nodeTemp == "4" + ? _data.child4ShortNameTemp + : null, + root: _data.rootTemp ? _data.rootTemp : null, + rootId: _data.rootIdTemp ? _data.rootIdTemp : null, + rootShortName: _data.rootShortNameTemp ? _data.rootShortNameTemp : null, + child1: _data.child1Temp ? _data.child1Temp : null, + child1Id: _data.child1IdTemp ? _data.child1IdTemp : null, + child1ShortName: _data.child1ShortNameTemp ? _data.child1ShortNameTemp : null, + child2: _data.child2Temp ? _data.child2Temp : null, + child2Id: _data.child2IdTemp ? _data.child2IdTemp : null, + child2ShortName: _data.child2ShortNameTemp ? _data.child2ShortNameTemp : null, + child3: _data.child3Temp ? _data.child3Temp : null, + child3Id: _data.child3IdTemp ? _data.child3IdTemp : null, + child3ShortName: _data.child3ShortNameTemp ? _data.child3ShortNameTemp : null, + child4: _data.child4Temp ? _data.child4Temp : null, + child4Id: _data.child4IdTemp ? _data.child4IdTemp : null, + child4ShortName: _data.child4ShortNameTemp ? _data.child4ShortNameTemp : null, + }; + }), + ); + + return new HttpSuccess({ data: data, total }); + } + + /** + * API ประวัติการแก้ไขรายการทะเบียนประวัติ + * + * @summary ประวัติการแก้ไขรายการทะเบียนประวัติ + * + * @param {string} id Id โปรไฟล์ + */ + @Get("history/user") + async getHistoryProfileByUser(@Request() request: RequestWithUser) { + const historyProfile = await this.profileHistoryRepo.find({ + relations: { + posLevel: true, + posType: true, + }, + where: { keycloak: request.user.sub }, + order: { + createdAt: "ASC", + }, + }); + + if (!historyProfile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + return new HttpSuccess(historyProfile); + } + + /** + * API ออกคำสั่งลูกจ้าง + * + * @summary ORG_038 - ออกคำสั่งลูกจ้าง (ADMIN) # + * + */ + @Get("report") + async getReport(@Request() request: RequestWithUser) { + const profiles = await this.profileRepo.find({ + where: { statusTemp: "REPORT", employeeClass: "TEMP" }, + relations: [ + "posLevel", + "posType", + "current_holders", + "current_holders.orgChild1", + "current_holders.orgChild2", + "current_holders.orgChild3", + "current_holders.orgChild4", + ], + }); + + if (!profiles) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + if (!findRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + } + + const formattedData = profiles.map((profile) => { + const fullName = `${profile.prefix} ${profile.firstName} ${profile.lastName}`; + const shortName = + profile.current_holders.length == 0 + ? null + : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 != + null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgChild3 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgChild2 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgChild1 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != + null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgRoot != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName}${profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : null; + + const root = + profile.current_holders.length == 0 || + (profile.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null) + ? null + : profile.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot; + + return { + id: profile.id, + prefix: profile.prefix, + firstName: profile.firstName, + lastName: profile.lastName, + fullName: fullName, + birthDate: profile.birthDate, + rank: profile.rank, + citizenId: profile.citizenId, + email: profile.email, + phone: profile.phone, + isProbation: profile.isProbation, + isLeave: profile.isLeave, + leaveReason: profile.leaveReason, + dateLeave: profile.dateLeave, + dateRetire: profile.dateRetire, + dateRetireLaw: profile.dateRetireLaw, + salaryLevel: profile.salaryLevel, + group: profile.group, + ethnicity: profile.ethnicity, + telephoneNumber: profile.telephoneNumber, + nationality: profile.nationality, + gender: profile.gender, + relationship: profile.relationship, + religion: profile.religion, + bloodGroup: profile.bloodGroup, + positionNumber: shortName, + organization: root == null ? null : root.orgRootShortName, + positionName: profile.position, + possitionTypeId: profile.posTypeId, + positionType: profile.posType?.posTypeName, + positionLevelId: profile.posLevelId, + positionLevel: profile.posLevel?.posLevelName, + }; + }); + + return new HttpSuccess(formattedData); + } + + /** + * API ออกคำสั่งลูกจ้าง + * + * @summary ORG_038 - ออกคำสั่งลูกจ้าง (ADMIN) # + * + */ + @Get("report-temp") + async getReportTemp(@Request() request: RequestWithUser) { + const profiles = await this.profileRepo.find({ + where: { statusTemp: "REPORT", employeeClass: "TEMP" }, + }); + + if (!profiles) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + if (!findRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + } + + const formattedData = profiles.map((profile) => { + const shortName = + profile.child4Temp != null + ? `${profile.child4ShortNameTemp}${profile.posMasterNoTemp}` + : profile.child3Temp != null + ? `${profile.child3ShortNameTemp}${profile.posMasterNoTemp}` + : profile.child2Temp != null + ? `${profile.child2ShortNameTemp}${profile.posMasterNoTemp}` + : profile.child1Temp != null + ? `${profile.child1ShortNameTemp}${profile.posMasterNoTemp}` + : profile.rootIdTemp != null + ? `${profile.rootShortNameTemp}${profile.posMasterNoTemp}` + : null; + + return { + id: profile.id, + citizenId: profile.citizenId, + prefix: profile.prefix, + firstName: profile.firstName, + lastName: profile.lastName, + organization: profile.rootTemp, + positionName: profile.positionTemp, + positionType: profile.posTypeNameTemp, + positionLevel: profile.posLevelNameTemp, + positionNumber: shortName, + birthDate: profile.birthDate, + }; + }); + + return new HttpSuccess(formattedData); + } + + /** + * API รายละเอียดรายการทะเบียนประวัติ + * + * @summary ORG_065 - รายละเอียดรายการทะเบียนประวัติ (ADMIN) #70 + * + * @param {string} id Id ทะเบียนประวัติ + */ + @Get("{id}") + async detailProfile(@Path() id: string) { + const profile = await this.profileRepo.findOne({ + relations: { + posLevel: true, + posType: true, + // gender: true, + // relationship: true, + // bloodGroup: true, + }, + where: { id }, + }); + + if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + return new HttpSuccess(profile); + } + + /** + * API รายการทะเบียนประวัติ + * + * @summary ORG_065 - รายการทะเบียนประวัติ (ADMIN) #70 + * + */ + @Get() + async listProfile( + @Query("page") page: number = 1, + @Query("pageSize") pageSize: number = 10, + @Query() searchField?: "firstName" | "lastName" | "fullName" | "citizenId" | "position", + @Query() searchKeyword: string = "", + @Query() posType?: string, + @Query() posLevel?: string, + @Query() yearLeave?: number, + @Query() isProbation?: boolean, + @Query() isRetire?: boolean, + @Query() type?: string, + ) { + let queryLike = + "CONCAT(profileEmployee.prefix, profileEmployee.firstName, ' ', profileEmployee.lastName) LIKE :keyword"; + if (searchField == "citizenId") { + queryLike = "profileEmployee.citizenId LIKE :keyword"; + } else if (searchField == "position") { + queryLike = "profileEmployee.position LIKE :keyword"; + } + const [record, total] = await this.profileRepo + .createQueryBuilder("profileEmployee") + .leftJoinAndSelect("profileEmployee.posLevel", "posLevel") + .leftJoinAndSelect("profileEmployee.posType", "posType") + .leftJoinAndSelect("profileEmployee.current_holders", "current_holders") + .leftJoinAndSelect("profileEmployee.profileEmployeeEmployment", "profileEmployeeEmployment") + .leftJoinAndSelect("current_holders.positions", "positions") + .leftJoinAndSelect("current_holders.orgRoot", "orgRoot") + .leftJoinAndSelect("current_holders.orgChild1", "orgChild1") + .leftJoinAndSelect("current_holders.orgChild2", "orgChild2") + .leftJoinAndSelect("current_holders.orgChild3", "orgChild3") + .leftJoinAndSelect("current_holders.orgChild4", "orgChild4") + .andWhere( + searchKeyword != undefined && searchKeyword != null && searchKeyword != "" + ? queryLike + : "1=1", + { + keyword: `%${searchKeyword}%`, + }, + ) + .andWhere( + posType != undefined && posType != null && posType != "" + ? "posType.posTypeName LIKE :keyword1" + : "1=1", + { + keyword1: `${posType}`, + }, + ) + .andWhere( + posLevel != undefined && posLevel != null && posLevel != "" + ? "posLevel.posLevelName LIKE :keyword2" + : "1=1", + { + keyword2: `${posLevel}`, + }, + ) + .andWhere( + isProbation != undefined && isProbation != null + ? `profile.isProbation = ${isProbation}` + : "1=1", + ) + .andWhere( + isRetire != undefined && isRetire != null + ? isRetire == true + ? `profile.dateRetire IS null` + : `profile.dateRetire IS NOT NULL` + : "1=1", + ) + .andWhere( + type !== undefined && type !== null && type !== "" + ? "profileEmployee.employeeClass LIKE :type" + : "1=1", + { + type: type == null || type == undefined ? null : `${type.trim().toUpperCase()}`, + }, + ) + .skip((page - 1) * pageSize) + .take(pageSize) + .getManyAndCount(); + const data = await Promise.all( + record.map((_data) => { + const shortName = + _data.current_holders.length == 0 + ? null + : _data.current_holders[0].orgChild4 != null + ? `${_data.current_holders[0].orgChild4.orgChild4ShortName}${_data.current_holders[0].posMasterNo}` + : _data.current_holders[0].orgChild3 != null + ? `${_data.current_holders[0].orgChild3.orgChild3ShortName}${_data.current_holders[0].posMasterNo}` + : _data.current_holders[0].orgChild2 != null + ? `${_data.current_holders[0].orgChild2.orgChild2ShortName}${_data.current_holders[0].posMasterNo}` + : _data.current_holders[0].orgChild1 != null + ? `${_data.current_holders[0].orgChild1.orgChild1ShortName}${_data.current_holders[0].posMasterNo}` + : _data.current_holders[0].orgRoot != null + ? `${_data.current_holders[0].orgRoot.orgRootShortName}${_data.current_holders[0].posMasterNo}` + : null; + const dateEmployment = + _data.profileEmployeeEmployment.length == 0 + ? null + : _data.profileEmployeeEmployment.reduce((latest, current) => { + return latest.date > current.date ? latest : current; + }).date; + return { + id: _data.id, + prefix: _data.prefix, + rank: _data.rank, + firstName: _data.firstName, + lastName: _data.lastName, + citizenId: _data.citizenId, + posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName, + posType: _data.posType == null ? null : _data.posType.posTypeName, + posTypeShortName: _data.posType == null ? null : _data.posType.posTypeShortName, + posLevelId: _data.posLevel == null ? null : _data.posLevel.id, + posTypeId: _data.posType == null ? null : _data.posType.id, + positionId: _data.positionIdTemp, + posmasterId: _data.posmasterIdTemp, + position: _data.position, + posNo: _data.employeeClass == "TEMP" ? _data.posMasterNoTemp : shortName, + employeeClass: _data.employeeClass == null ? null : _data.employeeClass, + govAge: Extension.CalculateGovAge(_data.dateAppoint, 0, 0), + age: Extension.CalculateAgeStrV2(_data.birthDate, 0, 0), + dateEmployment: dateEmployment, + dateAppoint: _data.dateAppoint, + dateStart: _data.dateStart, + createdAt: _data.createdAt, + dateRetireLaw: _data.dateRetireLaw, + draftOrganizationOrganization: + _data.nodeTemp == "0" + ? _data.rootTemp + : _data.nodeTemp == "1" + ? _data.child1Temp + : _data.nodeTemp == "2" + ? _data.child2Temp + : _data.nodeTemp == "3" + ? _data.child3Temp + : _data.nodeTemp == "4" + ? _data.child4Temp + : null, + draftPositionEmployee: _data.positionTemp, + draftOrgEmployeeStatus: _data.statusTemp, + node: _data.nodeTemp, + nodeId: _data.nodeIdTemp, + nodeName: + _data.nodeTemp == "0" + ? _data.rootTemp + : _data.nodeTemp == "1" + ? _data.child1Temp + : _data.nodeTemp == "2" + ? _data.child2Temp + : _data.nodeTemp == "3" + ? _data.child3Temp + : _data.nodeTemp == "4" + ? _data.child4Temp + : null, + nodeShortName: + _data.nodeTemp == "0" + ? _data.rootShortNameTemp + : _data.nodeTemp == "1" + ? _data.child1ShortNameTemp + : _data.nodeTemp == "2" + ? _data.child1ShortNameTemp + : _data.nodeTemp == "3" + ? _data.child3ShortNameTemp + : _data.nodeTemp == "4" + ? _data.child4ShortNameTemp + : null, + root: _data.rootTemp ? _data.rootTemp : null, + rootId: _data.rootIdTemp ? _data.rootIdTemp : null, + rootShortName: _data.rootShortNameTemp ? _data.rootShortNameTemp : null, + child1: _data.child1Temp ? _data.child1Temp : null, + child1Id: _data.child1IdTemp ? _data.child1IdTemp : null, + child1ShortName: _data.child1ShortNameTemp ? _data.child1ShortNameTemp : null, + child2: _data.child2Temp ? _data.child2Temp : null, + child2Id: _data.child2IdTemp ? _data.child2IdTemp : null, + child2ShortName: _data.child2ShortNameTemp ? _data.child2ShortNameTemp : null, + child3: _data.child3Temp ? _data.child3Temp : null, + child3Id: _data.child3IdTemp ? _data.child3IdTemp : null, + child3ShortName: _data.child3ShortNameTemp ? _data.child3ShortNameTemp : null, + child4: _data.child4Temp ? _data.child4Temp : null, + child4Id: _data.child4IdTemp ? _data.child4IdTemp : null, + child4ShortName: _data.child4ShortNameTemp ? _data.child4ShortNameTemp : null, + }; + }), + ); + + return new HttpSuccess({ data: data, total }); + } + + @Get("history/{id}") + async getProfileHistory(@Path() id: string) { + const profile = await this.profileHistoryRepo.find({ + relations: { + posLevel: true, + posType: true, + // gender: true, + // relationship: true, + // bloodGroup: true, + }, + where: { profileEmployeeId: id }, + }); + + if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + return new HttpSuccess(profile); + } + + /** + * API ค้นหารายชื่อไปครองตำแหน่ง + * + * @summary ORG_063 - ค้นหารายชื่อไปครองตำแหน่ง (ADMIN) #68 + * + */ + @Post("search") + async searchProfileOrg( + @Body() + requestBody: { + position?: string; + posLevelId?: string; + posTypeId?: string; + page: number; + pageSize: number; + keyword?: string; + }, + ) { + const orgRevision = await this.orgRevisionRepo.findOne({ + where: { + orgRevisionIsDraft: false, + orgRevisionIsCurrent: true, + }, + relations: ["employeePosMasters"], + }); + if (!orgRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง"); + } + const [profiles, total] = await this.profileRepo + .createQueryBuilder("profileEmployee") + .leftJoinAndSelect("profileEmployee.next_holders", "next_holders") + .leftJoinAndSelect("profileEmployee.posLevel", "posLevel") + .leftJoinAndSelect("profileEmployee.posType", "posType") + .where( + requestBody.position != null && requestBody.position != "" + ? "profileEmployee.position LIKE :position" + : "1=1", + { + position: `%${requestBody.position}%`, + }, + ) + .andWhere( + new Brackets((qb) => { + qb.where( + requestBody.keyword != null && requestBody.keyword != "" + ? "profileEmployee.prefix LIKE :keyword" + : "1=1", + { + keyword: `%${requestBody.keyword}%`, + }, + ) + .orWhere( + requestBody.keyword != null && requestBody.keyword != "" + ? "profileEmployee.firstName LIKE :keyword" + : "1=1", + { + keyword: `%${requestBody.keyword}%`, + }, + ) + .orWhere( + requestBody.keyword != null && requestBody.keyword != "" + ? "profileEmployee.lastName LIKE :keyword" + : "1=1", + { + keyword: `%${requestBody.keyword}%`, + }, + ) + .orWhere( + requestBody.keyword != null && requestBody.keyword != "" + ? "profileEmployee.citizenId LIKE :keyword" + : "1=1", + { + keyword: `%${requestBody.keyword}%`, + }, + ); + }), + ) + .andWhere( + requestBody.posTypeId != null && requestBody.posTypeId != "" + ? "profileEmployee.posTypeId LIKE :posTypeId" + : "1=1", + { + posTypeId: `%${requestBody.posTypeId}%`, + }, + ) + .andWhere( + requestBody.posLevelId != null && requestBody.posLevelId != "" + ? "profileEmployee.posLevelId LIKE :posLevelId" + : "1=1", + { + posLevelId: `%${requestBody.posLevelId}%`, + }, + ) + .andWhere( + new Brackets((qb) => { + qb.where("profileEmployee.id NOT IN (:...ids)", { + ids: + orgRevision.employeePosMasters + .filter((x) => x.next_holderId != null) + .map((x) => x.next_holderId).length == 0 + ? ["zxc"] + : orgRevision.employeePosMasters + .filter((x) => x.next_holderId != null) + .map((x) => x.next_holderId), + }); + }), + ) + .andWhere("profileEmployee.employeeClass = :employeeClass", { employeeClass: "PERM" }) + .skip((requestBody.page - 1) * requestBody.pageSize) + .take(requestBody.pageSize) + .getManyAndCount(); + const data = profiles.map((_data) => ({ + id: _data.id, + prefix: _data.prefix, + rank: _data.rank, + firstName: _data.firstName, + lastName: _data.lastName, + citizenId: _data.citizenId, + posLevel: _data.posLevel == null ? null : _data.posLevel.posLevelName, + posType: _data.posType == null ? null : _data.posType.posTypeName, + position: _data.position, + })); + + return new HttpSuccess({ data: data, total }); + } + + /** + * API ค้นหาประวัติการครองตำแหน่ง ลูกจ้าง + * + * @summary ค้นหาประวัติการครองตำแหน่ง ลูกจ้าง + * + */ + @Post("search/history/oc") + async searchHistoryOC( + @Body() + requestBody: { + posNo?: string; + position?: string; + }, + ) { + const profiles = await this.profileRepo + .createQueryBuilder("profileEmployee") + .leftJoinAndSelect("profileEmployee.profileSalarys", "profileSalarys") + .select([ + "profileEmployee.id", + "profileEmployee.prefix", + "profileEmployee.firstName", + "profileEmployee.lastName", + "profileEmployee.citizenId", + "profileSalarys.position", + "profileSalarys.posNo", + "profileSalarys.date", + ]) + .andWhere( + requestBody.position != null && requestBody.position != "" && requestBody.posNo == undefined + ? "profileSalarys.position LIKE :position" + : "1=2", + { + position: `%${requestBody.position}%`, + }, + ) + .orWhere( + requestBody.posNo != null && requestBody.posNo != "" && requestBody.position == undefined + ? "profileSalarys.posNo LIKE :posNo" + : "1=2", + { + posNo: `%${requestBody.posNo}%`, + }, + ) + .getMany(); + + const mapData = profiles.map((profile) => { + let profileSalary; + if (profile.profileSalarys && profile.profileSalarys.length > 0) { + profileSalary = profile.profileSalarys.reduce((latest, current) => { + return new Date(current.date) > new Date(latest.date) ? current : latest; + }); + } + return { + id: profile.id, + fullName: `${profile.prefix}${profile.firstName} ${profile.lastName}`, + citizenId: profile.citizenId, + position: profileSalary ? profileSalary.position : null, + posNo: profileSalary ? profileSalary.posNo : null, + date: profileSalary ? profileSalary.date : null, + }; + }); + + return new HttpSuccess(mapData); + } + + /** + * API ข้อมูลทะเบียนประวัติตาม keycloak + * + * @summary ORG_065 - ข้อมูลทะเบียนประวัติตาม keycloak (ADMIN) #70 + * + */ + @Get("keycloak/position") + async getProfileByKeycloak(@Request() request: { user: Record }) { + const profile = await this.profileRepo.findOne({ + where: { keycloak: request.user.sub }, + relations: ["posLevel", "posType", "current_holders", "current_holders.orgRoot"], + }); + if (!profile) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ"); + } + + const orgRevisionPublish = await this.orgRevisionRepo + .createQueryBuilder("orgRevision") + .where("orgRevision.orgRevisionIsDraft = false") + .andWhere("orgRevision.orgRevisionIsCurrent = true") + .getOne(); + if (!orgRevisionPublish) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง"); + } + + const _profile = { + profileId: profile.id, + rank: profile.rank, + prefix: profile.prefix, + firstName: profile.firstName, + lastName: profile.lastName, + citizenId: profile.citizenId, + position: profile.position, + posLevelName: profile.posLevel == null ? null : profile.posLevel.posLevelName, + posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank, + posLevelId: profile.posLevel == null ? null : profile.posLevel.id, + posTypeName: profile.posType == null ? null : profile.posType.posTypeName, + posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank, + posTypeId: profile.posType == null ? null : profile.posType.id, + rootId: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgRootId, + root: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot + .orgRootName, + child1Id: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgChild1Id, + child1: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1 + .orgChild1Name, + child2Id: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgChild2Id, + child2: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2 + .orgChild2Name, + child3Id: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgChild3Id, + child3: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3 + .orgChild3Name, + child4Id: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgChild4Id, + child4: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4 + .orgChild4Name, + }; + return new HttpSuccess(_profile); + } + + /** + * API ค้นหาข้อมูลทะเบียนประวัติ + * + * @summary ORG_065 - ค้นหาข้อมูลทะเบียนประวัติ (ADMIN) #70 + * + */ + @Post("search-personal") + async getProfileBySearchKeyword( + @Query("page") page: number = 1, + @Query("pageSize") pageSize: number = 10, + @Body() + body: { + fieldName: string; + keyword?: string; + }, + ) { + let findProfile: any; + let total: any; + const skip = (page - 1) * pageSize; + const take = pageSize; + switch (body.fieldName) { + case "citizenId": + [findProfile, total] = await this.profileRepo.findAndCount({ + where: { citizenId: Like(`%${body.keyword}%`) }, + relations: [ + "posType", + "posLevel", + "current_holders", + "profileSalarys", + "current_holders.orgRoot", + "current_holders.orgChild1", + "current_holders.orgChild2", + "current_holders.orgChild3", + "current_holders.orgChild4", + ], + skip, + take, + }); + break; + + case "firstname": + [findProfile, total] = await this.profileRepo.findAndCount({ + where: { firstName: Like(`%${body.keyword}%`) }, + relations: [ + "posType", + "posLevel", + "current_holders", + "profileSalarys", + "current_holders.orgRoot", + "current_holders.orgChild1", + "current_holders.orgChild2", + "current_holders.orgChild3", + "current_holders.orgChild4", + ], + skip, + take, + }); + break; + + case "lastname": + [findProfile, total] = await this.profileRepo.findAndCount({ + where: { lastName: Like(`%${body.keyword}%`) }, + relations: [ + "posType", + "posLevel", + "current_holders", + "profileSalarys", + "current_holders.orgRoot", + "current_holders.orgChild1", + "current_holders.orgChild2", + "current_holders.orgChild3", + "current_holders.orgChild4", + ], + skip, + take, + }); + break; + + default: + [findProfile, total] = await this.profileRepo.findAndCount({ + relations: [ + "posType", + "posLevel", + "current_holders", + "profileSalarys", + "current_holders.orgRoot", + "current_holders.orgChild1", + "current_holders.orgChild2", + "current_holders.orgChild3", + "current_holders.orgChild4", + ], + skip, + take, + }); + break; + } + + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + if (!findRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + } + + const mapDataProfile = await Promise.all( + findProfile.map(async (item: ProfileEmployee) => { + const fullName = `${item.prefix} ${item.firstName} ${item.lastName}`; + const shortName = + item.current_holders.length == 0 + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 != + null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 != + null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgChild2 != null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgChild1 != null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != + null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgRoot != null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : null; + + const root = + item.current_holders.length == 0 || + (item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null) + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot; + + let salary: any = ""; + if (item != null && item.profileSalarys != null && item.profileSalarys.length > 0) { + let _salary: any = item.profileSalarys.sort( + (a, b) => + (b.date == null ? 0 : b.date.getTime()) - (a.date == null ? 0 : a.date.getTime()), + ); + if (_salary.length > 0) { + salary = _salary[0]; + } + } + + const rootHolder = item.current_holders?.find( + (x) => x.orgRevisionId == findRevision.id, + )?.orgRoot; + const child1Holder = item.current_holders?.find( + (x) => x.orgRevisionId == findRevision.id, + )?.orgChild1; + const child2Holder = item.current_holders?.find( + (x) => x.orgRevisionId == findRevision.id, + )?.orgChild2; + const child3Holder = item.current_holders?.find( + (x) => x.orgRevisionId == findRevision.id, + )?.orgChild3; + const child4Holder = item.current_holders?.find( + (x) => x.orgRevisionId == findRevision.id, + )?.orgChild4; + const posMasterNo = item.current_holders?.find( + (x) => x.orgRevisionId == findRevision.id, + )?.posMasterNo; + + const latestProfileEducation = await this.profileEducationRepository.findOne({ + where: { profileEmployeeId: item.id }, + order: { endDate: "DESC" }, + }); + + return { + id: item.id, + prefix: item.prefix, + rank: item.rank, + firstName: item.firstName, + lastName: item.lastName, + position: item.position, + citizenId: item.citizenId, + email: item.email, + phone: item.phone, + name: fullName, + birthDate: item.birthDate, + positionLevel: item.posLevelId, + positionLevelName: item.posLevel?.posLevelName, + positionType: item.posTypeId, + positionTypeName: item.posType?.posTypeName, + posNo: shortName, + organization: root == null ? null : root.orgRootShortName, + salary: salary == "" ? "" : salary.amount, + root: rootHolder?.orgRootName ?? null, + rootId: rootHolder?.id ?? null, + rootShortName: rootHolder?.orgRootShortName ?? null, + child1: child1Holder?.orgChild1Name ?? null, + child1Id: child1Holder?.id ?? null, + child1ShortName: child1Holder?.orgChild1ShortName ?? null, + child2: child2Holder?.orgChild2Name ?? null, + child2Id: child2Holder?.id ?? null, + child2ShortName: child2Holder?.orgChild2ShortName ?? null, + child3: child3Holder?.orgChild3Name ?? null, + child3Id: child3Holder?.id ?? null, + child3ShortName: child3Holder?.orgChild3ShortName ?? null, + child4: child4Holder?.orgChild4Name ?? null, + child4Id: child4Holder?.id ?? null, + child4ShortName: child4Holder?.orgChild4ShortName ?? null, + posMasterNo: posMasterNo ?? null, + posTypeId: item.posTypeId, + posTypeName: item.posType?.posTypeName, + posLevelId: item.posLevelId, + posLevelName: item.posLevel?.posLevelName, + educationDegree: + latestProfileEducation != null && latestProfileEducation.educationLevel != null + ? latestProfileEducation.educationLevel + : null, + // ? { + // id: latestProfileEducation.id, + // degree: latestProfileEducation.degree, + // country: latestProfileEducation.country, + // duration: latestProfileEducation.duration, + // durationYear: latestProfileEducation.durationYear, + // field: latestProfileEducation.field, + // finishDate: latestProfileEducation.finishDate, + // fundName: latestProfileEducation.fundName, + // gpa: latestProfileEducation.gpa, + // institute: latestProfileEducation.institute, + // other: latestProfileEducation.other, + // startDate: latestProfileEducation.startDate, + // endDate: latestProfileEducation.endDate, + // educationLevel: latestProfileEducation.educationLevel, + // positionPath: latestProfileEducation.positionPath, + // positionPathId: latestProfileEducation.positionPathId, + // isDate: latestProfileEducation.isDate, + // isEducation: latestProfileEducation.isEducation, + // note: latestProfileEducation.note, + // } + // : null, + }; + }), + ); + + return new HttpSuccess({ data: mapDataProfile, total }); + } + + /** + * API ค้นหาผู้บังคับบัญชา + * + * @summary ORG_069 - ค้นหาผู้บังคับบัญชา (ADMIN) #75 + * + */ + @Get("search/commander") + async searchCommander(@Request() request: { user: Record }) { + let fullName_: any = {}; + let position_: any = {}; + let commanderAboveFullname_: any = {}; + let commanderAbovePosition_: any = {}; + let commanderFullname_: any = {}; + let commanderPosition_: any = {}; + + const findProfile = await this.profileRepo.findOne({ + where: { keycloak: request.user.sub }, + }); + + const findRevision = await this.orgRevisionRepo.findOne({ + where: { + orgRevisionIsCurrent: true, + }, + }); + + const findPosMaster = await this.posMasterRepo.findOne({ + where: { + current_holderId: findProfile?.id, + orgRevisionId: findRevision?.id, + }, + }); + + let node = 4; + let childId = findPosMaster?.orgChild4Id; + let condition: any = { orgChild4Id: childId }; + + if (findPosMaster?.orgChild4Id == null && findPosMaster?.orgChild3Id != null) { + node = 3; + childId = findPosMaster?.orgChild3Id; + condition = { orgChild3Id: childId, orgChild4Id: IsNull() }; + } else if (findPosMaster?.orgChild3Id == null && findPosMaster?.orgChild2Id != null) { + node = 2; + childId = findPosMaster?.orgChild2Id; + condition = { orgChild2Id: childId, orgChild3Id: IsNull() }; + } else if (findPosMaster?.orgChild2Id == null && findPosMaster?.orgChild1Id != null) { + node = 1; + childId = findPosMaster?.orgChild1Id; + condition = { orgChild1Id: childId, orgChild2Id: IsNull() }; + } else if (findPosMaster?.orgChild1Id == null) { + node = 0; + childId = findPosMaster?.orgRootId; + condition = { orgRootId: childId, orgChild1Id: IsNull() }; + } + + const findCmd = await this.posMasterRepo.findOne({ + where: { + current_holderId: Not(IsNull()) || Not(""), + orgRevisionId: findRevision?.id, + ...condition, + }, + relations: ["current_holder"], + order: { posMasterOrder: "ASC" }, + }); + let findOSAB: EmployeePosMaster | null = null; + let findTSAB: EmployeePosMaster | null = null; + //หาผู้บังคับบัญชาที่เหนือขึ้นไปอีก 1 ขั้น + if (node !== 0) { + findOSAB = await AppDataSource.getRepository(EmployeePosMaster) + .createQueryBuilder("posMaster") + .leftJoinAndSelect("posMaster.current_holder", "current_holder") + .where("posMaster.current_holderId IS NOT NULL") + .andWhere("posMaster.orgRevisionId = :revisionId", { revisionId: findRevision?.id }) + .andWhere( + new Brackets((qb) => { + if (node === 4) { + qb.andWhere("posMaster.orgChild4Id IS NULL"); + qb.andWhere("posMaster.orgChild3Id = :childId", { + childId: findPosMaster?.orgChild3Id, + }); + } else if (node === 3) { + qb.andWhere("posMaster.orgChild3Id IS NULL"); + qb.andWhere("posMaster.orgChild2Id = :childId", { + childId: findPosMaster?.orgChild2Id, + }); + } else if (node === 2) { + qb.andWhere("posMaster.orgChild2Id IS NULL"); + qb.andWhere("posMaster.orgChild1Id = :childId", { + childId: findPosMaster?.orgChild1Id, + }); + } else if (node === 1) { + qb.andWhere("posMaster.orgChild1Id IS NULL"); + qb.andWhere("posMaster.orgRootId = :childId", { childId: findPosMaster?.orgRootId }); + } + }), + ) + .orderBy("posMaster.posMasterOrder", "ASC") + .getOne(); + } + + //หาผู้บังคับบัญชาที่เหนือขึ้นไปอีก 2 ขั้น + if (node !== 0 && node !== 1) { + findTSAB = await AppDataSource.getRepository(EmployeePosMaster) + .createQueryBuilder("posMaster") + .leftJoinAndSelect("posMaster.current_holder", "current_holder") + .where("posMaster.current_holderId IS NOT NULL") + .andWhere("posMaster.orgRevisionId = :revisionId", { revisionId: findRevision?.id }) + .andWhere( + new Brackets((qb) => { + if (node === 4) { + qb.andWhere("posMaster.orgChild3Id IS NULL"); + qb.andWhere("posMaster.orgChild2Id = :childId", { + childId: findPosMaster?.orgChild2Id, + }); + } else if (node === 3) { + qb.andWhere("posMaster.orgChild2Id IS NULL"); + qb.andWhere("posMaster.orgChild1Id = :childId", { + childId: findPosMaster?.orgChild1Id, + }); + } else if (node === 2) { + qb.andWhere("posMaster.orgChild1Id IS NULL"); + qb.andWhere("posMaster.orgRootId = :childId", { + childId: findPosMaster?.orgRootId, + }); + } + }), + ) + .orderBy("posMaster.posMasterOrder", "ASC") + .getOne(); + } + fullName_ = + (findProfile?.prefix ?? "") + + (findProfile?.firstName ?? "") + + " " + + (findProfile?.lastName ?? ""); + position_ = findProfile?.position ?? ""; + commanderFullname_ = + (findCmd?.current_holder?.prefix ?? "") + + (findCmd?.current_holder?.firstName ?? "") + + " " + + (findCmd?.current_holder?.lastName ?? ""); + commanderPosition_ = findCmd?.current_holder?.position ?? ""; + commanderAboveFullname_ = + (findOSAB?.current_holder?.prefix ?? "") + + (findOSAB?.current_holder?.firstName ?? "") + + " " + + (findOSAB?.current_holder?.lastName ?? ""); + commanderAbovePosition_ = findOSAB?.current_holder?.position ?? ""; + + if (findCmd?.current_holderId == findProfile?.id) { + commanderFullname_ = + (findOSAB?.current_holder?.prefix ?? "") + + (findOSAB?.current_holder?.firstName ?? "") + + " " + + (findOSAB?.current_holder?.lastName ?? ""); + commanderPosition_ = findOSAB?.current_holder?.position ?? ""; + commanderAboveFullname_ = + (findTSAB?.current_holder?.prefix ?? "") + + (findTSAB?.current_holder?.firstName ?? "") + + " " + + (findTSAB?.current_holder?.lastName ?? ""); + commanderAbovePosition_ = findTSAB?.current_holder?.position ?? ""; + + const formattedDataTSAB = { + fullname: fullName_, + position: position_, + commanderAboveFullname: commanderAboveFullname_, + commanderAbovePosition: commanderAbovePosition_, + commanderFullname: commanderFullname_, + commanderPosition: commanderPosition_, + }; + return new HttpSuccess(formattedDataTSAB); + } + + const formattedData = { + fullname: fullName_, + position: position_, + commanderAboveFullname: commanderAboveFullname_, + commanderAbovePosition: commanderAbovePosition_, + commanderFullname: commanderFullname_, + commanderPosition: commanderPosition_, + }; + return new HttpSuccess(formattedData); + } + + /** + * API บันทึกตำแหน่งลูกจ้างชั่วคราว + * + * @summary บันทึกตำแหน่งลูกจ้างชั่วคราว (ADMIN) + * + * @param {string} id Id ทะเบียนประวัติลูกจ้างชั่วคราว + */ + @Put("position/{id}") + async positionProfileEmployee( + @Request() request: RequestWithUser, + @Path() id: string, + @Body() body: UpdatePositionTempProfileEmployee, + ) { + if (body.posLevelId === "") body.posLevelId = null; + if (body.posTypeId === "") body.posTypeId = null; + + if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้"); + } + if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้"); + } + const profileEmp = await this.profileRepo.findOneBy({ id }); + if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้"); + + switch (body.node) { + case 0: { + const data = await this.orgRootRepository.findOne({ + where: { id: body.nodeId }, + }); + if (data != null) { + profileEmp.rootIdTemp = data.id; + profileEmp.rootTemp = data.orgRootName; + profileEmp.rootShortNameTemp = data.orgRootShortName; + } + } + case 1: { + const data = await this.child1Repository.findOne({ + where: { id: body.nodeId }, + relations: ["orgRoot"], + }); + if (data != null) { + profileEmp.rootIdTemp = data.orgRoot.id; + profileEmp.rootTemp = data.orgRoot.orgRootName; + profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName; + profileEmp.child1IdTemp = data.id; + profileEmp.child1Temp = data.orgChild1Name; + profileEmp.child1ShortNameTemp = data.orgChild1ShortName; + } + } + case 2: { + const data = await this.child2Repository.findOne({ + where: { id: body.nodeId }, + relations: ["orgRoot", "orgChild1"], + }); + if (data != null) { + profileEmp.rootIdTemp = data.orgRoot.id; + profileEmp.rootTemp = data.orgRoot.orgRootName; + profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName; + profileEmp.child1IdTemp = data.orgChild1.id; + profileEmp.child1Temp = data.orgChild1.orgChild1Name; + profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName; + profileEmp.child2IdTemp = data.id; + profileEmp.child2Temp = data.orgChild2Name; + profileEmp.child2ShortNameTemp = data.orgChild2ShortName; + } + } + case 3: { + const data = await this.child3Repository.findOne({ + where: { id: body.nodeId }, + relations: ["orgRoot", "orgChild1", "orgChild2"], + }); + if (data != null) { + profileEmp.rootIdTemp = data.orgRoot.id; + profileEmp.rootTemp = data.orgRoot.orgRootName; + profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName; + profileEmp.child1IdTemp = data.orgChild1.id; + profileEmp.child1Temp = data.orgChild1.orgChild1Name; + profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName; + profileEmp.child2IdTemp = data.orgChild2.id; + profileEmp.child2Temp = data.orgChild2.orgChild2Name; + profileEmp.child2ShortNameTemp = data.orgChild2.orgChild2ShortName; + profileEmp.child3IdTemp = data.id; + profileEmp.child3Temp = data.orgChild3Name; + profileEmp.child3ShortNameTemp = data.orgChild3ShortName; + } + } + case 4: { + const data = await this.child4Repository.findOne({ + where: { id: body.nodeId }, + relations: ["orgRoot", "orgChild1", "orgChild2", "orgChild3"], + }); + if (data != null) { + profileEmp.rootIdTemp = data.orgRoot.id; + profileEmp.rootTemp = data.orgRoot.orgRootName; + profileEmp.rootShortNameTemp = data.orgRoot.orgRootShortName; + profileEmp.child1IdTemp = data.orgChild1.id; + profileEmp.child1Temp = data.orgChild1.orgChild1Name; + profileEmp.child1ShortNameTemp = data.orgChild1.orgChild1ShortName; + profileEmp.child2IdTemp = data.orgChild2.id; + profileEmp.child2Temp = data.orgChild2.orgChild2Name; + profileEmp.child2ShortNameTemp = data.orgChild2.orgChild2ShortName; + profileEmp.child3IdTemp = data.orgChild3.id; + profileEmp.child3Temp = data.orgChild3.orgChild3Name; + profileEmp.child3ShortNameTemp = data.orgChild3.orgChild3ShortName; + profileEmp.child4IdTemp = data.id; + profileEmp.child4Temp = data.orgChild4Name; + profileEmp.child4ShortNameTemp = data.orgChild4ShortName; + } + } + } + + profileEmp.lastUpdateUserId = request.user.sub; + profileEmp.lastUpdateFullName = request.user.name; + profileEmp.nodeTemp = String(body.node); + profileEmp.nodeIdTemp = body.nodeId; + profileEmp.orgRevisionIdTemp = body.orgRevisionId; + profileEmp.posmasterIdTemp = body.posmasterId; + profileEmp.posMasterNoTemp = body.posMasterNo; + profileEmp.positionIdTemp = body.positionId; + profileEmp.positionTemp = body.position; + profileEmp.positionFieldTemp = body.positionField; + profileEmp.posTypeIdTemp = String(body.posTypeId); + profileEmp.posTypeNameTemp = body.posTypeName; + profileEmp.posLevelIdTemp = String(body.posLevelId); + profileEmp.posLevelNameTemp = body.posLevelName; + profileEmp.statusTemp = "PENDING"; + this.profileRepo.merge(profileEmp, body); + await this.profileRepo.save(profileEmp); + return new HttpSuccess(); + } + + /** + * API เช็คเลขบัตร + * + * @summary เช็คเลขบัตร (ADMIN) + * + * @param {string} id Id ทะเบียนประวัติ + */ + @Put("citizenId/{id}") + async checkCitizenIdProfile( + @Path() id: string, + @Body() + requestBody: { citizenId: string }, + ) { + const profile = await this.profileRepo.findOne({ + where: { id: Not(id), citizenId: requestBody.citizenId }, + }); + if (profile) { + throw new HttpError( + HttpStatus.INTERNAL_SERVER_ERROR, + "เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว", + ); + } + return new HttpSuccess(); + } + + /** + * API ค้นหาข้อมูลทะเบียนประวัติ ทดลองปฏิบัติหน้าที่ราชการ + * + * @summary ค้นหาข้อมูลทะเบียนประวัติ ทดลองปฏิบัติหน้าที่ราชการ (ADMIN) + * + */ + @Post("probation") + async getProfileBySearchKeywordProbation( + @Body() + body: { + page: number; + pageSize: number; + keyword?: string; + }, + ) { + const [findProfile, total] = await AppDataSource.getRepository(ProfileEmployee) + .createQueryBuilder("profile") + .leftJoinAndSelect("profile.posLevel", "posLevel") + .leftJoinAndSelect("profile.current_holders", "current_holders") + .leftJoinAndSelect("current_holders.orgRevision", "orgRevision") + .leftJoinAndSelect("current_holders.orgRoot", "orgRoot") + .leftJoinAndSelect("current_holders.orgChild1", "orgChild1") + .leftJoinAndSelect("current_holders.orgChild2", "orgChild2") + .leftJoinAndSelect("current_holders.orgChild3", "orgChild3") + .leftJoinAndSelect("current_holders.orgChild4", "orgChild4") + .where("profile.prefix LIKE :keyword", { keyword: `%${body.keyword}%` }) + .orWhere("profile.firstName LIKE :keyword", { keyword: `%${body.keyword}%` }) + .orWhere("profile.lastName LIKE :keyword", { keyword: `%${body.keyword}%` }) + .orWhere("profile.position LIKE :keyword", { keyword: `%${body.keyword}%` }) + .orWhere("posLevel.posLevelName LIKE :keyword", { keyword: `%${body.keyword}%` }) + .orderBy("profile.citizenId", "ASC") + .skip((body.page - 1) * body.pageSize) + .take(body.pageSize) + .getManyAndCount(); + + const orgRevisionActive = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }, + }); + + const mapDataProfile = await Promise.all( + findProfile.map(async (item: ProfileEmployee) => { + return { + id: item.id, + rank: item.rank, + prefix: item.prefix, + firstName: item.firstName, + lastName: item.lastName, + position: item.position, + idcard: item.citizenId, + posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName, + isProbation: item.isProbation, + orgRootName: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot + ?.orgRootName == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgRoot + ?.orgRootName, + orgChild1Name: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1 == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild1 + ?.orgChild1Name == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) + ?.orgChild1?.orgChild1Name, + orgChild2Name: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2 == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild2 + ?.orgChild2Name == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) + ?.orgChild2?.orgChild2Name, + orgChild3Name: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3 == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild3 + ?.orgChild3Name == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) + ?.orgChild3?.orgChild3Name, + orgChild4Name: + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) == null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4 == + null || + item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id)?.orgChild4 + ?.orgChild4Name == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == orgRevisionActive?.id) + ?.orgChild4?.orgChild4Name, + }; + }), + ); + + return new HttpSuccess({ data: mapDataProfile, total }); + } + + /** + * API รายชื่อราชการที่เลื่อนเงินเดือน + * + * @summary ORG_072 - รายชื่อราชการที่เลื่อนเงินเดือน #76 + * + */ + @Post("salary/gen") + async salaryGen( + @Body() + body: { + page: number; + pageSize: number; + keyword?: string; + rootId?: string; + year: number; + period: string; + }, + ) { + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + if (!findRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + } + + const [findPosMaster, total] = await AppDataSource.getRepository(EmployeePosMaster) + .createQueryBuilder("employeePosMaster") + .leftJoinAndSelect("employeePosMaster.current_holder", "current_holder") + .leftJoinAndSelect("employeePosMaster.orgRoot", "orgRoot") + .leftJoinAndSelect("employeePosMaster.orgChild1", "orgChild1") + .leftJoinAndSelect("employeePosMaster.orgChild2", "orgChild2") + .leftJoinAndSelect("employeePosMaster.orgChild3", "orgChild3") + .leftJoinAndSelect("employeePosMaster.orgChild4", "orgChild4") + .leftJoinAndSelect("employeePosMaster.positions", "positions") + .leftJoinAndSelect("current_holder.profileSalarys", "profileSalarys") + .leftJoinAndSelect("current_holder.profileDisciplines", "profileDisciplines") + .leftJoinAndSelect("current_holder.posLevel", "posLevel") + .leftJoinAndSelect("current_holder.posType", "posType") + .where((qb) => { + if (body.rootId) { + qb.andWhere("employeePosMaster.orgRootId = :rootId", { rootId: body.rootId }); + } + qb.andWhere("employeePosMaster.current_holderId IS NOT NULL"); + qb.andWhere("employeePosMaster.orgRevisionId = :orgRevisionId", { + orgRevisionId: findRevision?.id, + }); + }) + .andWhere( + new Brackets((qb) => { + qb.where( + body.keyword != null && body.keyword != "" + ? "current_holder.prefix LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "current_holder.firstName LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "current_holder.lastName LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "current_holder.position LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + + .orWhere( + body.keyword != null && body.keyword != "" + ? "current_holder.citizenId LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "posType.posTypeName LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ) + .orWhere( + body.keyword != null && body.keyword != "" + ? "posLevel.posLevelName LIKE :keyword" + : "1=1", + { + keyword: `%${body.keyword}%`, + }, + ); + }), + ) + .orderBy("current_holder.citizenId", "ASC") + .skip((body.page - 1) * body.pageSize) + .take(body.pageSize) + .getManyAndCount(); + if (!findPosMaster) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. PosMaster"); + } + + const formattedData = findPosMaster.map((item) => { + let orgShortName = ""; + + if (item.orgChild1Id === null) { + orgShortName = item.orgRoot?.orgRootShortName; + } else if (item.orgChild2Id === null) { + orgShortName = item.orgChild1?.orgChild1ShortName; + } else if (item.orgChild3Id === null) { + orgShortName = item.orgChild2?.orgChild2ShortName; + } else if (item.orgChild4Id === null) { + orgShortName = item.orgChild3?.orgChild3ShortName; + } else { + orgShortName = item.orgChild4?.orgChild4ShortName; + } + + const amount = + item.current_holder == null || item.current_holder.profileSalarys.length == 0 + ? null + : item.current_holder.profileSalarys.sort((a: any, b: any) => b.date - a.date)[0].amount; + let datePeriodStart = new Date( + `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, "0")}-${String(new Date().getDate() + 1).padStart(2, "0")}T00:00:00.000Z`, + ); + let datePeriodEnd = new Date( + `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, "0")}-${String(new Date().getDate() + 1).padStart(2, "0")}T00:00:00.000Z`, + ); + if (body.period.toLocaleUpperCase() == "APR") { + datePeriodStart = new Date(`${body.year}-03-31T00:00:00.000Z`); + datePeriodEnd = new Date(`${body.year}-03-31T00:00:00.000Z`); + } + if (body.period.toLocaleUpperCase() == "OCT") { + datePeriodStart = new Date(`${body.year}-09-30T00:00:00.000Z`); + datePeriodEnd = new Date(`${body.year}-09-30T00:00:00.000Z`); + } + datePeriodStart = new Date( + new Date(datePeriodStart.setDate(datePeriodStart.getDate() + 1)).setMonth( + datePeriodStart.getMonth() - 6, + ), + ); + // const specialPosition = item.positions.find( + // (position) => position.positionIsSelected === true, + // ); + // const isSpecial = specialPosition ? specialPosition.isSpecial : null; + + return { + profileId: item.current_holder.id, + salaryLevel: item.current_holder.salaryLevel, + group: item.current_holder.group, + rank: item.current_holder.rank, + prefix: item.current_holder.prefix, + firstName: item.current_holder.firstName, + lastName: item.current_holder.lastName, + citizenId: item.current_holder.citizenId, + posMasterNoPrefix: item.posMasterNoPrefix, + posMasterNo: item.posMasterNo, + posMasterNoSuffix: item.posMasterNoSuffix, + orgShortName: orgShortName, + position: item.current_holder.position, + posType: + item.current_holder.posType == null ? null : item.current_holder.posType.posTypeName, + posTypeShort: + item.current_holder.posType == null ? null : item.current_holder.posType.posTypeShortName, + posLevel: + item.current_holder.posLevel == null ? null : item.current_holder.posLevel.posLevelName, + amount: amount ? amount : null, + rootId: item.orgRootId, + root: item.orgRoot?.orgRootName ? item.orgRoot.orgRootName : null, + child1Id: item.orgChild1Id, + child1: item.orgChild1?.orgChild1Name ? item.orgChild1.orgChild1Name : null, + child2Id: item.orgChild2Id, + child2: item.orgChild2?.orgChild2Name ? item.orgChild2.orgChild2Name : null, + child3Id: item.orgChild3Id, + child3: item.orgChild3?.orgChild3Name ? item.orgChild3.orgChild3Name : null, + child4Id: item.orgChild4Id, + child4: item.orgChild4?.orgChild4Name ? item.orgChild4.orgChild4Name : null, + result: null, + duration: null, + isPunish: + item.current_holder.profileDisciplines.filter( + (x: any) => + new Date( + `${new Date(x.date).getFullYear()}-${String(new Date(x.date).getMonth() + 1).padStart(2, "0")}-${String(new Date(x.date).getDate() + 1).padStart(2, "0")}T00:00:00.000Z`, + ) >= datePeriodStart && + new Date( + `${new Date(x.date).getFullYear()}-${String(new Date(x.date).getMonth() + 1).padStart(2, "0")}-${String(new Date(x.date).getDate() + 1).padStart(2, "0")}T00:00:00.000Z`, + ) <= datePeriodEnd, + ).length > 0 + ? true + : false, + isSuspension: item.current_holder.dateRetire == null ? false : true, + isAbsent: false, + isLeave: false, + isRetired: + item.current_holder.birthDate == null || + calculateRetireDate(item.current_holder.birthDate).getFullYear() != body.year + ? false + : true, + isSpecial: false, + }; + }); + + return new HttpSuccess({ data: formattedData, total: total }); + } + + /** + * API ข้อมูลทะเบียนประวัติตาม keycloak by revisionId + * + * @summary ข้อมูลทะเบียนประวัติตาม keycloak by revisionId (ADMIN) + * + */ + @Get("keycloak/position/{revisionId}") + async getProfileByKeycloakByRevision( + @Path() revisionId: string, + @Request() request: { user: Record }, + ) { + const profile = await this.profileRepo.findOne({ + where: { keycloak: request.user.sub }, + relations: ["posLevel", "posType", "current_holders", "current_holders.orgRoot"], + }); + if (!profile) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ"); + } + + const _profile = { + profileId: profile.id, + rank: profile.rank, + prefix: profile.prefix, + firstName: profile.firstName, + lastName: profile.lastName, + citizenId: profile.citizenId, + position: profile.position, + posLevelName: profile.posLevel == null ? null : profile.posLevel.posLevelName, + posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank, + posLevelId: profile.posLevel == null ? null : profile.posLevel.id, + posTypeName: profile.posType == null ? null : profile.posType.posTypeName, + posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank, + posTypeId: profile.posType == null ? null : profile.posType.id, + rootId: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRootId, + root: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgRoot.orgRootName, + child1Id: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1Id, + child1: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild1 + .orgChild1Name, + child2Id: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2Id, + child2: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild2 + .orgChild2Name, + child3Id: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3Id, + child3: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild3 + .orgChild3Name, + child4Id: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4Id, + child4: + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId) == null || + profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == revisionId)?.orgChild4 + .orgChild4Name, + }; + return new HttpSuccess(_profile); + } + + /** + * API ข้อมูลบุลคลที่มีอายุเกษียณราชการตามปี + * + * @summary ข้อมูลบุลคลที่มีอายุเกษียณราชการตามปี + * + */ + @Get("profileid/retire/{year}") + async getProfileByRetireYear(@Path() year: number) { + const profiles = await this.profileRepo + .createQueryBuilder("profileEmployee") + .leftJoinAndSelect("profileEmployee.posLevel", "posLevel") + .leftJoinAndSelect("profileEmployee.posType", "posType") + .leftJoinAndSelect("profileEmployee.current_holders", "current_holders") + .leftJoinAndSelect("current_holders.orgRoot", "orgRoot") + .leftJoinAndSelect("current_holders.orgChild1", "orgChild1") + .leftJoinAndSelect("current_holders.orgChild2", "orgChild2") + .leftJoinAndSelect("current_holders.orgChild3", "orgChild3") + .leftJoinAndSelect("current_holders.orgChild4", "orgChild4") + .leftJoinAndSelect("current_holders.positions", "positions") + // .leftJoinAndSelect("positions.posExecutive", "posExecutive") + .where("YEAR(profileEmployee.dateRetire) = :year", { year }) + .getMany(); + + if (!profiles || profiles.length === 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลที่มีอายุเกษียณราชการในปีนี้"); + } + + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + if (!findRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + } + const formattedData = profiles.map((item) => { + const posMaster = + item.current_holders == null || + item.current_holders.length == 0 || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id); + const position = + posMaster == null || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.positions == null || + item.current_holders?.find((x) => x.orgRevisionId == findRevision.id)?.positions.length == + 0 || + item.current_holders + .find((x) => x.orgRevisionId == findRevision.id) + ?.positions?.find((position) => position.positionIsSelected == true) == null + ? null + : item.current_holders + .find((x) => x.orgRevisionId == findRevision.id) + ?.positions?.find((position) => position.positionIsSelected == true); + // const posExecutive = + // position == null || + // item.current_holders + // .find((x) => x.orgRevisionId == findRevision.id) + // ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive == + // null || + // item.current_holders + // .find((x) => x.orgRevisionId == findRevision.id) + // ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive + // ?.posExecutiveName == null + // ? null + // : item.current_holders + // .find((x) => x.orgRevisionId == findRevision.id) + // ?.positions?.find((position) => position.positionIsSelected == true)?.posExecutive + // .posExecutiveName; + // const posExecutiveId = + // position == null || position.posExecutive == null ? null : position.posExecutive.id; + + const shortName = + item.current_holders.length == 0 + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 != + null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 != + null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2 != + null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgChild1 != null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgRoot != null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : null; + const root = + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot; + const child1 = + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1 == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1; + const child2 = + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2 == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2; + const child3 = + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3; + const child4 = + item.current_holders == null || + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 == null + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4; + + let node = null; + let nodeId = null; + let nodeShortName = null; + + if (root) { + node = 0; + nodeId = root.id; + nodeShortName = root.orgRootShortName; + } + if (child1) { + node = 1; + nodeId = child1.id; + nodeShortName = child1.orgChild1ShortName; + } + if (child2) { + node = 2; + nodeId = child2.id; + nodeShortName = child2.orgChild2ShortName; + } + if (child3) { + node = 3; + nodeId = child3.id; + nodeShortName = child3.orgChild3ShortName; + } + if (child4) { + node = 4; + nodeId = child4.id; + nodeShortName = child4.orgChild4ShortName; + } + + return { + profileId: item.id, + prefix: item.prefix, + rank: item.rank, + firstName: item.firstName, + lastName: item.lastName, + citizenId: item.citizenId, + root: root == null ? null : root.orgRootName, + rootId: root == null ? null : root.id, + rootShortName: root == null ? null : root.orgRootShortName, + child1: child1 == null ? null : child1.orgChild1Name, + child1Id: child1 == null ? null : child1.id, + child1ShortName: child1 == null ? null : child1.orgChild1ShortName, + child2: child2 == null ? null : child2.orgChild2Name, + child2Id: child2 == null ? null : child2.id, + child2ShortName: child2 == null ? null : child2.orgChild2ShortName, + child3: child3 == null ? null : child3.orgChild3Name, + child3Id: child3 == null ? null : child3.id, + child3ShortName: child3 == null ? null : child3.orgChild3ShortName, + child4: child4 == null ? null : child4.orgChild4Name, + child4Id: child4 == null ? null : child4.id, + child4ShortName: child4 == null ? null : child4.orgChild4ShortName, + dateRetire: item.dateRetire, + posLevelId: item.posLevel == null ? null : item.posLevel.id, + posLevelName: item.posLevel == null ? null : item.posLevel.posLevelName, + posLevelRank: item.posLevel == null ? null : item.posLevel.posLevelRank, + posTypeId: item.posType == null ? null : item.posType.id, + posTypeName: item.posType == null ? null : item.posType.posTypeName, + posTypeRank: item.posType == null ? null : item.posType.posTypeRank, + posNo: shortName, + posMasterNo: posMaster == null ? null : posMaster.posMasterNo, + position: item.position, + // posExecutiveId: posExecutiveId, + // posExecutiveName: posExecutive, + node: node, + nodeId: nodeId, + nodeShortName: nodeShortName, + }; + }); + return new HttpSuccess(formattedData); + } + + /** + * API อัพเดทเกษียณ + * + * @summary อัพเดทเกษียณ (ADMIN) + * + * @param {string} id Id ทะเบียนประวัติ + */ + @Post("leave/{id}") + async updateLeaveUser( + @Path() id: string, + @Body() + requestBody: { isLeave: boolean; leaveReason: string; dateLeave: Date }, + @Request() request: { user: Record }, + ) { + const profile = await this.profileRepo.findOne({ + where: { id: id }, + }); + if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + profile.isLeave = requestBody.isLeave; + profile.leaveReason = requestBody.leaveReason; + profile.dateLeave = requestBody.dateLeave; + if (requestBody.isLeave == true) { + await removeProfileInOrganize(profile.id, "EMPLOYEE"); + } + await this.profileRepo.save(profile); + + const profileSalary = await this.salaryRepository.findOne({ + where: { profileEmployeeId: id }, + order: { createdAt: "DESC" }, + }); + + return new HttpSuccess(); + } + + /** + * API แก้ไขข้อมูลลูกจ้างชั่วคราว + * + * @summary แก้ไขข้อมูลลูกจ้างชั่วคราว (ADMIN) + * + * @param {string} profileEmployeeId profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว + */ + @Put("information/{profileEmployeeId}") + async ProfileEmployeeInformation( + @Request() request: RequestWithUser, + @Path() profileEmployeeId: string, + @Body() body: UpdateInformationProfileEmployee, + ) { + const profileEmp = await this.profileRepo.findOneBy({ id: profileEmployeeId }); + if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้"); + + const history = new ProfileEmployeeInformationHistory(); + Object.assign(history, { ...profileEmp, id: undefined }); + Object.assign(profileEmp, body); + history.profileEmployeeId = profileEmployeeId; + history.lastUpdateFullName = request.user.name; + history.lastUpdateUserId = request.user.sub; + profileEmp.lastUpdateUserId = request.user.sub; + profileEmp.lastUpdateFullName = request.user.name; + + await Promise.all([ + this.profileRepo.save(profileEmp), + this.informationHistoryRepository.save(history), + ]); + return new HttpSuccess(); + } + + /** + * API ข้อมูลลูกจ้างชั่วคราว + * + * @summary ข้อมูลลูกจ้างชั่วคราว (ADMIN) + * + * @param {string} profileEmployeeId profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว + */ + @Get("information/{profileEmployeeId}") + async getInformationById(@Path() profileEmployeeId: string) { + const profileInformation = await this.profileRepo.findOne({ + where: { id: profileEmployeeId }, + }); + if (!profileInformation) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const mapData = { + id: profileInformation.id, + positionEmployeeGroupId: profileInformation.positionEmployeeGroupId, + positionEmployeeLineId: profileInformation.positionEmployeeLineId, + positionEmployeePositionId: profileInformation.positionEmployeePositionId, + employeeOc: profileInformation.employeeOc, + employeeTypeIndividual: profileInformation.employeeTypeIndividual, + employeeWage: profileInformation.employeeWage, + employeeMoneyIncrease: profileInformation.employeeMoneyIncrease, + employeeMoneyAllowance: profileInformation.employeeMoneyAllowance, + employeeMoneyEmployee: profileInformation.employeeMoneyEmployee, + employeeMoneyEmployer: profileInformation.employeeMoneyEmployer, + }; + return new HttpSuccess(mapData); + } + + /** + * API ประวัติการแก้ไขข้อมูลลูกจ้างชั่วคราว + * + * @summary ประวัติการแก้ไขข้อมูลลูกจ้างชั่วคราว (ADMIN) + * + * @param {string} profileEmployeeId profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว + */ + @Get("information/history/{profileEmployeeId}") + async getInformationHistory(@Path() profileEmployeeId: string) { + const profileInformation = await this.profileRepo.find({ + relations: { + information_histories: true, + }, + where: { id: profileEmployeeId }, + }); + if (!profileInformation) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const mapData = profileInformation + .flatMap((profile) => profile.information_histories) + .map((history) => ({ + id: history.id, + positionEmployeeGroupId: history.positionEmployeeGroupId, + positionEmployeeLineId: history.positionEmployeeLineId, + positionEmployeePositionId: history.positionEmployeePositionId, + employeeOc: history.employeeOc, + employeeTypeIndividual: history.employeeTypeIndividual, + employeeWage: history.employeeWage, + employeeMoneyIncrease: history.employeeMoneyIncrease, + employeeMoneyAllowance: history.employeeMoneyAllowance, + employeeMoneyEmployee: history.employeeMoneyEmployee, + employeeMoneyEmployer: history.employeeMoneyEmployer, + createdAt: history.createdAt, + createdUserId: history.createdUserId, + createdFullName: history.createdFullName, + lastUpdatedAt: history.lastUpdatedAt, + lastUpdateUserId: history.lastUpdateUserId, + lastUpdateFullName: history.lastUpdateFullName, + })); + return new HttpSuccess(mapData); + } + + /** + * API รายการข้อมูลการจ้าง + * + * @summary รายการข้อมูลการจ้าง + * + * @param {string} profileEmployeeId profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว + */ + @Get("employment/{profileEmployeeId}") + async ProfileEmployeeEmployment(@Path() profileEmployeeId: string) { + const employment = await this.employmentRepository.find({ + where: { profileEmployeeId: profileEmployeeId }, + order: { createdAt: "ASC" }, + }); + const mapData = employment.map((employment) => ({ + id: employment.id, + date: employment.date, + command: employment.command, + })); + return new HttpSuccess(mapData); + } + + /** + * API รายละเอียดข้อมูลการจ้าง + * + * @summary รายละเอียดข้อมูลการจ้าง + * + * @param {string} id Id ข้อมูลการจ้าง + */ + @Get("employment/id/{id}") + async GetEmploymentById(@Path() id: string) { + const employment = await this.employmentRepository.findOne({ + where: { id: id }, + }); + return new HttpSuccess(employment); + } + + /** + * API ประวัติของข้อมูลการจ้าง + * + * @summary ประวัติของข้อมูลการจ้าง + * + * @param {string} id Id ข้อมูลการจ้าง + */ + @Get("employment/history/{id}") + async GetHistoryEmploymentById(@Path() id: string) { + const employmentHistory = await this.employmentHistoryRepository.find({ + where: { profileEmployeeEmploymentId: id }, + order: { lastUpdatedAt: "ASC" }, + }); + return new HttpSuccess(employmentHistory); + } + + /** + * API เพิ่มข้อมูลการจ้าง + * + * @summary เพิ่มข้อมูลการจ้าง + * + * @param {string} profileEmployeeId profileEmployeeId ทะเบียนประวัติลูกจ้างชั่วคราว + */ + @Post("employment/{profileEmployeeId}") + async CreateEmployment( + @Path() profileEmployeeId: string, + @Body() body: CreateEmploymentProfileEmployee, + @Request() request: RequestWithUser, + ) { + const profile = await this.profileRepo.findOne({ + where: { id: profileEmployeeId }, + }); + if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const employment = new ProfileEmployeeEmployment(); + // const history = new ProfileEmployeeEmploymentHistory(); + Object.assign(employment, body); + employment.profileEmployeeId = profileEmployeeId; + employment.createdUserId = request.user.sub; + employment.createdFullName = request.user.name; + employment.lastUpdateUserId = request.user.sub; + employment.lastUpdateFullName = request.user.name; + await this.employmentRepository.save(employment); + // if (employment) { + // Object.assign(history, { ...employment, id: undefined }); + // history.profileEmployeeEmploymentId = employment.id; + // history.createdUserId = request.user.sub; + // history.createdFullName = request.user.name; + // history.lastUpdateFullName = request.user.name; + // history.lastUpdateUserId = request.user.sub; + // await this.employmentHistoryRepository.save(history); + // } + return new HttpSuccess(); + } + + /** + * API ลบข้อมูลการจ้าง + * + * @summary ลบข้อมูลการจ้าง (ADMIN) + * + * @param {string} id Id ข้อมูลการจ้าง + */ + @Delete("employment/{id}") + async DeleteEmployment(@Path() id: string) { + await this.employmentHistoryRepository.delete({ + profileEmployeeEmploymentId: id, + }); + + const result = await this.employmentRepository.delete({ id }); + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + return new HttpSuccess(); + } + + /** + * API แก้ไขข้อมูลการจ้าง + * + * @summary แก้ไขข้อมูลการจ้าง (ADMIN) + * + * @param {string} id Id ข้อมูลการจ้าง + */ + @Put("employment/{id}") + async UpdateEmployment( + @Request() request: RequestWithUser, + @Path() id: string, + @Body() body: UpdateEmploymentProfileEmployee, + ) { + const employment = await this.employmentRepository.findOneBy({ id }); + if (!employment) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileEmployeeEmploymentHistory(); + Object.assign(history, { ...employment, id: undefined }); + Object.assign(employment, body); + + employment.lastUpdateUserId = request.user.sub; + employment.lastUpdateFullName = request.user.name; + history.profileEmployeeEmploymentId = id; + history.lastUpdateFullName = request.user.name; + history.lastUpdateUserId = request.user.sub; + + await Promise.all([ + this.employmentRepository.save(employment), + this.employmentHistoryRepository.save(history), + ]); + + return new HttpSuccess(); + } + + /** + * API ออกคำสั่งลูกจ้าง + * + * @summary ORG_038 - ออกคำสั่งลูกจ้าง (ADMIN) # + * + */ + @Post("report") + async sendReport(@Request() request: RequestWithUser, @Body() requestBody: { id: string[] }) { + const profiles = await this.profileRepo.find({ where: { id: In(requestBody.id) } }); + + const _profiles = await Promise.all( + profiles.map(async (item: any) => { + return { + ...item, + statusTemp: "REPORT", + lastUpdateUserId: request.user.sub, + lastUpdateFullName: request.user.name, + }; + }), + ); + await this.profileRepo.save(_profiles); + return new HttpSuccess(); + } + + /** + * API ออกคำสั่งลูกจ้าง + * + * @summary ORG_038 - ออกคำสั่งลูกจ้าง (ADMIN) # + * + */ + @Post("report/resume") + async doneReport( + @Body() + body: { + result: { + id: string; + personId: string; + templateDoc: string; + amount: Double | null; + positionSalaryAmount: Double | null; + mouthSalaryAmount: Double | null; + refCommandNo: string; + }[]; + }, + @Request() request: { user: Record }, + ) { + await Promise.all( + body.result.map(async (v) => { + const profile = await this.profileRepo.findOne({ + where: { + id: v.id, + }, + relations: ["posType", "posLevel"], + }); + if (profile != null) { + await new CallAPI() + .PostData(request, "/org/profile-employee/salary", { + profileEmployeeId: profile.id, + date: new Date(), + amount: v.amount, + positionSalaryAmount: v.positionSalaryAmount, + mouthSalaryAmount: v.mouthSalaryAmount, + posNo: profile.posMasterNoTemp, + position: profile.positionTemp, + positionType: profile.posTypeNameTemp, + positionLevel: profile.posLevelNameTemp, + refCommandNo: v.refCommandNo, + templateDoc: v.templateDoc, + }) + .then(async (x) => { + profile.statusTemp = "DONE"; + profile.employeeClass = "PERM"; + const _null: any = null; + profile.employeeWage = v.amount == null ? _null : v.amount.toString(); + await this.profileRepo.save(profile); + }); + await new CallAPI() + .PostData(request, "/org/employee/pos/report/current", { + posmasterId: profile.posmasterIdTemp, + positionId: profile.positionIdTemp, + profileId: profile.id, + }) + .then(async (x) => {}); + } + }), + ); + return new HttpSuccess(); + } + + /** + * API ค้นหาข้อมูลทะเบียนประวัติที่ยังไม่เชื่อม keycloak + * + * @summary ค้นหาข้อมูลทะเบียนประวัติที่ยังไม่เชื่อม keycloak + * + */ + @Post("search-personal-no-keycloak") + async getProfileBySearchKeywordNoKeyCloak( + @Query("page") page: number = 1, + @Query("pageSize") pageSize: number = 10, + @Body() + body: { + fieldName: string; + keyword?: string; + }, + ) { + let findProfile: any; + let total: any; + const skip = (page - 1) * pageSize; + const take = pageSize; + switch (body.fieldName) { + case "citizenId": + [findProfile, total] = await this.profileRepo.findAndCount({ + where: { + keycloak: IsNull(), + citizenId: Like(`%${body.keyword}%`), + }, + relations: ["posType", "posLevel", "current_holders", "profileSalarys"], + skip, + take, + }); + break; + + case "firstname": + [findProfile, total] = await this.profileRepo.findAndCount({ + where: { + keycloak: IsNull(), + firstName: Like(`%${body.keyword}%`), + }, + relations: ["posType", "posLevel", "current_holders", "profileSalarys"], + skip, + take, + }); + break; + + case "lastname": + [findProfile, total] = await this.profileRepo.findAndCount({ + where: { + keycloak: IsNull(), + lastName: Like(`%${body.keyword}%`), + }, + relations: ["posType", "posLevel", "current_holders", "profileSalarys"], + skip, + take, + }); + break; + + default: + [findProfile, total] = await this.profileRepo.findAndCount({ + where: { + keycloak: IsNull(), + }, + relations: ["posType", "posLevel", "current_holders", "profileSalarys"], + skip, + take, + }); + break; + } + + const findRevision = await this.orgRevisionRepo.findOne({ + where: { orgRevisionIsCurrent: true }, + }); + if (!findRevision) { + throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); + } + + const mapDataProfile = await Promise.all( + findProfile.map(async (item: ProfileEmployee) => { + const fullName = `${item.prefix} ${item.firstName} ${item.lastName}`; + const shortName = + item.current_holders.length == 0 + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4 != + null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild4.orgChild4ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3 != + null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild3.orgChild3ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgChild2 != null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild2.orgChild2ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgChild1 != null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgChild1.orgChild1ShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != + null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id) + ?.orgRoot != null + ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot.orgRootShortName}${item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.posMasterNo}` + : null; + + const root = + item.current_holders.length == 0 || + (item.current_holders.find((x) => x.orgRevisionId == findRevision.id) != null && + item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot == null) + ? null + : item.current_holders.find((x) => x.orgRevisionId == findRevision.id)?.orgRoot; + + let salary: any = ""; + if (item != null && item.profileSalarys != null && item.profileSalarys.length > 0) { + let _salary: any = item.profileSalarys.sort( + (a, b) => + (b.date == null ? 0 : b.date.getTime()) - (a.date == null ? 0 : a.date.getTime()), + ); + if (_salary.length > 0) { + salary = _salary[0]; + } + } + + const posMasterNo = item.current_holders?.find( + (x) => x.orgRevisionId == findRevision.id, + )?.posMasterNo; + + const latestProfileEducation = await this.profileEducationRepository.findOne({ + where: { profileEmployeeId: item.id }, + order: { endDate: "DESC" }, + }); + + return { + id: item.id, + prefix: item.prefix, + rank: item.rank, + firstName: item.firstName, + lastName: item.lastName, + position: item.position, + citizenId: item.citizenId, + email: item.email, + phone: item.phone, + name: fullName, + birthDate: item.birthDate, + positionLevel: item.posLevelId, + positionLevelName: item.posLevel?.posLevelName, + positionType: item.posTypeId, + positionTypeName: item.posType?.posTypeName, + posNo: shortName, + organization: root == null ? null : root.orgRootShortName, + salary: salary == "" ? "" : salary.amount, + posMasterNo: posMasterNo ?? null, + posTypeId: item.posTypeId, + posTypeName: item.posType?.posTypeName, + posLevelId: item.posLevelId, + posLevelName: item.posLevel?.posLevelName, + educationDegree: + latestProfileEducation != null && latestProfileEducation.educationLevel != null + ? latestProfileEducation.educationLevel + : null, + }; + }), + ); + + return new HttpSuccess({ data: mapDataProfile, total }); + } + /** + * API ข้อมูลทะเบียนประวัติตาม profileid + * + * @summary ORG_065 - ข้อมูลทะเบียนประวัติตาม profileid (ADMIN) #70 + * + */ + @Get("profileid/position/{id}") + async getProfileByProfileid( + @Request() request: { user: Record }, + @Path() id: string, + ) { + const profile = await this.profileRepo.findOne({ + where: { id: id }, + relations: ["posLevel", "posType", "current_holders", "current_holders.orgRoot"], + }); + if (!profile) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ"); + } + + const orgRevisionPublish = await this.orgRevisionRepo + .createQueryBuilder("orgRevision") + .where("orgRevision.orgRevisionIsDraft = false") + .andWhere("orgRevision.orgRevisionIsCurrent = true") + .getOne(); + if (!orgRevisionPublish) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง"); + } + + const posMaster = + profile.current_holders == null || + profile.current_holders.length == 0 || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id); + const root = + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot == null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot; + const child1 = + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1; + const child2 = + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2; + const child3 = + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3; + const child4 = + profile.current_holders == null || + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4 == + null + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4; + // const position = await this.positionRepository.findOne({ + // relations: ["posExecutive"], + // where: { + // posMasterId: posMaster?.id, + // }, + // }); + const shortName = + profile.current_holders.length == 0 + ? null + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgChild4 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild4.orgChild4ShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != null && + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgChild3 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild3.orgChild3ShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != + null && + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgChild2 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild2.orgChild2ShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != + null && + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgChild1 != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgChild1.orgChild1ShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}` + : profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) != + null && + profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id) + ?.orgRoot != null + ? `${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.orgRoot.orgRootShortName}${profile.current_holders.find((x) => x.orgRevisionId == orgRevisionPublish.id)?.posMasterNo}` + : null; + const _profile: any = { + profileId: profile.id, + prefix: profile.prefix, + rank: profile.rank, + isProbation: profile.isProbation, + firstName: profile.firstName, + lastName: profile.lastName, + citizenId: profile.citizenId, + birthDate: profile.birthDate, + position: profile.position, + leaveDate: profile.dateLeave, + posMasterNo: posMaster == null ? null : posMaster.posMasterNo, + posLevelName: profile.posLevel == null ? null : profile.posLevel.posLevelName, + posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank, + posLevelId: profile.posLevel == null ? null : profile.posLevel.id, + posTypeName: profile.posType == null ? null : profile.posType.posTypeName, + posTypeRank: profile.posType == null ? null : profile.posType.posTypeRank, + posTypeId: profile.posType == null ? null : profile.posType.id, + // posExecutiveName: "", + rootId: root == null ? null : root.id, + root: root == null ? null : root.orgRootName, + rootShortName: root == null ? null : root.orgRootShortName, + child1Id: child1 == null ? null : child1.id, + child1: child1 == null ? null : child1.orgChild1Name, + child1ShortName: child1 == null ? null : child1.orgChild1ShortName, + child2Id: child2 == null ? null : child2.id, + child2: child2 == null ? null : child2.orgChild2Name, + child2ShortName: child2 == null ? null : child2.orgChild2ShortName, + child3Id: child3 == null ? null : child3.id, + child3: child3 == null ? null : child3.orgChild3Name, + child3ShortName: child3 == null ? null : child3.orgChild3ShortName, + child4Id: child4 == null ? null : child4.id, + child4: child4 == null ? null : child4.orgChild4Name, + child4ShortName: child4 == null ? null : child4.orgChild4ShortName, + node: null, + nodeId: null, + posNo: shortName, + }; + + if (_profile.child4Id != null) { + _profile.node = 4; + _profile.nodeId = _profile.child4Id; + } else if (_profile.child3Id != null) { + _profile.node = 3; + _profile.nodeId = _profile.child3Id; + } else if (_profile.child2Id != null) { + _profile.node = 2; + _profile.nodeId = _profile.child2Id; + } else if (_profile.child1Id != null) { + _profile.node = 1; + _profile.nodeId = _profile.child1Id; + } else if (_profile.rootId != null) { + _profile.node = 0; + _profile.nodeId = _profile.rootId; + } + return new HttpSuccess(_profile); + } +} diff --git a/src/controllers/ProfileFamilyCoupleEmployeeController.ts b/src/controllers/ProfileFamilyCoupleEmployeeController.ts index 66e3645d..fb270157 100644 --- a/src/controllers/ProfileFamilyCoupleEmployeeController.ts +++ b/src/controllers/ProfileFamilyCoupleEmployeeController.ts @@ -18,7 +18,11 @@ import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; import { RequestWithUser } from "../middlewares/user"; import { ProfileEmployee } from "../entities/ProfileEmployee"; -import { ProfileFamilyCouple, CreateProfileEmployeeFamilyCouple, UpdateProfileFamilyCouple } from "../entities/ProfileFamilyCouple"; +import { + ProfileFamilyCouple, + CreateProfileEmployeeFamilyCouple, + UpdateProfileFamilyCouple, +} from "../entities/ProfileFamilyCouple"; import { ProfileFamilyCoupleHistory } from "../entities/ProfileFamilyCoupleHistory"; import Extension from "../interfaces/extension"; import permission from "../interfaces/permission"; @@ -216,7 +220,7 @@ export class ProfileFamilyCoupleEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeFamilyCouple, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); const familyCouple = Object.assign(new ProfileFamilyCouple(), body); if (!familyCouple) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -263,7 +267,7 @@ export class ProfileFamilyCoupleEmployeeController extends Controller { @Body() body: UpdateProfileFamilyCouple, @Path() profileEmployeeId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const familyCouple = await this.ProfileFamilyCouple.findOneBy({ profileEmployeeId: profileEmployeeId, }); diff --git a/src/controllers/ProfileFamilyCoupleEmployeeTempController.ts b/src/controllers/ProfileFamilyCoupleEmployeeTempController.ts new file mode 100644 index 00000000..ec3b5294 --- /dev/null +++ b/src/controllers/ProfileFamilyCoupleEmployeeTempController.ts @@ -0,0 +1,301 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { + ProfileFamilyCouple, + CreateProfileEmployeeFamilyCouple, + UpdateProfileFamilyCouple, +} from "../entities/ProfileFamilyCouple"; +import { ProfileFamilyCoupleHistory } from "../entities/ProfileFamilyCoupleHistory"; +import Extension from "../interfaces/extension"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/family/couple") +@Tags("ProfileEmployeeFamilyCouple") +@Security("bearerAuth") +export class ProfileFamilyCoupleEmployeeController extends Controller { + private profileRepo = AppDataSource.getRepository(ProfileEmployee); + private ProfileFamilyCouple = AppDataSource.getRepository(ProfileFamilyCouple); + private ProfileFamilyCoupleHistory = AppDataSource.getRepository(ProfileFamilyCoupleHistory); + + @Get("user") + public async getFamilyCoupleUser(@Request() request: { user: Record }) { + const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const familyCouple = await this.ProfileFamilyCouple.findOne({ + select: [ + "id", + "couplePrefix", + "coupleFirstName", + "coupleLastName", + "coupleLastNameOld", + "coupleCareer", + "coupleCitizenId", + "coupleLive", + "relationship", + "profileId", + ], + where: { profileEmployeeId: profile.id }, + order: { lastUpdatedAt: "DESC" }, + }); + + return new HttpSuccess(familyCouple); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: { + id: "6207ae29-05ef-4abb-9a37-a887265d671e", + couplePrefix: "string", + coupleFirstName: "string", + coupleLastName: "string", + coupleLastNameOld: "string", + coupleCareer: "string", + coupleCitizenId: "string", + coupleLive: true, + relationship: "string", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + }, + }) + public async getFamilyCouple(@Path() profileEmployeeId: string) { + const profile = await this.profileRepo.findOne({ + where: { id: profileEmployeeId }, + }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const familyCouple = await this.ProfileFamilyCouple.findOne({ + select: [ + "id", + "couplePrefix", + "coupleFirstName", + "coupleLastName", + "coupleLastNameOld", + "coupleCareer", + "coupleCitizenId", + "coupleLive", + "relationship", + "profileEmployeeId", + ], + where: { profileEmployeeId }, + order: { lastUpdatedAt: "DESC" }, + }); + + return new HttpSuccess(familyCouple); + } + + /** + * + * @summary ประวัติแก้ไขครอบครัว by keycloak + * + */ + @Get("history/user") + public async familyCoupleHistoryUser(@Request() request: RequestWithUser) { + const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const familyCouple = await this.ProfileFamilyCouple.find({ + relations: ["histories"], + order: { lastUpdatedAt: "DESC" }, + where: { + profileEmployeeId: profile.id, + }, + }); + + const mapData = familyCouple + .flatMap((x) => x.histories) + .map((y) => ({ + id: y.id, + createdAt: y.createdAt, + createdUserId: y.createdUserId, + lastUpdatedAt: y.lastUpdatedAt, + lastUpdateUserId: y.lastUpdateUserId, + createdFullName: y.createdFullName, + lastUpdateFullName: y.lastUpdateFullName, + couplePrefix: y.couplePrefix, + coupleFirstName: y.coupleFirstName, + coupleLastName: y.coupleLastName, + coupleLastNameOld: y.coupleLastNameOld, + coupleCareer: y.coupleCareer, + coupleCitizenId: y.coupleCitizenId, + coupleLive: y.coupleLive, + relationship: y.relationship, + profileFamilyCoupleId: y.profileFamilyCoupleId, + profileEmployeeId: profile.id, + })); + + return new HttpSuccess(mapData); + } + + @Get("history/{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "6207ae29-05ef-4abb-9a37-a887265d671e", + createdAt: "2024-03-19T11:00:29.769Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-19T11:00:29.769Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + couplePrefix: "string", + coupleFirstName: "string", + coupleLastName: "string", + coupleLastNameOld: "string", + coupleCareer: "string", + coupleCitizenId: "string", + coupleLive: true, + relationship: "string", + profileFamilyCoupleId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + }, + ], + }) + public async familyCoupleHistory(@Path() profileEmployeeId: string) { + const profile = await this.profileRepo.findOne({ + where: { id: profileEmployeeId }, + }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const familyCouple = await this.ProfileFamilyCouple.find({ + relations: ["histories"], + order: { lastUpdatedAt: "DESC" }, + where: { profileEmployeeId: profileEmployeeId }, + }); + + const mapData = familyCouple + .flatMap((x) => x.histories) + .map((y) => ({ + id: y.id, + createdAt: y.createdAt, + createdUserId: y.createdUserId, + lastUpdatedAt: y.lastUpdatedAt, + lastUpdateUserId: y.lastUpdateUserId, + createdFullName: y.createdFullName, + lastUpdateFullName: y.lastUpdateFullName, + couplePrefix: y.couplePrefix, + coupleFirstName: y.coupleFirstName, + coupleLastName: y.coupleLastName, + coupleLastNameOld: y.coupleLastNameOld, + coupleCareer: y.coupleCareer, + coupleCitizenId: y.coupleCitizenId, + coupleLive: y.coupleLive, + relationship: y.relationship, + profileFamilyCoupleId: y.profileFamilyCoupleId, + profileEmployeeId: profileEmployeeId, + })); + + return new HttpSuccess(mapData); + } + + @Post() + public async FamilyCouple( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeFamilyCouple, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + const familyCouple = Object.assign(new ProfileFamilyCouple(), body); + if (!familyCouple) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + const profile = await this.profileRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + familyCouple.coupleCitizenId = Extension.CheckCitizen(String(body.coupleCitizenId)); + familyCouple.createdUserId = req.user.sub; + familyCouple.createdFullName = req.user.name; + familyCouple.lastUpdateUserId = req.user.sub; + familyCouple.lastUpdateFullName = req.user.name; + await this.ProfileFamilyCouple.save(familyCouple); + + if (familyCouple) { + profile.relationship = familyCouple.relationship; //update profileEmployee.relationship + const history: ProfileFamilyCoupleHistory = Object.assign(new ProfileFamilyCoupleHistory(), { + profileFamilyCoupleId: familyCouple.id, + couplePrefix: familyCouple.couplePrefix, + coupleFirstName: familyCouple.coupleFirstName, + coupleLastName: familyCouple.coupleLastName, + coupleLastNameOld: familyCouple.coupleLastNameOld, + coupleCareer: familyCouple.coupleCareer, + coupleCitizenId: familyCouple.coupleCitizenId, + coupleLive: familyCouple.coupleLive, + relationship: familyCouple.relationship, + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }); + await Promise.all([ + this.profileRepo.save(profile), + this.ProfileFamilyCoupleHistory.save(history), + ]); + } + return new HttpSuccess(familyCouple.id); + } + + @Patch("{profileEmployeeId}") + public async editFamilyCouple( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileFamilyCouple, + @Path() profileEmployeeId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const familyCouple = await this.ProfileFamilyCouple.findOneBy({ + profileEmployeeId: profileEmployeeId, + }); + if (!familyCouple) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileFamilyCoupleHistory(); + Object.assign(history, { ...familyCouple, id: undefined }); + Object.assign(familyCouple, body); + (familyCouple.lastUpdateUserId = req.user.sub), + (familyCouple.lastUpdateFullName = req.user.name); + familyCouple.coupleCitizenId = Extension.CheckCitizen(String(body.coupleCitizenId)); + history.profileFamilyCoupleId = familyCouple.id; + (history.couplePrefix = familyCouple.couplePrefix), + (history.coupleFirstName = familyCouple.coupleFirstName), + (history.coupleLastName = familyCouple.coupleLastName), + (history.coupleLastNameOld = familyCouple.coupleLastNameOld), + (history.coupleCareer = familyCouple.coupleCareer), + (history.coupleCitizenId = familyCouple.coupleCitizenId), + (history.coupleLive = familyCouple.coupleLive), + (history.relationship = familyCouple.relationship), + (history.lastUpdateUserId = req.user.sub), + (history.lastUpdateFullName = req.user.name); + + await Promise.all([ + this.ProfileFamilyCouple.save(familyCouple), + this.ProfileFamilyCoupleHistory.save(history), + ]); + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileFamilyFatherEmployeeController.ts b/src/controllers/ProfileFamilyFatherEmployeeController.ts index 05f35848..ee4a0c54 100644 --- a/src/controllers/ProfileFamilyFatherEmployeeController.ts +++ b/src/controllers/ProfileFamilyFatherEmployeeController.ts @@ -206,7 +206,7 @@ export class ProfileFamilyFatherEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeFamilyFather, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); const familyFather = Object.assign(new ProfileFamilyFather(), body); if (!familyFather) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -247,7 +247,7 @@ export class ProfileFamilyFatherEmployeeController extends Controller { @Body() body: UpdateProfileFamilyFather, @Path() profileEmployeeId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const familyFather = await this.ProfileFamilyFather.findOneBy({ profileEmployeeId: profileEmployeeId, }); diff --git a/src/controllers/ProfileFamilyFatherEmployeeTempController.ts b/src/controllers/ProfileFamilyFatherEmployeeTempController.ts new file mode 100644 index 00000000..bddb2c5f --- /dev/null +++ b/src/controllers/ProfileFamilyFatherEmployeeTempController.ts @@ -0,0 +1,279 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { + ProfileFamilyFather, + CreateProfileEmployeeFamilyFather, + UpdateProfileFamilyFather, +} from "../entities/ProfileFamilyFather"; +import { ProfileFamilyFatherHistory } from "../entities/ProfileFamilyFatherHistory"; +import Extension from "../interfaces/extension"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/family/father") +@Tags("ProfileEmployeeFamilyFather") +@Security("bearerAuth") +export class ProfileFamilyFatherEmployeeController extends Controller { + private profileRepo = AppDataSource.getRepository(ProfileEmployee); + private ProfileFamilyFather = AppDataSource.getRepository(ProfileFamilyFather); + private ProfileFamilyFatherHistory = AppDataSource.getRepository(ProfileFamilyFatherHistory); + + @Get("user") + public async getFamilyFatherUser(@Request() request: { user: Record }) { + const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const familyFather = await this.ProfileFamilyFather.findOne({ + select: [ + "id", + "fatherPrefix", + "fatherFirstName", + "fatherLastName", + "fatherCareer", + "fatherCitizenId", + "fatherLive", + "profileId", + ], + where: { profileEmployeeId: profile.id }, + order: { lastUpdatedAt: "DESC" }, + }); + + return new HttpSuccess(familyFather); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: { + id: "6207ae29-05ef-4abb-9a37-a887265d671e", + fatherPrefix: "string", + fatherFirstName: "string", + fatherLastName: "string", + fatherCareer: "string", + fatherCitizenId: "string", + fatherLive: true, + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + }, + }) + public async getFamilyFather(@Path() profileEmployeeId: string) { + const profile = await this.profileRepo.findOne({ + where: { id: profileEmployeeId }, + }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const familyFather = await this.ProfileFamilyFather.findOne({ + select: [ + "id", + "fatherPrefix", + "fatherFirstName", + "fatherLastName", + "fatherCareer", + "fatherCitizenId", + "fatherLive", + "profileEmployeeId", + ], + where: { profileEmployeeId }, + order: { lastUpdatedAt: "DESC" }, + }); + + return new HttpSuccess(familyFather); + } + + /** + * + * @summary ประวัติแก้ไขครอบครัว by keycloak + * + */ + @Get("history/user") + public async familyFatherHistoryUser(@Request() request: RequestWithUser) { + const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const familyFather = await this.ProfileFamilyFather.find({ + relations: ["histories"], + order: { lastUpdatedAt: "DESC" }, + where: { profileEmployeeId: profile.id }, + }); + + const mapData = familyFather + .flatMap((x) => x.histories) + .map((y) => ({ + id: y.id, + createdAt: y.createdAt, + createdUserId: y.createdUserId, + lastUpdatedAt: y.lastUpdatedAt, + lastUpdateUserId: y.lastUpdateUserId, + createdFullName: y.createdFullName, + lastUpdateFullName: y.lastUpdateFullName, + fatherPrefix: y.fatherPrefix, + fatherFirstName: y.fatherFirstName, + fatherLastName: y.fatherLastName, + fatherCareer: y.fatherCareer, + fatherCitizenId: y.fatherCitizenId, + fatherLive: y.fatherLive, + profileFamilyFatherId: y.profileFamilyFatherId, + profileEmployeeId: profile.id, + })); + + return new HttpSuccess(mapData); + } + + @Get("history/{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "6207ae29-05ef-4abb-9a37-a887265d671e", + createdAt: "2024-03-19T11:00:29.769Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-19T11:00:29.769Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + fatherPrefix: "string", + fatherFirstName: "string", + fatherLastName: "string", + fatherCareer: "string", + fatherCitizenId: "string", + fatherLive: true, + profileFamilyFatherId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + }, + ], + }) + public async familyFatherHistory(@Path() profileEmployeeId: string) { + const profile = await this.profileRepo.findOne({ + where: { id: profileEmployeeId }, + }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const familyFather = await this.ProfileFamilyFather.find({ + relations: ["histories"], + order: { lastUpdatedAt: "DESC" }, + where: { profileEmployeeId: profileEmployeeId }, + }); + + const mapData = familyFather + .flatMap((x) => x.histories) + .map((y) => ({ + id: y.id, + createdAt: y.createdAt, + createdUserId: y.createdUserId, + lastUpdatedAt: y.lastUpdatedAt, + lastUpdateUserId: y.lastUpdateUserId, + createdFullName: y.createdFullName, + lastUpdateFullName: y.lastUpdateFullName, + fatherPrefix: y.fatherPrefix, + fatherFirstName: y.fatherFirstName, + fatherLastName: y.fatherLastName, + fatherCareer: y.fatherCareer, + fatherCitizenId: y.fatherCitizenId, + fatherLive: y.fatherLive, + profileFamilyFatherId: y.profileFamilyFatherId, + profileEmployeeId: profileEmployeeId, + })); + + return new HttpSuccess(mapData); + } + + @Post() + public async FamilyFather( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeFamilyFather, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + const familyFather = Object.assign(new ProfileFamilyFather(), body); + if (!familyFather) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + const profile = await this.profileRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + familyFather.fatherCitizenId = Extension.CheckCitizen(String(body.fatherCitizenId)); + familyFather.createdUserId = req.user.sub; + familyFather.createdFullName = req.user.name; + familyFather.lastUpdateUserId = req.user.sub; + familyFather.lastUpdateFullName = req.user.name; + await this.ProfileFamilyFather.save(familyFather); + + if (familyFather) { + const history: ProfileFamilyFatherHistory = Object.assign(new ProfileFamilyFatherHistory(), { + profileFamilyFatherId: familyFather.id, + fatherPrefix: familyFather.fatherPrefix, + fatherFirstName: familyFather.fatherFirstName, + fatherLastName: familyFather.fatherLastName, + fatherCareer: familyFather.fatherCareer, + fatherCitizenId: familyFather.fatherCitizenId, + fatherLive: familyFather.fatherLive, + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }); + await this.ProfileFamilyFatherHistory.save(history); + } + return new HttpSuccess(familyFather.id); + } + + @Patch("{profileEmployeeId}") + public async editFamilyFather( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileFamilyFather, + @Path() profileEmployeeId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const familyFather = await this.ProfileFamilyFather.findOneBy({ + profileEmployeeId: profileEmployeeId, + }); + if (!familyFather) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileFamilyFatherHistory(); + Object.assign(history, { ...familyFather, id: undefined }); + Object.assign(familyFather, body); + (familyFather.lastUpdateUserId = req.user.sub), + (familyFather.lastUpdateFullName = req.user.name); + familyFather.fatherCitizenId = Extension.CheckCitizen(String(body.fatherCitizenId)); + history.profileFamilyFatherId = familyFather.id; + (history.fatherPrefix = familyFather.fatherPrefix), + (history.fatherFirstName = familyFather.fatherFirstName), + (history.fatherLastName = familyFather.fatherLastName), + (history.fatherCareer = familyFather.fatherCareer), + (history.fatherCitizenId = familyFather.fatherCitizenId), + (history.fatherLive = familyFather.fatherLive), + (history.lastUpdateUserId = req.user.sub), + (history.lastUpdateFullName = req.user.name); + + await Promise.all([ + this.ProfileFamilyFather.save(familyFather), + this.ProfileFamilyFatherHistory.save(history), + ]); + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileFamilyMotherEmployeeController.ts b/src/controllers/ProfileFamilyMotherEmployeeController.ts index ab922bd8..a2d9b052 100644 --- a/src/controllers/ProfileFamilyMotherEmployeeController.ts +++ b/src/controllers/ProfileFamilyMotherEmployeeController.ts @@ -18,7 +18,11 @@ import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; import { RequestWithUser } from "../middlewares/user"; import { ProfileEmployee } from "../entities/ProfileEmployee"; -import { ProfileFamilyMother, CreateProfileEmployeeFamilyMother, UpdateProfileFamilyMother } from "../entities/ProfileFamilyMother"; +import { + ProfileFamilyMother, + CreateProfileEmployeeFamilyMother, + UpdateProfileFamilyMother, +} from "../entities/ProfileFamilyMother"; import { ProfileFamilyMotherHistory } from "../entities/ProfileFamilyMotherHistory"; import Extension from "../interfaces/extension"; import permission from "../interfaces/permission"; @@ -202,7 +206,7 @@ export class ProfileFamilyMotherEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeFamilyMother, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); const familyMother = Object.assign(new ProfileFamilyMother(), body); if (!familyMother) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -243,7 +247,7 @@ export class ProfileFamilyMotherEmployeeController extends Controller { @Body() body: UpdateProfileFamilyMother, @Path() profileEmployeeId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const familyMother = await this.ProfileFamilyMother.findOneBy({ profileEmployeeId: profileEmployeeId, }); diff --git a/src/controllers/ProfileFamilyMotherEmployeeTempController.ts b/src/controllers/ProfileFamilyMotherEmployeeTempController.ts new file mode 100644 index 00000000..49efbb75 --- /dev/null +++ b/src/controllers/ProfileFamilyMotherEmployeeTempController.ts @@ -0,0 +1,279 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { + ProfileFamilyMother, + CreateProfileEmployeeFamilyMother, + UpdateProfileFamilyMother, +} from "../entities/ProfileFamilyMother"; +import { ProfileFamilyMotherHistory } from "../entities/ProfileFamilyMotherHistory"; +import Extension from "../interfaces/extension"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/family/mother") +@Tags("ProfileEmployeeFamilyMother") +@Security("bearerAuth") +export class ProfileFamilyMotherEmployeeController extends Controller { + private profileRepo = AppDataSource.getRepository(ProfileEmployee); + private ProfileFamilyMother = AppDataSource.getRepository(ProfileFamilyMother); + private ProfileFamilyMotherHistory = AppDataSource.getRepository(ProfileFamilyMotherHistory); + + @Get("user") + public async getFamilyMotherUser(@Request() request: { user: Record }) { + const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const familyMother = await this.ProfileFamilyMother.findOne({ + select: [ + "id", + "motherPrefix", + "motherFirstName", + "motherLastName", + "motherCareer", + "motherCitizenId", + "motherLive", + "profileId", + ], + where: { profileEmployeeId: profile.id }, + order: { lastUpdatedAt: "DESC" }, + }); + + return new HttpSuccess(familyMother); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: { + id: "6207ae29-05ef-4abb-9a37-a887265d671e", + motherPrefix: "string", + motherFirstName: "string", + motherLastName: "string", + motherCareer: "string", + motherCitizenId: "string", + motherLive: true, + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + }, + }) + public async getFamilyMother(@Path() profileEmployeeId: string) { + const profile = await this.profileRepo.findOne({ + where: { id: profileEmployeeId }, + }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const familyMother = await this.ProfileFamilyMother.findOne({ + select: [ + "id", + "motherPrefix", + "motherFirstName", + "motherLastName", + "motherCareer", + "motherCitizenId", + "motherLive", + "profileEmployeeId", + ], + where: { profileEmployeeId }, + order: { lastUpdatedAt: "DESC" }, + }); + + return new HttpSuccess(familyMother); + } + + /** + * + * @summary ประวัติแก้ไขครอบครัว by keycloak + * + */ + @Get("history/user") + public async familyMotherHistoryUser(@Request() request: RequestWithUser) { + const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const familyMother = await this.ProfileFamilyMother.find({ + relations: ["histories"], + order: { lastUpdatedAt: "DESC" }, + where: { profileEmployeeId: profile.id }, + }); + + const mapData = familyMother + .flatMap((x) => x.histories) + .map((y) => ({ + id: y.id, + createdAt: y.createdAt, + createdUserId: y.createdUserId, + lastUpdatedAt: y.lastUpdatedAt, + lastUpdateUserId: y.lastUpdateUserId, + createdFullName: y.createdFullName, + lastUpdateFullName: y.lastUpdateFullName, + motherPrefix: y.motherPrefix, + motherFirstName: y.motherFirstName, + motherLastName: y.motherLastName, + motherCareer: y.motherCareer, + motherCitizenId: y.motherCitizenId, + motherLive: y.motherLive, + profileFamilyMotherId: y.profileFamilyMotherId, + profileEmployeeId: profile.id, + })); + + return new HttpSuccess(mapData); + } + + @Get("history/{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "6207ae29-05ef-4abb-9a37-a887265d671e", + createdAt: "2024-03-19T11:00:29.769Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-19T11:00:29.769Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + motherPrefix: "string", + motherFirstName: "string", + motherLastName: "string", + motherCareer: "string", + motherCitizenId: "string", + motherLive: true, + profileFamilyMotherId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + }, + ], + }) + public async familyMotherHistory(@Path() profileEmployeeId: string) { + const profile = await this.profileRepo.findOne({ + where: { id: profileEmployeeId }, + }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const familyMother = await this.ProfileFamilyMother.find({ + relations: ["histories"], + order: { lastUpdatedAt: "DESC" }, + where: { profileEmployeeId: profileEmployeeId }, + }); + + const mapData = familyMother + .flatMap((x) => x.histories) + .map((y) => ({ + id: y.id, + createdAt: y.createdAt, + createdUserId: y.createdUserId, + lastUpdatedAt: y.lastUpdatedAt, + lastUpdateUserId: y.lastUpdateUserId, + createdFullName: y.createdFullName, + lastUpdateFullName: y.lastUpdateFullName, + motherPrefix: y.motherPrefix, + motherFirstName: y.motherFirstName, + motherLastName: y.motherLastName, + motherCareer: y.motherCareer, + motherCitizenId: y.motherCitizenId, + motherLive: y.motherLive, + profileFamilyMotherId: y.profileFamilyMotherId, + profileEmployeeId: profileEmployeeId, + })); + + return new HttpSuccess(mapData); + } + + @Post() + public async FamilyMother( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeFamilyMother, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + const familyMother = Object.assign(new ProfileFamilyMother(), body); + if (!familyMother) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + const profile = await this.profileRepo.findOneBy({ id: body.profileEmployeeId }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + familyMother.motherCitizenId = Extension.CheckCitizen(String(body.motherCitizenId)); + familyMother.createdUserId = req.user.sub; + familyMother.createdFullName = req.user.name; + familyMother.lastUpdateUserId = req.user.sub; + familyMother.lastUpdateFullName = req.user.name; + await this.ProfileFamilyMother.save(familyMother); + + if (familyMother) { + const history: ProfileFamilyMotherHistory = Object.assign(new ProfileFamilyMotherHistory(), { + profileFamilyMotherId: familyMother.id, + motherPrefix: familyMother.motherPrefix, + motherFirstName: familyMother.motherFirstName, + motherLastName: familyMother.motherLastName, + motherCareer: familyMother.motherCareer, + motherCitizenId: familyMother.motherCitizenId, + motherLive: familyMother.motherLive, + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }); + await this.ProfileFamilyMotherHistory.save(history); + } + return new HttpSuccess(familyMother.id); + } + + @Patch("{profileEmployeeId}") + public async editFamilyMother( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileFamilyMother, + @Path() profileEmployeeId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const familyMother = await this.ProfileFamilyMother.findOneBy({ + profileEmployeeId: profileEmployeeId, + }); + if (!familyMother) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileFamilyMotherHistory(); + Object.assign(history, { ...familyMother, id: undefined }); + Object.assign(familyMother, body); + (familyMother.lastUpdateUserId = req.user.sub), + (familyMother.lastUpdateFullName = req.user.name); + familyMother.motherCitizenId = Extension.CheckCitizen(String(body.motherCitizenId)); + history.profileFamilyMotherId = familyMother.id; + (history.motherPrefix = familyMother.motherPrefix), + (history.motherFirstName = familyMother.motherFirstName), + (history.motherLastName = familyMother.motherLastName), + (history.motherCareer = familyMother.motherCareer), + (history.motherCitizenId = familyMother.motherCitizenId), + (history.motherLive = familyMother.motherLive), + (history.lastUpdateUserId = req.user.sub), + (history.lastUpdateFullName = req.user.name); + + await Promise.all([ + this.ProfileFamilyMother.save(familyMother), + this.ProfileFamilyMotherHistory.save(history), + ]); + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileGovernmentEmployeeController.ts b/src/controllers/ProfileGovernmentEmployeeController.ts index 7bb64f1c..65f7991c 100644 --- a/src/controllers/ProfileGovernmentEmployeeController.ts +++ b/src/controllers/ProfileGovernmentEmployeeController.ts @@ -288,7 +288,7 @@ export class ProfileGovernmentEmployeeController extends Controller { @Body() body: UpdateProfileGovernment, @Path() profileEmployeeId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.profileEmployeeRepo.findOne({ where: { id: profileEmployeeId }, }); diff --git a/src/controllers/ProfileGovernmentEmployeeTempController.ts b/src/controllers/ProfileGovernmentEmployeeTempController.ts new file mode 100644 index 00000000..02e25174 --- /dev/null +++ b/src/controllers/ProfileGovernmentEmployeeTempController.ts @@ -0,0 +1,323 @@ +import { + Body, + Controller, + Example, + Get, + Patch, + Path, + Delete, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { + CreateProfileEmployeeGovernment, + ProfileGovernment, + UpdateProfileGovernment, +} from "../entities/ProfileGovernment"; +import { EmployeePosition } from "../entities/EmployeePosition"; +import { EmployeePosMaster } from "../entities/EmployeePosMaster"; +import { calculateAge, calculateRetireDate } from "../interfaces/utils"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/government") +@Tags("ProfileEmployeeGovernment") +@Security("bearerAuth") +export class ProfileGovernmentEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private govRepo = AppDataSource.getRepository(ProfileGovernment); + private positionRepo = AppDataSource.getRepository(EmployeePosition); + private posMasterRepo = AppDataSource.getRepository(EmployeePosMaster); + + /** + * + * @summary ข้อมูลราชการ + * + */ + @Get("user") + public async getGovHistoryUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const record = await this.profileEmployeeRepo.findOne({ + where: { id: profile.id }, + relations: { + posType: true, + posLevel: true, + }, + }); + const posMaster = await this.posMasterRepo.findOne({ + where: { + orgRevision: { + orgRevisionIsCurrent: true, + orgRevisionIsDraft: false, + }, + current_holderId: profile.id, + }, + order: { createdAt: "DESC" }, + relations: { + orgRoot: true, + orgChild1: true, + orgChild2: true, + orgChild3: true, + orgChild4: true, + }, + }); + // const position = await this.positionRepo.findOne({ + // where: { + // positionIsSelected: true, + // posMaster: { + // orgRevision: { + // orgRevisionIsCurrent: true, + // orgRevisionIsDraft: false, + // }, + // current_holderId: profile.id, + // }, + // }, + // order: { createdAt: "DESC" }, + // }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + const fullNameParts = [ + posMaster == null || posMaster.orgChild4 == null ? null : posMaster.orgChild4.orgChild4Name, + posMaster == null || posMaster.orgChild3 == null ? null : posMaster.orgChild3.orgChild3Name, + posMaster == null || posMaster.orgChild2 == null ? null : posMaster.orgChild2.orgChild2Name, + posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, + posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, + ]; + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + let orgShortName = ""; + if (posMaster != null) { + if (posMaster.orgChild1Id === null) { + orgShortName = posMaster.orgRoot?.orgRootShortName; + } else if (posMaster.orgChild2Id === null) { + orgShortName = posMaster.orgChild1?.orgChild1ShortName; + } else if (posMaster.orgChild3Id === null) { + orgShortName = posMaster.orgChild2?.orgChild2ShortName; + } else if (posMaster.orgChild4Id === null) { + orgShortName = posMaster.orgChild3?.orgChild3ShortName; + } else { + orgShortName = posMaster.orgChild4?.orgChild4ShortName; + } + } + const data = { + org: org, //สังกัด + position: record.position, //ตำแหน่ง + posLevel: record.posLevel == null ? null : record.posLevel.posLevelName, //ระดับ + posMasterNo: posMaster == null ? null : `${orgShortName} ${posMaster.posMasterNo}`, //เลขที่ตำแหน่ง + posType: record.posType == null ? null : record.posType.posTypeName, //ประเภท + dateLeave: record.birthDate == null ? null : calculateRetireDate(record.birthDate), + dateRetireLaw: record.dateRetireLaw ?? null, + govAge: record.dateStart == null ? null : calculateAge(record.dateStart), + dateAppoint: record.dateAppoint, + dateStart: record.dateStart, + govAgeAbsent: record.govAgeAbsent, + govAgePlus: record.govAgePlus, + reasonSameDate: record.reasonSameDate, + }; + + return new HttpSuccess(data); + } + + /** + * + * @summary ข้อมูลราชการ + * + */ + @Get("{profileEmployeeId}") + @Example({}) + public async getGovHistory(@Path() profileEmployeeId: string) { + const record = await this.profileEmployeeRepo.findOne({ + where: { id: profileEmployeeId }, + relations: { + posType: true, + posLevel: true, + }, + }); + const posMaster = await this.posMasterRepo.findOne({ + where: { + orgRevision: { + orgRevisionIsCurrent: true, + orgRevisionIsDraft: false, + }, + current_holderId: profileEmployeeId, + }, + order: { createdAt: "DESC" }, + relations: { + orgRoot: true, + orgChild1: true, + orgChild2: true, + orgChild3: true, + orgChild4: true, + }, + }); + const position = await this.positionRepo.findOne({ + where: { + positionIsSelected: true, + posMaster: { + orgRevision: { + orgRevisionIsCurrent: true, + orgRevisionIsDraft: false, + }, + current_holderId: profileEmployeeId, + }, + }, + order: { createdAt: "DESC" }, + }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + const fullNameParts = [ + posMaster == null || posMaster.orgChild4 == null ? null : posMaster.orgChild4.orgChild4Name, + posMaster == null || posMaster.orgChild3 == null ? null : posMaster.orgChild3.orgChild3Name, + posMaster == null || posMaster.orgChild2 == null ? null : posMaster.orgChild2.orgChild2Name, + posMaster == null || posMaster.orgChild1 == null ? null : posMaster.orgChild1.orgChild1Name, + posMaster == null || posMaster.orgRoot == null ? null : posMaster.orgRoot.orgRootName, + ]; + const org = fullNameParts.filter((part) => part !== undefined && part !== null).join("/"); + let orgShortName = ""; + if (posMaster != null) { + if (posMaster.orgChild1Id === null) { + orgShortName = posMaster.orgRoot?.orgRootShortName; + } else if (posMaster.orgChild2Id === null) { + orgShortName = posMaster.orgChild1?.orgChild1ShortName; + } else if (posMaster.orgChild3Id === null) { + orgShortName = posMaster.orgChild2?.orgChild2ShortName; + } else if (posMaster.orgChild4Id === null) { + orgShortName = posMaster.orgChild3?.orgChild3ShortName; + } else { + orgShortName = posMaster.orgChild4?.orgChild4ShortName; + } + } + const data = { + org: org, //สังกัด + position: record.position, //ตำแหน่ง + posLevel: record.posLevel == null ? null : record.posLevel.posLevelName, //ระดับ + posMasterNo: posMaster == null ? null : `${orgShortName} ${posMaster.posMasterNo}`, //เลขที่ตำแหน่ง + posType: record.posType == null ? null : record.posType.posTypeName, //ประเภท + dateLeave: record.birthDate == null ? null : calculateRetireDate(record.birthDate), //วันเกษียณ + dateAppoint: record.dateAppoint, //วันที่สั่งบรรจุ + dateStart: record.dateStart, //วันที่เริ่มปฎิบัติงานราชการ + reasonSameDate: record.reasonSameDate, //เหตุผลที่วันที่ไม่ตรงกัน + dateRetire: record.dateRetire ?? null, //วันครบเกษียณอายุ + govAge: record.dateStart == null ? null : calculateAge(record.dateStart), //อายุราชการ + govAgeAbsent: record.govAgeAbsent ?? null, // ขาดราชการ + govAgePlus: record.govAgePlus, // อายุราชการเกื้อกูล + dateRetireLaw: record.dateRetireLaw ?? null, // วันที่เกษียฯอายุราชการตามกฎหมาย + }; + return new HttpSuccess(data); + } + + /** + * + * @summary ประวัติข้อมูลราชการ by keycloak + * + */ + @Get("history/user") + public async govHistoryUser(@Request() request: RequestWithUser) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const record = await this.govRepo.find({ + order: { lastUpdatedAt: "DESC" }, + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(record); + } + + /** + * + * @summary ประวัติข้อมูลราชการ + * + */ + @Get("history/{profileEmployeeId}") + @Example({}) + public async govHistory(@Path() profileEmployeeId: string) { + const record = await this.govRepo.find({ + order: { lastUpdatedAt: "DESC" }, + where: { profileEmployeeId: profileEmployeeId }, + }); + return new HttpSuccess(record); + } + + // /** + // * + // * @summary เพิ่มข้อมูลราชการ + // * + // */ + // @Post() + // public async newGov(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeGovernment) { + // if (!body.profileEmployeeId) { + // throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + // } + + // const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + // if (!profile) { + // throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + // } + + // const data = new ProfileGovernment(); + // const meta = { + // createdUserId: req.user.sub, + // createdFullName: req.user.name, + // lastUpdateUserId: req.user.sub, + // lastUpdateFullName: req.user.name, + // }; + + // Object.assign(data, { ...body, ...meta }); + // await this.govRepo.save(data); + // return new HttpSuccess(); + // } + + /** + * + * @summary แก้ไขข้อมูลราชการ + * + */ + @Patch("{profileEmployeeId}") + public async editGov( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileGovernment, + @Path() profileEmployeeId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.profileEmployeeRepo.findOne({ + where: { id: profileEmployeeId }, + }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + const historyData = new ProfileGovernment(); + + Object.assign(historyData, { ...record, ...body, id: undefined }); + Object.assign(record, body); + record.lastUpdateFullName = req.user.name; + record.lastUpdateFullName = req.user.name; + historyData.profileEmployeeId = profileEmployeeId; + historyData.lastUpdateFullName = req.user.name; + historyData.lastUpdateFullName = req.user.name; + await Promise.all([this.profileEmployeeRepo.save(record), this.govRepo.save(historyData)]); + return new HttpSuccess(); + } + + // /** + // * + // * @summary ลบข้อมูลราชการ + // * + // */ + // @Delete("{profileEmployeeId}") + // public async deleteGov(@Path() profileEmployeeId: string) { + // const result = await this.govRepo.delete({ profileEmployeeId: profileEmployeeId }); + // if (result.affected == undefined || result.affected <= 0) { + // throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + // } + // return new HttpSuccess(); + // } +} diff --git a/src/controllers/ProfileHonorEmployeeController.ts b/src/controllers/ProfileHonorEmployeeController.ts index f5f211d4..439117a3 100644 --- a/src/controllers/ProfileHonorEmployeeController.ts +++ b/src/controllers/ProfileHonorEmployeeController.ts @@ -13,7 +13,11 @@ import { Tags, } from "tsoa"; import { AppDataSource } from "../database/data-source"; -import { CreateProfileEmployeeHonor, ProfileHonor, UpdateProfileHonor } from "../entities/ProfileHonor"; +import { + CreateProfileEmployeeHonor, + ProfileHonor, + UpdateProfileHonor, +} from "../entities/ProfileHonor"; import HttpSuccess from "../interfaces/http-success"; import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; @@ -138,7 +142,7 @@ export class ProfileHonorEmployeeController extends Controller { @Post() public async newHonor(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeHonor) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -171,7 +175,7 @@ export class ProfileHonorEmployeeController extends Controller { @Body() body: UpdateProfileHonor, @Path() honorId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.honorRepo.findOneBy({ id: honorId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -191,7 +195,7 @@ export class ProfileHonorEmployeeController extends Controller { @Delete("{honorId}") public async deleteTraning(@Path() honorId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.honorHistoryRepo.delete({ profileHonorId: honorId, }); diff --git a/src/controllers/ProfileHonorEmployeeTempController.ts b/src/controllers/ProfileHonorEmployeeTempController.ts new file mode 100644 index 00000000..7d50a3a7 --- /dev/null +++ b/src/controllers/ProfileHonorEmployeeTempController.ts @@ -0,0 +1,211 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileEmployeeHonor, + ProfileHonor, + UpdateProfileHonor, +} from "../entities/ProfileHonor"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileHonorHistory } from "../entities/ProfileHonorHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/honor") +@Tags("ProfileEmployeeHonor") +@Security("bearerAuth") +export class ProfileHonorEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private honorRepo = AppDataSource.getRepository(ProfileHonor); + private honorHistoryRepo = AppDataSource.getRepository(ProfileHonorHistory); + + @Get("user") + public async getHonorUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const record = await this.honorRepo.find({ + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(record); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "debfa8a7-83fb-4801-a940-8ae74e7638d3", + createdAt: "2024-03-12T03:10:05.594Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T03:10:05.594Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + detail: "string", + issueDate: "2024-03-12T10:09:47.000Z", + issuer: "string", + refCommandDate: "2024-03-12T10:09:47.000Z", + refCommandNo: "string", + isDate: true, + }, + ], + }) + public async getHonor(@Path() profileEmployeeId: string) { + const record = await this.honorRepo.findBy({ profileEmployeeId }); + return new HttpSuccess(record); + } + + /** + * + * @summary ประวัติแก้ไขเกียรติประวัติ by keycloak + * + */ + @Get("history/user") + public async honorHistoryUser(@Request() request: RequestWithUser) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const record = await this.honorHistoryRepo.find({ + where: { + histories: { + profileEmployeeId: profile.id, + }, + }, + }); + return new HttpSuccess(record); + } + + @Get("history/{honorId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "3bedb365-4a41-4df5-8f47-b6e143221d2c", + createdAt: "2024-03-12T03:11:01.395Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T03:11:01.395Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + detail: "detail", + issueDate: "2024-03-12T10:10:31.000Z", + issuer: "issuer", + refCommandDate: "2024-03-12T10:10:31.000Z", + refCommandNo: "refCommandNo", + isDate: true, + profileHonorId: "debfa8a7-83fb-4801-a940-8ae74e7638d3", + }, + { + id: "ba0e2f82-014e-46c6-8b82-a7c28eb5325f", + createdAt: "2024-03-12T03:10:05.657Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T03:10:05.657Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + detail: "string", + issueDate: "2024-03-12T10:09:47.000Z", + issuer: "string", + refCommandDate: "2024-03-12T10:09:47.000Z", + refCommandNo: "string", + isDate: true, + profileHonorId: "debfa8a7-83fb-4801-a940-8ae74e7638d3", + }, + ], + }) + public async honorHistory(@Path() honorId: string) { + const record = await this.honorHistoryRepo.findBy({ + profileHonorId: honorId, + }); + return new HttpSuccess(record); + } + + @Post() + public async newHonor(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeHonor) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileHonor(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.honorRepo.save(data); + + return new HttpSuccess(); + } + + @Patch("{honorId}") + public async editHonor( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileHonor, + @Path() honorId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.honorRepo.findOneBy({ id: honorId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileHonorHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileHonorId = honorId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([this.honorRepo.save(record), this.honorHistoryRepo.save(history)]); + + return new HttpSuccess(); + } + + @Delete("{honorId}") + public async deleteTraning(@Path() honorId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.honorHistoryRepo.delete({ + profileHonorId: honorId, + }); + + const result = await this.honorRepo.delete({ id: honorId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileInsigniaEmployeeController.ts b/src/controllers/ProfileInsigniaEmployeeController.ts index d59f1529..8d8f48cc 100644 --- a/src/controllers/ProfileInsigniaEmployeeController.ts +++ b/src/controllers/ProfileInsigniaEmployeeController.ts @@ -165,8 +165,11 @@ export class ProfileInsigniaEmployeeController extends Controller { } @Post() - public async newInsignia(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeInsignia) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + public async newInsignia( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeInsignia, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -206,7 +209,7 @@ export class ProfileInsigniaEmployeeController extends Controller { @Body() body: UpdateProfileInsignia, @Path() insigniaId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.insigniaRepo.findOneBy({ id: insigniaId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -233,7 +236,7 @@ export class ProfileInsigniaEmployeeController extends Controller { @Delete("{insigniaId}") public async deleteInsignia(@Path() insigniaId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.insigniaHistoryRepo.delete({ profileInsigniaId: insigniaId, }); diff --git a/src/controllers/ProfileInsigniaEmployeeTempController.ts b/src/controllers/ProfileInsigniaEmployeeTempController.ts new file mode 100644 index 00000000..4f927a6b --- /dev/null +++ b/src/controllers/ProfileInsigniaEmployeeTempController.ts @@ -0,0 +1,252 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileEmployeeInsignia, + ProfileInsignia, + UpdateProfileInsignia, +} from "../entities/ProfileInsignia"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileInsigniaHistory } from "../entities/ProfileInsigniaHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { Insignia } from "../entities/Insignia"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/insignia") +@Tags("ProfileEmployeeInsignia") +@Security("bearerAuth") +export class ProfileInsigniaEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private insigniaRepo = AppDataSource.getRepository(ProfileInsignia); + private insigniaHistoryRepo = AppDataSource.getRepository(ProfileInsigniaHistory); + private insigniaMetaRepo = AppDataSource.getRepository(Insignia); + + @Get("user") + public async getInsigniaUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const record = await this.insigniaRepo.find({ + relations: { + insignia: { + insigniaType: true, + }, + }, + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(record); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "c9d4dd52-25f5-491a-852d-28bfe00d66cb", + createdAt: "2024-03-12T03:05:09.393Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T03:05:09.393Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + year: 0, + no: "string", + volume: "string", + section: "string", + page: "string", + receiveDate: "2024-03-12T10:05:02.000Z", + insigniaId: "string", + insigniaType: "string", + dateAnnounce: "2024-03-12T10:05:02.000Z", + issue: "string", + volumeNo: "string", + refCommandDate: "2024-03-12T10:05:02.000Z", + refCommandNo: "string", + note: "string", + }, + ], + }) + public async getInsignia(@Path() profileEmployeeId: string) { + const record = await this.insigniaRepo.find({ + relations: { + insignia: { + insigniaType: true, + }, + }, + where: { profileEmployeeId }, + }); + return new HttpSuccess(record); + } + + @Get("history/{InsigniaId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "c363d13c-88bd-4954-adf5-70d3f5ca9c30", + createdAt: "2024-03-12T03:06:31.062Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T03:06:31.062Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + year: 0, + no: "no", + volume: "volume", + section: "section", + page: "page", + receiveDate: "2024-03-12T10:05:44.000Z", + insigniaId: "insigniaId", + insigniaType: "insigniaType", + dateAnnounce: "2024-03-12T10:05:44.000Z", + issue: "string", + volumeNo: "volumeNo", + refCommandDate: "2024-03-12T10:05:44.000Z", + refCommandNo: "refCommandNo", + note: "string", + profileInsigniaId: "c9d4dd52-25f5-491a-852d-28bfe00d66cb", + }, + { + id: "c9d4dd52-25f5-491a-852d-28bfe00d66cb", + createdAt: "2024-03-12T03:05:09.393Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T03:09:04.905Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + year: 0, + no: "string", + volume: "string", + section: "string", + page: "string", + receiveDate: "2024-03-12T10:05:02.000Z", + insigniaId: "string", + insigniaType: "string", + dateAnnounce: "2024-03-12T10:05:02.000Z", + issue: "string", + volumeNo: "string", + refCommandDate: "2024-03-12T10:05:02.000Z", + refCommandNo: "string", + note: "string", + profileInsigniaId: "c9d4dd52-25f5-491a-852d-28bfe00d66cb", + }, + ], + }) + public async getInsigniaHistory(@Path() InsigniaId: string) { + const record = await this.insigniaHistoryRepo.find({ + relations: { + insignia: { + insigniaType: true, + }, + }, + where: { + profileInsigniaId: InsigniaId, + }, + }); + return new HttpSuccess(record); + } + + @Post() + public async newInsignia( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeInsignia, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const insignia = await this.insigniaMetaRepo.findOne({ + where: { id: body.insigniaId }, + }); + if (!insignia) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลเครื่องราชฯ นี้"); + } + + const data = new ProfileInsignia(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.insigniaRepo.save(data); + + return new HttpSuccess(); + } + + @Patch("{insigniaId}") + public async editInsignia( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileInsignia, + @Path() insigniaId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.insigniaRepo.findOneBy({ id: insigniaId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const insignia = await this.insigniaMetaRepo.findOne({ + where: { id: body.insigniaId }, + }); + if (!insignia) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลเครื่องราชฯ นี้"); + } + + const history = new ProfileInsigniaHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileInsigniaId = insigniaId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([this.insigniaRepo.save(record), this.insigniaHistoryRepo.save(history)]); + + return new HttpSuccess(); + } + + @Delete("{insigniaId}") + public async deleteInsignia(@Path() insigniaId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.insigniaHistoryRepo.delete({ + profileInsigniaId: insigniaId, + }); + + const result = await this.insigniaRepo.delete({ id: insigniaId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileLeaveEmployeeController.ts b/src/controllers/ProfileLeaveEmployeeController.ts index 5c3a314b..6b69524f 100644 --- a/src/controllers/ProfileLeaveEmployeeController.ts +++ b/src/controllers/ProfileLeaveEmployeeController.ts @@ -68,7 +68,7 @@ export class ProfileLeaveEmployeeController extends Controller { @Post() public async newLeave(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeLeave) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); } @@ -107,7 +107,7 @@ export class ProfileLeaveEmployeeController extends Controller { @Body() body: UpdateProfileLeave, @Path() leaveId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.leaveRepo.findOneBy({ id: leaveId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -134,7 +134,7 @@ export class ProfileLeaveEmployeeController extends Controller { @Delete("{leaveId}") public async deleteLeave(@Path() leaveId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.leaveHistoryRepo.delete({ profileLeaveId: leaveId, }); diff --git a/src/controllers/ProfileLeaveEmployeeTempController.ts b/src/controllers/ProfileLeaveEmployeeTempController.ts new file mode 100644 index 00000000..6c295e6c --- /dev/null +++ b/src/controllers/ProfileLeaveEmployeeTempController.ts @@ -0,0 +1,150 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + ProfileLeaveHistory, + CreateProfileEmployeeLeave, + ProfileLeave, + UpdateProfileLeave, +} from "../entities/ProfileLeave"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { RequestWithUser } from "../middlewares/user"; +import { LeaveType } from "../entities/LeaveType"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/leave") +@Tags("ProfileLeave") +@Security("bearerAuth") +export class ProfileLeaveEmployeeController extends Controller { + private profileRepo = AppDataSource.getRepository(ProfileEmployee); + private leaveRepo = AppDataSource.getRepository(ProfileLeave); + private leaveHistoryRepo = AppDataSource.getRepository(ProfileLeaveHistory); + private leaveTypeRepository = AppDataSource.getRepository(LeaveType); + + @Get("user") + public async getLeaveUser(@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.leaveRepo.find({ + relations: { leaveType: true }, + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(record); + } + + @Get("{profileId}") + public async getLeave(@Path() profileId: string) { + const record = await this.leaveRepo.find({ + relations: { leaveType: true }, + where: { profileEmployeeId: profileId }, + }); + return new HttpSuccess(record); + } + + @Get("history/{leaveId}") + public async leaveHistory(@Path() leaveId: string) { + const record = await this.leaveHistoryRepo.find({ + relations: { leaveType: true }, + where: { profileLeaveId: leaveId }, + }); + return new HttpSuccess(record); + } + + @Post() + public async newLeave(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeLeave) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); + } + + const profile = await this.profileRepo.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const leaveType = await this.leaveTypeRepository.findOne({ + where: { id: body.leaveTypeId }, + }); + if (!leaveType) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทลานี้"); + } + + const data = new ProfileLeave(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.leaveRepo.save(data); + + return new HttpSuccess(); + } + + @Patch("{leaveId}") + public async editLeave( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileLeave, + @Path() leaveId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.leaveRepo.findOneBy({ id: leaveId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const leaveType = await this.leaveTypeRepository.findOne({ + where: { id: body.leaveTypeId }, + }); + if (!leaveType) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทลานี้"); + } + + const history = new ProfileLeaveHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileLeaveId = leaveId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([this.leaveRepo.save(record), this.leaveHistoryRepo.save(history)]); + + return new HttpSuccess(); + } + + @Delete("{leaveId}") + public async deleteLeave(@Path() leaveId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.leaveHistoryRepo.delete({ + profileLeaveId: leaveId, + }); + + const result = await this.leaveRepo.delete({ id: leaveId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileNopaidEmployeeController.ts b/src/controllers/ProfileNopaidEmployeeController.ts index 26cc91fc..bdf6bf7b 100644 --- a/src/controllers/ProfileNopaidEmployeeController.ts +++ b/src/controllers/ProfileNopaidEmployeeController.ts @@ -67,7 +67,7 @@ export class ProfileNopaidEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeNopaid, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); } @@ -100,7 +100,7 @@ export class ProfileNopaidEmployeeController extends Controller { @Body() body: UpdateProfileNopaid, @Path() nopaidId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.nopaidRepository.findOneBy({ id: nopaidId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -123,7 +123,7 @@ export class ProfileNopaidEmployeeController extends Controller { @Delete("{nopaidId}") public async deleteNopaid(@Path() nopaidId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.nopaidHistoryRepository.delete({ profileNopaidId: nopaidId, }); diff --git a/src/controllers/ProfileNopaidEmployeeTempController.ts b/src/controllers/ProfileNopaidEmployeeTempController.ts new file mode 100644 index 00000000..4db7982b --- /dev/null +++ b/src/controllers/ProfileNopaidEmployeeTempController.ts @@ -0,0 +1,139 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileNopaidHistory } from "../entities/ProfileNopaidHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { + CreateProfileEmployeeNopaid, + ProfileNopaid, + UpdateProfileNopaid, +} from "../entities/ProfileNopaid"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/nopaid") +@Tags("ProfileNopaid") +@Security("bearerAuth") +export class ProfileNopaidEmployeeController extends Controller { + private profileRepository = AppDataSource.getRepository(ProfileEmployee); + private nopaidRepository = AppDataSource.getRepository(ProfileNopaid); + private nopaidHistoryRepository = AppDataSource.getRepository(ProfileNopaidHistory); + + @Get("user") + public async getNopaidUser(@Request() request: { user: Record }) { + const profile = await this.profileRepository.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const lists = await this.nopaidRepository.find({ + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(lists); + } + + @Get("{profileId}") + public async getNopaid(@Path() profileId: string) { + const lists = await this.nopaidRepository.find({ + where: { profileEmployeeId: profileId }, + }); + return new HttpSuccess(lists); + } + + @Get("history/{nopaidId}") + public async nopaidHistory(@Path() nopaidId: string) { + const record = await this.nopaidHistoryRepository.find({ + where: { profileNopaidId: nopaidId }, + order: { createdAt: "DESC" }, + }); + return new HttpSuccess(record); + } + + @Post() + public async newNopaid( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeNopaid, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); + } + + const profile = await this.profileRepository.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileNopaid(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.nopaidRepository.save(data); + + return new HttpSuccess(); + } + + @Patch("{nopaidId}") + public async editNopaid( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileNopaid, + @Path() nopaidId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.nopaidRepository.findOneBy({ id: nopaidId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileNopaidHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileNopaidId = nopaidId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.nopaidRepository.save(record), + this.nopaidHistoryRepository.save(history), + ]); + + return new HttpSuccess(); + } + + @Delete("{nopaidId}") + public async deleteNopaid(@Path() nopaidId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.nopaidHistoryRepository.delete({ + profileNopaidId: nopaidId, + }); + + const result = await this.nopaidRepository.delete({ id: nopaidId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileOtherEmployeeController.ts b/src/controllers/ProfileOtherEmployeeController.ts index 11eee382..b843dc6b 100644 --- a/src/controllers/ProfileOtherEmployeeController.ts +++ b/src/controllers/ProfileOtherEmployeeController.ts @@ -64,7 +64,7 @@ export class ProfileOtherEmployeeController extends Controller { @Post() public async newOther(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeOther) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); } @@ -97,7 +97,7 @@ export class ProfileOtherEmployeeController extends Controller { @Body() body: UpdateProfileOther, @Path() otherId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.otherRepository.findOneBy({ id: otherId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -120,7 +120,7 @@ export class ProfileOtherEmployeeController extends Controller { @Delete("{otherId}") public async deleteOther(@Path() otherId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.otherHistoryRepository.delete({ profileOtherId: otherId, }); diff --git a/src/controllers/ProfileOtherEmployeeTempController.ts b/src/controllers/ProfileOtherEmployeeTempController.ts new file mode 100644 index 00000000..56cbb067 --- /dev/null +++ b/src/controllers/ProfileOtherEmployeeTempController.ts @@ -0,0 +1,136 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileOtherHistory } from "../entities/ProfileOtherHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import { + CreateProfileEmployeeOther, + ProfileOther, + UpdateProfileOther, +} from "../entities/ProfileOther"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/other") +@Tags("ProfileOther") +@Security("bearerAuth") +export class ProfileOtherEmployeeController extends Controller { + private profileRepository = AppDataSource.getRepository(ProfileEmployee); + private otherRepository = AppDataSource.getRepository(ProfileOther); + private otherHistoryRepository = AppDataSource.getRepository(ProfileOtherHistory); + + @Get("user") + public async getOtherUser(@Request() request: { user: Record }) { + const profile = await this.profileRepository.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const lists = await this.otherRepository.find({ + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(lists); + } + + @Get("{profileId}") + public async getOther(@Path() profileId: string) { + const lists = await this.otherRepository.find({ + where: { profileEmployeeId: profileId }, + }); + return new HttpSuccess(lists); + } + + @Get("history/{otherId}") + public async otherHistory(@Path() otherId: string) { + const record = await this.otherHistoryRepository.find({ + where: { profileOtherId: otherId }, + order: { createdAt: "DESC" }, + }); + return new HttpSuccess(record); + } + + @Post() + public async newOther(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeOther) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId"); + } + + const profile = await this.profileRepository.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileOther(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.otherRepository.save(data); + + return new HttpSuccess(); + } + + @Patch("{otherId}") + public async editOther( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileOther, + @Path() otherId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.otherRepository.findOneBy({ id: otherId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileOtherHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileOtherId = otherId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([ + this.otherRepository.save(record), + this.otherHistoryRepository.save(history), + ]); + + return new HttpSuccess(); + } + + @Delete("{otherId}") + public async deleteOther(@Path() otherId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.otherHistoryRepository.delete({ + profileOtherId: otherId, + }); + + const result = await this.otherRepository.delete({ id: otherId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +} diff --git a/src/controllers/ProfileSalaryEmployeeController.ts b/src/controllers/ProfileSalaryEmployeeController.ts index 58c0fe54..047560f7 100644 --- a/src/controllers/ProfileSalaryEmployeeController.ts +++ b/src/controllers/ProfileSalaryEmployeeController.ts @@ -69,7 +69,7 @@ export class ProfileSalaryEmployeeController extends Controller { @Request() req: RequestWithUser, @Body() body: CreateProfileSalaryEmployee, ) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -108,7 +108,7 @@ export class ProfileSalaryEmployeeController extends Controller { @Body() body: UpdateProfileSalaryEmployee, @Path() salaryId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.salaryRepo.findOneBy({ id: salaryId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -128,7 +128,7 @@ export class ProfileSalaryEmployeeController extends Controller { @Delete("{salaryId}") public async deleteSalaryEmployee(@Path() salaryId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.salaryHistoryRepo.delete({ profileSalaryId: salaryId, }); diff --git a/src/controllers/ProfileSalaryEmployeeTempController.ts b/src/controllers/ProfileSalaryEmployeeTempController.ts new file mode 100644 index 00000000..1570ec39 --- /dev/null +++ b/src/controllers/ProfileSalaryEmployeeTempController.ts @@ -0,0 +1,173 @@ +import { + Body, + Controller, + Delete, + Example, + 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"; +@Route("api/v1/org/profile-temp/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("{profileId}") + public async getSalaryEmployee(@Path() profileId: string) { + const record = await this.salaryRepo.find({ + where: { profileEmployeeId: profileId }, + order: { order: "ASC" }, + }); + return new HttpSuccess(record); + } + + @Get("history/{salaryId}") + public async salaryHistory(@Path() salaryId: string) { + const record = await this.salaryHistoryRepo.findBy({ + profileSalaryId: salaryId, + }); + return new HttpSuccess(record); + } + + @Post() + public async newSalaryEmployee( + @Request() req: RequestWithUser, + @Body() body: CreateProfileSalaryEmployee, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + 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 ดังกล่าว"); + } + + const dest_item = await this.salaryRepo.findOne({ + where: { profileEmployeeId: body.profileEmployeeId }, + order: { order: "DESC" }, + }); + + 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, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.salaryRepo.save(data); + + return new HttpSuccess(); + } + + @Patch("{salaryId}") + public async editSalaryEmployee( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileSalaryEmployee, + @Path() salaryId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.salaryRepo.findOneBy({ id: salaryId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileSalaryHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileSalaryId = salaryId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([this.salaryRepo.save(record), this.salaryHistoryRepo.save(history)]); + + return new HttpSuccess(); + } + + @Delete("{salaryId}") + public async deleteSalaryEmployee(@Path() salaryId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.salaryHistoryRepo.delete({ + profileSalaryId: salaryId, + }); + + const result = await this.salaryRepo.delete({ id: salaryId }); + + 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) { + 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(); + } +} diff --git a/src/controllers/ProfileTrainingEmployeeController.ts b/src/controllers/ProfileTrainingEmployeeController.ts index 2df7aaf1..f1334fbf 100644 --- a/src/controllers/ProfileTrainingEmployeeController.ts +++ b/src/controllers/ProfileTrainingEmployeeController.ts @@ -138,8 +138,11 @@ export class ProfileTrainingEmployeeController extends Controller { } @Post() - public async newTraining(@Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeTraining) { - await new permission().PermissionCreate(req,"SYS_REGISTRY_EMP"); + public async newTraining( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeTraining, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_EMP"); if (!body.profileEmployeeId) { throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); } @@ -172,7 +175,7 @@ export class ProfileTrainingEmployeeController extends Controller { @Body() body: UpdateProfileTraining, @Path() trainingId: string, ) { - await new permission().PermissionUpdate(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionUpdate(req, "SYS_REGISTRY_EMP"); const record = await this.trainingRepo.findOneBy({ id: trainingId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); @@ -192,7 +195,7 @@ export class ProfileTrainingEmployeeController extends Controller { @Delete("{trainingId}") public async deleteTraining(@Path() trainingId: string, @Request() req: RequestWithUser) { - await new permission().PermissionDelete(req,"SYS_REGISTRY_EMP"); + await new permission().PermissionDelete(req, "SYS_REGISTRY_EMP"); await this.trainingHistoryRepo.delete({ profileTrainingId: trainingId, }); diff --git a/src/controllers/ProfileTrainingEmployeeTempController.ts b/src/controllers/ProfileTrainingEmployeeTempController.ts new file mode 100644 index 00000000..3d7c618a --- /dev/null +++ b/src/controllers/ProfileTrainingEmployeeTempController.ts @@ -0,0 +1,211 @@ +import { + Body, + Controller, + Delete, + Example, + Get, + Patch, + Path, + Post, + Request, + Route, + Security, + Tags, +} from "tsoa"; +import { AppDataSource } from "../database/data-source"; +import { + CreateProfileEmployeeTraining, + ProfileTraining, + UpdateProfileTraining, +} from "../entities/ProfileTraining"; +import HttpSuccess from "../interfaces/http-success"; +import HttpStatus from "../interfaces/http-status"; +import HttpError from "../interfaces/http-error"; +import { ProfileTrainingHistory } from "../entities/ProfileTrainingHistory"; +import { RequestWithUser } from "../middlewares/user"; +import { ProfileEmployee } from "../entities/ProfileEmployee"; +import permission from "../interfaces/permission"; +@Route("api/v1/org/profile-temp/training") +@Tags("ProfileEmployeeTraining") +@Security("bearerAuth") +export class ProfileTrainingEmployeeController extends Controller { + private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee); + private trainingRepo = AppDataSource.getRepository(ProfileTraining); + private trainingHistoryRepo = AppDataSource.getRepository(ProfileTrainingHistory); + + @Get("user") + public async getTrainingUser(@Request() request: { user: Record }) { + const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub }); + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + const record = await this.trainingRepo.find({ + where: { profileEmployeeId: profile.id }, + }); + return new HttpSuccess(record); + } + + @Get("{profileEmployeeId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "3cf02fb7-2f0c-471b-b641-51d557375c0a", + createdAt: "2024-03-12T02:55:56.915Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T02:55:56.915Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + profileEmployeeId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201", + isActive: true, + startDate: "2024-03-12T09:55:23.000Z", + endDate: "2024-03-12T09:55:23.000Z", + numberOrder: "string", + topic: "string", + place: "string", + dateOrder: "2024-03-12T09:55:23.000Z", + department: "string", + duration: "string", + name: "string", + yearly: 0, + isDate: true, + }, + ], + }) + public async getTraining(@Path() profileEmployeeId: string) { + const record = await this.trainingRepo.findBy({ profileEmployeeId }); + return new HttpSuccess(record); + } + + @Get("history/{trainingId}") + @Example({ + status: 200, + message: "สำเร็จ", + result: [ + { + id: "6d4e9dbe-8697-4546-9651-0a1c3ea0a82d", + createdAt: "2024-03-12T02:55:56.971Z", + createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + lastUpdatedAt: "2024-03-12T02:55:56.971Z", + lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0", + createdFullName: "สาวิตรี ศรีสมัย", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + isActive: true, + startDate: "2024-03-12T09:55:23.000Z", + endDate: "2024-03-12T09:55:23.000Z", + numberOrder: "string", + topic: "string", + place: "string", + dateOrder: "2024-03-12T09:55:23.000Z", + department: "string", + duration: "string", + name: "string", + yearly: 0, + isDate: true, + profileTrainingId: "3cf02fb7-2f0c-471b-b641-51d557375c0a", + }, + { + id: "a251c176-3dac-4d09-9813-38c8db1127e3", + createdAt: "2024-03-12T02:58:17.917Z", + createdUserId: "00000000-0000-0000-0000-000000000000", + lastUpdatedAt: "2024-03-12T02:58:17.917Z", + lastUpdateUserId: "00000000-0000-0000-0000-000000000000", + createdFullName: "string", + lastUpdateFullName: "สาวิตรี ศรีสมัย", + isActive: true, + startDate: "2024-03-12T09:57:44.000Z", + endDate: "2024-03-12T09:57:44.000Z", + numberOrder: "string", + topic: "topic", + place: "place", + dateOrder: "2024-03-12T09:57:44.000Z", + department: "department", + duration: "string", + name: "name", + yearly: 0, + isDate: true, + profileTrainingId: "3cf02fb7-2f0c-471b-b641-51d557375c0a", + }, + ], + }) + public async trainingHistory(@Path() trainingId: string) { + const record = await this.trainingHistoryRepo.findBy({ + profileTrainingId: trainingId, + }); + return new HttpSuccess(record); + } + + @Post() + public async newTraining( + @Request() req: RequestWithUser, + @Body() body: CreateProfileEmployeeTraining, + ) { + await new permission().PermissionCreate(req, "SYS_REGISTRY_TEMP"); + if (!body.profileEmployeeId) { + throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId"); + } + + const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId }); + + if (!profile) { + throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); + } + + const data = new ProfileTraining(); + + const meta = { + createdUserId: req.user.sub, + createdFullName: req.user.name, + lastUpdateUserId: req.user.sub, + lastUpdateFullName: req.user.name, + }; + + Object.assign(data, { ...body, ...meta }); + + await this.trainingRepo.save(data); + + return new HttpSuccess(); + } + + @Patch("{trainingId}") + public async editTraining( + @Request() req: RequestWithUser, + @Body() body: UpdateProfileTraining, + @Path() trainingId: string, + ) { + await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP"); + const record = await this.trainingRepo.findOneBy({ id: trainingId }); + + if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + + const history = new ProfileTrainingHistory(); + + Object.assign(history, { ...record, id: undefined }); + Object.assign(record, body); + history.profileTrainingId = trainingId; + record.lastUpdateFullName = req.user.name; + history.lastUpdateFullName = req.user.name; + + await Promise.all([this.trainingRepo.save(record), this.trainingHistoryRepo.save(history)]); + + return new HttpSuccess(); + } + + @Delete("{trainingId}") + public async deleteTraining(@Path() trainingId: string, @Request() req: RequestWithUser) { + await new permission().PermissionDelete(req, "SYS_REGISTRY_TEMP"); + await this.trainingHistoryRepo.delete({ + profileTrainingId: trainingId, + }); + + const result = await this.trainingRepo.delete({ id: trainingId }); + + if (result.affected == undefined || result.affected <= 0) { + throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + } + + return new HttpSuccess(); + } +}