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,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 })
})