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>
This commit is contained in:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
9ef7de861f
commit
3ac80edc96
@@ -13,6 +13,11 @@ vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
const serviceTables = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: () => serviceTables.supabase,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
@@ -4,8 +4,10 @@ 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 { getPeppolAccessSummary } from '@/lib/invoices/peppol-access'
|
||||
import { listPeppolDeliverySummaries } from '@/lib/invoices/peppol-delivery'
|
||||
import { getPeppolTransportAvailability } from '@/lib/invoices/peppol-transport'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -39,9 +41,11 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
companyId,
|
||||
invoiceId,
|
||||
})
|
||||
const access = await getPeppolAccessSummary({ supabase, service: createServiceClient(), companyId })
|
||||
return privateNoStore(NextResponse.json({
|
||||
data: deliveries,
|
||||
transport: getPeppolTransportAvailability(),
|
||||
access,
|
||||
}))
|
||||
} catch (err) {
|
||||
return privateNoStore(errorResponse(err, log, { requestId }))
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from '@/lib/invoices/peppol-transport'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
const serviceTables = createQueuedMockSupabase()
|
||||
const requireAuthMock = vi.fn()
|
||||
const serviceRpcMock = vi.fn()
|
||||
const issueAndBookMock = vi.fn()
|
||||
@@ -37,7 +38,10 @@ vi.mock('@/lib/auth/require-write', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: () => ({ rpc: (...args: unknown[]) => serviceRpcMock(...args) }),
|
||||
createServiceClient: () => ({
|
||||
from: (...args: unknown[]) => serviceTables.supabase.from(...(args as [string])),
|
||||
rpc: (...args: unknown[]) => serviceRpcMock(...args),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/invoices/issue-and-book-invoice', () => ({
|
||||
@@ -135,6 +139,21 @@ function makeTransport(overrides: Partial<PeppolTransport> = {}): PeppolTranspor
|
||||
}
|
||||
}
|
||||
|
||||
const accessRow = {
|
||||
company_id: 'company-1',
|
||||
status: 'enabled',
|
||||
max_sends: 50,
|
||||
receive_enabled: false,
|
||||
requested_at: null, requested_by: null, request_note: null,
|
||||
enabled_at: '2026-08-21T16:00:00.000Z', enabled_by: 'jakob', disabled_at: null, note: null,
|
||||
created_at: '2026-08-21T16:00:00.000Z', updated_at: '2026-08-21T16:00:00.000Z',
|
||||
}
|
||||
/** Peppol access is per company: grant it (service reads access row, then the send count). */
|
||||
function grantAccess(maxSends: number | null = 50, sent = 0) {
|
||||
serviceTables.enqueue({ data: { ...accessRow, max_sends: maxSends }, error: null })
|
||||
serviceTables.enqueue({ data: null, error: null, count: sent })
|
||||
}
|
||||
|
||||
/** The service-role RPC echoes the event's status back as the projection. */
|
||||
function serviceRpcEcho() {
|
||||
serviceRpcMock.mockImplementation(async (_fn: string, args: Record<string, unknown>) => ({
|
||||
@@ -157,6 +176,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
serviceTables.reset()
|
||||
serviceRpcEcho()
|
||||
process.env.PEPPOL_TRANSPORT_PROVIDER = 'qvalia'
|
||||
process.env.QVALIA_PARTNER_REG_NO = 'SE5560000000'
|
||||
@@ -208,8 +228,31 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
expect(body.error.details.reason).toBe('provider_selection_required')
|
||||
})
|
||||
|
||||
it('refuses a company without a Peppol grant before touching the invoice', async () => {
|
||||
const transport = makeTransport()
|
||||
unregister = registerPeppolTransport(transport)
|
||||
serviceTables.enqueue({ data: null, error: null }) // no access row
|
||||
const response = await send()
|
||||
expect(response.status).toBe(403)
|
||||
expect((await response.json()).error.code).toBe('PEPPOL_ACCESS_REQUIRED')
|
||||
expect(transport.submit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses once the company has used its sending cap', async () => {
|
||||
const transport = makeTransport()
|
||||
unregister = registerPeppolTransport(transport)
|
||||
grantAccess(5, 5)
|
||||
const response = await send()
|
||||
expect(response.status).toBe(409)
|
||||
const body = await response.json()
|
||||
expect(body.error.code).toBe('PEPPOL_SEND_LIMIT_REACHED')
|
||||
expect(body.error.details).toMatchObject({ max_sends: 5, sent_count: 5 })
|
||||
expect(transport.submit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the invoice is not in the active company', async () => {
|
||||
unregister = registerPeppolTransport(makeTransport())
|
||||
grantAccess()
|
||||
enqueue({ data: null, error: { message: 'not found' } })
|
||||
const response = await send()
|
||||
expect(response.status).toBe(404)
|
||||
@@ -218,6 +261,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
|
||||
it('rejects cancelled and proforma invoices with a state conflict', async () => {
|
||||
unregister = registerPeppolTransport(makeTransport())
|
||||
grantAccess()
|
||||
enqueue({ data: invoiceRow({ status: 'cancelled' }), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
const response = await send()
|
||||
@@ -235,6 +279,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
}),
|
||||
})
|
||||
unregister = registerPeppolTransport(transport)
|
||||
grantAccess()
|
||||
enqueue({ data: invoiceRow(), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
enqueue({ data: stagedDelivery, error: null })
|
||||
@@ -252,6 +297,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
it('looks up, submits the staged XML and records the lifecycle for an already issued invoice', async () => {
|
||||
const transport = makeTransport()
|
||||
unregister = registerPeppolTransport(transport)
|
||||
grantAccess()
|
||||
enqueue({ data: invoiceRow(), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
enqueue({ data: stagedDelivery, error: null })
|
||||
@@ -294,6 +340,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
it('issues and books a draft only after the network accepted it', async () => {
|
||||
const transport = makeTransport()
|
||||
unregister = registerPeppolTransport(transport)
|
||||
grantAccess()
|
||||
enqueue({ data: invoiceRow({ status: 'draft' }), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
enqueue({ data: stagedDelivery, error: null })
|
||||
@@ -315,6 +362,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
|
||||
it('reports a failed issuance without pretending the network send did not happen', async () => {
|
||||
unregister = registerPeppolTransport(makeTransport())
|
||||
grantAccess()
|
||||
issueAndBookMock.mockResolvedValue({ ok: false, errorCode: 'INVOICE_MARK_SENT_RACE' })
|
||||
enqueue({ data: invoiceRow({ status: 'draft' }), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
@@ -334,6 +382,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
it('replays idempotently when the exact XML was already handed to the network', async () => {
|
||||
const transport = makeTransport()
|
||||
unregister = registerPeppolTransport(transport)
|
||||
grantAccess()
|
||||
enqueue({ data: invoiceRow(), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
enqueue({
|
||||
@@ -360,6 +409,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
),
|
||||
})
|
||||
unregister = registerPeppolTransport(transport)
|
||||
grantAccess()
|
||||
enqueue({ data: invoiceRow({ status: 'draft' }), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
enqueue({ data: stagedDelivery, error: null })
|
||||
@@ -386,6 +436,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
),
|
||||
})
|
||||
unregister = registerPeppolTransport(transport)
|
||||
grantAccess()
|
||||
enqueue({ data: invoiceRow(), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
enqueue({ data: stagedDelivery, error: null })
|
||||
@@ -405,6 +456,7 @@ describe('POST /api/invoices/[id]/peppol/send', () => {
|
||||
it('refuses to resend an exact document the access point already rejected', async () => {
|
||||
const transport = makeTransport()
|
||||
unregister = registerPeppolTransport(transport)
|
||||
grantAccess()
|
||||
enqueue({ data: invoiceRow(), error: null })
|
||||
enqueue({ data: company, error: null })
|
||||
enqueue({
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
stagePeppolDelivery,
|
||||
type PeppolDeliverySummary,
|
||||
} from '@/lib/invoices/peppol-delivery'
|
||||
import { checkPeppolSendPermission } from '@/lib/invoices/peppol-access'
|
||||
import { generatePeppolDocumentOrResponse, loadPeppolRecords } from '@/lib/invoices/peppol-document'
|
||||
import {
|
||||
getPeppolTransport,
|
||||
@@ -112,6 +113,21 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
}))
|
||||
}
|
||||
|
||||
// Access is granted per company by the operators and capped in sends:
|
||||
// refuse before any invoice data is touched.
|
||||
const service = createServiceClient()
|
||||
const permission = await checkPeppolSendPermission({ service, companyId })
|
||||
if (!permission.ok) {
|
||||
return privateNoStore(errorResponseFromCode(permission.code, log, {
|
||||
requestId,
|
||||
details: {
|
||||
access_status: permission.summary.status,
|
||||
max_sends: permission.summary.max_sends,
|
||||
sent_count: permission.summary.sent_count,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
const records = await loadPeppolRecords({ supabase, companyId, invoiceId, log, requestId })
|
||||
if (!records.ok) return records.response
|
||||
const { invoice, company } = records
|
||||
@@ -153,7 +169,6 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
if (!generated.ok) return generated.response
|
||||
const document = generated.document
|
||||
|
||||
const service = createServiceClient()
|
||||
const provider = transport.provider
|
||||
// Consolidated Qvalia setup: one provider account for every company. The
|
||||
// adapter resolves the account; the lifecycle only needs a stable label.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { createMockRequest, createMockRouteParams, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { registerPeppolTransport, type PeppolTransport } from '@/lib/invoices/peppol-transport'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
@@ -24,6 +24,13 @@ vi.mock('@/lib/supabase/server', () => ({
|
||||
import { DELETE, GET, POST } from '../route'
|
||||
|
||||
const user = { id: 'user-1', email: 'owner@example.test' }
|
||||
const enabledAccess = {
|
||||
company_id: 'company-1', status: 'enabled', max_sends: 50, receive_enabled: true,
|
||||
requested_at: null, requested_by: null, request_note: null,
|
||||
enabled_at: '2026-08-21T16:00:00.000Z', enabled_by: 'jakob', disabled_at: null, note: null,
|
||||
created_at: '2026-08-21T16:00:00.000Z', updated_at: '2026-08-21T16:00:00.000Z',
|
||||
}
|
||||
|
||||
const registeredRow = {
|
||||
id: 'reg-1',
|
||||
company_id: 'company-1',
|
||||
@@ -83,18 +90,20 @@ describe('/api/settings/peppol', () => {
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const response = await GET(createMockRequest('/api/settings/peppol'))
|
||||
const response = await GET(createMockRequest('/api/settings/peppol'), createMockRouteParams({}))
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('GET tells the truth when no access point is switched on', async () => {
|
||||
delete process.env.PEPPOL_TRANSPORT_PROVIDER
|
||||
const response = await GET(createMockRequest('/api/settings/peppol'))
|
||||
enqueue({ data: null, error: null }) // access row (none)
|
||||
const response = await GET(createMockRequest('/api/settings/peppol'), createMockRouteParams({}))
|
||||
const body = await response.json()
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.data).toMatchObject({
|
||||
transport: { available: false },
|
||||
receiving_supported: false,
|
||||
access: { status: 'none', send_enabled: false },
|
||||
registration: null,
|
||||
})
|
||||
})
|
||||
@@ -102,36 +111,58 @@ describe('/api/settings/peppol', () => {
|
||||
it('GET returns the live registration when the adapter supports receiving', async () => {
|
||||
unregister = registerPeppolTransport(makeTransport())
|
||||
enqueue({ data: [registeredRow], error: null })
|
||||
const response = await GET(createMockRequest('/api/settings/peppol'))
|
||||
enqueue({ data: enabledAccess, error: null }) // access row
|
||||
service.enqueue({ data: null, error: null, count: 3 }) // sends used
|
||||
const response = await GET(createMockRequest('/api/settings/peppol'), createMockRouteParams({}))
|
||||
const body = await response.json()
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.data.receiving_supported).toBe(true)
|
||||
expect(body.data.access).toMatchObject({ status: 'enabled', send_enabled: true, receive_enabled: true, sent_count: 3, remaining_sends: 47 })
|
||||
expect(body.data.registration).toMatchObject({ status: 'registered', participant_identifier: '5595386219' })
|
||||
expect(body.data.registration).not.toHaveProperty('business_card')
|
||||
})
|
||||
|
||||
it('POST refuses without a transport and in the sandbox', async () => {
|
||||
delete process.env.PEPPOL_TRANSPORT_PROVIDER
|
||||
expect((await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }))).status).toBe(503)
|
||||
expect((await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }), createMockRouteParams({}))).status).toBe(503)
|
||||
|
||||
process.env.PEPPOL_TRANSPORT_PROVIDER = 'qvalia'
|
||||
unregister = registerPeppolTransport(makeTransport())
|
||||
enqueue({ data: { is_sandbox: true }, error: null })
|
||||
const response = await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }))
|
||||
const response = await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }), createMockRouteParams({}))
|
||||
expect(response.status).toBe(403)
|
||||
expect((await response.json()).error.code).toBe('PEPPOL_SANDBOX_NOT_ALLOWED')
|
||||
})
|
||||
|
||||
it('POST refuses receiving without an access grant, and without the receiving flag', async () => {
|
||||
const transport = makeTransport()
|
||||
unregister = registerPeppolTransport(transport)
|
||||
enqueue({ data: { is_sandbox: false }, error: null })
|
||||
service.enqueue({ data: null, error: null }) // no access row
|
||||
const locked = await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }), createMockRouteParams({}))
|
||||
expect(locked.status).toBe(403)
|
||||
expect((await locked.json()).error.code).toBe('PEPPOL_ACCESS_REQUIRED')
|
||||
|
||||
reset(); service.reset()
|
||||
enqueue({ data: { is_sandbox: false }, error: null })
|
||||
service.enqueue({ data: { ...enabledAccess, receive_enabled: false }, error: null })
|
||||
const sendOnly = await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }), createMockRouteParams({}))
|
||||
expect(sendOnly.status).toBe(403)
|
||||
expect((await sendOnly.json()).error.code).toBe('PEPPOL_RECEIVING_NOT_ENABLED')
|
||||
expect(transport.registerRecipient).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST registers the company and returns the minimized registration', async () => {
|
||||
const transport = makeTransport()
|
||||
unregister = registerPeppolTransport(transport)
|
||||
enqueue({ data: { is_sandbox: false }, error: null })
|
||||
service.enqueue({ data: enabledAccess, error: null }) // access grant with receiving
|
||||
enqueue({ data: { org_number: '559538-6219', company_name: 'Arcim Technology AB', vat_number: 'SE559538621901', city: 'Stockholm', country: 'SE' }, error: null })
|
||||
service.enqueue({ data: [], error: null }) // existing
|
||||
service.enqueue({ data: { id: 'reg-1' }, error: null }) // insert pending
|
||||
service.enqueue({ data: registeredRow, error: null }) // finalize
|
||||
|
||||
const response = await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }))
|
||||
const response = await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }), createMockRouteParams({}))
|
||||
const body = await response.json()
|
||||
expect(response.status).toBe(201)
|
||||
expect(body.data.registration).toMatchObject({ status: 'registered', participant_scheme: '0007' })
|
||||
@@ -141,8 +172,9 @@ describe('/api/settings/peppol', () => {
|
||||
it('POST maps a personnummer-based company to a 422 with the reason', async () => {
|
||||
unregister = registerPeppolTransport(makeTransport())
|
||||
enqueue({ data: { is_sandbox: false }, error: null })
|
||||
service.enqueue({ data: enabledAccess, error: null })
|
||||
enqueue({ data: { org_number: '800101-1234', company_name: 'Firma', vat_number: null, city: null, country: 'SE' }, error: null })
|
||||
const response = await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }))
|
||||
const response = await POST(createMockRequest('/api/settings/peppol', { method: 'POST' }), createMockRouteParams({}))
|
||||
expect(response.status).toBe(422)
|
||||
expect((await response.json()).error.code).toBe('PEPPOL_REGISTRATION_PERSONAL_NUMBER')
|
||||
})
|
||||
@@ -152,13 +184,13 @@ describe('/api/settings/peppol', () => {
|
||||
unregister = registerPeppolTransport(transport)
|
||||
service.enqueue({ data: [registeredRow], error: null })
|
||||
service.enqueue({ data: { ...registeredRow, status: 'deregistered', deregistered_at: '2026-08-21T17:00:00.000Z' }, error: null })
|
||||
const ok = await DELETE(createMockRequest('/api/settings/peppol', { method: 'DELETE' }))
|
||||
const ok = await DELETE(createMockRequest('/api/settings/peppol', { method: 'DELETE' }), createMockRouteParams({}))
|
||||
expect(ok.status).toBe(200)
|
||||
expect((await ok.json()).data.registration.status).toBe('deregistered')
|
||||
expect(transport.unregisterRecipient).toHaveBeenCalledWith({ scheme: '0007', identifier: '5595386219' })
|
||||
|
||||
service.enqueue({ data: [], error: null })
|
||||
const missing = await DELETE(createMockRequest('/api/settings/peppol', { method: 'DELETE' }))
|
||||
const missing = await DELETE(createMockRequest('/api/settings/peppol', { method: 'DELETE' }), createMockRouteParams({}))
|
||||
expect(missing.status).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createMockRouteParams, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
const service = createQueuedMockSupabase()
|
||||
const requireAuthMock = vi.fn()
|
||||
const sendEmailMock = vi.fn()
|
||||
const isConfiguredMock = vi.fn()
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: () => service.supabase,
|
||||
}))
|
||||
vi.mock('@/lib/email/service', () => ({
|
||||
getEmailService: () => ({
|
||||
sendEmail: (...args: unknown[]) => sendEmailMock(...args),
|
||||
isConfigured: () => isConfiguredMock(),
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/lib/support', () => ({
|
||||
getSupportRecipientEmail: () => 'support@example.test',
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const user = { id: 'user-1', email: 'owner@example.test' }
|
||||
const requestedRow = {
|
||||
company_id: 'company-1',
|
||||
status: 'requested',
|
||||
max_sends: null,
|
||||
receive_enabled: false,
|
||||
requested_at: '2026-08-21T15:00:00.000Z',
|
||||
requested_by: 'user-1',
|
||||
request_note: null,
|
||||
enabled_at: null,
|
||||
enabled_by: null,
|
||||
disabled_at: null,
|
||||
note: null,
|
||||
created_at: '2026-08-21T15:00:00.000Z',
|
||||
updated_at: '2026-08-21T15:00:00.000Z',
|
||||
}
|
||||
|
||||
describe('POST /api/settings/peppol/access', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
service.reset()
|
||||
isConfiguredMock.mockReturnValue(true)
|
||||
sendEmailMock.mockResolvedValue({ success: true })
|
||||
requireAuthMock.mockResolvedValue({ user, supabase: mockSupabase, error: null })
|
||||
})
|
||||
|
||||
function post(body: unknown = {}) {
|
||||
return POST(createMockRequest('/api/settings/peppol/access', { method: 'POST', body }), createMockRouteParams({}))
|
||||
}
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
expect((await post()).status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an oversized note', async () => {
|
||||
const response = await post({ note: 'x'.repeat(2001) })
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('refuses the sandbox', async () => {
|
||||
enqueue({ data: { is_sandbox: true }, error: null })
|
||||
const response = await post()
|
||||
expect(response.status).toBe(403)
|
||||
expect((await response.json()).error.code).toBe('PEPPOL_SANDBOX_NOT_ALLOWED')
|
||||
})
|
||||
|
||||
it('records the request, mails the operators and returns the locked summary', async () => {
|
||||
enqueue({ data: { is_sandbox: false }, error: null }) // sandbox check
|
||||
service.enqueue({ data: null, error: null }) // no access row
|
||||
service.enqueue({ data: requestedRow, error: null }) // upsert
|
||||
enqueue({ data: { company_name: 'Kund AB', org_number: '556677-8899' }, error: null }) // company settings
|
||||
service.enqueue({ data: requestedRow, error: null }) // summary read
|
||||
|
||||
const response = await post({ note: 'Vi fakturerar Region Skåne' })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(201)
|
||||
expect(body.data.access).toMatchObject({ status: 'requested', send_enabled: false })
|
||||
expect(sendEmailMock).toHaveBeenCalledTimes(1)
|
||||
const mail = sendEmailMock.mock.calls[0][0] as { to: string; subject: string; text: string }
|
||||
expect(mail.to).toBe('support@example.test')
|
||||
expect(mail.subject).toContain('Kund AB')
|
||||
expect(mail.text).toContain('company-1')
|
||||
expect(mail.text).toContain('Region Skåne')
|
||||
})
|
||||
|
||||
it('is idempotent for a repeated request (no second e-mail) and 409 when already enabled', async () => {
|
||||
enqueue({ data: { is_sandbox: false }, error: null })
|
||||
service.enqueue({ data: requestedRow, error: null })
|
||||
service.enqueue({ data: requestedRow, error: null })
|
||||
const again = await post()
|
||||
expect(again.status).toBe(200)
|
||||
expect(sendEmailMock).not.toHaveBeenCalled()
|
||||
|
||||
reset(); service.reset()
|
||||
enqueue({ data: { is_sandbox: false }, error: null })
|
||||
service.enqueue({ data: { ...requestedRow, status: 'enabled', enabled_at: '2026-08-21T16:00:00.000Z' }, error: null })
|
||||
const enabled = await post()
|
||||
expect(enabled.status).toBe(409)
|
||||
expect((await enabled.json()).error.code).toBe('PEPPOL_ACCESS_ALREADY_ENABLED')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 },
|
||||
)
|
||||
@@ -3,6 +3,7 @@ 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 { getPeppolAccess, getPeppolAccessSummary } from '@/lib/invoices/peppol-access'
|
||||
import {
|
||||
deregisterCompanyFromPeppolReceiving,
|
||||
getPeppolRegistration,
|
||||
@@ -52,10 +53,12 @@ export const GET = withRouteContext(
|
||||
const registration = resolved
|
||||
? await getPeppolRegistration({ supabase, companyId, provider: resolved.provider })
|
||||
: null
|
||||
const access = await getPeppolAccessSummary({ supabase, service: createServiceClient(), companyId })
|
||||
return privateNoStore(NextResponse.json({
|
||||
data: {
|
||||
transport: availability,
|
||||
receiving_supported: !!resolved?.transport.registerRecipient,
|
||||
access,
|
||||
registration: registrationPayload(registration),
|
||||
},
|
||||
}))
|
||||
@@ -76,6 +79,14 @@ export const POST = withRouteContext(
|
||||
if (await isSandboxCompany(supabase, companyId)) {
|
||||
return privateNoStore(errorResponseFromCode('PEPPOL_SANDBOX_NOT_ALLOWED', log, { requestId }))
|
||||
}
|
||||
// Receiving consumes a contracted tenant slot: operators grant it per company.
|
||||
const access = await getPeppolAccess(createServiceClient(), companyId)
|
||||
if (!access || access.status !== 'enabled') {
|
||||
return privateNoStore(errorResponseFromCode('PEPPOL_ACCESS_REQUIRED', log, { requestId }))
|
||||
}
|
||||
if (!access.receive_enabled) {
|
||||
return privateNoStore(errorResponseFromCode('PEPPOL_RECEIVING_NOT_ENABLED', log, { requestId }))
|
||||
}
|
||||
|
||||
const { data: settings, error: settingsError } = await supabase
|
||||
.from('company_settings')
|
||||
|
||||
Reference in New Issue
Block a user