import { Body, Controller, Delete, Get, Path, Post, Request, Route, Security, Tags } from "tsoa"; import { AppDataSource } from "../database/data-source"; import HttpSuccess from "../interfaces/http-success"; import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; import { RequestWithUser } from "../middlewares/user"; import { CreateProfileEmployeeAvatar, ProfileAvatar } from "../entities/ProfileAvatar"; import { ProfileEmployee } from "../entities/ProfileEmployee"; @Route("api/v1/org/profile-employee/avatar") @Tags("ProfileAvatar") @Security("bearerAuth") export class ProfileAvatarEmployeeController extends Controller { private profileRepository = AppDataSource.getRepository(ProfileEmployee); private avatarRepository = AppDataSource.getRepository(ProfileAvatar); @Get("{profileId}") public async getAvatar(@Path() profileId: string) { const lists = await this.avatarRepository.find({ where: { profileEmployeeId: profileId }, }); return new HttpSuccess(lists); } @Post() public async newAvatar( @Request() req: RequestWithUser, @Body() body: CreateProfileEmployeeAvatar, ) { const profile = await this.profileRepository.findOneBy({ id: body.profileEmployeeId }); if (!profile) { throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว"); } const data = new ProfileAvatar(); 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.avatarRepository.save(data); let avatar = `ทะเบียนประวัติ/โปรไฟล์/${profile.id}/profile-employee-${data.id}`; data.avatar = avatar; await this.avatarRepository.save(data); profile.avatar = avatar; await this.profileRepository.save(profile); return new HttpSuccess(avatar); } @Delete("{avatarId}") public async deleteAvatar(@Path() avatarId: string) { const result = await this.avatarRepository.delete({ id: avatarId }); if (result.affected == undefined || result.affected <= 0) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); } return new HttpSuccess(); } }