Merge branch 'task/173' into develop

This commit is contained in:
mamoss 2025-10-09 23:24:59 +07:00
commit a4f7b021a0
7 changed files with 403 additions and 629 deletions

View file

@ -1152,26 +1152,6 @@ export class OrganizationController extends Controller {
*/ */
@Get("super-admin/{id}") @Get("super-admin/{id}")
async detailSuperAdmin(@Path() id: string, @Request() request: RequestWithUser) { async detailSuperAdmin(@Path() id: string, @Request() request: RequestWithUser) {
// let _data: any = {
// root: null,
// child1: null,
// child2: null,
// child3: null,
// child4: null,
// };
// const orgRevision = await this.orgRevisionRepository.findOne({ where: { id } });
// if (!orgRevision) {
// throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล");
// }
// if (!request.user.role.includes("SUPER_ADMIN")) {
// if (orgRevision.orgRevisionIsDraft == true && orgRevision.orgRevisionIsCurrent == false) {
// _data = await this.listAuthSysOrgFuncByRevisionIdN(request, "SYS_ORG", orgRevision.id);
// } else {
// _data = await this.listAuthSysOrgFuncByRevisionIdC(request, "SYS_ORG", orgRevision.id);
// }
// }
const orgRevision = await this.orgRevisionRepository.findOne({ const orgRevision = await this.orgRevisionRepository.findOne({
where: { id: id }, where: { id: id },
relations: ["posMasters"], relations: ["posMasters"],
@ -7527,208 +7507,7 @@ export class OrganizationController extends Controller {
const check = orgRevision.orgRoots.find((x) => x.isDeputy == true); const check = orgRevision.orgRoots.find((x) => x.isDeputy == true);
return new HttpSuccess(check != null); return new HttpSuccess(check != null);
} }
public async listAuthSysOrgFuncByRevisionIdN(
request: RequestWithUser,
system: string,
revisionId: string,
) {
let profile = await this.profileRepo.findOne({
where: {
keycloak: request.user.sub,
},
relations: ["next_holders", "next_holders.authRole", "next_holders.authRole.authRoles"],
});
let data: any = {
root: [null],
child1: [null],
child2: [null],
child3: [null],
child4: [null],
};
if (!profile) {
return {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
}
let attrOwnership =
profile?.next_holders
.filter((x) => x.orgRevisionId == revisionId)[0]
?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrOwnership || null;
let attrPrivilege =
profile?.next_holders
.filter((x) => x.orgRevisionId == revisionId)[0]
?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrPrivilege || null;
const posMaster = await this.posMasterRepository.findOne({
where: {
next_holderId: profile.id,
orgRevisionId: revisionId,
},
});
if (!posMaster) {
data = {
root: [null],
child1: [null],
child2: [null],
child3: [null],
child4: [null],
};
} else if (attrOwnership == "OWNER") {
data = {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
} else if (attrPrivilege == "ROOT") {
data = {
root: [posMaster.orgRootId],
child1: null,
child2: null,
child3: null,
child4: null,
privilege: "ROOT",
};
} else if (attrPrivilege == "CHILD") {
let node = 4;
if (posMaster.orgChild1Id == null) {
node = 0;
} else if (posMaster.orgChild2Id == null) {
node = 1;
} else if (posMaster.orgChild3Id == null) {
node = 2;
} else if (posMaster.orgChild4Id == null) {
node = 3;
}
data = {
root: node >= 0 ? [posMaster.orgRootId] : null,
child1: node >= 1 ? [posMaster.orgChild1Id] : null,
child2: node >= 2 ? [posMaster.orgChild2Id] : null,
child3: node >= 3 ? [posMaster.orgChild3Id] : null,
child4: node >= 4 ? [posMaster.orgChild4Id] : null,
};
} else if (attrPrivilege == "NORMAL") {
data = {
root: [posMaster.orgRootId],
child1: [posMaster.orgChild1Id],
child2: [posMaster.orgChild2Id],
child3: [posMaster.orgChild3Id],
child4: [posMaster.orgChild4Id],
};
} else if (attrPrivilege == "SPECIFIC") {
}
return data;
}
public async listAuthSysOrgFuncByRevisionIdC(
request: RequestWithUser,
system: string,
revisionId: string,
) {
let profile = await this.profileRepo.findOne({
where: {
keycloak: request.user.sub,
},
relations: [
"current_holders",
"current_holders.authRole",
"current_holders.authRole.authRoles",
],
});
let data: any = {
root: [null],
child1: [null],
child2: [null],
child3: [null],
child4: [null],
};
if (!profile) {
return {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
}
let attrOwnership =
profile?.current_holders
.filter((x) => x.orgRevisionId == revisionId)[0]
?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrOwnership || null;
let attrPrivilege =
profile?.current_holders
.filter((x) => x.orgRevisionId == revisionId)[0]
?.authRole?.authRoles?.filter((x) => x.authSysId == system)[0]?.attrPrivilege || null;
const posMaster = await this.posMasterRepository.findOne({
where: {
next_holderId: profile.id,
orgRevisionId: revisionId,
},
});
if (!posMaster) {
data = {
root: [null],
child1: [null],
child2: [null],
child3: [null],
child4: [null],
};
} else if (attrOwnership == "OWNER") {
data = {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
} else if (attrPrivilege == "ROOT") {
data = {
root: [posMaster.orgRootId],
child1: null,
child2: null,
child3: null,
child4: null,
privilege: "ROOT",
};
} else if (attrPrivilege == "CHILD") {
let node = 4;
if (posMaster.orgChild1Id == null) {
node = 0;
} else if (posMaster.orgChild2Id == null) {
node = 1;
} else if (posMaster.orgChild3Id == null) {
node = 2;
} else if (posMaster.orgChild4Id == null) {
node = 3;
}
data = {
root: node >= 0 ? [posMaster.orgRootId] : null,
child1: node >= 1 ? [posMaster.orgChild1Id] : null,
child2: node >= 2 ? [posMaster.orgChild2Id] : null,
child3: node >= 3 ? [posMaster.orgChild3Id] : null,
child4: node >= 4 ? [posMaster.orgChild4Id] : null,
};
} else if (attrPrivilege == "NORMAL") {
data = {
root: [posMaster.orgRootId],
child1: [posMaster.orgChild1Id],
child2: [posMaster.orgChild2Id],
child3: [posMaster.orgChild3Id],
child4: [posMaster.orgChild4Id],
};
} else if (attrPrivilege == "SPECIFIC") {
}
return data;
}
/** /**
* API 1 * API 1
* *

View file

@ -73,29 +73,10 @@ export class OrganizationDotnetController extends Controller {
role?: string | null; role?: string | null;
nodeId?: string | null; nodeId?: string | null;
node?: number | null; node?: number | null;
page: number;
pageSize: number;
}, },
) { ) {
// const profileRepository = AppDataSource.getRepository(Profile);
// const queryBuilder = profileRepository
// .createQueryBuilder("profile")
// .leftJoinAndSelect("profile.posLevel", "posLevel")
// .leftJoinAndSelect("profile.posType", "posType")
// if (body.citizenId || body.firstName || body.lastName) {
// queryBuilder.where(
// new Brackets((qb) => {
// if (body.citizenId) {
// qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
// }
// if (body.firstName) {
// qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
// }
// if (body.lastName) {
// qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
// }
// }),
// );
// }
// const profiles = await queryBuilder.getMany();
let condition = "1=1"; let condition = "1=1";
let conditionParams = {}; let conditionParams = {};
if (body.role === "CHILD") { if (body.role === "CHILD") {
@ -120,12 +101,13 @@ export class OrganizationDotnetController extends Controller {
break; break;
} }
conditionParams = { nodeId: body.nodeId }; conditionParams = { nodeId: body.nodeId };
} } else if (body.role === "ROOT") {
else if (body.role === "ROOT") {
condition = "orgRoot.ancestorDNA = :nodeId"; condition = "orgRoot.ancestorDNA = :nodeId";
conditionParams = { nodeId: body.nodeId }; conditionParams = { nodeId: body.nodeId };
} } else if (body.role === "PARENT") {
else if (body.role === "NORMAL") { condition = "orgChild1.ancestorDNA = :nodeId";
conditionParams = { nodeId: body.nodeId };
} else if (body.role === "NORMAL") {
switch (body.node) { switch (body.node) {
case 0: case 0:
condition = "orgRoot.ancestorDNA = :nodeId AND current_holders.orgChild1 IS NULL"; condition = "orgRoot.ancestorDNA = :nodeId AND current_holders.orgChild1 IS NULL";
@ -150,12 +132,12 @@ export class OrganizationDotnetController extends Controller {
} }
const findRevision = await this.orgRevisionRepo.findOne({ const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false } where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
}); });
if (!findRevision) { if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
} }
const profiles = await this.profileRepo const [profiles, total] = await this.profileRepo
.createQueryBuilder("profile") .createQueryBuilder("profile")
.leftJoinAndSelect("profile.posLevel", "posLevel") .leftJoinAndSelect("profile.posLevel", "posLevel")
.leftJoinAndSelect("profile.posType", "posType") .leftJoinAndSelect("profile.posType", "posType")
@ -169,20 +151,22 @@ export class OrganizationDotnetController extends Controller {
.andWhere( .andWhere(
new Brackets((qb) => { new Brackets((qb) => {
if (body.citizenId) { if (body.citizenId) {
qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` }); qb.andWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
} }
if (body.firstName) { if (body.firstName) {
qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` }); qb.andWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
} }
if (body.lastName) { if (body.lastName) {
qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` }); qb.andWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
} }
}), }),
) )
.andWhere(condition, conditionParams) .andWhere(condition, conditionParams)
.getMany() .skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
return new HttpSuccess(profiles); return new HttpSuccess({ data: profiles, total: total });
} }
/** /**
@ -201,40 +185,10 @@ export class OrganizationDotnetController extends Controller {
role?: string | null; role?: string | null;
nodeId?: string | null; nodeId?: string | null;
node?: number | null; node?: number | null;
page: number;
pageSize: number;
}, },
) { ) {
// const profileRepository = AppDataSource.getRepository(ProfileEmployee);
// const queryBuilder = profileRepository
// .createQueryBuilder("profile")
// .leftJoinAndSelect("profile.posLevel", "posLevel")
// .leftJoinAndSelect("profile.posType", "posType")
// .leftJoinAndSelect("profile.profileSalary", "profileSalary")
// .leftJoinAndSelect("profile.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")
// .orderBy("profileSalary.order", "DESC");
// if (body.citizenId || body.firstName || body.lastName) {
// queryBuilder.where(
// new Brackets((qb) => {
// if (body.citizenId) {
// qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
// }
// if (body.firstName) {
// qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
// }
// if (body.lastName) {
// qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
// }
// }),
// );
// }
// const profileEmp = await queryBuilder.getMany();
let condition = "1=1"; let condition = "1=1";
let conditionParams = {}; let conditionParams = {};
if (body.role === "CHILD") { if (body.role === "CHILD") {
@ -259,12 +213,13 @@ export class OrganizationDotnetController extends Controller {
break; break;
} }
conditionParams = { nodeId: body.nodeId }; conditionParams = { nodeId: body.nodeId };
} } else if (body.role === "ROOT") {
else if (body.role === "ROOT") {
condition = "orgRoot.ancestorDNA = :nodeId"; condition = "orgRoot.ancestorDNA = :nodeId";
conditionParams = { nodeId: body.nodeId }; conditionParams = { nodeId: body.nodeId };
} } else if (body.role === "PARENT") {
else if (body.role === "NORMAL") { condition = "orgChild1.ancestorDNA = :nodeId";
conditionParams = { nodeId: body.nodeId };
} else if (body.role === "NORMAL") {
switch (body.node) { switch (body.node) {
case 0: case 0:
condition = "orgRoot.ancestorDNA = :nodeId AND current_holders.orgChild1 IS NULL"; condition = "orgRoot.ancestorDNA = :nodeId AND current_holders.orgChild1 IS NULL";
@ -294,7 +249,7 @@ export class OrganizationDotnetController extends Controller {
if (!findRevision) { if (!findRevision) {
throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision"); throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
} }
const profileEmp = await this.profileEmpRepo const [profileEmp, total] = await this.profileEmpRepo
.createQueryBuilder("profile") .createQueryBuilder("profile")
.leftJoinAndSelect("profile.posLevel", "posLevel") .leftJoinAndSelect("profile.posLevel", "posLevel")
.leftJoinAndSelect("profile.posType", "posType") .leftJoinAndSelect("profile.posType", "posType")
@ -309,110 +264,112 @@ export class OrganizationDotnetController extends Controller {
.andWhere( .andWhere(
new Brackets((qb) => { new Brackets((qb) => {
if (body.citizenId) { if (body.citizenId) {
qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` }); qb.andWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
} }
if (body.firstName) { if (body.firstName) {
qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` }); qb.andWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
} }
if (body.lastName) { if (body.lastName) {
qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` }); qb.andWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
} }
}), }),
) )
.andWhere(condition, conditionParams) .andWhere(condition, conditionParams)
.orderBy("profileSalary.order", "DESC") .orderBy("profileSalary.order", "DESC")
.getMany() .skip((body.page - 1) * body.pageSize)
.take(body.pageSize)
.getManyAndCount();
const profileEmp_ = await Promise.all( // const profileEmp_ = await Promise.all(
profileEmp.map((item: ProfileEmployee) => { // profileEmp.map((item: ProfileEmployee) => {
const rootName = // const rootName =
item.current_holders.length == 0 // item.current_holders.length == 0
? null // ? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgRoot // : item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgRoot
?.orgRootName; // ?.orgRootName;
const shortName = // const shortName =
item.current_holders.length == 0 // item.current_holders.length == 0
? null // ? null
: item.current_holders.find((x) => x.orgRevisionId == findRevision?.id) != null && // : item.current_holders.find((x) => x.orgRevisionId == findRevision?.id) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgChild4 != // item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgChild4 !=
null // 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)?.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) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision?.id) // item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)
?.orgChild3 != null // ?.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)?.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) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision?.id) // item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)
?.orgChild2 != null // ?.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)?.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) != null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision?.id) // item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)
?.orgChild1 != null // ?.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)?.orgChild1.orgChild1ShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}`
: item.current_holders.find((x) => x.orgRevisionId == findRevision?.id) != // : item.current_holders.find((x) => x.orgRevisionId == findRevision?.id) !=
null && // null &&
item.current_holders.find((x) => x.orgRevisionId == findRevision?.id) // item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)
?.orgRoot != null // ?.orgRoot != null
? `${item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}` // ? `${item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.orgRoot.orgRootShortName} ${item.current_holders.find((x) => x.orgRevisionId == findRevision?.id)?.posMasterNo}`
: null; // : null;
return { // return {
oc: rootName, // oc: rootName,
id: item.id, // id: item.id,
createdAt: item.createdAt, // createdAt: item.createdAt,
createdUserId: item.createdUserId, // createdUserId: item.createdUserId,
lastUpdatedAt: item.lastUpdatedAt, // lastUpdatedAt: item.lastUpdatedAt,
lastUpdateUserId: item.lastUpdateUserId, // lastUpdateUserId: item.lastUpdateUserId,
createdFullName: item.createdFullName, // createdFullName: item.createdFullName,
lastUpdateFullName: item.lastUpdateFullName, // lastUpdateFullName: item.lastUpdateFullName,
avatar: item.avatar, // avatar: item.avatar,
avatarName: item.avatarName, // avatarName: item.avatarName,
rank: item.rank, // rank: item.rank,
prefix: item.prefix, // prefix: item.prefix,
firstName: item.firstName, // firstName: item.firstName,
lastName: item.lastName, // lastName: item.lastName,
citizenId: item.citizenId, // citizenId: item.citizenId,
position: item.position, // position: item.position,
posLevelId: item.posLevelId, // posLevelId: item.posLevelId,
posTypeId: item.posTypeId, // posTypeId: item.posTypeId,
email: item.email, // email: item.email,
phone: item.phone, // phone: item.phone,
keycloak: item.keycloak, // keycloak: item.keycloak,
isProbation: item.isProbation, // isProbation: item.isProbation,
isLeave: item.isLeave, // isLeave: item.isLeave,
leaveReason: item.leaveReason, // leaveReason: item.leaveReason,
dateLeave: item.dateLeave, // dateLeave: item.dateLeave,
dateRetire: item.dateRetire, // dateRetire: item.dateRetire,
dateAppoint: item.dateAppoint, // dateAppoint: item.dateAppoint,
dateRetireLaw: item.dateRetireLaw, // dateRetireLaw: item.dateRetireLaw,
dateStart: item.dateStart, // dateStart: item.dateStart,
govAgeAbsent: item.govAgeAbsent, // govAgeAbsent: item.govAgeAbsent,
govAgePlus: item.govAgePlus, // govAgePlus: item.govAgePlus,
birthDate: item.birthDate ?? new Date(), // birthDate: item.birthDate ?? new Date(),
reasonSameDate: item.reasonSameDate, // reasonSameDate: item.reasonSameDate,
ethnicity: item.ethnicity, // ethnicity: item.ethnicity,
telephoneNumber: item.phone, // telephoneNumber: item.phone,
nationality: item.nationality, // nationality: item.nationality,
gender: item.gender, // gender: item.gender,
relationship: item.relationship, // relationship: item.relationship,
religion: item.religion, // religion: item.religion,
bloodGroup: item.bloodGroup, // bloodGroup: item.bloodGroup,
registrationAddress: item.registrationAddress, // registrationAddress: item.registrationAddress,
registrationProvinceId: item.registrationProvinceId, // registrationProvinceId: item.registrationProvinceId,
registrationDistrictId: item.registrationDistrictId, // registrationDistrictId: item.registrationDistrictId,
registrationSubDistrictId: item.registrationSubDistrictId, // registrationSubDistrictId: item.registrationSubDistrictId,
registrationZipCode: item.registrationZipCode, // registrationZipCode: item.registrationZipCode,
currentAddress: item.currentAddress, // currentAddress: item.currentAddress,
currentProvinceId: item.currentProvinceId, // currentProvinceId: item.currentProvinceId,
currentDistrictId: item.currentDistrictId, // currentDistrictId: item.currentDistrictId,
currentSubDistrictId: item.currentSubDistrictId, // currentSubDistrictId: item.currentSubDistrictId,
currentZipCode: item.currentZipCode, // currentZipCode: item.currentZipCode,
posLevel: item.posLevel, // posLevel: item.posLevel,
posType: item.posType, // posType: item.posType,
posNo: shortName, // posNo: shortName,
}; // };
}), // }),
); // );
return new HttpSuccess(profileEmp_); return new HttpSuccess({ data: profileEmp, total: total });
} }
/** /**
@ -695,8 +652,8 @@ export class OrganizationDotnetController extends Controller {
} }
let positionLeaveName = let positionLeaveName =
profile.posType == null && profile.posLevel == null profile.posType == null && profile.posLevel == null
? "" ? ""
: `${profile.posType?.posTypeShortName ?? ""} ${profile.posLevel?.posLevelName ?? ""}` : `${profile.posType?.posTypeShortName ?? ""} ${profile.posLevel?.posLevelName ?? ""}`;
const _profileCurrent = profile?.current_holders?.find( const _profileCurrent = profile?.current_holders?.find(
(x) => (x) =>
@ -4077,27 +4034,27 @@ export class OrganizationDotnetController extends Controller {
// }; // };
// } // }
// } else { // } else {
if (body.node === 0) { if (body.node === 0) {
typeCondition = { typeCondition = {
orgRootId: body.nodeId, orgRootId: body.nodeId,
}; };
} else if (body.node === 1) { } else if (body.node === 1) {
typeCondition = { typeCondition = {
orgChild1Id: body.nodeId, orgChild1Id: body.nodeId,
}; };
} else if (body.node === 2) { } else if (body.node === 2) {
typeCondition = { typeCondition = {
orgChild2Id: body.nodeId, orgChild2Id: body.nodeId,
}; };
} else if (body.node === 3) { } else if (body.node === 3) {
typeCondition = { typeCondition = {
orgChild3Id: body.nodeId, orgChild3Id: body.nodeId,
}; };
} else if (body.node === 4) { } else if (body.node === 4) {
typeCondition = { typeCondition = {
orgChild4Id: body.nodeId, orgChild4Id: body.nodeId,
}; };
} }
// } // }
let profile = await this.profileRepo.find({ let profile = await this.profileRepo.find({
where: { keycloak: Not(IsNull()) || Not(""), isLeave: false, current_holders: typeCondition }, where: { keycloak: Not(IsNull()) || Not(""), isLeave: false, current_holders: typeCondition },
@ -4123,10 +4080,7 @@ export class OrganizationDotnetController extends Controller {
// isLeave: false, // isLeave: false,
current_holders: typeCondition, current_holders: typeCondition,
// isRetirement: true, // isRetirement: true,
dateRetire: And( dateRetire: And(Not(IsNull()), Between(startOfYear, endOfYear)),
Not(IsNull()),
Between(startOfYear, endOfYear)
)
}, },
relations: [ relations: [
"posType", "posType",
@ -4397,15 +4351,15 @@ export class OrganizationDotnetController extends Controller {
}, },
) { ) {
let findRevision = await this.orgRevisionRepo.findOne({ let findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false } where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
}); });
switch (body.node) { switch (body.node) {
case 0: case 0:
let orgRoot = await this.orgRootRepo.findOne({ let orgRoot = await this.orgRootRepo.findOne({
where: { where: {
id: body.nodeId, id: body.nodeId,
orgRevisionId: findRevision?.id orgRevisionId: findRevision?.id,
} },
}); });
return new HttpSuccess({ return new HttpSuccess({
rootName: orgRoot?.orgRootName ?? null, rootName: orgRoot?.orgRootName ?? null,
@ -4420,8 +4374,8 @@ export class OrganizationDotnetController extends Controller {
relations: ["orgRoot"], relations: ["orgRoot"],
where: { where: {
id: body.nodeId, id: body.nodeId,
orgRevisionId: findRevision?.id orgRevisionId: findRevision?.id,
} },
}); });
return new HttpSuccess({ return new HttpSuccess({
rootName: orgChild1?.orgRoot.orgRootName ?? null, rootName: orgChild1?.orgRoot.orgRootName ?? null,
@ -4436,8 +4390,8 @@ export class OrganizationDotnetController extends Controller {
relations: ["orgRoot", "orgChild1"], relations: ["orgRoot", "orgChild1"],
where: { where: {
id: body.nodeId, id: body.nodeId,
orgRevisionId: findRevision?.id orgRevisionId: findRevision?.id,
} },
}); });
return new HttpSuccess({ return new HttpSuccess({
rootName: orgChild2?.orgRoot.orgRootName ?? null, rootName: orgChild2?.orgRoot.orgRootName ?? null,
@ -4452,8 +4406,8 @@ export class OrganizationDotnetController extends Controller {
relations: ["orgRoot", "orgChild1", "orgChild2"], relations: ["orgRoot", "orgChild1", "orgChild2"],
where: { where: {
id: body.nodeId, id: body.nodeId,
orgRevisionId: findRevision?.id orgRevisionId: findRevision?.id,
} },
}); });
return new HttpSuccess({ return new HttpSuccess({
rootName: orgChild3?.orgRoot.orgRootName ?? null, rootName: orgChild3?.orgRoot.orgRootName ?? null,
@ -4468,8 +4422,8 @@ export class OrganizationDotnetController extends Controller {
relations: ["orgRoot", "orgChild1", "orgChild2", "orgChild3"], relations: ["orgRoot", "orgChild1", "orgChild2", "orgChild3"],
where: { where: {
id: body.nodeId, id: body.nodeId,
orgRevisionId: findRevision?.id orgRevisionId: findRevision?.id,
} },
}); });
return new HttpSuccess({ return new HttpSuccess({
rootName: orgChild4?.orgRoot.orgRootName ?? null, rootName: orgChild4?.orgRoot.orgRootName ?? null,
@ -4486,7 +4440,7 @@ export class OrganizationDotnetController extends Controller {
child2Name: null, child2Name: null,
child3Name: null, child3Name: null,
child4Name: null, child4Name: null,
});; });
} }
} }
@ -4511,82 +4465,82 @@ export class OrganizationDotnetController extends Controller {
}, },
) { ) {
let typeCondition: any = {}; let typeCondition: any = {};
if (body.role === "CHILD") { if (body.role === "CHILD" || body.role === "PARENT" || body.role === "ROOT") {
switch (body.node) { switch (body.node) {
case 0: case 0:
typeCondition = { typeCondition = {
orgRoot: { orgRoot: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case 1: case 1:
typeCondition = { typeCondition = {
orgChild1: { orgChild1: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case 2: case 2:
typeCondition = { typeCondition = {
orgChild2: { orgChild2: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case 3: case 3:
typeCondition = { typeCondition = {
orgChild3: { orgChild3: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case 4: case 4:
typeCondition = { typeCondition = {
orgChild4: { orgChild4: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
default: default:
typeCondition = {}; typeCondition = {};
break; break;
} }
} else if (body.role === "ROOT" || body.role === "OWNER") { } else if (body.role === "OWNER") {
switch (body.reqNode) { switch (body.reqNode) {
case 0: case 0:
typeCondition = { typeCondition = {
orgRoot: { orgRoot: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
case 1: case 1:
typeCondition = { typeCondition = {
orgChild1: { orgChild1: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
case 2: case 2:
typeCondition = { typeCondition = {
orgChild2: { orgChild2: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
case 3: case 3:
typeCondition = { typeCondition = {
orgChild3: { orgChild3: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
case 4: case 4:
typeCondition = { typeCondition = {
orgChild4: { orgChild4: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
default: default:
@ -4598,39 +4552,39 @@ export class OrganizationDotnetController extends Controller {
case 0: case 0:
typeCondition = { typeCondition = {
orgRoot: { orgRoot: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
orgChild1: IsNull() orgChild1: IsNull(),
}; };
break; break;
case 1: case 1:
typeCondition = { typeCondition = {
orgChild1: { orgChild1: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
orgChild2: IsNull() orgChild2: IsNull(),
}; };
break; break;
case 2: case 2:
typeCondition = { typeCondition = {
orgChild2: { orgChild2: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
orgChild3: IsNull() orgChild3: IsNull(),
}; };
break; break;
case 3: case 3:
typeCondition = { typeCondition = {
orgChild3: { orgChild3: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
orgChild4: IsNull() orgChild4: IsNull(),
}; };
break; break;
case 4: case 4:
typeCondition = { typeCondition = {
orgChild4: { orgChild4: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
}; };
break; break;
@ -4670,8 +4624,8 @@ export class OrganizationDotnetController extends Controller {
orgChild4Order: "ASC", orgChild4Order: "ASC",
}, },
posMasterNo: "ASC", posMasterNo: "ASC",
} },
} },
}); });
if (body.isRetirement) { if (body.isRetirement) {
profile = await this.profileRepo.find({ profile = await this.profileRepo.find({
@ -4693,7 +4647,7 @@ export class OrganizationDotnetController extends Controller {
}); });
} }
let findRevision = await this.orgRevisionRepo.findOne({ let findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false } where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
}); });
if (body.revisionId) { if (body.revisionId) {
@ -4703,7 +4657,7 @@ export class OrganizationDotnetController extends Controller {
} }
const profile_ = await Promise.all( const profile_ = await Promise.all(
profile.map(async(item: Profile) => { profile.map(async (item: Profile) => {
const shortName = const shortName =
item.current_holders.length == 0 item.current_holders.length == 0
? null ? null
@ -4747,8 +4701,8 @@ export class OrganizationDotnetController extends Controller {
let _posMaster = await this.posMasterRepository.findOne({ let _posMaster = await this.posMasterRepository.findOne({
where: { where: {
orgRevisionId: findRevision?.id, orgRevisionId: findRevision?.id,
current_holderId: item.id current_holderId: item.id,
} },
}); });
return { return {
@ -4769,7 +4723,7 @@ export class OrganizationDotnetController extends Controller {
orgChild1Id: _posMaster?.orgChild1Id, orgChild1Id: _posMaster?.orgChild1Id,
orgChild2Id: _posMaster?.orgChild2Id, orgChild2Id: _posMaster?.orgChild2Id,
orgChild3Id: _posMaster?.orgChild3Id, orgChild3Id: _posMaster?.orgChild3Id,
orgChild4Id: _posMaster?.orgChild4Id orgChild4Id: _posMaster?.orgChild4Id,
}; };
}), }),
); );
@ -5106,41 +5060,41 @@ export class OrganizationDotnetController extends Controller {
}, },
) { ) {
let typeCondition: any = {}; let typeCondition: any = {};
if (body.role === "CHILD") { if (body.role === "CHILD" || body.role === "PARENT" || body.role === "ROOT") {
switch (body.node) { switch (body.node) {
case 0: case 0:
typeCondition = { typeCondition = {
orgRoot: { orgRoot: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case 1: case 1:
typeCondition = { typeCondition = {
orgChild1: { orgChild1: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case 2: case 2:
typeCondition = { typeCondition = {
orgChild2: { orgChild2: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case 3: case 3:
typeCondition = { typeCondition = {
orgChild3: { orgChild3: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case 4: case 4:
typeCondition = { typeCondition = {
orgChild4: { orgChild4: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
} },
}; };
break; break;
case null: case null:
@ -5150,41 +5104,41 @@ export class OrganizationDotnetController extends Controller {
typeCondition = {}; typeCondition = {};
break; break;
} }
} else if (body.role === "ROOT" || body.role === "OWNER") { } else if (body.role === "OWNER") {
switch (body.reqNode) { switch (body.reqNode) {
case 0: case 0:
typeCondition = { typeCondition = {
orgRoot: { orgRoot: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
case 1: case 1:
typeCondition = { typeCondition = {
orgChild1: { orgChild1: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
case 2: case 2:
typeCondition = { typeCondition = {
orgChild2: { orgChild2: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
case 3: case 3:
typeCondition = { typeCondition = {
orgChild3: { orgChild3: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
case 4: case 4:
typeCondition = { typeCondition = {
orgChild4: { orgChild4: {
id: body.reqNodeId id: body.reqNodeId,
} },
}; };
break; break;
default: default:
@ -5196,39 +5150,39 @@ export class OrganizationDotnetController extends Controller {
case 0: case 0:
typeCondition = { typeCondition = {
orgRoot: { orgRoot: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
orgChild1: IsNull() orgChild1: IsNull(),
}; };
break; break;
case 1: case 1:
typeCondition = { typeCondition = {
orgChild1: { orgChild1: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
orgChild2: IsNull() orgChild2: IsNull(),
}; };
break; break;
case 2: case 2:
typeCondition = { typeCondition = {
orgChild2: { orgChild2: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
orgChild3: IsNull() orgChild3: IsNull(),
}; };
break; break;
case 3: case 3:
typeCondition = { typeCondition = {
orgChild3: { orgChild3: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
orgChild4: IsNull() orgChild4: IsNull(),
}; };
break; break;
case 4: case 4:
typeCondition = { typeCondition = {
orgChild4: { orgChild4: {
ancestorDNA: body.nodeId ancestorDNA: body.nodeId,
}, },
}; };
break; break;
@ -5268,8 +5222,8 @@ export class OrganizationDotnetController extends Controller {
orgChild4Order: "ASC", orgChild4Order: "ASC",
}, },
posMasterNo: "ASC", posMasterNo: "ASC",
} },
} },
}); });
if (body.isRetirement) { if (body.isRetirement) {
profile = await this.profileEmpRepo.find({ profile = await this.profileEmpRepo.find({
@ -5291,7 +5245,7 @@ export class OrganizationDotnetController extends Controller {
}); });
} }
let findRevision = await this.orgRevisionRepo.findOne({ let findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false } where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
}); });
if (body.revisionId) { if (body.revisionId) {
@ -5301,7 +5255,7 @@ export class OrganizationDotnetController extends Controller {
} }
const profile_ = await Promise.all( const profile_ = await Promise.all(
profile.map(async(item: ProfileEmployee) => { profile.map(async (item: ProfileEmployee) => {
const shortName = const shortName =
item.current_holders.length == 0 item.current_holders.length == 0
? null ? null
@ -5345,8 +5299,8 @@ export class OrganizationDotnetController extends Controller {
let _posMaster = await this.empPosMasterRepository.findOne({ let _posMaster = await this.empPosMasterRepository.findOne({
where: { where: {
orgRevisionId: findRevision?.id, orgRevisionId: findRevision?.id,
current_holderId: item.id current_holderId: item.id,
} },
}); });
return { return {
@ -5360,9 +5314,10 @@ export class OrganizationDotnetController extends Controller {
keycloak: item.keycloak, keycloak: item.keycloak,
posNo: shortName, posNo: shortName,
position: item.position, position: item.position,
positionLevel: item.posType?.posTypeShortName && item.posLevel?.posLevelName positionLevel:
? `${item.posType?.posTypeShortName} ${item.posLevel?.posLevelName}` item.posType?.posTypeShortName && item.posLevel?.posLevelName
: null, ? `${item.posType?.posTypeShortName} ${item.posLevel?.posLevelName}`
: null,
positionType: item.posType?.posTypeName ?? null, positionType: item.posType?.posTypeName ?? null,
oc: Oc, oc: Oc,
orgRootId: _posMaster?.orgRootId, orgRootId: _posMaster?.orgRootId,
@ -5580,7 +5535,7 @@ export class OrganizationDotnetController extends Controller {
} }
const position = await AppDataSource.query("CALL GetProfileEmployeeSalaryPosition(?, ?)", [ const position = await AppDataSource.query("CALL GetProfileEmployeeSalaryPosition(?, ?)", [
profile.id, profile.id,
_currentDate _currentDate,
]); ]);
const _position = position.length > 0 ? position[0] : []; const _position = position.length > 0 ? position[0] : [];
@ -5692,11 +5647,13 @@ export class OrganizationDotnetController extends Controller {
} }
} }
if (profile && profile?.isLeave) { if (profile && profile?.isLeave) {
_currentDate = profile && profile.leaveDate _currentDate =
? Extension.toDateOnlyString(profile.leaveDate) profile && profile.leaveDate ? Extension.toDateOnlyString(profile.leaveDate) : _currentDate;
: _currentDate
} }
const position = await AppDataSource.query("CALL GetProfileSalaryPosition(?, ?)", [profile.id, _currentDate]); const position = await AppDataSource.query("CALL GetProfileSalaryPosition(?, ?)", [
profile.id,
_currentDate,
]);
const _position = position.length > 0 ? position[0] : []; const _position = position.length > 0 ? position[0] : [];
const mapProfile = { const mapProfile = {

View file

@ -732,6 +732,14 @@ export class PermissionController extends Controller {
child3: null, child3: null,
child4: null, child4: null,
}; };
} else if (privilege == "PARENT") {
data = {
root: [x.orgRootId],
child1: [x.orgChild1Id],
child2: null,
child3: null,
child4: null,
};
} else if (privilege == "CHILD") { } else if (privilege == "CHILD") {
data = { data = {
root: node >= 0 ? [x.orgRootId] : null, root: node >= 0 ? [x.orgRootId] : null,

View file

@ -915,6 +915,7 @@ export class KeycloakController extends Controller {
// keycloak: IsNull(), // keycloak: IsNull(),
isLeave: false, isLeave: false,
}, },
order: { citizenId: "ASC" },
relations: ["roleKeycloaks"], relations: ["roleKeycloaks"],
}); });
@ -928,12 +929,11 @@ export class KeycloakController extends Controller {
}); });
// Process แบบ batch เพื่อลดการเรียก API ทีละตัว // Process แบบ batch เพื่อลดการเรียก API ทีละตัว
const batchSize = 10; const batchSize = 100;
const batches = []; const batches = [];
for (let i = 0; i < profiles.length; i += batchSize) { for (let i = 0; i < profiles.length; i += batchSize) {
batches.push(profiles.slice(i, i + batchSize)); batches.push(profiles.slice(i, i + batchSize));
} }
for (const batch of batches) { for (const batch of batches) {
await Promise.all( await Promise.all(
batch.map(async (_item) => { batch.map(async (_item) => {

View file

@ -55,29 +55,35 @@ export class WorkflowController extends Controller {
fullName?: string | null; fullName?: string | null;
}, },
) { ) {
// ขั้นที่ 1: ทำการค้นหา profile และ metaWorkflow แบบ parallel
const [userProfileOfficer, userProfileEmployee, metaWorkflow] = await Promise.all([
this.profileRepo.findOne({
where: { keycloak: req.user.sub },
select: ["id", "keycloak"],
}),
this.profileEmployeeRepo.findOne({
where: { keycloak: req.user.sub },
select: ["id", "keycloak"],
}),
this.metaWorkflowRepo.findOne({
where: {
sysName: body.sysName,
posLevelName: body.posLevelName,
posTypeName: body.posTypeName,
},
}),
]);
// กำหนด profile type และ profile
let profileType = "OFFICER"; let profileType = "OFFICER";
let profile: any = await this.profileRepo.findOne({ let profile: any = userProfileOfficer;
where: {
keycloak: req.user.sub,
},
});
if (!profile) { if (!profile) {
profileType = "EMPLOYEE"; profileType = "EMPLOYEE";
profile = await this.profileEmployeeRepo.findOne({ profile = userProfileEmployee;
where: {
keycloak: req.user.sub,
},
});
if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลผู้ใช้งาน"); if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลผู้ใช้งาน");
} }
const metaWorkflow = await this.metaWorkflowRepo.findOne({
where: {
sysName: body.sysName,
posLevelName: body.posLevelName,
posTypeName: body.posTypeName,
},
});
if (!metaWorkflow) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบกระบวนการนี้ได้"); if (!metaWorkflow) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบกระบวนการนี้ได้");
const meta = { const meta = {
@ -88,6 +94,8 @@ export class WorkflowController extends Controller {
createdAt: new Date(), createdAt: new Date(),
lastUpdatedAt: new Date(), lastUpdatedAt: new Date(),
}; };
// ขั้นที่ 2: สร้าง workflow และดึง metaState แบบ parallel
const workflow = new Workflow(); const workflow = new Workflow();
Object.assign(workflow, { Object.assign(workflow, {
...metaWorkflow, ...metaWorkflow,
@ -97,117 +105,130 @@ export class WorkflowController extends Controller {
profileType: profileType, profileType: profileType,
system: body.sysName, system: body.sysName,
}); });
await this.workflowRepo.save(workflow);
const metaState = await this.metaStateRepo.find({ const [savedWorkflow, metaStates] = await Promise.all([
where: { this.workflowRepo.save(workflow),
metaWorkflowId: metaWorkflow.id, this.metaStateRepo.find({
}, where: { metaWorkflowId: metaWorkflow.id },
order: { order: "ASC" }, order: { order: "ASC" },
}),
]);
// ขั้นที่ 3: สร้าง states ทั้งหมดในครั้งเดียว
const statesToCreate = metaStates.map((item) => {
const state = new State();
Object.assign(state, { ...item, id: undefined, workflowId: savedWorkflow.id, ...meta });
return state;
}); });
await Promise.all( const savedStates = await this.stateRepo.save(statesToCreate);
metaState.map(async (item) => {
const state = new State(); // ขั้นที่ 4: อัปเดต workflow.stateId กับ state แรก
Object.assign(state, { ...item, id: undefined, workflowId: workflow.id, ...meta }); const firstState = savedStates.find((state) => state.order === 1);
await this.stateRepo.save(state); if (firstState) {
if (state.order == 1) { savedWorkflow.stateId = firstState.id;
workflow.stateId = state.id; await this.workflowRepo.save(savedWorkflow);
await this.workflowRepo.save(workflow); }
}
const metaStateOperator = await this.metaStateOperatorRepo.find({ // ขั้นที่ 5: ดึง metaStateOperators ทั้งหมดและสร้าง stateOperators
where: { const metaStateIds = metaStates.map((item) => item.id);
metaStateId: item.id, const allMetaStateOperators = await this.metaStateOperatorRepo.find({
}, where: { metaStateId: In(metaStateIds) },
});
// สร้าง stateOperators ทั้งหมดในครั้งเดียว
const stateOperatorsToCreate: StateOperator[] = [];
allMetaStateOperators.forEach((metaStateOp) => {
const correspondingState = savedStates.find(
(state) =>
metaStates.find((metaState) => metaState.id === metaStateOp.metaStateId)?.order ===
state.order,
);
if (correspondingState) {
const stateOperator = new StateOperator();
Object.assign(stateOperator, {
...metaStateOp,
id: undefined,
stateId: correspondingState.id,
...meta,
}); });
await Promise.all( stateOperatorsToCreate.push(stateOperator);
metaStateOperator.map(async (item1) => { }
const stateOperator = new StateOperator(); });
Object.assign(stateOperator, { ...item1, id: undefined, stateId: state.id, ...meta });
await this.stateOperatorRepo.save(stateOperator); await this.stateOperatorRepo.save(stateOperatorsToCreate);
}), // ขั้นที่ 6: สร้าง StateOperatorUsers แบบ bulk
); const stateOperatorUsersToCreate: StateOperatorUser[] = [];
}), let orderNum = 1;
);
let num = 1; // เพิ่ม Owner ก่อน
const stateOperatorUser = new StateOperatorUser();
if (profile) { if (profile) {
Object.assign(stateOperatorUser, { const ownerStateOperatorUser = new StateOperatorUser();
profileId: profileType == "OFFICER" ? profile.id : null, Object.assign(ownerStateOperatorUser, {
profileEmployeeId: profileType != "OFFICER" ? profile.id : null, profileId: profileType === "OFFICER" ? profile.id : null,
profileEmployeeId: profileType !== "OFFICER" ? profile.id : null,
profileType: profileType, profileType: profileType,
operator: "Owner", operator: "Owner",
order: num, order: orderNum,
workflowId: workflow.id, workflowId: savedWorkflow.id,
...meta, ...meta,
}); });
stateOperatorUsersToCreate.push(ownerStateOperatorUser);
} }
await this.stateOperatorUserRepo.save(stateOperatorUser);
const profileOfficer = await this.posMasterRepo.find({ // ดึงข้อมูล profileOfficers และสร้าง StateOperatorUsers
const profileOfficers = await this.posMasterRepo.find({
where: { where: {
posMasterAssigns: { assignId: body.sysName }, posMasterAssigns: { assignId: body.sysName },
orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true }, orgRevision: { orgRevisionIsDraft: false, orgRevisionIsCurrent: true },
current_holderId: Not(IsNull()), // เพิ่มเงื่อนไขนี้เพื่อกรองเฉพาะที่มี current_holder
}, },
relations: ["orgChild1"], relations: ["orgChild1"],
select: ["current_holderId", "orgChild1"], // เลือกเฉพาะ field ที่จำเป็น
}); });
await Promise.all(
profileOfficer.map(async (item, i) => { // สร้าง StateOperatorUsers สำหรับ officers
if (item.current_holderId) { profileOfficers.forEach((item) => {
num = num + 1; if (item.current_holderId) {
if (item.orgChild1 == null || item.orgChild1.isOfficer == false) { orderNum += 1;
const stateOperatorUser = new StateOperatorUser(); const isPersonnelOfficer = item.orgChild1?.isOfficer === true;
Object.assign(stateOperatorUser, {
profileId: item.current_holderId, const officerStateOperatorUser = new StateOperatorUser();
operator: "Officer", Object.assign(officerStateOperatorUser, {
profileType: "OFFICER", profileId: item.current_holderId,
order: num, operator: isPersonnelOfficer ? "PersonnelOfficer" : "Officer",
workflowId: workflow.id, profileType: "OFFICER",
...meta, order: orderNum,
}); workflowId: savedWorkflow.id,
await this.stateOperatorUserRepo.save(stateOperatorUser); ...meta,
} else { });
const stateOperatorUser = new StateOperatorUser(); stateOperatorUsersToCreate.push(officerStateOperatorUser);
Object.assign(stateOperatorUser, { }
profileId: item.current_holderId, });
operator: "PersonnelOfficer",
profileType: "OFFICER", // บันทึก StateOperatorUsers ทั้งหมดในครั้งเดียว
order: num, await this.stateOperatorUserRepo.save(stateOperatorUsersToCreate);
workflowId: workflow.id,
...meta, // ขั้นที่ 7: ส่ง notification (ใช้ข้อมูลที่มีอยู่แล้วแทนการ query ใหม่)
}); const firstStateOperators = stateOperatorsToCreate.filter((so) =>
await this.stateOperatorUserRepo.save(stateOperatorUser); savedStates.find((state) => state.id === so.stateId && state.order === 1),
}
}
}),
); );
const _workflow = await this.workflowRepo.findOne({ const notificationReceivers = stateOperatorUsersToCreate
where: { id: workflow.id }, .filter((user) => firstStateOperators.some((op) => op.operator === user.operator))
relations: ["stateOperatorUsers"], .map((user) => ({
}); receiverUserId: user.profileType === "OFFICER" ? user.profileId : user.profileEmployeeId,
if (!_workflow) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่สามารถดำเนินการกระบวนการนี้ได้");
const _state = await this.stateRepo.findOne({
where: {
id: _workflow.stateId,
},
relations: ["stateOperators"],
});
if (!_state) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลขั้นตอนการอนุมัติ");
let profileNow = _workflow.stateOperatorUsers
.filter((x) => _state.stateOperators.map((s) => s.operator).includes(x.operator))
.map((x) => ({
receiverUserId: x.profileType == "OFFICER" ? x.profileId : x.profileEmployeeId,
notiLink: "", notiLink: "",
})); }));
await new CallAPI()
// ส่ง notification แบบ fire-and-forget
new CallAPI()
.PostData(req, "/placement/noti/profiles", { .PostData(req, "/placement/noti/profiles", {
// subject: `รายการถูกส่ง`, subject: `แจ้ง${savedWorkflow.name}ของ ${body.fullName}`,
// body: `รายการถูกส่ง`, body: `แจ้ง${savedWorkflow.name}ของ ${body.fullName}`,
subject: `แจ้ง${workflow.name}ของ ${body.fullName}`, receiverUserIds: notificationReceivers,
body: `แจ้ง${workflow.name}ของ ${body.fullName}`, payload: "",
receiverUserIds: profileNow,
payload: "", //แนบไฟล์
isSendMail: true, isSendMail: true,
isSendInbox: true, isSendInbox: true,
isSendNotification: true, isSendNotification: true,
@ -809,8 +830,8 @@ export class WorkflowController extends Controller {
pageSize: number; pageSize: number;
keycloakId?: string | null; keycloakId?: string | null;
type?: string | null; type?: string | null;
sortBy?: string | null, sortBy?: string | null;
descending?: boolean, descending?: boolean;
}, },
) { ) {
const userKeycloak = body.keycloakId ?? request.user.sub; const userKeycloak = body.keycloakId ?? request.user.sub;
@ -990,7 +1011,7 @@ export class WorkflowController extends Controller {
if (body.sortBy) { if (body.sortBy) {
queryBuilder = queryBuilder.orderBy( queryBuilder = queryBuilder.orderBy(
`entity.${body.sortBy}`, `entity.${body.sortBy}`,
body.descending ? "DESC" : "ASC" body.descending ? "DESC" : "ASC",
); );
} }

View file

@ -94,6 +94,15 @@ class CheckAuth {
child4: null, child4: null,
privilege: "ROOT", privilege: "ROOT",
}; };
} else if (privilege == "PARENT") {
data = {
root: [x.orgRootId],
child1: [x.orgChild1Id],
child2: null,
child3: null,
child4: null,
privilege: "PARENT",
};
} else if (privilege == "CHILD") { } else if (privilege == "CHILD") {
data = { data = {
root: node >= 0 ? [x.orgRootId] : null, root: node >= 0 ? [x.orgRootId] : null,

View file

@ -56,7 +56,7 @@ export async function getToken() {
if (data && data.access_token) { if (data && data.access_token) {
token = data.access_token; token = data.access_token;
} }
console.log(`token: ${token}`);
return token; return token;
} }