import { useDb } from '~~/server/database/client'; import { expenseParticipants, expenses } from '~~/server/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(event); 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] }; });