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

218 lines
7.6 KiB
TypeScript
Raw Normal View History

import {
Body,
Controller,
Get,
Patch,
Path,
Post,
Request,
Route,
Security,
Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import { In } from "typeorm";
import {
ProfileAbsentLate,
CreateProfileAbsentLate,
CreateProfileAbsentLateBatch,
UpdateProfileAbsentLate,
} from "../entities/ProfileAbsentLate";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { RequestWithUser } from "../middlewares/user";
import { Profile } from "../entities/Profile";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile/absent-late")
@Tags("ProfileAbsentLate")
@Security("bearerAuth")
export class ProfileAbsentLateController extends Controller {
private profileRepo = AppDataSource.getRepository(Profile);
private absentLateRepo = AppDataSource.getRepository(ProfileAbsentLate);
/**
* API / user
* @summary API / user
*/
@Get("user")
public async getAbsentLateUser(@Request() request: { user: Record<string, any> }) {
const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const record = await this.absentLateRepo.find({
where: { profileId: profile.id, isDeleted: false },
order: { stampDate: "DESC" },
});
return new HttpSuccess(record);
}
/**
* API / profileId
* @summary API / profileId
* @param profileId profile
*/
@Get("{profileId}")
public async getAbsentLate(@Path() profileId: string, @Request() req: RequestWithUser) {
let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER");
if (_workflow == false)
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId);
const record = await this.absentLateRepo.find({
where: { profileId, isDeleted: false },
order: { stampDate: "DESC" },
});
return new HttpSuccess(record);
}
/**
* API /
* @summary API /
*/
@Post()
public async newAbsentLate(
@Request() req: RequestWithUser,
@Body() body: CreateProfileAbsentLate,
) {
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 before = null;
const data = new ProfileAbsentLate();
const meta = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
Object.assign(data, { ...body, ...meta });
await this.absentLateRepo.save(data, { data: req });
setLogDataDiff(req, { before, after: data });
return new HttpSuccess(data.id);
}
/**
* API / ( Job)
* @summary API / ( Job)
*/
@Post("batch")
public async newAbsentLateBatch(
@Request() req: RequestWithUser,
@Body() body: CreateProfileAbsentLateBatch,
) {
if (!body.records || body.records.length === 0) {
throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณาระบุข้อมูลอย่างน้อย 1 รายการ");
}
const profileIds = [...new Set(body.records.map((r) => r.profileId))];
const profiles = await this.profileRepo.findBy({
id: In(profileIds),
});
const foundProfileIds = new Set(profiles.map((p) => p.id));
const validRecords = body.records.filter((r) => foundProfileIds.has(r.profileId));
if (validRecords.length === 0) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ที่ระบุ");
}
const meta = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
createdAt: new Date(),
lastUpdatedAt: new Date(),
};
const records = validRecords.map((item) => {
const data = new ProfileAbsentLate();
Object.assign(data, { ...item, ...meta });
return data;
});
const result = await this.absentLateRepo.save(records, { data: req });
return new HttpSuccess({ count: result.length, ids: result.map((r) => r.id) });
}
/**
* API /
* @summary API /
* @param absentLateId /
*/
@Patch("{absentLateId}")
public async editAbsentLate(
@Request() req: RequestWithUser,
@Body() body: UpdateProfileAbsentLate,
@Path() absentLateId: string,
) {
const record = await this.absentLateRepo.findOneBy({ id: absentLateId });
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
await new permission().PermissionOrgUserUpdate(
req,
"SYS_REGISTRY_OFFICER",
record.profileId,
);
const before = structuredClone(record);
Object.assign(record, body);
record.lastUpdateUserId = req.user.sub;
record.lastUpdateFullName = req.user.name;
record.lastUpdatedAt = new Date();
await Promise.all([
this.absentLateRepo.save(record, { data: req }),
setLogDataDiff(req, { before, after: record }),
]);
return new HttpSuccess();
}
/**
* API / (Soft Delete)
* @summary API / (Soft Delete)
* @param absentLateId /
*/
@Patch("update-delete/{absentLateId}")
public async updateIsDeleted(
@Request() req: RequestWithUser,
@Path() absentLateId: string,
) {
const record = await this.absentLateRepo.findOneBy({ id: absentLateId });
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
if (record.isDeleted === true) {
return new HttpSuccess();
}
await new permission().PermissionOrgUserDelete(req, "SYS_REGISTRY_OFFICER", record.profileId);
const before = structuredClone(record);
record.isDeleted = true;
record.lastUpdateUserId = req.user.sub;
record.lastUpdateFullName = req.user.name;
record.lastUpdatedAt = new Date();
await Promise.all([
this.absentLateRepo.save(record, { data: req }),
setLogDataDiff(req, { before, after: record }),
]);
return new HttpSuccess();
}
}