Add INVESTMENT account type with manual portfolio value recording
This commit is contained in:
44
src/app/api/accounts/[id]/record-value/route.ts
Normal file
44
src/app/api/accounts/[id]/record-value/route.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { auth } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
const schema = z.object({
|
||||
valueCents: z.number().int(),
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD'),
|
||||
})
|
||||
|
||||
export async function POST(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const { id } = await params
|
||||
const account = await prisma.account.findFirst({
|
||||
where: { id, userId: session.user.id, type: 'INVESTMENT' },
|
||||
})
|
||||
if (!account) return NextResponse.json({ error: 'Account not found' }, { status: 404 })
|
||||
|
||||
const result = schema.safeParse(await req.json())
|
||||
if (!result.success) return NextResponse.json({ error: result.error.flatten() }, { status: 400 })
|
||||
|
||||
const { valueCents, date } = result.data
|
||||
const d = new Date(date + 'T12:00:00')
|
||||
const year = d.getFullYear()
|
||||
const month = d.getMonth() + 1
|
||||
|
||||
await prisma.account.update({
|
||||
where: { id },
|
||||
data: { currentBalanceCents: valueCents },
|
||||
})
|
||||
|
||||
await prisma.balanceSnapshot.upsert({
|
||||
where: { accountId_year_month: { accountId: id, year, month } },
|
||||
update: { balanceCents: valueCents, computedAt: new Date() },
|
||||
create: { accountId: id, year, month, balanceCents: valueCents },
|
||||
})
|
||||
|
||||
return NextResponse.json({ ok: true })
|
||||
}
|
||||
Reference in New Issue
Block a user