* fix(invoices): reminders, AR ledger, AR reconciliation and deadlines only read fakturor The overdue-reminder run, the kundreskontra, the 1510 reconciliation and the deadlines page selected invoices by status alone. A sent proforma past its due date was chased with a betalningspaminnelse and flipped to 'overdue', and it appeared as a receivable. All four now filter document_type = 'invoice', which is also the precondition for adding quotes (offert): a quote carries a date but never a receivable. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * feat(invoices): offert (quote) document type with its own OF-series, decisions and conversion Adds document_type 'quote' with valid_until, quote_status (open / accepted / declined; expired is derived from valid_until, never stored) and quote_decided_at. Quotes are numbered OF-nnn at insert from company_settings.next_quote_number via generate_quote_number(), the same pattern as delivery notes, so a declined quote never leaves a hole in the F-series the way a proforma does. The column next_quote_number already existed on prod and staging without a migration; the migration adopts it. Engine: build-invoice-write writes the quote columns and keeps remaining_amount at 0; the draft editor refuses accepted or declined quotes; PATCH refuses changing a quote's or delivery note's document type since the number belongs to the series; mark-paid refuses quotes. New POST /api/invoices/[id]/quote-status records the decision and locks once an invoice exists. Conversion is extracted into lib/invoices/convert-to-invoice.ts (one implementation for the route and the MCP staged commit, which had drifted): a converted quote stays and flips to accepted, the invoice links back via converted_from_id and gets its due date from the customer's payment terms; a declined or already invoiced quote is refused. next-number previews the OF-series for quotes. Migration applied to the staging branch and registered as 20260902140000; the pg test runs in CI (pg-real). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * feat(invoices): quote PDF, email and filename surfaces The customer-facing surfaces get a quote sibling for every proforma branch: PDF title OFFERT / QUOTE with Offertdatum and Giltig till instead of the due date, a notice that the document is not an invoice or a payment request, and no payment box, OCR, bankgiro, Swish, QR or payment link. The email says the quote is attached and valid until the expiry, drops the payment details and pay-online button, and asks about the quote rather than the invoice. Filenames read "Offert nr OF-001". Seller VAT number and payment accounts are skipped for quotes as for proformas: a quote is not a faktura under ML 17 kap. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * feat(invoices): offert in the editor, list and detail pages Editor: "Offert" document type with a required "Giltig till" field (default today + 30 days) in place of the due date; the wire body mirrors it into due_date so the shared schema is satisfied. Payment link, ROT/RUT, periodisering and the bank box are already gated on real invoices. The type cannot be switched on an existing quote (its OF-number belongs to the series). List: an Offerter tab beside Proforma, "Ny offert" in the split button, and a status column that shows the decision or the derived expiry: Utgången and Avböjd are exception chips, Öppen and Accepterad muted text. Detail: Acceptera and Skapa faktura in the header, Avböj in the overflow menu; an expired quote asks before accepting or invoicing (bypassable); once an invoice exists the page links to it as Fakturerad and hides the decision actions. Strings in both sv and en. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * feat(mcp,v1): expose offert on the MCP tools and the v1 REST surface MCP: create_invoice takes document_type quote with a required valid_until and allocates the OF-number at insert; the convert tool keeps its id and accepts quotes with the registry refusal codes; new set_quote_status; list_invoices and get_invoice expose valid_until and the effective quote status, including a derived expired filter. The tools/list payload stays under its ceiling without a ledger change. The MCP staged convert now uses the shared converter. v1: POST /invoices/{id}/quote-status (registered in the endpoint registry, scope map and route loader), valid_until and quote_status in the list, create and detail shapes, and a quote_status list filter. Skill atoms mention offert. Decision log lines for the own number series, derived expiry, accepted-not-cancelled conversion and the header action layout. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * test(invoices): pass route params and period id in the new quote tests Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * refactor(invoices): literal update payloads in the converter so the phantom-column guard can read them Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * fix(invoices): close the quote review findings in one pass Skeptics (correctness, compliance, regression) and CodeRabbit on #2163: - quote_status is no longer a write-builder output, so a v1 PATCH or MCP update_invoice can never reset a recorded accept/decline; new quotes are opened by the invoices_quote_defaults trigger (20260902141000), which also keeps due_date and valid_until equal. v1 PATCH and the MCP update executor now use the shared editable-draft predicate. - One live invoice per converted source, enforced by a partial unique index; the converter maps 23505 to INVOICE_QUOTE_ALREADY_INVOICED and both quote-status routes compare-and-set on the decision they read. - MCP-created quotes carry remaining_amount 0; mark-paid, transaction match and voucher link refuse non-invoices on the MCP staging tools, the executors and the dashboard link route. - Conversion of a foreign-currency source refetches the rate for the conversion day (ML 8 kap 21-23 paragraphs) and fails closed without one; 0-day payment terms mean due on receipt. - bulk-create refuses quotes per item; list_invoices rejects a quote_status filter combined with another document_type; an omitted document_type on PATCH means unchanged. - attention, push notifications, open-AR count, FX revaluation, year-end and accrual auto-detect and bank-match suggestions only read fakturor. - Quote PDF and email print Summa / Total instead of Att betala. - Regenerated skills/accounted-api for the new v1 endpoint. Declined with reasons in DECISIONS.md: NOT VALID + VALIDATE and CONCURRENTLY on the migrations (repo precedent, 13.8k rows, transactional apply); re-validating VAT treatment at conversion (the converted invoice is a draft the user reviews; follow-up). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs * fix(invoices): second review round: migration versions, order links, batch allocation, races - Migrations renamed to 20260902220000 / 20260902221000: #2166 shipped its own 20260902141000 to prod while this PR was in review and prod's head moved past both files; below-head versions are skipped by branching, which would have left the quote trigger off prod. Staging rows renamed. - Quote lines never carry sales_order_item_id (an offer must not count as invoiced kundorder quantity); the converter carries a proforma line's order link onto the invoice. - Converter compare-and-sets the source (proforma cancel, quote accept): a concurrent cancel, proforma-to-order conversion or decision removes the orphan invoice with INVOICE_CONVERT_SOURCE_CHANGED instead of a second document for the same sale. - MCP set_quote_status gets the same compare-and-set as the HTTP routes; 0-row updates report INVOICE_QUOTE_CHANGED_CONCURRENTLY everywhere. quote-status (dashboard, v1, MCP) accepts valid_until so an expired sent quote can be reopened, as the docs promised. - MCP mark-paid refuses only quotes, parity with the dashboard route (a sent proforma marked paid is a supported prepayment record). - Batch allocation (dashboard route and MCP tool) refuses non-invoices before the RPC, which gates on status alone. - Customer AR drill-down, v1 customer open invoices and archive guard, and the calendar feed read fakturor only. - Draft quote PDF says "UTKAST" instead of "not a valid invoice"; the editor locks the document type on existing quotes and delivery notes. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs * chore(invoices): use roundOre in the quote MCP summaries and FX test after main tightened the guard baseline Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs * fix(invoices): third review round: atomic decision lock, viewer gate, lookup errors, quote payment terms - 20260902222000: BEFORE UPDATE trigger locks an accepted quote while a live converted invoice exists (the compare-and-set in the three decision writers could still be beaten by a conversion landing in between); the routes and the MCP tool map the raise to 409 INVOICE_QUOTE_ALREADY_INVOICED. generate_quote_number now also requires a non-viewer membership so a viewer's session token cannot burn OF-numbers through PostgREST. - Converter checks quote eligibility before the Riksbanken call and treats a failed company_settings read as a failure instead of a 30-day default. - Re-sending the same decision keeps quote_decided_at (idempotent). - gnubok_find_voucher_candidates_for_invoice refuses non-invoices like its write sibling; the dashboard link route surfaces a failed lookup. - Late-fee and credit-term texts never print on a quote. Applied and registered on staging; pg tests added. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs * fix(invoices): review nits: fail-closed batch lookup, dry-run expiry, quote heading, quote-date CHECK - match-batch surfaces a failed document lookup instead of allocating. - v1 quote-status dry-run preview carries the new valid_until. - Quote PDF heading reads Offertinformation / Quote information. - 20260902222000 also pins the date invariants the trigger maintains as a CHECK: a quote always has valid_until = due_date, nothing else has one. Applied on staging. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
508 lines
21 KiB
TypeScript
508 lines
21 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { eventBus } from '@/lib/events'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { CreateInvoiceSchema, CreateCreditNoteSchema } from '@/lib/api/schemas'
|
|
import type { Invoice, InvoiceDocumentType, InvoiceItem } from '@/types'
|
|
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
|
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
|
|
import { buildCreditNoteItem } from '@/lib/invoices/build-credit-note-item'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import type { Logger } from '@/lib/logger'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { maskEmbeddedCustomer } from '@/lib/customers/protect-personal-number'
|
|
|
|
ensureInitialized()
|
|
|
|
export const GET = withRouteContext(
|
|
'invoice.list',
|
|
async (request, ctx) => {
|
|
const { supabase, companyId, log, requestId } = ctx
|
|
|
|
const { searchParams } = new URL(request.url)
|
|
const status = searchParams.get('status')
|
|
const limit = parseInt(searchParams.get('limit') || '50')
|
|
const offset = parseInt(searchParams.get('offset') || '0')
|
|
|
|
let query = supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*)', { count: 'exact' })
|
|
.eq('company_id', companyId)
|
|
.order('invoice_date', { ascending: false })
|
|
.range(offset, offset + limit - 1)
|
|
|
|
if (status) {
|
|
query = query.eq('status', status)
|
|
}
|
|
// Kundorder detail: the invoices created from one order.
|
|
const salesOrderId = searchParams.get('sales_order_id')
|
|
if (salesOrderId && /^[0-9a-f-]{36}$/i.test(salesOrderId)) {
|
|
query = query.eq('sales_order_id', salesOrderId)
|
|
}
|
|
|
|
const { data, error, count } = await query
|
|
|
|
if (error) {
|
|
log.error('failed to list invoices', error)
|
|
return errorResponse(error, log, { requestId })
|
|
}
|
|
|
|
// Mask the embedded customer's personnummer: the customers(*) join
|
|
// carries the stored ciphertext, which has no business reaching a client.
|
|
return NextResponse.json({ data: (data ?? []).map(maskEmbeddedCustomer), count })
|
|
},
|
|
)
|
|
|
|
export const POST = withRouteContext(
|
|
'invoice.create',
|
|
async (request, ctx) => {
|
|
const { user, supabase, companyId, log, requestId } = ctx
|
|
|
|
let rawBody: unknown
|
|
try {
|
|
rawBody = await request.json()
|
|
} catch {
|
|
log.warn('invalid json body', { kind: 'json' })
|
|
return NextResponse.json(
|
|
{ error: 'Invalid JSON in request body', type: 'validation_error' },
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
|
|
if (typeof rawBody === 'object' && rawBody !== null && 'credited_invoice_id' in rawBody) {
|
|
const parsed = CreateCreditNoteSchema.safeParse(rawBody)
|
|
if (!parsed.success) {
|
|
log.warn('credit note validation failed', {
|
|
issueCount: parsed.error.issues.length,
|
|
})
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Validation failed',
|
|
type: 'validation_error',
|
|
errors: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message, code: i.code })),
|
|
},
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
return createCreditNote(supabase, companyId!, user.id, parsed.data, log, requestId)
|
|
}
|
|
|
|
const parsed = CreateInvoiceSchema.safeParse(rawBody)
|
|
if (!parsed.success) {
|
|
log.warn('invoice validation failed', { issueCount: parsed.error.issues.length })
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Validation failed',
|
|
type: 'validation_error',
|
|
errors: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message, code: i.code })),
|
|
},
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
const invoiceInput = parsed.data
|
|
const documentType: InvoiceDocumentType = invoiceInput.document_type || 'invoice'
|
|
|
|
const { data: customer, error: customerError } = await supabase
|
|
.from('customers')
|
|
.select('*')
|
|
.eq('id', invoiceInput.customer_id)
|
|
.eq('company_id', companyId!)
|
|
.single()
|
|
|
|
if (customerError || !customer) {
|
|
return errorResponseFromCode('INVOICE_CUSTOMER_NOT_FOUND', log, {
|
|
requestId,
|
|
details: { customerId: invoiceInput.customer_id },
|
|
})
|
|
}
|
|
|
|
// Shared validation + computation (VAT rules, accrual guards, totals,
|
|
// revenue-account override checks, server-side ROT/RUT, currency, item
|
|
// rows). Identical to the PATCH (draft edit) path: see build-invoice-write.
|
|
const build = await buildInvoiceWriteData({
|
|
supabase,
|
|
companyId: companyId!,
|
|
customer,
|
|
documentType,
|
|
input: invoiceInput,
|
|
})
|
|
if (!build.ok) {
|
|
if ('dbError' in build) {
|
|
log.error('invoice write build failed on a DB lookup', build.dbError as Error)
|
|
return errorResponse(build.dbError, log, { requestId })
|
|
}
|
|
return errorResponseFromCode(build.code, log, { requestId, details: build.details })
|
|
}
|
|
|
|
// Delivery notes and quotes are always numbered at insert from their own
|
|
// series (ignores save_as_draft): neither is a faktura, so no F-number is
|
|
// at stake. Invoices/proformas get their F-number below or at finalize.
|
|
let invoiceNumber: string | null = null
|
|
if (documentType === 'delivery_note') {
|
|
const { data: dnNumber } = await supabase.rpc('generate_delivery_note_number', {
|
|
p_company_id: companyId,
|
|
})
|
|
invoiceNumber = dnNumber
|
|
} else if (documentType === 'quote') {
|
|
const { data: quoteNumber, error: quoteNumberError } = await supabase.rpc('generate_quote_number', {
|
|
p_company_id: companyId,
|
|
})
|
|
if (quoteNumberError || !quoteNumber) {
|
|
log.error('quote number allocation failed', quoteNumberError ?? new Error('no number'))
|
|
return errorResponseFromCode('INVOICE_CREATE_NUMBER_ASSIGN_FAILED', log, { requestId })
|
|
}
|
|
invoiceNumber = quoteNumber
|
|
}
|
|
|
|
const { data: invoice, error: invoiceError } = await supabase
|
|
.from('invoices')
|
|
.insert({
|
|
user_id: user.id,
|
|
company_id: companyId,
|
|
invoice_number: invoiceNumber,
|
|
...build.invoiceFields,
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (invoiceError) {
|
|
log.error('invoice insert failed', invoiceError)
|
|
return errorResponseFromCode('INVOICE_CREATE_INSERT_FAILED', log, {
|
|
requestId,
|
|
details: { pgCode: invoiceError.code, pgMessage: getUserErrorMessage(invoiceError) },
|
|
})
|
|
}
|
|
|
|
const items = build.items.map((item) => ({ ...item, invoice_id: invoice.id }))
|
|
|
|
const { error: itemsError } = await supabase.from('invoice_items').insert(items)
|
|
|
|
if (itemsError) {
|
|
// Roll back invoice insert; otherwise the row is orphaned.
|
|
await supabase.from('invoices').delete().eq('id', invoice.id)
|
|
log.error('invoice items insert failed; rolled back invoice', itemsError, {
|
|
invoiceId: invoice.id,
|
|
})
|
|
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', log, {
|
|
requestId,
|
|
details: { pgCode: itemsError.code, pgMessage: getUserErrorMessage(itemsError) },
|
|
})
|
|
}
|
|
|
|
// Allocate the F-series number on save (Fortnox-style): UNLESS the caller
|
|
// asked to save as an unnumbered draft. A direct create gives the user a
|
|
// numbered draft they can download and send manually; "Spara som utkast"
|
|
// (save_as_draft) defers numbering to the explicit "Granska och skapa" step
|
|
// (POST /invoices/{id}/finalize) so the draft can be hard-deleted with no
|
|
// gap in the F-series per ML 17 kap 24§. Delivery notes are always numbered
|
|
// at insert above and ignore the flag.
|
|
if (!invoiceInput.save_as_draft && (documentType === 'invoice' || documentType === 'proforma')) {
|
|
try {
|
|
await ensureInvoiceNumber(supabase, companyId!, invoice as Invoice)
|
|
} catch (err) {
|
|
// Soft-cancel rather than hard-delete: if generate_invoice_number bumped
|
|
// the sequence before failing to write the number back, hard-deleting
|
|
// would leave a permanent gap in the F-series in violation of ML 17 kap
|
|
// 24§. Re-fetch the row to pick up any partially-written number, then
|
|
// flip status='cancelled' so the row (and any allocated number) is
|
|
// retained for audit. Log loudly if the cancel itself fails so an
|
|
// operator can clean up.
|
|
const { data: latest } = await supabase
|
|
.from('invoices')
|
|
.select('invoice_number')
|
|
.eq('id', invoice.id)
|
|
.single()
|
|
// Guard on status='draft' for symmetry with the DELETE handler: only
|
|
// drafts may be cancelled. At this point in the create flow the row
|
|
// can't realistically be anything else, but the symmetry prevents a
|
|
// future caller adding a status flip between insert and number-
|
|
// allocation from accidentally cancelling a posted invoice.
|
|
const { error: cancelErr } = await supabase
|
|
.from('invoices')
|
|
.update({ status: 'cancelled', updated_at: new Date().toISOString() })
|
|
.eq('id', invoice.id)
|
|
.eq('company_id', companyId!)
|
|
.eq('status', 'draft')
|
|
if (cancelErr) {
|
|
log.error('invoice number allocation failed AND rollback-cancel failed; row may be orphaned', cancelErr, {
|
|
invoiceId: invoice.id,
|
|
allocatedNumber: latest?.invoice_number ?? null,
|
|
originalError: (err as Error).message,
|
|
})
|
|
} else {
|
|
log.error('invoice number allocation failed; invoice soft-cancelled', err as Error, {
|
|
invoiceId: invoice.id,
|
|
allocatedNumber: latest?.invoice_number ?? null,
|
|
})
|
|
}
|
|
return errorResponseFromCode('INVOICE_CREATE_NUMBER_ASSIGN_FAILED', log, {
|
|
requestId,
|
|
})
|
|
}
|
|
}
|
|
|
|
const { data: completeInvoice } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*)')
|
|
.eq('id', invoice.id)
|
|
.single()
|
|
|
|
// Emit event only for real, issued invoices. Unnumbered drafts (save_as_draft)
|
|
// are not issued yet: the invoice.created event (which drives webhooks and the
|
|
// audit log) fires when the user finalizes via "Granska och skapa".
|
|
if (completeInvoice && documentType === 'invoice' && !invoiceInput.save_as_draft) {
|
|
await eventBus.emit({
|
|
type: 'invoice.created',
|
|
payload: { invoice: completeInvoice as Invoice, companyId: companyId!, userId: user.id },
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({ data: maskEmbeddedCustomer(completeInvoice) })
|
|
},
|
|
{ requireWrite: true },
|
|
)
|
|
|
|
async function createCreditNote(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
userId: string,
|
|
input: { credited_invoice_id: string; reason?: string },
|
|
log: Logger,
|
|
requestId: string,
|
|
) {
|
|
const { data: originalInvoice, error: originalError } = await supabase
|
|
.from('invoices')
|
|
.select('*, items:invoice_items(*)')
|
|
.eq('id', input.credited_invoice_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (originalError || !originalInvoice) {
|
|
return errorResponseFromCode('INVOICE_CREDIT_ORIGINAL_NOT_FOUND', log, { requestId })
|
|
}
|
|
|
|
if (originalInvoice.document_type && originalInvoice.document_type !== 'invoice') {
|
|
return errorResponseFromCode('INVOICE_CREDIT_NOT_INVOICE', log, {
|
|
requestId,
|
|
details: { documentType: originalInvoice.document_type },
|
|
})
|
|
}
|
|
|
|
if (originalInvoice.status === 'credited') {
|
|
return errorResponseFromCode('INVOICE_CREDIT_ALREADY_CREDITED', log, { requestId })
|
|
}
|
|
|
|
// 'partially_paid' is missing from this list and that is a real gap, not a
|
|
// rule: an aendringsfaktura per ML (2023:200) 17 kap 22-23 SS references the
|
|
// original's loepnummer, and whether the customer has paid nothing, part or
|
|
// all of it has no bearing on the right to issue one. It is NOT added here
|
|
// alone, because this door is not where the flow ends: issueCreditNote()
|
|
// (lib/invoices/issue-credit-note.ts) flips the original to 'credited' with
|
|
// the same three-status compare-and-set, and it runs AFTER the reversing
|
|
// verifikat is posted. Widening only this check would post an immutable
|
|
// voucher and then fail on the status flip, leaving a fully credited invoice
|
|
// sitting at 'partially_paid': open in the AR ledger and still chased by
|
|
// reminders. Widening it is a coordinated change across the six sites listed
|
|
// in DECISIONS.md, with issue-credit-note.ts first.
|
|
//
|
|
// Genuinely refused either way: 'draft' (never issued, so there is no
|
|
// loepnummer for ML 17 kap 22 to reference) and 'cancelled'. 'credited' is
|
|
// refused above.
|
|
if (!['sent', 'paid', 'overdue'].includes(originalInvoice.status)) {
|
|
return errorResponseFromCode('INVOICE_CREDIT_NOT_SENT', log, {
|
|
requestId,
|
|
details: { currentStatus: originalInvoice.status },
|
|
})
|
|
}
|
|
|
|
// Self-billed originals have invoice_number null by design (the DB
|
|
// constraint invoices_self_billed_numbering enforces it); their number
|
|
// lives in external_invoice_number. Without this fallback the credit note
|
|
// would be numbered the literal string 'KR-null' (issue #1820). Both null
|
|
// is impossible for an issued invoice, but refuse defensively rather than
|
|
// mint a garbage number.
|
|
const originalRef = originalInvoice.invoice_number ?? originalInvoice.external_invoice_number
|
|
if (!originalRef) {
|
|
return errorResponseFromCode('INVOICE_CREDIT_NO_NUMBER', log, { requestId })
|
|
}
|
|
|
|
// Returning the existing credit note makes the action idempotent. A
|
|
// cancelled, unissued draft is reopened so the deterministic KR number can
|
|
// be reused without colliding with the company-wide invoice-number key.
|
|
const { data: existingCreditNote, error: existingCreditNoteError } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*)')
|
|
.eq('credited_invoice_id', input.credited_invoice_id)
|
|
.eq('company_id', companyId)
|
|
.eq('creation_complete', true)
|
|
.maybeSingle()
|
|
|
|
if (existingCreditNoteError) {
|
|
log.error('failed to check for an existing credit note', existingCreditNoteError)
|
|
return errorResponse(existingCreditNoteError, log, { requestId })
|
|
}
|
|
if (existingCreditNote) {
|
|
if (existingCreditNote.status === 'cancelled' && !existingCreditNote.journal_entry_id) {
|
|
const today = new Date().toISOString().split('T')[0]
|
|
const { error: reopenError } = await supabase
|
|
.from('invoices')
|
|
.update({
|
|
status: 'draft',
|
|
invoice_date: today,
|
|
due_date: today,
|
|
notes: input.reason || `Krediterar faktura ${originalRef}`,
|
|
updated_at: new Date().toISOString(),
|
|
})
|
|
.eq('id', existingCreditNote.id)
|
|
.eq('company_id', companyId)
|
|
.eq('status', 'cancelled')
|
|
|
|
if (reopenError) {
|
|
log.error('failed to reopen cancelled credit note draft', reopenError)
|
|
return errorResponse(reopenError, log, { requestId })
|
|
}
|
|
|
|
const { data: reopenedCreditNote, error: reopenedError } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*)')
|
|
.eq('id', existingCreditNote.id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (reopenedError || !reopenedCreditNote) {
|
|
return errorResponse(reopenedError ?? new Error('Credit note draft not found'), log, {
|
|
requestId,
|
|
})
|
|
}
|
|
return NextResponse.json({ data: maskEmbeddedCustomer(reopenedCreditNote) })
|
|
}
|
|
return NextResponse.json({ data: maskEmbeddedCustomer(existingCreditNote) })
|
|
}
|
|
|
|
const creditNoteNumber = `KR-${originalRef}`
|
|
|
|
const { data: creditNote, error: creditNoteError } = await supabase
|
|
.from('invoices')
|
|
.insert({
|
|
user_id: userId,
|
|
company_id: companyId,
|
|
customer_id: originalInvoice.customer_id,
|
|
invoice_number: creditNoteNumber,
|
|
invoice_date: new Date().toISOString().split('T')[0],
|
|
due_date: new Date().toISOString().split('T')[0],
|
|
delivery_date: originalInvoice.delivery_date ?? null,
|
|
currency: originalInvoice.currency,
|
|
exchange_rate: originalInvoice.exchange_rate,
|
|
exchange_rate_date: originalInvoice.exchange_rate_date,
|
|
subtotal: -Math.abs(originalInvoice.subtotal),
|
|
subtotal_sek: originalInvoice.subtotal_sek ? -Math.abs(originalInvoice.subtotal_sek) : null,
|
|
vat_amount: -Math.abs(originalInvoice.vat_amount),
|
|
vat_amount_sek: originalInvoice.vat_amount_sek ? -Math.abs(originalInvoice.vat_amount_sek) : null,
|
|
total: -Math.abs(originalInvoice.total),
|
|
total_sek: originalInvoice.total_sek ? -Math.abs(originalInvoice.total_sek) : null,
|
|
vat_treatment: originalInvoice.vat_treatment,
|
|
vat_rate: originalInvoice.vat_rate,
|
|
moms_ruta: originalInvoice.moms_ruta,
|
|
reverse_charge_text: originalInvoice.reverse_charge_text,
|
|
your_reference: originalInvoice.your_reference,
|
|
our_reference: originalInvoice.our_reference,
|
|
// Same buyer routing on the kreditfaktura as the original.
|
|
invoice_marking: originalInvoice.invoice_marking ?? null,
|
|
// Positive magnitude, unlike the negated amounts above: the DB has
|
|
// CHECK (deduction_total >= 0), and every reader either recomputes the
|
|
// ROT/RUT amount from the items or skips credit notes entirely.
|
|
deduction_total: originalInvoice.deduction_total
|
|
? Math.abs(originalInvoice.deduction_total)
|
|
: 0,
|
|
deduction_personnummer_encrypted: originalInvoice.deduction_personnummer_encrypted ?? null,
|
|
deduction_personnummer_last4: originalInvoice.deduction_personnummer_last4 ?? null,
|
|
notes: input.reason || `Krediterar faktura ${originalRef}`,
|
|
credited_invoice_id: input.credited_invoice_id,
|
|
// Copy the original's dimension bag so the credit-note verifikat nets
|
|
// against the same dimension cells in reports (dimensions PR7).
|
|
default_dimensions: originalInvoice.default_dimensions ?? {},
|
|
status: 'draft',
|
|
creation_complete: false,
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (creditNoteError) {
|
|
if (creditNoteError.code === '23505') {
|
|
const { data: racedCreditNote } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*)')
|
|
.eq('credited_invoice_id', input.credited_invoice_id)
|
|
.eq('company_id', companyId)
|
|
.eq('creation_complete', true)
|
|
.maybeSingle()
|
|
if (racedCreditNote) return NextResponse.json({ data: maskEmbeddedCustomer(racedCreditNote) })
|
|
}
|
|
log.error('credit note insert failed', creditNoteError)
|
|
return errorResponseFromCode('INVOICE_CREATE_INSERT_FAILED', log, {
|
|
requestId,
|
|
details: { pgCode: creditNoteError.code, pgMessage: getUserErrorMessage(creditNoteError) },
|
|
})
|
|
}
|
|
|
|
const creditNoteItems = (originalInvoice.items || []).map((item: InvoiceItem) =>
|
|
buildCreditNoteItem(creditNote.id, item)
|
|
)
|
|
|
|
const { error: itemsError } = await supabase.from('invoice_items').insert(creditNoteItems)
|
|
|
|
if (itemsError) {
|
|
const { error: cleanupError } = await supabase
|
|
.from('invoices')
|
|
.delete()
|
|
.eq('id', creditNote.id)
|
|
.eq('company_id', companyId)
|
|
.eq('creation_complete', false)
|
|
if (cleanupError) {
|
|
log.error('failed to clean up incomplete credit note', cleanupError, {
|
|
creditNoteId: creditNote.id,
|
|
})
|
|
}
|
|
log.error('credit note items insert failed; rolled back', itemsError, {
|
|
creditNoteId: creditNote.id,
|
|
})
|
|
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', log, {
|
|
requestId,
|
|
details: { pgCode: itemsError.code, pgMessage: getUserErrorMessage(itemsError) },
|
|
})
|
|
}
|
|
|
|
const { error: completionError } = await supabase
|
|
.from('invoices')
|
|
.update({ creation_complete: true, updated_at: new Date().toISOString() })
|
|
.eq('id', creditNote.id)
|
|
.eq('company_id', companyId)
|
|
.eq('creation_complete', false)
|
|
|
|
if (completionError) {
|
|
log.error('failed to mark credit note creation complete', completionError, {
|
|
creditNoteId: creditNote.id,
|
|
})
|
|
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', log, { requestId })
|
|
}
|
|
|
|
const { data: completeCreditNote, error: completeCreditNoteError } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*)')
|
|
.eq('id', creditNote.id)
|
|
.eq('company_id', companyId)
|
|
.eq('creation_complete', true)
|
|
.single()
|
|
|
|
if (completeCreditNoteError || !completeCreditNote) {
|
|
log.error('failed to read completed credit note', completeCreditNoteError)
|
|
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', log, { requestId })
|
|
}
|
|
|
|
// A credit note is only issued when the user sends it or marks it as sent.
|
|
// Until then it is a non-editable draft: no journal entry is created and
|
|
// the original invoice remains in its current state.
|
|
return NextResponse.json({ data: maskEmbeddedCustomer(completeCreditNote) })
|
|
}
|