From e59ccf88b366a8e2e2bff8fab838a23765432321 Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Tue, 21 Oct 2025 00:11:18 +0700 Subject: [PATCH] fix: script create keycloak --- src/controllers/OrganizationController.ts | 145 ++++++++++++---------- 1 file changed, 77 insertions(+), 68 deletions(-) diff --git a/src/controllers/OrganizationController.ts b/src/controllers/OrganizationController.ts index 4cb17e6d..47e97934 100644 --- a/src/controllers/OrganizationController.ts +++ b/src/controllers/OrganizationController.ts @@ -7747,80 +7747,89 @@ export class OrganizationController extends Controller { */ @Get("update/org/profile-employee/create-keycloak") async createKeycloakForEmployee(@Request() request: RequestWithUser) { - const [profiles, token] = await Promise.all([ - this.profileEmployeeRepo.find({ - where: { - keycloak: IsNull(), - isActive: true, - }, - relations: ["roleKeycloaks"], - }), - getToken(), - ]); - - if (!token) - throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "ไม่สามารถเชื่อมต่อ Keycloak"); - let check: number = 0; - 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, token); - let userId: any = ""; - if (checkUser.length == 0) { - userId = await createUser( - _item.citizenId, - password, - { - firstName: _item.firstName, - lastName: _item.lastName, - // email: _item.email, - }, - token, - ); - if (typeof userId !== "string") { - throw new Error(userId.errorMessage); - } - } else { - userId = checkUser[0].id; - } + const profiles = await this.profileEmployeeRepo.find({ + where: { + keycloak: IsNull(), + isLeave: false, + isRetirement: false, + }, + order: { citizenId: "ASC" }, + relations: ["roleKeycloaks"], + }); - const list = await getRoles("", token); - 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"), - token, - ); + // ดึงข้อมูลที่ใช้บ่อยก่อน (cache) + const rolesList = await getRoles(); + if (!Array.isArray(rolesList)) + throw new Error("Failed. Cannot get role(s) data from the server."); - 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.profileEmployeeRepo.save(_item); - check += 1; - } + const roleKeycloak = await this.roleKeycloakRepo.find({ + where: { id: "8a1a0dc9-304c-4e5b-a90a-65f841048212" }, + }); + + // Process แบบ batch เพื่อลดการเรียก API ทีละตัว + const batchSize = 100; + 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])); + check += 1; + await this.profileEmployeeRepo.save(_item); + } + } catch (error) { + console.error(`Error processing ${_item.citizenId}:`, error); + } + }), + ); + } const total = profiles.length; - return new HttpSuccess({ total, successAmount: check }); } }