Files
splitt-the-bill/server/api/pots/[slug]/payments.post.ts
T
2026-07-01 15:43:18 +02:00

34 lines
1.3 KiB
TypeScript

import { useDb } from '../../../database/client'
import { expenseParticipants, expenses } from '../../../database/schema'
export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug')!
await getPotOrThrow(slug)
const body = await readBody(event)
const fromId = Number(body?.fromId)
const toId = Number(body?.toId)
const amountCents = Number(body?.amountCents)
if (!Number.isInteger(amountCents) || amountCents <= 0) {
throw createError({ statusCode: 400, statusMessage: 'amountCents must be a positive integer' })
}
if (fromId === toId) {
throw createError({ statusCode: 400, statusMessage: 'fromId and toId must differ' })
}
const potParticipants = await getParticipants(slug)
const validIds = new Set(potParticipants.map(p => p.id))
if (!validIds.has(fromId) || !validIds.has(toId)) {
throw createError({ statusCode: 400, statusMessage: 'fromId and toId must reference participants of this Pot' })
}
const db = useDb()
const [payment] = await db.insert(expenses)
.values({ potSlug: slug, type: 'payment', description: 'Settlement', amountCents, payerId: fromId })
.returning()
await db.insert(expenseParticipants).values({ expenseId: payment.id, participantId: toId })
return { ...payment, participantIds: [toId] }
})