fix(invoices): remaining_amount + invoice.paid on agent mark-paid path (#825) (#845)

* fix(invoices): book remaining_amount + emit invoice.paid on agent mark-paid path (#825)

The agent/MCP commit path commitMarkInvoicePaid flipped status to 'paid' and set
paid_amount = total but never wrote remaining_amount (left at the original total)
and never emitted invoice.paid — so partial state and webhooks diverged from the
dashboard and v1 mark-paid routes.

Route the agent path through the shared planInvoicePayment helper (the source of
truth introduced in #841): compute paid/remaining/status with the overpayment
guard BEFORE booking the JE (so a rejected payment never burns a voucher number),
persist remaining_amount + the partially_paid transition, and best-effort emit
invoice.paid for webhook parity.

Adds lib/pending-operations/__tests__/mark-invoice-paid.test.ts covering the
state + event behaviour of this path.

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

* fix(invoices): address review feedback on agent mark-paid path (#825)

- CAS-guard 409 message now reflects the expanded payable states: the UPDATE
  filter accepts partially_paid (reachable via a concurrent settle race), not
  just sent/overdue.
- Derive the settle amount from total − paid_amount when remaining_amount is
  null (legacy rows) instead of falling back to the full total, so a prior
  partial payment is not double-counted into a false overpayment rejection.

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

* fix(invoices): derive remaining from total − paid_amount on all mark-paid surfaces (#825)

The dashboard and v1 mark-paid routes defaulted the settle amount to invoice.total
when remaining_amount was null, which over-settles a legacy invoice that has a
prior partial payment recorded in paid_amount (false overpayment / AR over-credit).
Align both with the agent path (commit.ts): remaining_amount ?? total − paid_amount.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-30 16:01:07 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 46039f14f4
commit 5df6199bd1
6 changed files with 356 additions and 31 deletions
@@ -48,6 +48,7 @@ import {
createInvoiceCashEntry as mockedCash,
} from '@/lib/bookkeeping/invoice-entries'
import { POST as markPaid } from '../route'
import { eventBus } from '@/lib/events'
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
@@ -137,6 +138,7 @@ const PAID_INVOICE = {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
mockValidate.mockResolvedValue({
userId: USER_ID,
companyId: COMPANY_ID,
@@ -160,6 +162,9 @@ describe('POST /api/v1/companies/:companyId/invoices/:id/mark-paid', () => {
}),
)
const paidHandler = vi.fn()
eventBus.on('invoice.paid', paidHandler)
const res = await markPaid(
makeRequest(
`https://x.test/api/v1/companies/${COMPANY_ID}/invoices/${INVOICE_ID}/mark-paid`,
@@ -175,6 +180,11 @@ describe('POST /api/v1/companies/:companyId/invoices/:id/mark-paid', () => {
expect(body.data.journal_entry_id).toBe('jjjjjjjj-jjjj-4jjj-8jjj-jjjjjjjjjjjj')
expect(mockPayment).toHaveBeenCalled()
expect(mockCash).not.toHaveBeenCalled()
// invoice.paid must fire so registered webhooks fan out (issue #825).
expect(paidHandler).toHaveBeenCalledTimes(1)
expect(paidHandler).toHaveBeenCalledWith(
expect.objectContaining({ companyId: COMPANY_ID, userId: USER_ID, paymentAmount: 12500 }),
)
})
it('uses the cash-basis booking when accounting_method=cash', async () => {
@@ -329,6 +339,36 @@ describe('POST /api/v1/companies/:companyId/invoices/:id/mark-paid', () => {
expect(body.error.code).toBe('INVOICE_PAID_LINES_UNBALANCED')
})
it('returns 400 MATCH_AMOUNT_EXCEEDS_REMAINING when custom lines overpay the invoice', async () => {
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
invoices: { data: SENT_INVOICE, error: null },
company_settings: { data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null },
}),
)
// 15000 paid against a 12500 remaining → shared planInvoicePayment guard
// rejects BEFORE any journal entry is booked.
const res = await markPaid(
makeRequest(
`https://x.test/api/v1/companies/${COMPANY_ID}/invoices/${INVOICE_ID}/mark-paid`,
{
lines: [
{ account_number: '1930', debit_amount: 15000, credit_amount: 0 },
{ account_number: '1510', debit_amount: 0, credit_amount: 15000 },
],
},
),
detailParams(COMPANY_ID, INVOICE_ID),
)
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error.code).toBe('MATCH_AMOUNT_EXCEEDS_REMAINING')
expect(mockPayment).not.toHaveBeenCalled()
})
it('returns 400 INVOICE_PAID_NOT_PAYABLE for draft invoices', async () => {
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
@@ -42,6 +42,8 @@ import { AccountsNotInChartError, isBookkeepingError } from '@/lib/bookkeeping/e
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { eventBus } from '@/lib/events'
import { findDuplicatePaymentCandidatesForInvoice } from '@/lib/invoices/duplicate-payment-candidates'
import { planInvoicePayment } from '@/lib/invoices/apply-invoice-payment'
import { roundOre } from '@/lib/money'
import type { CreateJournalEntryInput, EntityType, Invoice } from '@/types'
const INVOICE_MARK_PAID_RESPONSE_COLUMNS =
@@ -259,27 +261,36 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
// when a concurrent partial payment slips through the pre-flight check
// (pre-flight sees status='sent' but the race-guard UPDATE later sees
// status='partially_paid' so a second full-total amount would be booked
// against an already-reduced AR balance).
// against an already-reduced AR balance). For legacy rows where
// remaining_amount was never written, derive it from total − paid_amount
// rather than the full total. This is the booking-currency amount (SEK for
// custom lines) used by the duplicate guard, the JE builder, and the event.
const paymentAmount = customLines
? customLines.reduce((s, l) => s + l.debit_amount, 0)
: (typed.remaining_amount ?? typed.total)
: (typed.remaining_amount ?? typed.total - (typed.paid_amount ?? 0))
const isPartial =
customLines !== undefined &&
Math.abs(paymentAmount - (typed.remaining_amount ?? typed.total)) > 0.005 // same half-öre epsilon as above
const newRemaining = Math.max(
0,
Math.round(((typed.remaining_amount ?? typed.total) - paymentAmount) * 100) / 100,
)
// 0.005 epsilon = half an öre. After rounding to 2 decimals above,
// newRemaining is in steps of 0.01; values ≤ 0.005 only arise from
// floating-point artefacts (e.g. 0.0000000001 from a SEK 99.99 payment
// against a SEK 99.99 invoice). Treating those as 'paid' avoids
// permanently-partially_paid invoices on full payment.
const newStatus: 'paid' | 'partially_paid' = newRemaining <= 0.005 ? 'paid' : 'partially_paid'
const newPaidAmount =
Math.round(((typed.paid_amount ?? 0) + paymentAmount) * 100) / 100
// Ledger math + overpayment guard via the shared planInvoicePayment helper —
// the single source of truth across all three mark-paid surfaces (this route,
// the dashboard route, and the agent commit path), so the paid/remaining/
// status math can never drift again. Custom lines are SEK; convert to invoice
// currency for the comparison so a foreign-currency invoice isn't falsely
// rejected as overpaid (the default path is already in invoice currency).
const fxRate =
typed.currency && typed.currency !== 'SEK' && typed.exchange_rate
? typed.exchange_rate
: 1
const paymentAmountInInvoiceCurrency = customLines
? roundOre(paymentAmount / fxRate)
: paymentAmount
const payment = planInvoicePayment(typed, paymentAmountInInvoiceCurrency)
if (!payment.ok) {
return v1ErrorResponseFromCode('MATCH_AMOUNT_EXCEEDS_REMAINING', ctx.log, {
requestId: ctx.requestId,
details: payment.details,
})
}
const { newPaidAmount, newRemaining, newStatus, isFullyPaid } = payment.plan
const isPartial = customLines !== undefined && !isFullyPaid
// Duplicate-payment guard: surface a likely-matching unlinked inbound
// bank transaction before booking (or before dry-run preview, so a