Client side catches it immediately (case-insensitive match against existing rules) and shows an inline error. API also rejects with 409 as the authoritative guard. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
43 lines
1.6 KiB
TypeScript
43 lines
1.6 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { auth } from '@/lib/auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { createBudgetRuleSchema } from '@/lib/validations/budget-rule'
|
|
|
|
export async function GET() {
|
|
const session = await auth()
|
|
if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const rules = await prisma.budgetRule.findMany({
|
|
where: { userId: session.user.id },
|
|
orderBy: { createdAt: 'asc' },
|
|
select: { id: true, budgetId: true, pattern: true },
|
|
})
|
|
return NextResponse.json(rules)
|
|
}
|
|
|
|
export async function POST(req: Request) {
|
|
const session = await auth()
|
|
if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const body = await req.json()
|
|
const parsed = createBudgetRuleSchema.safeParse(body)
|
|
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
|
|
|
const { budgetId, pattern } = parsed.data
|
|
|
|
// Verify budget belongs to this user
|
|
const budget = await prisma.budget.findFirst({ where: { id: budgetId, userId: session.user.id } })
|
|
if (!budget) return NextResponse.json({ error: 'Budget not found' }, { status: 404 })
|
|
|
|
const existing = await prisma.budgetRule.findFirst({
|
|
where: { budgetId, pattern: { equals: pattern, mode: 'insensitive' } },
|
|
})
|
|
if (existing) return NextResponse.json({ error: 'Duplicate rule pattern' }, { status: 409 })
|
|
|
|
const rule = await prisma.budgetRule.create({
|
|
data: { userId: session.user.id, budgetId, pattern },
|
|
select: { id: true, budgetId: true, pattern: true },
|
|
})
|
|
return NextResponse.json(rule, { status: 201 })
|
|
}
|