42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { auth } from '@/lib/auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { updateTransactionSchema } from '@/lib/validations/transaction'
|
|
|
|
type Params = { params: Promise<{ id: string }> }
|
|
|
|
export async function PATCH(req: Request, { params }: Params) {
|
|
const session = await auth()
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
const { id } = await params
|
|
const body = await req.json()
|
|
const parsed = updateTransactionSchema.safeParse(body)
|
|
if (!parsed.success) {
|
|
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
|
}
|
|
|
|
// Scope check via the account's userId
|
|
const existing = await prisma.transaction.findFirst({
|
|
where: { id, account: { userId: session.user.id } },
|
|
})
|
|
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
|
|
|
// Validate budgetId belongs to this user if provided
|
|
if (parsed.data.budgetId) {
|
|
const budget = await prisma.budget.findFirst({
|
|
where: { id: parsed.data.budgetId, userId: session.user.id },
|
|
})
|
|
if (!budget) return NextResponse.json({ error: 'Budget not found' }, { status: 404 })
|
|
}
|
|
|
|
const transaction = await prisma.transaction.update({
|
|
where: { id },
|
|
data: parsed.data,
|
|
})
|
|
|
|
return NextResponse.json(transaction)
|
|
}
|