Feat/voucher docs (#664)

* feat: implement inbox document picker and linking functionality

* feat: implement self-billing invoice functionality

- Added support for registering self-billed invoices received from customers.
- Updated the invoice schema to include fields for self-billing metadata such as `is_self_billed`, `external_invoice_number`, `self_billing_agreement_ref`, and `received_date`.
- Created API route for handling self-billed invoice submissions, including validation and error handling.
- Implemented database migrations to add necessary columns and constraints for self-billing invoices.
- Developed tests to ensure correct behavior of self-billing invoice creation and validation rules.
- Updated Swedish localization files to include new terms related to self-billing.

* feat: enforce SIE import requirement for non-Fortnox providers in migration process

* feat: streamline invoice processing and enhance error logging across APIs
This commit is contained in:
Mattsson
2026-06-04 13:14:57 +02:00
committed by GitHub
parent c1be9f15dd
commit 3e42fc6f32
45 changed files with 2675 additions and 529 deletions
@@ -0,0 +1,132 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
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 }),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
import { POST } from '../route'
import { requireWritePermission } from '@/lib/auth/require-write'
import { NextResponse } from 'next/server'
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
})
function makeReq(body: unknown) {
return new Request('http://localhost/api/documents/doc-1/link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
describe('POST /api/documents/[id]/link', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(makeReq({ journal_entry_id: 'je-1' }), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 403 when caller has read-only role', async () => {
vi.mocked(requireWritePermission).mockResolvedValue({
ok: false,
response: NextResponse.json(
{ error: 'Du har endast läsbehörighet i detta företag.' },
{ status: 403 },
),
})
const res = await POST(makeReq({ journal_entry_id: 'je-1' }), createMockRouteParams({ id: 'doc-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
})
it('rejects a missing journal_entry_id', async () => {
const res = await POST(makeReq({}), createMockRouteParams({ id: 'doc-1' }))
const { body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(body.error.code).toBe('VALIDATION_ERROR')
})
it('links the document and stamps the inbox item when inbox_item_id is given', async () => {
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1', file_name: 'x.pdf' } }) // link update
enqueue({ data: null }) // inbox stamp update
const res = await POST(
makeReq({ journal_entry_id: 'je-1', inbox_item_id: 'inbox-1' }),
createMockRouteParams({ id: 'doc-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(res)
expect(status).toBe(200)
expect(body.data.id).toBe('doc-1')
expect(mockSupabase.from).toHaveBeenCalledWith('document_attachments')
expect(mockSupabase.from).toHaveBeenCalledWith('invoice_inbox_items')
})
it('does not touch the inbox when no inbox_item_id is given', async () => {
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1', file_name: 'x.pdf' } }) // link update
const res = await POST(
makeReq({ journal_entry_id: 'je-1' }),
createMockRouteParams({ id: 'doc-1' }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(mockSupabase.from).not.toHaveBeenCalledWith('invoice_inbox_items')
})
it('maps a period-lock trigger error to PERIOD_LOCKED', async () => {
enqueue({
data: null,
error: { message: 'new row violates ... locked/closed fiscal period' },
})
const res = await POST(
makeReq({ journal_entry_id: 'je-1', inbox_item_id: 'inbox-1' }),
createMockRouteParams({ id: 'doc-1' }),
)
const { body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(body.error.code).toBe('PERIOD_LOCKED')
// The inbox stamp must not run when the link itself failed.
expect(mockSupabase.from).not.toHaveBeenCalledWith('invoice_inbox_items')
})
it('maps an already-linked error to DOC_LINK_ALREADY_LINKED', async () => {
enqueue({
data: null,
error: { message: 'document already linked to another entry' },
})
const res = await POST(
makeReq({ journal_entry_id: 'je-1' }),
createMockRouteParams({ id: 'doc-1' }),
)
const { body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(body.error.code).toBe('DOC_LINK_ALREADY_LINKED')
})
})
+44 -1
View File
@@ -9,7 +9,15 @@ ensureInitialized()
/**
* POST /api/documents/[id]/link — link a document to a journal entry.
*
* Body: { journal_entry_id: string, journal_entry_line_id?: string }
* Body: { journal_entry_id: string, journal_entry_line_id?: string, inbox_item_id?: string }
*
* When `inbox_item_id` is supplied (the "choose from inbox" flow), the inbox
* item is stamped with the verifikat id after a successful link so it drops out
* of the active inbox into "Bokförda" — reusing the inbox's own
* created_journal_entry_id lifecycle. The document link is the legally-relevant
* write and happens first; the inbox stamp is operational housekeeping, so a
* stamp failure is logged but does not fail the request (the doc is correctly
* attached and the DB immutability trigger still blocks any double-link).
*/
export const POST = withRouteContext(
'document.link',
@@ -35,12 +43,47 @@ export const POST = withRouteContext(
body.journal_entry_id,
body.journal_entry_line_id,
)
if (body.inbox_item_id) {
const { data: stamped, error: inboxError } = await supabase
.from('invoice_inbox_items')
.update({ created_journal_entry_id: body.journal_entry_id })
.eq('id', body.inbox_item_id)
.eq('company_id', companyId!)
// Only stamp the inbox item that actually owns this document — a
// mismatched pairing becomes a safe no-op rather than mis-marking an
// unrelated item as consumed.
.eq('document_id', id)
.select('id')
if (inboxError) {
// Non-fatal — the verifikat ↔ underlag link already succeeded.
opLog.warn('inbox item stamp after link failed', {
inboxItemId: body.inbox_item_id,
reason: inboxError.message,
})
} else if (!stamped || stamped.length === 0) {
// Zero rows updated means the supplied inbox_item_id / document_id
// pairing did not match (wrong company, wrong document, or a stale
// id). The doc link itself still succeeded; surface the cross-resource
// mismatch as an observable warning rather than silently ignoring it.
opLog.warn('inbox item stamp matched no rows (cross-resource mismatch)', {
inboxItemId: body.inbox_item_id,
})
}
}
return NextResponse.json({ data: document })
} catch (err) {
opLog.error('document link failed', err as Error, {
journalEntryId: body.journal_entry_id,
})
const message = err instanceof Error ? err.message : ''
// Linking writes journal_entry_id on document_attachments; the
// enforce_period_lock trigger blocks that when the target entry sits in a
// closed/locked period.
if (/locked\/closed fiscal period|Bokföringen är låst/i.test(message)) {
return errorResponseFromCode('PERIOD_LOCKED', opLog, { requestId })
}
if (/journal entry not found/i.test(message)) {
return errorResponseFromCode('DOC_LINK_ENTRY_NOT_FOUND', opLog, { requestId })
}
@@ -0,0 +1,127 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
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 }),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
import { GET } from '../route'
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
function makeReq() {
return new Request('http://localhost/api/documents/inbox-available')
}
describe('GET /api/documents/inbox-available', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await GET(makeReq(), createMockRouteParams({}))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns [] when no eligible inbox items (no second query)', async () => {
enqueue({ data: [] }) // inbox items
const res = await GET(makeReq(), createMockRouteParams({}))
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(res)
expect(status).toBe(200)
expect(body.data).toEqual([])
// Documents table never queried when there are no document ids.
expect(mockSupabase.from).not.toHaveBeenCalledWith('document_attachments')
})
it('joins inbox items to their documents and drops consumed/superseded ones', async () => {
enqueue({
data: [
{
id: 'inbox-1',
document_id: 'doc-1',
source: 'email',
created_at: '2026-05-01T00:00:00Z',
extracted_data: {
supplier: { name: 'Acme AB' },
totals: { total: 1250 },
invoice: { currency: 'SEK', invoiceDate: '2026-04-28' },
},
},
// doc-2's document is no longer current/unlinked → must be dropped.
{
id: 'inbox-2',
document_id: 'doc-2',
source: 'upload',
created_at: '2026-05-02T00:00:00Z',
extracted_data: null,
},
],
})
enqueue({
data: [
{
id: 'doc-1',
file_name: 'acme.pdf',
mime_type: 'application/pdf',
file_size_bytes: 1000,
journal_entry_id: null,
is_current_version: true,
},
],
})
const res = await GET(makeReq(), createMockRouteParams({}))
const { status, body } = await parseJsonResponse<{
data: Array<Record<string, unknown>>
}>(res)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
expect(body.data[0]).toEqual({
inbox_item_id: 'inbox-1',
document_id: 'doc-1',
file_name: 'acme.pdf',
mime_type: 'application/pdf',
file_size_bytes: 1000,
source: 'email',
created_at: '2026-05-01T00:00:00Z',
supplier_name: 'Acme AB',
amount: 1250,
currency: 'SEK',
invoice_date: '2026-04-28',
})
expect(mockSupabase.from).toHaveBeenCalledWith('invoice_inbox_items')
expect(mockSupabase.from).toHaveBeenCalledWith('document_attachments')
})
it('returns an error envelope when the inbox query fails', async () => {
enqueue({ data: null, error: { message: 'boom' } })
const res = await GET(makeReq(), createMockRouteParams({}))
const { status } = await parseJsonResponse(res)
expect(status).toBeGreaterThanOrEqual(500)
})
})
+114
View File
@@ -0,0 +1,114 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse } from '@/lib/errors/get-structured-error'
import type { InvoiceExtractionResult } from '@/types'
ensureInitialized()
/**
* GET /api/documents/inbox-available — list invoice-inbox documents that are
* available to attach as underlag to a verifikat.
*
* Returns only *unconsumed* inbox items: those that have a file but have not
* yet become a supplier invoice, a direct journal entry, or been matched to a
* bank transaction — and whose underlying document is not already linked to a
* verifikation. This mirrors the inbox's own "Att göra" set, narrowed to items
* with an attachable file. Re-pointing an already-linked document is forbidden
* (BFL 7 kap — räkenskapsinformation is immutable), so those are excluded here
* and the DB immutability trigger is the backstop.
*
* `invoice_inbox_items` is a core table, so a core route may read it directly
* without importing from @/extensions. When the invoice-inbox extension is not
* in use the table is simply empty and this returns [].
*/
interface InboxRow {
id: string
document_id: string | null
source: string | null
created_at: string
extracted_data: InvoiceExtractionResult | null
}
interface DocRow {
id: string
file_name: string
mime_type: string | null
file_size_bytes: number
journal_entry_id: string | null
is_current_version: boolean
}
export const GET = withRouteContext('document.inbox_available', async (_request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
// 1) Eligible inbox items — company-scoped (defense in depth alongside RLS),
// unconsumed, with a document.
const { data: inboxRows, error: inboxError } = await supabase
.from('invoice_inbox_items')
.select('id, document_id, source, created_at, extracted_data')
.eq('company_id', companyId)
.not('document_id', 'is', null)
.is('created_supplier_invoice_id', null)
.is('created_journal_entry_id', null)
.is('matched_transaction_id', null)
.order('created_at', { ascending: false })
.limit(100)
if (inboxError) {
log.error('inbox-available item query failed', inboxError)
return errorResponse(inboxError, log, { requestId })
}
const rows = (inboxRows ?? []) as InboxRow[]
const docIds = rows.map((r) => r.document_id).filter((id): id is string => !!id)
if (docIds.length === 0) {
return NextResponse.json({ data: [] })
}
// 2) The current, still-unlinked documents behind those items. Excluding
// docs with a journal_entry_id (already underlag elsewhere) and superseded
// versions keeps the picker honest even if an inbox column went stale.
const { data: docRows, error: docError } = await supabase
.from('document_attachments')
.select('id, file_name, mime_type, file_size_bytes, journal_entry_id, is_current_version')
.eq('company_id', companyId)
.in('id', docIds)
.is('journal_entry_id', null)
.eq('is_current_version', true)
if (docError) {
log.error('inbox-available document query failed', docError)
return errorResponse(docError, log, { requestId })
}
const docById = new Map<string, DocRow>()
for (const d of (docRows ?? []) as DocRow[]) docById.set(d.id, d)
// Preserve the inbox ordering (newest first); drop items whose document is
// gone, consumed, or superseded.
const data = rows
.map((row) => {
const doc = row.document_id ? docById.get(row.document_id) : undefined
if (!doc) return null
const ex = row.extracted_data
return {
inbox_item_id: row.id,
document_id: doc.id,
file_name: doc.file_name,
mime_type: doc.mime_type,
file_size_bytes: doc.file_size_bytes,
source: row.source,
created_at: row.created_at,
supplier_name: ex?.supplier?.name ?? null,
amount: ex?.totals?.total ?? null,
currency: ex?.invoice?.currency ?? 'SEK',
invoice_date: ex?.invoice?.invoiceDate ?? null,
}
})
.filter((x): x is NonNullable<typeof x> => x !== null)
return NextResponse.json({ data })
})