40 lines
1.5 KiB
TypeScript
40 lines
1.5 KiB
TypeScript
import { getQuery } from 'h3'
|
|
import { startOfMonth, endOfMonth } from 'date-fns'
|
|
import { prisma } from '../../utils/db'
|
|
import { requireUser } from '../../utils/auth'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const user = await requireUser(event)
|
|
const query = getQuery(event)
|
|
const includeInactive = query.includeInactive === 'true'
|
|
const month = typeof query.month === 'string' ? query.month : new Date().toISOString().slice(0, 7)
|
|
const monthStart = startOfMonth(new Date(`${month}-01T00:00:00`))
|
|
const monthEnd = endOfMonth(monthStart)
|
|
|
|
const assets = await prisma.asset.findMany({
|
|
where: { userId: user.id, ...(includeInactive ? {} : { active: true }) },
|
|
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }]
|
|
})
|
|
|
|
const balances = await Promise.all(assets.map(async (asset) => {
|
|
const where = {
|
|
userId: user.id,
|
|
assetId: asset.id,
|
|
...(asset.balanceType === 'monthly_reset'
|
|
? { occurredAt: { gte: monthStart, lte: monthEnd } }
|
|
: {})
|
|
}
|
|
const [income, expense] = await Promise.all([
|
|
prisma.transaction.aggregate({ where: { ...where, type: 'income' }, _sum: { amount: true } }),
|
|
prisma.transaction.aggregate({ where: { ...where, type: 'expense' }, _sum: { amount: true } })
|
|
])
|
|
const base = asset.balanceType === 'cumulative' ? asset.initialBalance : 0
|
|
return {
|
|
...asset,
|
|
balance: base + (income._sum.amount || 0) - (expense._sum.amount || 0)
|
|
}
|
|
}))
|
|
|
|
return balances
|
|
})
|