2023-10-11 19:17:56 +02:00

72 lines
2.7 KiB
TypeScript

import { Customers, Prisma } from "@prisma/client";
import CustomersRepository from "@Repositories/CustomersRepository";
import BaseService from "@Services/BaseService";
import ContactsService from "@Services/common/ContactService/ContactService";
import { Customer } from "le-coffre-resources/dist/SuperAdmin";
import { Service } from "typedi";
@Service()
export default class CustomersService extends BaseService {
constructor(private customerRepository: CustomersRepository, private contactService: ContactsService) {
super();
}
/**
* @description : Get all Customers
* @throws {Error} If Customers cannot be get
*/
public async get(query: Prisma.CustomersFindManyArgs): Promise<Customers[]> {
return this.customerRepository.findMany(query);
}
/**
* @description : Create a new customer
* @throws {Error} If customer cannot be created
*/
public async create(customerEntity: Customer): Promise<Customers> {
const customers = await this.get({
where: {
contact: {
OR: [{ email: customerEntity.contact?.email }, { cell_phone_number: customerEntity.contact?.cell_phone_number }],
},
},
});
if(customers[0]) return customers[0];
return this.customerRepository.create(customerEntity);
}
/**
* @description : Modify a customer
* @throws {Error} If customer cannot be modified
*/
public async update(uid: string, customerEntity: Customer): Promise<Customers> {
let errors = [];
if(customerEntity.contact?.email) {
const contactWithSameEmail = await this.contactService.getByEmail(customerEntity.contact.email);
if(contactWithSameEmail && contactWithSameEmail.uid != customerEntity.contact.uid) errors.push({property: "email", constraints: {email: "mail déjà utilisé"}});
}
if(customerEntity.contact?.cell_phone_number) {
const contactWithSamePhoneNumber = await this.contactService.getByPhone(customerEntity.contact.cell_phone_number);
if(contactWithSamePhoneNumber && contactWithSamePhoneNumber.uid != customerEntity.contact.uid) errors.push({property: "cell_phone_number", constraints: {phone: "numéro de téléphone déjà utilisé"}});
}
if(errors.length != 0) throw errors;
return this.customerRepository.update(uid, customerEntity);
}
/**
* @description : Get a customer by uid
* @throws {Error} If customer cannot be get by uid
*/
public async getByUid(uid: string, query?: Prisma.CustomersInclude): Promise<Customers | null> {
return this.customerRepository.findOneByUid(uid, query);
}
/**
* @description : Get a customer by contact uid
* @throws {Error} If customer cannot be get by contact uid
*/
public async getByContact(contactUid: string): Promise<Customers | null> {
return this.customerRepository.findOneByContact(contactUid);
}
}