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

501 lines
18 KiB
TypeScript
Raw Normal View History

2024-09-30 17:56:49 +07:00
import {
Body,
Controller,
Delete,
Get,
Patch,
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { RequestWithUser } from "../middlewares/user";
import { Profile } from "../entities/Profile";
import { CreateDevelopmentRequest, DevelopmentRequest } from "../entities/DevelopmentRequest";
import permission from "../interfaces/permission";
import { Brackets } from "typeorm";
import { DevelopmentProject } from "../entities/DevelopmentProject";
import { ProfileDevelopment } from "../entities/ProfileDevelopment";
import { ProfileDevelopmentHistory } from "../entities/ProfileDevelopmentHistory";
2024-10-04 18:12:23 +07:00
import { setLogDataDiff } from "../interfaces/utils";
2024-10-30 16:30:04 +07:00
import CallAPI from "../interfaces/call-api";
2025-06-12 15:56:42 +07:00
import { OrgRevision } from "../entities/OrgRevision";
2024-09-30 17:56:49 +07:00
@Route("api/v1/org/profile/development-request")
@Tags("DevelopmentRequest")
@Security("bearerAuth")
export class DevelopmentRequestController extends Controller {
private profileRepository = AppDataSource.getRepository(Profile);
private profileDevelopmentRepository = AppDataSource.getRepository(ProfileDevelopment);
private developmentRequestRepository = AppDataSource.getRepository(DevelopmentRequest);
private developmentProjectRepository = AppDataSource.getRepository(DevelopmentProject);
private developmentHistoryRepository = AppDataSource.getRepository(ProfileDevelopmentHistory);
2025-06-12 15:56:42 +07:00
private orgRevisionRepository = AppDataSource.getRepository(OrgRevision);
2024-09-30 17:56:49 +07:00
@Get("user")
public async getDevelopmentRequestUser(
@Request() req: RequestWithUser,
@Query("keyword") keyword: string = "",
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query("status") status?: string,
2025-09-03 11:20:23 +07:00
@Query("sortBy") sortBy?: string,
@Query("descending") descending?: boolean,
2024-09-30 17:56:49 +07:00
) {
const profile = await this.profileRepository.findOneBy({ keycloak: req.user.sub });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
2025-09-03 11:20:23 +07:00
let query = await AppDataSource.getRepository(DevelopmentRequest)
2024-09-30 17:56:49 +07:00
.createQueryBuilder("developmentRequest")
.andWhere(
status == undefined || status.trim().toUpperCase() == "ALL" || status == ""
? "1=1"
: "developmentRequest.status = :status",
{
status: status == undefined || status == null ? "" : status.trim().toUpperCase(),
},
)
.andWhere("developmentRequest.profileId = :profileId", { profileId: profile.id })
.andWhere(
new Brackets((qb) => {
qb.where(
keyword != null && keyword != "" ? "developmentRequest.reason LIKE :keyword" : "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != null && keyword != "" ? "developmentRequest.name LIKE :keyword" : "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != null && keyword != ""
? "developmentRequest.developmentTarget LIKE :keyword"
: "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != null && keyword != ""
? "developmentRequest.developmentResults LIKE :keyword"
: "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != null && keyword != ""
? "developmentRequest.developmentReport LIKE :keyword"
: "1=1",
{
keyword: `%${keyword}%`,
},
);
}),
)
.orderBy("developmentRequest.createdAt", "DESC")
2025-09-03 11:20:23 +07:00
if (sortBy) {
query = query.orderBy(
`developmentRequest.${sortBy}`,
descending ? "DESC" : "ASC"
);
}
const [lists, total] = await query
2024-09-30 17:56:49 +07:00
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
return new HttpSuccess({ data: lists, total });
}
@Get("admin")
public async getDevelopmentRequestAdmin(
2025-06-12 15:56:42 +07:00
@Request() request: RequestWithUser,
2024-09-30 17:56:49 +07:00
@Query("status") status: string,
@Query("keyword") keyword: string = "",
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
2025-09-23 11:54:17 +07:00
@Query("sortBy") sortBy?: string,
@Query("descending") descending?: boolean,
2024-09-30 17:56:49 +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(DevelopmentRequest)
2024-09-30 17:56:49 +07:00
.createQueryBuilder("developmentRequest")
2025-06-12 15:56:42 +07:00
.leftJoinAndSelect("developmentRequest.profile", "profile")
.leftJoinAndSelect("profile.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.orgRevision", "orgRevision")
2024-09-30 17:56:49 +07:00
.andWhere(
status == undefined || status.trim().toUpperCase() == "ALL" || status == ""
? "1=1"
: "developmentRequest.status = :status",
{
status: status == undefined || status == null ? "" : status.trim().toUpperCase(),
},
)
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)`
: `current_holders.orgChild1Id is null`
: "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,
},
)
2024-09-30 17:56:49 +07:00
.andWhere(
new Brackets((qb) => {
qb.where(
keyword != null && keyword != "" ? "developmentRequest.reason LIKE :keyword" : "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != null && keyword != "" ? "developmentRequest.name LIKE :keyword" : "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != null && keyword != ""
? "developmentRequest.developmentTarget LIKE :keyword"
: "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != null && keyword != ""
? "developmentRequest.developmentResults LIKE :keyword"
: "1=1",
{
keyword: `%${keyword}%`,
},
)
.orWhere(
keyword != null && keyword != ""
? "developmentRequest.developmentReport LIKE :keyword"
: "1=1",
{
keyword: `%${keyword}%`,
},
2025-06-12 15:56:42 +07:00
)
.orWhere(
2024-11-29 14:47:50 +07:00
keyword != null && keyword != ""
? "developmentRequest.createdFullName LIKE :keyword"
: "1=1",
{
keyword: `%${keyword}%`,
},
2024-09-30 17:56:49 +07:00
);
}),
)
2024-12-02 13:08:16 +07:00
.orderBy("developmentRequest.createdAt", "DESC")
2025-09-23 11:54:17 +07:00
if (sortBy) {
query = query.orderBy(
`developmentRequest.${sortBy}`,
descending ? "DESC" : "ASC"
);
}
const [lists, total] = await query
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
2025-06-12 15:56:42 +07:00
const _data = lists.map((item) => ({ ...item, profile: null }));
return new HttpSuccess({ data: _data, total });
2024-09-30 17:56:49 +07:00
}
@Get("admin/{id}")
public async getDevelopmentRequestByUser(@Path() id: string, @Request() req: RequestWithUser) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, id, "SYS_REGISTRY_OFFICER");
if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_OFFICER");
2024-09-30 17:56:49 +07:00
const data = await this.developmentRequestRepository.findOne({
where: { id: id },
relations: ["developmentProjects"],
});
if (!data) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const _data = {
...data,
developmentProjects: data.developmentProjects.map((x) => x.name),
};
return new HttpSuccess(_data);
}
@Get("user/{id}")
public async getDevelopmentRequestByAdmin(@Path() id: string, @Request() req: RequestWithUser) {
const data = await this.developmentRequestRepository.findOne({
where: { id: id },
relations: ["developmentProjects"],
});
if (!data) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const _data = {
...data,
developmentProjects: data.developmentProjects.map((x) => x.name),
};
return new HttpSuccess(_data);
}
@Post()
public async newDevelopmentRequest(
@Request() req: RequestWithUser,
@Body() body: CreateDevelopmentRequest,
) {
2024-10-30 16:30:04 +07:00
const profile = await this.profileRepository.findOne({
where: { keycloak: req.user.sub },
relations: ["posLevel", "posType"],
});
2024-09-30 17:56:49 +07:00
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
2024-10-04 18:12:23 +07:00
const before = null;
2024-09-30 17:56:49 +07:00
const data = new DevelopmentRequest();
const meta = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
Object.assign(data, { ...body, ...meta });
data.profileId = profile.id;
data.status = "PENDING";
2024-10-04 18:12:23 +07:00
await this.developmentRequestRepository.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
2024-09-30 17:56:49 +07:00
if (body.developmentProjects != null) {
await Promise.all(
body.developmentProjects.map(async (x) => {
let developmentProject = new DevelopmentProject();
developmentProject.name = x;
developmentProject.createdUserId = req.user.sub;
developmentProject.createdFullName = req.user.name;
developmentProject.lastUpdateUserId = req.user.sub;
developmentProject.lastUpdateFullName = req.user.name;
developmentProject.createdAt = new Date();
developmentProject.lastUpdatedAt = new Date();
developmentProject.developmentRequestId = data.id;
2024-10-04 18:12:23 +07:00
await this.developmentProjectRepository.save(developmentProject, { data: req });
setLogDataDiff(req, { before, after: developmentProject });
2024-09-30 17:56:49 +07:00
}),
);
}
2024-10-30 16:30:04 +07:00
await new CallAPI()
.PostData(req, "/org/workflow/add-workflow", {
refId: data.id,
sysName: "REGISTRY_IDP",
posLevelName: profile.posLevel.posLevelName,
posTypeName: profile.posType.posTypeName,
2025-06-12 15:56:42 +07:00
fullName: `${profile.prefix}${profile.firstName} ${profile.lastName}`,
2024-10-30 16:30:04 +07:00
})
.catch((error) => {
console.error("Error calling API:", error);
});
2024-09-30 17:56:49 +07:00
return new HttpSuccess(data.id);
}
@Patch("user/{developmentId}")
public async editUserDevelopmentRequest(
@Request() req: RequestWithUser,
@Body() body: CreateDevelopmentRequest,
@Path() developmentId: string,
) {
const record = await this.developmentRequestRepository.findOne({
where: { id: developmentId },
relations: ["developmentProjects"],
});
2024-10-04 18:12:23 +07:00
const before = structuredClone(record);
2024-09-30 17:56:49 +07:00
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
Object.assign(record, body);
record.lastUpdateUserId = req.user.sub;
record.lastUpdateFullName = req.user.name;
record.lastUpdatedAt = new Date();
2024-10-07 14:53:27 +07:00
await this.developmentRequestRepository.save(record, { data: req });
2024-10-04 18:12:23 +07:00
setLogDataDiff(req, { before, after: record });
2024-09-30 17:56:49 +07:00
await this.developmentProjectRepository.delete({ developmentRequestId: record.id });
if (body.developmentProjects != null) {
await Promise.all(
body.developmentProjects.map(async (x) => {
let developmentProject = new DevelopmentProject();
developmentProject.name = x;
developmentProject.createdUserId = req.user.sub;
developmentProject.createdFullName = req.user.name;
developmentProject.lastUpdateUserId = req.user.sub;
developmentProject.lastUpdateFullName = req.user.name;
developmentProject.createdAt = new Date();
developmentProject.lastUpdatedAt = new Date();
developmentProject.developmentRequestId = record.id;
2024-10-04 18:12:23 +07:00
await this.developmentProjectRepository.save(developmentProject, { data: req });
setLogDataDiff(req, { before: null, after: record });
2024-09-30 17:56:49 +07:00
}),
);
}
return new HttpSuccess(record.id);
}
@Patch("admin/{developmentId}")
public async editAdminDevelopmentRequest(
@Request() req: RequestWithUser,
@Body()
requestBody: { reason?: string | null; status: string },
@Path() developmentId: string,
) {
const record = await this.developmentRequestRepository.findOne({
where: { id: developmentId },
relations: ["developmentProjects"],
});
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
await new permission().PermissionUpdate(req, "SYS_REGISTRY_OFFICER");
2024-10-22 08:20:45 +07:00
2024-10-10 17:58:34 +07:00
if (requestBody.status == "APPROVE" && record.status == "PENDING") {
2024-09-30 17:56:49 +07:00
let profileDevelopment = new ProfileDevelopment();
const meta = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
Object.assign(profileDevelopment, {
...record,
...meta,
id: undefined,
type: "REQUEST",
2024-10-01 00:56:57 +07:00
kpiDevelopmentId: record.id,
2024-10-04 10:16:39 +07:00
developmentProjects: [],
2024-09-30 17:56:49 +07:00
});
2024-10-04 18:12:23 +07:00
await this.profileDevelopmentRepository.save(profileDevelopment, { data: req });
2024-09-30 17:56:49 +07:00
const history = new ProfileDevelopmentHistory();
Object.assign(history, {
...profileDevelopment,
id: undefined,
type: "REQUEST",
2024-10-01 00:56:57 +07:00
kpiDevelopmentId: record.id,
2024-10-04 10:16:39 +07:00
developmentProjects: [],
2024-09-30 17:56:49 +07:00
});
history.profileDevelopmentId = profileDevelopment.id;
2024-10-04 18:12:23 +07:00
await this.developmentHistoryRepository.save(history, { data: req });
2024-09-30 17:56:49 +07:00
if (record.developmentProjects != null) {
await Promise.all(
record.developmentProjects.map(async (x) => {
let developmentProject = new DevelopmentProject();
let developmentProjectHistory = new DevelopmentProject();
Object.assign(developmentProject, {
...meta,
id: undefined,
name: record.name,
profileDevelopmentId: profileDevelopment.id,
});
Object.assign(developmentProject, {
...meta,
id: undefined,
name: record.name,
profileDevelopmentHistoryId: history.id,
});
await Promise.all([
2024-10-04 18:12:23 +07:00
this.developmentProjectRepository.save(developmentProject, { data: req }),
setLogDataDiff(req, { before: null, after: developmentProject }),
this.developmentProjectRepository.save(developmentProjectHistory, { data: req }),
2024-09-30 17:56:49 +07:00
]);
}),
);
}
}
2024-10-10 17:58:34 +07:00
const before = structuredClone(record);
requestBody.status = requestBody.status.trim().toUpperCase();
Object.assign(record, requestBody);
2024-09-30 17:56:49 +07:00
2024-10-10 17:58:34 +07:00
record.lastUpdateUserId = req.user.sub;
record.lastUpdateFullName = req.user.name;
record.lastUpdatedAt = new Date();
await this.developmentRequestRepository.save(record, { data: req });
setLogDataDiff(req, { before, after: record });
2024-09-30 17:56:49 +07:00
return new HttpSuccess(record.id);
}
@Delete("{id}")
public async deleteDevelopmentRequest(@Path() id: string, @Request() req: RequestWithUser) {
const developmentRequest = await this.developmentRequestRepository.findOne({
where: { id },
});
if (!developmentRequest) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลคำขอนี้");
}
await this.developmentProjectRepository.delete({ developmentRequestId: id });
await this.developmentRequestRepository.delete({ id });
return new HttpSuccess();
}
}