import { Injectable } from '@nestjs/common'; import { PrismaService } from '../../prisma/prisma.service'; import { Prisma, ProductVersion } from '../../prisma/generated/client'; import { ProductVersionCreateInput } from '../../prisma/generated/models/ProductVersion'; /** Database access to product versions (one per Hiboutik size), identified by their product and `hiboutikSizeId`. */ @Injectable() export class ProductVersionDatabaseRepository { constructor(private readonly prisma: PrismaService) {} async getAll(): Promise { return this.prisma.productVersion.findMany({ orderBy: { hiboutikSizeId: 'asc' }, }); } /** * Creates or updates the version of `productId` with the same `hiboutikSizeId`. * @param db transaction client, to run it inside a transaction. */ async upsert( productId: string, productVersion: ProductVersionCreateInput, db: Prisma.TransactionClient = this.prisma, ): Promise { return db.productVersion.upsert({ where: { productId_hiboutikSizeId: { productId: productId, hiboutikSizeId: productVersion.hiboutikSizeId } }, create: productVersion, update: productVersion, }); } /** * Deletes the versions of a product that no longer exist in Hiboutik. * Order lines keep their own snapshot of the product, their link is set to null. * @param db transaction client, to run it inside a transaction. */ async deleteMissing(productId: string, keptHiboutikSizeIds: number[], db: Prisma.TransactionClient = this.prisma): Promise { const result = await db.productVersion.deleteMany({ where: { productId, hiboutikSizeId: { notIn: keptHiboutikSizeIds } }, }); return result.count; } }