add error on same email and phone number

This commit is contained in:
OxSaitama 2023-10-11 19:17:56 +02:00
parent 8f7367eb63
commit 13139cf167
10 changed files with 170 additions and 48 deletions

View File

@ -31,9 +31,9 @@ export default class CustomersController extends ApiController {
} }
const officeId: string = req.body.user.office_Id; const officeId: string = req.body.user.office_Id;
if(query.where?.office_folders?.some?.office_uid) delete query.where.office_folders.some.office_uid; if (query.where?.office_folders?.some?.office_uid) delete query.where.office_folders.some.office_uid;
if(query.where?.office_folders?.some?.office?.uid) delete query.where?.office_folders?.some?.office?.uid; if (query.where?.office_folders?.some?.office?.uid) delete query.where?.office_folders?.some?.office?.uid;
const customerWhereInput: Prisma.CustomersWhereInput = { ...query.where, office_folders: { some: { office_uid: officeId } }}; const customerWhereInput: Prisma.CustomersWhereInput = { ...query.where, office_folders: { some: { office_uid: officeId } } };
query.where = customerWhereInput; query.where = customerWhereInput;
//call service to get prisma entity //call service to get prisma entity
@ -79,7 +79,7 @@ export default class CustomersController extends ApiController {
/** /**
* @description Modify a specific customer by uid * @description Modify a specific customer by uid
*/ */
@Put("/api/v1/admin/customers/:uid", [authHandler, roleHandler, ruleHandler, customerHandler]) @Put("/api/v1/notary/customers/:uid", [authHandler, ruleHandler, customerHandler])
protected async put(req: Request, response: Response) { protected async put(req: Request, response: Response) {
try { try {
const uid = req.params["uid"]; const uid = req.params["uid"];
@ -95,22 +95,32 @@ export default class CustomersController extends ApiController {
return; return;
} }
req.body.contact.uid = userFound.contact_uid;
//init IUser resource with request body values //init IUser resource with request body values
const customerEntity = Customer.hydrate<Customer>(req.body); const customerEntity = Customer.hydrate<Customer>(req.body);
//validate user //validate user
await validateOrReject(customerEntity, { groups: ["updateCustomer"], forbidUnknownValues: false }); try {
await validateOrReject(customerEntity, { groups: ["updateCustomer"], forbidUnknownValues: false });
} catch (error) {
this.httpValidationError(response, error);
return;
}
//call service to get prisma entity //call service to get prisma entity
const customerEntityUpdated = await this.customersService.update(uid, customerEntity); try {
const customerEntityUpdated = await this.customersService.update(uid, customerEntity);
//Hydrate ressource with prisma entity
const customer = Customer.hydrate<Customer>(customerEntityUpdated, {
strategy: "excludeAll",
});
//Hydrate ressource with prisma entity //success
const customer = Customer.hydrate<Customer>(customerEntityUpdated, { this.httpSuccess(response, customer);
strategy: "excludeAll", } catch (error) {
}); console.log(error);
this.httpValidationError(response, error);
//success return;
this.httpSuccess(response, customer); }
} catch (error) { } catch (error) {
this.httpInternalError(response, error); this.httpInternalError(response, error);
return; return;

View File

@ -30,8 +30,8 @@ export default class CustomersController extends ApiController {
} }
const officeId: string = req.body.user.office_Id; const officeId: string = req.body.user.office_Id;
if(query.where?.office_folders) delete query.where.office_folders; if (query.where?.office_folders) delete query.where.office_folders;
const customerWhereInput: Prisma.CustomersWhereInput = { ...query.where, office_folders: { some: { office_uid: officeId } }}; const customerWhereInput: Prisma.CustomersWhereInput = { ...query.where, office_folders: { some: { office_uid: officeId } } };
query.where = customerWhereInput; query.where = customerWhereInput;
//call service to get prisma entity //call service to get prisma entity
@ -57,8 +57,12 @@ export default class CustomersController extends ApiController {
//init IUser resource with request body values //init IUser resource with request body values
const customerEntity = Customer.hydrate<Customer>(req.body); const customerEntity = Customer.hydrate<Customer>(req.body);
//validate user //validate user
await validateOrReject(customerEntity, { groups: ["createCustomer"], forbidUnknownValues: false }); try {
await validateOrReject(customerEntity, { groups: ["createCustomer"], forbidUnknownValues: false });
} catch (error) {
this.httpValidationError(response, error);
return;
}
//call service to get prisma entity //call service to get prisma entity
const customerEntityCreated = await this.customersService.create(customerEntity); const customerEntityCreated = await this.customersService.create(customerEntity);
//Hydrate ressource with prisma entity //Hydrate ressource with prisma entity
@ -93,22 +97,32 @@ export default class CustomersController extends ApiController {
return; return;
} }
req.body.contact.uid = userFound.contact_uid;
//init IUser resource with request body values //init IUser resource with request body values
const customerEntity = Customer.hydrate<Customer>(req.body); const customerEntity = Customer.hydrate<Customer>(req.body);
//validate user //validate user
await validateOrReject(customerEntity, { groups: ["updateCustomer"], forbidUnknownValues: false }); try {
await validateOrReject(customerEntity, { groups: ["updateCustomer"], forbidUnknownValues: false });
} catch (error) {
this.httpValidationError(response, error);
return;
}
//call service to get prisma entity //call service to get prisma entity
const customerEntityUpdated = await this.customersService.update(uid, customerEntity); try {
const customerEntityUpdated = await this.customersService.update(uid, customerEntity);
//Hydrate ressource with prisma entity
const customer = Customer.hydrate<Customer>(customerEntityUpdated, {
strategy: "excludeAll",
});
//Hydrate ressource with prisma entity //success
const customer = Customer.hydrate<Customer>(customerEntityUpdated, { this.httpSuccess(response, customer);
strategy: "excludeAll", } catch (error) {
}); console.log(error);
this.httpValidationError(response, error);
//success return;
this.httpSuccess(response, customer); }
} catch (error) { } catch (error) {
this.httpInternalError(response, error); this.httpInternalError(response, error);
return; return;

View File

@ -79,7 +79,7 @@ export default class CustomersController extends ApiController {
/** /**
* @description Modify a specific customer by uid * @description Modify a specific customer by uid
*/ */
@Put("/api/v1/super-admin/customers/:uid", [authHandler, roleHandler, ruleHandler, customerHandler]) @Put("/api/v1/notary/customers/:uid", [authHandler, ruleHandler, customerHandler])
protected async put(req: Request, response: Response) { protected async put(req: Request, response: Response) {
try { try {
const uid = req.params["uid"]; const uid = req.params["uid"];
@ -94,23 +94,33 @@ export default class CustomersController extends ApiController {
this.httpNotFoundRequest(response, "user not found"); this.httpNotFoundRequest(response, "user not found");
return; return;
} }
req.body.contact.uid = userFound.contact_uid;
//init IUser resource with request body values //init IUser resource with request body values
const customerEntity = Customer.hydrate<Customer>(req.body); const customerEntity = Customer.hydrate<Customer>(req.body);
//validate user //validate user
await validateOrReject(customerEntity, { groups: ["updateCustomer"], forbidUnknownValues: false }); try {
await validateOrReject(customerEntity, { groups: ["updateCustomer"], forbidUnknownValues: false });
} catch (error) {
this.httpValidationError(response, error);
return;
}
//call service to get prisma entity //call service to get prisma entity
const customerEntityUpdated = await this.customersService.update(uid, customerEntity); try {
const customerEntityUpdated = await this.customersService.update(uid, customerEntity);
//Hydrate ressource with prisma entity
const customer = Customer.hydrate<Customer>(customerEntityUpdated, {
strategy: "excludeAll",
});
//Hydrate ressource with prisma entity //success
const customer = Customer.hydrate<Customer>(customerEntityUpdated, { this.httpSuccess(response, customer);
strategy: "excludeAll", } catch (error) {
}); console.log(error);
this.httpValidationError(response, error);
//success return;
this.httpSuccess(response, customer); }
} catch (error) { } catch (error) {
this.httpInternalError(response, error); this.httpInternalError(response, error);
return; return;

View File

@ -26,4 +26,16 @@ export default class ContactRepository extends BaseRepository {
include: { customers: true } include: { customers: true }
}); });
} }
/**
* @description : Find unique customer by email
*/
public async findOneByPhoneNumber(cell_phone_number: string): Promise<(Contacts & {customers: Customers | null}) | null> {
return this.model.findUnique({
where: {
cell_phone_number: cell_phone_number,
},
include: { customers: true }
});
}
} }

View File

@ -45,7 +45,6 @@ export default abstract class BaseController {
} }
protected httpResponse(response: Response, httpCode: HttpCodes, responseData: IResponseData = {}) { protected httpResponse(response: Response, httpCode: HttpCodes, responseData: IResponseData = {}) {
console.log("httpResponse", httpCode, responseData);
if (responseData instanceof Error) { if (responseData instanceof Error) {
throw responseData; throw responseData;
} }

View File

@ -1,12 +1,13 @@
import { Customers, Prisma } from "@prisma/client"; import { Customers, Prisma } from "@prisma/client";
import CustomersRepository from "@Repositories/CustomersRepository"; import CustomersRepository from "@Repositories/CustomersRepository";
import BaseService from "@Services/BaseService"; import BaseService from "@Services/BaseService";
import ContactsService from "@Services/common/ContactService/ContactService";
import { Customer } from "le-coffre-resources/dist/Admin"; import { Customer } from "le-coffre-resources/dist/Admin";
import { Service } from "typedi"; import { Service } from "typedi";
@Service() @Service()
export default class CustomersService extends BaseService { export default class CustomersService extends BaseService {
constructor(private customerRepository: CustomersRepository) { constructor(private customerRepository: CustomersRepository, private contactService: ContactsService) {
super(); super();
} }
@ -23,6 +24,14 @@ export default class CustomersService extends BaseService {
* @throws {Error} If customer cannot be created * @throws {Error} If customer cannot be created
*/ */
public async create(customerEntity: Customer): Promise<Customers> { 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); return this.customerRepository.create(customerEntity);
} }
@ -31,6 +40,16 @@ export default class CustomersService extends BaseService {
* @throws {Error} If customer cannot be modified * @throws {Error} If customer cannot be modified
*/ */
public async update(uid: string, customerEntity: Customer): Promise<Customers> { 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: "Email 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); return this.customerRepository.update(uid, customerEntity);
} }

View File

@ -0,0 +1,27 @@
import { Contacts, Customers } from "@prisma/client";
import ContactsRepository from "@Repositories/ContactRepository";
import BaseService from "@Services/BaseService";
import { Service } from "typedi";
@Service()
export default class ContactsService extends BaseService {
constructor(private customerRepository: ContactsRepository) {
super();
}
/**
* @description : Get all Contacts
* @throws {Error} If Contacts cannot be get
*/
public async getByEmail(email: string): Promise<(Contacts & {customers: Customers | null}) | null> {
return this.customerRepository.findOneByEmail(email);
}
/**
* @description : Create a new customer
* @throws {Error} If customer cannot be created
*/
public async getByPhone(cell_phone_number: string): Promise<(Contacts & {customers: Customers | null}) | null> {
return this.customerRepository.findOneByPhoneNumber(cell_phone_number);
}
}

View File

@ -1,12 +1,13 @@
import { Customers, Prisma } from "@prisma/client"; import { Customers, Prisma } from "@prisma/client";
import CustomersRepository from "@Repositories/CustomersRepository"; import CustomersRepository from "@Repositories/CustomersRepository";
import BaseService from "@Services/BaseService"; import BaseService from "@Services/BaseService";
import ContactsService from "@Services/common/ContactService/ContactService";
import { Customer } from "le-coffre-resources/dist/Notary"; import { Customer } from "le-coffre-resources/dist/Notary";
import { Service } from "typedi"; import { Service } from "typedi";
@Service() @Service()
export default class CustomersService extends BaseService { export default class CustomersService extends BaseService {
constructor(private customerRepository: CustomersRepository) { constructor(private customerRepository: CustomersRepository, private contactService: ContactsService) {
super(); super();
} }
@ -39,6 +40,16 @@ export default class CustomersService extends BaseService {
* @throws {Error} If customer cannot be modified * @throws {Error} If customer cannot be modified
*/ */
public async update(uid: string, customerEntity: Customer): Promise<Customers> { 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); return this.customerRepository.update(uid, customerEntity);
} }

View File

@ -1,12 +1,13 @@
import { Customers, Prisma } from "@prisma/client"; import { Customers, Prisma } from "@prisma/client";
import CustomersRepository from "@Repositories/CustomersRepository"; import CustomersRepository from "@Repositories/CustomersRepository";
import BaseService from "@Services/BaseService"; import BaseService from "@Services/BaseService";
import ContactsService from "@Services/common/ContactService/ContactService";
import { Customer } from "le-coffre-resources/dist/SuperAdmin"; import { Customer } from "le-coffre-resources/dist/SuperAdmin";
import { Service } from "typedi"; import { Service } from "typedi";
@Service() @Service()
export default class CustomersService extends BaseService { export default class CustomersService extends BaseService {
constructor(private customerRepository: CustomersRepository) { constructor(private customerRepository: CustomersRepository, private contactService: ContactsService) {
super(); super();
} }
@ -23,6 +24,14 @@ export default class CustomersService extends BaseService {
* @throws {Error} If customer cannot be created * @throws {Error} If customer cannot be created
*/ */
public async create(customerEntity: Customer): Promise<Customers> { 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); return this.customerRepository.create(customerEntity);
} }
@ -31,6 +40,16 @@ export default class CustomersService extends BaseService {
* @throws {Error} If customer cannot be modified * @throws {Error} If customer cannot be modified
*/ */
public async update(uid: string, customerEntity: Customer): Promise<Customers> { 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); return this.customerRepository.update(uid, customerEntity);
} }

View File

@ -6,10 +6,11 @@ import { PrismaClient } from "@prisma/client";
import { customer, customerContact, customerContact_, customer_ } from "@Test/config/MockedData"; import { customer, customerContact, customerContact_, customer_ } from "@Test/config/MockedData";
import Container from "typedi"; import Container from "typedi";
import CustomersRepository from "@Repositories/CustomersRepository"; import CustomersRepository from "@Repositories/CustomersRepository";
import ContactService from "@Services/common/ContactService/ContactService";
const prisma = new PrismaClient(); const prisma = new PrismaClient();
const CustomersServiceTest = new CustomersService(Container.get(CustomersRepository)); const CustomersServiceTest = new CustomersService(Container.get(CustomersRepository), Container.get(ContactService));
afterAll(async () => { afterAll(async () => {
/* /*