hrms-api-org/src/controllers/ProfileEditController.ts

387 lines
12 KiB
TypeScript
Raw Normal View History

2024-07-19 11:08:47 +07:00
import {
Body,
Controller,
Delete,
Get,
Patch,
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import HttpSuccess from "../interfaces/http-success";
import { AppDataSource } from "../database/data-source";
import { Profile } from "../entities/Profile";
import { CreateProfileEdit, EditProfileEdit, ProfileEdit } from "../entities/ProfileEdit";
import { RequestWithUser } from "../middlewares/user";
2024-08-30 18:02:34 +07:00
import { Brackets } from "typeorm";
2024-10-17 19:26:33 +07:00
import CallAPI from "../interfaces/call-api";
2025-06-12 15:56:42 +07:00
import permission from "../interfaces/permission";
import { OrgRevision } from "../entities/OrgRevision";
import { OrgRoot } from "../entities/OrgRoot";
2024-07-19 11:08:47 +07:00
@Route("api/v1/org/profile/edit")
@Tags("ProfileEdit")
@Security("bearerAuth")
export class ProfileEditController extends Controller {
private profileRepo = AppDataSource.getRepository(Profile);
private profileEditRepo = AppDataSource.getRepository(ProfileEdit);
2025-06-12 15:56:42 +07:00
private orgRevisionRepository = AppDataSource.getRepository(OrgRevision);
private orgRootRepo = AppDataSource.getRepository(OrgRoot);
2024-07-19 11:08:47 +07:00
@Get("user")
public async detailProfileEditUser(
@Request() request: { user: Record<string, any> },
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query("keyword") keyword: string = "",
@Query("status") status: string = "",
2025-09-12 10:09:48 +07:00
@Query("sortBy") sortBy?: string,
@Query("descending") descending?: boolean,
2024-07-19 11:08:47 +07:00
) {
const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
2025-09-12 10:09:48 +07:00
let query = await AppDataSource.getRepository(ProfileEdit)
2024-07-19 11:08:47 +07:00
.createQueryBuilder("ProfileEdit")
.leftJoinAndSelect("ProfileEdit.profile", "profile")
.where((qb) => {
if (status != "" && status != null) {
qb.andWhere("ProfileEdit.status = :status", { status: status });
}
qb.andWhere("ProfileEdit.profileId = :profileId", { profileId: profile.id });
2024-07-19 11:08:47 +07:00
})
.andWhere(
new Brackets((qb) => {
2024-08-30 18:02:34 +07:00
qb.where(keyword != "" && keyword != null ? "ProfileEdit.topic LIKE :keyword" : "1=1", {
keyword: `%${keyword}%`,
2025-06-12 15:56:42 +07:00
})
.orWhere(
keyword != "" && keyword != null ? "ProfileEdit.detail LIKE :keyword" : "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != "" && keyword != null ? "ProfileEdit.remark LIKE :keyword" : "1=1",
{
keyword: `%${keyword}%`,
},
);
}),
)
2025-11-29 14:56:58 +07:00
.orderBy("ProfileEdit.createdAt", "DESC");
2025-09-12 10:09:48 +07:00
if (sortBy) {
2025-11-29 14:56:58 +07:00
query = query.orderBy(`ProfileEdit.${sortBy}`, descending ? "DESC" : "ASC");
2025-09-12 10:09:48 +07:00
}
const [getProfileEdit, total] = await query
2025-11-29 14:56:58 +07:00
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
2024-07-19 11:08:47 +07:00
const _data = getProfileEdit.map((item) => ({
id: item.id,
topic: item.topic,
detail: item.detail,
status: item.status,
remark: item.remark,
createdAt: item.createdAt,
createdFullName: item.createdFullName,
lastUpdatedAt: item.lastUpdatedAt,
lastUpdateFullName: item.lastUpdateFullName,
fullname:
(item?.profile?.prefix ?? "") +
"" +
(item?.profile?.firstName ?? "") +
" " +
(item?.profile?.lastName ?? ""),
}));
return new HttpSuccess({ data: _data, total: total });
}
@Get("admin")
public async detailProfileEditAdmin(
2025-06-12 15:56:42 +07:00
@Request() request: RequestWithUser,
2024-07-19 11:08:47 +07:00
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query("keyword") keyword: string = "",
@Query("status") status: string = "",
2025-09-23 11:54:17 +07:00
@Query("sortBy") sortBy?: string,
@Query("descending") descending?: boolean,
2024-07-19 11:08:47 +07:00
) {
2025-06-12 15:56:42 +07:00
let data = await new permission().PermissionOrgList(request, "SYS_REGISTRY_OFFICER");
const orgRevisionPublish = await this.orgRevisionRepository
.createQueryBuilder("orgRevision")
.where("orgRevision.orgRevisionIsDraft = false")
.andWhere("orgRevision.orgRevisionIsCurrent = true")
.getOne();
2025-09-23 11:54:17 +07:00
let query = await AppDataSource.getRepository(ProfileEdit)
2024-07-19 11:08:47 +07:00
.createQueryBuilder("ProfileEdit")
.leftJoinAndSelect("ProfileEdit.profile", "profile")
2025-06-12 15:56:42 +07:00
.leftJoinAndSelect("profile.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
.where((qb) => {
if (status != "" && status != null) {
qb.andWhere("ProfileEdit.status = :status", { status: status });
}
qb.andWhere("ProfileEdit.profileId IS NOT NULL");
2024-07-19 11:08:47 +07:00
})
2025-06-12 15:56:42 +07:00
.andWhere(orgRevisionPublish ? `current_holders.orgRevisionId = :revisionId` : "1=1", {
revisionId: orgRevisionPublish?.id,
})
.andWhere(
data.root != undefined && data.root != null
? data.root[0] != null
? `current_holders.orgRootId IN (:...root)`
: `current_holders.orgRootId is null`
: "1=1",
{
root: data.root,
},
)
.andWhere(
data.child1 != undefined && data.child1 != null
? data.child1[0] != null
? `current_holders.orgChild1Id IN (:...child1)`
2025-11-29 14:56:58 +07:00
: `current_holders.orgChild1Id is ${data.privilege == "PARENT" ? "not null" : "null"}`
2025-06-12 15:56:42 +07:00
: "1=1",
{
child1: data.child1,
},
)
.andWhere(
data.child2 != undefined && data.child2 != null
? data.child2[0] != null
? `current_holders.orgChild2Id IN (:...child2)`
: `current_holders.orgChild2Id is null`
: "1=1",
{
child2: data.child2,
},
)
.andWhere(
data.child3 != undefined && data.child3 != null
? data.child3[0] != null
? `current_holders.orgChild3Id IN (:...child3)`
: `current_holders.orgChild3Id is null`
: "1=1",
{
child3: data.child3,
},
)
.andWhere(
data.child4 != undefined && data.child4 != null
? data.child4[0] != null
? `current_holders.orgChild4Id IN (:...child4)`
: `current_holders.orgChild4Id is null`
: "1=1",
{
child4: data.child4,
},
)
.andWhere(
new Brackets((qb) => {
2024-08-30 18:02:34 +07:00
qb.where(keyword != "" && keyword != null ? "ProfileEdit.topic LIKE :keyword" : "1=1", {
keyword: `%${keyword}%`,
2025-06-12 15:56:42 +07:00
})
.orWhere(
keyword != "" && keyword != null ? "ProfileEdit.detail LIKE :keyword" : "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != "" && keyword != null ? "ProfileEdit.remark LIKE :keyword" : "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != "" && keyword != null
? "CONCAT(profile.prefix, profile.firstName, ' ', profile.lastName) LIKE :keyword"
: "1=1",
{
keyword: `%${keyword}%`,
},
);
}),
)
2025-11-29 14:56:58 +07:00
.orderBy("ProfileEdit.createdAt", "DESC");
2025-09-23 11:54:17 +07:00
if (sortBy) {
2025-11-29 14:56:58 +07:00
if (sortBy == "fullname") {
query = query.orderBy(`profile.firstName`, descending ? "DESC" : "ASC");
} else {
query = query.orderBy(`ProfileEdit.${sortBy}`, descending ? "DESC" : "ASC");
2025-09-23 11:54:17 +07:00
}
}
const [getProfileEdit, total] = await query
2025-11-29 14:56:58 +07:00
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
2025-09-23 11:54:17 +07:00
2024-07-19 11:08:47 +07:00
const _data = getProfileEdit.map((item) => ({
id: item.id,
idcard: item.profile.citizenId,
2024-10-10 15:22:47 +07:00
profileId: item.profile.id,
2024-07-19 11:08:47 +07:00
topic: item.topic,
detail: item.detail,
status: item.status,
remark: item.remark,
createdAt: item.createdAt,
createdFullName: item.createdFullName,
lastUpdatedAt: item.lastUpdatedAt,
lastUpdateFullName: item.lastUpdateFullName,
fullname:
(item?.profile?.prefix ?? "") +
"" +
(item?.profile?.firstName ?? "") +
" " +
(item?.profile?.lastName ?? ""),
}));
return new HttpSuccess({ data: _data, total: total });
}
2024-09-27 13:56:02 +07:00
// @Get("{Id}")
// public async detailProfileByIdEdit(@Path() Id: string) {
// const getProfileEdit = await this.profileEditRepo.findOne({
// where: { id: Id },
// });
// if (!getProfileEdit) {
// throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
// }
// return new HttpSuccess(getProfileEdit);
// }
@Get("{id}")
public async detailProfileEdit(@Path() id: string) {
2024-07-19 11:08:47 +07:00
const getProfileEdit = await this.profileEditRepo.findOne({
where: { id: id },
2024-07-19 11:08:47 +07:00
relations: ["profile"],
});
if (!getProfileEdit) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
const _data = {
id: getProfileEdit.id,
topic: getProfileEdit.topic,
detail: getProfileEdit.detail,
2024-10-23 00:31:00 +07:00
citizenId: getProfileEdit?.profile?.citizenId ?? "",
2024-07-19 11:08:47 +07:00
status: getProfileEdit.status,
remark: getProfileEdit.remark,
createdAt: getProfileEdit.createdAt,
createdFullName: getProfileEdit.createdFullName,
lastUpdatedAt: getProfileEdit.lastUpdatedAt,
lastUpdateFullName: getProfileEdit.lastUpdateFullName,
fullname:
(getProfileEdit?.profile?.prefix ?? "") +
"" +
(getProfileEdit?.profile?.firstName ?? "") +
" " +
(getProfileEdit?.profile?.lastName ?? ""),
};
return new HttpSuccess(_data);
}
@Post()
public async newProfileEdit(@Request() req: RequestWithUser, @Body() body: CreateProfileEdit) {
2024-10-17 19:26:33 +07:00
const profile = await this.profileRepo.findOne({
relations: {
posLevel: true,
posType: true,
current_holders: true
},
where: {
keycloak: req.user.sub,
current_holders: {
orgRevision: {
orgRevisionIsCurrent: true,
orgRevisionIsDraft: false
}
}
}
2024-10-17 19:26:33 +07:00
});
2024-07-19 11:08:47 +07:00
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const orgRoot = await this.orgRootRepo.findOne({
select: {
isDeputy: true
},
where: {
id: profile.current_holders.find(x => x.orgRootId)!.orgRootId ?? ""
}
})
2024-07-19 11:08:47 +07:00
const data = new ProfileEdit();
const meta = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
2024-08-30 18:02:34 +07:00
createdAt: new Date(),
lastUpdatedAt: new Date(),
2024-07-19 11:08:47 +07:00
};
Object.assign(data, { ...body, ...meta });
data.status = "PENDING";
await this.profileEditRepo.save(data);
2024-10-17 19:26:33 +07:00
await new CallAPI()
.PostData(req, "/org/workflow/add-workflow", {
refId: data.id,
2024-10-22 11:59:12 +07:00
sysName: "REGISTRY_PROFILE",
2024-10-17 19:26:33 +07:00
posLevelName: profile.posLevel.posLevelName,
posTypeName: profile.posType.posTypeName,
2025-06-12 15:56:42 +07:00
fullName: `${profile.prefix}${profile.firstName} ${profile.lastName}`,
isDeputy: orgRoot?.isDeputy ?? false
2024-10-17 19:26:33 +07:00
})
.catch((error) => {
console.error("Error calling API:", error);
});
2024-07-19 11:08:47 +07:00
return new HttpSuccess(data.id);
}
@Patch("{editId}")
public async editProfileEdit(
@Body() requestBody: EditProfileEdit,
@Request() req: RequestWithUser,
@Path() editId: string,
) {
// const record = await this.profileEditRepo.findOneBy({ id: editId });
const record = await this.profileEditRepo.findOne({
2024-08-30 18:02:34 +07:00
where: { id: editId },
});
2024-07-19 11:08:47 +07:00
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
Object.assign(record, requestBody);
record.lastUpdateFullName = req.user.name;
record.lastUpdateUserId = req.user.sub;
record.lastUpdatedAt = new Date();
await Promise.all([this.profileEditRepo.save(record)]);
return new HttpSuccess();
}
@Delete("{editId}")
public async deleteProfileEdit(@Path() editId: string) {
const result = await this.profileEditRepo.delete({ id: editId });
if (result.affected == undefined || result.affected <= 0)
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
return new HttpSuccess();
}
}