refactor(expenses): optimize expense aggregation queries for improved performance

This commit is contained in:
Jose Selesan
2026-05-29 19:00:03 -03:00
parent 94aab6dce7
commit 3daf67639a

View File

@@ -146,38 +146,36 @@ export async function payExpense(id: number, data: z.infer<typeof payExpenseSche
} }
export async function getMonthlyPayedTotal(year: number, month: number) { export async function getMonthlyPayedTotal(year: number, month: number) {
const expenses = await prisma.expense.findMany({ const result = await prisma.expense.aggregate({
where: { year, month, status: PaymentStatus.PAYED }, where: { year, month, status: PaymentStatus.PAYED },
select: { amountPayed: true }, _sum: { amountPayed: true },
}); });
const total = expenses.reduce((sum, e) => sum + Number(e.amountPayed ?? 0), 0); return { total: Number(result._sum.amountPayed ?? 0) };
return { total };
} }
export async function getMonthlyTotals(year: number, month: number) { export async function getMonthlyTotals(year: number, month: number) {
const [payed, pending] = await Promise.all([ const [payed, pending] = await Promise.all([
prisma.expense.findMany({ prisma.expense.aggregate({
where: { year, month, status: PaymentStatus.PAYED }, where: { year, month, status: PaymentStatus.PAYED },
select: { amountPayed: true }, _sum: { amountPayed: true },
}), }),
prisma.expense.findMany({ prisma.expense.aggregate({
where: { year, month, status: PaymentStatus.PENDING }, where: { year, month, status: PaymentStatus.PENDING },
select: { amount: true }, _sum: { amount: true },
}), }),
]); ]);
return { return {
payed: payed.reduce((sum, e) => sum + Number(e.amountPayed ?? 0), 0), payed: Number(payed._sum.amountPayed ?? 0),
pending: pending.reduce((sum, e) => sum + Number(e.amount), 0), pending: Number(pending._sum.amount ?? 0),
}; };
} }
export async function getTotalPending() { export async function getTotalPending() {
const expenses = await prisma.expense.findMany({ const result = await prisma.expense.aggregate({
where: { status: PaymentStatus.PENDING }, where: { status: PaymentStatus.PENDING },
select: { amount: true }, _sum: { amount: true },
}); });
const total = expenses.reduce((sum, e) => sum + Number(e.amount), 0); return { total: Number(result._sum.amount ?? 0) };
return { total };
} }
export async function generateExpensesForCurrentMonth() { export async function generateExpensesForCurrentMonth() {