refactor!: merge information into profile endpoint

This commit is contained in:
Methapon2001 2024-03-21 10:15:00 +07:00
parent 122e00d065
commit 8a1400d840
2 changed files with 102 additions and 397 deletions

View file

@ -16,31 +16,32 @@ import {
} from "tsoa"; } from "tsoa";
import { AppDataSource } from "../database/data-source"; import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success"; import HttpSuccess from "../interfaces/http-success";
import HttpStatusCode from "../interfaces/http-status"; import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error"; import HttpError from "../interfaces/http-error";
import { Profile, CreateProfile, UpdateProfile } from "../entities/Profile"; import { Profile, CreateProfile, UpdateProfile, ProfileHistory } from "../entities/Profile";
import { Brackets, In, IsNull, Like, Not } from "typeorm"; import { Brackets, IsNull, Like, Not } from "typeorm";
import { OrgRevision } from "../entities/OrgRevision"; import { OrgRevision } from "../entities/OrgRevision";
import { PosMaster } from "../entities/PosMaster"; import { PosMaster } from "../entities/PosMaster";
import { PosLevel } from "../entities/PosLevel"; import { PosLevel } from "../entities/PosLevel";
import { PosType } from "../entities/PosType"; import { PosType } from "../entities/PosType";
import { request } from "http";
import { calculateRetireDate } from "../interfaces/utils"; import { calculateRetireDate } from "../interfaces/utils";
import { RequestWithUser } from "../middlewares/user";
@Route("api/v1/org/profile") @Route("api/v1/org/profile")
@Tags("Profile") @Tags("Profile")
@Security("bearerAuth") @Security("bearerAuth")
@Response( @Response(
HttpStatusCode.INTERNAL_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง", "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
) )
@SuccessResponse(HttpStatusCode.OK, "สำเร็จ") @SuccessResponse(HttpStatus.OK, "สำเร็จ")
export class ProfileController extends Controller { export class ProfileController extends Controller {
private orgRevisionRepository = AppDataSource.getRepository(OrgRevision); private orgRevisionRepo = AppDataSource.getRepository(OrgRevision);
private posMasterRepository = AppDataSource.getRepository(PosMaster); private posMasterRepo = AppDataSource.getRepository(PosMaster);
private profileRepository = AppDataSource.getRepository(Profile); private profileRepo = AppDataSource.getRepository(Profile);
private posLevelRepository = AppDataSource.getRepository(PosLevel); private profileHistoryRepo = AppDataSource.getRepository(ProfileHistory);
private posTypeRepository = AppDataSource.getRepository(PosType); private posLevelRepo = AppDataSource.getRepository(PosLevel);
private posTypeRepo = AppDataSource.getRepository(PosType);
/** /**
* API * API
@ -49,58 +50,32 @@ export class ProfileController extends Controller {
* *
*/ */
@Post() @Post()
async createProfile( async createProfile(@Request() request: RequestWithUser, @Body() body: CreateProfile) {
@Body() if (await this.profileRepo.findOneBy({ citizenId: body.citizenId })) {
requestBody: CreateProfile,
@Request() request: { user: Record<string, any> },
) {
const _profile = await this.profileRepository.findOne({
where: { citizenId: requestBody.citizenId },
});
if (_profile) {
throw new HttpError( throw new HttpError(
HttpStatusCode.INTERNAL_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR,
"เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว", "เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว",
); );
} }
if (requestBody.posLevelId == "") {
requestBody.posLevelId = null; if (!body.posLevelId) body.posLevelId = null;
} if (!body.posTypeId) body.posTypeId = null;
if (requestBody.posLevelId) {
const checkPosLevel = await this.posLevelRepository.findOne({ if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) {
where: { id: requestBody.posLevelId }, throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
});
if (!checkPosLevel) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
}
} }
if (requestBody.posTypeId == "") { if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) {
requestBody.posTypeId = null; throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
if (requestBody.posTypeId) {
const checkPosType = await this.posTypeRepository.findOne({
where: { id: requestBody.posTypeId },
});
if (!checkPosType) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
} }
const checkCitizenId = await this.profileRepository.findOne({ const profile = Object.assign(new Profile(), body);
where: { citizenId: requestBody.citizenId },
});
if (checkCitizenId) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว");
}
const profile = Object.assign(new Profile(), requestBody);
profile.createdUserId = request.user.sub; profile.createdUserId = request.user.sub;
profile.createdFullName = request.user.name; profile.createdFullName = request.user.name;
profile.lastUpdateUserId = request.user.sub; profile.lastUpdateUserId = request.user.sub;
profile.lastUpdateFullName = request.user.name; profile.lastUpdateFullName = request.user.name;
await this.profileRepository.save(profile); await this.profileRepo.save(profile);
return new HttpSuccess(); return new HttpSuccess();
} }
@ -113,65 +88,48 @@ export class ProfileController extends Controller {
*/ */
@Put("{id}") @Put("{id}")
async updateProfile( async updateProfile(
@Request() request: RequestWithUser,
@Path() id: string, @Path() id: string,
@Body() @Body() body: UpdateProfile,
requestBody: CreateProfile,
@Request() request: { user: Record<string, any> },
) { ) {
const profile = await this.profileRepository.findOne({ where: { id: id } }); const exists =
if (!profile) { !!body.citizenId &&
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้"); (await this.profileRepo.findOne({
where: { id: Not(id), citizenId: body.citizenId },
}));
if (exists) {
throw new HttpError(HttpStatus.CONFLICT, "เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว");
} }
const _profile = await this.profileRepository.findOne({ if (!body.posLevelId) body.posLevelId = null;
where: { id: Not(id), citizenId: requestBody.citizenId }, if (!body.posTypeId) body.posTypeId = null;
});
if (_profile) { if (body.posLevelId && !(await this.posLevelRepo.findOneBy({ id: body.posLevelId }))) {
throw new HttpError( throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว",
);
} }
if (requestBody.posLevelId == "") { if (body.posTypeId && !(await this.posTypeRepo.findOneBy({ id: body.posTypeId }))) {
requestBody.posLevelId = null; throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
if (requestBody.posLevelId) {
const checkPosLevel = await this.posLevelRepository.findOne({
where: { id: requestBody.posLevelId },
});
if (!checkPosLevel) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่งนี้");
}
} }
if (requestBody.posTypeId == "") { const record = await this.profileRepo.findOneBy({ id });
requestBody.posTypeId = null;
}
if (requestBody.posTypeId) {
const checkPosType = await this.posTypeRepository.findOne({
where: { id: requestBody.posTypeId },
});
if (!checkPosType) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลประเภทตำแหน่งนี้");
}
}
const checkCitizenId = await this.profileRepository.findOne({ if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");
where: {
id: Not(id),
citizenId: requestBody.citizenId,
},
});
if (checkCitizenId) { await this.profileHistoryRepo.save(
throw new HttpError(HttpStatusCode.NOT_FOUND, "เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว"); Object.assign(new ProfileHistory(), {
} ...record,
id: undefined,
}),
);
Object.assign(record, body);
record.lastUpdateUserId = request.user.sub;
record.lastUpdateFullName = request.user.name;
await this.profileRepo.save(record);
profile.lastUpdateUserId = request.user.sub;
profile.lastUpdateFullName = request.user.name;
this.profileRepository.merge(profile, requestBody);
await this.profileRepository.save(profile);
return new HttpSuccess(); return new HttpSuccess();
} }
@ -184,13 +142,12 @@ export class ProfileController extends Controller {
*/ */
@Delete("{id}") @Delete("{id}")
async deleteProfile(@Path() id: string) { async deleteProfile(@Path() id: string) {
const delProfile = await this.profileRepository.findOne({ const result = await this.profileRepo.delete({ id });
where: { id },
}); if (result.affected && result.affected <= 0) {
if (!delProfile) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโปรไฟล์นี้");
} }
await this.profileRepository.delete({ id: id });
return new HttpSuccess(); return new HttpSuccess();
} }
@ -202,27 +159,20 @@ export class ProfileController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Get("{id}") @Get("{id}")
async detailProfile(@Path() id: string) { async getProfile(@Path() id: string) {
const profile = await this.profileRepository.findOne({ const profile = await this.profileRepo.findOne({
relations: { relations: {
posLevel: true, posLevel: true,
posType: true, posType: true,
gender: true,
relationship: true,
bloodGroup: true,
}, },
where: { id }, where: { id },
select: [
"id",
"prefix",
"firstName",
"lastName",
"citizenId",
"position",
"posLevelId",
"posTypeId",
],
}); });
if (!profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); if (!profile) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
return new HttpSuccess(profile); return new HttpSuccess(profile);
} }
@ -238,73 +188,32 @@ export class ProfileController extends Controller {
@Query("pageSize") pageSize: number = 10, @Query("pageSize") pageSize: number = 10,
@Query("keyword") keyword?: string, @Query("keyword") keyword?: string,
) { ) {
const [profile, total] = await this.profileRepository.findAndCount({ const [record, total] = await this.profileRepo.findAndCount({
select: [ relations: {
"id", posLevel: true,
"prefix", posType: true,
"firstName", gender: true,
"lastName", relationship: true,
"citizenId", bloodGroup: true,
"position", },
"posLevelId",
"posTypeId",
],
where: { where: {
citizenId: Like(`%${keyword}%`), citizenId: Like(`%${keyword}%`),
position: Like(`%${keyword}%`), position: Like(`%${keyword}%`),
prefix: Like(`%${keyword}%`), prefix: Like(`%${keyword}%`),
firstName: Like(`%${keyword}%`), firstName: Like(`%${keyword}%`),
lastName: Like(`%${keyword}%`), lastName: Like(`%${keyword}%`),
// posLevel: { posLevelName: keyword },
// posType: { posTypeName: Like(`%${keyword}%`) },
// salaryEmployeeMins: { group: keyword },
// salaryEmployee: { group: keyword },
}, },
order: { createdAt: "ASC" }, order: { createdAt: "ASC" },
skip: (page - 1) * pageSize, skip: (page - 1) * pageSize,
take: pageSize, take: pageSize,
}); });
// if (keyword != undefined && keyword !== "") { return new HttpSuccess({ data: record, total });
// const formattedKeyword = keyword.toLowerCase().replace(/\s+/g, "");
// const filteredProfile = profile.filter(
// (x) =>
// (x.prefix + x.firstName + x.lastName).replace(/\s+/g, "").includes(formattedKeyword) ||
// x.citizenId?.toString().includes(keyword) ||
// x.position?.toString().includes(keyword),
// );
// const formattedData = filteredProfile.map((item) => ({
// id: item.id,
// prefix: item.prefix,
// firstName: item.firstName,
// lastName: item.lastName,
// citizenId: item.citizenId,
// position: item.position,
// posLevelId: item.posLevelId,
// posTypeId: item.posTypeId,
// }));
// return new HttpSuccess({ data: formattedData, total: formattedData.length });
// }
const formattedData = profile.map((item) => ({
id: item.id,
prefix: item.prefix,
firstName: item.firstName,
lastName: item.lastName,
citizenId: item.citizenId,
position: item.position,
posLevelId: item.posLevelId,
posTypeId: item.posTypeId,
}));
return new HttpSuccess({ data: formattedData, total });
} }
/** /**
* API * API
* *
* @summary ORG_063 - (ADMIN) #68 * @summary ORG_063 - (ADMIN) #68
*
*/ */
@Post("search") @Post("search")
async searchProfileOrg( async searchProfileOrg(
@ -318,7 +227,7 @@ export class ProfileController extends Controller {
keyword?: string; keyword?: string;
}, },
) { ) {
const orgRevision = await this.orgRevisionRepository.findOne({ const orgRevision = await this.orgRevisionRepo.findOne({
where: { where: {
orgRevisionIsDraft: true, orgRevisionIsDraft: true,
orgRevisionIsCurrent: false, orgRevisionIsCurrent: false,
@ -326,9 +235,9 @@ export class ProfileController extends Controller {
relations: ["posMasters"], relations: ["posMasters"],
}); });
if (!orgRevision) { if (!orgRevision) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง"); throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
} }
const [profiles, total] = await this.profileRepository const [profiles, total] = await this.profileRepo
.createQueryBuilder("profile") .createQueryBuilder("profile")
.leftJoinAndSelect("profile.next_holders", "next_holders") .leftJoinAndSelect("profile.next_holders", "next_holders")
.leftJoinAndSelect("profile.posLevel", "posLevel") .leftJoinAndSelect("profile.posLevel", "posLevel")
@ -428,21 +337,21 @@ export class ProfileController extends Controller {
*/ */
@Get("keycloak/position") @Get("keycloak/position")
async getProfileByKeycloak(@Request() request: { user: Record<string, any> }) { async getProfileByKeycloak(@Request() request: { user: Record<string, any> }) {
const profile = await this.profileRepository.findOne({ const profile = await this.profileRepo.findOne({
where: { keycloak: request.user.sub }, where: { keycloak: request.user.sub },
relations: ["posLevel", "posType", "current_holders", "current_holders.orgRoot"], relations: ["posLevel", "posType", "current_holders", "current_holders.orgRoot"],
}); });
if (!profile) { if (!profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ"); throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
} }
const orgRevisionPublish = await this.orgRevisionRepository const orgRevisionPublish = await this.orgRevisionRepo
.createQueryBuilder("orgRevision") .createQueryBuilder("orgRevision")
.where("orgRevision.orgRevisionIsDraft = false") .where("orgRevision.orgRevisionIsDraft = false")
.andWhere("orgRevision.orgRevisionIsCurrent = true") .andWhere("orgRevision.orgRevisionIsCurrent = true")
.getOne(); .getOne();
if (!orgRevisionPublish) { if (!orgRevisionPublish) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง"); throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบแบบร่างโครงสร้าง");
} }
const _profile = { const _profile = {
@ -549,28 +458,28 @@ export class ProfileController extends Controller {
let findProfile: any; let findProfile: any;
switch (body.fieldName) { switch (body.fieldName) {
case "idcard": case "idcard":
findProfile = await this.profileRepository.find({ findProfile = await this.profileRepo.find({
where: { citizenId: Like(`%${body.keyword}%`) }, where: { citizenId: Like(`%${body.keyword}%`) },
relations: ["posType", "posLevel"], relations: ["posType", "posLevel"],
}); });
break; break;
case "firstname": case "firstname":
findProfile = await this.profileRepository.find({ findProfile = await this.profileRepo.find({
where: { firstName: Like(`%${body.keyword}%`) }, where: { firstName: Like(`%${body.keyword}%`) },
relations: ["posType", "posLevel"], relations: ["posType", "posLevel"],
}); });
break; break;
case "lastname": case "lastname":
findProfile = await this.profileRepository.find({ findProfile = await this.profileRepo.find({
where: { lastName: Like(`%${body.keyword}%`) }, where: { lastName: Like(`%${body.keyword}%`) },
relations: ["posType", "posLevel"], relations: ["posType", "posLevel"],
}); });
break; break;
default: default:
findProfile = await this.profileRepository.find({ findProfile = await this.profileRepo.find({
relations: ["posType", "posLevel"], relations: ["posType", "posLevel"],
}); });
break; break;
@ -609,17 +518,17 @@ export class ProfileController extends Controller {
let commanderFullname_: any = {}; let commanderFullname_: any = {};
let commanderPosition_: any = {}; let commanderPosition_: any = {};
const findProfile = await this.profileRepository.findOne({ const findProfile = await this.profileRepo.findOne({
where: { keycloak: request.user.sub }, where: { keycloak: request.user.sub },
}); });
const findRevision = await this.orgRevisionRepository.findOne({ const findRevision = await this.orgRevisionRepo.findOne({
where: { where: {
orgRevisionIsCurrent: true, orgRevisionIsCurrent: true,
}, },
}); });
const findPosMaster = await this.posMasterRepository.findOne({ const findPosMaster = await this.posMasterRepo.findOne({
where: { where: {
current_holderId: findProfile?.id, current_holderId: findProfile?.id,
orgRevisionId: findRevision?.id, orgRevisionId: findRevision?.id,
@ -648,7 +557,7 @@ export class ProfileController extends Controller {
condition = { orgRootId: childId, orgChild1Id: IsNull() }; condition = { orgRootId: childId, orgChild1Id: IsNull() };
} }
const findCmd = await this.posMasterRepository.findOne({ const findCmd = await this.posMasterRepo.findOne({
where: { where: {
current_holderId: Not(IsNull()) || Not(""), current_holderId: Not(IsNull()) || Not(""),
orgRevisionId: findRevision?.id, orgRevisionId: findRevision?.id,
@ -791,12 +700,12 @@ export class ProfileController extends Controller {
@Body() @Body()
requestBody: { citizenId: string }, requestBody: { citizenId: string },
) { ) {
const profile = await this.profileRepository.findOne({ const profile = await this.profileRepo.findOne({
where: { id: Not(id), citizenId: requestBody.citizenId }, where: { id: Not(id), citizenId: requestBody.citizenId },
}); });
if (profile) { if (profile) {
throw new HttpError( throw new HttpError(
HttpStatusCode.INTERNAL_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR,
"เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว", "เลขประจำตัวประชาชนนี้มีอยู่ในระบบแล้ว",
); );
} }
@ -838,7 +747,7 @@ export class ProfileController extends Controller {
.take(body.pageSize) .take(body.pageSize)
.getManyAndCount(); .getManyAndCount();
const orgRevisionActive = await this.orgRevisionRepository.findOne({ const orgRevisionActive = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }, where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
}); });
@ -928,11 +837,11 @@ export class ProfileController extends Controller {
period: string; period: string;
}, },
) { ) {
const findRevision = await this.orgRevisionRepository.findOne({ const findRevision = await this.orgRevisionRepo.findOne({
where: { orgRevisionIsCurrent: true }, where: { orgRevisionIsCurrent: true },
}); });
if (!findRevision) { if (!findRevision) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. OrgRevision"); throw new HttpError(HttpStatus.NOT_FOUND, "not found. OrgRevision");
} }
const [findPosMaster, total] = await AppDataSource.getRepository(PosMaster) const [findPosMaster, total] = await AppDataSource.getRepository(PosMaster)
@ -1024,7 +933,7 @@ export class ProfileController extends Controller {
.take(body.pageSize) .take(body.pageSize)
.getManyAndCount(); .getManyAndCount();
if (!findPosMaster) { if (!findPosMaster) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "not found. PosMaster"); throw new HttpError(HttpStatus.NOT_FOUND, "not found. PosMaster");
} }
const formattedData = findPosMaster.map((item) => { const formattedData = findPosMaster.map((item) => {
@ -1142,12 +1051,12 @@ export class ProfileController extends Controller {
@Path() revisionId: string, @Path() revisionId: string,
@Request() request: { user: Record<string, any> }, @Request() request: { user: Record<string, any> },
) { ) {
const profile = await this.profileRepository.findOne({ const profile = await this.profileRepo.findOne({
where: { keycloak: request.user.sub }, where: { keycloak: request.user.sub },
relations: ["posLevel", "posType", "current_holders", "current_holders.orgRoot"], relations: ["posLevel", "posType", "current_holders", "current_holders.orgRoot"],
}); });
if (!profile) { if (!profile) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ"); throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลบุคคลนี้ในระบบ");
} }
const _profile = { const _profile = {

View file

@ -1,204 +0,0 @@
import {
Controller,
Post,
Put,
Delete,
Route,
Security,
Tags,
Body,
Path,
Request,
SuccessResponse,
Response,
Get,
Query,
Patch,
Example,
} from "tsoa";
import HttpSuccess from "../interfaces/http-success";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import {
ProfileInformationHistory,
ProfileInformation,
CreateProfileInformation,
UpdateProfileInformation,
} from "../entities/ProfileInformation";
import { RequestWithUser } from "../middlewares/user";
import { Profile } from "../entities/Profile";
import { AppDataSource } from "../database/data-source";
@Route("api/v1/org/profile/information")
@Tags("ProfileInformation")
@Security("bearerAuth")
export class ProfileInformationController extends Controller {
private profileRepo = AppDataSource.getRepository(Profile);
private profileInformationRepo = AppDataSource.getRepository(ProfileInformation);
private profileInformationHistoryRepo = AppDataSource.getRepository(ProfileInformationHistory);
@Get("{profileId}")
@Example({
status: 200,
message: "สำเร็จ",
result: [
{
id: "42deba79-0725-403f-898d-6c142b2842a5",
createdAt: "2024-03-19T19:47:26.512Z",
createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0",
lastUpdatedAt: "2024-03-19T20:01:15.000Z",
lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0",
createdFullName: "สาวิตรี ศรีสมัย",
lastUpdateFullName: "สาวิตรี ศรีสมัย",
citizenId: "1849900687228",
prefix: "นาย",
firstName: "ธนพนธ์",
lastName: "แสงจันทร์",
birthDate: "2024-03-20T02:59:27.000Z",
ethnicity: "ไทย",
religion: "-",
telephoneNumber: "0639195701",
genderId: "74ec022c-b961-47f4-985e-2d9cbb10984c",
relationshipId: "5872f993-6dc3-44c7-85d3-f56825abd96d",
bloodGroupId: "fab11ded-8177-4e23-a791-78a10bc92333",
profileId: "1526d9d3-d8b1-43ab-81b5-a84dfbe99201",
},
],
})
public async detailProfileInformation(@Path() profileId: string) {
const getProfileInformation = await this.profileInformationRepo.findOne({
relations: {
bloodGroup: true,
relationship: true,
gender: true,
},
where: { profileId },
});
if (!getProfileInformation) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
return new HttpSuccess(getProfileInformation);
}
@Get("history/{informationId}")
@Example({
status: 200,
message: "สำเร็จ",
result: [
{
id: "9abba9df-5fa0-4056-847d-4b3680b61ee5",
createdAt: "2024-03-19T20:07:24.320Z",
createdUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0",
lastUpdatedAt: "2024-03-19T20:07:24.320Z",
lastUpdateUserId: "59134ef9-9e62-41d0-aac5-339be727f2b0",
createdFullName: "string",
lastUpdateFullName: "สาวิตรี ศรีสมัย",
citizenId: "1849900687228",
prefix: "นาย",
firstName: "ธนพนธ์",
lastName: "แสงจันทร์",
birthDate: "2024-03-20T03:05:41.000Z",
ethnicity: "ไทย",
religion: "-",
telephoneNumber: "0639195701",
genderId: "74ec022c-b961-47f4-985e-2d9cbb10984c",
relationshipId: "5872f993-6dc3-44c7-85d3-f56825abd96d",
bloodGroupId: "fab11ded-8177-4e23-a791-78a10bc92333",
profileId: null,
profileInformationId: "42deba79-0725-403f-898d-6c142b2842a5",
},
],
})
public async getProfileInformationHistory(@Path() informationId: string) {
const record = await this.profileInformationHistoryRepo.find({
relations: {
bloodGroup: true,
relationship: true,
gender: true,
},
where: {
profileInformationId: informationId,
},
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
return new HttpSuccess(record);
}
@Post()
public async newProfileInformation(
@Request() req: RequestWithUser,
@Body() body: CreateProfileInformation,
) {
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 ดังกล่าว");
}
const data = new ProfileInformation();
const meta = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
};
Object.assign(data, { ...body, ...meta });
await this.profileInformationRepo.save(data);
return new HttpSuccess();
}
@Patch("{informationId}")
public async editProfileInformation(
@Body() requestBody: UpdateProfileInformation,
@Request() req: RequestWithUser,
@Path() informationId: string,
) {
const record = await this.profileInformationRepo.findOneBy({ id: informationId });
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
const history = new ProfileInformationHistory();
console.log(requestBody);
Object.assign(history, { ...record, id: undefined });
Object.assign(record, requestBody);
history.profileInformationId = informationId;
history.lastUpdateFullName = req.user.name;
history.createdUserId = req.user.sub;
history.lastUpdateUserId = req.user.sub;
record.lastUpdateFullName = req.user.name;
await Promise.all([
this.profileInformationRepo.save(record),
this.profileInformationHistoryRepo.save(history),
]);
return new HttpSuccess();
}
@Delete("{informationId}")
public async deleteProfileInformation(@Path() informationId: string) {
await this.profileInformationHistoryRepo.delete({
profileInformationId: informationId,
});
const result = await this.profileInformationRepo.delete({ id: informationId });
if (result.affected && result.affected <= 0)
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
return new HttpSuccess();
}
}