File size: 5,800 Bytes
bac00ce
9e8f9e3
 
 
 
 
 
bac00ce
 
 
9e8f9e3
 
 
 
 
 
 
 
b2556e4
9e8f9e3
b2556e4
9e8f9e3
 
 
 
bac00ce
 
9e8f9e3
 
b2556e4
9e8f9e3
 
 
bac00ce
b2556e4
bac00ce
9e8f9e3
 
 
b2556e4
bac00ce
9e8f9e3
bac00ce
9e8f9e3
 
bac00ce
9e8f9e3
 
 
 
 
 
 
 
bac00ce
9e8f9e3
 
 
6588b71
bac00ce
9e8f9e3
bac00ce
9e8f9e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bac00ce
9e8f9e3
 
 
 
 
 
bac00ce
 
9e8f9e3
 
 
 
 
 
 
 
 
 
 
 
bac00ce
9e8f9e3
 
 
 
 
439f1c8
bac00ce
9e8f9e3
 
 
 
439f1c8
9e8f9e3
439f1c8
9e8f9e3
 
 
 
 
 
439f1c8
 
 
 
9e8f9e3
 
 
 
bac00ce
 
 
 
 
 
 
 
 
 
 
 
b2556e4
 
 
 
 
bac00ce
b2556e4
bac00ce
b2556e4
 
bac00ce
b2556e4
 
bac00ce
b2556e4
bac00ce
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8f9e3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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"
      }
    }
  }
}