98 lines
2.6 KiB
TypeScript
98 lines
2.6 KiB
TypeScript
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<Customers> {
|
|
const {
|
|
first_name,
|
|
last_name,
|
|
email,
|
|
phone_number,
|
|
residence,
|
|
invoice_id,
|
|
} = dto;
|
|
|
|
return this.prisma.$transaction(async (transaction) => {
|
|
const user: Users = await transaction.users.create({
|
|
data: {
|
|
first_name,
|
|
last_name,
|
|
email,
|
|
phone_number,
|
|
residence,
|
|
},
|
|
});
|
|
return transaction.customers.create({
|
|
data: {
|
|
user_id: user.id,
|
|
invoice_id,
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
findAll(): Promise<Customers[]> {
|
|
return this.prisma.customers.findMany({
|
|
include: { user: true },
|
|
})
|
|
}
|
|
|
|
async findOne(id:number): Promise<Customers> {
|
|
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<Customers> {
|
|
const customer = await this.findOne(id);
|
|
|
|
const {
|
|
first_name,
|
|
last_name,
|
|
email,
|
|
phone_number,
|
|
residence,
|
|
invoice_id,
|
|
} = dto;
|
|
|
|
return this.prisma.$transaction(async (transaction) => {
|
|
await transaction.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 transaction.customers.update({
|
|
where: { id },
|
|
data: {
|
|
...(invoice_id !== undefined && { invoice_id }),
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
async remove(id: number): Promise<Customers> {
|
|
await this.findOne(id);
|
|
return this.prisma.customers.delete({ where: { id }});
|
|
}
|
|
}
|