fix bug run delete keycloak

This commit is contained in:
Warunee Tamkoo 2025-10-03 22:18:32 +07:00
parent f28aca5c1d
commit abab998cd0
2 changed files with 38 additions and 26 deletions

View file

@ -37,7 +37,7 @@ import { sendToQueueOrg, sendToQueueOrgDraft } from "../services/rabbitmq";
import { PosType } from "../entities/PosType";
import { PosLevel } from "../entities/PosLevel";
import { PermissionOrg } from "../entities/PermissionOrg";
import { deleteUser } from "../keycloak";
import { deleteUser, getToken } from "../keycloak";
import {
CreatePosMasterHistoryEmployee,
CreatePosMasterHistoryOfficer,
@ -8159,35 +8159,47 @@ export class OrganizationController extends Controller {
// }),
// );
const profileLeave = await this.profileEmployeeRepo.find({
where: {
isLeave: true,
leaveType: "RETIRE",
},
});
const [profileLeave, token] = await Promise.all([
this.profileEmployeeRepo.find({
where: {
isLeave: true,
leaveType: "RETIRE",
},
}),
getToken(),
]);
if (!token)
throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "ไม่สามารถเชื่อมต่อ Keycloak");
let check: number = 0;
let notDelete: string[] = [];
await Promise.all(
profileLeave.map(async (profile) => {
profile.leaveReason = "เกษียณอายุราชการ";
profile.isActive = false;
if (profile.keycloak != null && profile.keycloak != "") {
const delUserKeycloak = await deleteUser(profile.keycloak);
if (delUserKeycloak) {
profile.keycloak = "";
profile.roleKeycloaks = [];
check += 1;
} else {
// push array not delete
notDelete.push(profile.keycloak);
// loop batch at 50 profiles
const chunkSize = 50;
for (let i = 0; i < profileLeave.length; i += chunkSize) {
const chunk = profileLeave.slice(i, i + chunkSize);
await Promise.all(
chunk.map(async (profile) => {
profile.leaveReason = "เกษียณอายุราชการ";
profile.isActive = false;
if (profile.keycloak != null && profile.keycloak != "") {
const delUserKeycloak = await deleteUser(profile.keycloak, token);
if (delUserKeycloak) {
profile.keycloak = "";
profile.roleKeycloaks = [];
check += 1;
} else {
// push array not delete
notDelete.push(profile.keycloak);
}
}
}
await this.profileEmployeeRepo.save(profile);
}),
);
await this.profileEmployeeRepo.save(profile);
}),
);
}
// จำนวนคนที่ถูกแก้ไขเหตุผลการลาออก
const total = profileLeave.length;

View file

@ -360,11 +360,11 @@ export async function enableStatus(userId: string, status: boolean) {
*
* @returns user true if success, false otherwise.
*/
export async function deleteUser(userId: string) {
export async function deleteUser(userId: string, token?: string) {
const res = await fetch(`${KC_URL}/admin/realms/${KC_REALMS}/users/${userId}`, {
// prettier-ignore
headers: {
"authorization": `Bearer ${await getToken()}`,
"authorization": `Bearer ${token || await getToken()}`,
"content-type": `application/json`,
},
method: "DELETE",