From f6c03e3c9178e7685ecbdb6db8941f96943cdd72 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Fri, 29 May 2026 19:05:23 -0300 Subject: [PATCH] refactor(expenses): optimize monthly totals and pending calculations using raw SQL queries --- .../src/modules/expenses/expenses.service.ts | 41 +++++++++---------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/apps/backend/src/modules/expenses/expenses.service.ts b/apps/backend/src/modules/expenses/expenses.service.ts index 5c799fe..13f7100 100644 --- a/apps/backend/src/modules/expenses/expenses.service.ts +++ b/apps/backend/src/modules/expenses/expenses.service.ts @@ -146,36 +146,33 @@ export async function payExpense(id: number, data: z.infer>` + SELECT CAST(SUM("amountPayed") AS NUMERIC) as total + FROM expenses + WHERE year = ${year} AND month = ${month} AND status = ${PaymentStatus.PAYED}::"PaymentStatus" + `; + return { total: Number(result[0]?.total ?? 0) }; } export async function getMonthlyTotals(year: number, month: number) { - const [payed, pending] = await Promise.all([ - prisma.expense.aggregate({ - where: { year, month, status: PaymentStatus.PAYED }, - _sum: { amountPayed: true }, - }), - prisma.expense.aggregate({ - where: { year, month, status: PaymentStatus.PENDING }, - _sum: { amount: true }, - }), - ]); + const result = await prisma.$queryRaw>` + SELECT + (SELECT CAST(SUM("amountPayed") AS NUMERIC) FROM expenses WHERE year = ${year} AND month = ${month} AND status = ${PaymentStatus.PAYED}::"PaymentStatus") as payed, + (SELECT CAST(SUM(amount) AS NUMERIC) FROM expenses WHERE year = ${year} AND month = ${month} AND status = ${PaymentStatus.PENDING}::"PaymentStatus") as pending + `; return { - payed: Number(payed._sum.amountPayed ?? 0), - pending: Number(pending._sum.amount ?? 0), + payed: Number(result[0]?.payed ?? 0), + pending: Number(result[0]?.pending ?? 0), }; } export async function getTotalPending() { - const result = await prisma.expense.aggregate({ - where: { status: PaymentStatus.PENDING }, - _sum: { amount: true }, - }); - return { total: Number(result._sum.amount ?? 0) }; + const result = await prisma.$queryRaw>` + SELECT CAST(SUM(amount) AS NUMERIC) as total + FROM expenses + WHERE status = ${PaymentStatus.PENDING}::"PaymentStatus" + `; + return { total: Number(result[0]?.total ?? 0) }; } export async function generateExpensesForCurrentMonth() {