update for revenue dashboard
Some checks failed
Deploy Backend / deploy (push) Has been cancelled

This commit is contained in:
wayanrivan
2026-07-07 09:03:33 +07:00
parent bce6ebd12f
commit 1c5195d986
11 changed files with 478 additions and 1246 deletions

View File

@ -11,7 +11,7 @@ import dayjs from "dayjs"
import jwt from "jsonwebtoken"
import fs from "fs"
import { v4 as uuidv4 } from "uuid"
import { Application, EmailBody, HospitalInformation, HrmsEmployee, Menu, User, UserRefreshToken, UserRole } from "entity"
import { User, UserRefreshToken, UserRole } from "entity"
import axios from "axios"
import CommonHelper from "../helpers/common"
import { MoreThan } from "typeorm"
@ -38,7 +38,7 @@ export class AuthController {
const schema = Joi.object().keys({
username: Joi.string().max(64).required().label("Username"),
password: Joi.string().min(8).required().label("Password"),
application: Joi.string().required().label("Application"),
// application: Joi.string().required().label("Application"),
})
const param: User & { application: string } = await schema.validateAsync(req.body)
@ -47,7 +47,7 @@ export class AuthController {
const userRefreshTokenRepository = OrmHelper.DB.getRepository(UserRefreshToken)
const user = await userRepository.findOne({
relations: ["roles", "roles.application", "employee", "employee.department", "employee.position", "employee.shift"],
// relations: ["roles", "roles.application", "employee", "employee.department", "employee.position", "employee.shift"],
select: ["id", "email", "name", "password", "username", "roles"],
where: { username: param.username },
})
@ -56,7 +56,9 @@ export class AuthController {
return ReturnHelper.errorResponse(res, 401, 401, Language.lang.failed_access, "Username or password is incorrect")
}
if (user != null && user.roles != null && user.roles.length > 0 && user.checkIfPasswordMatch(param.password)) {
if (
// user != null && user.roles != null && user.roles.length > 0 &&
user.checkIfPasswordMatch(param.password)) {
const { browser, device, os } = UAParser(req.get("User-Agent"))
const refresh_token = new UserRefreshToken()
@ -73,107 +75,109 @@ export class AuthController {
// const userRoleRepository = OrmHelper.DB.getRepository(UserRole);
let role_id = ""
let roles: UserRole
// let role_id = ""
// let roles: UserRole
if (user.roles) {
for (let r of user.roles) {
if (r.application.id == param.application) {
role_id = r.id
roles = r
}
}
// if (user.roles) {
// for (let r of user.roles) {
// if (r.application.id == param.application) {
// role_id = r.id
// roles = r
// }
// }
// }
// if (role_id == "") {
// return ReturnHelper.errorResponse(res, 403, 403, Language.lang.failed_access, "You don't have any roles in this application")
// } else {
// const userRole = await userRoleRepository.findOneBy({ id: role_id })
// var hrms = {
// uuid: null,
// idx: null,
// employee_id: null,
// employeename: null,
// title: null,
// department_id: null,
// departement_uuid: null,
// department_name: null,
// level_id: null,
// level_name: null,
// }
// If user has employee, populate hrms data
// if (user.employee && user.employee.id) {
// hrms.uuid = user.employee.id
// hrms.employee_id = user.employee.employee_id || null
// hrms.employeename = user.employee.name || null
// hrms.title = user.employee.position?.name || null
// hrms.department_id = user.employee.department?.id || null
// hrms.departement_uuid = user.employee.department?.id || null
// hrms.department_name = user.employee.department?.name || null
// hrms.level_id = user.employee.position?.id || null
// hrms.level_name = user.employee.position?.name || null
// }
// const roomQuery = `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(roomQuery, [user.id])
// const facility = await OrmHelper.DB.getRepository(HospitalInformation).findOne({
// select: {
// id: true,
// facility_id: true,
// name: true,
// address: true,
// phone: true,
// code: true,
// },
// where: {},
// })
var privateKey = fs.readFileSync("src/helpers/key/private.key")
var token = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) + Number(config.get("auth.access_token_lifetime")),
data: {
id: user.id,
username: user.username,
name: user.name,
// id_role: role_id,
// roles: roles.roles,
// // hrms: hrms,
},
},
privateKey,
{ algorithm: "RS256" }
)
delete user.password
const data = {
// user: { ...user, ...hrms, rooms },
// role_name: roles.name,
// default_page: roles.default_page ?? null,
// facility: facility ?? null,
// roles_list: await AuthController.getListRole(roles.roles),
token: {
access_token: token,
refresh_token: refresh_token.refresh_token,
},
}
if (role_id == "") {
return ReturnHelper.errorResponse(res, 403, 403, Language.lang.failed_access, "You don't have any roles in this application")
} else {
// const userRole = await userRoleRepository.findOneBy({ id: role_id })
var hrms = {
uuid: null,
idx: null,
employee_id: null,
employeename: null,
title: null,
department_id: null,
departement_uuid: null,
department_name: null,
level_id: null,
level_name: null,
}
// If user has employee, populate hrms data
if (user.employee && user.employee.id) {
hrms.uuid = user.employee.id
hrms.employee_id = user.employee.employee_id || null
hrms.employeename = user.employee.name || null
hrms.title = user.employee.position?.name || null
hrms.department_id = user.employee.department?.id || null
hrms.departement_uuid = user.employee.department?.id || null
hrms.department_name = user.employee.department?.name || null
hrms.level_id = user.employee.position?.id || null
hrms.level_name = user.employee.position?.name || null
}
const roomQuery = `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(roomQuery, [user.id])
const facility = await OrmHelper.DB.getRepository(HospitalInformation).findOne({
select: {
id: true,
facility_id: true,
name: true,
address: true,
phone: true,
code: true,
},
where: {},
})
var privateKey = fs.readFileSync("src/helpers/key/private.key")
var token = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) + Number(config.get("auth.access_token_lifetime")),
data: {
id: user.id,
username: user.username,
name: user.name,
id_role: role_id,
roles: roles.roles,
hrms: hrms,
},
},
privateKey,
{ algorithm: "RS256" }
)
delete user.password
const data = {
user: { ...user, ...hrms, rooms },
role_name: roles.name,
default_page: roles.default_page ?? null,
facility: facility ?? null,
roles_list: await AuthController.getListRole(roles.roles),
token: {
access_token: token,
refresh_token: refresh_token.refresh_token,
},
}
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_login, data)
}
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_login, data)
}
// }
if (user.roles == null || user.roles.length == 0) {
return ReturnHelper.errorResponse(res, 401, 401, Language.lang.failed_access, "You don't have any roles in this application")
} else {
return ReturnHelper.errorResponse(res, 401, 401, Language.lang.failed_access, "Username or password is incorrect")
}
// if (user.roles == null || user.roles.length == 0) {
// return ReturnHelper.errorResponse(res, 401, 401, Language.lang.failed_access, "You don't have any roles in this application")
// } else {
// return ReturnHelper.errorResponse(res, 401, 401, Language.lang.failed_access, "Username or password is incorrect")
// }
return ReturnHelper.errorResponse(res, 401, 401, Language.lang.failed_access, "Username or password is incorrect")
} catch (e: unknown) {
log.error(e)
const err = e as Error
@ -182,93 +186,93 @@ export class AuthController {
}
}
static async getListRole(roles: any): Promise<any> {
const repoMenu = OrmHelper.DB.getRepository(Menu)
// static async getListRole(roles: any): Promise<any> {
// // const repoMenu = OrmHelper.DB.getRepository(Menu)
const whereAttr = []
const whereVal = {}
// const whereAttr = []
// const whereVal = {}
for (let k in roles) {
let p = roles[k]
// for (let k in roles) {
// let p = roles[k]
whereAttr.push("id = :id" + k)
whereVal["id" + k] = p
}
// whereAttr.push("id = :id" + k)
// whereVal["id" + k] = p
// }
const res_list = repoMenu
.createQueryBuilder()
.where("(" + whereAttr.join(" or ") + ") and id_parent is null", whereVal)
.orderBy("order_number", "ASC")
// // const res_list = repoMenu
// // .createQueryBuilder()
// // .where("(" + whereAttr.join(" or ") + ") and id_parent is null", whereVal)
// // .orderBy("order_number", "ASC")
let list_data_final = await res_list.getMany()
// // let list_data_final = await res_list.getMany()
if (list_data_final.length > 0) {
const res_list_all = await repoMenu
.createQueryBuilder()
.where("(" + whereAttr.join(" or ") + ") and id_parent is not null", whereVal)
.orderBy("order_number", "ASC")
.getMany()
// // if (list_data_final.length > 0) {
// // const res_list_all = await repoMenu
// // .createQueryBuilder()
// // .where("(" + whereAttr.join(" or ") + ") and id_parent is not null", whereVal)
// // .orderBy("order_number", "ASC")
// // .getMany()
let list_child: any = {}
for (let p of res_list_all) {
if (!list_child[p.id_parent]) {
list_child[p.id_parent] = []
}
// // let list_child: any = {}
// // for (let p of res_list_all) {
// // if (!list_child[p.id_parent]) {
// // list_child[p.id_parent] = []
// // }
delete p.status
delete p.created_at
delete p.updated_at
delete p.deleted_at
// // delete p.status
// // delete p.created_at
// // delete p.updated_at
// // delete p.deleted_at
list_child[p.id_parent].push(p)
}
// // list_child[p.id_parent].push(p)
// // }
for (let f of list_data_final) {
delete f.status
delete f.created_at
delete f.updated_at
delete f.deleted_at
// // for (let f of list_data_final) {
// // delete f.status
// // delete f.created_at
// // delete f.updated_at
// // delete f.deleted_at
if (list_child[f.id]) {
f.children = list_child[f.id]
// // if (list_child[f.id]) {
// // f.children = list_child[f.id]
for (let g of f.children) {
if (list_child[g.id]) {
g.children = list_child[g.id]
// // for (let g of f.children) {
// // if (list_child[g.id]) {
// // g.children = list_child[g.id]
for (let h of g.children) {
if (list_child[h.id]) {
h.children = list_child[h.id]
// // for (let h of g.children) {
// // if (list_child[h.id]) {
// // h.children = list_child[h.id]
for (let i of h.children) {
if (list_child[i.id]) {
i.children = list_child[i.id]
// // for (let i of h.children) {
// // if (list_child[i.id]) {
// // i.children = list_child[i.id]
for (let j of i.children) {
if (list_child[j.id]) {
j.children = list_child[j.id]
// // for (let j of i.children) {
// // if (list_child[j.id]) {
// // j.children = list_child[j.id]
for (let k of j.children) {
if (list_child[k.id]) {
k.children = list_child[k.id]
}
}
}
}
}
}
}
}
}
}
}
}
// // for (let k of j.children) {
// // if (list_child[k.id]) {
// // k.children = list_child[k.id]
// // }
// // }
// // }
// // }
// // }
// // }
// // }
// // }
// // }
// // }
// // }
// // }
return list_data_final
}
// // return list_data_final
// // }
return {}
}
// return {}
// }
static async logout(req: Request, res: Response, next: NextFunction): Promise<Response> {
/*
@ -305,79 +309,6 @@ export class AuthController {
}
}
static async resetPassword(req: Request, res: Response, next: NextFunction): Promise<Response> {
/*
#swagger.tags = ['Auth']
#swagger.parameters['email'] = {
in: 'path',
description: 'Email',
required: true,
type: 'string'
}
#swagger.parameters['application'] = {
in: 'path',
description: 'Application',
required: true,
type: 'string'
}
*/
try {
const schema = Joi.object().keys({
email: Joi.string().email().required().label("Email"),
application: Joi.string().required().label("Application"),
})
const param: { email: string; application: string } = await schema.validateAsync(req.params)
const userRepository = OrmHelper.DB.getRepository(User)
const user = await userRepository.findOne({
where: { email: param.email },
})
user.reset_token = uuidv4()
await userRepository.save(user)
//send email reset password
const url = config.get("service.notification") + "api/email/send"
// console.log(url, 'url')
const template_raw = fs.readFileSync("assets/reset_password.html").toString()
const appRepository = OrmHelper.DB.getRepository(Application)
const app = await appRepository.findOneBy({ id: param.application })
const pairMap = {
// 'LINK': config.get('auth.reset_password_url') + user.reset_token,
LINK: app.reset_password_url + user.reset_token,
NAME: user.name,
}
const template = CommonHelper.generateTemplate(template_raw, pairMap)
const email: EmailBody = {
subject: "Reset Password",
to: [user.email],
cc: [],
bcc: [],
html: template,
}
const { data } = await axios.post(url, email)
return ReturnHelper.successResponseAny(res, 200, Language.lang.success, data)
// return ReturnHelper.errorResponse(res, 403, 401, Language.lang.failed_access);
} catch (e: unknown) {
log.error(e)
const err = e as Error
return ReturnHelper.errorResponse(res, 500, 402, Language.lang.failed, err.message)
}
}
static async renewToken(req: Request, res: Response, next: NextFunction): Promise<Response> {
/*
@ -415,17 +346,17 @@ export class AuthController {
let role_id = ""
let roles: UserRole
if (user.roles != null && user.roles.length > 0) {
for (let r of user.roles) {
if (r.application.id == param.application) {
role_id = r.id
// if (user.roles != null && user.roles.length > 0) {
// for (let r of user.roles) {
// if (r.application.id == param.application) {
// role_id = r.id
roles = r
}
}
} else {
return ReturnHelper.errorResponse(res, 403, 401, Language.lang.failed_access + ", you don't have any roles in this application")
}
// roles = r
// }
// }
// } else {
// return ReturnHelper.errorResponse(res, 403, 401, Language.lang.failed_access + ", you don't have any roles in this application")
// }
// const userRoleRepository = OrmHelper.DB.getRepository(UserRole);
// const userRole = await userRoleRepository.findOneBy({ id: role_id });
@ -451,7 +382,7 @@ export class AuthController {
return ReturnHelper.successResponseAny(res, 200, Language.lang.success, {
token,
role_name: roles.name,
roles_list: await AuthController.getListRole(roles.roles),
// roles_list: await AuthController.getListRole(roles.roles),
})
} else {
return ReturnHelper.errorResponse(res, 403, 402, Language.lang.failed_access + ", you don't have any roles in this application")
@ -470,14 +401,14 @@ export class AuthController {
static async updatePassword(req: Request, res: Response, next: NextFunction): Promise<Response> {
/*
#swagger.tags = ['Auth']
#swagger.parameters['token'] = {
in: 'path',
description: 'Token',
required: true,
type: 'string'
}
#swagger.requestBody = {
required: true,
description: "This action will effect to user related token",