* fix(invoices): remaining_amount can no longer be inserted as 0 on an unpaid invoice remaining_amount is NOT NULL DEFAULT 0 and every payment surface (payment dialog, bank match, Stripe sync, agent mark-paid) reads it as the customer's open balance. Four writers omitted it, so their invoices looked settled: the dialog rejected every payment as an overpayment and the bank match saw nothing to clear. Prod carried 337 such open invoices on 2026-08-17 (backfilled the same day, snapshot in _backfill_remaining_20260817). - Migration 20260817191708: BEFORE INSERT trigger invoices_derive_remaining_amount. When remaining_amount is NULL/0 on a real invoice (document_type invoice, not a credit note) with total > 0 and a status that still owes money, it becomes total - paid_amount - deduction_total (>= 0). The ROT/RUT share is a 1513 receivable on Skatteverket, never the customer's, exactly as buildInvoiceWriteData computes it. INSERT only: settlement code owns updates and legitimately writes 0 when paid in full. - pg-real test: derivation, explicit value respected, paid/prior/deduction arithmetic, drafts + overdue, paid/cancelled keep 0, credit notes and proformas untouched, never negative. - Writers fixed as well: proforma -> invoice conversion (dashboard route and MCP commitConvertInvoice), MCP commitCreateInvoice, sandbox seed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(sandbox): every row in the seed invoice batch carries remaining_amount + paid_amount PostgREST normalises a bulk insert to the union of keys, so a row that omits a column the others set arrives as NULL, not as the default. Keep the draft row on the same contract as the rest of the batch (CodeRabbit). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
166 lines
5.8 KiB
TypeScript
166 lines
5.8 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { eventBus } from '@/lib/events'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
|
import type { Invoice } from '@/types'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
|
|
ensureInitialized()
|
|
|
|
/**
|
|
* POST /api/invoices/[id]/convert
|
|
*
|
|
* Converts a proforma invoice to a real invoice.
|
|
* Copies all data, generates a real invoice number, and marks the proforma as cancelled.
|
|
*
|
|
* Ordering note: ensureInvoiceNumber() is the LAST side effect. The F-series
|
|
* counter only advances after items are inserted and the proforma is marked
|
|
* cancelled, so a partial failure in any earlier step rolls back the orphan
|
|
* row without leaking a number.
|
|
*/
|
|
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
|
'invoice.convert',
|
|
async (request, { supabase, user, companyId }, { params }) => {
|
|
const { id } = await params
|
|
|
|
const { data: proforma, error: proformaError } = await supabase
|
|
.from('invoices')
|
|
.select('*, items:invoice_items(*)')
|
|
.eq('id', id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (proformaError || !proforma) {
|
|
return NextResponse.json({ error: 'Proformafakturan hittades inte' }, { status: 404 })
|
|
}
|
|
|
|
if (proforma.document_type !== 'proforma') {
|
|
return NextResponse.json(
|
|
{ error: 'Endast proformafakturor kan konverteras' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
if (proforma.status === 'cancelled') {
|
|
return NextResponse.json(
|
|
{ error: 'Denna proformafaktura har redan makuleras' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const { data: invoice, error: invoiceError } = await supabase
|
|
.from('invoices')
|
|
.insert({
|
|
user_id: user.id,
|
|
company_id: companyId,
|
|
customer_id: proforma.customer_id,
|
|
invoice_number: null,
|
|
invoice_date: new Date().toISOString().split('T')[0],
|
|
due_date: proforma.due_date,
|
|
currency: proforma.currency,
|
|
exchange_rate: proforma.exchange_rate,
|
|
exchange_rate_date: proforma.exchange_rate_date,
|
|
subtotal: proforma.subtotal,
|
|
subtotal_sek: proforma.subtotal_sek,
|
|
vat_amount: proforma.vat_amount,
|
|
vat_amount_sek: proforma.vat_amount_sek,
|
|
total: proforma.total,
|
|
total_sek: proforma.total_sek,
|
|
// The converted invoice is a fresh unpaid receivable: proformas carry no
|
|
// ROT/RUT deduction, so the customer owes the full total. Omitting this
|
|
// left the NOT NULL DEFAULT 0, which every payment surface reads as
|
|
// "nothing open" (dialog overpayment rejection, bank match sees 0).
|
|
remaining_amount: proforma.total,
|
|
paid_amount: 0,
|
|
vat_treatment: proforma.vat_treatment,
|
|
vat_rate: proforma.vat_rate,
|
|
moms_ruta: proforma.moms_ruta,
|
|
reverse_charge_text: proforma.reverse_charge_text,
|
|
your_reference: proforma.your_reference,
|
|
our_reference: proforma.our_reference,
|
|
notes: proforma.notes,
|
|
document_type: 'invoice',
|
|
converted_from_id: id,
|
|
// Dimensions PR7: the converted invoice books with the proforma's bag.
|
|
default_dimensions: proforma.default_dimensions ?? {},
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (invoiceError) {
|
|
return NextResponse.json({ error: getUserErrorMessage(invoiceError) }, { status: 500 })
|
|
}
|
|
|
|
const items = (proforma.items || []).map((item: { sort_order: number; line_type?: 'product' | 'text'; description: string; quantity: number; unit: string; unit_price: number; line_total: number; dimensions?: Record<string, string> }) => ({
|
|
invoice_id: invoice.id,
|
|
sort_order: item.sort_order,
|
|
line_type: item.line_type ?? 'product',
|
|
description: item.description,
|
|
quantity: item.quantity,
|
|
unit: item.unit,
|
|
unit_price: item.unit_price,
|
|
line_total: item.line_total,
|
|
dimensions: item.dimensions ?? {},
|
|
}))
|
|
|
|
if (items.length > 0) {
|
|
const { error: itemsError } = await supabase
|
|
.from('invoice_items')
|
|
.insert(items)
|
|
|
|
if (itemsError) {
|
|
await supabase.from('invoices').delete().eq('id', invoice.id)
|
|
return NextResponse.json({ error: getUserErrorMessage(itemsError) }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
// Cancel the proforma. If this fails, the new (still unnumbered) invoice
|
|
// is an orphan: delete it so the user can retry without ending up with
|
|
// two active invoices for the same proforma. invoice_items cascade.
|
|
const previousProformaStatus = proforma.status
|
|
const { error: cancelError } = await supabase
|
|
.from('invoices')
|
|
.update({ status: 'cancelled' })
|
|
.eq('id', id)
|
|
|
|
if (cancelError) {
|
|
await supabase.from('invoices').delete().eq('id', invoice.id)
|
|
return NextResponse.json({ error: getUserErrorMessage(cancelError) }, { status: 500 })
|
|
}
|
|
|
|
// Allocate the F-series number last. If allocation fails, restore the
|
|
// proforma's previous status and delete the orphan invoice. The F-counter
|
|
// is unaffected because generate_invoice_number only commits on success.
|
|
try {
|
|
await ensureInvoiceNumber(supabase, companyId, invoice as Invoice)
|
|
} catch (err) {
|
|
await supabase
|
|
.from('invoices')
|
|
.update({ status: previousProformaStatus })
|
|
.eq('id', id)
|
|
await supabase.from('invoices').delete().eq('id', invoice.id)
|
|
return NextResponse.json(
|
|
{ error: err instanceof Error ? getUserErrorMessage(err) : 'Failed to assign invoice number' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
|
|
const { data: completeInvoice } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*)')
|
|
.eq('id', invoice.id)
|
|
.single()
|
|
|
|
if (completeInvoice) {
|
|
await eventBus.emit({
|
|
type: 'invoice.created',
|
|
payload: { invoice: completeInvoice as Invoice, companyId, userId: user.id },
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({ data: completeInvoice })
|
|
},
|
|
{ requireWrite: true },
|
|
)
|