Merge branch 'develop'

* develop:
  update report
  import
  fix issue #1184 รายการปรับระดับชั้นงาน+ย้าย (ตัวย่อระดับชั้นงานแสดงไม่ครบ)
This commit is contained in:
Warunee Tamkoo 2025-02-12 12:07:43 +07:00
commit 5344845c8c
6 changed files with 576 additions and 361 deletions

View file

@ -44,6 +44,7 @@ import { OrgChild3 } from "../entities/OrgChild3";
import { OrgChild4 } from "../entities/OrgChild4"; import { OrgChild4 } from "../entities/OrgChild4";
import { IMPORT_ORG } from "../entities/IMPORT_ORG"; import { IMPORT_ORG } from "../entities/IMPORT_ORG";
import { OrgRevision } from "../entities/OrgRevision"; import { OrgRevision } from "../entities/OrgRevision";
import { OFFICER } from "../entities/OFFICER";
@Route("api/v1/org/upload") @Route("api/v1/org/upload")
@Tags("UPLOAD") @Tags("UPLOAD")
@ -83,118 +84,24 @@ export class ImportDataController extends Controller {
private orgChild3Repo = AppDataSource.getRepository(OrgChild3); private orgChild3Repo = AppDataSource.getRepository(OrgChild3);
private orgChild4Repo = AppDataSource.getRepository(OrgChild4); private orgChild4Repo = AppDataSource.getRepository(OrgChild4);
private IMPORT_ORGRepo = AppDataSource.getRepository(IMPORT_ORG); private IMPORT_ORGRepo = AppDataSource.getRepository(IMPORT_ORG);
private OFFICERRepo = AppDataSource.getRepository(OFFICER);
/** /**
* @summary * @summary
*/ */
@Post("uploadProfile-Officer") @Post("uploadProfile-Officer")
async UploadFileSqlOfficer(@Request() request: { user: Record<string, any> }) { async UploadFileSqlOfficer(@Request() request: { user: Record<string, any> }) {
let users = []; const OFFICER = await this.OFFICERRepo.find();
let rowCount = 0;
const filePath = path.resolve(__dirname, "OFFICER.csv"); // Corrected file path
const readStream = fs.createReadStream(filePath).pipe(csvParser());
let profiles: any = [];
let null_: any = null; let null_: any = null;
for await (const item of readStream) { for await (const item of OFFICER) {
// readStream.map(async (item: any) => { let existingProfile = await this.profileRepo.findOne({
rowCount++; where: { citizenId: item.ID },
let type_: any = null;
let level_: any = null;
const profile = new Profile();
// if (item["FLAG_RETIRE_STATUSxxxx"] != "" && item["FLAG_RETIRE_STATUSxxxx"] != null) {
// continue;
// }
// if (item["FLAG_PERSON_TYPExxxx"] != "1") {
// continue;
// }
if (new Date(item["RET_YEAR"]).getFullYear() >= 2567) {
continue;
}
const existingProfile = await this.profileRepo.findOne({
where: { citizenId: item["ID"] },
}); });
if (existingProfile) { if (existingProfile == null) {
profile.id = existingProfile.id; } else {
// continue; existingProfile.position = item["WORK_LINE_NAME"] == "" ? null_ : item["WORK_LINE_NAME"];
await this.profileRepo.save(existingProfile);
} }
if (item["TYPE"]) {
type_ = await this.posTypeRepo.findOne({
where: { posTypeName: item["TYPE"] },
});
}
if (item["LEVEL"]) {
if (type_ == null) {
level_ = await this.posLevelRepo.findOne({
where: {
posLevelName: item["LEVEL"],
},
});
} else {
level_ = await this.posLevelRepo.findOne({
where: {
posLevelName: item["LEVEL"],
posTypeId: type_.id,
},
});
}
}
let dateRetire = new Date(item["BORN"]);
profile.citizenId = item["ID"] == "" ? "" : item["ID"];
profile.rank =
item["RANK_NAME"] == "" ||
item["RANK_NAME"] == "นาย" ||
item["RANK_NAME"] == "นาง" ||
item["RANK_NAME"] == "นางสาว"
? null
: item["RANK_NAME"];
profile.prefix = item["RANK_NAME"] == "" ? null : item["RANK_NAME"];
profile.prefixMain =
item["RANK_NAME"] == "" ||
(item["RANK_NAME"] != "นาย" && item["RANK_NAME"] != "นาง" && item["RANK_NAME"] != "นางสาว")
? null
: item["RANK_NAME"];
profile.firstName = item["FNAME"] == "" ? null : item["FNAME"];
profile.lastName = item["LNAME"] == "" ? null : item["LNAME"];
profile.gender = item["SEX"] == "1" ? "ชาย" : item["SEX"] == "2" ? "หญิง" : null_;
profile.birthDate = item["BORN"] == "" ? null_ : new Date(item["BORN"]);
profile.dateAppoint =
item["BEGIN_ENTRY_DATE"] == "" ? null_ : new Date(item["BEGIN_ENTRY_DATE"]);
profile.dateStart =
item["BEGIN_ENTRY_DATE"] == "" ? null_ : new Date(item["BEGIN_ENTRY_DATE"]);
profile.dateRetire = dateRetire == null ? null_ : calculateRetireDate(dateRetire);
profile.dateRetireLaw = dateRetire == null ? null_ : calculateRetireLaw(dateRetire);
profile.position = item["WORK_LINE_NAME"] == "" ? null : item["WORK_LINE_NAME"];
profile.posTypeId =
type_ != null && type_.posTypeName == item["TYPE"] && type_ ? type_.id : null;
profile.posLevelId =
level_ != null && level_.posLevelName == item["LEVEL"] && level_ ? level_.id : null;
profile.relationship =
item["สถานภาพ"] == "" ? "" : Extension.CheckRelationship(item["สถานภาพ"]);
// profile.isLeave =
// item["FLAG_RETIRE_STATUSxxxx"] == "" || item["FLAG_RETIRE_STATUSxxxx"] == null ? false : true;
profile.createdUserId = request.user.sub;
profile.createdFullName = request.user.name;
profile.lastUpdateUserId = request.user.sub;
profile.lastUpdateFullName = request.user.name;
profile.createdAt = new Date();
profile.lastUpdatedAt = new Date();
// profiles.push(profile);
console.log(">>>>>>>>>>>>>>>>>>>" + rowCount);
// if (profiles.length === BATCH_SIZE) {
await this.profileRepo.save(profile);
// profiles = await [];
// if (global.gc) {
// global.gc();
// }
// }
} }
// )
// );
// console.log(rowCount);
// await this.profileRepo.save(profiles);
return new HttpSuccess(); return new HttpSuccess();
} }
@ -296,7 +203,7 @@ export class ImportDataController extends Controller {
.select(["profile.citizenId", "profile.id"]) .select(["profile.citizenId", "profile.id"])
.orderBy("profile.citizenId", "ASC") .orderBy("profile.citizenId", "ASC")
// .skip(0) // .skip(0)
// .take(20) // .take(1000)
.getManyAndCount(); .getManyAndCount();
// for (var i = 1; i <= total / BATCH_SIZE; i++) { // for (var i = 1; i <= total / BATCH_SIZE; i++) {
// const profiles = await AppDataSource.getRepository(Profile) // const profiles = await AppDataSource.getRepository(Profile)
@ -546,7 +453,7 @@ export class ImportDataController extends Controller {
.select(["profile.citizenId", "profile.id"]) .select(["profile.citizenId", "profile.id"])
.orderBy("profile.citizenId", "ASC") .orderBy("profile.citizenId", "ASC")
// .skip(0) // .skip(0)
// .take(20) // .take(1000)
.getManyAndCount(); .getManyAndCount();
// for (var i = 1; i <= total / BATCH_SIZE; i++) { // for (var i = 1; i <= total / BATCH_SIZE; i++) {
// const profiles = await AppDataSource.getRepository(Profile) // const profiles = await AppDataSource.getRepository(Profile)
@ -853,7 +760,14 @@ export class ImportDataController extends Controller {
profiles.map(async (_item) => { profiles.map(async (_item) => {
const existingProfile = await this.HR_EDUCATIONRepo.find({ const existingProfile = await this.HR_EDUCATIONRepo.find({
where: { CIT: _item.citizenId }, where: { CIT: _item.citizenId },
select: ["CIT", "EDUCATION_CODE", "START_EDUCATION_YEAR", "EDUCATION_YEAR", "INSTITUE"], select: [
"CIT",
"EDUCATION_CODE",
"START_EDUCATION_YEAR",
"EDUCATION_YEAR",
"INSTITUE",
"EDUCATION_SEQ",
],
}); });
const educationLevel = await this.profileEducationRepo.findOne({ const educationLevel = await this.profileEducationRepo.findOne({
@ -885,6 +799,7 @@ export class ImportDataController extends Controller {
education.profileId = _item.id; education.profileId = _item.id;
education.degree = educationCode ? educationCode.EDUCATION_NAME : ""; education.degree = educationCode ? educationCode.EDUCATION_NAME : "";
education.institute = item.INSTITUE; education.institute = item.INSTITUE;
education.level = item.EDUCATION_SEQ ? null_ : Number(item.EDUCATION_SEQ);
education.startDate = startDate; education.startDate = startDate;
education.endDate = endDate; education.endDate = endDate;
education.createdUserId = request.user.sub; education.createdUserId = request.user.sub;
@ -1468,15 +1383,22 @@ export class ImportDataController extends Controller {
*/ */
@Post("ImportOrg") @Post("ImportOrg")
async ImportOrg(@Request() request: { user: Record<string, any> }) { async ImportOrg(@Request() request: { user: Record<string, any> }) {
const IMPORT_ORG = await this.IMPORT_ORGRepo.find({
where: { orgChild1: Not(IsNull()) || Not("") },
});
const orgRevision = await this.orgRevisionRepo.findOne({ const orgRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }, where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
}); });
if (orgRevision == null) return new HttpSuccess(); if (orgRevision == null) return new HttpSuccess();
//create root
const IMPORT_CHILD = await this.IMPORT_ORGRepo.find({
where: {
orgRoot: Not(""),
orgChild1: "",
orgChild2: "",
orgChild3: "",
},
});
await Promise.all( await Promise.all(
IMPORT_ORG.map(async (item) => { IMPORT_CHILD.map(async (item) => {
const orgRoot = new OrgRoot(); const orgRoot = new OrgRoot();
orgRoot.orgRootName = item.orgRoot; orgRoot.orgRootName = item.orgRoot;
orgRoot.orgRootShortName = item.orgShortname; orgRoot.orgRootShortName = item.orgShortname;
@ -1495,98 +1417,254 @@ export class ImportDataController extends Controller {
orgRoot.createdAt = new Date(); orgRoot.createdAt = new Date();
orgRoot.lastUpdatedAt = new Date(); orgRoot.lastUpdatedAt = new Date();
await this.orgRootRepo.save(orgRoot); await this.orgRootRepo.save(orgRoot);
}),
);
const IMPORT_CHILD1 = await this.IMPORT_ORGRepo.find({ //create child1
where: { orgChild2: Not(IsNull()), orgRoot: item.orgRoot }, const IMPORT_CHILD1 = await this.IMPORT_ORGRepo.find({
where: {
orgRoot: Not(""),
orgChild1: Not(""),
orgChild2: "",
orgChild3: "",
},
});
await Promise.all(
IMPORT_CHILD1.map(async (item) => {
const orgChild1 = new OrgChild1();
let orgRoot = await this.orgRootRepo.findOne({
where: { orgRootName: item.orgRoot },
}); });
await Promise.all( if (orgRoot == null) {
IMPORT_CHILD1.map(async (item1) => { orgRoot = new OrgRoot();
const orgChild1 = new OrgChild1(); orgRoot.orgRootName = item.orgRoot;
orgChild1.orgRootId = orgRoot.id; orgRoot.orgRootShortName = item.orgShortname;
orgChild1.orgChild1Name = item1.orgChild1; const rank: any = item.orgRank;
orgChild1.orgChild1ShortName = item.orgShortname; orgRoot.orgRootRank = rank;
const rank: any = item.orgRank; orgRoot.orgRootRankSub = item.orgSubRank;
orgChild1.orgChild1Rank = rank; orgRoot.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
orgChild1.orgChild1RankSub = item.orgSubRank; orgRoot.DIVISION_CODE = item.DIVISION_CODE;
orgChild1.DEPARTMENT_CODE = item.DEPARTMENT_CODE; orgRoot.SECTION_CODE = item.SECTION_CODE;
orgChild1.DIVISION_CODE = item.DIVISION_CODE; orgRoot.JOB_CODE = item.JOB_CODE;
orgChild1.SECTION_CODE = item.SECTION_CODE; orgRoot.orgRevisionId = orgRevision.id;
orgChild1.JOB_CODE = item.JOB_CODE; orgRoot.createdUserId = request.user.sub;
orgChild1.orgRevisionId = orgRevision.id; orgRoot.createdFullName = request.user.name;
orgChild1.createdUserId = request.user.sub; orgRoot.lastUpdateUserId = request.user.sub;
orgChild1.createdFullName = request.user.name; orgRoot.lastUpdateFullName = request.user.name;
orgChild1.lastUpdateUserId = request.user.sub; orgRoot.createdAt = new Date();
orgChild1.lastUpdateFullName = request.user.name; orgRoot.lastUpdatedAt = new Date();
orgChild1.createdAt = new Date(); await this.orgRootRepo.save(orgRoot);
orgChild1.lastUpdatedAt = new Date(); }
await this.orgChild1Repo.save(orgChild1);
const IMPORT_CHILD2 = await this.IMPORT_ORGRepo.find({
where: {
orgChild3: Not(IsNull()),
orgRoot: item.orgRoot,
orgChild1: item1.orgChild1,
},
});
await Promise.all( orgChild1.orgRootId = orgRoot.id;
IMPORT_CHILD2.map(async (item2) => { orgChild1.orgChild1Name = item.orgChild1;
const orgChild2 = new OrgChild2(); orgChild1.orgChild1ShortName = item.orgShortname;
orgChild2.orgRootId = orgRoot.id; const rank: any = item.orgRank;
orgChild2.orgChild1Id = orgChild1.id; orgChild1.orgChild1Rank = rank;
orgChild2.orgChild2Name = item2.orgChild2; orgChild1.orgChild1RankSub = item.orgSubRank;
orgChild2.orgChild2ShortName = item.orgShortname; orgChild1.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
const rank: any = item.orgRank; orgChild1.DIVISION_CODE = item.DIVISION_CODE;
orgChild2.orgChild2Rank = rank; orgChild1.SECTION_CODE = item.SECTION_CODE;
orgChild2.orgChild2RankSub = item.orgSubRank; orgChild1.JOB_CODE = item.JOB_CODE;
orgChild2.DEPARTMENT_CODE = item.DEPARTMENT_CODE; orgChild1.orgRevisionId = orgRevision.id;
orgChild2.DIVISION_CODE = item.DIVISION_CODE; orgChild1.createdUserId = request.user.sub;
orgChild2.SECTION_CODE = item.SECTION_CODE; orgChild1.createdFullName = request.user.name;
orgChild2.JOB_CODE = item.JOB_CODE; orgChild1.lastUpdateUserId = request.user.sub;
orgChild2.orgRevisionId = orgRevision.id; orgChild1.lastUpdateFullName = request.user.name;
orgChild2.createdUserId = request.user.sub; orgChild1.createdAt = new Date();
orgChild2.createdFullName = request.user.name; orgChild1.lastUpdatedAt = new Date();
orgChild2.lastUpdateUserId = request.user.sub; await this.orgChild1Repo.save(orgChild1);
orgChild2.lastUpdateFullName = request.user.name; }),
orgChild2.createdAt = new Date(); );
orgChild2.lastUpdatedAt = new Date();
await this.orgChild2Repo.save(orgChild2);
const IMPORT_CHILD3 = await this.IMPORT_ORGRepo.find({
where: {
orgRoot: item.orgRoot,
orgChild1: item1.orgChild1,
orgChild2: item2.orgChild2,
},
});
await Promise.all( //create child2
IMPORT_CHILD3.map(async (item) => { const IMPORT_CHILD2 = await this.IMPORT_ORGRepo.find({
const orgChild3 = new OrgChild3(); where: {
orgChild3.orgRootId = orgRoot.id; orgRoot: Not(""),
orgChild3.orgChild1Id = orgChild1.id; orgChild1: Not(""),
orgChild3.orgChild2Id = orgChild2.id; orgChild2: Not(""),
orgChild3.orgChild3Name = item.orgChild3; orgChild3: "",
orgChild3.orgChild3ShortName = item.orgShortname; },
const rank: any = item.orgRank; });
orgChild3.orgChild3Rank = rank; await Promise.all(
orgChild3.orgChild3RankSub = item.orgSubRank; IMPORT_CHILD2.map(async (item) => {
orgChild3.DEPARTMENT_CODE = item.DEPARTMENT_CODE; const orgChild2 = new OrgChild2();
orgChild3.DIVISION_CODE = item.DIVISION_CODE; let orgRoot = await this.orgRootRepo.findOne({
orgChild3.SECTION_CODE = item.SECTION_CODE; where: { orgRootName: item.orgRoot },
orgChild3.JOB_CODE = item.JOB_CODE; });
orgChild3.orgRevisionId = orgRevision.id; if (orgRoot == null) {
orgChild3.createdUserId = request.user.sub; orgRoot = new OrgRoot();
orgChild3.createdFullName = request.user.name; orgRoot.orgRootName = item.orgRoot;
orgChild3.lastUpdateUserId = request.user.sub; orgRoot.orgRootShortName = item.orgShortname;
orgChild3.lastUpdateFullName = request.user.name; const rank: any = item.orgRank;
orgChild3.createdAt = new Date(); orgRoot.orgRootRank = rank;
orgChild3.lastUpdatedAt = new Date(); orgRoot.orgRootRankSub = item.orgSubRank;
await this.orgChild3Repo.save(orgChild3); orgRoot.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
}), orgRoot.DIVISION_CODE = item.DIVISION_CODE;
); orgRoot.SECTION_CODE = item.SECTION_CODE;
}), orgRoot.JOB_CODE = item.JOB_CODE;
); orgRoot.orgRevisionId = orgRevision.id;
}), orgRoot.createdUserId = request.user.sub;
); orgRoot.createdFullName = request.user.name;
orgRoot.lastUpdateUserId = request.user.sub;
orgRoot.lastUpdateFullName = request.user.name;
orgRoot.createdAt = new Date();
orgRoot.lastUpdatedAt = new Date();
await this.orgRootRepo.save(orgRoot);
}
let orgChild1 = await this.orgChild1Repo.findOne({
where: { orgChild1Name: item.orgChild1 },
});
if (orgChild1 == null) {
orgChild1 = new OrgChild1();
orgChild1.orgRootId = orgRoot.id;
orgChild1.orgChild1Name = item.orgChild1;
orgChild1.orgChild1ShortName = item.orgShortname;
const rank: any = item.orgRank;
orgChild1.orgChild1Rank = rank;
orgChild1.orgChild1RankSub = item.orgSubRank;
orgChild1.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
orgChild1.DIVISION_CODE = item.DIVISION_CODE;
orgChild1.SECTION_CODE = item.SECTION_CODE;
orgChild1.JOB_CODE = item.JOB_CODE;
orgChild1.orgRevisionId = orgRevision.id;
orgChild1.createdUserId = request.user.sub;
orgChild1.createdFullName = request.user.name;
orgChild1.lastUpdateUserId = request.user.sub;
orgChild1.lastUpdateFullName = request.user.name;
orgChild1.createdAt = new Date();
orgChild1.lastUpdatedAt = new Date();
await this.orgChild1Repo.save(orgChild1);
}
orgChild2.orgRootId = orgRoot.id;
orgChild2.orgChild1Id = orgChild1.id;
orgChild2.orgChild2Name = item.orgChild2;
orgChild2.orgChild2ShortName = item.orgShortname;
const rank: any = item.orgRank;
orgChild2.orgChild2Rank = rank;
orgChild2.orgChild2RankSub = item.orgSubRank;
orgChild2.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
orgChild2.DIVISION_CODE = item.DIVISION_CODE;
orgChild2.SECTION_CODE = item.SECTION_CODE;
orgChild2.JOB_CODE = item.JOB_CODE;
orgChild2.orgRevisionId = orgRevision.id;
orgChild2.createdUserId = request.user.sub;
orgChild2.createdFullName = request.user.name;
orgChild2.lastUpdateUserId = request.user.sub;
orgChild2.lastUpdateFullName = request.user.name;
orgChild2.createdAt = new Date();
orgChild2.lastUpdatedAt = new Date();
await this.orgChild2Repo.save(orgChild2);
}),
);
//create child3
const IMPORT_CHILD3 = await this.IMPORT_ORGRepo.find({
where: {
orgRoot: Not(""),
orgChild1: Not(""),
orgChild2: Not(""),
orgChild3: Not(""),
},
});
await Promise.all(
IMPORT_CHILD3.map(async (item) => {
const orgChild3 = new OrgChild3();
let orgRoot = await this.orgRootRepo.findOne({
where: { orgRootName: item.orgRoot },
});
if (orgRoot == null) {
orgRoot = new OrgRoot();
orgRoot.orgRootName = item.orgRoot;
orgRoot.orgRootShortName = item.orgShortname;
const rank: any = item.orgRank;
orgRoot.orgRootRank = rank;
orgRoot.orgRootRankSub = item.orgSubRank;
orgRoot.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
orgRoot.DIVISION_CODE = item.DIVISION_CODE;
orgRoot.SECTION_CODE = item.SECTION_CODE;
orgRoot.JOB_CODE = item.JOB_CODE;
orgRoot.orgRevisionId = orgRevision.id;
orgRoot.createdUserId = request.user.sub;
orgRoot.createdFullName = request.user.name;
orgRoot.lastUpdateUserId = request.user.sub;
orgRoot.lastUpdateFullName = request.user.name;
orgRoot.createdAt = new Date();
orgRoot.lastUpdatedAt = new Date();
await this.orgRootRepo.save(orgRoot);
}
let orgChild1 = await this.orgChild1Repo.findOne({
where: { orgChild1Name: item.orgChild1 },
});
if (orgChild1 == null) {
orgChild1 = new OrgChild1();
orgChild1.orgRootId = orgRoot.id;
orgChild1.orgChild1Name = item.orgChild1;
orgChild1.orgChild1ShortName = item.orgShortname;
const rank: any = item.orgRank;
orgChild1.orgChild1Rank = rank;
orgChild1.orgChild1RankSub = item.orgSubRank;
orgChild1.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
orgChild1.DIVISION_CODE = item.DIVISION_CODE;
orgChild1.SECTION_CODE = item.SECTION_CODE;
orgChild1.JOB_CODE = item.JOB_CODE;
orgChild1.orgRevisionId = orgRevision.id;
orgChild1.createdUserId = request.user.sub;
orgChild1.createdFullName = request.user.name;
orgChild1.lastUpdateUserId = request.user.sub;
orgChild1.lastUpdateFullName = request.user.name;
orgChild1.createdAt = new Date();
orgChild1.lastUpdatedAt = new Date();
await this.orgChild1Repo.save(orgChild1);
}
let orgChild2 = await this.orgChild2Repo.findOne({
where: { orgChild2Name: item.orgChild2 },
});
if (orgChild2 == null) {
orgChild2 = new OrgChild2();
orgChild2.orgRootId = orgRoot.id;
orgChild2.orgChild1Id = orgChild1.id;
orgChild2.orgChild2Name = item.orgChild2;
orgChild2.orgChild2ShortName = item.orgShortname;
const rank: any = item.orgRank;
orgChild2.orgChild2Rank = rank;
orgChild2.orgChild2RankSub = item.orgSubRank;
orgChild2.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
orgChild2.DIVISION_CODE = item.DIVISION_CODE;
orgChild2.SECTION_CODE = item.SECTION_CODE;
orgChild2.JOB_CODE = item.JOB_CODE;
orgChild2.orgRevisionId = orgRevision.id;
orgChild2.createdUserId = request.user.sub;
orgChild2.createdFullName = request.user.name;
orgChild2.lastUpdateUserId = request.user.sub;
orgChild2.lastUpdateFullName = request.user.name;
orgChild2.createdAt = new Date();
orgChild2.lastUpdatedAt = new Date();
await this.orgChild2Repo.save(orgChild2);
}
orgChild3.orgRootId = orgRoot.id;
orgChild3.orgChild1Id = orgChild1.id;
orgChild3.orgChild2Id = orgChild2.id;
orgChild3.orgChild3Name = item.orgChild3;
orgChild3.orgChild3ShortName = item.orgShortname;
const rank: any = item.orgRank;
orgChild3.orgChild3Rank = rank;
orgChild3.orgChild3RankSub = item.orgSubRank;
orgChild3.DEPARTMENT_CODE = item.DEPARTMENT_CODE;
orgChild3.DIVISION_CODE = item.DIVISION_CODE;
orgChild3.SECTION_CODE = item.SECTION_CODE;
orgChild3.JOB_CODE = item.JOB_CODE;
orgChild3.orgRevisionId = orgRevision.id;
orgChild3.createdUserId = request.user.sub;
orgChild3.createdFullName = request.user.name;
orgChild3.lastUpdateUserId = request.user.sub;
orgChild3.lastUpdateFullName = request.user.name;
orgChild3.createdAt = new Date();
orgChild3.lastUpdatedAt = new Date();
await this.orgChild3Repo.save(orgChild3);
}), }),
); );
return new HttpSuccess(); return new HttpSuccess();

View file

@ -4383,7 +4383,9 @@ export class PositionController extends Controller {
posTypeId: position.posTypeId, posTypeId: position.posTypeId,
posTypeName: position.posType == null ? null : position.posType.posTypeName, posTypeName: position.posType == null ? null : position.posType.posTypeName,
posLevelId: position.posLevelId, posLevelId: position.posLevelId,
posLevelName: position.posLevel == null ? null : position.posLevel.posLevelName, posLevelName: position.posType == null && position.posLevel == null
? null
: `${position.posType.posTypeShortName} ${position.posLevel.posLevelName}`,
// posExecutiveId: position.posExecutiveId, // posExecutiveId: position.posExecutiveId,
// posExecutiveName: // posExecutiveName:
// position.posExecutive == null ? null : position.posExecutive.posExecutiveName, // position.posExecutive == null ? null : position.posExecutive.posExecutiveName,

View file

@ -6641,9 +6641,9 @@ export class ProfileController extends Controller {
position: profile.position, position: profile.position,
leaveDate: profile.dateLeave, leaveDate: profile.dateLeave,
posMasterNo: posMaster == null ? null : posMaster.posMasterNo, posMasterNo: posMaster == null ? null : posMaster.posMasterNo,
posLevelName: profile.posLevel == null posLevelName: profile.posType == null && profile.posLevel == null
? null ? null
: `${profile.posType.posTypeShortName ?? ""} ${profile.posLevel.posLevelName ?? ""}`, : `${profile.posType.posTypeShortName} ${profile.posLevel.posLevelName}`,
posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank, posLevelRank: profile.posLevel == null ? null : profile.posLevel.posLevelRank,
posLevelId: profile.posLevel == null ? null : profile.posLevel.id, posLevelId: profile.posLevel == null ? null : profile.posLevel.id,
posTypeName: profile.posType == null ? null : profile.posType.posTypeName, posTypeName: profile.posType == null ? null : profile.posType.posTypeName,

View file

@ -1,4 +1,14 @@
import { Controller, Get, Route, Security, Tags, SuccessResponse, Response, Path, Query } from "tsoa"; import {
Controller,
Get,
Route,
Security,
Tags,
SuccessResponse,
Response,
Path,
Query,
} from "tsoa";
import { AppDataSource } from "../database/data-source"; import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success"; import HttpSuccess from "../interfaces/http-success";
import HttpStatusCode from "../interfaces/http-status"; import HttpStatusCode from "../interfaces/http-status";
@ -37,7 +47,7 @@ export class ReportController extends Controller {
private posMasterRepository = AppDataSource.getRepository(PosMaster); private posMasterRepository = AppDataSource.getRepository(PosMaster);
private profileRepository = AppDataSource.getRepository(Profile); private profileRepository = AppDataSource.getRepository(Profile);
private empPosMasterRepository = AppDataSource.getRepository(EmployeePosMaster); private empPosMasterRepository = AppDataSource.getRepository(EmployeePosMaster);
/** /**
* API . * API .
* *
* @summary . * @summary .
@ -60,69 +70,79 @@ export class ReportController extends Controller {
const minAge = ageMin ?? 18; const minAge = ageMin ?? 18;
const maxAge = ageMax ?? 60; const maxAge = ageMax ?? 60;
if (minAge > maxAge) { if (minAge > maxAge) {
throw new HttpError(HttpStatus.NOT_FOUND, "ageMin cannot be greater than ageMax"); throw new HttpError(HttpStatus.NOT_FOUND, "ageMin cannot be greater than ageMax");
} }
const yearInAD = year?year:null; const yearInAD = year ? year : null;
const currentRevision = await this.orgRevisionRepository.findOne({ const currentRevision = await this.orgRevisionRepository.findOne({
where:{ where: {
orgRevisionIsCurrent: true orgRevisionIsCurrent: true,
} },
}); });
const rawdataProfile = await this.posMasterRepository const rawdataProfile = await this.posMasterRepository
.createQueryBuilder('posMaster') .createQueryBuilder("posMaster")
.leftJoinAndSelect('posMaster.current_holder', 'current_holder') .leftJoinAndSelect("posMaster.current_holder", "current_holder")
.leftJoinAndSelect('posMaster.positions', 'positions') .leftJoinAndSelect("posMaster.positions", "positions")
.leftJoinAndSelect('posMaster.orgRoot', 'orgRoot') .leftJoinAndSelect("posMaster.orgRoot", "orgRoot")
.leftJoinAndSelect('positions.posExecutive', 'posExecutive') .leftJoinAndSelect("positions.posExecutive", "posExecutive")
.leftJoinAndSelect('current_holder.posType', 'posType') .leftJoinAndSelect("current_holder.posType", "posType")
.leftJoinAndSelect('current_holder.posLevel', 'posLevel') .leftJoinAndSelect("current_holder.posLevel", "posLevel")
.leftJoinAndSelect('current_holder.profileEducations', 'profileEducations') .leftJoinAndSelect("current_holder.profileEducations", "profileEducations")
.where('posMaster.orgRevisionId = :currentRevisionId', { currentRevisionId: currentRevision?.id }) .where("posMaster.orgRevisionId = :currentRevisionId", {
.andWhere(rootId?'posMaster.orgRootId = :rootId': "1=1", { rootId: rootId }) currentRevisionId: currentRevision?.id,
.andWhere('posMaster.current_holderId Is Not Null') })
.andWhere('positions.positionIsSelected = :positionIsSelected', { positionIsSelected: true }) .andWhere(rootId ? "posMaster.orgRootId = :rootId" : "1=1", { rootId: rootId })
.andWhere( yearInAD && yearInAD != null? 'YEAR(current_holder.dateAppoint) = :year': "1=1", { year: yearInAD }) .andWhere("posMaster.current_holderId Is Not Null")
.andWhere(` .andWhere("positions.positionIsSelected = :positionIsSelected", { positionIsSelected: true })
.andWhere(yearInAD && yearInAD != null ? "YEAR(current_holder.dateAppoint) = :year" : "1=1", {
year: yearInAD,
})
.andWhere(
`
TIMESTAMPDIFF(YEAR, current_holder.birthDate, CURDATE()) >= :minAge TIMESTAMPDIFF(YEAR, current_holder.birthDate, CURDATE()) >= :minAge
AND TIMESTAMPDIFF(YEAR, current_holder.birthDate, CURDATE()) <= :maxAge AND TIMESTAMPDIFF(YEAR, current_holder.birthDate, CURDATE()) <= :maxAge
`, { minAge, maxAge }) `,
.orderBy("posType.posTypeName","ASC") { minAge, maxAge },
.getMany(); )
if(!rawdataProfile){ .orderBy("posType.posTypeName", "ASC")
.getMany();
if (!rawdataProfile) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ"); throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
} }
const mapData = rawdataProfile const mapData = rawdataProfile.map((x) => {
.map((x) => { const latestEducation = x.current_holder.profileEducations.sort(
const latestEducation = x.current_holder.profileEducations.sort((a:any, b:any) => b.endDate - a.startDate)[0]; (a: any, b: any) => b.endDate - a.startDate,
)[0];
return { return {
name: x.current_holder.firstName + " " + x.current_holder.lastName, name: x.current_holder.firstName + " " + x.current_holder.lastName,
affiliation: x.orgRoot.orgRootName??"-", affiliation: x.orgRoot.orgRootName ?? "-",
gender: x.current_holder.gender??"-", gender: x.current_holder.gender ?? "-",
positionName: x.positions[0]?x.positions[0].positionName:"-", positionName: x.positions[0] ? x.positions[0].positionName : "-",
status: x.current_holder.relationship??"-", status: x.current_holder.relationship ?? "-",
posType: x.current_holder.posType.posTypeName??"-", posType: x.current_holder.posType.posTypeName ?? "-",
posLevel: x.current_holder.posLevel.posLevelName??"-", posLevel: x.current_holder.posLevel.posLevelName ?? "-",
degree: latestEducation ? latestEducation.educationLevel : "-", degree: latestEducation ? latestEducation.educationLevel : "-",
posExecutive: x.positions[0].posExecutive?x.positions[0].posExecutive.posExecutiveName:"-", posExecutive: x.positions[0].posExecutive
? x.positions[0].posExecutive.posExecutiveName
: "-",
currentPreiodPos: "-", currentPreiodPos: "-",
levelPeriodPos: "-", levelPeriodPos: "-",
}; };
}); });
const groupedData = mapData.reduce((acc:any, item) => { const groupedData = mapData.reduce((acc: any, item) => {
const key = `${item.posType} - ${item.affiliation} - ${item.gender} - ${item.degree || 'ไม่พบข้อมูล'} - ${item.status || 'ไม่พบข้อมูล'} - ${item.positionName} - ${item.posLevel} - ${item.posExecutive || 'ไม่พบข้อมูล'} `; const key = `${item.posType} - ${item.affiliation} - ${item.gender} - ${item.degree || "ไม่พบข้อมูล"} - ${item.status || "ไม่พบข้อมูล"} - ${item.positionName} - ${item.posLevel} - ${item.posExecutive || "ไม่พบข้อมูล"} `;
if (!acc[key]) { if (!acc[key]) {
acc[key] = { acc[key] = {
posType: item.posType && item.posType != "" ? item.posType: "-", posType: item.posType && item.posType != "" ? item.posType : "-",
affiliation: item.affiliation && item.affiliation != "" ? item.affiliation: "-", affiliation: item.affiliation && item.affiliation != "" ? item.affiliation : "-",
gender: item.gender && item.gender != "" ? item.gender: "-", gender: item.gender && item.gender != "" ? item.gender : "-",
degree: item.degree && item.degree != "" ? item.degree: "-", degree: item.degree && item.degree != "" ? item.degree : "-",
status: item.status && item.status != "" ? item.status: "-", status: item.status && item.status != "" ? item.status : "-",
positionName: item.positionName && item.positionName != "" ? item.positionName: "-", positionName: item.positionName && item.positionName != "" ? item.positionName : "-",
posLevel: item.posLevel && item.posLevel != "" ? item.posLevel: "-", posLevel: item.posLevel && item.posLevel != "" ? item.posLevel : "-",
posExecutive: item.posExecutive && item.posExecutive != "" ? item.posExecutive: "-", posExecutive: item.posExecutive && item.posExecutive != "" ? item.posExecutive : "-",
currentPreiodPos: "-", currentPreiodPos: "-",
levelPeriodPos: "-", levelPeriodPos: "-",
count: 0, count: 0,
@ -132,23 +152,25 @@ export class ReportController extends Controller {
return acc; return acc;
}, {}); }, {});
const result = Object.values(groupedData).map((item: any) => ({ const result = Object.values(groupedData).map((item: any) => ({
...item , ...item,
count: Extension.ToThaiNumber(item.count.toString()), count: Extension.ToThaiNumber(item.count.toString()),
})); }));
return new HttpSuccess({ return new HttpSuccess({
template: "registry-officer", template: "registry-officer",
reportName: "xlsx-report", reportName: "xlsx-report",
data: { data: {
year: year?Extension.ToThaiNumber(year.toString()):Extension.ToThaiNumber(new Date().getFullYear().toString()), year: year
? Extension.ToThaiNumber((year + 543).toString())
: Extension.ToThaiNumber((new Date().getFullYear() + 543).toString()),
date: Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date())), date: Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date())),
list: result list: result,
}, },
}); });
} }
/** /**
* API . * API .
* *
* @summary . * @summary .
@ -171,64 +193,73 @@ export class ReportController extends Controller {
const minAge = ageMin ?? 18; const minAge = ageMin ?? 18;
const maxAge = ageMax ?? 60; const maxAge = ageMax ?? 60;
if (minAge > maxAge) { if (minAge > maxAge) {
throw new HttpError(HttpStatus.NOT_FOUND, "ageMin cannot be greater than ageMax"); throw new HttpError(HttpStatus.NOT_FOUND, "ageMin cannot be greater than ageMax");
} }
const yearInAD = year?year:null; const yearInAD = year ? year : null;
const currentRevision = await this.orgRevisionRepository.findOne({ const currentRevision = await this.orgRevisionRepository.findOne({
where:{ where: {
orgRevisionIsCurrent: true orgRevisionIsCurrent: true,
} },
}); });
const rawdataProfile = await this.empPosMasterRepository const rawdataProfile = await this.empPosMasterRepository
.createQueryBuilder('posMaster') .createQueryBuilder("posMaster")
.leftJoinAndSelect('posMaster.current_holder', 'current_holder') .leftJoinAndSelect("posMaster.current_holder", "current_holder")
.leftJoinAndSelect('posMaster.positions', 'positions') .leftJoinAndSelect("posMaster.positions", "positions")
.leftJoinAndSelect('posMaster.orgRoot', 'orgRoot') .leftJoinAndSelect("posMaster.orgRoot", "orgRoot")
.leftJoinAndSelect('current_holder.posType', 'posType') .leftJoinAndSelect("current_holder.posType", "posType")
.leftJoinAndSelect('current_holder.posLevel', 'posLevel') .leftJoinAndSelect("current_holder.posLevel", "posLevel")
.leftJoinAndSelect('current_holder.profileEducations', 'profileEducations') .leftJoinAndSelect("current_holder.profileEducations", "profileEducations")
.where('posMaster.orgRevisionId = :currentRevisionId', { currentRevisionId: currentRevision?.id }) .where("posMaster.orgRevisionId = :currentRevisionId", {
.andWhere(rootId?'posMaster.orgRootId = :rootId': "1=1", { rootId: rootId }) currentRevisionId: currentRevision?.id,
.andWhere('posMaster.current_holderId Is Not Null') })
.andWhere('positions.positionIsSelected = :positionIsSelected', { positionIsSelected: true }) .andWhere(rootId ? "posMaster.orgRootId = :rootId" : "1=1", { rootId: rootId })
.andWhere( yearInAD && yearInAD != null? 'YEAR(current_holder.dateAppoint) = :year': "1=1", { year: yearInAD }) .andWhere("posMaster.current_holderId Is Not Null")
.andWhere(` .andWhere("positions.positionIsSelected = :positionIsSelected", { positionIsSelected: true })
.andWhere(yearInAD && yearInAD != null ? "YEAR(current_holder.dateAppoint) = :year" : "1=1", {
year: yearInAD,
})
.andWhere(
`
TIMESTAMPDIFF(YEAR, current_holder.birthDate, CURDATE()) >= :minAge TIMESTAMPDIFF(YEAR, current_holder.birthDate, CURDATE()) >= :minAge
AND TIMESTAMPDIFF(YEAR, current_holder.birthDate, CURDATE()) <= :maxAge AND TIMESTAMPDIFF(YEAR, current_holder.birthDate, CURDATE()) <= :maxAge
`, { minAge, maxAge }) `,
.orderBy("posType.posTypeName","ASC") { minAge, maxAge },
.getMany(); )
if(!rawdataProfile){ .orderBy("posType.posTypeName", "ASC")
.getMany();
if (!rawdataProfile) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ"); throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
} }
const mapData = rawdataProfile.map((x) => { const mapData = rawdataProfile.map((x) => {
const latestEducation = x.current_holder.profileEducations.sort((a:any, b:any) => b.endDate - a.startDate)[0]; const latestEducation = x.current_holder.profileEducations.sort(
(a: any, b: any) => b.endDate - a.startDate,
)[0];
return { return {
name: x.current_holder.firstName + " " + x.current_holder.lastName, name: x.current_holder.firstName + " " + x.current_holder.lastName,
affiliation: x.orgRoot.orgRootName??"-", affiliation: x.orgRoot.orgRootName ?? "-",
gender: x.current_holder.gender??"-", gender: x.current_holder.gender ?? "-",
positionName: x.positions[0]?x.positions[0].positionName: "-", positionName: x.positions[0] ? x.positions[0].positionName : "-",
status: x.current_holder.relationship??"-", status: x.current_holder.relationship ?? "-",
posType: x.current_holder.posType.posTypeName??"-", posType: x.current_holder.posType.posTypeName ?? "-",
posLevel: x.current_holder.posLevel.posLevelName??"-", posLevel: x.current_holder.posLevel.posLevelName ?? "-",
degree: latestEducation ? latestEducation.educationLevel : "-", degree: latestEducation ? latestEducation.educationLevel : "-",
period: "-", period: "-",
}; };
}); });
const groupedData = mapData.reduce((acc:any, item) => { const groupedData = mapData.reduce((acc: any, item) => {
const key = `${item.affiliation} - ${item.gender} - ${item.degree || 'ไม่พบข้อมูล'} - ${item.status || 'ไม่พบข้อมูล'} - ${item.posType} - ${item.positionName} - ${item.posLevel} const key = `${item.affiliation} - ${item.gender} - ${item.degree || "ไม่พบข้อมูล"} - ${item.status || "ไม่พบข้อมูล"} - ${item.posType} - ${item.positionName} - ${item.posLevel}
`; `;
if (!acc[key]) { if (!acc[key]) {
acc[key] = { acc[key] = {
affiliation: item.affiliation && item.affiliation != ""?item.affiliation:"-", affiliation: item.affiliation && item.affiliation != "" ? item.affiliation : "-",
gender: item.gender && item.gender != ""?item.gender:"-", gender: item.gender && item.gender != "" ? item.gender : "-",
degree: item.degree && item.degree != ""?item.degree:"-", degree: item.degree && item.degree != "" ? item.degree : "-",
status: item.status && item.status != ""?item.status:"-", status: item.status && item.status != "" ? item.status : "-",
posType: item.posType && item.posType != ""?item.posType:"-", posType: item.posType && item.posType != "" ? item.posType : "-",
positionName: item.positionName && item.positionName != ""?item.positionName:"-", positionName: item.positionName && item.positionName != "" ? item.positionName : "-",
posLevel: Extension.ToThaiNumber(item.posLevel.toString()), posLevel: Extension.ToThaiNumber(item.posLevel.toString()),
period: "-", period: "-",
count: 0, count: 0,
@ -240,20 +271,21 @@ export class ReportController extends Controller {
}, {}); }, {});
const result = Object.values(groupedData).map((item: any) => ({ const result = Object.values(groupedData).map((item: any) => ({
...item , ...item,
count: Extension.ToThaiNumber(item.count.toString()) count: Extension.ToThaiNumber(item.count.toString()),
})); }));
return new HttpSuccess({ return new HttpSuccess({
template: "registry-emp", template: "registry-emp",
reportName: "xlsx-report", reportName: "xlsx-report",
data: { data: {
year: year?Extension.ToThaiNumber(year.toString()):Extension.ToThaiNumber(new Date().getFullYear().toString()), year: year
? Extension.ToThaiNumber((year + 543).toString())
: Extension.ToThaiNumber((new Date().getFullYear() + 543).toString()),
date: Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date())), date: Extension.ToThaiNumber(Extension.ToThaiShortDate(new Date())),
list: result list: result,
}, },
}); });
} }
/** /**
@ -6468,11 +6500,11 @@ export class ReportController extends Controller {
@Get("report4/{rootId}") @Get("report4/{rootId}")
async findReport4(@Path() rootId: string) { async findReport4(@Path() rootId: string) {
const orgRootData = await this.orgRootRepository.findOne({ const orgRootData = await this.orgRootRepository.findOne({
where: { id: rootId } where: { id: rootId },
}); });
if (!orgRootData) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); if (!orgRootData) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
const posMaster = await this.posMasterRepository const posMaster = await this.posMasterRepository
.createQueryBuilder("posMaster") .createQueryBuilder("posMaster")
.leftJoinAndSelect("posMaster.positions", "position") .leftJoinAndSelect("posMaster.positions", "position")
@ -6482,17 +6514,20 @@ export class ReportController extends Controller {
.orderBy("posType.posTypeRank", "ASC") .orderBy("posType.posTypeRank", "ASC")
.addOrderBy("posLevel.posLevelRank", "ASC") .addOrderBy("posLevel.posLevelRank", "ASC")
.getMany(); .getMany();
const _posMaster = posMaster
.map((x) => ({
type: [...new Set(x.positions.flatMap((y) => y.posType.posTypeName))].join(","),
typeRank: [...new Set(x.positions.flatMap((y) => y.posType.posTypeRank))].join(""),
level: [...new Set(x.positions.flatMap((y) => y.posLevel.posLevelName))].join(","),
levelRank: [...new Set(x.positions.flatMap((y) => `${y.posType.posTypeRank}${y.posLevel.posLevelRank}`))].join(""),
positions: [...new Set(x.positions.flatMap((y) => y.positionName))].join(""),
}))
const groupedData = _posMaster.reduce((acc:any, curr:any) => { const _posMaster = posMaster.map((x) => ({
type: [...new Set(x.positions.flatMap((y) => y.posType.posTypeName))].join(","),
typeRank: [...new Set(x.positions.flatMap((y) => y.posType.posTypeRank))].join(""),
level: [...new Set(x.positions.flatMap((y) => y.posLevel.posLevelName))].join(","),
levelRank: [
...new Set(
x.positions.flatMap((y) => `${y.posType.posTypeRank}${y.posLevel.posLevelRank}`),
),
].join(""),
positions: [...new Set(x.positions.flatMap((y) => y.positionName))].join(""),
}));
const groupedData = _posMaster.reduce((acc: any, curr: any) => {
const key = `${curr.type}|${curr.typeRank}|${curr.level}|${curr.levelRank}`; const key = `${curr.type}|${curr.typeRank}|${curr.level}|${curr.levelRank}`;
if (!acc[key]) { if (!acc[key]) {
acc[key] = { ...curr, total: 1 }; acc[key] = { ...curr, total: 1 };
@ -6501,7 +6536,7 @@ export class ReportController extends Controller {
} }
return acc; return acc;
}, {}); }, {});
let result = Object.values(groupedData) let result = Object.values(groupedData)
.map((x: any) => ({ .map((x: any) => ({
type: x.type, type: x.type,
@ -6523,16 +6558,16 @@ export class ReportController extends Controller {
let _total: number = 0; let _total: number = 0;
let _reslut = new Array(); let _reslut = new Array();
result.forEach((x:any, idx:number) => { result.forEach((x: any, idx: number) => {
allTotal += x.total; allTotal += x.total;
total += x.total; total += x.total;
if(x.type === tmpType) { if (x.type === tmpType) {
_reslut.push({ _reslut.push({
...x, ...x,
type: "" type: "",
}) });
}else { } else {
if(x.type !== tmpType && tmpType != "") { if (x.type !== tmpType && tmpType != "") {
_total = total - x.total; _total = total - x.total;
_reslut.push({ _reslut.push({
type: "", type: "",
@ -6541,13 +6576,13 @@ export class ReportController extends Controller {
levelRank: "", levelRank: "",
total: _total, total: _total,
remark: "", remark: "",
}) });
total = x.total; total = x.total;
_total = 0; _total = 0;
} }
_reslut.push({ _reslut.push({
...x ...x,
}) });
} }
tmpType = x.type; tmpType = x.type;
}); });
@ -6559,7 +6594,7 @@ export class ReportController extends Controller {
levelRank: "", levelRank: "",
total: total, total: total,
remark: "", remark: "",
}) });
_reslut.push({ _reslut.push({
type: "", type: "",
typeRank: "", typeRank: "",
@ -6569,24 +6604,24 @@ export class ReportController extends Controller {
remark: "", remark: "",
}); });
return new HttpSuccess({ return new HttpSuccess({
template: "report4", template: "report4",
reportName: "report4", reportName: "report4",
data: { data: {
dateCurrent: Extension.ToThaiShortDate(new Date()), dateCurrent: Extension.ToThaiShortDate(new Date()),
rootName: orgRootData ? orgRootData.orgRootName : "-", rootName: orgRootData ? orgRootData.orgRootName : "-",
data: _reslut data: _reslut,
} },
}); });
} }
@Get("report4-employee/{rootId}") @Get("report4-employee/{rootId}")
async findReportEmp4(@Path() rootId: string) { async findReportEmp4(@Path() rootId: string) {
const orgRootData = await this.orgRootRepository.findOne({ const orgRootData = await this.orgRootRepository.findOne({
where: { id: rootId } where: { id: rootId },
}); });
if (!orgRootData) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); if (!orgRootData) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
const posMaster = await this.empPosMasterRepository const posMaster = await this.empPosMasterRepository
.createQueryBuilder("posMaster") .createQueryBuilder("posMaster")
.leftJoinAndSelect("posMaster.positions", "position") .leftJoinAndSelect("posMaster.positions", "position")
@ -6596,17 +6631,20 @@ export class ReportController extends Controller {
.orderBy("posType.posTypeRank", "ASC") .orderBy("posType.posTypeRank", "ASC")
.addOrderBy("posLevel.posLevelRank", "ASC") .addOrderBy("posLevel.posLevelRank", "ASC")
.getMany(); .getMany();
const _posMaster = posMaster
.map((x) => ({
type: [...new Set(x.positions.flatMap((y) => y.posType.posTypeName))].join(","),
typeRank: [...new Set(x.positions.flatMap((y) => y.posType.posTypeRank))].join(""),
level: [...new Set(x.positions.flatMap((y) => y.posLevel.posLevelName))].join(","),
levelRank: [...new Set(x.positions.flatMap((y) => `${y.posType.posTypeRank}${y.posLevel.posLevelRank}`))].join(""),
positions: [...new Set(x.positions.flatMap((y) => y.positionName))].join(""),
}))
const groupedData = _posMaster.reduce((acc:any, curr:any) => { const _posMaster = posMaster.map((x) => ({
type: [...new Set(x.positions.flatMap((y) => y.posType.posTypeName))].join(","),
typeRank: [...new Set(x.positions.flatMap((y) => y.posType.posTypeRank))].join(""),
level: [...new Set(x.positions.flatMap((y) => y.posLevel.posLevelName))].join(","),
levelRank: [
...new Set(
x.positions.flatMap((y) => `${y.posType.posTypeRank}${y.posLevel.posLevelRank}`),
),
].join(""),
positions: [...new Set(x.positions.flatMap((y) => y.positionName))].join(""),
}));
const groupedData = _posMaster.reduce((acc: any, curr: any) => {
const key = `${curr.type}|${curr.typeRank}|${curr.level}|${curr.levelRank}`; const key = `${curr.type}|${curr.typeRank}|${curr.level}|${curr.levelRank}`;
if (!acc[key]) { if (!acc[key]) {
acc[key] = { ...curr, total: 1 }; acc[key] = { ...curr, total: 1 };
@ -6615,14 +6653,14 @@ export class ReportController extends Controller {
} }
return acc; return acc;
}, {}); }, {});
let result = Object.values(groupedData) let result = Object.values(groupedData)
.map((x: any) => ({ .map((x: any) => ({
type: x.type, type: x.type,
typeRank: parseInt(x.typeRank), typeRank: parseInt(x.typeRank),
level: x.level, level: x.level,
levelRank: parseInt(x.levelRank), levelRank: parseInt(x.levelRank),
total: x.total, total: x.total,
remark: x.positions, remark: x.positions,
})) }))
@ -6638,16 +6676,16 @@ export class ReportController extends Controller {
let _total: number = 0; let _total: number = 0;
let _reslut = new Array(); let _reslut = new Array();
result.forEach((x:any, idx:number) => { result.forEach((x: any, idx: number) => {
allTotal += x.total; allTotal += x.total;
total += x.total; total += x.total;
if(x.type === tmpType) { if (x.type === tmpType) {
_reslut.push({ _reslut.push({
...x, ...x,
type: "" type: "",
}) });
}else { } else {
if(x.type !== tmpType && tmpType != "") { if (x.type !== tmpType && tmpType != "") {
_total = total - x.total; _total = total - x.total;
_reslut.push({ _reslut.push({
type: "", type: "",
@ -6656,13 +6694,13 @@ export class ReportController extends Controller {
levelRank: "", levelRank: "",
total: _total, total: _total,
remark: "", remark: "",
}) });
total = x.total; total = x.total;
_total = 0; _total = 0;
} }
_reslut.push({ _reslut.push({
...x ...x,
}) });
} }
tmpType = x.type; tmpType = x.type;
}); });
@ -6674,7 +6712,7 @@ export class ReportController extends Controller {
levelRank: "", levelRank: "",
total: total, total: total,
remark: "", remark: "",
}) });
_reslut.push({ _reslut.push({
type: "", type: "",
typeRank: "", typeRank: "",
@ -6684,15 +6722,14 @@ export class ReportController extends Controller {
remark: "", remark: "",
}); });
return new HttpSuccess({ return new HttpSuccess({
template: "report4", template: "report4",
reportName: "report4", reportName: "report4",
data: { data: {
dateCurrent: Extension.ToThaiShortDate(new Date()), dateCurrent: Extension.ToThaiShortDate(new Date()),
rootName: orgRootData ? orgRootData.orgRootName : "-", rootName: orgRootData ? orgRootData.orgRootName : "-",
data: _reslut data: _reslut,
} },
}); });
} }
} }

View file

@ -45,4 +45,11 @@ export class HR_EDUCATION {
default: null, default: null,
}) })
INSTITUE: string; INSTITUE: string;
@Column({
nullable: true,
length: 255,
default: null,
})
EDUCATION_SEQ: string;
} }

91
src/entities/OFFICER.ts Normal file
View file

@ -0,0 +1,91 @@
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";
@Entity("OFFICER")
export class OFFICER {
@PrimaryGeneratedColumn()
id!: number;
// @Column({
// nullable: true,
// type: "text",
// default: null,
// })
// RET_YEAR: string;
@Column({
nullable: true,
type: "text",
default: null,
})
ID: string;
@Column({
nullable: true,
type: "text",
default: null,
})
MP_CATEGORY: string;
@Column({
nullable: true,
type: "text",
default: null,
})
MP_LEVEL: string;
@Column({
nullable: true,
type: "text",
default: null,
})
BORN: string;
@Column({
nullable: true,
type: "text",
default: null,
})
RANK_NAME: string;
@Column({
nullable: true,
type: "text",
default: null,
})
FNAME: string;
@Column({
nullable: true,
type: "text",
default: null,
})
LNAME: string;
@Column({
nullable: true,
type: "text",
default: null,
})
BEGIN_ENTRY_DATE: string;
@Column({
nullable: true,
type: "text",
default: null,
})
SEX: string;
@Column({
nullable: true,
type: "text",
default: null,
})
WORK_LINE_NAME: string;
@Column({
nullable: true,
type: "text",
default: null,
})
SALARY: string;
}