import { OrgRevision } from "../entities/OrgRevision"; import { AppDataSource } from "../database/data-source"; import { PosMaster } from "../entities/PosMaster"; import { Position } from "../entities/Position"; import { EmployeePosMaster } from "../entities/EmployeePosMaster"; import { EmployeePosition } from "../entities/EmployeePosition"; import { In, IsNull, MoreThan, Not } from "typeorm"; import { RequestWithUser } from "../middlewares/user"; import { Command } from "../entities/Command"; import { ProfileSalary } from "../entities/ProfileSalary"; export function calculateAge(start: Date, end = new Date()) { if (start.getTime() > end.getTime()) return null; let year = end.getFullYear() - start.getFullYear(); let month = end.getMonth() - start.getMonth(); let day = end.getDate() - start.getDate(); // if (month < 0) { // month += 12; // year -= 1; // } // if (day < 0) { // month -= 1; // day = // new Date(start.getFullYear(), start.getMonth(), 0).getDate() - // start.getDate() + // end.getDate(); // } if (day < 0) { month -= 1; day += new Date(end.getFullYear(), end.getMonth(), 0).getDate(); } if (month < 0) { month += 12; year -= 1; } return { year, month, day }; } export async function calculateGovAge(profileId: string) { const records = await AppDataSource.getRepository(ProfileSalary).find({ where: { profileId: profileId, }, select: ["date", "dateGovernment", "isGovernment"], order: { order: "ASC" }, }); // หา record ทั้งหมด if (!records || records.length === 0) { return null; } let sumYears = 0; let sumMonths = 0; let sumDays = 0; let endDateFristRec: any; endDateFristRec = await AppDataSource.getRepository(ProfileSalary).findOne({ where: { profileId: profileId, dateGovernment: Not(IsNull()), isGovernment: false, }, select: ["date", "dateGovernment", "isGovernment", "order"], order: { order: "ASC" }, }); // หา isGovernment: false record แรก let totalYears1 = 0; let totalMonths1 = 0; let totalDays1 = 0; const firstStartDate = new Date(records[0].date); const firstEndDate = endDateFristRec?new Date(endDateFristRec.dateGovernment):new Date(); console.log("[firstStartDate]",firstStartDate); console.log("[firstEndDate]",firstEndDate); totalYears1 = firstEndDate.getFullYear() - firstStartDate.getFullYear(); totalMonths1 = firstEndDate.getMonth() - firstStartDate.getMonth(); totalDays1 = firstEndDate.getDate() - firstStartDate.getDate(); if (totalDays1 < 0) { totalMonths1 -= 1; // หาวันในเดือนก่อนหน้า const lastMonth = new Date(firstEndDate.getFullYear(), firstEndDate.getMonth(), 0).getDate(); totalDays1 += lastMonth; } if (totalMonths1 < 0) { totalMonths1 += 12; totalYears1 -= 1; } const records_middle = await AppDataSource.getRepository(ProfileSalary).find({ where: { profileId: profileId, order: MoreThan(endDateFristRec?.order), dateGovernment: Not(IsNull()), }, select: ["date", "dateGovernment", "isGovernment", "order"], order: { order: "ASC" }, }); // หา record order ที่ทำหลังจาก endDateFristRec console.log("[Gov1]", totalYears1, totalMonths1, totalDays1); if (!records_middle || records_middle.length === 0) { // ถ้าไม่เจอแปลว่ากำลังพักราชการอยู่หรือยังไม่เคยพักราชการ sumYears = totalYears1, sumMonths = totalMonths1, sumDays = totalDays1 console.log("[SumGov1]", sumYears, sumMonths, sumDays); return { sumYears, sumMonths, sumDays, }; } let totalYears2 = 0; let totalMonths2 = 0; let totalDays2 = 0; for (let i = 0; i < records_middle.length; i++) { const startDate = new Date(records_middle[i].dateGovernment); const endDate = (i < records_middle.length - 1) ? new Date(records_middle[i + 1].dateGovernment) : new Date(); // วันที่ปัจจุบันถ้าเป็นช่วงสุดท้าย if (records_middle[i].isGovernment === false && records_middle[i + 1].isGovernment === false) { break; } if (records_middle[i].isGovernment === false && i === records_middle.length - 1) { break; } console.log("[SDate]", startDate); console.log("[EDate]", endDate); // คำนวณระยะเวลา let years_mid = endDate.getFullYear() - startDate.getFullYear(); let months_mid = endDate.getMonth() - startDate.getMonth(); let days_mid = endDate.getDate() - startDate.getDate(); if (days_mid < 0) { months_mid--; const lastMonthDays = new Date(endDate.getFullYear(), endDate.getMonth(), 0).getDate(); days_mid += lastMonthDays; // ปรับวันให้ถูกต้อง } // การปรับเดือน if (months_mid < 0) { months_mid += 12; years_mid--; } // รวมเข้ากับ total totalYears2 += years_mid; totalMonths2 += months_mid; totalDays2 += days_mid; } // การปรับค่าหาก totalMonths2 เกิน 12 if (totalMonths2 >= 12) { totalYears2 += Math.floor(totalMonths2 / 12); totalMonths2 = totalMonths2 % 12; } // การปรับค่าหาก totalDays2 เกินจำนวนวันในเดือน const daysInCurrentMonth = new Date( new Date().getFullYear(), new Date().getMonth() + 1, 0, ).getDate(); if (totalDays2 >= daysInCurrentMonth) { totalMonths2 += Math.floor(totalDays2 / daysInCurrentMonth); totalDays2 = totalDays2 % daysInCurrentMonth; } sumYears = totalYears1 + totalYears2; sumMonths = totalMonths1 + totalMonths2; sumDays = totalDays1 + totalDays2; if (sumMonths >= 12) { sumYears += Math.floor(sumMonths / 12); sumMonths = sumMonths % 12; } console.log("[data1]",totalYears1+"/"+totalMonths1+"/"+totalDays1); console.log("[data2]",totalYears2+"/"+totalMonths2+"/"+totalDays2); console.log("[SumGovAge]", sumYears, sumMonths, sumDays); return { sumYears, sumMonths, sumDays, }; } export function calculateRetireDate(birthDate: Date) { // let _birthDate = birthDate; // _birthDate.setFullYear(_birthDate.getFullYear() + 60); var year = d.getFullYear(); var d = birthDate; var year = d.getFullYear(); var month = d.getMonth(); var day = d.getDate(); var c = new Date(year + 60, month, day - 1); return c; } export function calculateRetireLaw(birthDate: Date) { let dd = birthDate.getDate(); let mm = birthDate.getMonth(); let yy = birthDate.getFullYear(); let flag = true; switch (mm) { case 9: if (dd >= 2) flag = false; break; case 10: flag = false; break; case 11: flag = false; break; } if (flag == true) return new Date(`${yy + 60}-09-30T00:00:00.000+07:00`); return new Date(`${yy + 61}-09-30T00:00:00.000+07:00`); } export function calculateRetireYear(birthDate: Date) { let dd = birthDate.getDate(); let mm = birthDate.getMonth(); let yy = birthDate.getFullYear(); let flag = true; switch (mm) { case 10: if (dd >= 2) flag = false; break; case 11: break; case 12: break; } if (flag) return yy + 60; return yy + 61; } export async function removeProfileInOrganize(profileId: string, type: string) { const currentRevision = await AppDataSource.getRepository(OrgRevision) .createQueryBuilder("orgRevision") .where("orgRevision.orgRevisionIsDraft = false") .andWhere("orgRevision.orgRevisionIsCurrent = true") .getOne(); if (!currentRevision) { return; } if (type === "OFFICER") { const findProfileInposMaster = await AppDataSource.getRepository(PosMaster) .createQueryBuilder("posMaster") .where("posMaster.orgRevisionId = :orgRevisionId", { orgRevisionId: currentRevision?.id }) .andWhere("posMaster.current_holderId = :profileId", { profileId }) .getOne(); await AppDataSource.getRepository(PosMaster) .createQueryBuilder() .update(PosMaster) .set({ current_holderId: null }) .where("id = :id", { id: findProfileInposMaster?.id }) .execute(); if (!findProfileInposMaster) { return; } const findPosition = await AppDataSource.getRepository(Position) .createQueryBuilder("position") .where("position.posMasterId = :posMasterId", { posMasterId: findProfileInposMaster?.id }) .getMany(); if (!findPosition) { return; } await AppDataSource.getRepository(Position) .createQueryBuilder() .update(Position) .set({ positionIsSelected: false }) .where("id IN (:...ids)", { ids: findPosition.map((item) => item.id) }) .execute(); } if (type === "EMPLOYEE") { const findProfileInEmpPosMaster = await AppDataSource.getRepository(EmployeePosMaster) .createQueryBuilder("employeePosMaster") .where("employeePosMaster.orgRevisionId = :orgRevisionId", { orgRevisionId: currentRevision?.id, }) .andWhere("employeePosMaster.current_holderId = :profileId", { profileId }) .getOne(); await AppDataSource.getRepository(EmployeePosMaster) .createQueryBuilder() .update(EmployeePosMaster) .set({ current_holderId: null }) .where("id = :id", { id: findProfileInEmpPosMaster?.id }) .execute(); if (!findProfileInEmpPosMaster) { return; } const findEmpPosition = await AppDataSource.getRepository(EmployeePosition) .createQueryBuilder("employeePosition") .where("employeePosition.posMasterId = :posMasterId", { posMasterId: findProfileInEmpPosMaster?.id, }) .getMany(); if (!findEmpPosition) { return; } await AppDataSource.getRepository(EmployeePosition) .createQueryBuilder() .update(EmployeePosition) .set({ positionIsSelected: false }) .where("id IN (:...ids)", { ids: findEmpPosition.map((item) => item.id) }) .execute(); } } export async function checkReturnCommandType(commandId: string) { const commandRepository = AppDataSource.getRepository(Command); const _type = await commandRepository.findOne({ where: { id: commandId }, relations: ["commandType"], }); if (!["C-PM-08", "C-PM-09"].includes(String(_type?.commandType.code))) { return false; } return true; } export async function checkExceptCommandType(commandId: string) { const commandRepository = AppDataSource.getRepository(Command); const _type = await commandRepository.findOne({ where: { id: commandId }, relations: ["commandType"], }); if (!["C-PM-25", "C-PM-26"].includes(String(_type?.commandType.code))) { return false; } return true; } export async function checkCommandType(commandId: string) { const commandRepository = AppDataSource.getRepository(Command); const _type = await commandRepository.findOne({ where: { id: commandId }, relations: ["commandType"], }); if (!["C-PM-12", "C-PM-13", "C-PM-17", "C-PM-18", "C-PM-23", "C-PM-19", "C-PM-20"].includes(String(_type?.commandType.code))) { return false; } return true; } //logs export type DataDiff = { before: any; after: any; }; export type LogSequence = { action: string; status: "success" | "error"; description: string; query?: any; request?: { method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; url?: string; payload?: string; response?: string; }; }; export function setLogDataDiff(req: RequestWithUser, data: DataDiff) { req.app.locals.logData.dataDiff = { before: JSON.stringify(data.before), after: JSON.stringify(data.after), }; } export function addLogSequence(req: RequestWithUser, data: LogSequence) { if (!req?.app?.locals?.logData?.sequence) { req.app.locals.logData.sequence = []; } req.app.locals.logData.sequence = req.app.locals.logData.sequence.concat(data); } export function editLogSequence(req: RequestWithUser, index: number, data: LogSequence) { req.app.locals.logData.sequence[index] = data; } export function commandTypePath(commandCode: string): string | null { switch (commandCode) { case "C-PM-01": return "/placement/recruit/report"; // case "C-PM-02": return "/placement/candidate/report"; // case "C-PM-03": return "/placement/appoint/report"; case "C-PM-04": return "/placement/move/report"; case "C-PM-05": return "/placement/appointment/appoint/report"; case "C-PM-06": return "/placement/slip/report"; case "C-PM-07": return "/placement/appointment/move/report"; case "C-PM-08": return "/retirement/other/appoint/report"; case "C-PM-09": return "/retirement/other/out/report"; case "C-PM-10": return "/probation/report/command10/officer/report"; case "C-PM-11": return "/probation/report/command11/officer/report";//PROBATION case "C-PM-12": return "/probation/report/command12/officer/report";//PROBATION case "C-PM-13": return "/placement/transfer/command/report"; case "C-PM-14": return "/placement/receive/command/report"; case "C-PM-15": return "/placement/officer/command/report"; case "C-PM-16": return "/placement/repatriation/command/report"; case "C-PM-17": return "/retirement/resign/command/report"; case "C-PM-18": return "/retirement/out/command/report"; case "C-PM-19": return "/discipline/result/command19/report"; case "C-PM-20": return "/discipline/result/command20/report"; case "C-PM-21": return "/org/command/command21/employee/report";//ORG case "C-PM-22": return "/placement/appointment/employee-appoint/report"; case "C-PM-23": return "/retirement/resign/employee/report"; case "C-PM-24": return "/placement/appointment/employee-move/report"; case "C-PM-25": return "/discipline/result/command25/report"; case "C-PM-26": return "/discipline/result/command26/report"; case "C-PM-27": return "/discipline/result/command27/report"; case "C-PM-28": return "/discipline/result/command28/report"; case "C-PM-29": return "/discipline/result/command29/report"; case "C-PM-30": return "/discipline/result/command30/report"; case "C-PM-31": return "/discipline/result/command31/report"; case "C-PM-32": return "/discipline/result/command32/report"; case "C-PM-33": return "/salary/report/command/officer/report";//SALARY case "C-PM-34": return "/salary/report/command/officer/report";//SALARY case "C-PM-35": return "/salary/report/command/officer/report";//SALARY case "C-PM-36": return "/salary/report/command/employee/report";//SALARY case "C-PM-37": return "/salary/report/command/employee/report";//SALARY case "C-PM-38": return "/org/command/command38/officer/report";//ORG case "C-PM-39": return "/placement/appointment/slip/report"; case "C-PM-40": return "/org/command/command40/officer/report";//ORG case "C-PM-41": return "/retirement/resign/leave-cancel/report"; default: return null; } }