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) {
|
export async function getMonthlyPayedTotal(year: number, month: number) {
|
||||||
const result = await prisma.expense.aggregate({
|
const result = await prisma.$queryRaw<Array<{ total: string | null }>>`
|
||||||
where: { year, month, status: PaymentStatus.PAYED },
|
SELECT CAST(SUM("amountPayed") AS NUMERIC) as total
|
||||||
_sum: { amountPayed: true },
|
FROM expenses
|
||||||
});
|
WHERE year = ${year} AND month = ${month} AND status = ${PaymentStatus.PAYED}::"PaymentStatus"
|
||||||
return { total: Number(result._sum.amountPayed ?? 0) };
|
`;
|
||||||
|
return { total: Number(result[0]?.total ?? 0) };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getMonthlyTotals(year: number, month: number) {
|
export async function getMonthlyTotals(year: number, month: number) {
|
||||||
const [payed, pending] = await Promise.all([
|
const result = await prisma.$queryRaw<Array<{ payed: string | null; pending: string | null }>>`
|
||||||
prisma.expense.aggregate({
|
SELECT
|
||||||
where: { year, month, status: PaymentStatus.PAYED },
|
(SELECT CAST(SUM("amountPayed") AS NUMERIC) FROM expenses WHERE year = ${year} AND month = ${month} AND status = ${PaymentStatus.PAYED}::"PaymentStatus") as payed,
|
||||||
_sum: { amountPayed: true },
|
(SELECT CAST(SUM(amount) AS NUMERIC) FROM expenses WHERE year = ${year} AND month = ${month} AND status = ${PaymentStatus.PENDING}::"PaymentStatus") as pending
|
||||||
}),
|
`;
|
||||||
prisma.expense.aggregate({
|
|
||||||
where: { year, month, status: PaymentStatus.PENDING },
|
|
||||||
_sum: { amount: true },
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
return {
|
return {
|
||||||
payed: Number(payed._sum.amountPayed ?? 0),
|
payed: Number(result[0]?.payed ?? 0),
|
||||||
pending: Number(pending._sum.amount ?? 0),
|
pending: Number(result[0]?.pending ?? 0),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getTotalPending() {
|
export async function getTotalPending() {
|
||||||
const result = await prisma.expense.aggregate({
|
const result = await prisma.$queryRaw<Array<{ total: string | null }>>`
|
||||||
where: { status: PaymentStatus.PENDING },
|
SELECT CAST(SUM(amount) AS NUMERIC) as total
|
||||||
_sum: { amount: true },
|
FROM expenses
|
||||||
});
|
WHERE status = ${PaymentStatus.PENDING}::"PaymentStatus"
|
||||||
return { total: Number(result._sum.amount ?? 0) };
|
`;
|
||||||
|
return { total: Number(result[0]?.total ?? 0) };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateExpensesForCurrentMonth() {
|
export async function generateExpensesForCurrentMonth() {
|
||||||
|
|||||||
Reference in New Issue
Block a user