import { Body, Controller, Delete, Get, Patch, Path, Post, Request, Route, Security, Tags, } from "tsoa"; import { AppDataSource } from "../database/data-source"; import { CreateProfileHonor, ProfileHonor, UpdateProfileHonor } from "../entities/ProfileHonor"; import HttpSuccess from "../interfaces/http-success"; import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; import { ProfileHonorHistory } from "../entities/ProfileHonorHistory"; import { RequestWithUser } from "../middlewares/user"; @Route("api/v1/org/profile/honor") @Tags("ProfileHonor") @Security("bearerAuth") export class ProfileHonorController extends Controller { private honorRepo = AppDataSource.getRepository(ProfileHonor); private honorHistoryRepo = AppDataSource.getRepository(ProfileHonorHistory); @Get("{profileId}") public async getHonor(@Path() profileId: string) { const record = await this.honorRepo.findBy({ profileId }); return new HttpSuccess(record); } @Get("history/{honorId}") public async honorHistory(@Path() honorId: string) { const record = await this.honorHistoryRepo.findBy({ profileHonorId: honorId, }); return new HttpSuccess(record); } @Post() public async newHonor(@Request() req: RequestWithUser, @Body() body: CreateProfileHonor) { const data = new ProfileHonor(); const history = new ProfileHonorHistory(); const meta = { createdUserId: req.user.sub, createdFullName: req.user.name, lastUpdateUserId: req.user.sub, lastUpdateFullName: req.user.name, }; Object.assign(data, { ...body, ...meta }); Object.assign(history, { ...body, ...meta }); const result = await this.honorRepo.save(data); history.profileHonorId = result.id; await this.honorHistoryRepo.save(history); return new HttpSuccess(); } @Patch("{honorId}") public async editHonor( @Request() req: RequestWithUser, @Body() body: UpdateProfileHonor, @Path() honorId: string, ) { const record = await this.honorRepo.findOneBy({ id: honorId }); if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); const history = new ProfileHonorHistory(); Object.assign(record, body); Object.assign(history, { ...body, id: undefined }); history.profileHonorId = honorId; record.lastUpdateFullName = req.user.name; history.lastUpdateFullName = req.user.name; await Promise.all([this.honorRepo.save(record), this.honorHistoryRepo.save(history)]); return new HttpSuccess(); } @Delete("{honorId}") public async deleteTraning(@Path() honorId: string) { await this.honorHistoryRepo.delete({ profileHonorId: honorId, }); const result = await this.honorRepo.delete({ id: honorId }); if (result.affected && result.affected <= 0) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); } return new HttpSuccess(); } }