import { getQuery, getRouterParam, createError } from 'h3' import { startOfMonth, endOfMonth } from 'date-fns' import { prisma } from '../../utils/db' export default defineEventHandler(async (event) => { const token = getRouterParam(event, 'token')! const query = getQuery(event) 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 link = await prisma.shareLink.findUnique({ where: { token }, include: { user: { select: { id: true, name: true } } } }) if (!link || link.revokedAt || link.expiresAt <= new Date()) { throw createError({ statusCode: 404, statusMessage: 'Share link not found' }) } const [transactions, assets] = await Promise.all([ prisma.transaction.findMany({ where: { userId: link.userId, occurredAt: { gte: monthStart, lte: monthEnd } }, include: { asset: true, category: { include: { parent: true } } }, orderBy: { occurredAt: 'desc' } }), prisma.asset.findMany({ where: { userId: link.userId, active: true }, orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }] }) ]) await prisma.shareLink.update({ where: { id: link.id }, data: { lastViewedAt: new Date() } }) const summary = transactions.reduce((acc, tx) => { acc[tx.type] += tx.amount acc.diff = acc.income - acc.expense return acc }, { income: 0, expense: 0, diff: 0 }) return { owner: link.user.name, name: link.name, expiresAt: link.expiresAt, summary, assets, transactions } })