* feat(peppol): receive e-invoices via Qvalia: registration, inbound archive, inbox delivery Second Peppol slice (#546). Qvalia confirmed that sending needs no per-company account, so receiving keeps the consolidated partner account: each company publishes its 0007:orgnr on our account and inbound documents are routed by the AccountingCustomerParty endpoint. - PeppolTransport grows optional receiving methods (registerRecipient, unregisterRecipient, listInboundDocuments, fetchInboundDocumentXml); the Qvalia adapter implements them (PUT/DELETE /peppol/{id}, readinvoices / readcreditnotes, exact XML fetch). - lib/invoices/peppol-inbound-ubl.ts reads the provider's UBL-JSON (xml2js-style prefixed keys, verified against Qvalia's real inbound test invoice, kept as a fixture) into a neutral document: parties, payment means with SE:BANKGIRO/SE:PLUSGIRO/IBAN, totals, VAT subtotals, lines, embedded attachments, credit notes. - Migration 20260821170000: peppol_registrations (one live row per company and participant), peppol_inbound_documents (exact XML immutable and undeletable, routed once), invoice_inbox_items.source gains 'peppol' with a per-channel dedupe index; pg-real test covers RLS, uniqueness, immutability and routing. - POST/DELETE/GET /api/settings/peppol + "E-faktura via Peppol" switch in Settings > Fakturering; personnummer-based companies are refused until 0088 GLN exists; sandbox refused. - GET /api/peppol/inbound/cron every 10 minutes: archive, route, deliver. lib/invoices/peppol-inbox-delivery.ts archives the XML as a WORM document (upload_source e_invoice, extractionOwner none), an embedded PDF when present, and creates the inbox row with the extraction filled from the UBL (confidence 1, no model pass), matching the supplier by org number. The existing inbox review/convert flow takes over. - document-service accepts application/xml for the archive; inbox list shows a Peppol icon. Refs #546 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TqFpxeWqbpR7bcwUJLRERQ * test(peppol): archive contract, pg fixture and phantom-column ceiling for the receiving tables The two new tables are räkenskapsinformation and join MASTER_DATA_DUMP_TABLES; the pg fixture for a deregistered row now carries deregistered_at as the status-shape constraint requires; the archive insert is an inline literal and the one generic processing-state updater is accounted for in the ceiling. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TqFpxeWqbpR7bcwUJLRERQ --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
142 lines
5.1 KiB
TypeScript
142 lines
5.1 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { privateNoStore } from '@/lib/api/private-no-store'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import {
|
|
deregisterCompanyFromPeppolReceiving,
|
|
getPeppolRegistration,
|
|
registerCompanyForPeppolReceiving,
|
|
type PeppolRegistrationRow,
|
|
} from '@/lib/invoices/peppol-registration'
|
|
import {
|
|
getPeppolTransport,
|
|
getPeppolTransportAvailability,
|
|
type PeppolTransport,
|
|
} from '@/lib/invoices/peppol-transport'
|
|
import { isSandboxCompany } from '@/lib/sandbox/guard'
|
|
import { createServiceClient } from '@/lib/supabase/server'
|
|
import type { CompanySettings } from '@/types'
|
|
|
|
ensureInitialized()
|
|
|
|
function registrationPayload(row: PeppolRegistrationRow | null) {
|
|
if (!row) return null
|
|
return {
|
|
id: row.id,
|
|
provider: row.provider,
|
|
participant_scheme: row.participant_scheme,
|
|
participant_identifier: row.participant_identifier,
|
|
status: row.status,
|
|
registered_at: row.registered_at,
|
|
deregistered_at: row.deregistered_at,
|
|
last_error: row.last_error,
|
|
updated_at: row.updated_at,
|
|
}
|
|
}
|
|
|
|
function resolveTransport(): { transport: PeppolTransport; provider: string } | null {
|
|
const availability = getPeppolTransportAvailability()
|
|
if (!availability.available) return null
|
|
const transport = getPeppolTransport(availability.provider)
|
|
return transport ? { transport, provider: availability.provider } : null
|
|
}
|
|
|
|
/** GET /api/settings/peppol: receiving status for the active company. */
|
|
export const GET = withRouteContext(
|
|
'settings.peppol.get',
|
|
async (_request, { supabase, companyId, log, requestId }) => {
|
|
const availability = getPeppolTransportAvailability()
|
|
const resolved = resolveTransport()
|
|
try {
|
|
const registration = resolved
|
|
? await getPeppolRegistration({ supabase, companyId, provider: resolved.provider })
|
|
: null
|
|
return privateNoStore(NextResponse.json({
|
|
data: {
|
|
transport: availability,
|
|
receiving_supported: !!resolved?.transport.registerRecipient,
|
|
registration: registrationPayload(registration),
|
|
},
|
|
}))
|
|
} catch (err) {
|
|
return privateNoStore(errorResponse(err, log, { requestId }))
|
|
}
|
|
},
|
|
)
|
|
|
|
/** POST /api/settings/peppol: publish the company's Peppol identifier for receiving. */
|
|
export const POST = withRouteContext(
|
|
'settings.peppol.register',
|
|
async (_request, { supabase, companyId, user, log, requestId }) => {
|
|
const resolved = resolveTransport()
|
|
if (!resolved) {
|
|
return privateNoStore(errorResponseFromCode('PEPPOL_TRANSPORT_UNAVAILABLE', log, { requestId }))
|
|
}
|
|
if (await isSandboxCompany(supabase, companyId)) {
|
|
return privateNoStore(errorResponseFromCode('PEPPOL_SANDBOX_NOT_ALLOWED', log, { requestId }))
|
|
}
|
|
|
|
const { data: settings, error: settingsError } = await supabase
|
|
.from('company_settings')
|
|
.select('org_number, company_name, vat_number, city, country')
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
if (settingsError || !settings) {
|
|
return privateNoStore(errorResponseFromCode('INVOICE_SEND_COMPANY_SETTINGS_MISSING', log, { requestId }))
|
|
}
|
|
|
|
try {
|
|
const result = await registerCompanyForPeppolReceiving({
|
|
service: createServiceClient(),
|
|
companyId,
|
|
userId: user.id,
|
|
transport: resolved.transport,
|
|
settings: settings as Pick<CompanySettings, 'org_number' | 'company_name' | 'vat_number' | 'city' | 'country'>,
|
|
})
|
|
if (!result.ok) {
|
|
return privateNoStore(errorResponseFromCode(result.code, log, {
|
|
requestId,
|
|
...('detail' in result && result.detail ? { details: { reason: result.detail } } : {}),
|
|
}))
|
|
}
|
|
return privateNoStore(NextResponse.json({
|
|
data: { registration: registrationPayload(result.registration) },
|
|
}, { status: 201 }))
|
|
} catch (err) {
|
|
return privateNoStore(errorResponse(err, log, { requestId }))
|
|
}
|
|
},
|
|
{ requireWrite: true },
|
|
)
|
|
|
|
/** DELETE /api/settings/peppol: withdraw the identifier from the Access Point. */
|
|
export const DELETE = withRouteContext(
|
|
'settings.peppol.deregister',
|
|
async (_request, { companyId, log, requestId }) => {
|
|
const resolved = resolveTransport()
|
|
if (!resolved) {
|
|
return privateNoStore(errorResponseFromCode('PEPPOL_TRANSPORT_UNAVAILABLE', log, { requestId }))
|
|
}
|
|
try {
|
|
const result = await deregisterCompanyFromPeppolReceiving({
|
|
service: createServiceClient(),
|
|
companyId,
|
|
transport: resolved.transport,
|
|
})
|
|
if (!result.ok) {
|
|
return privateNoStore(errorResponseFromCode(result.code, log, {
|
|
requestId,
|
|
...('detail' in result && result.detail ? { details: { reason: result.detail } } : {}),
|
|
}))
|
|
}
|
|
return privateNoStore(NextResponse.json({
|
|
data: { registration: registrationPayload(result.registration) },
|
|
}))
|
|
} catch (err) {
|
|
return privateNoStore(errorResponse(err, log, { requestId }))
|
|
}
|
|
},
|
|
{ requireWrite: true },
|
|
)
|