refactor(expenses): optimize monthly totals and pending calculations using raw SQL queries
This commit is contained in:
@@ -146,36 +146,33 @@ export async function payExpense(id: number, data: z.infer<typeof payExpenseSche
|
||||
}
|
||||
|
||||
export async function getMonthlyPayedTotal(year: number, month: number) {
|
||||
const result = await prisma.expense.aggregate({
|
||||
where: { year, month, status: PaymentStatus.PAYED },
|
||||
_sum: { amountPayed: true },
|
||||
});
|
||||
return { total: Number(result._sum.amountPayed ?? 0) };
|
||||
const result = await prisma.$queryRaw<Array<{ total: string | null }>>`
|
||||
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<Array<{ payed: string | null; pending: string | null }>>`
|
||||
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<Array<{ total: string | null }>>`
|
||||
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() {
|
||||
|
||||
Reference in New Issue
Block a user