This commit is contained in:
@ -1,5 +1,5 @@
|
||||
import axios from "axios";
|
||||
import { HospitalInformation, HrmsEmployee, Paging, User, UserRefreshToken, UserRole, UserToRoom } from "entity";
|
||||
import { Paging, User, UserRefreshToken } from "entity";
|
||||
import exceljs from "exceljs";
|
||||
import { NextFunction, Response } from "express";
|
||||
import { Request } from "express-jwt";
|
||||
@ -9,23 +9,13 @@ import CommonHelper from "../helpers/common";
|
||||
import { ReturnHelper } from "../helpers/express/return";
|
||||
import { OrmHelper } from "../helpers/orm";
|
||||
import { Language } from "../langs/lang";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import fileUpload from "express-fileupload";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import config from "../../config/stag.json";
|
||||
import { IsNull, Not } from "typeorm";
|
||||
import { IsNull } from "typeorm";
|
||||
|
||||
const log: Logger<ILogObj> = new Logger({
|
||||
name: "[UserController]",
|
||||
type: "pretty",
|
||||
});
|
||||
const STORAGE_DIR = "assets/saude/";
|
||||
|
||||
const buildFileUrl = (fileName: string): string => {
|
||||
const base = config.server.host_swagger.endsWith("/") ? config.server.host_swagger : `${config.server.host_swagger}/`;
|
||||
return `${base}${STORAGE_DIR}${fileName}`;
|
||||
};
|
||||
|
||||
export class UserController {
|
||||
static async list(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
@ -85,7 +75,7 @@ export class UserController {
|
||||
const { whereAttr, whereVal } = CommonHelper.handleFilter({
|
||||
filter: param.filter,
|
||||
col_any_eq: ["email"],
|
||||
col_any_like: ["User.name", "User.username", "roles.name"], // ← tambah roles.name
|
||||
col_any_like: ["User.name", "User.username"],
|
||||
});
|
||||
|
||||
const res_count = userRepository
|
||||
@ -96,7 +86,7 @@ export class UserController {
|
||||
const subquery = userRepository
|
||||
.createQueryBuilder("User")
|
||||
.select("User.id", "id")
|
||||
.leftJoin("User.roles", "roles")
|
||||
// .leftJoin("User.roles", "roles")
|
||||
.where(whereAttr, whereVal)
|
||||
.orderBy("User." + param.order_field, param.order_direction)
|
||||
.offset(offset)
|
||||
@ -106,8 +96,8 @@ export class UserController {
|
||||
.createQueryBuilder("User")
|
||||
.innerJoin("(" + subquery.getQuery() + ")", "sub", "User.id = sub.id")
|
||||
.setParameters(subquery.getParameters())
|
||||
.leftJoinAndSelect("User.roles", "roles")
|
||||
.leftJoinAndSelect("roles.application", "application")
|
||||
// .leftJoinAndSelect("User.roles", "roles")
|
||||
// .leftJoinAndSelect("roles.application", "application")
|
||||
.orderBy("User." + param.order_field, param.order_direction);
|
||||
|
||||
// const subquery = userRepository
|
||||
@ -146,228 +136,6 @@ export class UserController {
|
||||
// ← Tambahkan mapping ini
|
||||
const mapped_data = list_data.map((user) => ({
|
||||
...user,
|
||||
profile_picture: user.profile_picture ?? null,
|
||||
file_profile_picture: user.profile_picture ? buildFileUrl(user.profile_picture) : null,
|
||||
}));
|
||||
|
||||
return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, count_data, current_page, total_count_data, mapped_data);
|
||||
} catch (e: unknown) {
|
||||
log.error(e);
|
||||
const err = e as Error;
|
||||
|
||||
return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
static async listDoctor(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
#swagger.tags = ['User']
|
||||
#swagger.security = [{ "bearerAuth": [] }]
|
||||
#swagger.parameters['filter'] = {
|
||||
description: 'Filter with 2 format : <ul><li>Simple format use text plaint will filter eq:email or like %name% or like %username%</li><li>Advance format using field existing {status:\'Y\', any:\'SAME AS PLAINT LOGIC\', etc...}</li></ul>',
|
||||
in: 'query',
|
||||
type: 'string'
|
||||
}
|
||||
#swagger.parameters['limit'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
type: 'number'
|
||||
}
|
||||
#swagger.parameters['page'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
type: 'number'
|
||||
}
|
||||
#swagger.parameters['with_deleted'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
type: 'boolean'
|
||||
}
|
||||
#swagger.parameters['order_field'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
type: 'string'
|
||||
}
|
||||
#swagger.parameters['order_direction'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
schema: {
|
||||
'@enum': ['ASC', 'DESC']
|
||||
}
|
||||
}
|
||||
*/
|
||||
try {
|
||||
const schema = Joi.object().keys({
|
||||
filter: Joi.any().allow("").optional().label("Filter"),
|
||||
page: Joi.number().required().min(1).label("Page"),
|
||||
limit: Joi.number().required().min(1).label("Limit"),
|
||||
with_deleted: Joi.bool().required().label("With Deleted"),
|
||||
order_field: Joi.string().required().label("Order Field"),
|
||||
order_direction: Joi.string().allow("asc", "desc").required().label("Order Direction"),
|
||||
});
|
||||
|
||||
const param: Paging = await schema.validateAsync(req.query);
|
||||
const userRepository = OrmHelper.DB.getRepository(User);
|
||||
const offset = (param.page - 1) * param.limit;
|
||||
|
||||
const { whereAttr, whereVal } = CommonHelper.handleFilter({
|
||||
filter: param.filter,
|
||||
col_any_eq: ["email"],
|
||||
col_any_like: ["User.name", "User.username"],
|
||||
additional_where: "roles.is_doctor = true",
|
||||
});
|
||||
|
||||
const res_count = userRepository
|
||||
.createQueryBuilder("User")
|
||||
.leftJoin("User.roles", "roles")
|
||||
.where(whereAttr, whereVal);
|
||||
|
||||
const orderExpr = "User." + param.order_field;
|
||||
const subquery = userRepository
|
||||
.createQueryBuilder("User")
|
||||
.select("User.id", "id")
|
||||
.addSelect(orderExpr, "_list_doctor_order")
|
||||
.leftJoin("User.roles", "roles")
|
||||
.where(whereAttr, whereVal)
|
||||
.orderBy(orderExpr, param.order_direction)
|
||||
.offset(offset)
|
||||
.limit(param.limit)
|
||||
.distinct(true);
|
||||
|
||||
const res_list = userRepository
|
||||
.createQueryBuilder("User")
|
||||
.innerJoin("(" + subquery.getQuery() + ")", "sub", "User.id = sub.id")
|
||||
.setParameters(subquery.getParameters())
|
||||
.leftJoinAndSelect("User.roles", "roles")
|
||||
.leftJoinAndSelect("roles.application", "application")
|
||||
.orderBy("User." + param.order_field, param.order_direction)
|
||||
.distinct(true);
|
||||
|
||||
if (param.with_deleted) {
|
||||
res_count.withDeleted();
|
||||
res_list.withDeleted();
|
||||
}
|
||||
|
||||
const current_page = param.page;
|
||||
const total_count_data = await res_count.getCount();
|
||||
const list_data = await res_list.getMany();
|
||||
const count_data = CommonHelper.countObject(list_data);
|
||||
|
||||
const mapped_data = list_data.map((user) => ({
|
||||
...user,
|
||||
profile_picture: user.profile_picture ?? null,
|
||||
file_profile_picture: user.profile_picture ? buildFileUrl(user.profile_picture) : null,
|
||||
}));
|
||||
|
||||
return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, count_data, current_page, total_count_data, mapped_data);
|
||||
} catch (e: unknown) {
|
||||
log.error(e);
|
||||
const err = e as Error;
|
||||
|
||||
return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
static async listDoctorAndNurse(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
#swagger.tags = ['User']
|
||||
#swagger.security = [{ "bearerAuth": [] }]
|
||||
#swagger.parameters['filter'] = {
|
||||
description: 'Filter with 2 format : <ul><li>Simple format use text plaint will filter eq:email or like %name% or like %username%</li><li>Advance format using field existing {status:\'Y\', any:\'SAME AS PLAINT LOGIC\', etc...}</li></ul>',
|
||||
in: 'query',
|
||||
type: 'string'
|
||||
}
|
||||
#swagger.parameters['limit'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
type: 'number'
|
||||
}
|
||||
#swagger.parameters['page'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
type: 'number'
|
||||
}
|
||||
#swagger.parameters['with_deleted'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
type: 'boolean'
|
||||
}
|
||||
#swagger.parameters['order_field'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
type: 'string'
|
||||
}
|
||||
#swagger.parameters['order_direction'] = {
|
||||
in: 'query',
|
||||
required: true,
|
||||
schema: {
|
||||
'@enum': ['ASC', 'DESC']
|
||||
}
|
||||
}
|
||||
*/
|
||||
try {
|
||||
const schema = Joi.object().keys({
|
||||
filter: Joi.any().allow("").optional().label("Filter"),
|
||||
page: Joi.number().required().min(1).label("Page"),
|
||||
limit: Joi.number().required().min(1).label("Limit"),
|
||||
with_deleted: Joi.bool().required().label("With Deleted"),
|
||||
order_field: Joi.string().required().label("Order Field"),
|
||||
order_direction: Joi.string().allow("asc", "desc").required().label("Order Direction"),
|
||||
});
|
||||
|
||||
const param: Paging = await schema.validateAsync(req.query);
|
||||
const userRepository = OrmHelper.DB.getRepository(User);
|
||||
const offset = (param.page - 1) * param.limit;
|
||||
|
||||
const { whereAttr, whereVal } = CommonHelper.handleFilter({
|
||||
filter: param.filter,
|
||||
col_any_eq: ["email"],
|
||||
col_any_like: ["User.name", "User.username"],
|
||||
additional_where: "roles.is_doctor = true OR roles.is_nurse = true",
|
||||
});
|
||||
|
||||
const res_count = userRepository
|
||||
.createQueryBuilder("User")
|
||||
.leftJoin("User.roles", "roles")
|
||||
.where(whereAttr, whereVal);
|
||||
|
||||
const orderExpr = "User." + param.order_field;
|
||||
const subquery = userRepository
|
||||
.createQueryBuilder("User")
|
||||
.select("User.id", "id")
|
||||
.addSelect(orderExpr, "_list_doctor_order")
|
||||
.leftJoin("User.roles", "roles")
|
||||
.where(whereAttr, whereVal)
|
||||
.orderBy(orderExpr, param.order_direction)
|
||||
.offset(offset)
|
||||
.limit(param.limit)
|
||||
.distinct(true);
|
||||
|
||||
const res_list = userRepository
|
||||
.createQueryBuilder("User")
|
||||
.innerJoin("(" + subquery.getQuery() + ")", "sub", "User.id = sub.id")
|
||||
.setParameters(subquery.getParameters())
|
||||
.leftJoinAndSelect("User.roles", "roles")
|
||||
.leftJoinAndSelect("roles.application", "application")
|
||||
.orderBy("User." + param.order_field, param.order_direction)
|
||||
.distinct(true);
|
||||
|
||||
if (param.with_deleted) {
|
||||
res_count.withDeleted();
|
||||
res_list.withDeleted();
|
||||
}
|
||||
|
||||
const current_page = param.page;
|
||||
const total_count_data = await res_count.getCount();
|
||||
const list_data = await res_list.getMany();
|
||||
const count_data = CommonHelper.countObject(list_data);
|
||||
|
||||
const mapped_data = list_data.map((user) => ({
|
||||
...user,
|
||||
profile_picture: user.profile_picture ?? null,
|
||||
file_profile_picture: user.profile_picture ? buildFileUrl(user.profile_picture) : null,
|
||||
signature: user.signature ?? null,
|
||||
file_signature: user.signature ? buildFileUrl(user.signature) : null,
|
||||
}));
|
||||
|
||||
return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, count_data, current_page, total_count_data, mapped_data);
|
||||
@ -491,11 +259,9 @@ export class UserController {
|
||||
const schema = Joi.object().keys({
|
||||
email: Joi.string().email().max(64).allow("", null).optional().label("Email"),
|
||||
username: Joi.string().max(64).required().label("Username"),
|
||||
// password: Joi.string().pattern(new RegExp("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$")).min(8).required().label("Password"),
|
||||
password: Joi.string().allow("").optional().label("Password"),
|
||||
retype_password: Joi.ref("password"),
|
||||
name: Joi.string().max(64).required().label("Name"),
|
||||
employee_id: Joi.string().uuid().optional().allow("").label("Employee ID"),
|
||||
status: Joi.string().required().label("Status"),
|
||||
});
|
||||
|
||||
@ -528,13 +294,6 @@ export class UserController {
|
||||
|
||||
const data = new User();
|
||||
|
||||
if (param.employee_id && param.employee_id != "") {
|
||||
const employee = await OrmHelper.DB.manager.getRepository(HrmsEmployee).findOneByOrFail({ id: param.employee_id });
|
||||
data.employee = employee;
|
||||
} else {
|
||||
data.employee = null;
|
||||
}
|
||||
|
||||
data.name = param.name;
|
||||
data.username = param.username;
|
||||
data.password = param.password;
|
||||
@ -556,156 +315,156 @@ export class UserController {
|
||||
}
|
||||
}
|
||||
|
||||
static async addRole(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
#swagger.tags = ['User']
|
||||
#swagger.security = [{
|
||||
"bearerAuth": []
|
||||
}]
|
||||
// static async addRole(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
// /*
|
||||
// #swagger.tags = ['User']
|
||||
// #swagger.security = [{
|
||||
// "bearerAuth": []
|
||||
// }]
|
||||
|
||||
#swagger.parameters['id'] = {
|
||||
in: 'path',
|
||||
description: 'User ID.',
|
||||
required: true,
|
||||
type: 'string'
|
||||
}
|
||||
// #swagger.parameters['id'] = {
|
||||
// in: 'path',
|
||||
// description: 'User ID.',
|
||||
// required: true,
|
||||
// type: 'string'
|
||||
// }
|
||||
|
||||
#swagger.parameters['id_role'] = {
|
||||
in: 'path',
|
||||
description: 'User Role ID.',
|
||||
required: true,
|
||||
type: 'string'
|
||||
}
|
||||
*/
|
||||
// #swagger.parameters['id_role'] = {
|
||||
// in: 'path',
|
||||
// description: 'User Role ID.',
|
||||
// required: true,
|
||||
// type: 'string'
|
||||
// }
|
||||
// */
|
||||
|
||||
try {
|
||||
const schema = Joi.object().keys({
|
||||
id: Joi.string().uuid().required().label("ID"),
|
||||
id_role: Joi.string().uuid().required().label("ID"),
|
||||
});
|
||||
// try {
|
||||
// const schema = Joi.object().keys({
|
||||
// id: Joi.string().uuid().required().label("ID"),
|
||||
// id_role: Joi.string().uuid().required().label("ID"),
|
||||
// });
|
||||
|
||||
const param: { id: string; id_role: string } = await schema.validateAsync(req.params);
|
||||
// const param: { id: string; id_role: string } = await schema.validateAsync(req.params);
|
||||
|
||||
const userRepository = OrmHelper.DB.getRepository(User);
|
||||
const repo_role = OrmHelper.DB.getRepository(UserRole);
|
||||
// const userRepository = OrmHelper.DB.getRepository(User);
|
||||
// const repo_role = OrmHelper.DB.getRepository(UserRole);
|
||||
|
||||
const data = await userRepository.findOne({
|
||||
relations: ["roles", "roles.application"],
|
||||
where: { id: param.id },
|
||||
});
|
||||
// const data = await userRepository.findOne({
|
||||
// relations: ["roles", "roles.application"],
|
||||
// where: { id: param.id },
|
||||
// });
|
||||
|
||||
if (data != null) {
|
||||
// const new_role = await repo_role.findOneBy({ id: param.id_role });
|
||||
const new_role = await repo_role.findOne({
|
||||
relations: {
|
||||
application: true,
|
||||
},
|
||||
where: { id: param.id_role },
|
||||
});
|
||||
// if (data != null) {
|
||||
// // const new_role = await repo_role.findOneBy({ id: param.id_role });
|
||||
// const new_role = await repo_role.findOne({
|
||||
// relations: {
|
||||
// application: true,
|
||||
// },
|
||||
// where: { id: param.id_role },
|
||||
// });
|
||||
|
||||
if (data.roles) {
|
||||
for (let r of data.roles) {
|
||||
if (r.id == param.id_role) {
|
||||
//already added
|
||||
return ReturnHelper.errorResponse(res, 409, 401, Language.lang.failed_insert + ", roles already exists ", "");
|
||||
}
|
||||
// if (data.roles) {
|
||||
// for (let r of data.roles) {
|
||||
// if (r.id == param.id_role) {
|
||||
// //already added
|
||||
// return ReturnHelper.errorResponse(res, 409, 401, Language.lang.failed_insert + ", roles already exists ", "");
|
||||
// }
|
||||
|
||||
if (r.application.id == new_role?.application.id) {
|
||||
return ReturnHelper.errorResponse(res, 409, 402, Language.lang.failed_insert + ", roles in this application already exists ", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (r.application.id == new_role?.application.id) {
|
||||
// return ReturnHelper.errorResponse(res, 409, 402, Language.lang.failed_insert + ", roles in this application already exists ", "");
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
if (!data.roles) {
|
||||
data.roles = [];
|
||||
}
|
||||
// if (!data.roles) {
|
||||
// data.roles = [];
|
||||
// }
|
||||
|
||||
data.roles.push(new_role);
|
||||
// data.roles.push(new_role);
|
||||
|
||||
await userRepository.save(data);
|
||||
// await userRepository.save(data);
|
||||
|
||||
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, data);
|
||||
} else {
|
||||
return ReturnHelper.errorResponse(res, 404, 403, Language.lang.failed_not_found, "");
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
log.error(e);
|
||||
const err = e as Error;
|
||||
// return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, data);
|
||||
// } else {
|
||||
// return ReturnHelper.errorResponse(res, 404, 403, Language.lang.failed_not_found, "");
|
||||
// }
|
||||
// } catch (e: unknown) {
|
||||
// log.error(e);
|
||||
// const err = e as Error;
|
||||
|
||||
return ReturnHelper.errorResponse(res, 500, 404, Language.lang.failed_update, err.message);
|
||||
}
|
||||
}
|
||||
// return ReturnHelper.errorResponse(res, 500, 404, Language.lang.failed_update, err.message);
|
||||
// }
|
||||
// }
|
||||
|
||||
static async deleteRole(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
#swagger.tags = ['User']
|
||||
#swagger.security = [{
|
||||
"bearerAuth": []
|
||||
}]
|
||||
// static async deleteRole(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
// /*
|
||||
// #swagger.tags = ['User']
|
||||
// #swagger.security = [{
|
||||
// "bearerAuth": []
|
||||
// }]
|
||||
|
||||
#swagger.parameters['id'] = {
|
||||
in: 'path',
|
||||
description: 'User ID.',
|
||||
required: true,
|
||||
type: 'string'
|
||||
}
|
||||
// #swagger.parameters['id'] = {
|
||||
// in: 'path',
|
||||
// description: 'User ID.',
|
||||
// required: true,
|
||||
// type: 'string'
|
||||
// }
|
||||
|
||||
#swagger.parameters['id_role'] = {
|
||||
in: 'path',
|
||||
description: 'User Role ID.',
|
||||
required: true,
|
||||
type: 'string'
|
||||
}
|
||||
*/
|
||||
// #swagger.parameters['id_role'] = {
|
||||
// in: 'path',
|
||||
// description: 'User Role ID.',
|
||||
// required: true,
|
||||
// type: 'string'
|
||||
// }
|
||||
// */
|
||||
|
||||
try {
|
||||
const schema = Joi.object().keys({
|
||||
id: Joi.string().uuid().required().label("ID"),
|
||||
id_role: Joi.string().uuid().required().label("ID"),
|
||||
});
|
||||
// try {
|
||||
// const schema = Joi.object().keys({
|
||||
// id: Joi.string().uuid().required().label("ID"),
|
||||
// id_role: Joi.string().uuid().required().label("ID"),
|
||||
// });
|
||||
|
||||
const param: { id: string; id_role: string } = await schema.validateAsync(req.params);
|
||||
// const param: { id: string; id_role: string } = await schema.validateAsync(req.params);
|
||||
|
||||
const userRepository = OrmHelper.DB.getRepository(User);
|
||||
// const userRepository = OrmHelper.DB.getRepository(User);
|
||||
|
||||
const data = await userRepository.findOne({
|
||||
relations: {
|
||||
roles: true,
|
||||
},
|
||||
where: { id: param.id },
|
||||
});
|
||||
// const data = await userRepository.findOne({
|
||||
// relations: {
|
||||
// roles: true,
|
||||
// },
|
||||
// where: { id: param.id },
|
||||
// });
|
||||
|
||||
if (data != null && data.roles) {
|
||||
let found = false;
|
||||
let new_roles: UserRole[] = [];
|
||||
// if (data != null && data.roles) {
|
||||
// let found = false;
|
||||
// let new_roles: UserRole[] = [];
|
||||
|
||||
for (let r of data.roles) {
|
||||
if (r.id != param.id_role) {
|
||||
new_roles.push(r);
|
||||
} else if (r.id == param.id_role) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
// for (let r of data.roles) {
|
||||
// if (r.id != param.id_role) {
|
||||
// new_roles.push(r);
|
||||
// } else if (r.id == param.id_role) {
|
||||
// found = true;
|
||||
// }
|
||||
// }
|
||||
|
||||
data.roles = new_roles;
|
||||
// data.roles = new_roles;
|
||||
|
||||
if (found) {
|
||||
await userRepository.save(data);
|
||||
// if (found) {
|
||||
// await userRepository.save(data);
|
||||
|
||||
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_delete, data);
|
||||
} else {
|
||||
return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found + ", role not found", "");
|
||||
}
|
||||
} else {
|
||||
return ReturnHelper.errorResponse(res, 404, 402, Language.lang.failed_not_found, "");
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
log.error(e);
|
||||
const err = e as Error;
|
||||
// return ReturnHelper.successResponseAny(res, 200, Language.lang.success_delete, data);
|
||||
// } else {
|
||||
// return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found + ", role not found", "");
|
||||
// }
|
||||
// } else {
|
||||
// return ReturnHelper.errorResponse(res, 404, 402, Language.lang.failed_not_found, "");
|
||||
// }
|
||||
// } catch (e: unknown) {
|
||||
// log.error(e);
|
||||
// const err = e as Error;
|
||||
|
||||
return ReturnHelper.errorResponse(res, 500, 403, Language.lang.failed_delete, err.message);
|
||||
}
|
||||
}
|
||||
// return ReturnHelper.errorResponse(res, 500, 403, Language.lang.failed_delete, err.message);
|
||||
// }
|
||||
// }
|
||||
|
||||
static async updateProfile(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
@ -818,47 +577,6 @@ export class UserController {
|
||||
}
|
||||
}
|
||||
|
||||
static async uploadFile(files: fileUpload.FileArray | null | undefined, fieldName: string): Promise<string | null> {
|
||||
if (!files || !files[fieldName]) return null;
|
||||
|
||||
const file = files[fieldName] as fileUpload.UploadedFile;
|
||||
|
||||
const maxSize = 1 * 1024 * 1024; // 1MB
|
||||
if (file.size > maxSize) {
|
||||
throw { message: `${fieldName}: File size exceeds 1MB limit` };
|
||||
}
|
||||
|
||||
const allowedMimes = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/svg+xml", "image/svg"];
|
||||
if (!allowedMimes.includes(file.mimetype)) {
|
||||
throw {
|
||||
message: `${fieldName}: Invalid file type. Only JPG, PNG, WEBP, and SVG are allowed`,
|
||||
};
|
||||
}
|
||||
|
||||
const ext = file.name.split(".");
|
||||
const name = uuidv4() + "." + ext[ext.length - 1];
|
||||
const file_path = path.join(STORAGE_DIR, name);
|
||||
|
||||
if (!fs.existsSync(STORAGE_DIR)) {
|
||||
fs.mkdirSync(STORAGE_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
await file.mv(file_path);
|
||||
log.info(`File uploaded successfully: ${file_path}`);
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
static async deleteFile(filePath: string): Promise<void> {
|
||||
try {
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
log.info(`File deleted successfully: ${filePath}`);
|
||||
}
|
||||
} catch (e) {
|
||||
log.error(`Failed to delete file: ${filePath}`, e);
|
||||
}
|
||||
}
|
||||
|
||||
static async update(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
@ -877,19 +595,10 @@ export class UserController {
|
||||
#swagger.requestBody = {
|
||||
required: true,
|
||||
content: {
|
||||
"multipart/form-data": {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
email: { type: "string", description: "Email" },
|
||||
username: { type: "string", description: "Username" },
|
||||
password: { type: "string", description: "Password" },
|
||||
retype_password: { type: "string", description: "Retype Password" },
|
||||
name: { type: "string", description: "name" },
|
||||
status: { type: "string", description: "Status" },
|
||||
profile_picture: { type: "string", description: "String" }
|
||||
}
|
||||
}
|
||||
$ref: "#/components/schemas/user"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -903,9 +612,7 @@ export class UserController {
|
||||
password: Joi.string().allow("").optional().label("Password"),
|
||||
retype_password: Joi.ref("password"),
|
||||
name: Joi.string().max(64).required().label("Name"),
|
||||
employee_id: Joi.string().uuid().optional().allow("").label("Employee ID"),
|
||||
status: Joi.string().required().label("Status"),
|
||||
profile_picture: Joi.string().allow("", null).optional().label("Profile Picture"),
|
||||
});
|
||||
|
||||
req.body.id = req.params["id"];
|
||||
@ -925,7 +632,6 @@ export class UserController {
|
||||
// }
|
||||
// }
|
||||
|
||||
data.profile_picture = param.profile_picture || data.profile_picture;
|
||||
data.name = param.name;
|
||||
data.username = param.username;
|
||||
if (param.email !== undefined) {
|
||||
@ -968,97 +674,6 @@ export class UserController {
|
||||
}
|
||||
}
|
||||
|
||||
static async updateUserSignature(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
#swagger.tags = ['User']
|
||||
#swagger.security = [{
|
||||
"bearerAuth": []
|
||||
}]
|
||||
#swagger.consumes = ['multipart/form-data']
|
||||
#swagger.parameters['id'] = {
|
||||
in: 'path',
|
||||
description: 'User ID.',
|
||||
required: true,
|
||||
type: 'string'
|
||||
}
|
||||
|
||||
#swagger.requestBody = {
|
||||
required: true,
|
||||
content: {
|
||||
"multipart/form-data": {
|
||||
schema: {
|
||||
type: "object",
|
||||
required: ["user_signature"],
|
||||
properties: {
|
||||
user_signature: { type: "string", format: "binary", description: "Image file (max 1MB, jpg/png/webp)" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
try {
|
||||
const schema = Joi.object().keys({
|
||||
id: Joi.string().uuid().required().label("ID"),
|
||||
user_signature: Joi.string().allow("", null).optional().label("User Signature"),
|
||||
});
|
||||
|
||||
req.body.id = req.params["id"];
|
||||
|
||||
const param: any = await schema.validateAsync(req.body);
|
||||
|
||||
const userRepository = OrmHelper.DB.getRepository(User);
|
||||
|
||||
const data = await userRepository.findOneBy({ id: param.id });
|
||||
|
||||
if (data != null) {
|
||||
const usersignature = await UserController.uploadFile(req.files, "user_signature");
|
||||
|
||||
if (usersignature) {
|
||||
// ← Hapus signature lama jika ada
|
||||
if (data.signature) {
|
||||
const oldFilePath = path.join(STORAGE_DIR, data.signature);
|
||||
await UserController.deleteFile(oldFilePath);
|
||||
}
|
||||
|
||||
data.signature = usersignature;
|
||||
}
|
||||
|
||||
// data.name = param.name;
|
||||
// data.username = param.username;
|
||||
// data.email = param.email;
|
||||
// data.status = param.status;
|
||||
// data.updated_by = req.auth?.data.name;
|
||||
// data.updated_at = new Date();
|
||||
|
||||
// if (param.employee_id && param.employee_id != "") {
|
||||
// const employee = await OrmHelper.DB.manager
|
||||
// .getRepository(HrmsEmployee)
|
||||
// .findOneByOrFail({id: param.employee_id});
|
||||
// data.employee = employee;
|
||||
// } else {
|
||||
// data.employee = null;
|
||||
// }
|
||||
|
||||
// if (param.password) {
|
||||
// data.password = param.password;
|
||||
// data.hashPassword();
|
||||
// }
|
||||
|
||||
await userRepository.save(data);
|
||||
|
||||
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, data);
|
||||
} else {
|
||||
return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found, "");
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
log.error(e);
|
||||
const err = e as Error;
|
||||
|
||||
return ReturnHelper.errorResponse(res, 500, 402, Language.lang.failed_update, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
static async delete(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
@ -1106,65 +721,6 @@ export class UserController {
|
||||
}
|
||||
}
|
||||
|
||||
static async detail(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
#swagger.tags = ['User']
|
||||
#swagger.security = [{
|
||||
"bearerAuth": []
|
||||
}]
|
||||
#swagger.parameters['id'] = {
|
||||
in: 'path',
|
||||
description: 'User ID.',
|
||||
required: true,
|
||||
type: 'string'
|
||||
}
|
||||
*/
|
||||
try {
|
||||
const schema = Joi.object().keys({
|
||||
id: Joi.string().uuid().required().label("ID"),
|
||||
});
|
||||
|
||||
const param: User = await schema.validateAsync(req.params);
|
||||
|
||||
const userRepository = OrmHelper.DB.getRepository(User);
|
||||
|
||||
const detail = await userRepository.findOne({
|
||||
relations: ["roles", "roles.application", "employee", "employee.department", "employee.position", "employee.shift", "employee.nationality", "employee.aldeia", "employee.suco", "employee.administrativu", "employee.munisipo"],
|
||||
where: { id: param.id },
|
||||
});
|
||||
|
||||
const repoHospital = OrmHelper.DB.getRepository(HospitalInformation);
|
||||
const hospital = await repoHospital.findOne({ where: { id: Not(IsNull()) } });
|
||||
|
||||
if (detail != null) {
|
||||
const query = `SELECT r.id, r.room, r.code
|
||||
FROM rooms r
|
||||
INNER JOIN user_to_room utr ON utr.room_id = r.id
|
||||
WHERE utr.user_id = $1 AND r.deleted_at IS NULL AND utr.deleted_at IS NULL`
|
||||
const rooms = await OrmHelper.DB.query(query, [detail.id])
|
||||
|
||||
const data = {
|
||||
...detail,
|
||||
rooms: rooms,
|
||||
signature: detail.signature ?? null,
|
||||
file_signature: detail.signature ? buildFileUrl(detail.signature) : null,
|
||||
profile: detail.profile_picture ?? null,
|
||||
profile_picture: detail.profile_picture ? buildFileUrl(detail.profile_picture) : null,
|
||||
hospital: hospital,
|
||||
};
|
||||
|
||||
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_view, data);
|
||||
} else {
|
||||
return ReturnHelper.errorResponse(res, 404, 401, Language.lang.failed_not_found, "");
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
log.error(e);
|
||||
const err = e as Error;
|
||||
|
||||
return ReturnHelper.errorResponse(res, 500, 402, Language.lang.failed_view, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
static async restore(req: Request, res: Response, next: NextFunction): Promise<Response> {
|
||||
/*
|
||||
#swagger.tags = ['User']
|
||||
|
||||
Reference in New Issue
Block a user