module customers
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { UserRole } from '../users/enums/user-role.enum';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { CreateCustomerDto } from './dto/create-customer.dto';
|
||||
import { UpdateCustomerDto } from './dto/update-customer.dto';
|
||||
import { Customer } from './entities/customer.entity';
|
||||
|
||||
@Injectable()
|
||||
export class CustomersService {
|
||||
constructor(
|
||||
@InjectRepository(Customer)
|
||||
private readonly customersRepository: Repository<Customer>,
|
||||
private readonly usersService: UsersService,
|
||||
) {}
|
||||
|
||||
async create(createCustomerDto: CreateCustomerDto): Promise<Customer> {
|
||||
const user = await this.usersService.create({
|
||||
firstName: createCustomerDto.firstName,
|
||||
lastName: createCustomerDto.lastName,
|
||||
mobile: createCustomerDto.mobile,
|
||||
role: UserRole.CUSTOMER,
|
||||
});
|
||||
|
||||
const customer = this.customersRepository.create({
|
||||
userId: user.id,
|
||||
dateOfBirth: createCustomerDto.dateOfBirth,
|
||||
address: createCustomerDto.address,
|
||||
});
|
||||
|
||||
const saved = await this.customersRepository.save(customer);
|
||||
return this.findOne(saved.id);
|
||||
}
|
||||
|
||||
findAll(): Promise<Customer[]> {
|
||||
return this.customersRepository.find({ relations: { user: true } });
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<Customer> {
|
||||
const customer = await this.customersRepository.findOne({
|
||||
where: { id },
|
||||
relations: { user: true },
|
||||
});
|
||||
if (!customer) {
|
||||
throw new NotFoundException(`Customer #${id} not found`);
|
||||
}
|
||||
return customer;
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
updateCustomerDto: UpdateCustomerDto,
|
||||
): Promise<Customer> {
|
||||
const customer = await this.findOne(id);
|
||||
const { firstName, lastName, mobile, dateOfBirth, address } =
|
||||
updateCustomerDto;
|
||||
|
||||
if (
|
||||
firstName !== undefined ||
|
||||
lastName !== undefined ||
|
||||
mobile !== undefined
|
||||
) {
|
||||
await this.usersService.update(customer.userId, {
|
||||
firstName,
|
||||
lastName,
|
||||
mobile,
|
||||
});
|
||||
}
|
||||
|
||||
if (dateOfBirth !== undefined) {
|
||||
customer.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
if (address !== undefined) {
|
||||
customer.address = address;
|
||||
}
|
||||
|
||||
await this.customersRepository.save(customer);
|
||||
return this.findOne(customer.id);
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
const customer = await this.findOne(id);
|
||||
await this.usersService.remove(customer.userId);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user