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

2688 lines
95 KiB
TypeScript
Raw Normal View History

2024-09-11 17:29:33 +07:00
import {
Controller,
Post,
Put,
Delete,
Route,
Security,
Tags,
Body,
Path,
Request,
SuccessResponse,
Response,
Get,
Query,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatusCode from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { Command } from "../entities/Command";
2024-10-10 11:12:31 +07:00
import { Brackets, LessThan, MoreThan, Double, In, Not } from "typeorm";
2024-09-11 17:29:33 +07:00
import { CommandType } from "../entities/CommandType";
import { CommandSend } from "../entities/CommandSend";
2024-10-08 16:35:08 +07:00
import { Profile, CreateProfileAllFields } from "../entities/Profile";
import { RequestWithUser } from "../middlewares/user";
import { OrgRevision } from "../entities/OrgRevision";
2024-09-13 15:34:01 +07:00
import { CommandSendCC } from "../entities/CommandSendCC";
2024-09-25 11:17:38 +07:00
import { CommandSalary } from "../entities/CommandSalary";
import { CommandRecive } from "../entities/CommandRecive";
import HttpStatus from "../interfaces/http-status";
2024-09-26 16:05:59 +07:00
import Extension from "../interfaces/extension";
2024-10-01 17:51:48 +07:00
import { ProfileEmployee } from "../entities/ProfileEmployee";
import CallAPI from "../interfaces/call-api";
2024-10-08 16:35:08 +07:00
import { ProfileSalary, CreateProfileSalary } from "../entities/ProfileSalary";
2024-10-04 15:35:14 +07:00
import { ProfileSalaryHistory } from "../entities/ProfileSalaryHistory";
2024-10-08 16:35:08 +07:00
import {
calculateRetireDate,
calculateRetireLaw,
removeProfileInOrganize,
setLogDataDiff,
} from "../interfaces/utils";
2024-10-04 15:35:14 +07:00
import { Position } from "../entities/Position";
import { PosMaster } from "../entities/PosMaster";
import { EmployeePosition } from "../entities/EmployeePosition";
import { EmployeePosMaster } from "../entities/EmployeePosMaster";
import { ProfileDiscipline } from "../entities/ProfileDiscipline";
import { ProfileDisciplineHistory } from "../entities/ProfileDisciplineHistory";
2024-10-04 22:36:34 +07:00
import { PosMasterAct } from "../entities/PosMasterAct";
2024-10-08 16:35:08 +07:00
import { PosLevel } from "../entities/PosLevel";
import { PosType } from "../entities/PosType";
2024-10-10 11:12:31 +07:00
import { addUserRoles, createUser, getRoles } from "../keycloak";
2024-10-08 16:35:08 +07:00
import { ProfileEducation, CreateProfileEducation } from "../entities/ProfileEducation";
import { ProfileEducationHistory } from "../entities/ProfileEducationHistory";
2024-10-10 11:12:31 +07:00
import { CreateProfileCertificate, ProfileCertificate } from "../entities/ProfileCertificate";
2024-10-08 16:35:08 +07:00
import { ProfileCertificateHistory } from "../entities/ProfileCertificateHistory";
2024-10-10 11:12:31 +07:00
import permission from "../interfaces/permission";
2024-09-11 17:29:33 +07:00
@Route("api/v1/org/command")
@Tags("Command")
@Security("bearerAuth")
@Response(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
@SuccessResponse(HttpStatusCode.OK, "สำเร็จ")
export class CommandController extends Controller {
private commandRepository = AppDataSource.getRepository(Command);
private commandTypeRepository = AppDataSource.getRepository(CommandType);
private commandSendRepository = AppDataSource.getRepository(CommandSend);
2024-09-13 15:34:01 +07:00
private commandSendCCRepository = AppDataSource.getRepository(CommandSendCC);
2024-09-25 11:17:38 +07:00
private commandSalaryRepository = AppDataSource.getRepository(CommandSalary);
private commandReciveRepository = AppDataSource.getRepository(CommandRecive);
private profileRepository = AppDataSource.getRepository(Profile);
2024-10-01 17:51:48 +07:00
private profileEmployeeRepository = AppDataSource.getRepository(ProfileEmployee);
private orgRevisionRepo = AppDataSource.getRepository(OrgRevision);
2024-10-04 15:35:14 +07:00
private salaryRepo = AppDataSource.getRepository(ProfileSalary);
private salaryHistoryRepo = AppDataSource.getRepository(ProfileSalaryHistory);
private posMasterRepository = AppDataSource.getRepository(PosMaster);
private positionRepository = AppDataSource.getRepository(Position);
private employeePosMasterRepository = AppDataSource.getRepository(EmployeePosMaster);
private employeePositionRepository = AppDataSource.getRepository(EmployeePosition);
private disciplineRepository = AppDataSource.getRepository(ProfileDiscipline);
private disciplineHistoryRepository = AppDataSource.getRepository(ProfileDisciplineHistory);
2024-10-04 22:36:34 +07:00
private posMasterActRepository = AppDataSource.getRepository(PosMasterAct);
2024-10-08 16:35:08 +07:00
private posLevelRepo = AppDataSource.getRepository(PosLevel);
private posTypeRepo = AppDataSource.getRepository(PosType);
private profileEducationRepo = AppDataSource.getRepository(ProfileEducation);
private profileEducationHistoryRepo = AppDataSource.getRepository(ProfileEducationHistory);
private certificateRepo = AppDataSource.getRepository(ProfileCertificate);
private certificateHistoryRepo = AppDataSource.getRepository(ProfileCertificateHistory);
2024-09-11 17:29:33 +07:00
/**
* API list
*
* @summary API list
*
*/
@Get("list")
async GetResult(
2024-10-09 16:20:43 +07:00
@Request() request: RequestWithUser,
2024-09-11 17:29:33 +07:00
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10,
@Query() keyword: string = "",
@Query() commandTypeId?: string | null,
@Query() year?: number,
@Query() status?: string | null,
) {
2024-10-10 11:12:31 +07:00
let profilekArray: any = [];
let _profile = await this.profileRepository.findOne({
where: { keycloak: request.user.sub },
relations: ["current_holders", "current_holders.orgRevision"],
});
let isDirector =
_profile?.current_holders?.filter(
(x) =>
x.orgRevision?.orgRevisionIsCurrent == true && x.orgRevision?.orgRevisionIsDraft == false,
)[0]?.isDirector || false;
if (isDirector) {
let _data: any = {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
if (!request.user.role.includes("SUPER_ADMIN")) {
2024-10-10 11:15:33 +07:00
_data = await new permission().PermissionOrgList(request, "COMMAND");
2024-10-10 11:12:31 +07:00
}
const profiles = await this.profileRepository
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.current_holders", "current_holders")
.leftJoinAndSelect("current_holders.orgRoot", "orgRoot")
.leftJoinAndSelect("current_holders.orgChild1", "orgChild1")
.leftJoinAndSelect("current_holders.orgChild2", "orgChild2")
.leftJoinAndSelect("current_holders.orgChild3", "orgChild3")
.leftJoinAndSelect("current_holders.orgChild4", "orgChild4")
.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,
},
)
.select("profile.keycloak", "keycloak")
.getRawMany();
profilekArray = profiles.map((p) => p.keycloak);
}
2024-09-11 17:29:33 +07:00
const [commands, total] = await this.commandRepository
.createQueryBuilder("command")
2024-10-10 11:12:31 +07:00
.andWhere(
new Brackets((qb) => {
qb.orWhere(
profilekArray.length > 0
? "command.createdUserId IN (:...profilekArray)"
: "command.createdUserId='1'",
{
profilekArray: profilekArray,
},
).orWhere("command.createdUserId = :createdUserId", {
createdUserId: request.user.sub,
});
}),
)
2024-09-11 17:29:33 +07:00
.andWhere(
status != null && status != undefined && status != ""
2024-09-24 11:31:08 +07:00
? "command.status IN (:...status)"
2024-09-11 17:29:33 +07:00
: "1=1",
{
status:
status == null || status == undefined || status == ""
? null
2024-09-24 09:45:43 +07:00
: status.trim().toLocaleUpperCase() == "NEW" ||
status.trim().toLocaleUpperCase() == "DRAFT"
? ["NEW", "DRAFT"]
: [status.trim().toLocaleUpperCase()],
2024-09-11 17:29:33 +07:00
},
)
.andWhere(
year != null && year != undefined && year != 0
? "command.commandYear = :commandYear"
: "1=1",
{
commandYear: year == null || year == undefined || year == 0 ? null : `${year}`,
},
)
2024-09-11 17:29:33 +07:00
.andWhere(
commandTypeId != null && commandTypeId != undefined && commandTypeId != ""
? "command.commandTypeId = :commandTypeId"
: "1=1",
{
commandTypeId:
commandTypeId == null || commandTypeId == undefined || commandTypeId == ""
? null
: `${commandTypeId}`,
},
)
2024-10-08 10:09:56 +07:00
.andWhere(
new Brackets((qb) => {
qb.where(keyword != null && keyword != "" ? "command.commandNo LIKE :keyword" : "1=1", {
keyword: `%${keyword}%`,
2024-10-09 12:53:13 +07:00
}).orWhere(keyword != null && keyword != "" ? "command.issue LIKE :keyword" : "1=1", {
keyword: `%${keyword}%`,
});
2024-10-08 10:09:56 +07:00
}),
)
2024-09-26 19:46:09 +07:00
.orderBy("command.createdAt", "DESC")
2024-09-11 17:29:33 +07:00
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
const data = commands.map((_data) => ({
id: _data.id,
commandNo: _data.commandNo,
commandYear: _data.commandYear,
commandAffectDate: _data.commandAffectDate,
commandExcecuteDate: _data.commandExcecuteDate,
assignFullName: _data.createdFullName,
createdFullName: _data.createdFullName,
status: _data.status,
2024-09-25 16:17:06 +07:00
issue: _data.issue,
2024-09-11 17:29:33 +07:00
}));
return new HttpSuccess({ data, total });
}
/**
* API body
*
* @summary API body
*
*/
@Post()
async Post(
@Body()
requestBody: {
commandTypeId: string;
commandNo: string | null;
commandYear: number | null;
},
@Request() request: RequestWithUser,
2024-09-11 17:29:33 +07:00
) {
const command = Object.assign(new Command(), requestBody);
const commandType = await this.commandTypeRepository.findOne({
where: { id: requestBody.commandTypeId },
});
if (!commandType) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ");
}
command.detailHeader = commandType.detailHeader;
command.detailBody = commandType.detailBody;
command.detailFooter = commandType.detailFooter;
command.isAttachment = commandType.isAttachment;
2024-09-24 09:45:43 +07:00
command.status = "NEW";
command.issue = commandType.name;
2024-09-11 17:29:33 +07:00
command.createdUserId = request.user.sub;
command.createdFullName = request.user.name;
command.createdAt = new Date();
command.lastUpdateUserId = request.user.sub;
command.lastUpdateFullName = request.user.name;
command.lastUpdatedAt = new Date();
await this.commandRepository.save(command);
return new HttpSuccess(command.id);
}
/**
* API tab1
*
* @summary API tab1
*
* @param {string} id Id
*/
@Get("tab1/{id}")
async GetByIdTab1(@Path() id: string) {
const command = await this.commandRepository.findOne({
where: { id },
relations: ["commandType", "commandType.commandTypeSys"],
2024-09-11 17:29:33 +07:00
});
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
const _command = {
id: command.id,
status: command.status,
commandNo: command.commandNo,
commandYear: command.commandYear,
issue: command.issue,
detailHeader: command.detailHeader,
detailBody: command.detailBody,
detailFooter: command.detailFooter,
2024-09-25 21:05:16 +07:00
isBangkok: command.isBangkok,
isAttachment: command.isAttachment,
commandAffectDate: command.commandAffectDate,
commandExcecuteDate: command.commandExcecuteDate,
commandTypeName: command.commandType?.name || null,
commandSysId: command.commandType?.commandSysId || null,
};
return new HttpSuccess(_command);
2024-09-11 17:29:33 +07:00
}
/**
* API body Tab1
*
* @summary API body Tab1
*
* @param {string} id Id
*/
@Put("tab1/{id}")
async PutTab1(
@Path() id: string,
@Body()
requestBody: {
commandNo: string | null;
commandYear: number | null;
issue: string | null;
detailHeader: string | null;
detailBody: string | null;
detailFooter: string | null;
commandAffectDate: Date | null;
commandExcecuteDate: Date | null;
2024-10-09 12:53:13 +07:00
isBangkok: string | null;
2024-09-26 17:25:33 +07:00
isAttachment: boolean | null;
2024-09-11 17:29:33 +07:00
},
@Request() request: RequestWithUser,
2024-09-11 17:29:33 +07:00
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
const data = new Command();
Object.assign(data, { ...command, ...requestBody });
data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name;
data.lastUpdatedAt = new Date();
await this.commandRepository.save(data);
return new HttpSuccess();
}
2024-09-24 16:42:24 +07:00
/**
* API tab2
*
* @summary API tab2
*
* @param {string} id Id
*/
@Get("tab2/{id}")
async GetByIdTab2(@Path() id: string) {
const command = await this.commandRepository.findOne({
where: { id },
relations: ["commandSalary", "commandRecives"],
});
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
const _command = {
id: command.id,
commandSalaryId: command.commandSalaryId,
commandSalary: command.commandSalary?.name || null,
positionDetail: command.positionDetail,
2024-09-25 16:17:06 +07:00
commandRecives: command.commandRecives
2024-09-24 16:42:24 +07:00
.sort((a, b) => a.order - b.order)
.map((x) => ({
2024-09-25 16:17:06 +07:00
id: x.id,
2024-09-24 16:42:24 +07:00
citizenId: x.citizenId,
2024-10-02 14:08:40 +07:00
prefix: x.prefix,
firstName: x.firstName,
lastName: x.lastName,
// profileId: x.profileId,
2024-09-24 16:42:24 +07:00
order: x.order,
2024-09-25 16:17:06 +07:00
remarkVertical: x.remarkVertical,
remarkHorizontal: x.remarkHorizontal,
amount: x.amount,
positionSalaryAmount: x.positionSalaryAmount,
mouthSalaryAmount: x.mouthSalaryAmount,
2024-09-24 16:42:24 +07:00
})),
};
return new HttpSuccess(_command);
}
/**
* API body Tab2
*
* @summary API body Tab2
*
* @param {string} id Id
*/
@Put("tab2/{id}")
async PutTab2(
@Path() id: string,
@Body()
requestBody: {
2024-09-25 11:17:38 +07:00
positionDetail: string | null;
commandSalaryId: string | null;
2024-09-24 16:42:24 +07:00
},
@Request() request: RequestWithUser,
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
2024-09-25 11:17:38 +07:00
if (requestBody.commandSalaryId != undefined && requestBody.commandSalaryId != null) {
const commandSalary = await this.commandSalaryRepository.findOne({
where: { id: requestBody.commandSalaryId },
});
if (!commandSalary) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลต้นแบบ");
}
}
2024-09-24 16:42:24 +07:00
const data = new Command();
Object.assign(data, { ...command, ...requestBody });
data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name;
data.lastUpdatedAt = new Date();
await this.commandRepository.save(data);
return new HttpSuccess();
}
2024-09-25 21:05:16 +07:00
@Get("tab2/swap/{direction}/{commandReciveId}")
2024-09-25 11:17:38 +07:00
public async swapSalary(
@Path() direction: string,
commandReciveId: string,
@Request() req: RequestWithUser,
) {
const source_item = await this.commandReciveRepository.findOne({
where: { id: commandReciveId },
});
if (source_item == null) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const sourceOrder = source_item.order;
if (direction.trim().toUpperCase() == "UP") {
const dest_item = await this.commandReciveRepository.findOne({
where: { commandId: source_item.commandId, order: LessThan(sourceOrder) },
order: { order: "DESC" },
});
if (dest_item == null) return new HttpSuccess();
var destOrder = dest_item.order;
dest_item.order = sourceOrder;
source_item.order = destOrder;
await Promise.all([
this.commandReciveRepository.save(source_item),
this.commandReciveRepository.save(dest_item),
]);
} else {
const dest_item = await this.commandReciveRepository.findOne({
where: { commandId: source_item.commandId, order: MoreThan(sourceOrder) },
order: { order: "ASC" },
});
if (dest_item == null) return new HttpSuccess();
var destOrder = dest_item.order;
dest_item.order = sourceOrder;
source_item.order = destOrder;
await Promise.all([
this.commandReciveRepository.save(source_item),
this.commandReciveRepository.save(dest_item),
]);
}
return new HttpSuccess();
}
2024-09-25 16:17:06 +07:00
/**
* API body Tab2
*
* @summary API body Tab2
*
* @param {string} id Id
*/
@Put("tab2/recive/{commandReciveId}")
async PutTab2Recive(
@Path() commandReciveId: string,
@Body()
requestBody: {
remarkVertical: string | null;
remarkHorizontal: string | null;
amount: Double | null;
positionSalaryAmount: Double | null;
mouthSalaryAmount: Double | null;
},
@Request() request: RequestWithUser,
) {
const commandRecive = await this.commandReciveRepository.findOne({
where: { id: commandReciveId },
});
if (!commandRecive) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ได้รับคำสั่ง");
}
const data = new CommandRecive();
Object.assign(data, { ...commandRecive, ...requestBody });
data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name;
data.lastUpdatedAt = new Date();
await this.commandReciveRepository.save(data);
return new HttpSuccess();
}
2024-09-25 11:17:38 +07:00
/**
* API
*
* @summary API
*
* @param {string} id Id
*/
2024-09-25 16:17:06 +07:00
@Delete("tab2/{commandReciveId}")
2024-10-07 22:35:43 +07:00
async DeleteTab2(@Path() commandReciveId: string, @Request() request: RequestWithUser) {
2024-09-25 11:17:38 +07:00
const commandRecive = await this.commandReciveRepository.findOne({
2024-09-25 16:17:06 +07:00
where: { id: commandReciveId },
2024-10-07 22:35:43 +07:00
relations: ["command", "command.commandType"],
2024-09-25 11:17:38 +07:00
});
if (!commandRecive) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ได้รับคำสั่ง");
}
2024-10-07 22:35:43 +07:00
const path = this.commandTypePath(commandRecive.command.commandType.code);
if (path == null) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ");
await new CallAPI()
.PostData(request, path + "/delete", {
refIds: [commandRecive.refId],
})
.then(async (res) => {})
.catch(() => {});
2024-09-25 16:17:06 +07:00
const commandId = commandRecive.commandId;
2024-09-26 11:18:28 +07:00
await this.commandReciveRepository.delete(commandRecive.id);
2024-09-25 16:17:06 +07:00
const commandReciveList = await this.commandReciveRepository.find({
where: {
commandId: commandId,
},
order: { order: "ASC" },
});
commandReciveList.map(async (p, i) => {
p.order = i + 1;
await this.commandReciveRepository.save(p);
});
2024-10-07 22:35:43 +07:00
2024-09-25 11:17:38 +07:00
return new HttpSuccess();
}
/**
* API tab3
*
* @summary API tab3
*
* @param {string} id Id
*/
@Get("tab3/{id}")
async GetByIdTab3(@Path() id: string) {
const command = await this.commandRepository.findOne({
where: { id },
2024-09-13 15:34:01 +07:00
relations: ["commandSends", "commandSends.commandSendCCs"],
});
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
const _command = command.commandSends.map((item) => ({
id: item.id,
citizenId: item.citizenId,
prefix: item.prefix,
2024-09-25 21:05:16 +07:00
firstName: item.firstName,
lastName: item.lastName,
position: item.position,
org: item.org,
2024-09-13 15:34:01 +07:00
sendCC: item.commandSendCCs.map((x) => x.name),
profileId: item.profileId,
}));
return new HttpSuccess(_command);
}
/**
* API body Tab3
*
* @summary API body Tab3
*
* @param {string} id Id
*/
@Put("tab3-add/{id}")
async PutTab3Add(
@Path() id: string,
@Body()
requestBody: {
profileId: string[];
},
@Request() request: RequestWithUser,
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
let _null: any = null;
await Promise.all(
requestBody.profileId.map(async (item) => {
const commandSendCheck = await this.commandSendRepository.findOne({
where: { profileId: item, commandId: command.id },
});
if (commandSendCheck) return;
let profile = await this.profileRepository.findOne({
where: { id: item },
relations: ["current_holders", "current_holders.orgRoot"],
});
if (!profile) return;
const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true },
});
const commandSend = new CommandSend();
commandSend.citizenId = profile.citizenId;
commandSend.prefix =
profile.rank != null && profile.rank != "" ? profile.rank : profile.prefix;
2024-09-25 21:05:16 +07:00
commandSend.firstName = profile.firstName;
commandSend.lastName = profile.lastName;
commandSend.position = profile.position;
commandSend.org =
profile.current_holders?.find((x) => x.orgRevisionId == findRevision?.id)?.orgRoot
?.orgRootName || _null;
commandSend.profileId = profile.id;
commandSend.commandId = command.id;
commandSend.createdUserId = request.user.sub;
commandSend.createdFullName = request.user.name;
commandSend.createdAt = new Date();
commandSend.lastUpdateUserId = request.user.sub;
commandSend.lastUpdateFullName = request.user.name;
commandSend.lastUpdatedAt = new Date();
await this.commandSendRepository.save(commandSend);
}),
);
return new HttpSuccess();
}
/**
* API body Tab3
*
* @summary API body Tab3
*
* @param {string} id Id
*/
@Put("tab3/{id}")
async PutTab3Update(
@Path() id: string,
@Body()
requestBody: {
commandSend: {
id: string;
2024-09-13 15:34:01 +07:00
sendCC: string[];
}[];
},
@Request() request: RequestWithUser,
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
await Promise.all(
requestBody.commandSend.map(async (item) => {
2024-09-13 15:34:01 +07:00
const commandSendCC = await this.commandSendCCRepository.find({
where: { commandSendId: item.id },
});
2024-09-13 15:34:01 +07:00
await this.commandSendCCRepository.remove(commandSendCC);
2024-09-13 15:34:01 +07:00
await Promise.all(
item.sendCC.map(async (item1) => {
const _commandSendCC = new CommandSendCC();
_commandSendCC.name = item1;
_commandSendCC.commandSendId = item.id;
_commandSendCC.createdUserId = request.user.sub;
_commandSendCC.createdFullName = request.user.name;
_commandSendCC.createdAt = new Date();
_commandSendCC.lastUpdateUserId = request.user.sub;
_commandSendCC.lastUpdateFullName = request.user.name;
_commandSendCC.lastUpdatedAt = new Date();
await this.commandSendCCRepository.save(_commandSendCC);
}),
);
}),
);
return new HttpSuccess();
}
/**
* API body Tab3
*
* @summary API body Tab3
*
* @param {string} id Id
*/
@Delete("tab3/{commandSendId}")
async DeleteTab3Update(
@Path() commandSendId: string,
@Body()
requestBody: { reason?: string | null },
@Request() request: RequestWithUser,
) {
const command = await this.commandSendRepository.findOne({ where: { id: commandSendId } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้ได้รับสำเนาคำสั่ง");
}
2024-09-27 11:10:17 +07:00
await this.commandSendCCRepository.delete({ commandSendId: commandSendId });
await this.commandSendRepository.delete(commandSendId);
return new HttpSuccess();
}
2024-09-11 17:29:33 +07:00
/**
* API
*
* @summary API
*
* @param {string} id Id
*/
@Put("copy/{id}")
async PutCopy(
@Path() id: string,
@Body()
requestBody: { commandNo?: string | null; commandYear?: number | null },
@Request() request: RequestWithUser,
2024-09-11 17:29:33 +07:00
) {
2024-09-27 10:12:54 +07:00
const command = await this.commandRepository.findOne({
where: { id: id },
});
2024-09-11 17:29:33 +07:00
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
const copy = new Command();
Object.assign(copy, { ...command, ...requestBody, id: undefined });
2024-09-27 17:14:15 +07:00
const _null: any = null;
2024-09-27 10:12:54 +07:00
copy.status = "NEW";
2024-09-27 17:14:15 +07:00
copy.commandAffectDate = _null;
copy.commandExcecuteDate = _null;
copy.isSignature = _null;
copy.isDraft = _null;
copy.isSign = _null;
2024-09-11 17:29:33 +07:00
copy.createdUserId = request.user.sub;
copy.createdFullName = request.user.name;
copy.createdAt = new Date();
copy.lastUpdateUserId = request.user.sub;
copy.lastUpdateFullName = request.user.name;
copy.lastUpdatedAt = new Date();
await this.commandRepository.save(copy);
2024-09-27 10:12:54 +07:00
2024-09-11 17:29:33 +07:00
return new HttpSuccess(copy.id);
}
/**
* API
*
* @summary API
*
* @param {string} id Id
*/
@Put("cancel/{id}")
async PutCancel(
@Path() id: string,
@Body()
requestBody: { reason?: string | null },
@Request() request: RequestWithUser,
2024-09-11 17:29:33 +07:00
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
command.status = "CANCEL";
command.lastUpdateUserId = request.user.sub;
command.lastUpdateFullName = request.user.name;
command.lastUpdatedAt = new Date();
await this.commandRepository.save(command);
return new HttpSuccess();
}
/**
* API
*
* @summary API
*
* @param {string} id Id
*/
@Put("resume/{id}")
async PutDraft(
@Path() id: string,
@Body()
requestBody: { reason?: string | null },
@Request() request: RequestWithUser,
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
command.status = "DRAFT";
command.lastUpdateUserId = request.user.sub;
command.lastUpdateFullName = request.user.name;
command.lastUpdatedAt = new Date();
await this.commandRepository.save(command);
return new HttpSuccess();
}
2024-09-11 17:29:33 +07:00
/**
* API
*
* @summary API
*
* @param {string} id Id
*/
@Delete("{id}")
2024-10-07 22:35:43 +07:00
async Delete(@Path() id: string, @Request() request: RequestWithUser) {
2024-09-11 17:29:33 +07:00
const command = await this.commandRepository.findOne({
where: { id: id },
2024-10-07 22:35:43 +07:00
relations: ["commandType", "commandRecives"],
2024-09-11 17:29:33 +07:00
});
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
2024-09-26 19:46:09 +07:00
const commandSend = await this.commandSendRepository.find({
where: { commandId: id },
});
2024-10-07 22:35:43 +07:00
const path = this.commandTypePath(command.commandType.code);
if (path == null) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ");
await new CallAPI()
.PostData(request, path + "/delete", {
refIds: command.commandRecives.map((x) => x.refId),
})
.then(async (res) => {})
.catch(() => {});
2024-09-26 19:46:09 +07:00
await this.commandSendCCRepository.delete({ commandSendId: In(commandSend.map((x) => x.id)) });
2024-09-26 16:05:59 +07:00
await this.commandReciveRepository.delete({ commandId: command.id });
await this.commandSendRepository.delete({ commandId: command.id });
2024-09-11 17:29:33 +07:00
await this.commandRepository.delete(command.id);
return new HttpSuccess();
}
/**
* API tab0
*
* @summary API tab0
*
* @param {string} id Id
*/
@Get("tab0/{id}")
async GetByIdTab0(@Path() id: string) {
const command = await this.commandRepository.findOne({
where: { id },
});
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
const _command = {
id: command.id,
isSignature: command.isSignature,
status: command.status,
isDraft: command.isDraft,
isSign: command.isSign,
2024-09-24 16:42:24 +07:00
isAttachment: command.isAttachment,
};
return new HttpSuccess(_command);
}
/**
* API
*
* @summary API
*
* @param {string} id Id
*/
@Put("sign/{id}")
async PutSelectSign(
@Path() id: string,
@Body()
requestBody: { sign: boolean },
@Request() request: RequestWithUser,
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
command.isSignature = requestBody.sign;
command.status = "DRAFT";
command.lastUpdateUserId = request.user.sub;
command.lastUpdateFullName = request.user.name;
command.lastUpdatedAt = new Date();
await this.commandRepository.save(command);
return new HttpSuccess();
}
/**
* API
*
* @summary API
*
* @param {string} id Id
*/
@Put("draft/{id}")
async PutSelectDraft(
@Path() id: string,
@Body()
2024-09-24 16:42:24 +07:00
requestBody: { sign: boolean },
@Request() request: RequestWithUser,
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
2024-09-24 16:42:24 +07:00
command.isDraft = requestBody.sign;
command.status = "PENDING";
command.lastUpdateUserId = request.user.sub;
command.lastUpdateFullName = request.user.name;
command.lastUpdatedAt = new Date();
await this.commandRepository.save(command);
return new HttpSuccess();
}
/**
* API
*
* @summary API
*
* @param {string} id Id
*/
@Put("pending-check/{id}")
async PutSelectPending_Check(
@Path() id: string,
@Body()
requestBody: { sign?: boolean },
@Request() request: RequestWithUser,
) {
const command = await this.commandRepository.findOne({ where: { id: id } });
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
command.isSign = true;
command.lastUpdateUserId = request.user.sub;
command.lastUpdateFullName = request.user.name;
command.lastUpdatedAt = new Date();
await this.commandRepository.save(command);
return new HttpSuccess();
}
/**
2024-10-01 23:33:45 +07:00
* API
*
2024-10-01 23:33:45 +07:00
* @summary API
*
* @param {string} id Id
*/
@Put("pending/{id}")
async PutSelectPending(
@Path() id: string,
@Body()
requestBody: { sign?: boolean },
@Request() request: RequestWithUser,
) {
2024-10-01 23:33:45 +07:00
const command = await this.commandRepository.findOne({
where: { id: id },
relations: ["commandType", "commandRecives"],
});
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
command.isSign = true;
if (command.commandExcecuteDate == null)
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบวันที่คำสั่งมีผล");
2024-10-07 23:33:55 +07:00
let profiles = command.commandRecives
.filter((x) => x.profileId != null)
.map(async (x) => x.profileId);
2024-10-09 12:53:13 +07:00
await new CallAPI()
2024-10-07 23:33:55 +07:00
.PostData(request, "/placement/noti/profiles", {
subject: `${command.issue}`,
body: `${command.issue}`,
receiverUserId: profiles,
2024-10-09 12:53:13 +07:00
payload: "", //แนบไฟล์
2024-10-07 23:33:55 +07:00
isSendMail: true,
isSendInbox: true,
receiveDate: command.commandExcecuteDate,
})
.catch((error) => {
console.error("Error calling API:", error);
});
if (
new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()) <
new Date(
command.commandExcecuteDate.getFullYear(),
command.commandExcecuteDate.getMonth(),
command.commandExcecuteDate.getDate(),
)
) {
command.status = "WAITING";
} else {
2024-10-01 23:33:45 +07:00
const path = this.commandTypePath(command.commandType.code);
2024-10-01 17:51:48 +07:00
if (path == null) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ");
2024-10-03 11:54:55 +07:00
await new CallAPI()
.PostData(request, path + "/excecute", {
2024-10-01 23:33:45 +07:00
refIds: command.commandRecives
.filter((x) => x.refId != null)
.map((x) => ({
refId: x.refId,
commandAffectDate: command.commandAffectDate,
commandNo: command.commandNo,
commandYear: command.commandYear,
templateDoc: command.positionDetail,
2024-10-02 11:12:28 +07:00
amount: x.amount,
positionSalaryAmount: x.positionSalaryAmount,
mouthSalaryAmount: x.mouthSalaryAmount,
2024-10-01 23:33:45 +07:00
})),
2024-10-01 17:51:48 +07:00
})
2024-10-03 11:54:55 +07:00
.then(async (res) => {
2024-10-01 23:33:45 +07:00
command.status = "REPORTED";
2024-10-03 11:54:55 +07:00
})
.catch((e) => {});
}
command.lastUpdateUserId = request.user.sub;
command.lastUpdateFullName = request.user.name;
command.lastUpdatedAt = new Date();
await this.commandRepository.save(command);
return new HttpSuccess();
}
2024-09-26 16:05:59 +07:00
/**
* API tab4
*
* @summary API tab4
*
* @param {string} id Id
*/
@Get("tab4/cover/{id}")
2024-10-01 17:51:48 +07:00
async GetByIdTab4Cover(@Path() id: string, @Request() request: RequestWithUser) {
2024-09-26 16:05:59 +07:00
const command = await this.commandRepository.findOne({
where: { id },
relations: ["commandType"],
});
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
const _command = {
issue: "...................................",
commandNo: command.commandNo,
commandYear: command.commandYear,
commandTitle: command.issue,
detailHeader: command.detailHeader,
detailBody: command.detailBody,
detailFooter: command.detailFooter,
2024-09-26 17:37:20 +07:00
commandDate:
command.commandAffectDate == null
? ""
2024-09-26 17:37:20 +07:00
: Extension.ToThaiNumber(Extension.ToThaiFullDate2(command.commandAffectDate)),
commandExcecuteDate:
command.commandExcecuteDate == null
? ""
2024-09-26 17:37:20 +07:00
: Extension.ToThaiNumber(Extension.ToThaiFullDate2(command.commandExcecuteDate)),
2024-09-26 16:05:59 +07:00
name: "...................................",
position: "...................................",
};
return new HttpSuccess({
template: command.commandType.fileCover,
reportName: "docx-report",
2024-09-26 17:25:33 +07:00
data: _command,
2024-09-26 16:05:59 +07:00
});
}
/**
* API tab4
*
* @summary API tab4
*
* @param {string} id Id
*/
@Get("tab4/attachment/{id}")
2024-10-01 17:51:48 +07:00
async GetByIdTab4Attachment(@Path() id: string, @Request() request: RequestWithUser) {
2024-09-26 16:05:59 +07:00
const command = await this.commandRepository.findOne({
where: { id },
2024-10-01 17:51:48 +07:00
relations: ["commandType", "commandRecives"],
2024-09-26 16:05:59 +07:00
});
if (!command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้");
}
2024-10-01 17:51:48 +07:00
let _command: any = [];
2024-10-01 23:33:45 +07:00
const path = this.commandTypePath(command.commandType.code);
2024-10-01 17:51:48 +07:00
if (path == null) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ");
2024-10-03 11:54:55 +07:00
await new CallAPI()
.PostData(request, path + "/attachment", {
2024-10-07 22:35:43 +07:00
refIds: command.commandRecives
.filter((x) => x.refId != null)
.map((x) => ({
refId: x.refId,
Sequence: x.order,
CitizenId: x.citizenId,
Prefix: x.prefix,
FirstName: x.firstName,
LastName: x.lastName,
Amount: x.amount,
PositionSalaryAmount: x.positionSalaryAmount,
MouthSalaryAmount: x.mouthSalaryAmount,
RemarkHorizontal: x.remarkHorizontal,
RemarkVertical: x.remarkVertical,
CommandYear: command.commandYear,
})),
2024-10-01 17:51:48 +07:00
})
.then(async (res) => {
_command = res;
})
.catch(() => {});
2024-09-26 16:05:59 +07:00
return new HttpSuccess({
template: command.commandType.fileAttachment,
reportName: "xlsx-report",
2024-09-26 17:25:33 +07:00
data: _command,
2024-09-26 16:05:59 +07:00
});
}
2024-10-01 17:51:48 +07:00
/**
* API body
*
* @summary API body
*
*/
@Post("person")
async PostPerson(
@Body()
requestBody: {
2024-10-02 11:12:28 +07:00
commandTypeId?: string | null;
2024-10-01 17:51:48 +07:00
commandNo?: string | null;
commandYear?: number | null;
commandId?: string | null;
commandAffectDate?: Date | null;
commandExcecuteDate?: Date | null;
2024-10-01 17:51:48 +07:00
persons: {
refId: string;
2024-10-09 12:53:13 +07:00
profileId?: string | null;
2024-10-01 17:51:48 +07:00
citizenId: string;
2024-10-02 14:08:40 +07:00
prefix: string;
firstName: string;
lastName: string;
2024-10-01 17:51:48 +07:00
}[];
},
@Request() request: RequestWithUser,
) {
let command = new Command();
2024-10-01 23:33:45 +07:00
let commandCode = null;
2024-10-07 22:35:43 +07:00
let null_: any = null;
2024-10-01 17:51:48 +07:00
if (
requestBody.commandId != undefined &&
requestBody.commandId != null &&
requestBody.commandId != ""
) {
const _command = await this.commandRepository.findOne({
where: { id: requestBody.commandId },
2024-10-01 23:33:45 +07:00
relations: ["commandRecives", "commandType"],
2024-10-01 17:51:48 +07:00
order: {
commandRecives: {
order: "DESC",
},
},
});
if (!_command) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบคำสั่งนี้ในระบบ");
}
2024-10-01 23:33:45 +07:00
commandCode = _command.commandType.code;
2024-10-01 17:51:48 +07:00
command = _command;
} else {
command = Object.assign(new Command(), requestBody);
2024-10-02 11:12:28 +07:00
if (!requestBody.commandTypeId) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่ง");
}
2024-10-01 17:51:48 +07:00
const commandType = await this.commandTypeRepository.findOne({
where: { id: requestBody.commandTypeId },
});
if (!commandType) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ");
}
2024-10-01 23:33:45 +07:00
commandCode = commandType.code;
2024-10-01 17:51:48 +07:00
command.detailHeader = commandType.detailHeader;
command.detailBody = commandType.detailBody;
command.detailFooter = commandType.detailFooter;
command.isAttachment = commandType.isAttachment;
command.status = "NEW";
command.issue = commandType.name;
2024-10-07 22:35:43 +07:00
(command.commandAffectDate = requestBody.commandAffectDate
? new Date(requestBody.commandAffectDate)
2024-10-07 22:35:43 +07:00
: null_),
(command.commandExcecuteDate = requestBody.commandExcecuteDate
? new Date(requestBody.commandExcecuteDate)
: null_),
(command.createdUserId = request.user.sub);
2024-10-01 17:51:48 +07:00
command.createdFullName = request.user.name;
command.createdAt = new Date();
command.lastUpdateUserId = request.user.sub;
command.lastUpdateFullName = request.user.name;
command.lastUpdatedAt = new Date();
await this.commandRepository.save(command);
}
2024-10-01 23:33:45 +07:00
const path = this.commandTypePath(commandCode);
2024-10-01 17:51:48 +07:00
if (path == null) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ");
2024-10-03 11:54:55 +07:00
await new CallAPI()
2024-10-01 17:51:48 +07:00
.PostData(request, path, {
2024-10-07 22:35:43 +07:00
refIds: requestBody.persons.filter((x) => x.refId != null).map((x) => x.refId),
2024-10-01 17:51:48 +07:00
})
.then(async (res) => {
let order =
command.commandRecives == null || command.commandRecives.length <= 0
? 0
: command.commandRecives[0].order;
await Promise.all(
requestBody.persons.map(async (item) => {
const _commandRecive = await this.commandReciveRepository.findOne({
where: {
commandId: command.id,
refId: item.refId,
},
});
if (_commandRecive) return;
order = order + 1;
let commandRecive = new CommandRecive();
commandRecive = Object.assign(new CommandRecive(), item);
commandRecive.order = order;
commandRecive.commandId = command.id;
commandRecive.createdUserId = request.user.sub;
commandRecive.createdFullName = request.user.name;
commandRecive.createdAt = new Date();
commandRecive.lastUpdateUserId = request.user.sub;
commandRecive.lastUpdateFullName = request.user.name;
commandRecive.lastUpdatedAt = new Date();
await this.commandReciveRepository.save(commandRecive);
}),
);
})
.catch(() => {});
return new HttpSuccess(command.id);
}
2024-10-04 15:35:14 +07:00
@Post("excexute/salary-current")
public async newSalaryAndUpdateCurrent(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
amount?: Double | null;
positionSalaryAmount?: Double | null;
mouthSalaryAmount?: Double | null;
posNo: string | null;
position: string | null;
positionLine: string | null;
positionPathSide: string | null;
positionExecutive: string | null;
positionType: string | null;
positionLevel: string | null;
refCommandNo: string | null;
templateDoc: string | null;
posmasterId: string;
positionId: string;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileRepository.findOneBy({ id: item.profileId });
if (!profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัตินี้");
}
const dest_item = await this.salaryRepo.findOne({
where: { profileId: item.profileId },
order: { order: "DESC" },
});
const before = null;
const data = new ProfileSalary();
const meta = {
order: dest_item == null ? 1 : dest_item.order + 1,
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, { ...item, ...meta });
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history, { data: req });
const posMaster = await this.posMasterRepository.findOne({
where: { id: item.posmasterId },
});
if (posMaster == null)
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งนี้");
const posMasterOld = await this.posMasterRepository.findOne({
where: {
current_holderId: item.profileId,
orgRevisionId: posMaster.orgRevisionId,
},
});
if (posMasterOld != null) posMasterOld.current_holderId = null;
const positionOld = await this.positionRepository.findOne({
where: {
posMasterId: posMasterOld?.id,
positionIsSelected: true,
},
});
if (positionOld != null) {
positionOld.positionIsSelected = false;
await this.positionRepository.save(positionOld);
}
const checkPosition = await this.positionRepository.find({
where: {
posMasterId: item.posmasterId,
positionIsSelected: true,
},
});
if (checkPosition.length > 0) {
const clearPosition = checkPosition.map((positions) => ({
...positions,
positionIsSelected: false,
}));
await this.positionRepository.save(clearPosition);
}
posMaster.current_holderId = item.profileId;
if (posMasterOld != null) await this.posMasterRepository.save(posMasterOld);
await this.posMasterRepository.save(posMaster);
const positionNew = await this.positionRepository.findOne({
where: {
id: item.positionId,
posMasterId: item.posmasterId,
},
});
if (positionNew != null) {
positionNew.positionIsSelected = true;
profile.posLevelId = positionNew.posLevelId;
profile.posTypeId = positionNew.posTypeId;
profile.position = positionNew.positionName;
await this.profileRepository.save(profile);
await this.positionRepository.save(positionNew);
}
}),
);
return new HttpSuccess();
}
@Post("excexute/salary-employee-current")
public async newSalaryEmployeeAndUpdateCurrent(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
amount?: Double | null;
positionSalaryAmount?: Double | null;
mouthSalaryAmount?: Double | null;
posNo: string | null;
position: string | null;
positionType: string | null;
positionLevel: string | null;
refCommandNo: string | null;
templateDoc: string | null;
posmasterId: string;
positionId: string;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileEmployeeRepository.findOneBy({ id: item.profileId });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const dest_item = await this.salaryRepo.findOne({
where: { profileEmployeeId: item.profileId },
order: { order: "DESC" },
});
const before = null;
const data = new ProfileSalary();
const meta = {
order: dest_item == null ? 1 : dest_item.order + 1,
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
2024-10-04 22:36:34 +07:00
Object.assign(data, {
...item,
...meta,
profileEmployeeId: item.profileId,
profileId: undefined,
});
2024-10-04 15:35:14 +07:00
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history, { data: req });
const posMaster = await this.employeePosMasterRepository.findOne({
where: { id: item.posmasterId },
relations: ["orgRoot"],
});
if (posMaster == null)
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งนี้");
const posMasterOld = await this.employeePosMasterRepository.findOne({
where: {
current_holderId: item.profileId,
orgRevisionId: posMaster.orgRevisionId,
},
});
if (posMasterOld != null) posMasterOld.current_holderId = null;
if (posMasterOld != null) posMasterOld.next_holderId = null;
const positionOld = await this.employeePositionRepository.findOne({
where: {
posMasterId: posMasterOld?.id,
positionIsSelected: true,
},
});
if (positionOld != null) {
positionOld.positionIsSelected = false;
await this.employeePositionRepository.save(positionOld);
}
const checkPosition = await this.employeePositionRepository.find({
where: {
posMasterId: item.posmasterId,
positionIsSelected: true,
},
});
if (checkPosition.length > 0) {
const clearPosition = checkPosition.map((positions) => ({
...positions,
positionIsSelected: false,
}));
await this.employeePositionRepository.save(clearPosition);
}
posMaster.current_holderId = item.profileId;
posMaster.next_holderId = item.profileId;
if (posMasterOld != null) await this.employeePosMasterRepository.save(posMasterOld);
await this.employeePosMasterRepository.save(posMaster);
const positionNew = await this.employeePositionRepository.findOne({
where: {
id: item.positionId,
posMasterId: item.posmasterId,
},
});
if (positionNew != null) {
positionNew.positionIsSelected = true;
profile.posLevelId = positionNew.posLevelId;
profile.posTypeId = positionNew.posTypeId;
profile.position = positionNew.positionName;
profile.employeeOc = posMaster?.orgRoot?.orgRootName ?? null;
profile.positionEmployeePositionId = positionNew.positionName;
await this.profileEmployeeRepository.save(profile);
await this.employeePositionRepository.save(positionNew);
}
}),
);
return new HttpSuccess();
}
@Post("excexute/salary-leave")
public async newSalaryAndUpdateLeave(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
amount?: Double | null;
positionSalaryAmount?: Double | null;
mouthSalaryAmount?: Double | null;
posNo: string | null;
position: string | null;
positionLine: string | null;
positionPathSide: string | null;
positionExecutive: string | null;
positionType: string | null;
positionLevel: string | null;
refCommandNo: string | null;
templateDoc: string | null;
isLeave: boolean;
leaveReason?: string | null;
dateLeave?: Date | null;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileRepository.findOneBy({ id: item.profileId });
if (!profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัตินี้");
}
const dest_item = await this.salaryRepo.findOne({
where: { profileId: item.profileId },
order: { order: "DESC" },
});
const before = null;
const data = new ProfileSalary();
const meta = {
order: dest_item == null ? 1 : dest_item.order + 1,
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, { ...item, ...meta });
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history, { data: req });
const _null: any = null;
profile.isLeave = item.isLeave;
profile.leaveReason = item.leaveReason ?? _null;
profile.dateLeave = item.dateLeave ?? _null;
profile.lastUpdateUserId = req.user.sub;
profile.lastUpdateFullName = req.user.name;
profile.lastUpdatedAt = new Date();
if (item.isLeave == true) {
await removeProfileInOrganize(profile.id, "OFFICER");
}
await this.profileRepository.save(profile);
}),
);
return new HttpSuccess();
}
@Post("excexute/salary-employee-leave")
public async newSalaryEmployeeAndUpdateLeave(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
amount?: Double | null;
positionSalaryAmount?: Double | null;
mouthSalaryAmount?: Double | null;
posNo: string | null;
position: string | null;
positionType: string | null;
positionLevel: string | null;
refCommandNo: string | null;
templateDoc: string | null;
isLeave: boolean;
leaveReason?: string | null;
dateLeave?: Date | null;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileEmployeeRepository.findOneBy({ id: item.profileId });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const dest_item = await this.salaryRepo.findOne({
where: { profileEmployeeId: item.profileId },
order: { order: "DESC" },
});
const before = null;
const data = new ProfileSalary();
const meta = {
order: dest_item == null ? 1 : dest_item.order + 1,
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
2024-10-04 22:36:34 +07:00
Object.assign(data, {
...item,
...meta,
profileEmployeeId: item.profileId,
profileId: undefined,
});
2024-10-04 15:35:14 +07:00
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history, { data: req });
const _null: any = null;
profile.isLeave = item.isLeave;
profile.leaveReason = item.leaveReason ?? _null;
profile.dateLeave = item.dateLeave ?? _null;
profile.lastUpdateUserId = req.user.sub;
profile.lastUpdateFullName = req.user.name;
profile.lastUpdatedAt = new Date();
if (item.isLeave == true) {
await removeProfileInOrganize(profile.id, "EMPLOYEE");
}
await this.profileEmployeeRepository.save(profile);
}),
);
return new HttpSuccess();
}
@Post("excexute/salary")
public async newSalaryAndUpdate(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
amount?: Double | null;
positionSalaryAmount?: Double | null;
mouthSalaryAmount?: Double | null;
posNo: string | null;
position: string | null;
positionLine: string | null;
positionPathSide: string | null;
positionExecutive: string | null;
positionType: string | null;
positionLevel: string | null;
refCommandNo: string | null;
templateDoc: string | null;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileRepository.findOneBy({ id: item.profileId });
if (!profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัตินี้");
}
const dest_item = await this.salaryRepo.findOne({
where: { profileId: item.profileId },
order: { order: "DESC" },
});
const before = null;
const data = new ProfileSalary();
const meta = {
order: dest_item == null ? 1 : dest_item.order + 1,
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, { ...item, ...meta });
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history, { data: req });
}),
);
return new HttpSuccess();
}
@Post("excexute/salary-employee")
public async newSalaryEmployeeAndUpdate(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
amount?: Double | null;
positionSalaryAmount?: Double | null;
mouthSalaryAmount?: Double | null;
posNo: string | null;
position: string | null;
positionType: string | null;
positionLevel: string | null;
refCommandNo: string | null;
templateDoc: string | null;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileEmployeeRepository.findOneBy({ id: item.profileId });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const dest_item = await this.salaryRepo.findOne({
where: { profileEmployeeId: item.profileId },
order: { order: "DESC" },
});
const before = null;
const data = new ProfileSalary();
const meta = {
order: dest_item == null ? 1 : dest_item.order + 1,
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
2024-10-04 22:36:34 +07:00
Object.assign(data, {
...item,
...meta,
profileEmployeeId: item.profileId,
profileId: undefined,
});
2024-10-04 15:35:14 +07:00
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history, { data: req });
}),
);
return new HttpSuccess();
}
@Post("excexute/salary-leave-discipline")
public async newSalaryAndUpdateLeaveDiscipline(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
refCommandNo?: string | null;
salaryRef?: string | null;
isLeave: boolean | null;
leaveReason?: string | null;
dateLeave?: Date | null;
refCommandDate?: Date | null;
detail?: string | null;
level?: string | null;
unStigma?: string | null;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileRepository.findOne({
relations: ["profileSalary"],
where: { id: item.profileId },
order: {
profileSalary: {
order: "DESC",
},
},
});
if (!profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัตินี้");
}
// ประวัติตำแหน่ง
const data = new ProfileSalary();
const meta = {
profileId: item.profileId,
date: item.date,
refCommandNo: item.refCommandNo,
templateDoc: item.salaryRef,
position: profile.profileSalary.length > 0 ? profile.profileSalary[0].position : null,
positionType:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionType : null,
positionLevel:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionLevel : null,
posNo: profile.profileSalary.length > 0 ? profile.profileSalary[0].posNo : null,
positionLine:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionLine : null,
positionPathSide:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionPathSide : null,
positionExecutive:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionExecutive : null,
amount: profile.profileSalary.length > 0 ? profile.profileSalary[0].amount : null,
positionSalaryAmount:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionSalaryAmount : null,
mouthSalaryAmount:
profile.profileSalary.length > 0 ? profile.profileSalary[0].mouthSalaryAmount : null,
order:
profile.profileSalary.length >= 0
? profile.profileSalary.length > 0
? profile.profileSalary[0].order + 1
: 1
: null,
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, meta);
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data);
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history);
// ประวัติวินัย
const dataDis = new ProfileDiscipline();
const metaDis = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
Object.assign(dataDis, { ...body, ...metaDis });
const historyDis = new ProfileDisciplineHistory();
Object.assign(historyDis, { ...dataDis, id: undefined });
await this.disciplineRepository.save(dataDis);
historyDis.profileDisciplineId = dataDis.id;
await this.disciplineHistoryRepository.save(historyDis);
// ทะเบียนประวัติ
if (item.isLeave != null) {
const _null: any = null;
profile.isLeave = item.isLeave;
profile.leaveReason = item.leaveReason ?? _null;
profile.dateLeave = item.dateLeave ?? _null;
profile.lastUpdateUserId = req.user.sub;
profile.lastUpdateFullName = req.user.name;
profile.lastUpdatedAt = new Date();
if (item.isLeave == true) {
await removeProfileInOrganize(profile.id, "OFFICER");
}
await this.profileRepository.save(profile);
}
}),
);
return new HttpSuccess();
}
2024-10-04 22:36:34 +07:00
@Post("excexute/salary-probation")
public async newSalaryAndUpdateLeaveDisciplinefgh(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
refCommandNo?: string | null;
salaryRef?: string | null;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileRepository.findOne({
relations: ["profileSalary"],
where: { id: item.profileId },
order: {
profileSalary: {
order: "DESC",
},
},
});
if (!profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทะเบียนประวัตินี้");
}
// ประวัติตำแหน่ง
const data = new ProfileSalary();
const meta = {
profileId: item.profileId,
date: item.date,
refCommandNo: item.refCommandNo,
templateDoc: item.salaryRef,
position: profile.profileSalary.length > 0 ? profile.profileSalary[0].position : null,
positionType:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionType : null,
positionLevel:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionLevel : null,
posNo: profile.profileSalary.length > 0 ? profile.profileSalary[0].posNo : null,
positionLine:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionLine : null,
positionPathSide:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionPathSide : null,
positionExecutive:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionExecutive : null,
amount: profile.profileSalary.length > 0 ? profile.profileSalary[0].amount : null,
positionSalaryAmount:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionSalaryAmount : null,
mouthSalaryAmount:
profile.profileSalary.length > 0 ? profile.profileSalary[0].mouthSalaryAmount : null,
order:
profile.profileSalary.length >= 0
? profile.profileSalary.length > 0
? profile.profileSalary[0].order + 1
: 1
: null,
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, meta);
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data);
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history);
}),
);
return new HttpSuccess();
}
@Post("excexute/salary-probation-leave")
async ExecuteCommand12Async(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
profileId: string;
date?: Date | null;
refCommandNo?: string | null;
salaryRef?: string | null;
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const profile = await this.profileRepository.findOne({
relations: ["profileSalary"],
where: { id: item.profileId },
order: {
profileSalary: {
order: "DESC",
},
},
});
if (!profile) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
}
const _profile = await this.profileRepository.findOne({
where: { id: item.profileId },
});
if (!_profile) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์");
}
let dateLeave_: any = item.date;
await removeProfileInOrganize(profile.id, "OFFICER");
_profile.isLeave = true;
_profile.leaveReason =
"คำสั่งให้ข้าราชการออกจากราชการเพราะผลการทดลองปฏิบัติหน้าที่ราชการต่ำกว่ามาตรฐานที่กำหนด";
_profile.dateLeave = dateLeave_;
_profile.lastUpdateUserId = req.user.sub;
_profile.lastUpdateFullName = req.user.name;
_profile.lastUpdatedAt = new Date();
const profileSalary: ProfileSalary = Object.assign(new ProfileSalary(), {
profileId: item.profileId,
date: item.date,
refCommandNo: item.refCommandNo,
templateDoc: item.salaryRef,
position: profile.profileSalary.length > 0 ? profile.profileSalary[0].position : null,
positionType:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionType : null,
positionLevel:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionLevel : null,
posNo: profile.profileSalary.length > 0 ? profile.profileSalary[0].posNo : null,
positionLine:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionLine : null,
positionPathSide:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionPathSide : null,
positionExecutive:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionExecutive : null,
amount: profile.profileSalary.length > 0 ? profile.profileSalary[0].amount : null,
positionSalaryAmount:
profile.profileSalary.length > 0 ? profile.profileSalary[0].positionSalaryAmount : null,
mouthSalaryAmount:
profile.profileSalary.length > 0 ? profile.profileSalary[0].mouthSalaryAmount : null,
order:
profile.profileSalary.length >= 0
? profile.profileSalary.length > 0
? profile.profileSalary[0].order + 1
: 1
: null,
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
});
await Promise.all([
this.profileRepository.save(_profile),
this.salaryRepo.save(profileSalary),
]);
const history = new ProfileSalaryHistory();
Object.assign(history, { ...profileSalary, id: undefined });
history.profileSalaryId = profileSalary.id;
await this.salaryHistoryRepo.save(history);
}),
);
return new HttpSuccess();
}
2024-10-08 16:35:08 +07:00
@Post("excexute/create-officer-profile")
public async CreateOfficeProfileExcecute(
@Request() req: RequestWithUser,
@Body()
body: {
data: {
2024-10-09 12:53:13 +07:00
bodyProfile: CreateProfileAllFields;
2024-10-10 13:07:10 +07:00
bodyEducations?: CreateProfileEducation[];
bodyCertificates?: CreateProfileCertificate[];
bodySalarys?: CreateProfileSalary | null;
bodyPosition?: {
2024-10-08 16:35:08 +07:00
posmasterId: string;
positionId: string;
2024-10-10 13:07:10 +07:00
} | null;
2024-10-08 16:35:08 +07:00
}[];
},
) {
await Promise.all(
body.data.map(async (item) => {
const before = null;
const meta = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
2024-10-09 15:45:42 +07:00
const _null: any = null;
2024-10-08 16:35:08 +07:00
if (item.bodyProfile.posLevelId === "") item.bodyProfile.posLevelId = null;
if (item.bodyProfile.posTypeId === "") item.bodyProfile.posTypeId = null;
2024-10-10 11:12:31 +07:00
if (
item.bodyProfile.posLevelId &&
!(await this.posLevelRepo.findOneBy({ id: item.bodyProfile.posLevelId }))
) {
2024-10-08 16:35:08 +07:00
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
}
2024-10-10 11:12:31 +07:00
if (
item.bodyProfile.posTypeId &&
!(await this.posTypeRepo.findOneBy({ id: item.bodyProfile.posTypeId }))
) {
2024-10-08 16:35:08 +07:00
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
2024-10-10 11:12:31 +07:00
let profile: any = await this.profileRepository.findOneBy({
citizenId: item.bodyProfile.citizenId,
});
if (!profile) {
2024-10-09 15:45:42 +07:00
profile = Object.assign({ ...item.bodyProfile, ...meta });
2024-10-10 11:12:31 +07:00
profile.dateRetire =
item.bodyProfile.birthDate == null
? _null
: calculateRetireDate(item.bodyProfile.birthDate);
profile.dateRetireLaw =
item.bodyProfile.birthDate == null
? _null
: calculateRetireLaw(item.bodyProfile.birthDate);
2024-10-09 15:45:42 +07:00
const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, {
firstName: profile.firstName,
lastName: profile.lastName,
email: profile.email,
2024-10-08 16:35:08 +07:00
requiredActions: ["UPDATE_PASSWORD"],
});
if (typeof userKeycloakId !== "string") {
throw new Error(userKeycloakId.errorMessage);
}
const list = await getRoles();
2024-10-09 12:53:13 +07:00
if (!Array.isArray(list))
throw new Error("Failed. Cannot get role(s) data from the server.");
2024-10-08 16:35:08 +07:00
const result = await addUserRoles(
userKeycloakId,
list
.filter((v) => v.name === "USER")
.map((x) => ({
id: x.id,
name: x.name,
2024-10-09 12:53:13 +07:00
})),
2024-10-08 16:35:08 +07:00
);
if (!result) throw new Error("Failed. Cannot set user's role.");
2024-10-09 15:45:42 +07:00
profile.keycloak = userKeycloakId;
await this.profileRepository.save(profile);
setLogDataDiff(req, { before, after: profile });
}
if(profile && profile.id) {
2024-10-08 16:35:08 +07:00
//Educations
2024-10-10 13:07:10 +07:00
if(item.bodyEducations && item.bodyEducations.length > 0) {
await Promise.all(
item.bodyEducations.map(async (education) => {
const profileEdu = new ProfileEducation();
Object.assign(profileEdu, { ...education, ...meta });
const eduHistory = new ProfileEducationHistory();
Object.assign(eduHistory, { ...profileEdu, id: undefined });
profileEdu.profileId = profile.id;
await this.profileEducationRepo.save(profileEdu, { data: req });
setLogDataDiff(req, { before, after: profileEdu });
eduHistory.profileEducationId = profileEdu.id;
await this.profileEducationHistoryRepo.save(eduHistory, { data: req });
}),
);
}
2024-10-08 16:35:08 +07:00
//Certificates
2024-10-10 13:07:10 +07:00
if(item.bodyCertificates && item.bodyCertificates.length > 0) {
await Promise.all(
item.bodyCertificates.map(async (cer) => {
const profileCer = new ProfileCertificate();
Object.assign(profileCer, { ...cer, ...meta });
const cerHistory = new ProfileCertificateHistory();
Object.assign(cerHistory, { ...profileCer, id: undefined });
profileCer.profileId = profile.id;
2024-10-10 13:07:10 +07:00
await this.certificateRepo.save(profileCer, { data: req });
setLogDataDiff(req, { before, after: profileCer });
cerHistory.profileCertificateId = profileCer.id;
await this.certificateHistoryRepo.save(cerHistory, { data: req });
}),
);
2024-10-08 16:35:08 +07:00
}
2024-10-10 13:07:10 +07:00
//Salary
if(item.bodySalarys && item.bodySalarys != null) {
const dest_item = await this.salaryRepo.findOne({
where: { profileId: profile.id },
order: { order: "DESC" },
});
const profileSal = new ProfileSalary();
Object.assign(profileSal, { ...item.bodySalarys, ...meta });
const salaryHistory = new ProfileSalaryHistory();
Object.assign(salaryHistory, { ...profileSal, id: undefined });
2024-10-10 13:48:20 +07:00
profileSal.order = dest_item == null ? 1 : dest_item.order + 1
profileSal.profileId = profile.id;
2024-10-10 13:07:10 +07:00
await this.salaryRepo.save(profileSal, { data: req });
setLogDataDiff(req, { before, after: profileSal });
salaryHistory.profileSalaryId = profileSal.id;
await this.salaryHistoryRepo.save(salaryHistory, { data: req });
2024-10-08 16:35:08 +07:00
}
2024-10-10 13:07:10 +07:00
//Position
if(item.bodyPosition && item.bodyPosition != null) {
const posMaster = await this.posMasterRepository.findOne({
where: { id: item.bodyPosition.posmasterId },
});
if (posMaster == null)
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งนี้");
2024-10-09 12:53:13 +07:00
2024-10-10 13:07:10 +07:00
const posMasterOld = await this.posMasterRepository.findOne({
where: {
current_holderId: profile.id,
orgRevisionId: posMaster.orgRevisionId,
},
});
if (posMasterOld != null) posMasterOld.current_holderId = null;
2024-10-09 12:53:13 +07:00
2024-10-10 13:07:10 +07:00
const positionOld = await this.positionRepository.findOne({
where: {
posMasterId: posMasterOld?.id,
positionIsSelected: true,
},
});
if (positionOld != null) {
positionOld.positionIsSelected = false;
await this.positionRepository.save(positionOld);
}
2024-10-09 12:53:13 +07:00
2024-10-10 13:07:10 +07:00
const checkPosition = await this.positionRepository.find({
where: {
posMasterId: item.bodyPosition.posmasterId,
positionIsSelected: true,
},
});
if (checkPosition.length > 0) {
const clearPosition = checkPosition.map((positions) => ({
...positions,
positionIsSelected: false,
}));
await this.positionRepository.save(clearPosition);
}
2024-10-10 13:07:10 +07:00
posMaster.current_holderId = profile.id;
if (posMasterOld != null) await this.posMasterRepository.save(posMasterOld);
await this.posMasterRepository.save(posMaster);
2024-10-10 13:07:10 +07:00
const positionNew = await this.positionRepository.findOne({
where: {
id: item.bodyPosition.positionId,
posMasterId: item.bodyPosition.posmasterId,
},
});
if (positionNew != null) {
positionNew.positionIsSelected = true;
profile.posLevelId = positionNew.posLevelId;
profile.posTypeId = positionNew.posTypeId;
profile.position = positionNew.positionName;
await this.profileRepository.save(profile, { data: req });
setLogDataDiff(req, { before, after: profile });
await this.positionRepository.save(positionNew, { data: req });
}
2024-10-08 16:35:08 +07:00
}
}
2024-10-09 12:53:13 +07:00
}),
2024-10-08 16:35:08 +07:00
);
return new HttpSuccess();
}
2024-10-04 22:36:34 +07:00
@Post("command21/employee/report/excecute")
public async command21SalaryEmployeeExcecute(
@Request() req: RequestWithUser,
@Body()
body: {
refIds: {
refId: string;
commandAffectDate: Date | null;
commandNo: string | null;
commandYear: number;
templateDoc: string | null;
amount: Double | null;
positionSalaryAmount: Double | null;
mouthSalaryAmount: Double | null;
}[];
},
) {
await Promise.all(
body.refIds.map(async (item) => {
const profile = await this.profileEmployeeRepository.findOneBy({ id: item.refId });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const dest_item = await this.salaryRepo.findOne({
where: { profileEmployeeId: item.refId },
order: { order: "DESC" },
});
const before = null;
const data = new ProfileSalary();
const meta = {
profileEmployeeId: profile.id,
date: new Date(),
amount: item.amount,
positionSalaryAmount: item.positionSalaryAmount,
mouthSalaryAmount: item.mouthSalaryAmount,
posNo: profile.posMasterNoTemp,
position: profile.positionTemp,
positionType: profile.posTypeNameTemp,
positionLevel: profile.posLevelNameTemp,
refCommandNo: `${item.commandNo}/${Extension.ToThaiYear(item.commandYear)}`,
templateDoc: item.templateDoc,
order: dest_item == null ? 1 : dest_item.order + 1,
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, meta);
const history = new ProfileSalaryHistory();
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history, { data: req });
const posMaster = await this.employeePosMasterRepository.findOne({
where: { id: profile.posmasterIdTemp },
relations: ["orgRoot"],
});
if (posMaster == null)
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลตำแหน่งนี้");
const posMasterOld = await this.employeePosMasterRepository.findOne({
where: {
current_holderId: profile.id,
orgRevisionId: posMaster.orgRevisionId,
},
});
if (posMasterOld != null) posMasterOld.current_holderId = null;
if (posMasterOld != null) posMasterOld.next_holderId = null;
const positionOld = await this.employeePositionRepository.findOne({
where: {
posMasterId: posMasterOld?.id,
positionIsSelected: true,
},
});
if (positionOld != null) {
positionOld.positionIsSelected = false;
await this.employeePositionRepository.save(positionOld);
}
const checkPosition = await this.employeePositionRepository.find({
where: {
posMasterId: profile.posmasterIdTemp,
positionIsSelected: true,
},
});
if (checkPosition.length > 0) {
const clearPosition = checkPosition.map((positions) => ({
...positions,
positionIsSelected: false,
}));
await this.employeePositionRepository.save(clearPosition);
}
posMaster.current_holderId = profile.id;
posMaster.next_holderId = profile.id;
if (posMasterOld != null) await this.employeePosMasterRepository.save(posMasterOld);
await this.employeePosMasterRepository.save(posMaster);
const positionNew = await this.employeePositionRepository.findOne({
where: {
id: profile.positionIdTemp,
posMasterId: profile.posmasterIdTemp,
},
});
if (positionNew != null) {
positionNew.positionIsSelected = true;
profile.posLevelId = positionNew.posLevelId;
profile.posTypeId = positionNew.posTypeId;
profile.position = positionNew.positionName;
profile.employeeOc = posMaster?.orgRoot?.orgRootName ?? null;
profile.positionEmployeePositionId = positionNew.positionName;
profile.statusTemp = "DONE";
profile.employeeClass = "PERM";
const _null: any = null;
profile.employeeWage = item.amount == null ? _null : item.amount.toString();
await this.profileEmployeeRepository.save(profile);
await this.employeePositionRepository.save(positionNew);
}
}),
);
return new HttpSuccess();
}
@Post("command21/employee/report")
public async command21SalaryEmployee(
@Request() req: RequestWithUser,
@Body()
body: {
refIds: string[];
},
) {
return new HttpSuccess();
}
@Post("command40/officer/report/excecute")
public async command40SalaryOfficerExcecute(
@Request() req: RequestWithUser,
@Body()
body: {
refIds: {
refId: string;
commandAffectDate: Date | null;
commandNo: string | null;
commandYear: number;
templateDoc: string | null;
amount: Double | null;
positionSalaryAmount: Double | null;
mouthSalaryAmount: Double | null;
}[];
},
) {
return new HttpSuccess();
}
@Post("command40/officer/report")
public async command40SalaryOfficer(
@Request() req: RequestWithUser,
@Body()
body: {
refIds: string[];
},
) {
return new HttpSuccess();
}
@Post("command40/officer/report/attachment")
public async command40SalaryOfficerAttachment(
@Request() req: RequestWithUser,
@Body()
body: {
refIds: string[];
},
) {
let data: any = [];
await Promise.all(
body.refIds.map(async (item, i) => {
const posMasterAct = await this.posMasterActRepository.findOne({
relations: [
"posMaster",
"posMaster",
"posMaster.orgRoot",
"posMaster.orgChild1",
"posMaster.orgChild2",
"posMaster.orgChild3",
"posMaster.orgChild4",
"posMaster.current_holder",
"posMasterChild",
"posMasterChild.orgRoot",
"posMasterChild.orgChild1",
"posMasterChild.orgChild2",
"posMasterChild.orgChild3",
"posMasterChild.orgChild4",
"posMasterChild.current_holder",
"posMasterChild.current_holder.posLevel",
"posMasterChild.current_holder.posType",
],
where: {
id: item,
},
});
if (!posMasterAct) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
const organization = [
posMasterAct.posMasterChild?.current_holder?.position ?? null,
posMasterAct.posMasterChild?.orgChild4?.orgChild4Name ?? null,
posMasterAct.posMasterChild?.orgChild3?.orgChild3Name ?? null,
posMasterAct.posMasterChild?.orgChild2?.orgChild2Name ?? null,
posMasterAct.posMasterChild?.orgChild1?.orgChild1Name ?? null,
posMasterAct.posMasterChild?.orgRoot?.orgRootName ?? null,
];
const _organization = organization
.filter((part) => part !== undefined && part !== null)
.join("/");
const organizationNew = [
posMasterAct.posMaster?.current_holder?.position ?? null,
posMasterAct.posMaster?.orgChild4?.orgChild4Name ?? null,
posMasterAct.posMaster?.orgChild3?.orgChild3Name ?? null,
posMasterAct.posMaster?.orgChild2?.orgChild2Name ?? null,
posMasterAct.posMaster?.orgChild1?.orgChild1Name ?? null,
posMasterAct.posMaster?.orgRoot?.orgRootName ?? null,
];
const _organizationNew = organizationNew
.filter((part) => part !== undefined && part !== null)
.join("/");
var _data = {
no: Extension.ToThaiNumber((i + 1).toString()),
fullName:
posMasterAct.posMasterChild?.current_holder?.prefix ??
"" + posMasterAct.posMasterChild?.current_holder?.firstName ??
"" + " " + posMasterAct.posMasterChild?.current_holder?.lastName ??
null,
organization: _organization,
position: posMasterAct.posMasterChild?.current_holder?.position ?? null,
postype: posMasterAct.posMasterChild?.current_holder?.posType?.posTypeName ?? null,
poslevel: posMasterAct.posMasterChild?.current_holder?.posLevel?.posLevelName ?? null,
organizationNew: _organizationNew,
// date: Extension.ToThaiShortDate_noPrefix(new Date()),
dateStart: "",
dateEnd: "",
order:
posMasterAct.posMasterOrder == null
? "-"
: "ลำดับที่ " + Extension.ToThaiNumber(posMasterAct.posMasterOrder.toString()),
};
data.push(_data);
}),
);
return new HttpSuccess(data);
}
@Post("command38/officer/report/excecute")
public async command38SalaryOfficerExcecute(
@Request() req: RequestWithUser,
@Body()
body: {
refIds: {
refId: string;
commandAffectDate: Date | null;
commandNo: string | null;
commandYear: number;
templateDoc: string | null;
amount: Double | null;
positionSalaryAmount: Double | null;
mouthSalaryAmount: Double | null;
}[];
},
) {
return new HttpSuccess();
}
@Post("command38/officer/report")
public async command38SalaryOfficer(
@Request() req: RequestWithUser,
@Body()
body: {
refIds: string[];
},
) {
return new HttpSuccess();
}
2024-10-01 23:33:45 +07:00
commandTypePath(commandCode: string) {
switch (commandCode) {
2024-10-01 17:51:48 +07:00
case "C-PM-01":
2024-10-04 22:36:34 +07:00
return "/placement/recruit/report"; //
2024-10-01 17:51:48 +07:00
case "C-PM-02":
2024-10-04 22:36:34 +07:00
return "/placement/candidate/report"; //
2024-10-01 17:51:48 +07:00
case "C-PM-03":
2024-10-03 11:54:55 +07:00
return "/placement/appoint/report";
2024-10-01 17:51:48 +07:00
case "C-PM-04":
2024-10-03 11:54:55 +07:00
return "/placement/move/report";
2024-10-01 17:51:48 +07:00
case "C-PM-05":
2024-10-03 11:54:55 +07:00
return "/placement/appointment/appoint/report";
2024-10-01 17:51:48 +07:00
case "C-PM-06":
2024-10-03 11:54:55 +07:00
return "/placement/appointment/slip/report";
2024-10-01 17:51:48 +07:00
case "C-PM-07":
2024-10-03 11:54:55 +07:00
return "/placement/appointment/move/report";
2024-10-01 17:51:48 +07:00
case "C-PM-08":
2024-10-03 11:54:55 +07:00
return "/retirement/other/appoint/report";
2024-10-01 17:51:48 +07:00
case "C-PM-09":
2024-10-03 11:54:55 +07:00
return "/retirement/other/out/report";
2024-10-01 17:51:48 +07:00
case "C-PM-10":
2024-10-03 11:54:55 +07:00
return "/xxxxxx";
2024-10-01 17:51:48 +07:00
case "C-PM-11":
2024-10-04 22:36:34 +07:00
return "/probation/report/command11/officer/report";
2024-10-01 17:51:48 +07:00
case "C-PM-12":
2024-10-04 22:36:34 +07:00
return "/probation/report/command12/officer/report";
2024-10-01 17:51:48 +07:00
case "C-PM-13":
2024-10-03 11:54:55 +07:00
return "/placement/transfer/command/report";
2024-10-01 17:51:48 +07:00
case "C-PM-14":
2024-10-03 11:54:55 +07:00
return "/placement/Receive/command/report";
2024-10-01 17:51:48 +07:00
case "C-PM-15":
2024-10-03 11:54:55 +07:00
return "/placement/officer/command/report";
2024-10-01 17:51:48 +07:00
case "C-PM-16":
2024-10-03 11:54:55 +07:00
return "/placement/repatriation/command/report";
2024-10-01 17:51:48 +07:00
case "C-PM-17":
2024-10-03 11:54:55 +07:00
return "/retirement/resign/command/report";
2024-10-01 17:51:48 +07:00
case "C-PM-18":
2024-10-03 11:54:55 +07:00
return "/retirement/out/command/report";
2024-10-01 17:51:48 +07:00
case "C-PM-19":
2024-10-04 22:36:34 +07:00
return "/discipline/result/command19/report";
2024-10-01 17:51:48 +07:00
case "C-PM-20":
2024-10-04 22:36:34 +07:00
return "/discipline/result/command20/report";
2024-10-01 17:51:48 +07:00
case "C-PM-21":
2024-10-04 22:36:34 +07:00
return "/org/command/command21/employee/report";
2024-10-01 17:51:48 +07:00
case "C-PM-22":
2024-10-03 11:54:55 +07:00
return "/placement/appointment/employee-appoint/report";
2024-10-01 17:51:48 +07:00
case "C-PM-23":
2024-10-03 11:54:55 +07:00
return "/retirement/resign/employee/report";
2024-10-01 17:51:48 +07:00
case "C-PM-24":
2024-10-03 11:54:55 +07:00
return "/placement/appointment/employee-move/report";
2024-10-01 17:51:48 +07:00
case "C-PM-25":
2024-10-04 18:16:11 +07:00
return "/discipline/result/command25/report";
2024-10-01 17:51:48 +07:00
case "C-PM-26":
2024-10-04 18:16:11 +07:00
return "/discipline/result/command26/report";
2024-10-01 17:51:48 +07:00
case "C-PM-27":
2024-10-04 18:16:11 +07:00
return "/discipline/result/command27/report";
2024-10-01 17:51:48 +07:00
case "C-PM-28":
2024-10-04 18:16:11 +07:00
return "/discipline/result/command28/report";
2024-10-01 17:51:48 +07:00
case "C-PM-29":
2024-10-04 18:16:11 +07:00
return "/discipline/result/command29/report";
2024-10-01 17:51:48 +07:00
case "C-PM-30":
2024-10-04 18:16:11 +07:00
return "/discipline/result/command30/report";
2024-10-01 17:51:48 +07:00
case "C-PM-31":
2024-10-04 18:16:11 +07:00
return "/discipline/result/command31/report";
2024-10-01 17:51:48 +07:00
case "C-PM-32":
2024-10-04 18:16:11 +07:00
return "/discipline/result/command32/report";
2024-10-01 17:51:48 +07:00
case "C-PM-33":
2024-10-04 22:36:34 +07:00
return "/salary/report/command/officer/report";
2024-10-01 17:51:48 +07:00
case "C-PM-34":
2024-10-04 22:36:34 +07:00
return "/salary/report/command/officer/report";
2024-10-01 17:51:48 +07:00
case "C-PM-35":
2024-10-04 22:36:34 +07:00
return "/salary/report/command/officer/report";
2024-10-01 17:51:48 +07:00
case "C-PM-36":
2024-10-04 22:36:34 +07:00
return "/salary/report/command/employee/report";
2024-10-01 17:51:48 +07:00
case "C-PM-37":
2024-10-04 22:36:34 +07:00
return "/salary/report/command/employee/report";
2024-10-01 17:51:48 +07:00
case "C-PM-38":
2024-10-04 22:36:34 +07:00
return "/org/command/command38/officer/report";
2024-10-01 17:51:48 +07:00
case "C-PM-39":
2024-10-03 11:54:55 +07:00
return "/placement/slip/report";
2024-10-01 17:51:48 +07:00
case "C-PM-40":
2024-10-04 22:36:34 +07:00
return "/org/command/command40/officer/report";
2024-10-01 17:51:48 +07:00
case "C-PM-41":
2024-10-03 11:54:55 +07:00
return "/retirement/resign/leave-cancel/report";
2024-10-01 17:51:48 +07:00
default:
2024-10-01 23:33:45 +07:00
return null;
2024-10-01 17:51:48 +07:00
}
}
2024-09-11 17:29:33 +07:00
}