import { Injectable } from '@nestjs/common'; import { PrismaService } from '../../prisma/prisma.service'; import { Customer } from '../../prisma/generated/client'; import { CustomerCreateInput } from '../../prisma/generated/models/Customer'; /** Database access to customers. Rows are matched with Hiboutik by `hiboutikId`. */ @Injectable() export class CustomerDatabaseRepository { constructor(private readonly prisma: PrismaService) {} async getAll(): Promise { return this.prisma.customer.findMany({ orderBy: { hiboutikId: 'asc' }, }); } /** Creates or updates the customer with the same `hiboutikId`. */ async upsert(customer: CustomerCreateInput): Promise { return this.prisma.customer.upsert({ where: { hiboutikId: customer.hiboutikId }, create: customer, update: customer, }); } /** * Deletes the customers that no longer exist in Hiboutik. * Their addresses are deleted (onDelete: Cascade), their orders are kept with no customer (onDelete: SetNull). */ async deleteMissing(keptHiboutikIds: number[]): Promise { const result = await this.prisma.customer.deleteMany({ where: { hiboutikId: { notIn: keptHiboutikIds } }, }); return result.count; } }