import { Controller, Post, UseAuth, Req, Request, Res, Response, HeaderParams, BodyParams, Get, PathParams, QueryParams } from '@tsed/common'; import { Docs } from '@tsed/swagger'; import Joi from '@hapi/joi'; import { Like, Raw } from 'typeorm'; import { VerificationJWT } from '../../middleware/auth/VerificationJWT'; import { Validator } from '../../middleware/validator/Validator'; import { Customer } from '../../entity/Customer'; import { Password } from '../../util/password'; @Controller("/admin/customer") @Docs("docs_admin") export class CustomerController { constructor() { } // =====================GET LIST===================== @Get('') @UseAuth(VerificationJWT) @Validator({ page: Joi.number().min(0), limit: Joi.number().min(0) }) async findAll( @HeaderParams("token") token: string, @QueryParams("page") page: number, @QueryParams("limit") limit: number, @QueryParams("isBlock") isBlock: boolean, @QueryParams("search") search: string = "", @Req() req: Request, @Res() res: Response ) { const where = { phone: Raw(alias => `concat( ${alias}, " ", name) LIKE "%${search}%"`), isBlock } if (req.query.isBlock === undefined) { delete where.isBlock } const [customer, total] = await Customer.findAndCount({ skip: (page - 1) * limit, take: limit, where, order: { id: "DESC" }, }) return res.sendOK({ data: customer, total }) } // =====================UPDATE ITEM===================== @Post('/:customerId/update') @UseAuth(VerificationJWT) @Validator({ customer: Joi.required(), customerId: Joi.number().required() }) async update( @Req() req: Request, @Res() res: Response, @HeaderParams("token") token: string, @BodyParams("customer") customer: Customer, @PathParams("customerId") customerId: number, ) { await Customer.findOneOrThrowId(+customerId) customer.id = customerId await customer.save() return res.sendOK(customer, 'Cập nhật thành công!') } // =====================GET ITEM===================== @Get('/:customerId') @UseAuth(VerificationJWT) @Validator({ customerId: Joi.number().required(), }) async findOne( @Req() req: Request, @Res() res: Response, @HeaderParams("token") token: string, @PathParams("customerId") customerId: number, ) { const customer = await Customer.findOneOrThrowId(+customerId) return res.sendOK(customer) } // =====================RESET PASSWORD===================== @Post('/:customerId/update/password') @UseAuth(VerificationJWT) @Validator({ customerId: Joi.number().required(), password: Joi.string().required() }) async updatePassword( @Req() req: Request, @Res() res: Response, @HeaderParams('token') token: string, @PathParams('customerId') customerId: number, @BodyParams('password') password: string ) { const customer = await Customer.findOneOrThrowId(+customerId); customer.password = await Password.hash(password) await customer.save() return res.sendOK(customer, 'Cập nhật thành công.') } } // END FILE