Files
accounted/app/api/transactions/batch-match-invoices/route.ts
T
Jakob WennbergandClaude Opus 4.6 7c3518a080 feat: payment matching audit trail and partial payments (#89)
* feat: payment matching audit trail, partial payments, and match improvements

- Add payment_match_log table (append-only audit trail per BFL 7:1) with
  immutability triggers and proper RLS
- Add invoice_payments table for partial payment tracking, mirroring
  supplier_invoice_payments pattern
- Add remaining_amount column + partially_paid status to invoices
- Add match-log.ts service for recording match/unmatch state transitions
- Improve match-invoice route: support partial payments, record audit log,
  emit payment.matched events, handle storno conflicts
- Improve match-supplier-invoice route: audit logging, partial payment support
- Update invoice-entries.ts for partial payment journal entries
- Update transaction ingest to detect and auto-suggest invoice matches
- Update bank-reconciliation to handle partial payment state
- Add invoice_payments, payment_match_log types and helpers
- Extend tests for match-invoice route and transaction ingest

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address review feedback — payment matching correctness bugs

- P1: Return 500 on non-23505 payment insert failures instead of
  silently continuing with corrupted invoice state (both routes)
- P1: Fix foreign-currency partial payment matching — use proportional
  remaining SEK amount instead of full total_sek
- P2: Check error when clearing journal_entry_id after storno
- P2: Add updated_at column + trigger to invoice_payments table
- P2: Make supplier_invoice_payments.user_id NOT NULL after backfill

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 13:00:37 +01:00

66 lines
1.7 KiB
TypeScript

import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { getBestInvoiceMatch } from '@/lib/invoices/invoice-matching'
import type { Transaction } from '@/types'
/**
* POST /api/transactions/batch-match-invoices
* Run invoice matching for all uncategorized income transactions without potential_invoice_id
*/
export async function POST() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Fetch uncategorized income transactions without a potential match
const { data: transactions, error: txError } = await supabase
.from('transactions')
.select('*')
.eq('user_id', user.id)
.is('is_business', null)
.gt('amount', 0)
.is('potential_invoice_id', null)
.is('invoice_id', null)
.order('date', { ascending: false })
.limit(50)
if (txError || !transactions) {
return NextResponse.json({ error: 'Failed to fetch transactions' }, { status: 500 })
}
let matched = 0
const matchedInvoiceIds = new Set<string>()
for (const tx of transactions) {
try {
const bestMatch = await getBestInvoiceMatch(
supabase,
user.id,
tx as Transaction,
0.50
)
if (bestMatch && !matchedInvoiceIds.has(bestMatch.invoice.id)) {
await supabase
.from('transactions')
.update({ potential_invoice_id: bestMatch.invoice.id })
.eq('id', tx.id)
matchedInvoiceIds.add(bestMatch.invoice.id)
matched++
}
} catch {
// Continue with other transactions
}
}
return NextResponse.json({
processed: transactions.length,
matched,
})
}