AnhLedger's picture
see list of user
439f1c8
import { Body, forwardRef, HttpStatus, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { UserEntity } from '../../entities/user.entity.js';
import { SignUpDto } from '../authentication/dto/sign-up.dto.js';
import { UpdateUserDto } from './dto/update-user-dto.js';
import { ValidateService } from '../../validate/validate.service.js';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { FilterOperator, paginate, PaginateConfig, PaginateQuery } from 'nestjs-paginate';
import { UpdateUsersDto } from './dto/update-users.dto.js';
import { In } from 'typeorm';
export type User = any;
@Injectable()
export class UserService {
constructor(
private validateService: ValidateService,
private jwtService: JwtService,
) { }
async create(signUpDto: SignUpDto): Promise<UserEntity | undefined> {
return UserEntity.create({
full_name: signUpDto.full_name,
phone_number: signUpDto.phone_number,
email: signUpDto.email,
hash_password: signUpDto.password
})
}
async save(userEntity: UserEntity): Promise<UserEntity | undefined> {
return UserEntity.save(userEntity);
}
async findOneByField(field: string, value: any): Promise<UserEntity | undefined> {
return UserEntity.findOne({
where: { [field]: value }
});
}
async updateUserById(userId: string, updateUserDto: UpdateUserDto) {
await this.validateService.checkExistField('email', updateUserDto.email);
await this.validateService.checkExistField('phone_number', updateUserDto.phone_number);
const user = await UserEntity.findOne({
where: { id: userId }
});
if (!user) {
throw new NotFoundException(`User with ID ${userId} not found`);
}
Object.assign(user, updateUserDto);
if (updateUserDto.hash_password) {
const saltRounds = 10;
user.hash_password = await bcrypt.hash(updateUserDto.hash_password, saltRounds); // Mã hóa mật khẩu
}
await UserEntity.save(user);
const payload = { sub: user.id, username: user.full_name, role: user.role };
const token = await this.jwtService.signAsync(payload)
return {
access_token: token
};
}
async findAllUser(query: PaginateQuery) {
const paginateConfig: PaginateConfig<UserEntity> = {
sortableColumns: ['id', 'full_name', 'phone_number', 'email'],
nullSort: 'last',
defaultSortBy: [['id', 'DESC']],
searchableColumns: ['full_name'],
filterableColumns: {
full_name: [
FilterOperator.LT,
FilterOperator.LTE,
FilterOperator.GT,
FilterOperator.GTE,
],
item_type: [FilterOperator.EQ]
},
};
return paginate(query, UserEntity.createQueryBuilder(), paginateConfig);
}
async findAllByName(fullName: string, query: PaginateQuery) {
const queryBuilder = UserEntity.createQueryBuilder('users')
.where('users.full_name = :fullName', { fullName });
const paginateConfig: PaginateConfig<UserEntity> = {
sortableColumns: ['id', 'full_name', 'phone_number', 'email'],
nullSort: 'last',
defaultSortBy: [['id', 'DESC']],
searchableColumns: ['full_name'],
filterableColumns: {
full_name: [
FilterOperator.LT,
FilterOperator.LTE,
FilterOperator.GT,
FilterOperator.GTE,
],
item_type: [FilterOperator.EQ]
},
};
return paginate(query, queryBuilder, paginateConfig);
}
async getUsers(query: PaginateQuery) {
const queryBuilder = UserEntity.createQueryBuilder('users')
const paginateConfig: PaginateConfig<UserEntity> = {
sortableColumns: ['id', 'full_name', 'phone_number', 'email'],
nullSort: 'last',
defaultSortBy: [['id', 'DESC']],
searchableColumns: ['full_name', 'phone_number'],
filterableColumns: {
id: [FilterOperator.EQ],
full_name: [
FilterOperator.LT,
FilterOperator.LTE,
FilterOperator.GT,
FilterOperator.GTE,
],
phone_number: [FilterOperator.EQ],
email: [FilterOperator.EQ],
branch_id:[FilterOperator.EQ],
role: [FilterOperator.EQ]
},
};
return paginate(query, queryBuilder, paginateConfig);
}
async updateUsers(updateUsersDto: UpdateUsersDto[]) {
try {
//Lấy ra id trong updateUsersDto
const userIds = updateUsersDto.map(user => user.id).filter(id => id !== undefined);
//Lấy ra các user tồn tại trong db
const existingUsers = await UserEntity.find({
where: { id: In(userIds) },
});
// Bước 2: Kết hợp dữ liệu từ yêu cầu với dữ liệu hiện có
const mergedData: Partial<User>[] = [];
for (const userData of updateUsersDto) {
if (userData.hash_password)
userData.hash_password = await bcrypt.hash(userData.hash_password, 10);
const existingUser = existingUsers.find(user => user.id === userData.id);
if (existingUser) {
// Merge data: keep existing fields for any data not included in the request
mergedData.push({ ...existingUser, ...userData });
} else {
// For new users, use only the request data
mergedData.push(userData);
}
}
console.log(updateUsersDto)
UserEntity.upsert(mergedData, ['id'])
return {
statusCode: HttpStatus.OK,
message: "Thành công"
}
} catch (error) {
return {
statusCode: HttpStatus.OK,
message: "Thất bại"
}
}
}
}