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:
co-authored by
Claude Opus 4.6
parent
50bf7b3b0f
commit
29240738fa
@@ -0,0 +1,135 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/extensions/ai-consent', () => ({
|
||||
AI_EXTENSIONS: ['receipt-ocr', 'ai-categorization', 'ai-chat'],
|
||||
hasAiConsent: vi.fn(),
|
||||
grantAiConsent: vi.fn(),
|
||||
revokeAiConsent: vi.fn(),
|
||||
isAiExtension: vi.fn((id: string) =>
|
||||
['receipt-ocr', 'ai-categorization', 'ai-chat'].includes(id)
|
||||
),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { hasAiConsent, grantAiConsent, revokeAiConsent } from '@/lib/extensions/ai-consent'
|
||||
import { GET, POST, DELETE } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
const mockHasAiConsent = vi.mocked(hasAiConsent)
|
||||
const mockGrantAiConsent = vi.mocked(grantAiConsent)
|
||||
const mockRevokeAiConsent = vi.mocked(revokeAiConsent)
|
||||
|
||||
function mockAuth(userId: string | null) {
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({
|
||||
data: { user: userId ? { id: userId } : null },
|
||||
}),
|
||||
},
|
||||
} as any)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/ai-consent', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockAuth(null)
|
||||
const { status } = await parseJsonResponse(await GET())
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns consent status for all AI extensions', async () => {
|
||||
mockAuth('user-1')
|
||||
mockHasAiConsent
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true)
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: Record<string, boolean> }>(
|
||||
await GET()
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({
|
||||
'receipt-ocr': true,
|
||||
'ai-categorization': false,
|
||||
'ai-chat': true,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/ai-consent', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockAuth(null)
|
||||
const req = createMockRequest('/api/ai-consent', {
|
||||
method: 'POST',
|
||||
body: { extension_id: 'receipt-ocr' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('grants consent for valid AI extension', async () => {
|
||||
mockAuth('user-1')
|
||||
mockGrantAiConsent.mockResolvedValue(undefined)
|
||||
|
||||
const req = createMockRequest('/api/ai-consent', {
|
||||
method: 'POST',
|
||||
body: { extension_id: 'receipt-ocr' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { consented: boolean } }>(
|
||||
await POST(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.consented).toBe(true)
|
||||
expect(mockGrantAiConsent).toHaveBeenCalledWith(expect.anything(), 'user-1', 'receipt-ocr')
|
||||
})
|
||||
|
||||
it('returns 400 for non-AI extension', async () => {
|
||||
mockAuth('user-1')
|
||||
|
||||
const req = createMockRequest('/api/ai-consent', {
|
||||
method: 'POST',
|
||||
body: { extension_id: 'enable-banking' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/ai-consent', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockAuth(null)
|
||||
const req = createMockRequest('/api/ai-consent', {
|
||||
method: 'DELETE',
|
||||
body: { extension_id: 'ai-chat' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await DELETE(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('revokes consent for valid AI extension', async () => {
|
||||
mockAuth('user-1')
|
||||
mockRevokeAiConsent.mockResolvedValue(undefined)
|
||||
|
||||
const req = createMockRequest('/api/ai-consent', {
|
||||
method: 'DELETE',
|
||||
body: { extension_id: 'ai-chat' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { consented: boolean } }>(
|
||||
await DELETE(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.consented).toBe(false)
|
||||
expect(mockRevokeAiConsent).toHaveBeenCalledWith(expect.anything(), 'user-1', 'ai-chat')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
AI_EXTENSIONS,
|
||||
hasAiConsent,
|
||||
grantAiConsent,
|
||||
revokeAiConsent,
|
||||
isAiExtension,
|
||||
} from '@/lib/extensions/ai-consent'
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const statuses: Record<string, boolean> = {}
|
||||
for (const ext of AI_EXTENSIONS) {
|
||||
statuses[ext] = await hasAiConsent(supabase, user.id, ext)
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: statuses })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { extension_id } = body
|
||||
|
||||
if (!extension_id || !isAiExtension(extension_id)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid or non-AI extension_id' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
await grantAiConsent(supabase, user.id, extension_id)
|
||||
return NextResponse.json({ data: { consented: true } })
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { extension_id } = body
|
||||
|
||||
if (!extension_id || !isAiExtension(extension_id)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid or non-AI extension_id' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
await revokeAiConsent(supabase, user.id, extension_id)
|
||||
return NextResponse.json({ data: { consented: false } })
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } 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)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/audit-trail', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockAuth(null)
|
||||
const req = createMockRequest('/api/audit-trail')
|
||||
const { status, body } = await parseJsonResponse(await GET(req))
|
||||
expect(status).toBe(401)
|
||||
expect(body).toEqual({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
it('returns audit log with data and count', async () => {
|
||||
mockAuth('user-1')
|
||||
const entries = [
|
||||
{ id: '1', action: 'INSERT', table_name: 'journal_entries', created_at: '2024-01-01T00:00:00Z' },
|
||||
{ id: '2', action: 'COMMIT', table_name: 'journal_entries', created_at: '2024-01-02T00:00:00Z' },
|
||||
]
|
||||
mockGetAuditLog.mockResolvedValue({ data: entries as any, count: 2 })
|
||||
|
||||
const req = createMockRequest('/api/audit-trail')
|
||||
const { status, body } = await parseJsonResponse<{ data: any[]; count: number }>(await GET(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(2)
|
||||
expect(body.count).toBe(2)
|
||||
expect(mockGetAuditLog).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'user-1',
|
||||
expect.objectContaining({})
|
||||
)
|
||||
})
|
||||
|
||||
it('passes query param filters to getAuditLog', async () => {
|
||||
mockAuth('user-1')
|
||||
mockGetAuditLog.mockResolvedValue({ data: [], count: 0 })
|
||||
|
||||
const req = createMockRequest('/api/audit-trail', {
|
||||
searchParams: {
|
||||
action: 'INSERT',
|
||||
table_name: 'journal_entries',
|
||||
record_id: 'rec-1',
|
||||
from_date: '2024-01-01',
|
||||
to_date: '2024-12-31',
|
||||
page: '2',
|
||||
page_size: '25',
|
||||
},
|
||||
})
|
||||
|
||||
await GET(req)
|
||||
|
||||
expect(mockGetAuditLog).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'user-1',
|
||||
{
|
||||
action: 'INSERT',
|
||||
table_name: 'journal_entries',
|
||||
record_id: 'rec-1',
|
||||
from_date: '2024-01-01',
|
||||
to_date: '2024-12-31',
|
||||
page: 2,
|
||||
pageSize: 25,
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 500 on service error', async () => {
|
||||
mockAuth('user-1')
|
||||
mockGetAuditLog.mockRejectedValue(new Error('DB error'))
|
||||
|
||||
const req = createMockRequest('/api/audit-trail')
|
||||
const { status, body } = await parseJsonResponse(await GET(req))
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body).toEqual({ error: 'DB error' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getAuditLog } from '@/lib/core/audit/audit-service'
|
||||
import type { AuditAction } from '@/types'
|
||||
|
||||
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 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,
|
||||
page: searchParams.has('page') ? Number(searchParams.get('page')) : undefined,
|
||||
pageSize: searchParams.has('page_size') ? Number(searchParams.get('page_size')) : undefined,
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await getAuditLog(supabase, user.id, filters)
|
||||
return NextResponse.json({ data: result.data, count: result.count })
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to fetch audit log' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { ensureInitialized } from '@/lib/init'
|
||||
import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import { createExtensionContext } from '@/lib/extensions/context-factory'
|
||||
import { isExtensionEnabled } from '@/lib/extensions/toggle-check'
|
||||
import { hasAiConsent, isAiExtension } from '@/lib/extensions/ai-consent'
|
||||
import type { ApiRouteDefinition } from '@/lib/extensions/types'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -82,6 +83,17 @@ async function handleRequest(
|
||||
return NextResponse.json({ error: 'Extension is disabled' }, { status: 403 })
|
||||
}
|
||||
|
||||
// AI consent check
|
||||
if (isAiExtension(extensionId)) {
|
||||
const consented = await hasAiConsent(supabase, user.id, extensionId)
|
||||
if (!consented) {
|
||||
return NextResponse.json(
|
||||
{ error: 'AI consent required', code: 'AI_CONSENT_REQUIRED' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Find matching route (supports :param patterns)
|
||||
let matchedRoute: ApiRouteDefinition | null = null
|
||||
let extractedParams: Record<string, string> = {}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user