import { Injectable, NotFoundException } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { CreateCustomerDto } from '../dtos/create-customer.dto'; import { Customers, Users } from '@prisma/client'; import { UpdateCustomerDto } from '../dtos/update-customer.dto'; @Injectable() export class CustomersService { constructor(private readonly prisma: PrismaService) {} async create(dto: CreateCustomerDto): Promise { const { first_name, last_name, email, phone_number, residence, invoice_id, } = dto; return this.prisma.$transaction(async (tx) => { const user: Users = await tx.users.create({ data: { first_name, last_name, email, phone_number, residence, }, }); return tx.customers.create({ data: { user_id: user.id, invoice_id, }, }); }); } findAll(): Promise { return this.prisma.customers.findMany({ include: { user: true }, }) } async findOne(id:number): Promise { const customer = await this.prisma.customers.findUnique({ where: { id }, include: { user: true }, }); if(!customer) { throw new NotFoundException(`Customer #${id} not found`); } return customer; } async update( id: number, dto: UpdateCustomerDto, ): Promise { const customer = await this.findOne(id); const { first_name, last_name, email, phone_number, residence, invoice_id, } = dto; return this.prisma.$transaction(async (tx) => { await tx.users.update({ where: { id: customer.user_id }, data: { ...(first_name !== undefined && { first_name }), ...(last_name !== undefined && { last_name }), ...(email !== undefined && { email }), ...(phone_number !== undefined && { phone_number }), ...(residence !== undefined && { residence }), }, }); return tx.customers.update({ where: { id }, data: { ...(invoice_id !== undefined && { invoice_id }), }, }); }); } async remove(id: number): Promise { await this.findOne(id); return this.prisma.customers.delete({ where: { id }}); } }