From 40f1a08b901ddfd564da6fdcdc3eab930a628c8a Mon Sep 17 00:00:00 2001 From: Kittapath <67353855+M-FTP@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:08:15 +0700 Subject: [PATCH] refactor code create user emp (#177) Co-authored-by: mamoss <> --- src/controllers/UserController.ts | 202 ++++++++++++++++++++++-------- 1 file changed, 149 insertions(+), 53 deletions(-) diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index 8d77b1ec..7d85e6f9 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -908,66 +908,82 @@ export class KeycloakController extends Controller { ) { const profiles = await this.profileEmpRepo.find({ where: { - keycloak: IsNull(), + // keycloak: IsNull(), + isLeave: false, }, relations: ["roleKeycloaks"], }); - for await (const _item of profiles) { - let password = _item.citizenId; - if (_item.birthDate != null) { - // const gregorianYear = _item.birthDate.getFullYear() + 543; + // ดึงข้อมูลที่ใช้บ่อยก่อน (cache) + const rolesList = await getRoles(); + if (!Array.isArray(rolesList)) + throw new Error("Failed. Cannot get role(s) data from the server."); - // const formattedDate = - // _item.birthDate.toISOString().slice(8, 10) + - // _item.birthDate.toISOString().slice(5, 7) + - // gregorianYear; - // password = formattedDate; - const _date = new Date(_item.birthDate.toDateString()) - .getDate() - .toString() - .padStart(2, "0"); - const _month = (new Date(_item.birthDate.toDateString()).getMonth() + 1) - .toString() - .padStart(2, "0"); - const _year = new Date(_item.birthDate.toDateString()).getFullYear() + 543; - password = `${_date}${_month}${_year}`; - } - const checkUser = await getUserByUsername(_item.citizenId); - let userId: any = ""; - if (checkUser.length == 0) { - userId = await createUser(_item.citizenId, password, { - firstName: _item.firstName, - lastName: _item.lastName, - // email: _item.email, - }); - if (typeof userId !== "string") { - throw new Error(userId.errorMessage); - } - } else { - userId = checkUser[0].id; - } + const roleKeycloak = await this.roleKeycloakRepo.find({ + where: { id: "8a1a0dc9-304c-4e5b-a90a-65f841048212" }, + }); - const list = await getRoles(); - if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server."); - const result = await addUserRoles( - userId, - list.filter((v) => v.id == "8a1a0dc9-304c-4e5b-a90a-65f841048212"), + // Process แบบ batch เพื่อลดการเรียก API ทีละตัว + const batchSize = 10; + const batches = []; + for (let i = 0; i < profiles.length; i += batchSize) { + batches.push(profiles.slice(i, i + batchSize)); + } + + for (const batch of batches) { + await Promise.all( + batch.map(async (_item) => { + let password = _item.citizenId; + if (_item.birthDate != null) { + const _date = new Date(_item.birthDate.toDateString()) + .getDate() + .toString() + .padStart(2, "0"); + const _month = (new Date(_item.birthDate.toDateString()).getMonth() + 1) + .toString() + .padStart(2, "0"); + const _year = new Date(_item.birthDate.toDateString()).getFullYear() + 543; + password = `${_date}${_month}${_year}`; + } + + try { + const checkUser = await getUserByUsername(_item.citizenId); + let userId: any = ""; + if (checkUser.length == 0) { + userId = await createUser(_item.citizenId, password, { + firstName: _item.firstName, + lastName: _item.lastName, + }); + if (typeof userId !== "string") { + console.error(`Failed to create user for ${_item.citizenId}:`, userId.errorMessage); + return; + } + } else { + userId = checkUser[0].id; + } + + const result = await addUserRoles( + userId, + rolesList.filter((v) => v.id == "8a1a0dc9-304c-4e5b-a90a-65f841048212"), + ); + + if (!result) { + console.error(`Failed to set role for user ${_item.citizenId}`); + return; + } + + if (typeof userId === "string") { + _item.keycloak = userId; + } + if (_item) { + _item.roleKeycloaks = Array.from(new Set([..._item.roleKeycloaks, ...roleKeycloak])); + await this.profileEmpRepo.save(_item); + } + } catch (error) { + console.error(`Error processing ${_item.citizenId}:`, error); + } + }), ); - - if (!result) { - throw new Error("Failed. Cannot set user's role."); - } - if (typeof userId === "string") { - _item.keycloak = userId; - } - const roleKeycloak = await this.roleKeycloakRepo.find({ - where: { id: "8a1a0dc9-304c-4e5b-a90a-65f841048212" }, - }); - if (_item) { - _item.roleKeycloaks = Array.from(new Set([..._item.roleKeycloaks, ...roleKeycloak])); - this.profileEmpRepo.save(_item); - } } return ""; } @@ -1079,4 +1095,84 @@ export class KeycloakController extends Controller { } return ""; } + + @Post("add-role-staff/user-emp/{child1Id}") + @Security("bearerAuth", ["system", "admin"]) + async addroleStaffToUserEmp( + @Path() child1Id: string, + @Request() request: { user: { sub: string; preferred_username: string } }, + ) { + const profiles = await this.profileEmpRepo.find({ + where: { + keycloak: Not(IsNull()), + isLeave: false, + current_holders: { + orgChild1Id: child1Id, + }, + }, + relations: ["roleKeycloaks"], + }); + // return profiles.length; + + for await (const _item of profiles) { + let password = _item.citizenId; + if (_item.birthDate != null) { + const _date = new Date(_item.birthDate.toDateString()) + .getDate() + .toString() + .padStart(2, "0"); + const _month = (new Date(_item.birthDate.toDateString()).getMonth() + 1) + .toString() + .padStart(2, "0"); + const _year = new Date(_item.birthDate.toDateString()).getFullYear() + 543; + password = `${_date}${_month}${_year}`; + } + const checkUser = await getUserByUsername(_item.citizenId); + let userId: any = ""; + if (checkUser.length == 0) { + userId = await createUser(_item.citizenId, password, { + firstName: _item.firstName, + lastName: _item.lastName, + }); + if (typeof userId !== "string") { + throw new Error(userId.errorMessage); + } + } else { + userId = checkUser[0].id; + } + + const list = await getRoles(); + if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server."); + const resultUser = await addUserRoles( + userId, + list.filter((v) => v.id == "8a1a0dc9-304c-4e5b-a90a-65f841048212"), + ); + const resultStaff = await addUserRoles( + userId, + list.filter((v) => v.id == "f1fff8db-0795-47c1-9952-f3c18d5b6172"), + ); + + // if (!resultUser) { + // throw new Error("Failed. Cannot set user's role."); + // } + + // if (!resultStaff) { + // throw new Error("Failed. Cannot set staff's role."); + // } + if (typeof userId === "string") { + _item.keycloak = userId; + } + const roleKeycloakUser = await this.roleKeycloakRepo.find({ + where: { id: "8a1a0dc9-304c-4e5b-a90a-65f841048212" }, + }); + const roleKeycloakStaff = await this.roleKeycloakRepo.find({ + where: { id: "f1fff8db-0795-47c1-9952-f3c18d5b6172" }, + }); + if (_item) { + _item.roleKeycloaks = Array.from(new Set([...roleKeycloakUser, ...roleKeycloakStaff])); + this.profileEmpRepo.save(_item); + } + } + return ""; + } }