Files
accounted/app/api/settings/peppol/access/route.ts
T
3ac80edc96 feat(peppol): gate Peppol per company: request access, operator enables with a sending cap (#1794)
* feat(peppol): gate Peppol per company: request access, operator enables with a sending cap

Peppol is no longer available to every company by default. Each transmission
is billed per document by the access point and each receiving identifier
consumes a contracted tenant slot, so the product now works like this:

- peppol_access (new table, RLS read-only for members, service-role writes):
  status requested | enabled | disabled, max_sends (null = no cap),
  receive_enabled as a separate grant, who asked and who enabled.
- POST /api/settings/peppol/access: the company asks from Settings >
  Fakturering; the row is written and the operators are e-mailed (best effort,
  the row is the source of truth).
- scripts/peppol/access.ts list | enable <company|orgnr> [--max-sends N]
  [--receive] | disable | show: the operator side.
- POST /api/invoices/[id]/peppol/send refuses PEPPOL_ACCESS_REQUIRED /
  PEPPOL_SEND_LIMIT_REACHED before touching the invoice; the invoice page's
  send item says so instead of pretending. Registration for receiving refuses
  PEPPOL_ACCESS_REQUIRED / PEPPOL_RECEIVING_NOT_ENABLED.
- Settings UI: access status row with "Begär åtkomst", sends used of cap,
  receiving switch only once receiving is granted.

Refs #546

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TqFpxeWqbpR7bcwUJLRERQ

* test(peppol): pass route params to the settings handlers; baseline-align the access row

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TqFpxeWqbpR7bcwUJLRERQ

* fix(peppol): revoke default table privileges from authenticated on the access and receiving tables

Supabase grants ALL on new tables to authenticated by default; the earlier
REVOKE covered PUBLIC and anon only, so a member's UPDATE on peppol_access was
an RLS-filtered no-op instead of a permission error (pg-real caught it).

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>
2026-08-21 17:27:45 +02:00

92 lines
4.2 KiB
TypeScript

import { NextResponse } from 'next/server'
import { z } from 'zod'
import { privateNoStore } from '@/lib/api/private-no-store'
import { validateBody } from '@/lib/api/validate'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getBranding } from '@/lib/branding/service'
import { getEmailService } from '@/lib/email/service'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { ensureInitialized } from '@/lib/init'
import {
getPeppolAccessSummary,
requestPeppolAccess,
} from '@/lib/invoices/peppol-access'
import { isSandboxCompany } from '@/lib/sandbox/guard'
import { createServiceClient } from '@/lib/supabase/server'
import { getSupportRecipientEmail } from '@/lib/support'
ensureInitialized()
const RequestAccessSchema = z.object({
note: z.string().trim().max(2000).optional(),
})
function escapeHtml(value: string): string {
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
/**
* POST /api/settings/peppol/access: the company asks for Peppol access.
*
* Writes the request row (service role; the browser cannot grant itself
* anything) and tells the operators by e-mail. The e-mail is best-effort: the
* row is the source of truth and the operators' script lists open requests.
*/
export const POST = withRouteContext(
'settings.peppol.access.request',
async (request, { supabase, companyId, user, log, requestId }) => {
const validation = await validateBody(request, RequestAccessSchema)
if (!validation.success) return validation.response
const note = validation.data.note?.trim() || null
if (await isSandboxCompany(supabase, companyId)) {
return privateNoStore(errorResponseFromCode('PEPPOL_SANDBOX_NOT_ALLOWED', log, { requestId }))
}
const service = createServiceClient()
try {
const result = await requestPeppolAccess({ service, companyId, userId: user.id, note })
if (!result.ok) {
return privateNoStore(errorResponseFromCode(result.code, log, { requestId }))
}
if (result.created) {
const { data: company } = await supabase
.from('company_settings')
.select('company_name, org_number')
.eq('company_id', companyId)
.maybeSingle()
const emailService = getEmailService()
if (emailService.isConfigured()) {
const companyName = (company as { company_name?: string | null } | null)?.company_name ?? 'okänt bolag'
const orgNumber = (company as { org_number?: string | null } | null)?.org_number ?? 'saknas'
const sent = await emailService.sendEmail({
to: getSupportRecipientEmail(),
subject: `[${getBranding().appName.toLowerCase()} peppol] Åtkomstbegäran: ${companyName}`,
replyTo: user.email,
html: [
`<p><strong>Bolag:</strong> ${escapeHtml(companyName)} (${escapeHtml(orgNumber)})</p>`,
`<p><strong>Company ID:</strong> ${companyId}</p>`,
`<p><strong>Begärd av:</strong> ${escapeHtml(user.email ?? '')} (${user.id})</p>`,
note ? `<hr /><p>${escapeHtml(note).replace(/\n/g, '<br />')}</p>` : '',
`<hr /><p>Aktivera: <code>npx tsx --env-file=.env.local scripts/peppol/access.ts enable ${companyId} --max-sends 50</code></p>`,
].join('\n'),
text: `Bolag: ${companyName} (${orgNumber})\nCompany ID: ${companyId}\nBegärd av: ${user.email ?? ''} (${user.id})\n\n${note ?? ''}\n\nAktivera: npx tsx --env-file=.env.local scripts/peppol/access.ts enable ${companyId} --max-sends 50`,
})
if (!sent.success) {
log.warn('peppol access request e-mail failed', { companyId, reason: sent.error })
}
} else {
log.warn('peppol access request: e-mail service not configured, request recorded only', { companyId })
}
}
const summary = await getPeppolAccessSummary({ supabase: service, service, companyId })
return privateNoStore(NextResponse.json({ data: { access: summary } }, { status: result.created ? 201 : 200 }))
} catch (err) {
return privateNoStore(errorResponse(err, log, { requestId }))
}
},
{ requireWrite: true },
)