diff --git a/src/controllers/CommandController.ts b/src/controllers/CommandController.ts index 4454e041..f116f73e 100644 --- a/src/controllers/CommandController.ts +++ b/src/controllers/CommandController.ts @@ -2215,7 +2215,6 @@ export class CommandController extends Controller { profile.lastUpdateUserId = req.user.sub; profile.lastUpdateFullName = req.user.name; profile.lastUpdatedAt = new Date(); - // profile.dateStart = new Date(); if (item.isLeave == true) { await removeProfileInOrganize(profile.id, "OFFICER"); } @@ -2236,21 +2235,25 @@ export class CommandController extends Controller { const returnWork = await checkReturnCommandType(String(item.commandId)); //คำสั่งบรรจุกลับเข้ารับราชการ หรือ ผู้ออกไปรับราชการทหารกลับเข้ารับราชการ solutionเดิม ให้ enable user เปลี่ยนเป็นสร้าง user ใหม่เลยเพราะยังไงตอนถูกพักก็ถูกลบ user if (returnWork && item.isGovernment) { - /*if (profile.keycloak != null) { - const enableActive = await enableStatus(profile.keycloak, true); - if (!enableActive) throw new Error("Failed. Cannot change enable status."); - } else {*/ - const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { - firstName: profile.firstName, - lastName: profile.lastName, - }); - // if (typeof userKeycloakId !== "string") { - // throw new Error(userKeycloakId.errorMessage); - // } - const list = await getRoles(); - if (!Array.isArray(list)) - throw new Error("Failed. Cannot get role(s) data from the server."); - const result = await addUserRoles( + let userKeycloakId; + userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { + firstName: profile.firstName, + lastName: profile.lastName, + }); + // กรณี Keycloak ไม่ถูกลบ ให้ลบซ้ำอีกรอบแล้วสร้างใหม่ + if (profile.keycloak != null && userKeycloakId && userKeycloakId.error === "User exists with same username") { + const delUserKeycloak = await deleteUser(profile.keycloak); + if(delUserKeycloak) { + userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { + firstName: profile.firstName, + lastName: profile.lastName, + }); + } + } + const list = await getRoles(); + let result = false; + if (Array.isArray(list) && userKeycloakId) { + result = await addUserRoles( userKeycloakId, list .filter((v) => v.name === "USER") @@ -2259,10 +2262,9 @@ export class CommandController extends Controller { name: x.name, })), ); - // if (!result) throw new Error("Failed. Cannot set user's role."); - profile.keycloak = typeof userKeycloakId === "string" ? userKeycloakId : ""; - /*}*/ + } profile.isActive = true; + profile.keycloak = typeof userKeycloakId === "string" ? userKeycloakId : ""; profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : []; } await this.profileRepository.save(profile);