import Database from "@Common/databases/database"; import BaseRepository from "@Repositories/BaseRepository"; import { Service } from "typedi"; import { Customers, ECivility, ECustomerStatus, Prisma } from "@prisma/client"; import { Customer } from "le-coffre-resources/dist/SuperAdmin"; @Service() export default class CustomersRepository extends BaseRepository { constructor(private database: Database) { super(); } protected get model() { return this.database.getClient().customers; } protected get instanceDb() { return this.database.getClient(); } /** * @description : Find many customers */ public async findMany(query: any): Promise { query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); return this.model.findMany(query); } /** * @description : Create a customer */ public async create(customer: Customer): Promise { const createArgs: Prisma.CustomersCreateArgs = { data: { status: ECustomerStatus.PENDING, contact: { create: { first_name: customer.contact.first_name, last_name: customer.contact.last_name, email: customer.contact.email, phone_number: customer.contact.phone_number, cell_phone_number: customer.contact?.cell_phone_number, civility: ECivility[customer.contact.civility as keyof typeof ECivility], address: {} }, }, }, }; if (customer.contact.address) { createArgs.data.contact!.create!.address!.create = { address: customer.contact.address!.address, zip_code: customer.contact.address!.zip_code, city: customer.contact.address!.city, }; } return this.model.create(createArgs); } /** * @description : Update data from a customer */ public async update(uid: string, customer: Customer): Promise { const updateArgs: Prisma.CustomersUpdateArgs = { where: { uuid: uid, }, data: { status: ECustomerStatus[customer.status as keyof typeof ECustomerStatus], contact: { update: { first_name: customer.contact.first_name, last_name: customer.contact.last_name, email: customer.contact.email, phone_number: customer.contact.phone_number, cell_phone_number: customer.contact.cell_phone_number, civility: ECivility[customer.contact.civility as keyof typeof ECivility], address: {} }, }, }, } if (customer.contact.address) { updateArgs.data.contact!.update!.address!.update = { address: customer.contact.address!.address, zip_code: customer.contact.address!.zip_code, city: customer.contact.address!.city, }; } return this.model.update(updateArgs); } /** * @description : Find unique customer */ public async findOneByUid(uid: string): Promise { const customerEntity = await this.model.findUnique({ where: { uuid: uid, }, }); if (!customerEntity) { throw new Error("Customer not found"); } return customerEntity; } }