From 5df6199bd12366742217733bfc4b029049a5b45d Mon Sep 17 00:00:00 2001 From: Jakob Wennberg <149234542+jakobwennberg@users.noreply.github.com> Date: Tue, 30 Jun 2026 16:01:07 +0200 Subject: [PATCH] fix(invoices): remaining_amount + invoice.paid on agent mark-paid path (#825) (#845) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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) * 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) * 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) --------- Co-authored-by: Claude Opus 4.8 (1M context) --- .../[id]/mark-paid/__tests__/route.test.ts | 56 ++++++++- app/api/invoices/[id]/mark-paid/route.ts | 73 ++++++++++-- .../[id]/mark-paid/__tests__/route.test.ts | 40 +++++++ .../invoices/[id]/mark-paid/route.ts | 47 +++++--- .../__tests__/mark-invoice-paid.test.ts | 110 ++++++++++++++++++ lib/pending-operations/commit.ts | 61 +++++++++- 6 files changed, 356 insertions(+), 31 deletions(-) create mode 100644 lib/pending-operations/__tests__/mark-invoice-paid.test.ts diff --git a/app/api/invoices/[id]/mark-paid/__tests__/route.test.ts b/app/api/invoices/[id]/mark-paid/__tests__/route.test.ts index 516596d2..56a3bed9 100644 --- a/app/api/invoices/[id]/mark-paid/__tests__/route.test.ts +++ b/app/api/invoices/[id]/mark-paid/__tests__/route.test.ts @@ -7,6 +7,7 @@ import { makeInvoice, makeCustomer, } from '@/tests/helpers' +import { eventBus } from '@/lib/events' const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase() vi.mock('@/lib/supabase/server', () => ({ @@ -52,6 +53,7 @@ describe('POST /api/invoices/[id]/mark-paid', () => { beforeEach(() => { vi.clearAllMocks() reset() + eventBus.clear() mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } }) }) @@ -134,12 +136,16 @@ describe('POST /api/invoices/[id]/mark-paid', () => { mockCreateInvoicePaymentJournalEntry.mockResolvedValue({ id: 'je-1' }) + const paidHandler = vi.fn() + eventBus.on('invoice.paid', paidHandler) + const request = createMockRequest('/api/invoices/inv-1/mark-paid', { method: 'POST' }) const response = await POST(request, createMockRouteParams({ id: 'inv-1' })) const { status, body } = await parseJsonResponse<{ success: boolean status: string paid_amount: number + remaining_amount: number journal_entry_id: string | null }>(response) @@ -147,7 +153,18 @@ describe('POST /api/invoices/[id]/mark-paid', () => { expect(body.success).toBe(true) expect(body.status).toBe('paid') expect(body.paid_amount).toBe(12500) + expect(body.remaining_amount).toBe(0) expect(body.journal_entry_id).toBe('je-1') + // invoice.paid must fire so registered webhooks fan out (issue #825). + expect(paidHandler).toHaveBeenCalledTimes(1) + expect(paidHandler).toHaveBeenCalledWith( + expect.objectContaining({ + companyId: 'company-1', + userId: 'user-1', + paymentAmount: 12500, + invoice: expect.objectContaining({ id: 'inv-1', status: 'paid', paid_amount: 12500, remaining_amount: 0 }), + }), + ) expect(mockCreateInvoicePaymentJournalEntry).toHaveBeenCalledWith( expect.anything(), 'company-1', @@ -436,11 +453,48 @@ describe('POST /api/invoices/[id]/mark-paid', () => { body: { lines: partialLines }, }) const response = await POST(request, createMockRouteParams({ id: 'inv-1' })) - const { status, body } = await parseJsonResponse<{ success: boolean; journal_entry_id: string }>(response) + const { status, body } = await parseJsonResponse<{ + success: boolean + status: string + paid_amount: number + remaining_amount: number + paid_at: string | null + journal_entry_id: string + }>(response) expect(status).toBe(200) expect(body.success).toBe(true) expect(body.journal_entry_id).toBe('je-partial') + // A 5000 payment on a 12500 invoice → partially_paid, remaining 7500. + expect(body.status).toBe('partially_paid') + expect(body.paid_amount).toBe(5000) + expect(body.remaining_amount).toBe(7500) + expect(body.paid_at).toBeNull() + }) + + it('returns 400 MATCH_AMOUNT_EXCEEDS_REMAINING when custom lines overpay the invoice', async () => { + // No customer → duplicate guard skips; the overpayment guard must reject + // BEFORE any journal entry is created (planInvoicePayment runs first). + const invoice = makeInvoice({ id: 'inv-1', status: 'sent', total: 12500 }) + + enqueue({ data: invoice, error: null }) + + const overpayLines = [ + { account_number: '1930', debit_amount: 15000, credit_amount: 0 }, + { account_number: '1510', debit_amount: 0, credit_amount: 15000 }, + ] + + const request = createMockRequest('/api/invoices/inv-1/mark-paid', { + method: 'POST', + body: { lines: overpayLines }, + }) + const response = await POST(request, createMockRouteParams({ id: 'inv-1' })) + const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response) + + expect(status).toBe(400) + expect((body.error as unknown as { code: string }).code).toBe('MATCH_AMOUNT_EXCEEDS_REMAINING') + expect(mockCreateJournalEntry).not.toHaveBeenCalled() + expect(mockCreateInvoicePaymentJournalEntry).not.toHaveBeenCalled() }) it('surfaces ocr_exact match_reason when tx reference normalizes to invoice_number', async () => { diff --git a/app/api/invoices/[id]/mark-paid/route.ts b/app/api/invoices/[id]/mark-paid/route.ts index 77789214..9f71e8c9 100644 --- a/app/api/invoices/[id]/mark-paid/route.ts +++ b/app/api/invoices/[id]/mark-paid/route.ts @@ -12,6 +12,9 @@ import { ensureInitialized } from '@/lib/init' import { withRouteContext } from '@/lib/api/with-route-context' import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error' import { findDuplicatePaymentCandidatesForInvoice } from '@/lib/invoices/duplicate-payment-candidates' +import { planInvoicePayment } from '@/lib/invoices/apply-invoice-payment' +import { eventBus } from '@/lib/events' +import { roundOre } from '@/lib/money' import type { CreateJournalEntryInput, EntityType, Invoice } from '@/types' ensureInitialized() @@ -89,8 +92,12 @@ export const POST = withRouteContext( // /api/supplier-invoices/[id]/mark-paid. The dialog always sends custom // lines, so the partial-payment skip is gated on total debit vs remaining, // not on the mere presence of customLines. + const invForRemaining = invoice as Invoice & { + remaining_amount?: number | null + paid_amount?: number | null + } const remainingAmount = - (invoice as Invoice & { remaining_amount?: number }).remaining_amount ?? invoice.total + invForRemaining.remaining_amount ?? invoice.total - (invForRemaining.paid_amount ?? 0) const paymentAmount = customLines ? customLines.reduce((s, l) => s + l.debit_amount, 0) : remainingAmount @@ -144,6 +151,30 @@ export const POST = withRouteContext( const invoiceAlreadyBooked = !!(invoice as { journal_entry_id?: string | null }).journal_entry_id const useCashEntry = !invoiceAlreadyBooked && accountingMethod === 'cash' + // Ledger math + overpayment guard via the shared planInvoicePayment helper — + // the same single source of truth the match-invoice flow uses, so the three + // mark-paid surfaces (this route, the v1 API, and the agent commit path) + // cannot drift again. Runs BEFORE any journal entry is created so a doomed + // overpayment never burns a voucher number. paymentAmount and the + // duplicate-payment guard above operate in the booking currency (SEK for + // custom lines); convert to invoice currency for the ledger comparison so a + // foreign-currency invoice isn't falsely rejected as overpaid. + const fxRate = + invoice.currency && invoice.currency !== 'SEK' && invoice.exchange_rate + ? invoice.exchange_rate + : 1 + const paymentAmountInInvoiceCurrency = customLines + ? roundOre(paymentAmount / fxRate) + : paymentAmount + const payment = planInvoicePayment(invoice, paymentAmountInInvoiceCurrency) + if (!payment.ok) { + return errorResponseFromCode('MATCH_AMOUNT_EXCEEDS_REMAINING', opLog, { + requestId, + details: payment.details, + }) + } + const { newPaidAmount, newRemaining, newStatus } = payment.plan + const isRealInvoice = !invoice.document_type || invoice.document_type === 'invoice' let journalEntryId: string | null = null @@ -225,13 +256,14 @@ export const POST = withRouteContext( const { data: updateResult, error: updateError } = await supabase .from('invoices') .update({ - status: 'paid', - paid_at: now, - paid_amount: invoice.total, + status: newStatus, + paid_amount: newPaidAmount, + remaining_amount: newRemaining, + ...(newStatus === 'paid' ? { paid_at: now } : {}), }) .eq('id', id) .eq('company_id', companyId) - .in('status', ['sent', 'overdue']) + .in('status', ['sent', 'overdue', 'partially_paid']) .select('id') if (updateError) { @@ -265,11 +297,36 @@ export const POST = withRouteContext( return errorResponseFromCode('INVOICE_PAID_RACE', opLog, { requestId }) } + // Notify subscribers — invoice.paid fans out to registered webhooks + // (lib/webhooks/handler.ts). Best-effort: the payment is already committed, + // so an emit failure must not fail the request. Mirrors the v1 route. + try { + await eventBus.emit({ + type: 'invoice.paid', + payload: { + invoice: { + ...(invoice as Invoice), + status: newStatus, + paid_amount: newPaidAmount, + remaining_amount: newRemaining, + paid_at: newStatus === 'paid' ? now : (invoice as Invoice).paid_at, + } as Invoice, + companyId: companyId!, + userId: user.id, + paymentAmount: paymentAmountInInvoiceCurrency, + paymentDate, + }, + }) + } catch (err) { + opLog.error('invoice.paid emit failed', err as Error, { invoiceId: id }) + } + return NextResponse.json({ success: true, - status: 'paid', - paid_at: now, - paid_amount: invoice.total, + status: newStatus, + paid_at: newStatus === 'paid' ? now : null, + paid_amount: newPaidAmount, + remaining_amount: newRemaining, journal_entry_id: journalEntryId, }) }, diff --git a/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/__tests__/route.test.ts b/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/__tests__/route.test.ts index 320bc6c9..cd02abd7 100644 --- a/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/__tests__/route.test.ts +++ b/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/__tests__/route.test.ts @@ -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 const mockServiceClient = createServiceClientNoCookies as ReturnType @@ -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({ diff --git a/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/route.ts b/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/route.ts index b93e5734..01f520ee 100644 --- a/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/route.ts +++ b/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/route.ts @@ -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 diff --git a/lib/pending-operations/__tests__/mark-invoice-paid.test.ts b/lib/pending-operations/__tests__/mark-invoice-paid.test.ts new file mode 100644 index 00000000..a0485358 --- /dev/null +++ b/lib/pending-operations/__tests__/mark-invoice-paid.test.ts @@ -0,0 +1,110 @@ +/** + * State + event coverage for the agent/MCP mark-invoice-paid commit path + * (`commitMarkInvoicePaid` in lib/pending-operations/commit.ts). + * + * Regression guard for issue #825: this path previously flipped status to + * 'paid' and set paid_amount = total but never wrote remaining_amount (leaving + * it at the original total) and never emitted invoice.paid (so webhooks never + * fired). It now routes through the shared planInvoicePayment helper and emits + * invoice.paid, matching the dashboard and v1 mark-paid routes. + * + * Duplicate-payment-guard behaviour is covered separately in + * commit-duplicate-guard.test.ts; here the guard is stubbed to "no candidates". + */ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { eventBus } from '@/lib/events/bus' +import { createQueuedMockSupabase } from '@/tests/helpers' +import type { PendingOperation } from '@/types' + +const mockCreatePaymentEntry = vi.fn() +const mockCreateCashEntry = vi.fn() +vi.mock('@/lib/bookkeeping/invoice-entries', async () => { + const actual = await vi.importActual( + '@/lib/bookkeeping/invoice-entries', + ) + return { + ...actual, + createInvoicePaymentJournalEntry: (...args: unknown[]) => mockCreatePaymentEntry(...args), + createInvoiceCashEntry: (...args: unknown[]) => mockCreateCashEntry(...args), + } +}) + +const mockFindDupPayments = vi.fn() +vi.mock('@/lib/invoices/duplicate-payment-candidates', () => ({ + findDuplicatePaymentCandidatesForInvoice: (...args: unknown[]) => mockFindDupPayments(...args), +})) + +import { commitPendingOperation } from '../commit' + +function makePendingOp(overrides: Partial): PendingOperation { + return { + id: 'op-1', + user_id: 'user-1', + company_id: 'company-1', + operation_type: 'mark_invoice_paid', + status: 'pending', + title: 'test', + params: {}, + preview_data: {}, + result_data: null, + actor_type: 'user', + actor_id: null, + actor_label: null, + risk_level: 'medium', + created_at: '2026-05-03T00:00:00Z', + resolved_at: null, + updated_at: '2026-05-03T00:00:00Z', + ...overrides, + } as PendingOperation +} + +beforeEach(() => { + vi.clearAllMocks() + eventBus.clear() + mockFindDupPayments.mockResolvedValue([]) + mockCreatePaymentEntry.mockResolvedValue({ id: 'je-1' }) + mockCreateCashEntry.mockResolvedValue({ id: 'je-1' }) +}) + +describe('commitPendingOperation: mark_invoice_paid state + invoice.paid', () => { + it('zeroes remaining_amount and emits invoice.paid on full payment (issue #825)', async () => { + const { supabase, enqueue } = createQueuedMockSupabase() + enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim + enqueue({ + data: { + id: 'inv-1', + invoice_number: '2026001', + status: 'sent', + total: 525, + remaining_amount: 525, + paid_amount: null, + document_type: 'invoice', + journal_entry_id: null, + customer: { name: 'Test AB' }, + }, + error: null, + }) // invoice fetch + enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' }, error: null }) // settings + enqueue({ data: [{ id: 'inv-1' }], error: null }) // invoice CAS update + enqueue({ data: null, error: null }) // dispatcher pending_operations update + + const paidHandler = vi.fn() + eventBus.on('invoice.paid', paidHandler) + + const op = makePendingOp({ params: { invoice_id: 'inv-1', payment_date: '2026-03-30' } }) + const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op) + + expect(result.status).toBe('committed') + expect(result.data).toMatchObject({ status: 'paid', remaining_amount: 0, journal_entry_id: 'je-1' }) + + expect(paidHandler).toHaveBeenCalledTimes(1) + expect(paidHandler).toHaveBeenCalledWith( + expect.objectContaining({ + companyId: 'company-1', + userId: 'user-1', + paymentAmount: 525, + invoice: expect.objectContaining({ id: 'inv-1', status: 'paid', remaining_amount: 0, paid_amount: 525 }), + }), + ) + }) +}) diff --git a/lib/pending-operations/commit.ts b/lib/pending-operations/commit.ts index 039c7acb..b68cb2d5 100644 --- a/lib/pending-operations/commit.ts +++ b/lib/pending-operations/commit.ts @@ -1017,6 +1017,29 @@ async function commitMarkInvoicePaid( const invoiceAlreadyBooked = !!(invoice as { journal_entry_id?: string | null }).journal_entry_id const useCashEntry = !invoiceAlreadyBooked && accountingMethod === 'cash' + // Paid/remaining/status math + overpayment guard via the shared + // planInvoicePayment helper — the single source of truth across the three + // mark-paid surfaces (this agent path, the dashboard route, and the v1 API). + // This path settles the full remaining (no custom lines), so it can never + // overpay, but routing through the helper keeps the state identical. Runs + // BEFORE the JE below so a rejected payment never burns a voucher number. + // Settle the full outstanding balance. Prefer remaining_amount; for legacy rows + // where it was never written, derive it from total − paid_amount rather than + // falling back to the full total (which would double-count a prior partial + // payment and trip the overpayment guard). + const inv = invoice as { remaining_amount?: number | null; paid_amount?: number | null } + const paymentAmount = inv.remaining_amount ?? (invoice.total - (inv.paid_amount ?? 0)) + const payment = planInvoicePayment(invoice, paymentAmount) + if (!payment.ok) { + return { + error: + getErrorEntry('MATCH_AMOUNT_EXCEEDS_REMAINING')?.message_sv ?? + 'Betalningsbeloppet är större än fakturans återstående belopp.', + status: 400, + } + } + const { newPaidAmount, newRemaining, newStatus } = payment.plan + if (isRealInvoice) { if (useCashEntry) { const je = await createInvoiceCashEntry( @@ -1049,10 +1072,15 @@ async function commitMarkInvoicePaid( // invoice no-ops here instead of double-booking the payment. const { data: updateResult, error: updateError } = await supabase .from('invoices') - .update({ status: 'paid', paid_at: now, paid_amount: invoice.total }) + .update({ + status: newStatus, + paid_amount: newPaidAmount, + remaining_amount: newRemaining, + ...(newStatus === 'paid' ? { paid_at: now } : {}), + }) .eq('id', invoiceId) .eq('company_id', companyId) - .in('status', ['sent', 'overdue']) + .in('status', ['sent', 'overdue', 'partially_paid']) .select('id') if (updateError) { @@ -1078,12 +1106,37 @@ async function commitMarkInvoicePaid( ) } return { - error: 'Invoice can only be marked as paid when status is "sent" or "overdue"', + error: 'Invoice can only be marked as paid from a payable status (sent, overdue or partially paid)', status: 409, } } - return { data: { status: 'paid', journal_entry_id: journalEntryId } } + // Notify subscribers — invoice.paid fans out to registered webhooks + // (lib/webhooks/handler.ts). Best-effort: the payment is already committed, + // so an emit failure must not fail the operation. Parity with the v1 and + // dashboard mark-paid routes, which previously emitted while this path did not. + try { + await eventBus.emit({ + type: 'invoice.paid', + payload: { + invoice: { + ...(invoice as Invoice), + status: newStatus, + paid_amount: newPaidAmount, + remaining_amount: newRemaining, + paid_at: newStatus === 'paid' ? now : (invoice as Invoice).paid_at, + } as Invoice, + companyId, + userId, + paymentAmount, + paymentDate, + }, + }) + } catch (err) { + log.warn('invoice.paid emit failed', err) + } + + return { data: { status: newStatus, remaining_amount: newRemaining, journal_entry_id: journalEntryId } } } async function commitSendInvoice(