feat: custom inbound mail domains, rot/rut payout file, invoice email texts, security hardening (#878)
* fix(security): guard MCP test keys, RLS role gate + voucher RPC guards, /api MFA gate, deps - MCP: force dry-run / block writes for test-mode API keys in tools/call (extensions/general/mcp-server) - DB: current_user_can_write role gate on write policies (40 tables) + tenant guards, SET search_path, REVOKE anon on commit_journal_entry / next_voucher_number / detect_voucher_gaps (migration 20260702093000) - Middleware: MFA (AAL2) gate on cookie-authenticated /api routes via apiPathSkipsMfaGate - Deps: npm audit fix clears mailparser/linkify-it/nodemailer/svix/uuid highs; xlsx -> SheetJS 0.20.3 Adds unit + pg-real tests. Does not touch in-progress ROT/RUT or invoice-email-texts work. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(invoices): rot/rut begäran om utbetalning — HUS XML (V6), payout tracking + settlement, MCP tool Generates Skatteverkets begäran-om-utbetalning file (schema V6) from paid ROT/RUT invoices — no submission API exists, the file is uploaded manually at skatteverket.se. Headless by design for now: API routes + MCP tool (gnubok_generate_rot_rut_file), no UI surfaces. - lib/invoices/rot-rut-file.ts: pure XML generator with deterministic per-invoice blockers (hours, work type, personnummer, property info, mixed rot+rut, XSD limits) + 31 January deadline warnings - rot_rut_payout_requests(+items) tables: one active begäran per invoice (DB triggers incl. reactivation guard), RLS, audit, pg-real tests - Settlement: POST /settle books debit 1930 / credit 1513 via the engine (source_type rot_rut_payout); partial payouts → partially_paid - Work-type lists corrected against Begaran.xsd: IT-tjänster is rut-only, snöskottning/tillsyn/tvätt added (schablontjänster utfört-only) - Fix: invoice-level fastighetsbeteckning was validated but never persisted — now stamped onto rot lines in build-invoice-write; API accepts bostadsrätt pair (lägenhetsnr + BRF orgnr, editor UI deferred) - invoice_items.brf_org_number migration + MCP scope invoices:write Co-Authored-By: Claude Fable 5 <[email protected]> * feat(invoices): per-company editable invoice email texts Add an "E-posttexter" section under Settings -> Fakturering where the subject, greeting, body and sign-off of the standard invoice email can be customized per company in Swedish and English. Fields pre-fill with the standard texts and only diffs from the standard are stored (company_settings.invoice_email_texts JSONB), so future improvements to the stock wording still reach companies that have not customized. Each field has a reset-to-standard button; cleared fields snap back. Texts support a fixed placeholder set (invoice number, customer name, first name, company, due date, amount) substituted at send time in a single pass; unknown placeholders stay literal. Custom texts are HTML-escaped after substitution, newlines become <br> in the HTML variant, and subject lines are flattened to a single header line. Overrides apply to standard invoices only - credit notes, proforma and delivery notes keep the stock texts. All send paths (UI, v1 API, MCP approval, recurring) pick the texts up via the existing settings row. The Zod schema half of this change (InvoiceEmailTextsSchema in lib/api/schemas.ts) was inadvertently included in 8291f745. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(documents): accept PDFs with preamble before %PDF- header, surface content rejections as 400 detectFileMagic required the %PDF- signature at byte 0 (BOM aside), rejecting genuine PDFs that carry a leading newline or junk bytes — files every ISO 32000 reader opens fine. Now scan the first 1024 bytes for the signature, matching real-reader behavior. Image types stay strict at offset 0 to keep the anti-placeholder defense tight. Magic-byte rejections were also mislabeled as DOC_UPLOAD_STORAGE_FAILED (500 'Filen kunde inte sparas'), blaming storage for a client-side file problem. Both upload routes now map them to a new DOC_UPLOAD_INVALID_CONTENT (400) with an accurate message. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(bookkeeping): full keyboard flow for manual journal entry Enter now drives the whole verifikat flow: verifikationstext drops into the first row missing an account, konto commits advance to debet, Enter on an empty debet hops to kredit, and an entered amount jumps to the next row. Once the voucher balances, Enter opens the review (unchanged gate) and the auto-focused confirm posts it — including through the no-underlag warning dialog. Escape in the inline review goes back to the form. Also fixes an Enter footgun in AccountCombobox: a bare Enter on a freshly focused field no longer selects the first account in the list — selection now requires typing or arrow navigation; otherwise Enter re-commits the current value or bubbles to the form-level handler. Co-Authored-By: Claude Fable 5 <[email protected]> * feat: add custom inbound domains management for companies - Implemented functionality to allow companies to claim and manage their own inbound email domains via Resend's API. - Created a new table `company_inbound_domains` to store domain information, including status and DNS records. - Added necessary RLS policies to restrict access based on user roles (owner/admin). - Developed functions for domain normalization, validation, claiming, verification, and removal. - Implemented webhook handling for domain status updates from Resend. - Added comprehensive tests for RLS, constraints, and triggers related to the new domain management feature. * fix: address PR #878 review findings and CI failures - migrations: drop the ai_usage_tracking policy block from the role-gate migration — the table was removed by 20260504120000_remove_ai_subsystem and only lingers on staging as drift; a from-scratch chain (pg-real, Supabase preview) failed on it - invoice-inbox: never flip a custom domain to verified off a domain.updated webhook alone — confirm the receiving capability with Resend first (fail-closed); normalize both sides of the orphan-adoption domain match - rot/rut: block files where begärt belopp exceeds what the buyer paid (DEDUCTION_EXCEEDS_PAYMENT); tighten brf_org_number validation to real orgnr shapes; parameterize the settlement bank account (19xx, default 1930) - rot/rut routes: log acting user on financial mutations, stop swallowing item mirror errors, narrow response projections (no customer ids through the invoice join); document the deliberate inline-XML decision - documents: stop echoing raw storage-layer error messages to clients Co-Authored-By: Claude Fable 5 <[email protected]> * fix: round-2 CI + compliance findings on PR #878 - migrations: the role-gate migration targeted automation_webhooks, which 20260515170000_webhooks_v2 renamed to webhooks on the canonical chain (staging kept the old name — drift); gate public.webhooks instead, dropping legacy schema-sync policy names defensively. Restore the 20260623130000 owner fallback in next_voucher_number that the stale copied-verbatim body silently reverted (caught by engine.pg locally). Full migration chain verified from scratch against supabase/postgres:15. - mcp: bump the tools/list payload ceiling 44K -> 45K — main's #877 qualified-identifier schemas plus this branch's rot/rut tool crossed the ceiling only in combination; documented in the test's history log. - rot/rut: refuse partial settlement before Skatteverkets beslut is recorded (would bypass the PATCH lifecycle and strand the request); block zero-kronor ärenden (ZERO_DEDUCTION); require sekelsiffra 16 on 12-digit brf orgnr in both schema validation and normalizeBrfOrgNr Co-Authored-By: Claude Fable 5 <[email protected]> * fix: rename branch migrations off main's colliding versions After the merge with main, two versions were shared by two files each (20260702100000: rot_rut_payout_requests vs company_settings_dimensions_ enabled; 20260702130000: invoice_email_texts vs pending_operations_add_ create_dimension_value). psql-based CI applies by filename and doesn't care, but Supabase branching records migrations by version (PK) — the second file with the same version breaks the preview with a schema_migrations_pkey duplicate. Neither branch migration is version- recorded on staging or prod, so renaming to fresh 20260703 versions is safe; nothing between the old and new positions depends on these objects. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(security): scope the /api MFA-gate bypass to real Bearer-auth surfaces Any Authorization header — attacker-controlled — used to skip the AAL2 gate for every /api route, so a stolen-password AAL1 cookie session could reach cookie-authenticated routes (which ignore the header) by attaching `Authorization: x`. The skip is now scoped to the surfaces whose auth contract IS the header (/api/v1 API keys, the MCP endpoint's OAuth tokens); pure Bearer callers elsewhere (cron secret, signed webhooks) carry no cookie session and were never touched by the gate, which only fires for cookie users. Superagent P2 on PR #878. Co-Authored-By: Claude Fable 5 <[email protected]> * test: normalize path separators in dimension statutory guard scan The route scan compared walked file paths against a POSIX-path allowlist, so the suite failed on Windows (backslash separators) while passing on Linux CI. Normalize the scanned paths to forward slashes. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5
parent
678f2ccffd
commit
237b77a366
-14
@@ -66,20 +66,6 @@ supabase/.temp/
|
||||
# `npm run taxonomy:check` (core-build.yml) and the golden test pins against
|
||||
# the example document.
|
||||
/dev_docs/*
|
||||
!/dev_docs/bokslut/
|
||||
/dev_docs/bokslut/*
|
||||
!/dev_docs/bokslut/taxonomi/
|
||||
/dev_docs/bokslut/taxonomi/*
|
||||
!/dev_docs/bokslut/taxonomi/taxonomi-paket-2024-09-12_rev20250312.zip
|
||||
!/dev_docs/bokslut/taxonomi/dokumentation/
|
||||
/dev_docs/bokslut/taxonomi/dokumentation/*
|
||||
!/dev_docs/bokslut/taxonomi/dokumentation/k2-ab-arsredovisning-elementlista-2024-09-12_rev20250312_sv.xlsx
|
||||
!/dev_docs/bokslut/taxonomi/dokumentation/tuple-innehallsmodell-arsredovisning-k2-2024-09-12.xlsx
|
||||
!/dev_docs/bokslut/exempel/
|
||||
/dev_docs/bokslut/exempel/*
|
||||
!/dev_docs/bokslut/exempel/k2/
|
||||
/dev_docs/bokslut/exempel/k2/*
|
||||
!/dev_docs/bokslut/exempel/k2/faststalld-arsredovisning-exempel-1-rev20240214.xhtml
|
||||
|
||||
# Extension registry (auto-generated but defaults are committed)
|
||||
# Run `npm run setup:extensions` to regenerate after changing extensions.config.json
|
||||
|
||||
@@ -71,11 +71,20 @@ export const POST = withRouteContext(
|
||||
details: { reason: message },
|
||||
})
|
||||
}
|
||||
// Magic-byte validation rejections (validateDocumentMagicBytes) are a
|
||||
// client problem, not a storage failure — surface as 400 with an
|
||||
// accurate message instead of the misleading "kunde inte sparas".
|
||||
if (/kunde inte verifieras|matchar inte den angivna filtypen/i.test(message)) {
|
||||
opLog.warn('document upload rejected by content validation', { reason: message })
|
||||
return errorResponseFromCode('DOC_UPLOAD_INVALID_CONTENT', opLog, {
|
||||
requestId,
|
||||
details: { reason: message },
|
||||
})
|
||||
}
|
||||
// Full error is logged above; the raw message can leak storage-layer
|
||||
// internals, so the client only gets the generic code + requestId.
|
||||
opLog.error('document upload failed', err as Error)
|
||||
return errorResponseFromCode('DOC_UPLOAD_STORAGE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: message },
|
||||
})
|
||||
return errorResponseFromCode('DOC_UPLOAD_STORAGE_FAILED', opLog, { requestId })
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
makeInvoice,
|
||||
} from '@/tests/helpers'
|
||||
import { encryptPersonnummer } from '@/lib/salary/personnummer'
|
||||
import type { Invoice, InvoiceItem } from '@/types'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
const mockUploadDocument = vi.fn()
|
||||
vi.mock('@/lib/core/documents/document-service', () => ({
|
||||
uploadDocument: (...args: unknown[]) => mockUploadDocument(...args),
|
||||
}))
|
||||
|
||||
const mockCreatePayoutEntry = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/rot-rut-entries', () => ({
|
||||
createRotRutPayoutEntry: (...args: unknown[]) => mockCreatePayoutEntry(...args),
|
||||
}))
|
||||
|
||||
import { GET as eligibleGET } from '../eligible/route'
|
||||
import { POST as payoutFilePOST } from '../payout-file/route'
|
||||
import { GET as requestsGET } from '../payout-requests/route'
|
||||
import { PATCH as requestPATCH } from '../payout-requests/[id]/route'
|
||||
import { POST as settlePOST } from '../payout-requests/[id]/settle/route'
|
||||
|
||||
const INVOICE_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const REQUEST_ID = '22222222-2222-4222-8222-222222222222'
|
||||
// Skatteverket official example personnummer (synthetic).
|
||||
const PNR = '198406012388'
|
||||
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
function makeRotItem(overrides: Partial<InvoiceItem> = {}): InvoiceItem {
|
||||
return {
|
||||
id: 'item-1',
|
||||
invoice_id: INVOICE_ID,
|
||||
sort_order: 0,
|
||||
description: 'Snickeri',
|
||||
quantity: 1,
|
||||
unit: 'tim',
|
||||
unit_price: 10000,
|
||||
line_total: 10000,
|
||||
vat_rate: 25,
|
||||
vat_amount: 2500,
|
||||
deduction_type: 'rot',
|
||||
deduction_amount: 3000,
|
||||
labor_hours: 25,
|
||||
work_type: 'BYGG',
|
||||
housing_designation: 'Stockholm Vasastan 1:23',
|
||||
apartment_number: null,
|
||||
brf_org_number: null,
|
||||
created_at: '2026-06-01T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makePaidRotInvoice(overrides: Partial<Invoice> = {}): Invoice {
|
||||
return makeInvoice({
|
||||
id: INVOICE_ID,
|
||||
status: 'paid',
|
||||
paid_at: '2026-06-20T10:00:00Z',
|
||||
deduction_total: 3000,
|
||||
deduction_personnummer_encrypted: encryptPersonnummer(PNR),
|
||||
items: [makeRotItem()],
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
function makePayoutRequestRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: REQUEST_ID,
|
||||
company_id: 'company-1',
|
||||
user_id: 'user-1',
|
||||
deduction_type: 'rot',
|
||||
name: 'ROT 2026-07-02',
|
||||
status: 'generated',
|
||||
requested_total: 3000,
|
||||
decided_total: null,
|
||||
file_name: 'rot_begaran_2026-07-02.xml',
|
||||
file_document_id: null,
|
||||
settlement_journal_entry_id: null,
|
||||
submitted_at: null,
|
||||
decided_at: null,
|
||||
created_at: '2026-07-02T00:00:00Z',
|
||||
updated_at: '2026-07-02T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
mockUploadDocument.mockResolvedValue({ id: 'doc-1' })
|
||||
})
|
||||
|
||||
describe('GET /api/rot-rut/eligible', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const response = await eligibleGET(createMockRequest('/api/rot-rut/eligible'))
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('splits invoices into eligible and blocked', async () => {
|
||||
const good = makePaidRotInvoice()
|
||||
const missingHours = makePaidRotInvoice({
|
||||
id: '33333333-3333-4333-8333-333333333333',
|
||||
invoice_number: 'F-BAD',
|
||||
items: [makeRotItem({ labor_hours: null })],
|
||||
})
|
||||
enqueue({ data: [good, missingHours] })
|
||||
enqueue({ data: [] }) // no active request items
|
||||
|
||||
const response = await eligibleGET(
|
||||
createMockRequest('/api/rot-rut/eligible', { searchParams: { type: 'rot' } }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { eligible: Array<{ invoice_id: string; begart_belopp: number }>; blocked: Array<{ code: string }> }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.eligible).toHaveLength(1)
|
||||
expect(body.data.eligible[0].invoice_id).toBe(INVOICE_ID)
|
||||
expect(body.data.eligible[0].begart_belopp).toBe(3000)
|
||||
expect(body.data.blocked).toHaveLength(1)
|
||||
expect(body.data.blocked[0].code).toBe('MISSING_HOURS')
|
||||
})
|
||||
|
||||
it('hides invoices already in an active request', async () => {
|
||||
enqueue({ data: [makePaidRotInvoice()] })
|
||||
enqueue({ data: [{ invoice_id: INVOICE_ID, request: { id: 'r', status: 'submitted', company_id: 'company-1' } }] })
|
||||
|
||||
const response = await eligibleGET(createMockRequest('/api/rot-rut/eligible'))
|
||||
const { body } = await parseJsonResponse<{
|
||||
data: { eligible: unknown[]; blocked: unknown[] }
|
||||
}>(response)
|
||||
|
||||
expect(body.data.eligible).toHaveLength(0)
|
||||
expect(body.data.blocked).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('returns 500 on database error', async () => {
|
||||
enqueue({ data: null, error: { message: 'boom' } })
|
||||
const response = await eligibleGET(createMockRequest('/api/rot-rut/eligible'))
|
||||
expect(response.status).toBe(500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/rot-rut/payout-file', () => {
|
||||
const validBody = { deduction_type: 'rot', invoice_ids: [INVOICE_ID] }
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const response = await payoutFilePOST(
|
||||
createMockRequest('/api/rot-rut/payout-file', { method: 'POST', body: validBody }),
|
||||
)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 on invalid body', async () => {
|
||||
const response = await payoutFilePOST(
|
||||
createMockRequest('/api/rot-rut/payout-file', {
|
||||
method: 'POST',
|
||||
body: { deduction_type: 'gront', invoice_ids: [] },
|
||||
}),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('generates the file, records the request and archives the document', async () => {
|
||||
enqueue({ data: [makePaidRotInvoice()] }) // invoices fetch
|
||||
enqueue({ data: makePayoutRequestRow() }) // request insert
|
||||
enqueue({ data: null }) // items insert
|
||||
enqueue({ data: null }) // file_document_id update
|
||||
|
||||
const response = await payoutFilePOST(
|
||||
createMockRequest('/api/rot-rut/payout-file', { method: 'POST', body: validBody }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { xml: string; file_name: string; arenden: unknown[]; request: { id: string } }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.xml).toContain('<ns2:RotBegaran>')
|
||||
expect(body.data.xml).toContain(`<ns2:Kopare>${PNR}</ns2:Kopare>`)
|
||||
expect(body.data.arenden).toHaveLength(1)
|
||||
expect(body.data.request.id).toBe(REQUEST_ID)
|
||||
expect(mockUploadDocument).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects all-or-nothing when a selected invoice is blocked', async () => {
|
||||
enqueue({
|
||||
data: [
|
||||
makePaidRotInvoice(),
|
||||
makePaidRotInvoice({
|
||||
id: '33333333-3333-4333-8333-333333333333',
|
||||
status: 'sent',
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
const response = await payoutFilePOST(
|
||||
createMockRequest('/api/rot-rut/payout-file', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
deduction_type: 'rot',
|
||||
invoice_ids: [INVOICE_ID, '33333333-3333-4333-8333-333333333333'],
|
||||
},
|
||||
}),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: { code: string; details?: { blockers: Array<{ code: string }> } }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('ROT_RUT_INVOICES_BLOCKED')
|
||||
})
|
||||
|
||||
it('returns 404 when an invoice id does not belong to the company', async () => {
|
||||
enqueue({ data: [] })
|
||||
const response = await payoutFilePOST(
|
||||
createMockRequest('/api/rot-rut/payout-file', { method: 'POST', body: validBody }),
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('maps the double-request trigger to 409 and rolls back the header row', async () => {
|
||||
enqueue({ data: [makePaidRotInvoice()] })
|
||||
enqueue({ data: makePayoutRequestRow() })
|
||||
enqueue({ data: null, error: { code: '23505', message: 'already included in an active rot/rut payout request' } })
|
||||
enqueue({ data: null }) // rollback delete
|
||||
|
||||
const response = await payoutFilePOST(
|
||||
createMockRequest('/api/rot-rut/payout-file', { method: 'POST', body: validBody }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('ROT_RUT_INVOICE_CONFLICT')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/rot-rut/payout-requests', () => {
|
||||
it('lists requests', async () => {
|
||||
enqueue({ data: [makePayoutRequestRow()] })
|
||||
const response = await requestsGET(createMockRequest('/api/rot-rut/payout-requests'))
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/rot-rut/payout-requests/[id]', () => {
|
||||
const routeParams = createMockRouteParams({ id: REQUEST_ID })
|
||||
|
||||
it('returns 404 for an unknown request', async () => {
|
||||
enqueue({ data: null })
|
||||
const response = await requestPATCH(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { status: 'submitted' },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('rejects an invalid transition', async () => {
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'paid' }) })
|
||||
const response = await requestPATCH(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { status: 'submitted' },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('ROT_RUT_INVALID_STATUS_TRANSITION')
|
||||
})
|
||||
|
||||
it('requires decided_total for partially_paid', async () => {
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'submitted' }) })
|
||||
const response = await requestPATCH(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { status: 'partially_paid' },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('marks a generated request as submitted', async () => {
|
||||
enqueue({ data: makePayoutRequestRow() })
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'submitted', submitted_at: '2026-07-02T12:00:00Z' }) })
|
||||
|
||||
const response = await requestPATCH(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { status: 'submitted' },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { status: string } }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.status).toBe('submitted')
|
||||
})
|
||||
|
||||
it('records a rejection with decided_total 0', async () => {
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'submitted' }) })
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'rejected', decided_total: 0 }) })
|
||||
|
||||
const response = await requestPATCH(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { status: 'rejected' },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { status: string } }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.status).toBe('rejected')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/rot-rut/payout-requests/[id]/settle', () => {
|
||||
const routeParams = createMockRouteParams({ id: REQUEST_ID })
|
||||
const settleBody = { payment_date: '2026-07-10' }
|
||||
|
||||
it('returns 404 for an unknown request', async () => {
|
||||
enqueue({ data: null })
|
||||
const response = await settlePOST(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/settle`, {
|
||||
method: 'POST',
|
||||
body: settleBody,
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('refuses an already settled request', async () => {
|
||||
enqueue({
|
||||
data: makePayoutRequestRow({
|
||||
status: 'paid',
|
||||
settlement_journal_entry_id: 'je-1',
|
||||
}),
|
||||
})
|
||||
const response = await settlePOST(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/settle`, {
|
||||
method: 'POST',
|
||||
body: settleBody,
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('ROT_RUT_SETTLE_INVALID_STATE')
|
||||
})
|
||||
|
||||
it('books the payout and completes the request as paid', async () => {
|
||||
mockCreatePayoutEntry.mockResolvedValue({ id: 'je-1' })
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'submitted' }) })
|
||||
enqueue({
|
||||
data: makePayoutRequestRow({
|
||||
status: 'paid',
|
||||
settlement_journal_entry_id: 'je-1',
|
||||
decided_total: 3000,
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [{ id: 'item-1', requested_amount: 3000 }] })
|
||||
enqueue({ data: null }) // item decided_amount update
|
||||
|
||||
const response = await settlePOST(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/settle`, {
|
||||
method: 'POST',
|
||||
body: settleBody,
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { journal_entry_id: string; request: { status: string } }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.journal_entry_id).toBe('je-1')
|
||||
expect(body.data.request.status).toBe('paid')
|
||||
expect(mockCreatePayoutEntry).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({ amount: 3000, paymentDate: '2026-07-10' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards bank_account to the engine and defaults it to undefined', async () => {
|
||||
mockCreatePayoutEntry.mockResolvedValue({ id: 'je-3' })
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'submitted' }) })
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'paid', settlement_journal_entry_id: 'je-3' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const response = await settlePOST(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/settle`, {
|
||||
method: 'POST',
|
||||
body: { payment_date: '2026-07-10', bank_account: '1920' },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockCreatePayoutEntry).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({ bankAccount: '1920' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a non-19xx bank_account', async () => {
|
||||
const response = await settlePOST(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/settle`, {
|
||||
method: 'POST',
|
||||
body: { payment_date: '2026-07-10', bank_account: '3001' },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('books a partial payout as partially_paid once the beslut is recorded', async () => {
|
||||
mockCreatePayoutEntry.mockResolvedValue({ id: 'je-2' })
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'submitted', decided_total: 2000 }) })
|
||||
enqueue({
|
||||
data: makePayoutRequestRow({ status: 'partially_paid', decided_total: 2000 }),
|
||||
})
|
||||
|
||||
const response = await settlePOST(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/settle`, {
|
||||
method: 'POST',
|
||||
body: { payment_date: '2026-07-10', amount: 2000 },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { request: { status: string } } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.request.status).toBe('partially_paid')
|
||||
})
|
||||
|
||||
it('refuses a partial settlement before the beslut is recorded', async () => {
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'submitted', decided_total: null }) })
|
||||
|
||||
const response = await settlePOST(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/settle`, {
|
||||
method: 'POST',
|
||||
body: { payment_date: '2026-07-10', amount: 2000 },
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).not.toBe(200)
|
||||
expect(body.error.code).toBe('ROT_RUT_SETTLE_INVALID_STATE')
|
||||
expect(mockCreatePayoutEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 500 and does not update the request when the engine fails', async () => {
|
||||
mockCreatePayoutEntry.mockRejectedValue(new Error('period locked'))
|
||||
enqueue({ data: makePayoutRequestRow({ status: 'submitted' }) })
|
||||
|
||||
const response = await settlePOST(
|
||||
createMockRequest(`/api/rot-rut/payout-requests/${REQUEST_ID}/settle`, {
|
||||
method: 'POST',
|
||||
body: settleBody,
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
expect(response.status).toBe(500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { listRotRutCandidates } from '@/lib/invoices/rot-rut-service'
|
||||
|
||||
/**
|
||||
* GET /api/rot-rut/eligible?type=rot|rut
|
||||
*
|
||||
* Lists paid invoices carrying a ROT/RUT claim that are NOT yet part of an
|
||||
* active begäran om utbetalning, split into:
|
||||
* - eligible: ready for file generation (with the amounts the file will use)
|
||||
* - blocked: excluded, with the exact blocker (same evaluation as the
|
||||
* generator — what this endpoint approves, the file accepts)
|
||||
*/
|
||||
export const GET = withRouteContext('rot_rut.eligible', async (request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const typeParam = searchParams.get('type')
|
||||
const type = typeParam === 'rut' ? 'rut' : 'rot'
|
||||
|
||||
const result = await listRotRutCandidates(supabase, companyId!, type)
|
||||
if (!result.ok) {
|
||||
log.error('failed to list rot/rut candidates', result.dbError as Error)
|
||||
return errorResponse(result.dbError, log, { requestId })
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: { type, eligible: result.eligible, blocked: result.blocked },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { RotRutPayoutFileSchema } from '@/lib/api/schemas'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { createRotRutPayoutRequest } from '@/lib/invoices/rot-rut-service'
|
||||
import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||
|
||||
/**
|
||||
* POST /api/rot-rut/payout-file
|
||||
*
|
||||
* Generates the begäran-om-utbetalning XML (Skatteverket husavdrag, schema
|
||||
* V6) for the selected invoices, records a rot_rut_payout_requests row (one
|
||||
* active begäran per invoice — DB-enforced), archives the file as
|
||||
* räkenskapsinformation, and returns the XML for download.
|
||||
*
|
||||
* All-or-nothing: if any selected invoice fails eligibility the request is
|
||||
* rejected with per-invoice blockers — a silently thinner file would be a
|
||||
* guess about the user's intent.
|
||||
*
|
||||
* DELIBERATE: the XML (which embeds buyers' personnummer, as Skatteverkets
|
||||
* schema requires) is returned inline. The file only exists to be saved and
|
||||
* uploaded manually on skatteverket.se — there is no UI download surface for
|
||||
* this headless flow, and a document-reference indirection would dead-end the
|
||||
* user whenever the (best-effort) archive failed. Transport is TLS,
|
||||
* authenticated, MFA-gated and write-role-gated via withRouteContext.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'rot_rut.payout_file',
|
||||
async (request, ctx) => {
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const validation = await validateBody(request, RotRutPayoutFileSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const input = validation.data
|
||||
|
||||
const result = await createRotRutPayoutRequest(supabase, companyId!, user.id, {
|
||||
type: input.deduction_type,
|
||||
invoiceIds: input.invoice_ids,
|
||||
name: input.name,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
return errorResponseFromCode(result.code, log, {
|
||||
requestId,
|
||||
details: {
|
||||
...(result.blockers ? { blockers: result.blockers } : {}),
|
||||
...(result.missingInvoiceIds ? { missing_invoice_ids: result.missingInvoiceIds } : {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Archive the XML as räkenskapsinformation (7-year retention via the
|
||||
// document WORM chain). Best-effort: the user gets the file either way
|
||||
// and can re-generate; a failed archive must not orphan the begäran.
|
||||
let fileDocumentId: string | null = null
|
||||
try {
|
||||
const buffer = new TextEncoder().encode(result.file.xml!).buffer as ArrayBuffer
|
||||
const doc = await uploadDocument(
|
||||
supabase,
|
||||
user.id,
|
||||
companyId!,
|
||||
{ name: result.file.file_name, buffer },
|
||||
{ upload_source: 'system' },
|
||||
)
|
||||
fileDocumentId = doc.id
|
||||
await supabase
|
||||
.from('rot_rut_payout_requests')
|
||||
.update({ file_document_id: doc.id })
|
||||
.eq('id', result.request.id as string)
|
||||
} catch (docError) {
|
||||
log.error('failed to archive rot/rut payout file document', docError as Error)
|
||||
}
|
||||
|
||||
log.info('rot/rut payout file generated', {
|
||||
requestId: result.request.id,
|
||||
type: input.deduction_type,
|
||||
arenden: result.file.arenden.length,
|
||||
requestedTotal: result.file.requested_total,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
request: { ...result.request, file_document_id: fileDocumentId },
|
||||
xml: result.file.xml,
|
||||
file_name: result.file.file_name,
|
||||
arenden: result.file.arenden,
|
||||
warnings: result.file.warnings,
|
||||
},
|
||||
})
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,139 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { RotRutRequestPatchSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { RotRutPayoutRequestStatus } from '@/types'
|
||||
|
||||
/**
|
||||
* Forward-only lifecycle. Reactivation of cancelled/rejected begäran is
|
||||
* deliberately impossible from the API (and double-guarded by the DB
|
||||
* trigger enforce_rot_rut_request_reactivation) — retry after avslag means
|
||||
* generating a NEW file, mirroring how Skatteverkets e-tjänst works.
|
||||
*/
|
||||
const ALLOWED_TRANSITIONS: Record<RotRutPayoutRequestStatus, RotRutPayoutRequestStatus[]> = {
|
||||
generated: ['submitted', 'cancelled'],
|
||||
submitted: ['paid', 'partially_paid', 'rejected', 'cancelled'],
|
||||
paid: [],
|
||||
partially_paid: [],
|
||||
rejected: [],
|
||||
cancelled: [],
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/rot-rut/payout-requests/[id]
|
||||
*
|
||||
* Advance the begäran lifecycle: mark the file as uploaded (submitted), or
|
||||
* record Skatteverkets beslut (paid / partially_paid / rejected +
|
||||
* decided_total). Booking the actual payout is POST [id]/settle.
|
||||
*/
|
||||
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'rot_rut.requests.patch',
|
||||
async (request, ctx, { params }) => {
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
const { id } = await params
|
||||
|
||||
const validation = await validateBody(request, RotRutRequestPatchSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const input = validation.data
|
||||
|
||||
const { data: payoutRequest, error: fetchError } = await supabase
|
||||
.from('rot_rut_payout_requests')
|
||||
.select('*')
|
||||
.eq('company_id', companyId!)
|
||||
.eq('id', id)
|
||||
.maybeSingle()
|
||||
|
||||
if (fetchError) {
|
||||
log.error('failed to fetch rot/rut payout request', fetchError)
|
||||
return errorResponse(fetchError, log, { requestId })
|
||||
}
|
||||
if (!payoutRequest) {
|
||||
return errorResponseFromCode('ROT_RUT_REQUEST_NOT_FOUND', log, { requestId })
|
||||
}
|
||||
|
||||
const from = payoutRequest.status as RotRutPayoutRequestStatus
|
||||
if (!ALLOWED_TRANSITIONS[from]?.includes(input.status)) {
|
||||
return errorResponseFromCode('ROT_RUT_INVALID_STATUS_TRANSITION', log, {
|
||||
requestId,
|
||||
details: { from, to: input.status },
|
||||
})
|
||||
}
|
||||
// Partial approval without the approved amount is meaningless.
|
||||
if (input.status === 'partially_paid' && input.decided_total === undefined) {
|
||||
return errorResponseFromCode('ROT_RUT_INVALID_STATUS_TRANSITION', log, {
|
||||
requestId,
|
||||
details: { from, to: input.status, reason: 'decided_total krävs för delvis beviljad' },
|
||||
})
|
||||
}
|
||||
|
||||
const now = new Date().toISOString()
|
||||
const update: Record<string, unknown> = { status: input.status }
|
||||
if (input.status === 'submitted') {
|
||||
update.submitted_at = now
|
||||
}
|
||||
if (input.status === 'paid' || input.status === 'partially_paid' || input.status === 'rejected') {
|
||||
update.decided_at = now
|
||||
update.decided_total =
|
||||
input.decided_total ??
|
||||
(input.status === 'paid' ? payoutRequest.requested_total : 0)
|
||||
}
|
||||
|
||||
const { data: updated, error: updateError } = await supabase
|
||||
.from('rot_rut_payout_requests')
|
||||
.update(update)
|
||||
.eq('company_id', companyId!)
|
||||
.eq('id', id)
|
||||
.select(
|
||||
'id, name, deduction_type, status, requested_total, decided_total, submitted_at, decided_at, settlement_journal_entry_id',
|
||||
)
|
||||
.single()
|
||||
|
||||
if (updateError) {
|
||||
log.error('failed to update rot/rut payout request', updateError)
|
||||
return errorResponse(updateError, log, { requestId })
|
||||
}
|
||||
|
||||
// Status transitions record Skatteverkets beslut — the audit trail must
|
||||
// show who recorded them.
|
||||
log.info('rot/rut payout request status changed', {
|
||||
userId: user.id,
|
||||
payoutRequestId: id,
|
||||
from,
|
||||
to: input.status,
|
||||
decidedTotal: update.decided_total ?? null,
|
||||
})
|
||||
|
||||
// Full approval: mirror the per-invoice godkänt belopp onto the items.
|
||||
// Partial approval leaves item amounts null — the split is only known
|
||||
// from Skatteverkets beslut, never guessed.
|
||||
if (input.status === 'paid' && input.decided_total === undefined) {
|
||||
const { data: items, error: itemsFetchError } = await supabase
|
||||
.from('rot_rut_payout_request_items')
|
||||
.select('id, requested_amount')
|
||||
.eq('request_id', id)
|
||||
if (itemsFetchError) {
|
||||
log.warn('failed to fetch items for decided_amount mirror', {
|
||||
requestId: id,
|
||||
message: itemsFetchError.message,
|
||||
})
|
||||
} else {
|
||||
for (const item of items ?? []) {
|
||||
const { error: mirrorError } = await supabase
|
||||
.from('rot_rut_payout_request_items')
|
||||
.update({ decided_amount: item.requested_amount })
|
||||
.eq('id', item.id)
|
||||
if (mirrorError) {
|
||||
log.warn('failed to mirror decided_amount onto item', {
|
||||
itemId: item.id,
|
||||
message: mirrorError.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: updated })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,162 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { RotRutSettleSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { createRotRutPayoutEntry } from '@/lib/bookkeeping/rot-rut-entries'
|
||||
|
||||
/**
|
||||
* POST /api/rot-rut/payout-requests/[id]/settle
|
||||
*
|
||||
* Books Skatteverkets utbetalning for a begäran:
|
||||
*
|
||||
* Debit 19xx bank account (default 1930) [amount]
|
||||
* Credit 1513 Skattereduktion rot/rut [amount]
|
||||
*
|
||||
* The journal entry IS the accounting record here, so engine failure blocks
|
||||
* the operation (see .claude/skills/erp-api-route — payment entries block).
|
||||
* amount defaults to decided_total, falling back to requested_total. If the
|
||||
* amount equals requested_total the request completes as 'paid'; anything
|
||||
* lower records 'partially_paid' with decided_total = amount.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'rot_rut.requests.settle',
|
||||
async (request, ctx, { params }) => {
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
const { id } = await params
|
||||
|
||||
const validation = await validateBody(request, RotRutSettleSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const input = validation.data
|
||||
|
||||
const { data: payoutRequest, error: fetchError } = await supabase
|
||||
.from('rot_rut_payout_requests')
|
||||
.select('*')
|
||||
.eq('company_id', companyId!)
|
||||
.eq('id', id)
|
||||
.maybeSingle()
|
||||
|
||||
if (fetchError) {
|
||||
log.error('failed to fetch rot/rut payout request', fetchError)
|
||||
return errorResponse(fetchError, log, { requestId })
|
||||
}
|
||||
if (!payoutRequest) {
|
||||
return errorResponseFromCode('ROT_RUT_REQUEST_NOT_FOUND', log, { requestId })
|
||||
}
|
||||
|
||||
const settleable =
|
||||
!payoutRequest.settlement_journal_entry_id &&
|
||||
!['cancelled', 'rejected'].includes(payoutRequest.status)
|
||||
if (!settleable) {
|
||||
return errorResponseFromCode('ROT_RUT_SETTLE_INVALID_STATE', log, {
|
||||
requestId,
|
||||
details: {
|
||||
status: payoutRequest.status,
|
||||
already_settled: !!payoutRequest.settlement_journal_entry_id,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const amount =
|
||||
input.amount ?? Number(payoutRequest.decided_total ?? payoutRequest.requested_total)
|
||||
|
||||
// A partial settlement must follow a recorded beslut: without this guard a
|
||||
// settle with amount < requested_total on an undecided request would flip
|
||||
// it to partially_paid while bypassing the PATCH lifecycle rule that
|
||||
// partially_paid requires decided_total — the beslut would never be
|
||||
// recorded and later PATCH calls would be blocked by ALLOWED_TRANSITIONS.
|
||||
if (amount < Number(payoutRequest.requested_total) && payoutRequest.decided_total == null) {
|
||||
return errorResponseFromCode('ROT_RUT_SETTLE_INVALID_STATE', log, {
|
||||
requestId,
|
||||
details: {
|
||||
status: payoutRequest.status,
|
||||
reason:
|
||||
'Delutbetalning kräver att Skatteverkets beslut registreras först (decided_total via PATCH).',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// The voucher is the accounting record — engine failure must block.
|
||||
let journalEntryId: string
|
||||
try {
|
||||
const entry = await createRotRutPayoutEntry(supabase, companyId!, user.id, {
|
||||
requestId: payoutRequest.id,
|
||||
requestName: payoutRequest.name,
|
||||
deductionType: payoutRequest.deduction_type,
|
||||
paymentDate: input.payment_date,
|
||||
amount,
|
||||
bankAccount: input.bank_account,
|
||||
})
|
||||
journalEntryId = entry.id
|
||||
} catch (engineError) {
|
||||
log.error('failed to book rot/rut payout entry', engineError as Error)
|
||||
return errorResponse(engineError, log, { requestId })
|
||||
}
|
||||
|
||||
const fullyPaid = amount >= Number(payoutRequest.requested_total)
|
||||
const update: Record<string, unknown> = {
|
||||
settlement_journal_entry_id: journalEntryId,
|
||||
status: fullyPaid ? 'paid' : 'partially_paid',
|
||||
decided_total: payoutRequest.decided_total ?? amount,
|
||||
}
|
||||
if (!payoutRequest.decided_at) {
|
||||
update.decided_at = new Date().toISOString()
|
||||
}
|
||||
|
||||
const { data: updated, error: updateError } = await supabase
|
||||
.from('rot_rut_payout_requests')
|
||||
.update(update)
|
||||
.eq('company_id', companyId!)
|
||||
.eq('id', id)
|
||||
.select(
|
||||
'id, name, deduction_type, status, requested_total, decided_total, decided_at, settlement_journal_entry_id',
|
||||
)
|
||||
.single()
|
||||
|
||||
if (updateError) {
|
||||
// The voucher exists (immutable per BFL) but the request row didn't
|
||||
// absorb the link — surface loudly, do NOT try to unbook.
|
||||
log.error('rot/rut payout entry booked but request update failed', updateError, {
|
||||
journalEntryId,
|
||||
payoutRequestId: id,
|
||||
})
|
||||
return errorResponse(updateError, log, { requestId })
|
||||
}
|
||||
|
||||
if (fullyPaid) {
|
||||
const { data: items, error: itemsFetchError } = await supabase
|
||||
.from('rot_rut_payout_request_items')
|
||||
.select('id, requested_amount')
|
||||
.eq('request_id', id)
|
||||
if (itemsFetchError) {
|
||||
log.warn('failed to fetch items for decided_amount mirror', {
|
||||
payoutRequestId: id,
|
||||
message: itemsFetchError.message,
|
||||
})
|
||||
}
|
||||
for (const item of items ?? []) {
|
||||
const { error: mirrorError } = await supabase
|
||||
.from('rot_rut_payout_request_items')
|
||||
.update({ decided_amount: item.requested_amount })
|
||||
.eq('id', item.id)
|
||||
if (mirrorError) {
|
||||
log.warn('failed to mirror decided_amount onto item', {
|
||||
itemId: item.id,
|
||||
message: mirrorError.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info('rot/rut payout settled', {
|
||||
userId: user.id,
|
||||
payoutRequestId: id,
|
||||
journalEntryId,
|
||||
amount,
|
||||
fullyPaid,
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: { request: updated, journal_entry_id: journalEntryId } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
|
||||
/**
|
||||
* GET /api/rot-rut/payout-requests
|
||||
*
|
||||
* Request history (all statuses), newest first, with per-invoice items.
|
||||
*/
|
||||
export const GET = withRouteContext('rot_rut.requests.list', async (request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const typeFilter = searchParams.get('type')
|
||||
|
||||
// Explicit projections — the history list needs identifiers and amounts,
|
||||
// not every column (and never customer ids through the invoice join).
|
||||
let query = supabase
|
||||
.from('rot_rut_payout_requests')
|
||||
.select(
|
||||
'id, name, deduction_type, status, requested_total, decided_total, file_name, file_document_id, ' +
|
||||
'created_at, submitted_at, decided_at, settlement_journal_entry_id, ' +
|
||||
'items:rot_rut_payout_request_items(id, invoice_id, requested_amount, decided_amount, ' +
|
||||
'invoice:invoices(id, invoice_number))',
|
||||
)
|
||||
.eq('company_id', companyId!)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(100)
|
||||
|
||||
if (typeFilter === 'rot' || typeFilter === 'rut') {
|
||||
query = query.eq('deduction_type', typeFilter)
|
||||
}
|
||||
|
||||
const { data, error } = await query
|
||||
if (error) {
|
||||
log.error('failed to list rot/rut payout requests', error)
|
||||
return errorResponse(error, log, { requestId })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
})
|
||||
@@ -289,10 +289,22 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
{ requestId: ctx.requestId },
|
||||
)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'unknown'
|
||||
// Magic-byte validation rejections (validateDocumentMagicBytes) are a
|
||||
// client problem, not a storage failure — surface as 400 with an
|
||||
// accurate message instead of the misleading "kunde inte sparas".
|
||||
if (/kunde inte verifieras|matchar inte den angivna filtypen/i.test(message)) {
|
||||
opLog.warn('document upload rejected by content validation', { reason: message })
|
||||
return v1ErrorResponseFromCode('DOC_UPLOAD_INVALID_CONTENT', opLog, {
|
||||
requestId: ctx.requestId,
|
||||
details: { reason: message },
|
||||
})
|
||||
}
|
||||
// Full error is logged above; the raw message can leak storage-layer
|
||||
// internals, so the client only gets the generic code + requestId.
|
||||
opLog.error('document upload failed', err as Error)
|
||||
return v1ErrorResponseFromCode('DOC_UPLOAD_STORAGE_FAILED', opLog, {
|
||||
requestId: ctx.requestId,
|
||||
details: { reason: err instanceof Error ? err.message : 'unknown' },
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
@@ -49,6 +49,11 @@ export default function AccountCombobox({ value, accounts, onChange, onCommit, o
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const internalInputRef = useRef<HTMLInputElement>(null)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
// Whether the user has typed or arrow-navigated since the field was focused.
|
||||
// Enter only selects the highlighted item after an actual interaction — a
|
||||
// bare Enter on a freshly-focused field must not grab the first account in
|
||||
// the list (it either re-commits the current value or bubbles to the form).
|
||||
const hasInteractedRef = useRef(false)
|
||||
|
||||
// Attach the internal ref (used for focus bookkeeping) and forward the element
|
||||
// to any external callback ref the parent passed.
|
||||
@@ -140,8 +145,14 @@ export default function AccountCombobox({ value, accounts, onChange, onCommit, o
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (!isOpen) {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
hasInteractedRef.current = true
|
||||
setIsOpen(true)
|
||||
e.preventDefault()
|
||||
} else if (e.key === 'Enter' && /^\d{4}$/.test(search)) {
|
||||
// Dropdown closed but a full account number sits in the field — treat
|
||||
// Enter as a re-commit so focus advances to the amount field.
|
||||
e.preventDefault()
|
||||
onCommit?.(search)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -149,16 +160,27 @@ export default function AccountCombobox({ value, accounts, onChange, onCommit, o
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault()
|
||||
hasInteractedRef.current = true
|
||||
setHighlightedIndex((prev) => Math.min(prev + 1, flatList.length - 1))
|
||||
break
|
||||
case 'ArrowUp':
|
||||
e.preventDefault()
|
||||
hasInteractedRef.current = true
|
||||
setHighlightedIndex((prev) => Math.max(prev - 1, 0))
|
||||
break
|
||||
case 'Enter':
|
||||
e.preventDefault()
|
||||
if (flatList[highlightedIndex]) {
|
||||
if (hasInteractedRef.current && flatList[highlightedIndex]) {
|
||||
e.preventDefault()
|
||||
selectAccount(flatList[highlightedIndex].account_number)
|
||||
} else if (/^\d{4}$/.test(search)) {
|
||||
// Committed number, no new interaction — advance without re-selecting.
|
||||
e.preventDefault()
|
||||
setIsOpen(false)
|
||||
onCommit?.(search)
|
||||
} else {
|
||||
// Nothing actively chosen — close the list and let the event bubble
|
||||
// so the form-level Enter (open review when balanced) can take over.
|
||||
setIsOpen(false)
|
||||
}
|
||||
break
|
||||
case 'Escape':
|
||||
@@ -170,6 +192,7 @@ export default function AccountCombobox({ value, accounts, onChange, onCommit, o
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value
|
||||
hasInteractedRef.current = true
|
||||
setSearch(newValue)
|
||||
// Emit any 4-digit numeric value to the parent. Unknown BAS numbers are
|
||||
// accepted optimistically — the submit-time ActivateAccountsDialog lets
|
||||
@@ -193,6 +216,7 @@ export default function AccountCombobox({ value, accounts, onChange, onCommit, o
|
||||
}
|
||||
|
||||
const handleFocus = () => {
|
||||
hasInteractedRef.current = false
|
||||
setIsOpen(true)
|
||||
}
|
||||
|
||||
|
||||
@@ -165,11 +165,16 @@ export default function JournalEntryForm({
|
||||
// user typed in the combobox so we can prefill the dialog.
|
||||
const [creatingAccountForLine, setCreatingAccountForLine] = useState<number | null>(null)
|
||||
const [createAccountPrefill, setCreateAccountPrefill] = useState<string>('')
|
||||
// Per-row refs to the debit inputs so we can auto-advance focus there once an
|
||||
// account is committed on a row. Two layouts render simultaneously (mobile
|
||||
// cards + desktop table); we focus whichever one is actually visible.
|
||||
// Per-row refs to the account/debit/credit inputs so the keyboard flow can
|
||||
// advance focus with Enter: konto → debet → kredit → nästa rads konto. Two
|
||||
// layouts render simultaneously (mobile cards + desktop table); we focus
|
||||
// whichever one is actually visible.
|
||||
const desktopAccountRefs = useRef<(HTMLInputElement | null)[]>([])
|
||||
const mobileAccountRefs = useRef<(HTMLInputElement | null)[]>([])
|
||||
const desktopDebitRefs = useRef<(HTMLInputElement | null)[]>([])
|
||||
const mobileDebitRefs = useRef<(HTMLInputElement | null)[]>([])
|
||||
const desktopCreditRefs = useRef<(HTMLInputElement | null)[]>([])
|
||||
const mobileCreditRefs = useRef<(HTMLInputElement | null)[]>([])
|
||||
// Confirm button in the inline (bare) review, focused on open so Enter posts.
|
||||
const bareConfirmRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
@@ -512,18 +517,37 @@ export default function JournalEntryForm({
|
||||
updateLine(index, side === 'debit' ? 'debit_amount' : 'credit_amount', fill.toFixed(2))
|
||||
}
|
||||
|
||||
// Move focus to a row's debit input. Deferred a frame so it runs after any
|
||||
// Move focus to a row's input. Deferred a frame so it runs after any
|
||||
// re-render (e.g. the auto-appended trailing row). offsetParent is null for
|
||||
// display:none elements, so this picks whichever layout is currently visible.
|
||||
const focusDebit = useCallback((index: number) => {
|
||||
requestAnimationFrame(() => {
|
||||
const d = desktopDebitRefs.current[index]
|
||||
const m = mobileDebitRefs.current[index]
|
||||
const target = d && d.offsetParent !== null ? d : m && m.offsetParent !== null ? m : (d ?? m)
|
||||
target?.focus()
|
||||
target?.select?.()
|
||||
})
|
||||
}, [])
|
||||
const focusRowInput = useCallback(
|
||||
(
|
||||
desktop: React.RefObject<(HTMLInputElement | null)[]>,
|
||||
mobile: React.RefObject<(HTMLInputElement | null)[]>,
|
||||
index: number
|
||||
) => {
|
||||
requestAnimationFrame(() => {
|
||||
const d = desktop.current?.[index]
|
||||
const m = mobile.current?.[index]
|
||||
const target = d && d.offsetParent !== null ? d : m && m.offsetParent !== null ? m : (d ?? m)
|
||||
target?.focus()
|
||||
target?.select?.()
|
||||
})
|
||||
},
|
||||
[]
|
||||
)
|
||||
const focusAccount = useCallback(
|
||||
(index: number) => focusRowInput(desktopAccountRefs, mobileAccountRefs, index),
|
||||
[focusRowInput]
|
||||
)
|
||||
const focusDebit = useCallback(
|
||||
(index: number) => focusRowInput(desktopDebitRefs, mobileDebitRefs, index),
|
||||
[focusRowInput]
|
||||
)
|
||||
const focusCredit = useCallback(
|
||||
(index: number) => focusRowInput(desktopCreditRefs, mobileCreditRefs, index),
|
||||
[focusRowInput]
|
||||
)
|
||||
|
||||
// Keep exactly one trailing blank row so the user never has to click "Lägg
|
||||
// till rad": once the last row is started (account or amount), append a fresh
|
||||
@@ -676,6 +700,44 @@ export default function JournalEntryForm({
|
||||
if (canSubmitReview()) handleReview()
|
||||
}
|
||||
|
||||
// Enter-to-advance inside the konteringsrader: konto → debet → kredit →
|
||||
// nästa rads konto. Navigation only fires while the entry is NOT
|
||||
// submittable — once the voucher balances, Enter falls through to the
|
||||
// form-level handler above and opens the review instead, so a single Enter
|
||||
// never both moves focus and submits.
|
||||
const handleAmountKeyDown =
|
||||
(index: number, side: 'debit' | 'credit') =>
|
||||
(e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key !== 'Enter' || canSubmitReview()) return
|
||||
e.preventDefault()
|
||||
// An amount on this side finishes the row (debit clears credit and vice
|
||||
// versa) → jump to the next row's account. An empty debit means the row
|
||||
// books on the credit side → hop across first.
|
||||
if (side === 'debit' && !(parseFloat(lines[index].debit_amount) > 0)) {
|
||||
focusCredit(index)
|
||||
} else {
|
||||
focusAccount(index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
// Enter in a radbeskrivning continues to that row's amount.
|
||||
const handleLineDescKeyDown =
|
||||
(index: number) => (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key !== 'Enter' || canSubmitReview()) return
|
||||
e.preventDefault()
|
||||
focusDebit(index)
|
||||
}
|
||||
|
||||
// Enter in the verifikationstext drops into the first row still missing an
|
||||
// account, so the top-to-bottom keyboard flow never needs the mouse.
|
||||
const handleHeaderDescKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key !== 'Enter' || canSubmitReview()) return
|
||||
const idx = lines.findIndex((l) => !l.account_number)
|
||||
if (idx === -1) return
|
||||
e.preventDefault()
|
||||
focusAccount(idx)
|
||||
}
|
||||
|
||||
// Inner submit: builds payload, POSTs, throws a structured error on failure
|
||||
// (so the activation hook can intercept ACCOUNTS_NOT_IN_CHART).
|
||||
const postJournalEntry = useCallback(async () => {
|
||||
@@ -929,7 +991,17 @@ export default function JournalEntryForm({
|
||||
// summary instead of stacking a second dialog over the form dialog. The
|
||||
// no-underlag caveat folds in here so there's a single confirm step.
|
||||
const reviewPanel = (
|
||||
<div className="space-y-4">
|
||||
<div
|
||||
className="space-y-4"
|
||||
// The host dialog swallows Escape (accidental-close guard), so Escape
|
||||
// here is free to mean "back to the form" — keyboard mirror of ←.
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape' && !isSubmitting) {
|
||||
e.stopPropagation()
|
||||
setShowReview(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
@@ -1022,6 +1094,7 @@ export default function JournalEntryForm({
|
||||
<Input
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
onKeyDown={handleHeaderDescKeyDown}
|
||||
placeholder={t('description_placeholder')}
|
||||
className="mt-1 h-8"
|
||||
/>
|
||||
@@ -1223,6 +1296,7 @@ export default function JournalEntryForm({
|
||||
onChange={(num) => updateLine(index, 'account_number', num)}
|
||||
onCommit={() => focusDebit(index)}
|
||||
onCreateAccount={(prefill) => handleOpenCreateAccount(index, prefill)}
|
||||
inputRef={(el) => { mobileAccountRefs.current[index] = el }}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
@@ -1238,6 +1312,7 @@ export default function JournalEntryForm({
|
||||
<Input
|
||||
value={line.line_description}
|
||||
onChange={(e) => updateLine(index, 'line_description', e.target.value)}
|
||||
onKeyDown={handleLineDescKeyDown(index)}
|
||||
placeholder={t('line_description_placeholder')}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
@@ -1248,6 +1323,7 @@ export default function JournalEntryForm({
|
||||
type="number"
|
||||
value={line.debit_amount}
|
||||
onChange={(e) => updateLine(index, 'debit_amount', e.target.value)}
|
||||
onKeyDown={handleAmountKeyDown(index, 'debit')}
|
||||
onDoubleClick={() => handleFillBalance(index, 'debit')}
|
||||
title={t('fill_balance_tooltip')}
|
||||
placeholder="0,00"
|
||||
@@ -1260,9 +1336,11 @@ export default function JournalEntryForm({
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs text-muted-foreground">{t('col_credit')}</Label>
|
||||
<Input
|
||||
ref={(el) => { mobileCreditRefs.current[index] = el }}
|
||||
type="number"
|
||||
value={line.credit_amount}
|
||||
onChange={(e) => updateLine(index, 'credit_amount', e.target.value)}
|
||||
onKeyDown={handleAmountKeyDown(index, 'credit')}
|
||||
onDoubleClick={() => handleFillBalance(index, 'credit')}
|
||||
title={t('fill_balance_tooltip')}
|
||||
placeholder="0,00"
|
||||
@@ -1348,6 +1426,7 @@ export default function JournalEntryForm({
|
||||
onChange={(num) => updateLine(index, 'account_number', num)}
|
||||
onCommit={() => focusDebit(index)}
|
||||
onCreateAccount={(prefill) => handleOpenCreateAccount(index, prefill)}
|
||||
inputRef={(el) => { desktopAccountRefs.current[index] = el }}
|
||||
className="h-8"
|
||||
/>
|
||||
</td>
|
||||
@@ -1355,6 +1434,7 @@ export default function JournalEntryForm({
|
||||
<Input
|
||||
value={line.line_description}
|
||||
onChange={(e) => updateLine(index, 'line_description', e.target.value)}
|
||||
onKeyDown={handleLineDescKeyDown(index)}
|
||||
placeholder={t('line_description_placeholder')}
|
||||
className="h-8"
|
||||
/>
|
||||
@@ -1372,6 +1452,7 @@ export default function JournalEntryForm({
|
||||
type="number"
|
||||
value={line.debit_amount}
|
||||
onChange={(e) => updateLine(index, 'debit_amount', e.target.value)}
|
||||
onKeyDown={handleAmountKeyDown(index, 'debit')}
|
||||
onDoubleClick={() => handleFillBalance(index, 'debit')}
|
||||
title={t('fill_balance_tooltip')}
|
||||
placeholder="0,00"
|
||||
@@ -1383,9 +1464,11 @@ export default function JournalEntryForm({
|
||||
</td>
|
||||
<td className="py-1.5 px-1">
|
||||
<Input
|
||||
ref={(el) => { desktopCreditRefs.current[index] = el }}
|
||||
type="number"
|
||||
value={line.credit_amount}
|
||||
onChange={(e) => updateLine(index, 'credit_amount', e.target.value)}
|
||||
onKeyDown={handleAmountKeyDown(index, 'credit')}
|
||||
onDoubleClick={() => handleFillBalance(index, 'credit')}
|
||||
title={t('fill_balance_tooltip')}
|
||||
placeholder="0,00"
|
||||
@@ -1504,7 +1587,9 @@ export default function JournalEntryForm({
|
||||
entityType={company?.entity_type}
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-1.5 text-xs text-muted-foreground">{t('fill_balance_hint')}</p>
|
||||
<p className="mt-1.5 text-xs text-muted-foreground">
|
||||
{t('fill_balance_hint')} {t('keyboard_hint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Document attachments — hidden when editing a draft; underlag is
|
||||
@@ -1666,6 +1751,7 @@ export default function JournalEntryForm({
|
||||
setShowReview(true)
|
||||
}}
|
||||
isSubmitting={false}
|
||||
autoFocusConfirm
|
||||
title={t('no_doc_dialog_title')}
|
||||
warningText={t('no_doc_dialog_warning')}
|
||||
confirmLabel={t('no_doc_confirm')}
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { AlertTriangle, Check, Copy, Loader2, RefreshCw, Trash2 } from 'lucide-react'
|
||||
import { formatDateLong } from '@/lib/utils'
|
||||
import type { CompanyInboundDomain, InboundDomainDnsRecord } from '@/types'
|
||||
|
||||
const BASE = '/api/extensions/ext/invoice-inbox/inbox/domain'
|
||||
|
||||
const STATUS_BADGE: Record<
|
||||
CompanyInboundDomain['status'],
|
||||
{ label: string; variant: 'secondary' | 'success' | 'destructive' }
|
||||
> = {
|
||||
pending: { label: 'Väntar på DNS', variant: 'secondary' },
|
||||
verified: { label: 'Verifierad', variant: 'success' },
|
||||
failed: { label: 'Misslyckades', variant: 'destructive' },
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
// Settings dialog for a company's own inbound domain. Claims the domain via
|
||||
// the extension API, renders the DNS records the user must publish, and
|
||||
// re-checks verification on demand. Everything mail-routing happens
|
||||
// server-side — this surface only manages the claim lifecycle.
|
||||
export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
|
||||
const { toast } = useToast()
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [domain, setDomain] = useState<CompanyInboundDomain | null>(null)
|
||||
const [domainInput, setDomainInput] = useState('')
|
||||
const [isClaiming, setIsClaiming] = useState(false)
|
||||
const [isChecking, setIsChecking] = useState(false)
|
||||
const [isRemoving, setIsRemoving] = useState(false)
|
||||
|
||||
const fetchDomain = useCallback(async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const res = await fetch(BASE)
|
||||
const json = await res.json()
|
||||
if (res.ok) setDomain(json.data ?? null)
|
||||
} catch {
|
||||
// Leave the previous state; the dialog shows the claim form on null.
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (open) fetchDomain()
|
||||
}, [open, fetchDomain])
|
||||
|
||||
const handleClaim = useCallback(async () => {
|
||||
if (!domainInput.trim()) return
|
||||
setIsClaiming(true)
|
||||
try {
|
||||
const res = await fetch(BASE, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ domain: domainInput }),
|
||||
})
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error ?? 'Kunde inte lägga till domänen')
|
||||
setDomain(json.data)
|
||||
setDomainInput('')
|
||||
toast({
|
||||
title: 'Domän tillagd',
|
||||
description: 'Lägg till DNS-posterna nedan hos din domänleverantör.',
|
||||
})
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Kunde inte lägga till domänen',
|
||||
description: err instanceof Error ? err.message : 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsClaiming(false)
|
||||
}
|
||||
}, [domainInput, toast])
|
||||
|
||||
const handleVerify = useCallback(async () => {
|
||||
setIsChecking(true)
|
||||
try {
|
||||
const res = await fetch(`${BASE}/verify`, { method: 'POST' })
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error ?? 'Kontrollen misslyckades')
|
||||
setDomain(json.data)
|
||||
toast(
|
||||
json.data.status === 'verified'
|
||||
? { title: 'Domänen är verifierad', description: 'E-post till domänen landar nu i dokumentinkorgen.' }
|
||||
: { title: 'Inte verifierad än', description: 'DNS-ändringar kan ta upp till någon timme att slå igenom.' }
|
||||
)
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Kontrollen misslyckades',
|
||||
description: err instanceof Error ? err.message : 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsChecking(false)
|
||||
}
|
||||
}, [toast])
|
||||
|
||||
const handleRemove = useCallback(async () => {
|
||||
if (!domain) return
|
||||
if (!confirm(`Ta bort ${domain.domain}? E-post till domänen slutar landa i Accounted.`)) return
|
||||
setIsRemoving(true)
|
||||
try {
|
||||
const res = await fetch(BASE, { method: 'DELETE' })
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error ?? 'Borttagningen misslyckades')
|
||||
setDomain(null)
|
||||
toast({ title: 'Domänen borttagen' })
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Borttagningen misslyckades',
|
||||
description: err instanceof Error ? err.message : 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsRemoving(false)
|
||||
}
|
||||
}, [domain, toast])
|
||||
|
||||
const handleCopy = useCallback(
|
||||
(value: string) => {
|
||||
navigator.clipboard.writeText(value).catch(() => {})
|
||||
toast({ title: 'Kopierat' })
|
||||
},
|
||||
[toast]
|
||||
)
|
||||
|
||||
const records: InboundDomainDnsRecord[] = domain?.dns_records ?? []
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Egen domän för inkorgen</DialogTitle>
|
||||
<DialogDescription>
|
||||
Ta emot leverantörsfakturor direkt på bolagets egen adress, t.ex.
|
||||
faktura@dittbolag.se — utan vidarebefordran.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-24 w-full" />
|
||||
</div>
|
||||
) : !domain ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border p-4 text-sm">
|
||||
<AlertTriangle className="h-4 w-4 shrink-0 mt-0.5 text-muted-foreground" />
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium">Viktigt om din domän redan tar emot e-post</p>
|
||||
<p className="text-muted-foreground">
|
||||
Domänens MX-poster pekas om till Accounted. Om domänen redan används för
|
||||
e-post (Google Workspace, Microsoft 365) slutar din vanliga e-post att
|
||||
fungera — använd då en underdomän, t.ex.{' '}
|
||||
<code className="font-mono text-xs">faktura.dittbolag.se</code>, eller
|
||||
fortsätt vidarebefordra till din vanliga inkorgsadress.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={domainInput}
|
||||
onChange={(e) => setDomainInput(e.target.value)}
|
||||
placeholder="faktura.dittbolag.se"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') handleClaim()
|
||||
}}
|
||||
/>
|
||||
<Button onClick={handleClaim} disabled={isClaiming || !domainInput.trim()}>
|
||||
{isClaiming ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : null}
|
||||
Lägg till
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<code className="font-mono text-sm truncate">{domain.domain}</code>
|
||||
<Badge variant={STATUS_BADGE[domain.status].variant}>
|
||||
{STATUS_BADGE[domain.status].label}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button variant="outline" size="sm" onClick={handleVerify} disabled={isChecking}>
|
||||
{isChecking ? (
|
||||
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3.5 w-3.5 mr-1.5" />
|
||||
)}
|
||||
Kontrollera igen
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleRemove}
|
||||
disabled={isRemoving}
|
||||
aria-label="Ta bort domän"
|
||||
>
|
||||
{isRemoving ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{domain.status === 'verified' ? (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border p-4 text-sm">
|
||||
<Check className="h-4 w-4 shrink-0 mt-0.5 text-muted-foreground" />
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium">
|
||||
Klart — ge dina leverantörer{' '}
|
||||
<code className="font-mono text-xs">faktura@{domain.domain}</code>
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
Alla adresser på domänen fungerar; allt landar i dokumentinkorgen.
|
||||
{domain.verified_at ? ` Verifierad ${formatDateLong(domain.verified_at)}.` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Lägg till posterna nedan hos din domänleverantör (Loopia, one.com,
|
||||
Cloudflare …) och klicka sedan på Kontrollera igen. Ändringar kan ta upp
|
||||
till någon timme att slå igenom.
|
||||
</p>
|
||||
{records.length > 0 ? (
|
||||
<div className="rounded-lg border border-border overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border">
|
||||
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Typ</th>
|
||||
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Namn</th>
|
||||
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Värde</th>
|
||||
<th className="px-3 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Prio</th>
|
||||
<th className="px-3 py-2" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{records.map((r, i) => (
|
||||
<tr key={`${r.type}-${r.name}-${i}`} className="border-b border-border last:border-0">
|
||||
<td className="px-3 py-2 font-mono text-xs">{r.type}</td>
|
||||
<td className="px-3 py-2 font-mono text-xs break-all">{r.name}</td>
|
||||
<td className="px-3 py-2 font-mono text-xs break-all">{r.value}</td>
|
||||
<td className="px-3 py-2 font-mono text-xs text-right tabular-nums">
|
||||
{r.priority ?? '—'}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right">
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
onClick={() => handleCopy(r.value)}
|
||||
aria-label={`Kopiera ${r.type}-värde`}
|
||||
>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Inga DNS-poster tillgängliga — klicka på Kontrollera igen.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -44,6 +44,8 @@ import type { InvoiceExtractionResult } from '@/types'
|
||||
import BookDirectlyDialog from '@/components/extensions/general/BookDirectlyDialog'
|
||||
import NewSupplierInvoiceDialog from '@/components/supplier-invoices/NewSupplierInvoiceDialog'
|
||||
import BulkBookInboxDialog from '@/components/extensions/general/BulkBookInboxDialog'
|
||||
// InboxCustomDomainDialog (egen domän) is built but gated off — see
|
||||
// INBOX_CUSTOM_DOMAINS_ENABLED in extensions/general/invoice-inbox/index.ts.
|
||||
import TransactionMatchPicker from '@/components/inbox/TransactionMatchPicker'
|
||||
import { useAgentSheet } from '@/components/agent/AgentSheetProvider'
|
||||
|
||||
|
||||
@@ -138,6 +138,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
work_type: z.string().nullable().optional(),
|
||||
housing_designation: z.string().nullable().optional(),
|
||||
apartment_number: z.string().nullable().optional(),
|
||||
brf_org_number: z.string().nullable().optional(),
|
||||
// Periodisering (förutbetald intäkt). Active when balance account is
|
||||
// non-null; both period dates are then required (refine below).
|
||||
accrual_period_start: z.string().nullable().optional(),
|
||||
@@ -199,7 +200,10 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
self_billing_agreement_ref: z.string().optional(),
|
||||
received_date: z.string().optional(),
|
||||
// Invoice-level ROT/RUT claim info. Personnummer is plaintext on
|
||||
// the wire; the API encrypts it before storage.
|
||||
// the wire; the API encrypts it before storage. The API additionally
|
||||
// accepts the bostadsrätt pair (deduction_apartment_number +
|
||||
// deduction_brf_org_number) — no editor UI for it yet, rot i
|
||||
// bostadsrätt data enters via API/MCP until the payout-file UI ships.
|
||||
deduction_personnummer: z.string().optional(),
|
||||
deduction_housing_designation: z.string().optional(),
|
||||
items: z.array(itemSchema).min(1, t('validation_min_one_row')),
|
||||
@@ -262,6 +266,10 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
// draft. Starts true for create (always derive), false for edit (skip once).
|
||||
const didInitialCustomerSync = useRef(!isEditMode)
|
||||
|
||||
// Edit mode: the claim card's property fields are restored from the first
|
||||
// rot line (they're stamped onto every rot line server-side at save time).
|
||||
const initialRotLine = initial?.items?.find((i) => i.deduction_type === 'rot') ?? null
|
||||
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
@@ -291,7 +299,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
self_billing_agreement_ref: '',
|
||||
received_date: '',
|
||||
deduction_personnummer: '',
|
||||
deduction_housing_designation: '',
|
||||
deduction_housing_designation: initialRotLine?.housing_designation ?? '',
|
||||
items: (initial.items ?? []).map((item) => ({
|
||||
line_type: (item.line_type ?? 'product') as 'product' | 'text',
|
||||
description: item.description,
|
||||
@@ -306,6 +314,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
work_type: item.work_type ?? null,
|
||||
housing_designation: item.housing_designation ?? null,
|
||||
apartment_number: item.apartment_number ?? null,
|
||||
brf_org_number: item.brf_org_number ?? null,
|
||||
accrual_period_start: item.accrual_period_start ?? null,
|
||||
accrual_period_end: item.accrual_period_end ?? null,
|
||||
accrual_balance_account: item.accrual_balance_account ?? null,
|
||||
@@ -334,6 +343,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
work_type: null,
|
||||
housing_designation: null,
|
||||
apartment_number: null,
|
||||
brf_org_number: null,
|
||||
accrual_period_start: null,
|
||||
accrual_period_end: null,
|
||||
accrual_balance_account: null,
|
||||
@@ -927,6 +937,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
work_type: _wt,
|
||||
housing_designation: _hd,
|
||||
apartment_number: _an,
|
||||
brf_org_number: _bn,
|
||||
...rest
|
||||
} = item
|
||||
return rest
|
||||
@@ -1003,6 +1014,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
work_type: _wt,
|
||||
housing_designation: _hd,
|
||||
apartment_number: _an,
|
||||
brf_org_number: _bn,
|
||||
...rest
|
||||
} = item
|
||||
return rest
|
||||
@@ -1061,6 +1073,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
work_type: _wt,
|
||||
housing_designation: _hd,
|
||||
apartment_number: _an,
|
||||
brf_org_number: _bn,
|
||||
...rest
|
||||
} = item
|
||||
return rest
|
||||
@@ -1816,6 +1829,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
work_type: null,
|
||||
housing_designation: null,
|
||||
apartment_number: null,
|
||||
brf_org_number: null,
|
||||
accrual_period_start: null,
|
||||
accrual_period_end: null,
|
||||
accrual_balance_account: null,
|
||||
@@ -1852,6 +1866,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
work_type: null,
|
||||
housing_designation: null,
|
||||
apartment_number: null,
|
||||
brf_org_number: null,
|
||||
accrual_period_start: null,
|
||||
accrual_period_end: null,
|
||||
accrual_balance_account: null,
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import {
|
||||
INVOICE_EMAIL_DEFAULT_TEXTS,
|
||||
INVOICE_EMAIL_PLACEHOLDER_KEYS,
|
||||
} from '@/lib/email/invoice-templates'
|
||||
import type { CompanySettings, InvoiceEmailTextOverrides, InvoiceEmailTexts } from '@/types'
|
||||
|
||||
interface InvoiceEmailTextsSettingsProps {
|
||||
settings: CompanySettings
|
||||
onUpdate: (updates: Partial<CompanySettings>) => void
|
||||
}
|
||||
|
||||
type Lang = 'sv' | 'en'
|
||||
type Field = keyof InvoiceEmailTextOverrides
|
||||
|
||||
const LANGS: Lang[] = ['sv', 'en']
|
||||
|
||||
const FIELD_CONFIG: Array<{ field: Field; labelKey: string; multiline?: boolean }> = [
|
||||
{ field: 'subject', labelKey: 'subject_label' },
|
||||
{ field: 'greeting', labelKey: 'greeting_label' },
|
||||
{ field: 'body', labelKey: 'body_label', multiline: true },
|
||||
{ field: 'signoff', labelKey: 'signoff_label' },
|
||||
]
|
||||
|
||||
// The editor always shows the EFFECTIVE text (override or standard), never an
|
||||
// empty field — users see and edit the mail that actually goes out.
|
||||
type DisplayTexts = Record<Lang, Record<Field, string>>
|
||||
|
||||
function buildDisplay(stored: InvoiceEmailTexts | null | undefined): DisplayTexts {
|
||||
const result = {} as DisplayTexts
|
||||
for (const lang of LANGS) {
|
||||
result[lang] = {} as Record<Field, string>
|
||||
for (const { field } of FIELD_CONFIG) {
|
||||
const value = stored?.[lang]?.[field]
|
||||
result[lang][field] =
|
||||
typeof value === 'string' && value.trim() !== ''
|
||||
? value
|
||||
: INVOICE_EMAIL_DEFAULT_TEXTS[lang][field]
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Cleared fields have no meaning of their own — snap them back to standard.
|
||||
function normalize(display: DisplayTexts): DisplayTexts {
|
||||
const result = {} as DisplayTexts
|
||||
for (const lang of LANGS) {
|
||||
result[lang] = {} as Record<Field, string>
|
||||
for (const { field } of FIELD_CONFIG) {
|
||||
const value = display[lang][field]
|
||||
result[lang][field] =
|
||||
value.trim() === '' ? INVOICE_EMAIL_DEFAULT_TEXTS[lang][field] : value
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Store only changes: a field equal to the standard text is NOT an override,
|
||||
// so future improvements to the standard wording reach every company that
|
||||
// hasn't customized. Empty result → null (column reads "all defaults").
|
||||
function toOverrides(display: DisplayTexts): InvoiceEmailTexts | null {
|
||||
const result: InvoiceEmailTexts = {}
|
||||
for (const lang of LANGS) {
|
||||
const langOverrides: InvoiceEmailTextOverrides = {}
|
||||
for (const { field } of FIELD_CONFIG) {
|
||||
const value = display[lang][field].trim()
|
||||
if (value !== '' && value !== INVOICE_EMAIL_DEFAULT_TEXTS[lang][field]) {
|
||||
langOverrides[field] = value
|
||||
}
|
||||
}
|
||||
if (Object.keys(langOverrides).length > 0) result[lang] = langOverrides
|
||||
}
|
||||
return Object.keys(result).length > 0 ? result : null
|
||||
}
|
||||
|
||||
export function InvoiceEmailTextsSettings({ settings, onUpdate }: InvoiceEmailTextsSettingsProps) {
|
||||
const t = useTranslations('settings_email_texts')
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
const [texts, setTexts] = useState<DisplayTexts>(() => buildDisplay(settings.invoice_email_texts))
|
||||
// Serialized last-persisted overrides — skips no-op PUTs on blur without
|
||||
// edits. toOverrides() builds keys in a fixed order, so comparison is stable.
|
||||
const lastSavedRef = useRef<string>(
|
||||
JSON.stringify(toOverrides(buildDisplay(settings.invoice_email_texts))),
|
||||
)
|
||||
|
||||
const setField = (lang: Lang, field: Field, value: string) => {
|
||||
setTexts((prev) => ({ ...prev, [lang]: { ...prev[lang], [field]: value } }))
|
||||
}
|
||||
|
||||
// Whole-object save: a JSONB column update replaces the stored value, and
|
||||
// the inactive language tab is unmounted, so per-field PATCHes can't work.
|
||||
const persist = useCallback(async (display: DisplayTexts) => {
|
||||
const overrides = toOverrides(display)
|
||||
const serialized = JSON.stringify(overrides)
|
||||
if (serialized === lastSavedRef.current) return
|
||||
try {
|
||||
const response = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ invoice_email_texts: overrides }),
|
||||
})
|
||||
if (!response.ok) throw new Error()
|
||||
lastSavedRef.current = serialized
|
||||
onUpdate({ invoice_email_texts: overrides })
|
||||
} catch {
|
||||
toast({ title: t('toast_save_failed'), variant: 'destructive' })
|
||||
}
|
||||
}, [onUpdate, toast, t])
|
||||
|
||||
const handleBlur = () => {
|
||||
const normalized = normalize(texts)
|
||||
setTexts(normalized)
|
||||
void persist(normalized)
|
||||
}
|
||||
|
||||
const resetField = (lang: Lang, field: Field) => {
|
||||
const next = {
|
||||
...texts,
|
||||
[lang]: { ...texts[lang], [field]: INVOICE_EMAIL_DEFAULT_TEXTS[lang][field] },
|
||||
}
|
||||
setTexts(next)
|
||||
void persist(next)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{t('heading')}
|
||||
</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t('description')}</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="sv">
|
||||
<TabsList>
|
||||
<TabsTrigger value="sv">{t('tab_sv')}</TabsTrigger>
|
||||
<TabsTrigger value="en">{t('tab_en')}</TabsTrigger>
|
||||
</TabsList>
|
||||
{LANGS.map((lang) => (
|
||||
<TabsContent key={lang} value={lang} className="mt-4 space-y-4">
|
||||
{lang === 'en' && (
|
||||
<p className="text-xs text-muted-foreground">{t('en_tab_hint')}</p>
|
||||
)}
|
||||
{FIELD_CONFIG.map(({ field, labelKey, multiline }) => {
|
||||
const id = `invoice-email-${field}-${lang}`
|
||||
const modified =
|
||||
texts[lang][field].trim() !== INVOICE_EMAIL_DEFAULT_TEXTS[lang][field]
|
||||
const common = {
|
||||
id,
|
||||
value: texts[lang][field],
|
||||
onBlur: handleBlur,
|
||||
disabled: !canWrite,
|
||||
}
|
||||
return (
|
||||
<div key={field} className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor={id}>{t(labelKey)}</Label>
|
||||
{modified && canWrite && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => resetField(lang, field)}
|
||||
className="text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
|
||||
>
|
||||
{t('reset_label')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{multiline ? (
|
||||
<Textarea
|
||||
{...common}
|
||||
rows={4}
|
||||
onChange={(e) => setField(lang, field, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
{...common}
|
||||
onChange={(e) => setField(lang, field, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
|
||||
<div className="space-y-1">
|
||||
{/* Legend is rendered from code, not messages/*.json — ICU message
|
||||
syntax treats literal braces as interpolation. */}
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>{t('placeholders_help')}</span>
|
||||
{INVOICE_EMAIL_PLACEHOLDER_KEYS.map((key) => (
|
||||
<code key={key} className="rounded bg-muted px-1 text-xs">{`{${key}}`}</code>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('firstname_note')}</p>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { BankDetailsForm, validateBankFields } from '@/components/settings/BankDetailsForm'
|
||||
import { InvoiceSettingsForm } from '@/components/settings/InvoiceSettingsForm'
|
||||
import { InvoiceEmailTextsSettings } from '@/components/settings/InvoiceEmailTextsSettings'
|
||||
import { InvoicePreviewCard } from '@/components/settings/InvoicePreviewCard'
|
||||
import { PdfPrintSettings } from '@/components/settings/PdfPrintSettings'
|
||||
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
|
||||
@@ -73,6 +74,11 @@ export function InvoicingSettingsContent() {
|
||||
<div className="border-t border-border pt-8">
|
||||
<PdfPrintSettings settings={settings} onUpdate={updateSettings} />
|
||||
</div>
|
||||
|
||||
{/* Invoice email texts — autosaves on blur */}
|
||||
<div className="border-t border-border pt-8">
|
||||
<InvoiceEmailTextsSettings settings={settings} onUpdate={updateSettings} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { invoiceInboxExtension } from '@/extensions/general/invoice-inbox'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
|
||||
// The custom-domain routes are gated off by default (product decision
|
||||
// 2026-07-02) — enable the flag for the behavior tests, and prove the gate
|
||||
// itself in the last describe.
|
||||
beforeEach(() => {
|
||||
process.env.INBOX_CUSTOM_DOMAINS_ENABLED = 'true'
|
||||
})
|
||||
afterEach(() => {
|
||||
delete process.env.INBOX_CUSTOM_DOMAINS_ENABLED
|
||||
})
|
||||
|
||||
const claimMock = vi.fn()
|
||||
const verifyMock = vi.fn()
|
||||
const removeMock = vi.fn()
|
||||
const getMock = vi.fn()
|
||||
|
||||
vi.mock('@/extensions/general/invoice-inbox/lib/custom-domains', async () => {
|
||||
const actual = await vi.importActual<
|
||||
typeof import('@/extensions/general/invoice-inbox/lib/custom-domains')
|
||||
>('@/extensions/general/invoice-inbox/lib/custom-domains')
|
||||
return {
|
||||
...actual,
|
||||
claimCustomDomain: (...args: unknown[]) => claimMock(...args),
|
||||
checkCustomDomainVerification: (...args: unknown[]) => verifyMock(...args),
|
||||
removeCustomDomain: (...args: unknown[]) => removeMock(...args),
|
||||
getCustomDomain: (...args: unknown[]) => getMock(...args),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/rate-limits/inbox', () => ({
|
||||
checkInboxUploadRateLimit: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
function findRoute(method: string, path: string) {
|
||||
return invoiceInboxExtension.apiRoutes!.find(
|
||||
(r) => r.method === method && r.path === path
|
||||
)!
|
||||
}
|
||||
|
||||
function buildCtx(supabase: unknown, overrides: Partial<ExtensionContext> = {}): ExtensionContext {
|
||||
return {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'invoice-inbox',
|
||||
supabase: supabase as ExtensionContext['supabase'],
|
||||
emit: vi.fn(),
|
||||
settings: { get: vi.fn(), set: vi.fn() },
|
||||
storage: { from: vi.fn() } as unknown as ExtensionContext['storage'],
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as unknown as ExtensionContext['log'],
|
||||
services: {},
|
||||
...overrides,
|
||||
} as ExtensionContext
|
||||
}
|
||||
|
||||
const DOMAIN_ROW = {
|
||||
id: 'row-1',
|
||||
company_id: 'company-1',
|
||||
domain: 'hansbolag.example',
|
||||
status: 'pending',
|
||||
resend_domain_id: 'rd_1',
|
||||
dns_records: [],
|
||||
verified_at: null,
|
||||
last_checked_at: null,
|
||||
}
|
||||
|
||||
describe('GET /inbox/domain', () => {
|
||||
const route = findRoute('GET', '/inbox/domain')
|
||||
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('returns 401 without context', async () => {
|
||||
const res = await route.handler(createMockRequest('/inbox/domain'), undefined)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns the current domain row (or null)', async () => {
|
||||
getMock.mockResolvedValue(DOMAIN_ROW)
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
const res = await route.handler(createMockRequest('/inbox/domain'), buildCtx(supabase))
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof DOMAIN_ROW }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.domain).toBe('hansbolag.example')
|
||||
expect(getMock).toHaveBeenCalledWith(expect.anything(), 'company-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /inbox/domain', () => {
|
||||
const route = findRoute('POST', '/inbox/domain')
|
||||
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('returns 403 for non-admin members', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'member' } })
|
||||
const request = createMockRequest('/inbox/domain', {
|
||||
method: 'POST',
|
||||
body: { domain: 'hansbolag.example' },
|
||||
})
|
||||
const res = await route.handler(request, buildCtx(supabase))
|
||||
expect(res.status).toBe(403)
|
||||
expect(claimMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('claims the domain for admins', async () => {
|
||||
claimMock.mockResolvedValue({ ok: true, data: DOMAIN_ROW })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'admin' } })
|
||||
const request = createMockRequest('/inbox/domain', {
|
||||
method: 'POST',
|
||||
body: { domain: 'hansbolag.example' },
|
||||
})
|
||||
const res = await route.handler(request, buildCtx(supabase))
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof DOMAIN_ROW }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('row-1')
|
||||
expect(claimMock).toHaveBeenCalledWith(expect.anything(), 'company-1', 'hansbolag.example')
|
||||
})
|
||||
|
||||
it('maps lib failures to their status codes', async () => {
|
||||
claimMock.mockResolvedValue({ ok: false, status: 409, error: 'Domänen är redan registrerad.' })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
const request = createMockRequest('/inbox/domain', {
|
||||
method: 'POST',
|
||||
body: { domain: 'hansbolag.example' },
|
||||
})
|
||||
const res = await route.handler(request, buildCtx(supabase))
|
||||
expect(res.status).toBe(409)
|
||||
})
|
||||
|
||||
it('rejects a missing domain field with 400', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
const request = createMockRequest('/inbox/domain', { method: 'POST', body: {} })
|
||||
const res = await route.handler(request, buildCtx(supabase))
|
||||
expect(res.status).toBe(400)
|
||||
expect(claimMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks sandbox companies from claiming a domain', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'owner' } }) // company_members role check
|
||||
enqueue({ data: { is_sandbox: true } }) // company_settings sandbox check
|
||||
const request = createMockRequest('/inbox/domain', {
|
||||
method: 'POST',
|
||||
body: { domain: 'hansbolag.example' },
|
||||
})
|
||||
const res = await route.handler(request, buildCtx(supabase))
|
||||
expect(res.status).toBe(403)
|
||||
expect(claimMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /inbox/domain/verify', () => {
|
||||
const route = findRoute('POST', '/inbox/domain/verify')
|
||||
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('returns 403 for viewers', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
const res = await route.handler(
|
||||
createMockRequest('/inbox/domain/verify', { method: 'POST' }),
|
||||
buildCtx(supabase),
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('re-checks verification for admins', async () => {
|
||||
verifyMock.mockResolvedValue({ ok: true, data: { ...DOMAIN_ROW, status: 'verified' } })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'admin' } })
|
||||
const res = await route.handler(
|
||||
createMockRequest('/inbox/domain/verify', { method: 'POST' }),
|
||||
buildCtx(supabase),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { status: string } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.status).toBe('verified')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /inbox/domain', () => {
|
||||
const route = findRoute('DELETE', '/inbox/domain')
|
||||
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('returns 403 for non-admin members', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'member' } })
|
||||
const res = await route.handler(
|
||||
createMockRequest('/inbox/domain', { method: 'DELETE' }),
|
||||
buildCtx(supabase),
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
expect(removeMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('removes the domain for owners', async () => {
|
||||
removeMock.mockResolvedValue({ ok: true, data: { removed: true } })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
const res = await route.handler(
|
||||
createMockRequest('/inbox/domain', { method: 'DELETE' }),
|
||||
buildCtx(supabase),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { removed: boolean } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.removed).toBe(true)
|
||||
})
|
||||
|
||||
it('surfaces a Resend removal failure without deleting the row', async () => {
|
||||
removeMock.mockResolvedValue({ ok: false, status: 502, error: 'Kunde inte ta bort domänen.' })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
const res = await route.handler(
|
||||
createMockRequest('/inbox/domain', { method: 'DELETE' }),
|
||||
buildCtx(supabase),
|
||||
)
|
||||
expect(res.status).toBe(502)
|
||||
})
|
||||
})
|
||||
|
||||
describe('INBOX_CUSTOM_DOMAINS_ENABLED gate', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
delete process.env.INBOX_CUSTOM_DOMAINS_ENABLED
|
||||
})
|
||||
|
||||
it('returns 403 FEATURE_DISABLED on every /inbox/domain route when the flag is off', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
const routes: Array<[string, string]> = [
|
||||
['GET', '/inbox/domain'],
|
||||
['POST', '/inbox/domain'],
|
||||
['POST', '/inbox/domain/verify'],
|
||||
['DELETE', '/inbox/domain'],
|
||||
]
|
||||
for (const [method, path] of routes) {
|
||||
const res = await findRoute(method, path).handler(
|
||||
createMockRequest(path, { method }),
|
||||
buildCtx(supabase),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ code: string }>(res)
|
||||
expect(status).toBe(403)
|
||||
expect(body.code).toBe('FEATURE_DISABLED')
|
||||
}
|
||||
expect(getMock).not.toHaveBeenCalled()
|
||||
expect(claimMock).not.toHaveBeenCalled()
|
||||
expect(verifyMock).not.toHaveBeenCalled()
|
||||
expect(removeMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,6 +19,19 @@ vi.mock('@supabase/supabase-js', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
// applyDomainStatusFromWebhook confirms the receiving capability with Resend
|
||||
// before flipping a row to verified — keep that lookup off the network.
|
||||
const { domainsMock } = vi.hoisted(() => ({
|
||||
domainsMock: {
|
||||
get: vi.fn(),
|
||||
},
|
||||
}))
|
||||
vi.mock('resend', () => ({
|
||||
Resend: class {
|
||||
domains = domainsMock
|
||||
},
|
||||
}))
|
||||
|
||||
// Rate limiter is a thin RPC wrapper; bypass it so the queued-mock sequence
|
||||
// in each test doesn't have to account for the extra Supabase call.
|
||||
vi.mock('@/lib/rate-limits/inbox', () => ({
|
||||
@@ -103,15 +116,142 @@ describe('POST /inbound', () => {
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('returns 404 when no recipient matches our domain', async () => {
|
||||
it('returns 404 when no recipient matches our domain or a verified custom domain', async () => {
|
||||
vi.mocked(verifyInboundWebhook).mockReturnValue(
|
||||
mockReceivedEvent({ to: ['[email protected]'] }) as never
|
||||
)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [] }) // company_inbound_domains lookup finds nothing
|
||||
vi.mocked(createClient).mockReturnValue(supabase as never)
|
||||
|
||||
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
||||
const res = await webhookRoute.handler(request)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('routes mail on a verified custom domain to its company (any local part)', async () => {
|
||||
vi.mocked(verifyInboundWebhook).mockReturnValue(
|
||||
mockReceivedEvent({ to: ['[email protected]'], attachments: [] }) as never
|
||||
)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ company_id: 'company-9', domain: 'hansbolag.example' }] }) // verified domain
|
||||
enqueue({ data: { created_by: 'user-owner-9' } }) // company owner
|
||||
enqueue({ data: null }) // no-attachments error-row insert
|
||||
vi.mocked(createClient).mockReturnValue(supabase as never)
|
||||
vi.mocked(fetchReceivingEmail).mockResolvedValue({
|
||||
object: 'email',
|
||||
id: 'em_123',
|
||||
to: ['[email protected]'],
|
||||
from: '[email protected]',
|
||||
created_at: '2026-04-20T10:00:00Z',
|
||||
subject: 'Invoice #5678',
|
||||
bcc: null,
|
||||
cc: null,
|
||||
reply_to: null,
|
||||
html: null,
|
||||
text: 'Body',
|
||||
headers: {},
|
||||
message_id: '<msg@x>',
|
||||
raw: null,
|
||||
attachments: [],
|
||||
} as never)
|
||||
|
||||
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
||||
const res = await webhookRoute.handler(request)
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data.reason).toBe('no_attachments')
|
||||
})
|
||||
|
||||
it('does not route mail for an unverified custom domain', async () => {
|
||||
vi.mocked(verifyInboundWebhook).mockReturnValue(
|
||||
mockReceivedEvent({ to: ['[email protected]'] }) as never
|
||||
)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
// status='verified' filter means a pending claim never matches
|
||||
enqueue({ data: [] })
|
||||
vi.mocked(createClient).mockReturnValue(supabase as never)
|
||||
|
||||
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
||||
const res = await webhookRoute.handler(request)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('prefers the shared-domain address when both shared and custom recipients are present', async () => {
|
||||
vi.mocked(verifyInboundWebhook).mockReturnValue(
|
||||
mockReceivedEvent({
|
||||
to: ['[email protected]', '[email protected]'],
|
||||
attachments: [],
|
||||
}) as never
|
||||
)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
// Only the three shared-path queries are enqueued — if the handler also
|
||||
// ran the custom-domain lookup, the queue would shift and created_by
|
||||
// would resolve to null (500). A 200 proves the shared path won.
|
||||
enqueue({ data: { id: 'inbox-1', company_id: 'company-1', status: 'active' } })
|
||||
enqueue({ data: { created_by: 'user-owner-1' } })
|
||||
enqueue({ data: null }) // no-attachments error-row insert
|
||||
vi.mocked(createClient).mockReturnValue(supabase as never)
|
||||
vi.mocked(fetchReceivingEmail).mockResolvedValue({
|
||||
object: 'email',
|
||||
id: 'em_123',
|
||||
to: ['[email protected]', '[email protected]'],
|
||||
from: '[email protected]',
|
||||
created_at: '2026-04-20T10:00:00Z',
|
||||
subject: 'Invoice #5678',
|
||||
bcc: null,
|
||||
cc: null,
|
||||
reply_to: null,
|
||||
html: null,
|
||||
text: 'Body',
|
||||
headers: {},
|
||||
message_id: '<msg@x>',
|
||||
raw: null,
|
||||
attachments: [],
|
||||
} as never)
|
||||
|
||||
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
||||
const res = await webhookRoute.handler(request)
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data.reason).toBe('no_attachments')
|
||||
})
|
||||
|
||||
it('applies domain.updated events to custom-domain rows', async () => {
|
||||
process.env.RESEND_API_KEY = 'test-key'
|
||||
domainsMock.get.mockResolvedValue({
|
||||
data: {
|
||||
id: 'rd_123',
|
||||
status: 'verified',
|
||||
capabilities: { receiving: 'enabled', sending: 'disabled' },
|
||||
records: [],
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
vi.mocked(verifyInboundWebhook).mockReturnValue({
|
||||
type: 'domain.updated',
|
||||
created_at: '2026-07-01T10:00:00Z',
|
||||
data: {
|
||||
id: 'rd_123',
|
||||
name: 'hansbolag.example',
|
||||
status: 'verified',
|
||||
created_at: '2026-07-01T09:00:00Z',
|
||||
region: 'eu-west-1',
|
||||
records: [],
|
||||
},
|
||||
} as never)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'row-1', verified_at: null } }) // row by resend_domain_id
|
||||
enqueue({ data: null }) // update
|
||||
vi.mocked(createClient).mockReturnValue(supabase as never)
|
||||
|
||||
const request = createMockRequest('/inbound', { method: 'POST', body: {} })
|
||||
const res = await webhookRoute.handler(request)
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data.domain_updated).toBe(true)
|
||||
})
|
||||
|
||||
it('returns 404 when the address is not in company_inboxes', async () => {
|
||||
vi.mocked(verifyInboundWebhook).mockReturnValue(mockReceivedEvent() as never)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { extractLocalPartForDomain } from '@/extensions/general/invoice-inbox/lib/resend-inbound'
|
||||
import { extractLocalPartForDomain, parseRecipients } from '@/extensions/general/invoice-inbox/lib/resend-inbound'
|
||||
|
||||
describe('extractLocalPartForDomain', () => {
|
||||
it('returns the local part when a recipient matches the domain', () => {
|
||||
@@ -50,3 +50,24 @@ describe('extractLocalPartForDomain', () => {
|
||||
expect(result).toBe('acme-xxx')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseRecipients', () => {
|
||||
it('splits recipients into lowercased localPart/domain pairs in order', () => {
|
||||
expect(
|
||||
parseRecipients(['[email protected]', '[email protected]'])
|
||||
).toEqual([
|
||||
{ localPart: 'faktura', domain: 'hansbolag.se' },
|
||||
{ localPart: 'billing', domain: 'acme.se' },
|
||||
])
|
||||
})
|
||||
|
||||
it('skips malformed addresses', () => {
|
||||
expect(parseRecipients(['not-an-email', '@x.se', 'foo@', '[email protected]'])).toEqual([
|
||||
{ localPart: 'ok', domain: 'a.se' },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns an empty array for no recipients', () => {
|
||||
expect(parseRecipients([])).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
fetchReceivingEmail,
|
||||
fetchInboundAttachment,
|
||||
extractLocalPartForDomain,
|
||||
parseRecipients,
|
||||
isEmailReceivedEvent,
|
||||
ResendSignatureError,
|
||||
} from './lib/resend-inbound'
|
||||
@@ -17,6 +18,14 @@ import {
|
||||
getActiveInbox,
|
||||
composeInboxAddress,
|
||||
} from './lib/inbox-provisioning'
|
||||
import {
|
||||
claimCustomDomain,
|
||||
checkCustomDomainVerification,
|
||||
removeCustomDomain,
|
||||
getCustomDomain,
|
||||
findCompanyForRecipientDomains,
|
||||
applyDomainStatusFromWebhook,
|
||||
} from './lib/custom-domains'
|
||||
import { createSupplierInvoiceRegistrationEntry } from '@/lib/bookkeeping/supplier-invoice-entries'
|
||||
import { createSchedulesForSupplierInvoice } from '@/lib/bookkeeping/accruals/from-invoices'
|
||||
import { suggestBalanceAccount } from '@/lib/bookkeeping/accruals/account-suggestions'
|
||||
@@ -143,6 +152,27 @@ const UpdateExtractedDataSchema = z.object({
|
||||
.optional(),
|
||||
})
|
||||
|
||||
// Claim body for POST /inbox/domain. Length-capped only — real validation
|
||||
// (punycode, hostname shape, blocklist) lives in normalizeInboundDomain /
|
||||
// validateClaimableDomain so the same rules apply to every caller.
|
||||
const ClaimDomainSchema = z.object({
|
||||
domain: z.string().trim().min(1).max(255),
|
||||
})
|
||||
|
||||
// Custom inbound domains are fully built but deliberately not exposed —
|
||||
// product decision 2026-07-02: the default is the Fortnox-style shared
|
||||
// address (+ user-side forwarding); own-domain inbound waits for real demand.
|
||||
// Flip INBOX_CUSTOM_DOMAINS_ENABLED=true to re-enable the /inbox/domain
|
||||
// routes. The globe entry point in InvoiceInboxWorkspace was removed at the
|
||||
// same time — restore it when re-enabling.
|
||||
const customDomainsEnabled = () => process.env.INBOX_CUSTOM_DOMAINS_ENABLED === 'true'
|
||||
|
||||
const customDomainsDisabledResponse = () =>
|
||||
NextResponse.json(
|
||||
{ error: 'Egen domän är inte tillgänglig.', code: 'FEATURE_DISABLED' },
|
||||
{ status: 403 }
|
||||
)
|
||||
|
||||
const UPLOAD_ALLOWED_MIME_TYPES = new Set([
|
||||
'application/pdf',
|
||||
'image/jpeg',
|
||||
@@ -1288,6 +1318,123 @@ export const invoiceInboxExtension: Extension = {
|
||||
},
|
||||
},
|
||||
|
||||
// ── Custom inbound domain: read current state ────────────
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/inbox/domain',
|
||||
handler: async (_request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
if (!customDomainsEnabled()) return customDomainsDisabledResponse()
|
||||
|
||||
try {
|
||||
const row = await getCustomDomain(ctx.supabase, ctx.companyId)
|
||||
// null when the company has no custom domain — the UI renders the
|
||||
// claim form in that case.
|
||||
return NextResponse.json({ data: row })
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to load domain' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// ── Custom inbound domain: claim (admin/owner only) ──────
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/inbox/domain',
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
if (!customDomainsEnabled()) return customDomainsDisabledResponse()
|
||||
|
||||
const isAdmin = await isCompanyAdmin(ctx.supabase, ctx.userId, ctx.companyId)
|
||||
if (!isAdmin) return NextResponse.json({ error: 'Behörighet saknas.' }, { status: 403 })
|
||||
|
||||
// Sandbox companies are anonymous 24h demo accounts — letting them
|
||||
// register domains in our Resend account is a pure abuse vector.
|
||||
if (await isSandboxCompany(ctx.supabase, ctx.companyId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Egen domän är inte tillgänglig i sandlådan.' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
// Claiming hits the Resend domains API — share the per-company inbox
|
||||
// quota so a claim/delete loop can't burn the provider budget.
|
||||
const limit = await checkInboxUploadRateLimit(ctx.supabase, ctx.companyId)
|
||||
if (!limit.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: 'För många förfrågningar — försök igen om en stund.', retry_after: limit.retryAfterSec },
|
||||
{ status: 429, headers: { 'Retry-After': String(limit.retryAfterSec ?? 60) } },
|
||||
)
|
||||
}
|
||||
|
||||
let body: z.infer<typeof ClaimDomainSchema>
|
||||
try {
|
||||
body = ClaimDomainSchema.parse(await request.json())
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Invalid request body' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const result = await claimCustomDomain(ctx.supabase, ctx.companyId, body.domain)
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.error }, { status: result.status })
|
||||
}
|
||||
return NextResponse.json({ data: result.data })
|
||||
},
|
||||
},
|
||||
|
||||
// ── Custom inbound domain: re-check verification ─────────
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/inbox/domain/verify',
|
||||
handler: async (_request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
if (!customDomainsEnabled()) return customDomainsDisabledResponse()
|
||||
|
||||
const isAdmin = await isCompanyAdmin(ctx.supabase, ctx.userId, ctx.companyId)
|
||||
if (!isAdmin) return NextResponse.json({ error: 'Behörighet saknas.' }, { status: 403 })
|
||||
|
||||
// verify() triggers a DNS check at Resend — rate-limit the button.
|
||||
const limit = await checkInboxUploadRateLimit(ctx.supabase, ctx.companyId)
|
||||
if (!limit.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: 'För många kontroller — försök igen om en stund.', retry_after: limit.retryAfterSec },
|
||||
{ status: 429, headers: { 'Retry-After': String(limit.retryAfterSec ?? 60) } },
|
||||
)
|
||||
}
|
||||
|
||||
const result = await checkCustomDomainVerification(ctx.supabase, ctx.companyId)
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.error }, { status: result.status })
|
||||
}
|
||||
return NextResponse.json({ data: result.data })
|
||||
},
|
||||
},
|
||||
|
||||
// ── Custom inbound domain: remove (admin/owner only) ─────
|
||||
{
|
||||
method: 'DELETE',
|
||||
path: '/inbox/domain',
|
||||
handler: async (_request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
if (!customDomainsEnabled()) return customDomainsDisabledResponse()
|
||||
|
||||
const isAdmin = await isCompanyAdmin(ctx.supabase, ctx.userId, ctx.companyId)
|
||||
if (!isAdmin) return NextResponse.json({ error: 'Behörighet saknas.' }, { status: 403 })
|
||||
|
||||
const result = await removeCustomDomain(ctx.supabase, ctx.companyId)
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.error }, { status: result.status })
|
||||
}
|
||||
return NextResponse.json({ data: result.data })
|
||||
},
|
||||
},
|
||||
|
||||
// ── Resend Inbound webhook (Svix-signed, no user auth) ──
|
||||
{
|
||||
method: 'POST',
|
||||
@@ -1313,44 +1460,87 @@ export const invoiceInboxExtension: Extension = {
|
||||
return NextResponse.json({ error: 'Verification failed' }, { status: 500 })
|
||||
}
|
||||
|
||||
// Resend pushes domain.* lifecycle events to the same webhook. Apply
|
||||
// domain.updated to custom-domain rows so verification flips without
|
||||
// the user pressing "Kontrollera igen" (requires the event type to be
|
||||
// subscribed on the Resend webhook; harmless when it isn't).
|
||||
if (event.type === 'domain.updated') {
|
||||
const domainServiceSupabase = createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!
|
||||
)
|
||||
const matched = await applyDomainStatusFromWebhook(domainServiceSupabase, {
|
||||
id: event.data.id,
|
||||
status: event.data.status,
|
||||
records: event.data.records,
|
||||
})
|
||||
return NextResponse.json({ data: { domain_updated: matched } })
|
||||
}
|
||||
|
||||
if (!isEmailReceivedEvent(event)) {
|
||||
return NextResponse.json({ data: { ignored: event.type } }, { status: 200 })
|
||||
}
|
||||
|
||||
const { email_id, to, from, subject, message_id, created_at } = event.data
|
||||
|
||||
const localPart = extractLocalPartForDomain(to, domain)
|
||||
if (!localPart) {
|
||||
console.warn('[invoice-inbox/inbound] No recipient matched domain', { to, domain })
|
||||
return NextResponse.json({ error: 'No matching recipient' }, { status: 404 })
|
||||
}
|
||||
|
||||
const serviceSupabase = createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!
|
||||
)
|
||||
|
||||
const { data: inbox } = await serviceSupabase
|
||||
.from('company_inboxes')
|
||||
.select('id, company_id, status')
|
||||
.eq('local_part', localPart)
|
||||
.maybeSingle()
|
||||
// Recipient → company resolution. Shared-domain addresses first
|
||||
// (existing local_part flow), then per-company verified custom
|
||||
// domains. Custom domains are catch-all by design: MX routing is
|
||||
// per-domain, and a supplier typing fakturor@ instead of faktura@
|
||||
// must land in the inbox rather than silently vanish (Resend has
|
||||
// already accepted the message; there is no bounce path).
|
||||
let companyId: string | null = null
|
||||
let sharedInboxStatus: string | null = null
|
||||
|
||||
if (!inbox) {
|
||||
return NextResponse.json({ error: 'Address not found' }, { status: 404 })
|
||||
const localPart = extractLocalPartForDomain(to, domain)
|
||||
if (localPart) {
|
||||
const { data: inbox } = await serviceSupabase
|
||||
.from('company_inboxes')
|
||||
.select('id, company_id, status')
|
||||
.eq('local_part', localPart)
|
||||
.maybeSingle()
|
||||
if (inbox) {
|
||||
sharedInboxStatus = inbox.status
|
||||
if (inbox.status === 'active') companyId = inbox.company_id
|
||||
}
|
||||
}
|
||||
if (inbox.status !== 'active') {
|
||||
return NextResponse.json({ error: 'Address no longer active' }, { status: 410 })
|
||||
|
||||
if (!companyId) {
|
||||
const customDomains = parseRecipients(to)
|
||||
.map((r) => r.domain)
|
||||
.filter((d) => d !== domain.toLowerCase())
|
||||
if (customDomains.length > 0) {
|
||||
const match = await findCompanyForRecipientDomains(serviceSupabase, customDomains)
|
||||
if (match) companyId = match.companyId
|
||||
}
|
||||
}
|
||||
|
||||
if (!companyId) {
|
||||
// Preserve the pre-custom-domain status semantics: 410 for a
|
||||
// deprecated/blocked shared address, 404 otherwise.
|
||||
if (sharedInboxStatus && sharedInboxStatus !== 'active') {
|
||||
return NextResponse.json({ error: 'Address no longer active' }, { status: 410 })
|
||||
}
|
||||
console.warn('[invoice-inbox/inbound] No recipient matched', { to, domain })
|
||||
return NextResponse.json(
|
||||
{ error: localPart ? 'Address not found' : 'No matching recipient' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
const { data: company } = await serviceSupabase
|
||||
.from('companies')
|
||||
.select('created_by')
|
||||
.eq('id', inbox.company_id)
|
||||
.eq('id', companyId)
|
||||
.single()
|
||||
|
||||
if (!company?.created_by) {
|
||||
console.error('[invoice-inbox/inbound] Company has no created_by', inbox.company_id)
|
||||
console.error('[invoice-inbox/inbound] Company has no created_by', companyId)
|
||||
return NextResponse.json({ error: 'Company owner missing' }, { status: 500 })
|
||||
}
|
||||
const userId = company.created_by
|
||||
@@ -1370,11 +1560,11 @@ export const invoiceInboxExtension: Extension = {
|
||||
// Per-company rate limit (30/min, 500/day). Same Postgres-backed
|
||||
// RPC as /upload. Acknowledge + drop on cap — returning 429 to
|
||||
// Resend would just consume more budget via their retry.
|
||||
const limit = await checkInboxUploadRateLimit(serviceSupabase, inbox.company_id)
|
||||
const limit = await checkInboxUploadRateLimit(serviceSupabase, companyId)
|
||||
if (!limit.ok) {
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId: inbox.company_id,
|
||||
companyId,
|
||||
correlationId: email_id,
|
||||
aggregateType: 'System',
|
||||
aggregateId: email_id,
|
||||
@@ -1404,7 +1594,7 @@ export const invoiceInboxExtension: Extension = {
|
||||
if (truncatedCount > 0) {
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId: inbox.company_id,
|
||||
companyId,
|
||||
correlationId: email_id,
|
||||
aggregateType: 'System',
|
||||
aggregateId: email_id,
|
||||
@@ -1426,7 +1616,7 @@ export const invoiceInboxExtension: Extension = {
|
||||
|
||||
if (attachments.length === 0) {
|
||||
await serviceSupabase.from('invoice_inbox_items').insert({
|
||||
company_id: inbox.company_id,
|
||||
company_id: companyId,
|
||||
user_id: userId,
|
||||
status: 'error',
|
||||
source: 'email',
|
||||
@@ -1459,7 +1649,7 @@ export const invoiceInboxExtension: Extension = {
|
||||
// oversized values when read back into the UI / audit trails.
|
||||
try {
|
||||
await serviceSupabase.from('invoice_inbox_items').insert({
|
||||
company_id: inbox.company_id,
|
||||
company_id: companyId,
|
||||
user_id: userId,
|
||||
status: 'error',
|
||||
source: 'email',
|
||||
@@ -1530,7 +1720,7 @@ export const invoiceInboxExtension: Extension = {
|
||||
const innerResult = await uploadAndExtract(
|
||||
serviceSupabase,
|
||||
userId,
|
||||
inbox.company_id,
|
||||
companyId,
|
||||
{ name: innerName, buffer: innerArrayBuffer, type: innerType },
|
||||
'email',
|
||||
{
|
||||
@@ -1562,7 +1752,7 @@ export const invoiceInboxExtension: Extension = {
|
||||
const result = await uploadAndExtract(
|
||||
serviceSupabase,
|
||||
userId,
|
||||
inbox.company_id,
|
||||
companyId,
|
||||
{ name: download.filename, buffer: download.buffer, type: download.contentType },
|
||||
'email',
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -94,6 +94,19 @@ export function extractLocalPartForDomain(recipients: string[], domain: string):
|
||||
return null
|
||||
}
|
||||
|
||||
// Splits every parseable recipient into { localPart, domain }, lowercased and
|
||||
// in original order. Used to match recipients against per-company verified
|
||||
// custom domains when none of them is on the shared inbound domain.
|
||||
export function parseRecipients(recipients: string[]): Array<{ localPart: string; domain: string }> {
|
||||
const parsed: Array<{ localPart: string; domain: string }> = []
|
||||
for (const addr of recipients) {
|
||||
const match = addr.match(/^\s*([^@\s]+)@([^@\s]+?)\s*$/)
|
||||
if (!match) continue
|
||||
parsed.push({ localPart: match[1].toLowerCase(), domain: match[2].toLowerCase() })
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
export function isEmailReceivedEvent(event: WebhookEventPayload): event is EmailReceivedEvent {
|
||||
return event.type === 'email.received'
|
||||
}
|
||||
|
||||
@@ -85,9 +85,16 @@ describe('tools/list payload size guard', () => {
|
||||
// already use the compact "Dims bag" form (~90 tokens trimmed first);
|
||||
// the remainder is schema structure the resolve-don't-select contract
|
||||
// depends on, not trimmable prose.
|
||||
// * 44K → 45K when the rot/rut branch merged with main: main's #877 put
|
||||
// qualified identifiers in all tool output schemas (+~260 across 103
|
||||
// tools — wire contract, not prose) and the branch added
|
||||
// gnubok_generate_rot_rut_file (~444: begäran-om-utbetalning file flow,
|
||||
// eligible/blocked per-invoice output). Each side alone was under the
|
||||
// ceiling; the combination crossed it by ~220. Descriptions are at
|
||||
// their trimmed floor per the entries above.
|
||||
// Long-term answer to growth is leaning harder on gnubok_search_tools — if this
|
||||
// fires again, prefer trimming descriptions or making a tool opt-in via search
|
||||
// before bumping further.
|
||||
expect(approxTokens).toBeLessThan(44_000)
|
||||
expect(approxTokens).toBeLessThan(45_000)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Tests for the test-mode API-key write guard in the MCP dispatcher.
|
||||
*
|
||||
* A `gnubok_sk_test_` key is bound to the REAL active company. On the v1 REST
|
||||
* surface every write is forced to dry-run (or blocked when it can't be
|
||||
* simulated). The MCP tools/call path must mirror that: a write tool that
|
||||
* cannot be simulated is refused BEFORE execute() so a test key can never stage
|
||||
* a real pending_operation (and, with the approve scope, commit it). Read tools
|
||||
* pass through unchanged.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/auth/api-keys')>()
|
||||
const chain: unknown = new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => resolve({ data: null, error: null })
|
||||
}
|
||||
return () => chain
|
||||
},
|
||||
},
|
||||
)
|
||||
return {
|
||||
...actual,
|
||||
extractBearerToken: vi.fn().mockReturnValue('test-token'),
|
||||
// A TEST-mode key holding the approve scope, so the scope gate passes and
|
||||
// the test-key write guard is what we exercise.
|
||||
validateApiKey: vi.fn().mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: '11111111-1111-4111-8111-111111111111',
|
||||
scopes: ['pending_operations:approve', 'reports:read'],
|
||||
apiKeyId: 'key-test-1',
|
||||
apiKeyName: 'Test Key',
|
||||
mode: 'test',
|
||||
}),
|
||||
createServiceClientNoCookies: vi.fn(() => ({ from: () => chain, rpc: () => chain })),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
|
||||
return { ...actual, hasCapability: vi.fn().mockResolvedValue(true) }
|
||||
})
|
||||
|
||||
import { handleMcpRequest } from '../server'
|
||||
|
||||
function mcpToolCall(name: string, args: Record<string, unknown> = {}): Request {
|
||||
return new Request('http://localhost:3000/api/extensions/ext/mcp-server/mcp', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test-token' },
|
||||
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
|
||||
})
|
||||
}
|
||||
|
||||
interface ToolCalledEvent {
|
||||
tool: string
|
||||
success: boolean
|
||||
isError: boolean
|
||||
errorKind: string | null
|
||||
latencyMs: number
|
||||
}
|
||||
|
||||
function captureNextToolCalled(): Promise<ToolCalledEvent> {
|
||||
return new Promise((resolve) => {
|
||||
const off = eventBus.on('mcp.tool_called', (payload) => {
|
||||
off()
|
||||
resolve(payload as unknown as ToolCalledEvent)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function parsedToolResult(response: Response): Promise<{ isError: boolean; payload: Record<string, unknown> }> {
|
||||
const json = await response.json()
|
||||
const result = json.result as { isError?: boolean; content: { text: string }[] }
|
||||
return { isError: result.isError === true, payload: JSON.parse(result.content[0].text) }
|
||||
}
|
||||
|
||||
describe('MCP test-key write guard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
it('blocks a non-simulatable write tool for a test-mode key — before execute()', async () => {
|
||||
const eventPromise = captureNextToolCalled()
|
||||
|
||||
// approve has readOnlyHint:false and no dry_run param → cannot be simulated.
|
||||
const response = await handleMcpRequest(
|
||||
mcpToolCall('gnubok_approve_pending_operation', { operation_id: 'op-1' }),
|
||||
)
|
||||
const { isError } = await parsedToolResult(response)
|
||||
|
||||
expect(isError).toBe(true)
|
||||
const event = await eventPromise
|
||||
expect(event.errorKind).toBe('test_key_write_blocked')
|
||||
expect(event.success).toBe(false)
|
||||
// Exits before tool.execute() — no pending op is ever committed.
|
||||
expect(event.latencyMs).toBe(0)
|
||||
})
|
||||
|
||||
it('lets a read-only tool through for a test-mode key', async () => {
|
||||
const eventPromise = captureNextToolCalled()
|
||||
|
||||
await handleMcpRequest(mcpToolCall('gnubok_list_skills', {}))
|
||||
|
||||
const event = await eventPromise
|
||||
// Whatever happens inside execute(), the test-key guard must NOT fire on a
|
||||
// read tool.
|
||||
expect(event.errorKind).not.toBe('test_key_write_blocked')
|
||||
})
|
||||
})
|
||||
@@ -64,6 +64,7 @@ import { generateSupplierLedger } from '@/lib/reports/supplier-ledger'
|
||||
import { getReconciliationStatus } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { createInvoicePaymentJournalEntry, createInvoiceCashEntry, createInvoiceJournalEntry } from '@/lib/bookkeeping/invoice-entries'
|
||||
import { findMatchingInvoices } from '@/lib/invoices/invoice-matching'
|
||||
import { listRotRutCandidates, createRotRutPayoutRequest } from '@/lib/invoices/rot-rut-service'
|
||||
import {
|
||||
findMatchingVouchersForInvoice,
|
||||
validateVoucherForInvoiceLink,
|
||||
@@ -9057,6 +9058,135 @@ export const tools: McpTool[] = [
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_generate_rot_rut_file',
|
||||
title: 'Generate Rot/Rut Payout File',
|
||||
description:
|
||||
'Begäran om utbetalning for rot/rut (Skatteverket husavdrag): XML file from paid deduction invoices, uploaded manually on skatteverket.se (no API exists). Call with list_only=true first to see eligible invoices and blockers. Generating records an active begäran per invoice.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
deduction_type: { type: 'string', enum: ['rot', 'rut'] },
|
||||
list_only: {
|
||||
type: 'boolean',
|
||||
description: 'Only list eligible + blocked invoices, generate nothing (default false)',
|
||||
},
|
||||
invoice_ids: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: 'Invoices to include. Omitted = all currently eligible.',
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
maxLength: 16,
|
||||
description: 'NamnPaBegaran shown in Skatteverkets e-tjänst (max 16 chars). Omitted = generated.',
|
||||
},
|
||||
},
|
||||
required: ['deduction_type'],
|
||||
},
|
||||
outputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
deduction_type: { type: 'string' },
|
||||
eligible: { type: 'array', items: { type: 'object' } },
|
||||
blocked: {
|
||||
type: 'array',
|
||||
items: { type: 'object' },
|
||||
description: 'Invoices excluded from begäran with per-invoice blocker code + Swedish message',
|
||||
},
|
||||
generated: { type: 'boolean' },
|
||||
request_id: { type: ['string', 'null'] },
|
||||
file_name: { type: ['string', 'null'] },
|
||||
xml: { type: ['string', 'null'], description: 'File content — save as UTF-8 .xml and upload on skatteverket.se' },
|
||||
requested_total: { type: 'number' },
|
||||
arenden: { type: 'array', items: { type: 'object' } },
|
||||
warnings: { type: 'array', items: { type: 'string' } },
|
||||
upload_url: { type: 'string' },
|
||||
},
|
||||
required: ['deduction_type', 'generated'],
|
||||
},
|
||||
annotations: {
|
||||
readOnlyHint: false, // records a rot_rut_payout_requests row when generating
|
||||
destructiveHint: false,
|
||||
idempotentHint: false, // second call conflicts (one active begäran per invoice)
|
||||
openWorldHint: false,
|
||||
},
|
||||
async execute(args, companyId, userId, supabase) {
|
||||
const type = args.deduction_type as 'rot' | 'rut'
|
||||
if (type !== 'rot' && type !== 'rut') throw new Error('deduction_type must be rot or rut')
|
||||
const uploadUrl = 'https://www7.skatteverket.se/portal/rotrut/begar-utbetalning/fil'
|
||||
|
||||
const candidates = await listRotRutCandidates(supabase, companyId, type)
|
||||
if (!candidates.ok) throw new Error('Failed to list rot/rut candidates')
|
||||
|
||||
if (args.list_only === true) {
|
||||
return {
|
||||
deduction_type: type,
|
||||
eligible: candidates.eligible,
|
||||
blocked: candidates.blocked,
|
||||
generated: false,
|
||||
request_id: null,
|
||||
file_name: null,
|
||||
xml: null,
|
||||
requested_total: candidates.eligible.reduce((sum, e) => sum + e.begart_belopp, 0),
|
||||
warnings: [],
|
||||
upload_url: uploadUrl,
|
||||
}
|
||||
}
|
||||
|
||||
const requestedIds = Array.isArray(args.invoice_ids) && args.invoice_ids.length > 0
|
||||
? (args.invoice_ids as string[])
|
||||
: candidates.eligible.map((e) => e.invoice_id)
|
||||
if (requestedIds.length === 0) {
|
||||
return {
|
||||
deduction_type: type,
|
||||
eligible: [],
|
||||
blocked: candidates.blocked,
|
||||
generated: false,
|
||||
request_id: null,
|
||||
file_name: null,
|
||||
xml: null,
|
||||
requested_total: 0,
|
||||
warnings: ['Inga fakturor är redo att begäras. Se blocked för orsaker per faktura.'],
|
||||
upload_url: uploadUrl,
|
||||
}
|
||||
}
|
||||
|
||||
const result = await createRotRutPayoutRequest(supabase, companyId, userId, {
|
||||
type,
|
||||
invoiceIds: requestedIds,
|
||||
name: typeof args.name === 'string' ? args.name : undefined,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
const blockerLines = (result.blockers ?? [])
|
||||
.map((b) => `${b.invoice_number ?? b.invoice_id}: ${b.message}`)
|
||||
.join(' | ')
|
||||
throw new Error(
|
||||
result.code === 'ROT_RUT_INVOICE_CONFLICT'
|
||||
? 'Minst en faktura ingår redan i en aktiv begäran om utbetalning.'
|
||||
: `Filen kunde inte skapas (${result.code}).${blockerLines ? ` ${blockerLines}` : ''}`,
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
deduction_type: type,
|
||||
eligible: candidates.eligible,
|
||||
blocked: candidates.blocked,
|
||||
generated: true,
|
||||
request_id: result.request.id as string,
|
||||
file_name: result.file.file_name,
|
||||
xml: result.file.xml,
|
||||
requested_total: result.file.requested_total,
|
||||
arenden: result.file.arenden,
|
||||
warnings: result.file.warnings,
|
||||
upload_url: uploadUrl,
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_audit_package',
|
||||
title: 'Generate Audit Package',
|
||||
@@ -11386,7 +11516,7 @@ function emitToolCallTelemetry(payload: {
|
||||
success: boolean
|
||||
isError: boolean
|
||||
errorCode: string | null
|
||||
errorKind: 'execution' | 'scope_denied' | 'capability_denied' | 'unknown_tool' | null
|
||||
errorKind: 'execution' | 'scope_denied' | 'capability_denied' | 'unknown_tool' | 'test_key_write_blocked' | null
|
||||
errorMessage: string | null
|
||||
requestId: string | number | null
|
||||
userId: string
|
||||
@@ -11650,7 +11780,7 @@ export async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
})
|
||||
}
|
||||
|
||||
const { userId, companyId, scopes: keyScopes, apiKeyId, apiKeyName } = authResult
|
||||
const { userId, companyId, scopes: keyScopes, apiKeyId, apiKeyName, mode: keyMode } = authResult
|
||||
const supabase = createServiceClientNoCookies()
|
||||
// The Mcp-Session-Id header (introduced in spec 2025-06-18) is the canonical
|
||||
// way for an agent to keep a stable identifier across tools/call invocations
|
||||
@@ -11870,6 +12000,47 @@ export async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
)
|
||||
}
|
||||
|
||||
// Test-mode API keys are simulation-only. Mirror the v1 REST guard
|
||||
// (lib/api/v1/with-api-v1.ts): force dry-run on any write tool that
|
||||
// supports it, and block writes that cannot be simulated. Without this a
|
||||
// gnubok_sk_test_ key — which is bound to the real active company — could
|
||||
// stage real pending_operations here and, with the approve scope, commit
|
||||
// them. Runs before execute() so nothing is ever staged for a test key.
|
||||
if (keyMode === 'test' && tool.annotations?.readOnlyHint === false) {
|
||||
const props = (tool.inputSchema as { properties?: Record<string, unknown> } | undefined)
|
||||
?.properties
|
||||
if (props && 'dry_run' in props) {
|
||||
;(toolArgs as Record<string, unknown>).dry_run = true
|
||||
} else {
|
||||
const blocked = toToolError(
|
||||
new Error(
|
||||
'Test-nyckel kan inte utföra riktiga skrivningar mot det här verktyget. Använd en live-nyckel för skarpa operationer.'
|
||||
),
|
||||
{ toolName }
|
||||
)
|
||||
emitToolCallTelemetry({
|
||||
tool: toolName,
|
||||
requiredScope: requiredScope ?? null,
|
||||
actor,
|
||||
latencyMs: 0,
|
||||
success: false,
|
||||
isError: true,
|
||||
errorCode: blocked.error.code,
|
||||
errorKind: 'test_key_write_blocked',
|
||||
errorMessage: blocked.error.message_sv,
|
||||
requestId: id ?? null,
|
||||
userId,
|
||||
companyId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
jsonRpc(id ?? null, {
|
||||
content: [{ type: 'text', text: JSON.stringify(blocked, null, 2) }],
|
||||
isError: true,
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Detect if THIS call follows the previous call's `next` hint — must
|
||||
// run before execute() so we don't double-store on this call. Emits
|
||||
// mcp.next_hint_followed when the agent's behaviour matches the hint.
|
||||
|
||||
@@ -426,6 +426,27 @@ describe('CreateInvoiceItemSchema', () => {
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts orgnr-shaped brf_org_number values', () => {
|
||||
for (const value of ['769600-0000', '7696000000', '167696000000']) {
|
||||
const result = CreateInvoiceItemSchema.safeParse(validInvoiceItem({ brf_org_number: value }))
|
||||
expect(result.success).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('normalizes an empty brf_org_number to null', () => {
|
||||
const result = CreateInvoiceItemSchema.safeParse(validInvoiceItem({ brf_org_number: '' }))
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) expect(result.data.brf_org_number).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects malformed brf_org_number values', () => {
|
||||
// incl. a 12-digit value without the mandatory sekelsiffra 16 prefix
|
||||
for (const value of ['---', '123', '76-96000000', 'ABC600-0000', '123456789012']) {
|
||||
const result = CreateInvoiceItemSchema.safeParse(validInvoiceItem({ brf_org_number: value }))
|
||||
expect(result.success).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a product row with an empty description', () => {
|
||||
const result = CreateInvoiceItemSchema.safeParse(validInvoiceItem({ description: ' ' }))
|
||||
expect(result.success).toBe(false)
|
||||
@@ -1307,6 +1328,82 @@ describe('UpdateSettingsSchema', () => {
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('invoice_email_texts', () => {
|
||||
it('accepts a valid nested partial', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
invoice_email_texts: { sv: { body: 'Tack för din beställning!' } },
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) {
|
||||
expect(result.data.invoice_email_texts).toEqual({
|
||||
sv: { body: 'Tack för din beställning!' },
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('accepts both languages with all four fields', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
invoice_email_texts: {
|
||||
sv: {
|
||||
subject: 'Faktura {fakturanummer}',
|
||||
greeting: 'Hejsan,',
|
||||
body: 'Här kommer fakturan.',
|
||||
signoff: 'Allt gott,',
|
||||
},
|
||||
en: {
|
||||
subject: 'Invoice {fakturanummer}',
|
||||
greeting: 'Hello,',
|
||||
body: 'Please find the invoice attached.',
|
||||
signoff: 'Best,',
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts null to clear all overrides', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ invoice_email_texts: null })
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) expect(result.data.invoice_email_texts).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects body over 2000 characters', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
invoice_email_texts: { sv: { body: 'x'.repeat(2001) } },
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects subject over 200 characters', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
invoice_email_texts: { sv: { subject: 'x'.repeat(201) } },
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a non-string field value', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
invoice_email_texts: { sv: { subject: 123 } },
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('strips unknown keys inside a language object', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({
|
||||
invoice_email_texts: { sv: { body: 'Hej', subjct: 'typo' } },
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) {
|
||||
expect(result.data.invoice_email_texts).toEqual({ sv: { body: 'Hej' } })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a bare string as the column value', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ invoice_email_texts: 'Tack!' })
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
|
||||
@@ -285,6 +285,18 @@ export const CreateInvoiceItemSchema = z
|
||||
work_type: z.string().max(64).nullable().optional(),
|
||||
housing_designation: z.string().max(128).nullable().optional(),
|
||||
apartment_number: z.string().max(32).nullable().optional(),
|
||||
// Bostadsrättsföreningens orgnr (XSD BrfOrgNrTYPE). If present it must be
|
||||
// a real orgnr shape — 10 digits (optional dash after position 6) or the
|
||||
// 12-digit sekelsiffra form — or Skatteverkets schemavalidering rejects
|
||||
// the whole file at upload time. Empty string = cleared field → null.
|
||||
brf_org_number: z
|
||||
.union([
|
||||
z.string().regex(/^(\d{6}-?\d{4}|16\d{10})$/, 'Ogiltigt organisationsnummer (10 siffror, ev. med bindestreck)'),
|
||||
z.literal(''),
|
||||
])
|
||||
.transform((v) => v || null)
|
||||
.nullable()
|
||||
.optional(),
|
||||
// Periodisering (förutbetald intäkt): defer the line's net revenue over
|
||||
// the service period. The revenue entry credits the 29xx interim account
|
||||
// instead of the revenue account; output VAT is never deferred.
|
||||
@@ -354,6 +366,18 @@ export const CreateInvoiceSchema = z.object({
|
||||
// present (enforced via rot-rut-rules.validateInvoice in the API).
|
||||
deduction_personnummer: z.string().max(20).optional(),
|
||||
deduction_housing_designation: z.string().max(128).optional(),
|
||||
// ROT i bostadsrätt: lägenhetsnummer + föreningens orgnr replace the
|
||||
// fastighetsbeteckning (Begaran.xsd: LagenhetsNr + BrfOrgNr). Stamped onto
|
||||
// the rot lines server-side, same as deduction_housing_designation.
|
||||
deduction_apartment_number: z.string().max(25).optional(),
|
||||
// Same orgnr shape rule as items[].brf_org_number; empty string = not set.
|
||||
deduction_brf_org_number: z
|
||||
.union([
|
||||
z.string().regex(/^(\d{6}-?\d{4}|16\d{10})$/, 'Ogiltigt organisationsnummer (10 siffror, ev. med bindestreck)'),
|
||||
z.literal(''),
|
||||
])
|
||||
.transform((v) => v || undefined)
|
||||
.optional(),
|
||||
// When true, save as an unnumbered draft: skip F-series allocation and the
|
||||
// invoice.created event until the user finalizes via POST /invoices/{id}/finalize
|
||||
// ("Granska och skapa"). An unnumbered draft is not yet an issued faktura
|
||||
@@ -379,6 +403,36 @@ export const CreateCreditNoteSchema = z.object({
|
||||
reason: z.string().optional(),
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// Rot/rut begäran om utbetalning (Skatteverkets husavdragstjänst)
|
||||
// ============================================================
|
||||
|
||||
export const RotRutPayoutFileSchema = z.object({
|
||||
deduction_type: z.enum(['rot', 'rut']),
|
||||
invoice_ids: z.array(uuid).min(1).max(500),
|
||||
// NamnPaBegaran — the XSD caps it at 16 chars; omitted → generated.
|
||||
name: z.string().min(1).max(16).optional(),
|
||||
})
|
||||
|
||||
export const RotRutRequestPatchSchema = z.object({
|
||||
status: z.enum(['submitted', 'paid', 'partially_paid', 'rejected', 'cancelled']),
|
||||
// Godkänt belopp from Skatteverkets beslut. Only meaningful together with
|
||||
// paid/partially_paid/rejected.
|
||||
decided_total: nonNegativeAmount.optional(),
|
||||
})
|
||||
|
||||
export const RotRutSettleSchema = z.object({
|
||||
payment_date: isoDate,
|
||||
// Defaults server-side to decided_total ?? requested_total.
|
||||
amount: z.number().positive().optional(),
|
||||
// BAS 19xx account the payout landed on (1920 Bank, 1930 Företagskonto, …).
|
||||
// Omitted → 1930. The engine validates existence against chart_of_accounts.
|
||||
bank_account: z
|
||||
.string()
|
||||
.regex(/^19\d{2}$/, 'Bankkontot måste vara ett BAS 19xx-konto')
|
||||
.optional(),
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// Articles (artikelregister)
|
||||
// ============================================================
|
||||
@@ -1165,6 +1219,24 @@ export const MatchSupplierInvoiceSchema = z.object({
|
||||
// Settings schemas
|
||||
// ============================================================
|
||||
|
||||
// Editable invoice email texts (standard invoices only). Nested JSONB —
|
||||
// unknown keys inside are stripped (Zod default, consistent with this file).
|
||||
// Empty strings pass validation; the template resolver treats whitespace-only
|
||||
// as unset, and the UI prunes empties before saving so the stored object
|
||||
// stays minimal. Subject is a mail header: CR/LF are stripped at render time
|
||||
// regardless.
|
||||
const InvoiceEmailTextsLangSchema = z.object({
|
||||
subject: z.string().max(200, 'Ämnesraden får vara max 200 tecken').optional(),
|
||||
greeting: z.string().max(200, 'Hälsningen får vara max 200 tecken').optional(),
|
||||
body: z.string().max(2000, 'Brödtexten får vara max 2000 tecken').optional(),
|
||||
signoff: z.string().max(200, 'Avslutningen får vara max 200 tecken').optional(),
|
||||
})
|
||||
|
||||
export const InvoiceEmailTextsSchema = z.object({
|
||||
sv: InvoiceEmailTextsLangSchema.optional(),
|
||||
en: InvoiceEmailTextsLangSchema.optional(),
|
||||
})
|
||||
|
||||
export const UpdateSettingsSchema = z.object({
|
||||
entity_type: EntityTypeSchema.optional(),
|
||||
company_name: z.string().optional(),
|
||||
@@ -1242,6 +1314,10 @@ export const UpdateSettingsSchema = z.object({
|
||||
invoice_company_name_position: z.enum(['header', 'footer']).optional(),
|
||||
invoice_late_fee_text: z.string().nullable().optional(),
|
||||
invoice_credit_terms_text: z.string().nullable().optional(),
|
||||
// Editable invoice email texts — { sv?: {...}, en?: {...} }; null clears
|
||||
// all overrides. Without this entry the generic PUT would silently strip
|
||||
// the field (the schema is the de-facto column whitelist).
|
||||
invoice_email_texts: InvoiceEmailTextsSchema.nullable().optional(),
|
||||
// Invoice branding — colors enforced as #RRGGBB at the DB level too
|
||||
// (see migration 20260526120200_invoice_branding.sql). The dedicated
|
||||
// /api/settings/invoicing/branding route is the primary path; these
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { apiPathSkipsMfaGate } from '@/lib/auth/api-mfa-gate'
|
||||
|
||||
describe('apiPathSkipsMfaGate', () => {
|
||||
it('skips the gate only on Bearer-auth surfaces when an Authorization header is present', () => {
|
||||
expect(apiPathSkipsMfaGate('/api/v1/companies/abc/invoices', true)).toBe(true)
|
||||
expect(apiPathSkipsMfaGate('/api/extensions/ext/mcp-server/mcp', true)).toBe(true)
|
||||
})
|
||||
|
||||
it('never lets an Authorization header disable the gate on cookie-authenticated routes', () => {
|
||||
// A stolen-password AAL1 cookie session must not bypass MFA by attaching
|
||||
// a garbage Authorization header the route ignores (Superagent P2, #878).
|
||||
expect(apiPathSkipsMfaGate('/api/bookkeeping/journal-entries/123', true)).toBe(false)
|
||||
expect(apiPathSkipsMfaGate('/api/reports/full-archive', true)).toBe(false)
|
||||
expect(apiPathSkipsMfaGate('/api/salary/employees/1', true)).toBe(false)
|
||||
// Non-MCP extension routes authenticate via cookies in the dispatcher.
|
||||
expect(apiPathSkipsMfaGate('/api/extensions/ext/invoice-inbox/custom-domain', true)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not skip Bearer-auth surfaces without an Authorization header', () => {
|
||||
expect(apiPathSkipsMfaGate('/api/v1/companies/abc/invoices', false)).toBe(false)
|
||||
expect(apiPathSkipsMfaGate('/api/extensions/ext/mcp-server/mcp', false)).toBe(false)
|
||||
})
|
||||
|
||||
it('skips the gate for the AAL1 escape-hatch and OAuth routes', () => {
|
||||
expect(apiPathSkipsMfaGate('/api/account/password', false)).toBe(true)
|
||||
expect(apiPathSkipsMfaGate('/api/account/set-password', false)).toBe(true)
|
||||
expect(apiPathSkipsMfaGate('/api/company', false)).toBe(true)
|
||||
expect(apiPathSkipsMfaGate('/api/company/members', false)).toBe(true)
|
||||
expect(apiPathSkipsMfaGate('/api/mcp-oauth/authorize', false)).toBe(true)
|
||||
expect(apiPathSkipsMfaGate('/api/mcp-oauth/token', false)).toBe(true)
|
||||
})
|
||||
|
||||
it('gates cookie-authenticated calls to sensitive dashboard routes', () => {
|
||||
expect(apiPathSkipsMfaGate('/api/bookkeeping/journal-entries/123', false)).toBe(false)
|
||||
expect(apiPathSkipsMfaGate('/api/salary/employees/1', false)).toBe(false)
|
||||
expect(apiPathSkipsMfaGate('/api/reports/full-archive', false)).toBe(false)
|
||||
expect(apiPathSkipsMfaGate('/api/documents/1', false)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not let a lookalike prefix bypass the account/company allowlist', () => {
|
||||
// "/api/accounts" (plural, a different resource) must NOT match the
|
||||
// "/api/account/" escape hatch.
|
||||
expect(apiPathSkipsMfaGate('/api/accounts', false)).toBe(false)
|
||||
expect(apiPathSkipsMfaGate('/api/account', false)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -243,6 +243,8 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_export_sie: 'reports:read',
|
||||
gnubok_audit_package: 'reports:read',
|
||||
gnubok_import_sie: 'bookkeeping:write',
|
||||
// Rot/rut begäran om utbetalning (records a payout request on generate)
|
||||
gnubok_generate_rot_rut_file: 'invoices:write',
|
||||
// Supplier CRUD
|
||||
gnubok_create_supplier: 'suppliers:write',
|
||||
// Supplier invoice lifecycle
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user