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

406 lines
14 KiB
TypeScript
Raw Normal View History

2024-02-23 15:15:11 +07:00
import {
Body,
2024-02-23 15:15:11 +07:00
Controller,
Delete,
Get,
Patch,
Path,
Post,
Request,
2024-02-23 15:15:11 +07:00
Route,
Security,
Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import { CreateProfileSalary, ProfileSalary, UpdateProfileSalary } from "../entities/ProfileSalary";
2024-02-23 15:15:11 +07:00
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
2024-02-23 15:15:11 +07:00
import HttpError from "../interfaces/http-error";
import { ProfileSalaryHistory } from "../entities/ProfileSalaryHistory";
import { RequestWithUser } from "../middlewares/user";
2024-02-23 15:15:11 +07:00
import { Profile } from "../entities/Profile";
2025-03-04 17:51:57 +07:00
import { In, LessThan, MoreThan } from "typeorm";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile/salary")
2024-02-23 15:15:11 +07:00
@Tags("ProfileSalary")
@Security("bearerAuth")
export class ProfileSalaryController extends Controller {
private profileRepo = AppDataSource.getRepository(Profile);
private salaryRepo = AppDataSource.getRepository(ProfileSalary);
private salaryHistoryRepo = AppDataSource.getRepository(ProfileSalaryHistory);
2024-05-23 16:44:37 +07:00
@Get("user")
public async getSalaryUser(@Request() request: { user: Record<string, any> }) {
const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
2025-02-24 16:21:33 +07:00
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const record = await this.salaryRepo.find({
2025-03-05 15:10:16 +07:00
where: { profileId: profile.id, commandCode: In(["5", "6", "7"]) },
2025-02-24 16:21:33 +07:00
order: { order: "ASC" },
});
return new HttpSuccess(record);
}
@Get("position/user")
public async getSalaryPositionUser(@Request() request: { user: Record<string, any> }) {
const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
2024-05-23 16:44:37 +07:00
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const record = await this.salaryRepo.find({
2025-03-05 15:10:16 +07:00
where: {
profileId: profile.id,
commandCode: In([
"0",
"9",
"1",
"2",
"3",
"4",
"8",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
]),
},
2024-05-23 16:44:37 +07:00
order: { order: "ASC" },
});
return new HttpSuccess(record);
}
@Get("{profileId}")
public async getSalary(@Path() profileId: string, @Request() req: RequestWithUser) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER");
2025-02-24 11:04:17 +07:00
if (_workflow == false)
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId);
const record = await this.salaryRepo.find({
2025-03-04 17:51:57 +07:00
where: { profileId: profileId, commandCode: In(["5", "6", "7"]) },
2025-02-24 11:04:17 +07:00
order: { order: "ASC" },
});
return new HttpSuccess(record);
}
@Get("position/{profileId}")
public async getPositionSalary(@Path() profileId: string, @Request() req: RequestWithUser) {
let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER");
2024-10-22 08:20:45 +07:00
if (_workflow == false)
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId);
const record = await this.salaryRepo.find({
2025-03-04 17:51:57 +07:00
where: {
profileId: profileId,
commandCode: In([
"0",
"9",
"1",
"2",
"3",
"4",
"8",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
]),
},
order: { order: "ASC" },
});
return new HttpSuccess(record);
}
@Get("tenure/{profileId}")
public async getPositionTenure(@Path() profileId: string, @Request() req: RequestWithUser) {
2025-02-28 14:50:26 +07:00
const sql_mode = await AppDataSource.query(
"SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));",
);
2025-02-28 11:45:04 +07:00
const position = await AppDataSource.query("CALL GetProfileSalaryPosition(?)", [profileId]);
const _position = position.length > 0 ? position[0] : [];
const mapPosition =
_position.length > 1
? _position.slice(1).map((curr: any, index: number) => ({
year: curr.Years ? Math.floor(Number(curr.Years)) : 0,
month: curr.Months ? Math.floor(Number(curr.Months)) : 0,
day: curr.Days ? Math.floor(Number(curr.Days)) : 0,
name: _position[index]?.positionName,
}))
: [];
const posLevel = await AppDataSource.query("CALL GetProfileSalaryLevel(?)", [profileId]);
const _posLevel = posLevel.length > 0 ? posLevel[0] : [];
const mapPosLevel =
_posLevel.length > 1
? _posLevel.slice(1).map((curr: any, index: number) => ({
year: curr.Years ? Math.floor(Number(curr.Years)) : 0,
month: curr.Months ? Math.floor(Number(curr.Months)) : 0,
day: curr.Days ? Math.floor(Number(curr.Days)) : 0,
name: _posLevel[index]?.positionLevel,
}))
: [];
2025-02-28 11:45:04 +07:00
const posExecutive = await AppDataSource.query("CALL GetProfileSalaryExecutive(?)", [
profileId,
]);
const _posExecutive = posExecutive.length > 0 ? posExecutive[0] : [];
const mapPosExecutive =
_posExecutive.length > 1
? _posExecutive.slice(1).map((curr: any, index: number) => ({
year: curr.Years ? Math.floor(Number(curr.Years)) : 0,
month: curr.Months ? Math.floor(Number(curr.Months)) : 0,
day: curr.Days ? Math.floor(Number(curr.Days)) : 0,
2025-03-04 09:31:05 +07:00
name: _posExecutive[index]?.positionExecutive,
2025-02-28 11:45:04 +07:00
}))
: [];
return new HttpSuccess({
position: mapPosition,
posLevel: mapPosLevel,
2025-02-28 11:45:04 +07:00
posExecutive: mapPosExecutive,
});
}
@Get("admin/{profileId}")
public async getSalaryAdmin(@Path() profileId: string, @Request() req: RequestWithUser) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, profileId, "SYS_SALARY_OFFICER");
if (_workflow == false) await new permission().PermissionGet(req, "SYS_SALARY_OFFICER");
const record = await this.salaryRepo.find({
where: { profileId: profileId },
order: { order: "ASC" },
});
return new HttpSuccess(record);
}
@Get("admin/history/{salaryId}")
public async salaryAdminHistory(@Path() salaryId: string, @Request() req: RequestWithUser) {
const _record = await this.salaryRepo.findOneBy({ id: salaryId });
if (_record) {
2024-10-22 08:20:45 +07:00
let _workflow = await new permission().Workflow(req, salaryId, "SYS_REGISTRY_OFFICER");
if (_workflow == false)
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", _record.profileId);
}
const record = await this.salaryHistoryRepo.find({
where: {
profileSalaryId: salaryId,
},
order: { createdAt: "DESC" },
});
return new HttpSuccess(record);
}
@Get("history/{salaryId}")
2024-09-25 16:17:06 +07:00
public async salaryHistory(@Path() salaryId: string) {
2024-08-30 18:02:34 +07:00
const record = await this.salaryHistoryRepo.find({
where: {
profileSalaryId: salaryId,
},
order: { createdAt: "DESC" },
});
return new HttpSuccess(record);
}
2024-02-23 15:15:11 +07:00
@Post()
public async newSalary(@Request() req: RequestWithUser, @Body() body: CreateProfileSalary) {
if (!body.profileId) {
throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
2024-02-23 15:15:11 +07:00
}
2024-08-30 18:02:34 +07:00
const profile = await this.profileRepo.findOneBy({ id: body.profileId });
2024-02-28 14:47:28 +07:00
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
2024-02-23 15:15:11 +07:00
}
await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profile.id);
2024-02-23 15:15:11 +07:00
const dest_item = await this.salaryRepo.findOne({
where: { profileId: body.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(),
};
2025-01-08 14:15:28 +07:00
const _null: any = null;
Object.assign(data, { ...body, ...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 });
2025-01-08 14:15:28 +07:00
profile.amount = body?.amount ?? _null;
profile.positionSalaryAmount = body?.positionSalaryAmount ?? _null;
profile.mouthSalaryAmount = body.mouthSalaryAmount ?? _null;
await this.profileRepo.save(profile, { data: req });
2025-01-08 14:15:28 +07:00
return new HttpSuccess();
}
@Post("update")
public async updateSalary(@Request() req: RequestWithUser, @Body() body: CreateProfileSalary) {
if (!body.profileId) {
throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
}
const profile = await this.profileRepo.findOneBy({ id: body.profileId });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profile.id);
const dest_item = await this.salaryRepo.findOne({
where: { profileId: body.profileId },
order: { order: "DESC" },
});
const before = null;
const data = new ProfileSalary();
const meta = {
2024-04-02 10:12:29 +07:00
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,
2024-08-30 18:02:34 +07:00
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
Object.assign(data, { ...body, ...meta });
const history = new ProfileSalaryHistory();
2024-08-13 20:01:53 +07:00
Object.assign(history, { ...data, id: undefined });
await this.salaryRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
2024-08-13 20:01:53 +07:00
history.profileSalaryId = data.id;
await this.salaryHistoryRepo.save(history, { data: req });
2025-01-08 14:15:28 +07:00
let null_: any = null;
2024-11-15 13:48:24 +07:00
profile.amount = body.amount ?? null_;
2024-12-06 18:53:56 +07:00
profile.amountSpecial = body.amountSpecial ?? null_;
2024-11-15 13:48:24 +07:00
profile.positionSalaryAmount = body.positionSalaryAmount ?? null_;
profile.mouthSalaryAmount = body.mouthSalaryAmount ?? null_;
await this.profileRepo.save(profile);
2024-02-23 15:15:11 +07:00
return new HttpSuccess();
}
@Patch("{salaryId}")
public async editSalary(
@Request() req: RequestWithUser,
@Body() body: UpdateProfileSalary,
@Path() salaryId: string,
2024-02-23 15:15:11 +07:00
) {
const record = await this.salaryRepo.findOneBy({ id: salaryId });
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", record.profileId);
const before = structuredClone(record);
const history = new ProfileSalaryHistory();
Object.assign(record, body);
2024-09-01 22:44:23 +07:00
Object.assign(history, { ...record, id: undefined });
history.profileSalaryId = salaryId;
record.lastUpdateUserId = req.user.sub;
record.lastUpdateFullName = req.user.name;
2024-08-30 18:02:34 +07:00
record.lastUpdatedAt = new Date();
history.lastUpdateUserId = req.user.sub;
history.lastUpdateFullName = req.user.name;
history.createdUserId = req.user.sub;
history.createdFullName = req.user.name;
2024-08-30 18:02:34 +07:00
history.createdAt = new Date();
history.lastUpdatedAt = new Date();
await Promise.all([
this.salaryRepo.save(record, { data: req }),
setLogDataDiff(req, { before, after: record }),
this.salaryHistoryRepo.save(history, { data: req }),
]);
2024-02-23 15:15:11 +07:00
2024-02-28 14:47:28 +07:00
return new HttpSuccess();
2024-02-23 15:15:11 +07:00
}
@Delete("{salaryId}")
public async deleteSalary(@Path() salaryId: string, @Request() req: RequestWithUser) {
const _record = await this.salaryRepo.findOneBy({ id: salaryId });
if (_record) {
2024-08-30 18:02:34 +07:00
await new permission().PermissionOrgUserDelete(
req,
"SYS_REGISTRY_OFFICER",
_record.profileId,
);
}
2024-09-25 16:17:06 +07:00
const data = await this.salaryRepo.findOneBy({ id: salaryId });
if (!data) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
if (data == null) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const profileId = data.profileId;
await this.salaryHistoryRepo.delete({
profileSalaryId: salaryId,
2024-02-23 15:15:11 +07:00
});
const result = await this.salaryRepo.delete({ id: salaryId });
2024-09-25 16:17:06 +07:00
const salaryList = await this.salaryRepo.find({
where: {
profileId: profileId,
},
});
salaryList.forEach(async (p, i) => {
p.order = i + 1;
await this.salaryRepo.save(p);
});
if (result.affected == undefined || result.affected <= 0) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
2024-02-23 15:15:11 +07:00
}
return new HttpSuccess();
}
@Get("swap/{direction}/{salaryId}")
2024-08-30 18:02:34 +07:00
public async swapSalary(
@Path() direction: string,
salaryId: string,
@Request() req: RequestWithUser,
) {
const source_item = await this.salaryRepo.findOne({ where: { id: salaryId } });
// if (source_item) {
2024-10-22 08:20:45 +07:00
//await new permission().PermissionOrgUserGet(req,"SYS_REGISTRY_OFFICER",source_item.profileId,); //ไม่แน่ใจOFFปิดไว้ก่อน
// }
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.salaryRepo.findOne({
where: { profileId: source_item.profileId, 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.salaryRepo.save(source_item), this.salaryRepo.save(dest_item)]);
} else {
const dest_item = await this.salaryRepo.findOne({
where: { profileId: source_item.profileId, 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.salaryRepo.save(source_item), this.salaryRepo.save(dest_item)]);
}
return new HttpSuccess();
}
2024-02-23 15:15:11 +07:00
}