import { CustomerSelect, CustomerWhereInput } from '@/generated/prisma/models' import { PrismaService } from '@/prisma/prisma.service' import { Injectable } from '@nestjs/common' import { ResponseMapper } from 'common/response/response-mapper' import { UpdateCustomerIndividualDto, UpdateCustomerLegalDto, } from './dto/create-customers.dto' @Injectable() export class consumerCustomersService { constructor(private readonly prisma: PrismaService) {} defaultSelect: CustomerSelect = { id: true, type: true, is_favorite: true, created_at: true, individual: { select: { first_name: true, last_name: true, national_id: true, postal_code: true, economic_code: true, }, }, legal: { select: { company_name: true, registration_number: true, postal_code: true, economic_code: true, }, }, } private defaultWhere(consumer_id: string): CustomerWhereInput { return { OR: [ { individual: { business_activity: { consumer_id, }, }, }, { legal: { business_activity: { consumer_id, }, }, }, ], } } async findAll(consumer_id: string, page = 1, perPage = 10) { const [customers, total] = await this.prisma.$transaction(async tx => [ await tx.customer.findMany({ where: this.defaultWhere(consumer_id), select: this.defaultSelect, skip: (page - 1) * perPage, take: 10, }), await tx.customer.count({ where: this.defaultWhere(consumer_id), }), ]) return ResponseMapper.paginate(customers, { total, page, perPage }) } async findOne(consumer_id: string, customer_id: string) { const customer = await this.prisma.customer.findUniqueOrThrow({ where: { ...this.defaultWhere(consumer_id), id: customer_id, }, select: this.defaultSelect, }) return ResponseMapper.single(customer) } async updateLegal( consumer_id: string, customer_id: string, data: UpdateCustomerLegalDto, ) { const customer = await this.prisma.customer.update({ where: { id: customer_id, legal: { business_activity: { consumer_id, }, }, }, data: { is_favorite: data.is_favorite, legal: { update: { ...data, }, }, }, }) return ResponseMapper.update(customer) } async updateIndividual( consumer_id: string, customer_id: string, data: UpdateCustomerIndividualDto, ) { const customer = await this.prisma.customer.update({ where: { id: customer_id, individual: { business_activity: { consumer_id, }, }, }, data: { is_favorite: data.is_favorite, individual: { update: { ...data, }, }, }, }) return ResponseMapper.update(customer) } }