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, customer_individual: { select: { first_name: true, last_name: true, national_id: true, postal_code: true, economic_code: true, }, }, customer_legal: { select: { company_name: true, registration_number: true, postal_code: true, economic_code: true, }, }, } private defaultWhere(consumer_id: string): CustomerWhereInput { return { OR: [ { customer_individual: { complex: { business_activity: { consumer_id, }, }, }, }, { customer_legal: { complex: { business_activity: { consumer_id, }, }, }, }, ], } } async findAll(consumer_id: string, page = 1, pageSize = 10) { const [customers, count] = await this.prisma.$transaction(async tx => [ await tx.customer.findMany({ where: this.defaultWhere(consumer_id), select: this.defaultSelect, skip: (page - 1) * pageSize, take: 10, }), await tx.customer.count({ where: this.defaultWhere(consumer_id), }), ]) return ResponseMapper.paginate(customers, { count, page, pageSize }) } 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, customer_legal: { complex: { business_activity: { consumer_id, }, }, }, }, data: { is_favorite: data.is_favorite, customer_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, customer_individual: { complex: { business_activity: { consumer_id, }, }, }, }, data: { is_favorite: data.is_favorite, customer_individual: { update: { ...data, }, }, }, }) return ResponseMapper.update(customer) } }