feat: add INK2 declaration, full archive export, AI consent gate, fix VAT declaration rutor

- Fix VAT declaration ruta mappings to match SKV 4700 form correctly
  (ruta 05 = total taxable sales, ruta 10/11/12 = output VAT per rate)
- Add INK2 declaration report for aktiebolag with SRU export
- Add full archive ZIP export for 7-year retention compliance
- Add AI consent gate requiring user approval before AI extension API calls
- Add DPA and privacy policy public pages
- Add audit trail API routes
- Update VAT registration threshold from 80k to 120k kr in onboarding
- Update CLAUDE.md documentation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-03-05 14:20:47 +01:00
co-authored by Claude Opus 4.6
parent 50bf7b3b0f
commit 29240738fa
32 changed files with 3496 additions and 97 deletions
@@ -0,0 +1,133 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest } from '@/tests/helpers'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
}))
vi.mock('@/lib/core/audit/audit-service', () => ({
getAuditLog: vi.fn(),
}))
import { createClient } from '@/lib/supabase/server'
import { getAuditLog } from '@/lib/core/audit/audit-service'
import { GET } from '../route'
const mockCreateClient = vi.mocked(createClient)
const mockGetAuditLog = vi.mocked(getAuditLog)
function mockAuth(userId: string | null) {
mockCreateClient.mockResolvedValue({
auth: {
getUser: vi.fn().mockResolvedValue({
data: { user: userId ? { id: userId } : null },
}),
},
} as any)
}
const sampleEntries = [
{
id: '1',
user_id: 'user-1',
action: 'INSERT' as const,
table_name: 'journal_entries',
record_id: 'rec-1',
actor_id: null,
old_state: null,
new_state: { description: 'Test entry' },
description: 'Created journal entry',
created_at: '2024-06-15T10:00:00Z',
},
{
id: '2',
user_id: 'user-1',
action: 'COMMIT' as const,
table_name: 'journal_entries',
record_id: 'rec-1',
actor_id: null,
old_state: { status: 'draft' },
new_state: { status: 'posted' },
description: 'Committed journal entry',
created_at: '2024-06-15T10:01:00Z',
},
]
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/reports/audit-trail', () => {
it('returns 401 when not authenticated', async () => {
mockAuth(null)
const req = createMockRequest('/api/reports/audit-trail')
const res = await GET(req)
expect(res.status).toBe(401)
})
it('returns CSV format with correct headers', async () => {
mockAuth('user-1')
mockGetAuditLog.mockResolvedValue({ data: sampleEntries as any, count: 2 })
const req = createMockRequest('/api/reports/audit-trail', {
searchParams: { format: 'csv' },
})
const res = await GET(req)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('text/csv; charset=utf-8')
expect(res.headers.get('Content-Disposition')).toBe('attachment; filename="audit-trail.csv"')
const text = await res.text()
const lines = text.split('\n')
expect(lines[0]).toBe('timestamp,action,table_name,record_id,description,old_state,new_state')
expect(lines).toHaveLength(3) // header + 2 entries
expect(lines[1]).toContain('INSERT')
expect(lines[1]).toContain('journal_entries')
})
it('returns JSON format as downloadable file', async () => {
mockAuth('user-1')
mockGetAuditLog.mockResolvedValue({ data: sampleEntries as any, count: 2 })
const req = createMockRequest('/api/reports/audit-trail', {
searchParams: { format: 'json' },
})
const res = await GET(req)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/json')
expect(res.headers.get('Content-Disposition')).toBe('attachment; filename="audit-trail.json"')
const body = await res.json()
expect(body.data).toHaveLength(2)
expect(body.count).toBe(2)
})
it('paginates through all entries', async () => {
mockAuth('user-1')
// First call returns 500 entries (full page), second returns 100 (last page)
const bigPage = Array.from({ length: 500 }, (_, i) => ({
...sampleEntries[0],
id: `entry-${i}`,
}))
const lastPage = Array.from({ length: 100 }, (_, i) => ({
...sampleEntries[0],
id: `entry-${500 + i}`,
}))
mockGetAuditLog
.mockResolvedValueOnce({ data: bigPage as any, count: 600 })
.mockResolvedValueOnce({ data: lastPage as any, count: 600 })
const req = createMockRequest('/api/reports/audit-trail', {
searchParams: { format: 'json' },
})
const res = await GET(req)
const body = await res.json()
expect(body.data).toHaveLength(600)
expect(mockGetAuditLog).toHaveBeenCalledTimes(2)
})
})
+94
View File
@@ -0,0 +1,94 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { getAuditLog } from '@/lib/core/audit/audit-service'
import type { AuditLogEntry, AuditAction } from '@/types'
const CSV_HEADERS = 'timestamp,action,table_name,record_id,description,old_state,new_state'
function escapeCSV(value: string | null | undefined): string {
if (value == null) return ''
const str = String(value)
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
return `"${str.replace(/"/g, '""')}"`
}
return str
}
function entryToCSVRow(entry: AuditLogEntry): string {
return [
escapeCSV(entry.created_at),
escapeCSV(entry.action),
escapeCSV(entry.table_name),
escapeCSV(entry.record_id),
escapeCSV(entry.description),
escapeCSV(entry.old_state ? JSON.stringify(entry.old_state) : null),
escapeCSV(entry.new_state ? JSON.stringify(entry.new_state) : null),
].join(',')
}
export async function GET(request: Request) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { searchParams } = new URL(request.url)
const format = searchParams.get('format') || 'json'
const filters = {
action: (searchParams.get('action') as AuditAction) || undefined,
table_name: searchParams.get('table_name') || undefined,
record_id: searchParams.get('record_id') || undefined,
from_date: searchParams.get('from_date') || undefined,
to_date: searchParams.get('to_date') || undefined,
}
try {
// Paginate through all matching entries
const allEntries: AuditLogEntry[] = []
let page = 1
const pageSize = 500
while (true) {
const result = await getAuditLog(supabase, user.id, {
...filters,
page,
pageSize,
})
allEntries.push(...result.data)
if (allEntries.length >= result.count || result.data.length < pageSize) {
break
}
page++
}
if (format === 'csv') {
const csvRows = [CSV_HEADERS, ...allEntries.map(entryToCSVRow)]
const csvContent = csvRows.join('\n')
return new NextResponse(csvContent, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': 'attachment; filename="audit-trail.csv"',
},
})
}
// Default: JSON
return new NextResponse(JSON.stringify({ data: allEntries, count: allEntries.length }), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Content-Disposition': 'attachment; filename="audit-trail.json"',
},
})
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to generate audit trail report' },
{ status: 500 }
)
}
}
+38
View File
@@ -0,0 +1,38 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateFullArchive } from '@/lib/reports/full-archive-export'
export async function GET(request: Request) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { searchParams } = new URL(request.url)
const periodId = searchParams.get('period_id')
if (!periodId) {
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
}
try {
const zipBuffer = await generateFullArchive(supabase, user.id, {
period_id: periodId,
include_documents: searchParams.get('include_documents') !== 'false',
})
return new NextResponse(zipBuffer, {
status: 200,
headers: {
'Content-Type': 'application/zip',
'Content-Disposition': `attachment; filename="arkiv_${periodId}.zip"`,
},
})
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to generate archive'
const status = message.includes('not found') ? 404 : 500
return NextResponse.json({ error: message }, { status })
}
}
+63
View File
@@ -0,0 +1,63 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateINK2Declaration } from '@/lib/reports/ink2/ink2-engine'
import {
generateSRUFile,
sruFileToString,
getSRUFilename,
} from '@/lib/reports/ink2/sru-generator'
/**
* GET /api/reports/ink2
*
* Generate INK2 declaration for aktiebolag.
*
* Query parameters:
* - period_id: Fiscal period ID (required)
* - format: 'json' (default) or 'sru' for SRU file download
*/
export async function GET(request: Request) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { searchParams } = new URL(request.url)
const periodId = searchParams.get('period_id')
const format = searchParams.get('format') || 'json'
if (!periodId) {
return NextResponse.json(
{ error: 'period_id is required' },
{ status: 400 }
)
}
try {
const declaration = await generateINK2Declaration(supabase, user.id, periodId)
if (format === 'sru') {
const sruFile = generateSRUFile(declaration)
const sruContent = sruFileToString(sruFile)
const filename = getSRUFilename(declaration)
return new NextResponse(sruContent, {
status: 200,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
},
})
}
return NextResponse.json({ data: declaration })
} catch (err) {
console.error('Error generating INK2 declaration:', err)
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to generate INK2 declaration' },
{ status: 500 }
)
}
}