From 552bb9d51fff63dfda49d720624aa0fb043a7b23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20Bj=C3=B6rk?= Date: Thu, 12 Dec 2024 15:55:33 +0100 Subject: [PATCH] allow null for scope 3 categories in order to delete them --- src/lib/prisma.ts | 18 +++++++++++++++++- src/routes/updateCompanies.ts | 2 +- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/lib/prisma.ts b/src/lib/prisma.ts index cd04ceaa..6a7292c7 100644 --- a/src/lib/prisma.ts +++ b/src/lib/prisma.ts @@ -135,7 +135,7 @@ export async function upsertScope1And2( export async function upsertScope3( emissions: Emissions, scope3: { - categories?: { category: number; total: number }[] + categories?: { category: number; total: number | null }[] statedTotalEmissions?: OptionalNullable< Omit > @@ -167,12 +167,28 @@ export async function upsertScope3( }, }) + await prisma.scope3Category.deleteMany({ + where: { + scope3Id: updatedScope3.id, + category: { + in: (scope3.categories ?? []) + .filter((c) => c.total === null) + .map((c) => c.category), + }, + }, + }) + // Upsert only the scope 3 categories from the request body await Promise.all( (scope3.categories ?? []).map((scope3Category) => { const matching = updatedScope3.categories.find( ({ category }) => scope3Category.category === category ) + + if (scope3Category.total === null) { + return null + } + return prisma.scope3Category.upsert({ where: { id: matching?.id ?? 0, diff --git a/src/routes/updateCompanies.ts b/src/routes/updateCompanies.ts index a1674379..8859b3e4 100644 --- a/src/routes/updateCompanies.ts +++ b/src/routes/updateCompanies.ts @@ -298,7 +298,7 @@ export const emissionsSchema = z .array( z.object({ category: z.number().int().min(1).max(16), - total: z.number(), + total: z.number().nullable(), }) ) .optional(),