refactor: consolidate extension system to general-only with manifest-driven architecture

- Remove all sector-specific extensions (construction, ecommerce, export,
  hotel, restaurant, tech) — only general-purpose extensions remain
- Move NE-bilaga and SRU export from extensions to core reports (lib/reports/)
- Move moms-box-mapping from extensions/export/shared to lib/vat/
- Replace per-extension API routes with catch-all dispatcher
  (app/api/extensions/ext/[...path]/route.ts)
- Add manifest.json for each extension with metadata, env vars, and deps
- Add api-routes.ts pattern for extension-defined API endpoints
- Add code generation scripts (generate-extension-registry, create-extension)
- Add extensions.config.json for opt-in extension loading
- Add extensions.schema.json for config validation
- Add email service interface with noop default (lib/email/service.ts)
- Add CI workflow (core-build.yml) to verify core builds with zero extensions
- Add migration 045: expand account_type CHECK for untaxed_reserves
- Update CLAUDE.md with comprehensive extension system documentation
- Update all report engines and bookkeeping services for new imports
- Clean up extensions.schema.json to only list existing extensions

Co-Authored-By: Claude Opus 4.6 <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-02-26 14:32:56 +01:00
co-authored by Claude Opus 4.6
parent 39e407644d
commit 03b569d708
289 changed files with 7325 additions and 27598 deletions
+30
View File
@@ -0,0 +1,30 @@
name: Core Build (no extensions)
on: [pull_request]
jobs:
core-only:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- name: Reset extensions config
run: echo '{"extensions":[]}' > extensions.config.json
- run: npm run setup:extensions
- run: npm run build
- run: npm test
- name: Check no core imports from extensions
run: |
VIOLATIONS=$(grep -r "from '@/extensions/" lib/ app/api/ components/ --include="*.ts" --include="*.tsx" \
| grep -v "app/api/extensions/" \
| grep -v "components/extensions/" \
| grep -v "lib/extensions/_generated/" \
| grep -v "lib/extensions/loader.ts" || true)
if [ -n "$VIOLATIONS" ]; then
echo "ERROR: Core code imports from @/extensions/:"
echo "$VIOLATIONS"
exit 1
fi
+5
View File
@@ -40,3 +40,8 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
# Extension registry (auto-generated but defaults are committed)
# Run `npm run setup:extensions` to regenerate after changing extensions.config.json
# The empty defaults in lib/extensions/_generated/ are committed so core compiles
# out of the box without running the generator.
+412 -95
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -25,6 +25,7 @@ import { getDefaultAccountForCategory, getDefaultVatTreatmentForCategory } from
import type { TransactionWithInvoice, ViewMode, CategorizeHandler } from '@/components/transactions/transaction-types'
import type { TransactionCategory, CreateTransactionInput, Invoice, Customer, VatTreatment, InvoiceInboxItem } from '@/types'
import type { SuggestedCategory, SuggestedTemplate } from '@/lib/transactions/category-suggestions'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
export default function TransactionsPage() {
const [transactions, setTransactions] = useState<TransactionWithInvoice[]>([])
@@ -625,7 +626,7 @@ export default function TransactionsPage() {
onMarkPrivate={handleMarkPrivate}
onOpenMatchDialog={openMatchDialog}
onOpenCategoryDialog={openCategoryDialog}
onOpenDescribe={openDescribeDialog}
onOpenDescribe={ENABLED_EXTENSION_IDS.has('ai-categorization') ? openDescribeDialog : undefined}
onOpenQuickReview={handleOpenQuickReview}
onToggleSelect={toggleBatchSelect}
/>
@@ -1,5 +1,8 @@
import { NextResponse } from 'next/server'
import { seedAllTemplateEmbeddings, getSchemaVersion } from '@/lib/bookkeeping/template-embeddings'
import { extensionRegistry } from '@/lib/extensions/registry'
import { ensureInitialized } from '@/lib/init'
ensureInitialized()
export async function POST(request: Request) {
const authHeader = request.headers.get('authorization')
@@ -9,14 +12,23 @@ export async function POST(request: Request) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const aiExt = extensionRegistry.get('ai-categorization')
if (!aiExt?.services?.seedAllTemplateEmbeddings || !aiExt?.services?.getSchemaVersion) {
return NextResponse.json(
{ error: 'ai-categorization extension not loaded' },
{ status: 503 }
)
}
try {
const { seeded, errors } = await seedAllTemplateEmbeddings()
const { seeded, errors } = await aiExt.services.seedAllTemplateEmbeddings()
const schemaVersion = await aiExt.services.getSchemaVersion()
return NextResponse.json({
success: errors.length === 0,
seeded,
errors,
schema_version: getSchemaVersion(),
schema_version: schemaVersion,
})
} catch (error) {
return NextResponse.json(
@@ -15,7 +15,7 @@ export async function POST(
}
try {
const period = await closePeriod(user.id, id)
const period = await closePeriod(supabase, user.id, id)
return NextResponse.json({ data: period })
} catch (err) {
return NextResponse.json(
@@ -15,7 +15,7 @@ export async function POST(
}
try {
const period = await lockPeriod(user.id, id)
const period = await lockPeriod(supabase, user.id, id)
return NextResponse.json({ data: period })
} catch (err) {
return NextResponse.json(
@@ -23,8 +23,8 @@ export async function GET(
try {
const [validation, preview] = await Promise.all([
validateYearEndReadiness(user.id, id),
previewYearEndClosing(user.id, id),
validateYearEndReadiness(supabase, user.id, id),
previewYearEndClosing(supabase, user.id, id),
])
return NextResponse.json({ data: { validation, preview } })
@@ -52,7 +52,7 @@ export async function POST(
}
try {
const result = await executeYearEndClosing(user.id, id)
const result = await executeYearEndClosing(supabase, user.id, id)
return NextResponse.json({ data: result })
} catch (err) {
return NextResponse.json(
@@ -100,7 +100,7 @@ describe('POST /api/bookkeeping/journal-entries/[id]/correct', () => {
expect(status).toBe(200)
expect(body.data.reversal).toEqual(reversal)
expect(body.data.corrected).toEqual(corrected)
expect(mockCorrectEntry).toHaveBeenCalledWith('user-1', 'entry-1', lines)
expect(mockCorrectEntry).toHaveBeenCalledWith(expect.anything(), 'user-1', 'entry-1', lines)
})
it('returns 400 when correctEntry throws for unbalanced lines', async () => {
@@ -24,7 +24,7 @@ export async function POST(
const body = validation.data
try {
const result = await correctEntry(user.id, id, body.lines)
const result = await correctEntry(supabase, user.id, id, body.lines)
return NextResponse.json({ data: result })
} catch (err) {
return NextResponse.json(
@@ -60,7 +60,7 @@ describe('POST /api/bookkeeping/journal-entries/[id]/reverse', () => {
expect(status).toBe(200)
expect(body.data).toEqual(reversalEntry)
expect(mockReverseEntry).toHaveBeenCalledWith('user-1', 'entry-1')
expect(mockReverseEntry).toHaveBeenCalledWith(expect.anything(), 'user-1', 'entry-1')
})
it('returns 400 when engine throws', async () => {
@@ -15,7 +15,7 @@ export async function POST(
}
try {
const reversalEntry = await reverseEntry(user.id, id)
const reversalEntry = await reverseEntry(supabase, user.id, id)
return NextResponse.json({ data: reversalEntry })
} catch (err) {
return NextResponse.json(
@@ -137,7 +137,7 @@ describe('POST /api/bookkeeping/journal-entries', () => {
expect(status).toBe(200)
expect(body.data).toEqual(entry)
expect(mockCreateJournalEntry).toHaveBeenCalledWith('user-1', input)
expect(mockCreateJournalEntry).toHaveBeenCalledWith(expect.anything(), 'user-1', input)
})
it('returns 400 when engine throws', async () => {
+1 -1
View File
@@ -69,7 +69,7 @@ export async function POST(request: Request) {
const body = validation.data
try {
const entry = await createJournalEntry(user.id, body)
const entry = await createJournalEntry(supabase, user.id, body)
return NextResponse.json({ data: entry })
} catch (err) {
return NextResponse.json(
@@ -38,7 +38,7 @@ export async function POST(request: Request) {
}
try {
const result = await evaluateMappingRules(user.id, transaction)
const result = await evaluateMappingRules(supabase, user.id, transaction)
return NextResponse.json({ data: result })
} catch (err) {
return NextResponse.json(
+1
View File
@@ -38,6 +38,7 @@ export async function POST(
}
const document = await linkToJournalEntry(
supabase,
user.id,
id,
body.journal_entry_id,
+1 -1
View File
@@ -24,7 +24,7 @@ export async function POST(
const { id } = await params
try {
const result = await verifyIntegrity(user.id, id)
const result = await verifyIntegrity(supabase, user.id, id)
return NextResponse.json({ data: result })
} catch (error) {
+1 -1
View File
@@ -36,7 +36,7 @@ export async function POST(
const buffer = await file.arrayBuffer()
const newVersion = await createNewVersion(user.id, id, {
const newVersion = await createNewVersion(supabase, user.id, id, {
name: file.name,
buffer,
type: file.type,
+1 -1
View File
@@ -38,7 +38,7 @@ export async function POST(request: Request) {
const buffer = await file.arrayBuffer()
const document = await uploadDocument(user.id, {
const document = await uploadDocument(supabase, user.id, {
name: file.name,
buffer,
type: file.type,
@@ -1,63 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { getSettings, saveSettings } from '@/extensions/general/ai-categorization'
import { ensureInitialized } from '@/lib/init'
ensureInitialized()
/**
* GET /api/extensions/ai-categorization/settings
* Get the current user's ai-categorization extension settings
*/
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 settings = await getSettings(user.id)
return NextResponse.json({ data: settings })
}
/**
* PATCH /api/extensions/ai-categorization/settings
* Update the current user's ai-categorization extension settings
*/
export async function PATCH(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()
// Validate setting keys
const allowedKeys = [
'autoSuggestEnabled',
'confidenceThreshold',
'providerModel',
]
const filtered: Record<string, unknown> = {}
for (const key of allowedKeys) {
if (key in body) {
filtered[key] = body[key]
}
}
if (Object.keys(filtered).length === 0) {
return NextResponse.json({ error: 'No valid settings provided' }, { status: 400 })
}
const settings = await saveSettings(user.id, filtered)
return NextResponse.json({ data: settings })
}
@@ -1,95 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { categorizeTransactions } from '@/extensions/general/ai-categorization'
import { ensureInitialized } from '@/lib/init'
import type { CategorizationSuggestion } from '@/extensions/general/ai-categorization/categorizer'
ensureInitialized()
/**
* GET /api/extensions/ai-categorization/suggestions?transaction_ids=id1,id2,...
* Fetch pre-computed AI suggestions for given transaction IDs
*/
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 idsParam = searchParams.get('transaction_ids')
if (!idsParam) {
return NextResponse.json({ error: 'transaction_ids is required' }, { status: 400 })
}
const transactionIds = idsParam.split(',').filter(Boolean).slice(0, 50)
// Read stored suggestions from extension_data
const keys = transactionIds.map((id) => `suggestion:${id}`)
const { data: records } = await supabase
.from('extension_data')
.select('key, value')
.eq('user_id', user.id)
.eq('extension_id', 'ai-categorization')
.in('key', keys)
const suggestions: Record<string, CategorizationSuggestion> = {}
if (records) {
for (const record of records) {
const txId = record.key.replace('suggestion:', '')
suggestions[txId] = record.value as unknown as CategorizationSuggestion
}
}
return NextResponse.json({ suggestions })
}
/**
* POST /api/extensions/ai-categorization/suggestions
* Trigger on-demand AI categorization for given transaction IDs
*/
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 { transaction_ids } = body
if (!Array.isArray(transaction_ids) || transaction_ids.length === 0) {
return NextResponse.json({ error: 'transaction_ids is required' }, { status: 400 })
}
const ids = transaction_ids.slice(0, 50)
try {
const suggestions = await categorizeTransactions(user.id, ids)
// Group by transaction ID
const grouped: Record<string, CategorizationSuggestion> = {}
for (const s of suggestions) {
grouped[s.transactionId] = s
}
return NextResponse.json({ suggestions: grouped })
} catch (error) {
console.error('[ai-categorization] On-demand categorization failed:', error)
return NextResponse.json(
{ error: 'AI categorization failed' },
{ status: 500 }
)
}
}
-169
View File
@@ -1,169 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateChatResponse } from '@/extensions/general/ai-chat/chatbot/chain'
import { CHATBOT_CONFIG } from '@/extensions/general/ai-chat/chatbot/config'
import type { ChatMessage, ChatRequest } from '@/types/chat'
// Simple in-memory rate limiting (per user)
const rateLimitMap = new Map<string, { count: number; resetTime: number }>()
function checkRateLimit(userId: string): boolean {
const now = Date.now()
const limit = rateLimitMap.get(userId)
if (!limit || now > limit.resetTime) {
rateLimitMap.set(userId, {
count: 1,
resetTime: now + 60000, // 1 minute window
})
return true
}
if (limit.count >= CHATBOT_CONFIG.rateLimitPerMinute) {
return false
}
limit.count++
return true
}
/**
* POST /api/chat
* Send a message and get a response
*/
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 })
}
// Rate limiting
if (!checkRateLimit(user.id)) {
return NextResponse.json(
{ error: 'Rate limit exceeded. Please wait a moment.' },
{ status: 429 }
)
}
try {
const body: ChatRequest = await request.json()
const { message, session_id } = body
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return NextResponse.json(
{ error: 'Message is required' },
{ status: 400 }
)
}
let sessionId = session_id
// Create new session if not provided
if (!sessionId) {
const { data: newSession, error: sessionError } = await supabase
.from('chat_sessions')
.insert({
user_id: user.id,
title: message.slice(0, 100), // Use first 100 chars of message as title
})
.select()
.single()
if (sessionError) {
console.error('Error creating session:', sessionError)
return NextResponse.json(
{ error: 'Failed to create chat session' },
{ status: 500 }
)
}
sessionId = newSession.id
} else {
// Verify session belongs to user
const { data: existingSession } = await supabase
.from('chat_sessions')
.select('id')
.eq('id', sessionId)
.eq('user_id', user.id)
.single()
if (!existingSession) {
return NextResponse.json(
{ error: 'Session not found' },
{ status: 404 }
)
}
}
// Save user message
const { data: userMessage, error: userMsgError } = await supabase
.from('chat_messages')
.insert({
session_id: sessionId,
user_id: user.id,
role: 'user',
content: message.trim(),
sources: [],
})
.select()
.single()
if (userMsgError) {
console.error('Error saving user message:', userMsgError)
return NextResponse.json(
{ error: 'Failed to save message' },
{ status: 500 }
)
}
// Get conversation history
const { data: history } = await supabase
.from('chat_messages')
.select('role, content')
.eq('session_id', sessionId)
.order('created_at', { ascending: true })
.limit(CHATBOT_CONFIG.maxHistoryMessages)
const conversationHistory = (history || []) as ChatMessage[]
// Generate AI response
const result = await generateChatResponse(message.trim(), conversationHistory)
// Save assistant message
const { data: assistantMessage, error: assistantMsgError } = await supabase
.from('chat_messages')
.insert({
session_id: sessionId,
user_id: user.id,
role: 'assistant',
content: result.content,
sources: result.sources,
})
.select()
.single()
if (assistantMsgError) {
console.error('Error saving assistant message:', assistantMsgError)
return NextResponse.json(
{ error: 'Failed to save response' },
{ status: 500 }
)
}
return NextResponse.json({
message: assistantMessage,
session_id: sessionId,
})
} catch (err) {
console.error('Chat error:', err)
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to process chat' },
{ status: 500 }
)
}
}
@@ -1,146 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
/**
* GET /api/chat/sessions/[id]
* Get a single chat session with its messages
*/
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { id } = await params
// Get session with messages
const { data: session, error: sessionError } = await supabase
.from('chat_sessions')
.select('*')
.eq('id', id)
.eq('user_id', user.id)
.single()
if (sessionError || !session) {
return NextResponse.json({ error: 'Session not found' }, { status: 404 })
}
// Get messages
const { data: messages, error: messagesError } = await supabase
.from('chat_messages')
.select('*')
.eq('session_id', id)
.order('created_at', { ascending: true })
if (messagesError) {
console.error('Error fetching messages:', messagesError)
return NextResponse.json(
{ error: 'Failed to fetch messages' },
{ status: 500 }
)
}
return NextResponse.json({
session,
messages: messages || [],
})
}
/**
* PATCH /api/chat/sessions/[id]
* Update a chat session (e.g., rename)
*/
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { id } = await params
try {
const body = await request.json()
const { title } = body
const { data, error } = await supabase
.from('chat_sessions')
.update({ title })
.eq('id', id)
.eq('user_id', user.id)
.select()
.single()
if (error) {
console.error('Error updating session:', error)
return NextResponse.json(
{ error: 'Failed to update session' },
{ status: 500 }
)
}
if (!data) {
return NextResponse.json({ error: 'Session not found' }, { status: 404 })
}
return NextResponse.json({ data })
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to update session' },
{ status: 400 }
)
}
}
/**
* DELETE /api/chat/sessions/[id]
* Delete a chat session and its messages
*/
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { id } = await params
// Delete session (messages will cascade delete due to FK)
const { error } = await supabase
.from('chat_sessions')
.delete()
.eq('id', id)
.eq('user_id', user.id)
if (error) {
console.error('Error deleting session:', error)
return NextResponse.json(
{ error: 'Failed to delete session' },
{ status: 500 }
)
}
return NextResponse.json({ success: true })
}
@@ -1,84 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
/**
* GET /api/chat/sessions
* List all chat sessions for the authenticated user
*/
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 limit = parseInt(searchParams.get('limit') || '20')
const offset = parseInt(searchParams.get('offset') || '0')
const { data, error, count } = await supabase
.from('chat_sessions')
.select('*', { count: 'exact' })
.eq('user_id', user.id)
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
if (error) {
console.error('Error fetching sessions:', error)
return NextResponse.json(
{ error: 'Failed to fetch sessions' },
{ status: 500 }
)
}
return NextResponse.json({ data, count })
}
/**
* POST /api/chat/sessions
* Create a new chat session
*/
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 })
}
try {
const body = await request.json()
const { title } = body
const { data, error } = await supabase
.from('chat_sessions')
.insert({
user_id: user.id,
title: title || null,
})
.select()
.single()
if (error) {
console.error('Error creating session:', error)
return NextResponse.json(
{ error: 'Failed to create session' },
{ status: 500 }
)
}
return NextResponse.json({ data })
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to create session' },
{ status: 400 }
)
}
}
-195
View File
@@ -1,195 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { streamChatResponse } from '@/extensions/general/ai-chat/chatbot/chain'
import { CHATBOT_CONFIG } from '@/extensions/general/ai-chat/chatbot/config'
import type { ChatMessage, ChatRequest, SourceReference } from '@/types/chat'
// Simple in-memory rate limiting (per user)
const rateLimitMap = new Map<string, { count: number; resetTime: number }>()
function checkRateLimit(userId: string): boolean {
const now = Date.now()
const limit = rateLimitMap.get(userId)
if (!limit || now > limit.resetTime) {
rateLimitMap.set(userId, {
count: 1,
resetTime: now + 60000,
})
return true
}
if (limit.count >= CHATBOT_CONFIG.rateLimitPerMinute) {
return false
}
limit.count++
return true
}
/**
* POST /api/chat/stream
* Streaming chat response via Server-Sent Events
*/
export async function POST(request: Request) {
const supabase = await createClient()
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
return new Response(
JSON.stringify({ error: 'Unauthorized' }),
{ status: 401, headers: { 'Content-Type': 'application/json' } }
)
}
if (!checkRateLimit(user.id)) {
return new Response(
JSON.stringify({ error: 'Rate limit exceeded' }),
{ status: 429, headers: { 'Content-Type': 'application/json' } }
)
}
try {
const body: ChatRequest = await request.json()
const { message, session_id } = body
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return new Response(
JSON.stringify({ error: 'Message is required' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
)
}
let sessionId = session_id
// Create new session if not provided
if (!sessionId) {
const { data: newSession, error: sessionError } = await supabase
.from('chat_sessions')
.insert({
user_id: user.id,
title: message.slice(0, 100),
})
.select()
.single()
if (sessionError) {
return new Response(
JSON.stringify({ error: 'Failed to create session' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
)
}
sessionId = newSession.id
} else {
// Verify session belongs to user
const { data: existingSession } = await supabase
.from('chat_sessions')
.select('id')
.eq('id', sessionId)
.eq('user_id', user.id)
.single()
if (!existingSession) {
return new Response(
JSON.stringify({ error: 'Session not found' }),
{ status: 404, headers: { 'Content-Type': 'application/json' } }
)
}
}
// Save user message
await supabase
.from('chat_messages')
.insert({
session_id: sessionId,
user_id: user.id,
role: 'user',
content: message.trim(),
sources: [],
})
// Get conversation history
const { data: history } = await supabase
.from('chat_messages')
.select('role, content')
.eq('session_id', sessionId)
.order('created_at', { ascending: true })
.limit(CHATBOT_CONFIG.maxHistoryMessages)
const conversationHistory = (history || []) as ChatMessage[]
// Create streaming response
const encoder = new TextEncoder()
let fullContent = ''
let sources: SourceReference[] = []
const stream = new ReadableStream({
async start(controller) {
try {
// Send session ID first
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ type: 'session', session_id: sessionId })}\n\n`)
)
// Stream the response
for await (const chunk of streamChatResponse(message.trim(), conversationHistory)) {
if (chunk.type === 'content') {
fullContent += chunk.data as string
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ type: 'content', content: chunk.data })}\n\n`)
)
} else if (chunk.type === 'sources') {
sources = chunk.data as SourceReference[]
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ type: 'sources', sources: chunk.data })}\n\n`)
)
}
}
// Save the complete assistant message
const { data: savedMessage } = await supabase
.from('chat_messages')
.insert({
session_id: sessionId,
user_id: user.id,
role: 'assistant',
content: fullContent,
sources,
})
.select()
.single()
// Send done signal with message ID
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ type: 'done', message_id: savedMessage?.id })}\n\n`)
)
controller.close()
} catch (error) {
console.error('Streaming error:', error)
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ type: 'error', error: 'Streaming failed' })}\n\n`)
)
controller.close()
}
},
})
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
},
})
} catch (err) {
console.error('Stream setup error:', err)
return new Response(
JSON.stringify({ error: 'Failed to setup stream' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
)
}
}
@@ -1,156 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
generateReceivablesReport,
type ReceivableInvoice,
type ReceivableCustomer,
type GLLine,
type ExchangeRateInfo,
} from '@/extensions/export/currency-receivables/lib/receivables-engine'
import { fetchMultipleRates } from '@/lib/currency/riksbanken'
import type { Currency } from '@/types'
const SUPPORTED_CURRENCIES: Currency[] = ['EUR', 'USD', 'GBP', 'NOK', 'DKK']
const FX_ACCOUNTS = ['3960', '7960']
/**
* GET /api/extensions/export/currency-receivables/report
*
* Generate a multi-currency receivables report showing FX exposure,
* unrealized gains/losses, and realized FX from GL.
*
* Query params:
* year (optional) — Year for realized FX trend (default: current year)
*/
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 yearStr = searchParams.get('year')
const year = yearStr ? parseInt(yearStr, 10) : new Date().getFullYear()
if (isNaN(year) || year < 2000 || year > 2100) {
return NextResponse.json({ error: 'Invalid year' }, { status: 400 })
}
const referenceDate = new Date().toISOString().split('T')[0]
try {
// Fetch open foreign-currency invoices
const invoices = await fetchAllRows<ReceivableInvoice>(({ from, to }) =>
supabase
.from('invoices')
.select('id, invoice_number, invoice_date, due_date, status, currency, total, total_sek, exchange_rate, customer_id')
.eq('user_id', user.id)
.in('status', ['sent', 'overdue'])
.neq('currency', 'SEK')
.range(from, to)
)
// Fetch customers
const customerIds = [...new Set(invoices.map(inv => inv.customer_id))]
let customers: ReceivableCustomer[] = []
if (customerIds.length > 0) {
const { data: customerData } = await supabase
.from('customers')
.select('id, name, country')
.eq('user_id', user.id)
.in('id', customerIds)
customers = (customerData || []) as ReceivableCustomer[]
}
// Fetch current Riksbanken rates for all supported currencies
const rateMap = await fetchMultipleRates(SUPPORTED_CURRENCIES)
const currentRates: ExchangeRateInfo[] = []
for (const [, rate] of rateMap) {
if (rate.currency !== 'SEK') {
currentRates.push({
currency: rate.currency,
rate: rate.rate,
date: rate.date,
})
}
}
// Fetch realized FX GL lines for the year
const realizedFXLines = await fetchFXLines(supabase, user.id, year)
const report = generateReceivablesReport({
invoices,
customers,
currentRates,
realizedFXLines,
referenceDate,
year,
})
return NextResponse.json({ data: report })
} catch (err) {
console.error('Error generating currency receivables report:', err)
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to generate report' },
{ status: 500 },
)
}
}
/**
* Fetch GL lines on accounts 3960 (FX gains) and 7960 (FX losses)
* for posted journal entries in the given year.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function fetchFXLines(supabase: any, userId: string, year: number): Promise<GLLine[]> {
const startDate = `${year}-01-01`
const endDate = `${year}-12-31`
// Get posted journal entry IDs in the year
const { data: entries, error: entriesError } = await supabase
.from('journal_entries')
.select('id, entry_date')
.eq('user_id', userId)
.eq('status', 'posted')
.gte('entry_date', startDate)
.lte('entry_date', endDate)
if (entriesError || !entries || entries.length === 0) return []
const entryDateMap = new Map<string, string>()
for (const e of entries as Array<{ id: string; entry_date: string }>) {
entryDateMap.set(e.id, e.entry_date)
}
const entryIds = entries.map((e: { id: string }) => e.id)
// Fetch lines in batches
const BATCH_SIZE = 200
const allLines: GLLine[] = []
for (let i = 0; i < entryIds.length; i += BATCH_SIZE) {
const batch = entryIds.slice(i, i + BATCH_SIZE)
const { data: lines } = await supabase
.from('journal_entry_lines')
.select('journal_entry_id, account_number, debit_amount, credit_amount')
.in('journal_entry_id', batch)
.in('account_number', FX_ACCOUNTS)
if (lines) {
for (const line of lines as Array<{ journal_entry_id: string; account_number: string; debit_amount: number; credit_amount: number }>) {
allLines.push({
account_number: line.account_number,
debit: Number(line.debit_amount) || 0,
credit: Number(line.credit_amount) || 0,
entry_date: entryDateMap.get(line.journal_entry_id) || startDate,
})
}
}
}
return allLines
}
@@ -1,166 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
generateECSalesListReport,
getMonthPeriod,
getQuarterPeriod,
type ECSalesListInvoice,
type ECSalesListCustomer,
type GLAccountTotal,
} from '@/extensions/export/eu-sales-list/lib/eu-sales-list-engine'
import { generateCSV, generateCSVFilename } from '@/extensions/export/eu-sales-list/lib/csv-generator'
import { generateSKVXml, generateXMLFilename } from '@/extensions/export/eu-sales-list/lib/skv-xml-generator'
/**
* GET /api/extensions/export/eu-sales-list/download
*
* Download an EC Sales List (periodisk sammanställning) as CSV or XML.
*
* Query params:
* year (required) — Fiscal year
* month (optional) — 1-12, for monthly filing
* quarter (optional) — 1-4, for quarterly filing
* format (required) — 'csv' or 'xml'
*/
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 })
}
// Parse query parameters
const { searchParams } = new URL(request.url)
const yearStr = searchParams.get('year')
const monthStr = searchParams.get('month')
const quarterStr = searchParams.get('quarter')
const format = searchParams.get('format')
if (!yearStr) {
return NextResponse.json({ error: 'year is required' }, { status: 400 })
}
if (!format || !['csv', 'xml'].includes(format)) {
return NextResponse.json({ error: 'format is required and must be csv or xml' }, { status: 400 })
}
const year = parseInt(yearStr, 10)
if (isNaN(year) || year < 2000 || year > 2100) {
return NextResponse.json({ error: 'Invalid year' }, { status: 400 })
}
if (!monthStr && !quarterStr) {
return NextResponse.json({ error: 'Either month or quarter is required' }, { status: 400 })
}
if (monthStr && quarterStr) {
return NextResponse.json({ error: 'Provide either month or quarter, not both' }, { status: 400 })
}
let month: number | undefined
let quarter: number | undefined
if (monthStr) {
month = parseInt(monthStr, 10)
if (isNaN(month) || month < 1 || month > 12) {
return NextResponse.json({ error: 'Invalid month' }, { status: 400 })
}
}
if (quarterStr) {
quarter = parseInt(quarterStr, 10)
if (isNaN(quarter) || quarter < 1 || quarter > 4) {
return NextResponse.json({ error: 'Invalid quarter' }, { status: 400 })
}
}
const period = month !== undefined
? getMonthPeriod(year, month)
: getQuarterPeriod(year, quarter!)
try {
// Fetch company settings
const { data: company, error: companyError } = await supabase
.from('company_settings')
.select('company_name, org_number, vat_number')
.eq('user_id', user.id)
.single()
if (companyError || !company) {
return NextResponse.json({ error: 'Company settings not found' }, { status: 404 })
}
const reporterVatNumber = company.vat_number || `SE${(company.org_number || '').replace(/\D/g, '')}01`
// Fetch invoices
const invoices = await fetchAllRows<ECSalesListInvoice>(({ from, to }) =>
supabase
.from('invoices')
.select('id, invoice_number, invoice_date, status, currency, total, total_sek, subtotal, subtotal_sek, vat_treatment, moms_ruta, document_type, credited_invoice_id, customer_id')
.eq('user_id', user.id)
.gte('invoice_date', period.start)
.lte('invoice_date', period.end)
.in('status', ['sent', 'paid', 'overdue'])
.eq('vat_treatment', 'reverse_charge')
.range(from, to)
)
// Fetch customers
const customerIds = [...new Set(invoices.map(inv => inv.customer_id))]
let customers: ECSalesListCustomer[] = []
if (customerIds.length > 0) {
const { data: customerData } = await supabase
.from('customers')
.select('id, name, country, customer_type, vat_number, vat_number_validated')
.eq('user_id', user.id)
.in('id', customerIds)
customers = (customerData || []) as ECSalesListCustomer[]
}
// Generate report
const report = generateECSalesListReport({
invoices,
customers,
reporterVatNumber,
reporterName: company.company_name || '',
year,
month,
quarter,
})
// Generate file content
if (format === 'csv') {
const content = generateCSV(report)
const filename = generateCSVFilename(report)
return new NextResponse(content, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
},
})
}
// XML format
const content = generateSKVXml(report)
const filename = generateXMLFilename(report)
return new NextResponse(content, {
status: 200,
headers: {
'Content-Type': 'application/xml; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
},
})
} catch (err) {
console.error('Error generating EC Sales List download:', err)
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to generate download' },
{ status: 500 },
)
}
}
@@ -1,212 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
generateECSalesListReport,
getMonthPeriod,
getQuarterPeriod,
getFilingDeadline,
daysUntilDeadline,
type ECSalesListInvoice,
type ECSalesListCustomer,
type GLAccountTotal,
} from '@/extensions/export/eu-sales-list/lib/eu-sales-list-engine'
/**
* GET /api/extensions/export/eu-sales-list/report
*
* Generate an EC Sales List (periodisk sammanställning) report.
*
* Query params:
* year (required) — Fiscal year, e.g. 2026
* month (optional) — 1-12, for monthly filing (goods)
* quarter (optional) — 1-4, for quarterly filing (services)
*
* Either month or quarter must be provided, not both.
*/
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 })
}
// Parse query parameters
const { searchParams } = new URL(request.url)
const yearStr = searchParams.get('year')
const monthStr = searchParams.get('month')
const quarterStr = searchParams.get('quarter')
if (!yearStr) {
return NextResponse.json({ error: 'year is required' }, { status: 400 })
}
const year = parseInt(yearStr, 10)
if (isNaN(year) || year < 2000 || year > 2100) {
return NextResponse.json({ error: 'Invalid year. Must be between 2000 and 2100' }, { status: 400 })
}
if (!monthStr && !quarterStr) {
return NextResponse.json({ error: 'Either month or quarter is required' }, { status: 400 })
}
if (monthStr && quarterStr) {
return NextResponse.json({ error: 'Provide either month or quarter, not both' }, { status: 400 })
}
let month: number | undefined
let quarter: number | undefined
if (monthStr) {
month = parseInt(monthStr, 10)
if (isNaN(month) || month < 1 || month > 12) {
return NextResponse.json({ error: 'Invalid month. Must be 1-12' }, { status: 400 })
}
}
if (quarterStr) {
quarter = parseInt(quarterStr, 10)
if (isNaN(quarter) || quarter < 1 || quarter > 4) {
return NextResponse.json({ error: 'Invalid quarter. Must be 1-4' }, { status: 400 })
}
}
// Determine date range
const period = month !== undefined
? getMonthPeriod(year, month)
: getQuarterPeriod(year, quarter!)
try {
// Fetch company settings for reporter info
const { data: company, error: companyError } = await supabase
.from('company_settings')
.select('company_name, org_number, vat_number')
.eq('user_id', user.id)
.single()
if (companyError || !company) {
return NextResponse.json({ error: 'Company settings not found' }, { status: 404 })
}
const reporterVatNumber = company.vat_number || `SE${(company.org_number || '').replace(/\D/g, '')}01`
// Fetch invoices for the period
const invoices = await fetchAllRows<ECSalesListInvoice>(({ from, to }) =>
supabase
.from('invoices')
.select('id, invoice_number, invoice_date, status, currency, total, total_sek, subtotal, subtotal_sek, vat_treatment, moms_ruta, document_type, credited_invoice_id, customer_id')
.eq('user_id', user.id)
.gte('invoice_date', period.start)
.lte('invoice_date', period.end)
.in('status', ['sent', 'paid', 'overdue'])
.eq('vat_treatment', 'reverse_charge')
.range(from, to)
)
// Collect unique customer IDs
const customerIds = [...new Set(invoices.map(inv => inv.customer_id))]
// Fetch customers (only if we have invoices)
let customers: ECSalesListCustomer[] = []
if (customerIds.length > 0) {
const { data: customerData, error: customerError } = await supabase
.from('customers')
.select('id, name, country, customer_type, vat_number, vat_number_validated')
.eq('user_id', user.id)
.in('id', customerIds)
if (customerError) {
return NextResponse.json({ error: 'Failed to fetch customers' }, { status: 500 })
}
customers = (customerData || []) as ECSalesListCustomer[]
}
// Fetch GL account totals for cross-check
// Query posted journal entries in the period, then sum credit amounts
// on the relevant revenue accounts (3108, 3308, 3109, 3521)
const glTotals = await fetchGLTotals(supabase, user.id, period.start, period.end)
// Generate report
const report = generateECSalesListReport({
invoices,
customers,
glTotals: glTotals.length > 0 ? glTotals : undefined,
reporterVatNumber,
reporterName: company.company_name || '',
year,
month,
quarter,
})
// Add deadline info
const deadline = getFilingDeadline(year, month, quarter)
const daysLeft = daysUntilDeadline(deadline)
return NextResponse.json({
data: {
...report,
deadline,
daysUntilDeadline: daysLeft,
},
})
} catch (err) {
console.error('Error generating EC Sales List report:', err)
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to generate report' },
{ status: 500 },
)
}
}
// ── GL cross-check helper ───────────────────────────────────
const CROSS_CHECK_ACCOUNTS = ['3108', '3109', '3308', '3521']
/**
* Fetch credit totals for cross-check accounts from posted journal entries.
* Mirrors the approach used by /api/bookkeeping/account-totals.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function fetchGLTotals(supabase: any, userId: string, startDate: string, endDate: string): Promise<GLAccountTotal[]> {
// Get posted journal entry IDs in the period
const { data: entries, error: entriesError } = await supabase
.from('journal_entries')
.select('id')
.eq('user_id', userId)
.eq('status', 'posted')
.gte('entry_date', startDate)
.lte('entry_date', endDate)
if (entriesError || !entries || entries.length === 0) return []
const entryIds = entries.map((e: { id: string }) => e.id)
// Fetch lines in batches (same pattern as account-totals route)
const BATCH_SIZE = 200
const allLines: Array<{ account_number: string; credit_amount: number }> = []
for (let i = 0; i < entryIds.length; i += BATCH_SIZE) {
const batch = entryIds.slice(i, i + BATCH_SIZE)
const { data: lines } = await supabase
.from('journal_entry_lines')
.select('account_number, credit_amount')
.in('journal_entry_id', batch)
.in('account_number', CROSS_CHECK_ACCOUNTS)
if (lines) allLines.push(...lines)
}
// Aggregate credits per account
const totals = new Map<string, number>()
for (const line of allLines) {
const credit = Number(line.credit_amount) || 0
totals.set(line.account_number, (totals.get(line.account_number) ?? 0) + credit)
}
return Array.from(totals.entries()).map(([account_number, credit]) => ({
account_number,
credit: Math.round(credit * 100) / 100,
}))
}
@@ -1,165 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
generateIntrastatReport,
type IntrastatInvoice,
type IntrastatCustomer,
type IntrastatInvoiceItem,
type ProductMetadata,
} from '@/extensions/export/intrastat/lib/intrastat-engine'
import { generateSCBCsv, generateSCBFilename } from '@/extensions/export/intrastat/lib/scb-csv-generator'
import { getMonthPeriod } from '@/extensions/export/eu-sales-list/lib/eu-sales-list-engine'
/**
* GET /api/extensions/export/intrastat/download
*
* Download an Intrastat declaration as SCB-compatible CSV.
*
* Query params:
* year (required) — Fiscal year
* month (required) — 1-12
*/
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 yearStr = searchParams.get('year')
const monthStr = searchParams.get('month')
if (!yearStr || !monthStr) {
return NextResponse.json({ error: 'year and month are required' }, { status: 400 })
}
const year = parseInt(yearStr, 10)
const month = parseInt(monthStr, 10)
if (isNaN(year) || year < 2000 || year > 2100) {
return NextResponse.json({ error: 'Invalid year' }, { status: 400 })
}
if (isNaN(month) || month < 1 || month > 12) {
return NextResponse.json({ error: 'Invalid month' }, { status: 400 })
}
const period = getMonthPeriod(year, month)
try {
const { data: company } = await supabase
.from('company_settings')
.select('company_name, org_number, vat_number')
.eq('user_id', user.id)
.single()
if (!company) {
return NextResponse.json({ error: 'Company settings not found' }, { status: 404 })
}
const reporterVatNumber = company.vat_number || `SE${(company.org_number || '').replace(/\D/g, '')}01`
// Fetch invoices
const invoices = await fetchAllRows<IntrastatInvoice>(({ from, to }) =>
supabase
.from('invoices')
.select('id, invoice_number, invoice_date, status, vat_treatment, moms_ruta, currency, total_sek, subtotal_sek, subtotal, document_type, credited_invoice_id, customer_id')
.eq('user_id', user.id)
.gte('invoice_date', period.start)
.lte('invoice_date', period.end)
.in('status', ['sent', 'paid', 'overdue'])
.eq('vat_treatment', 'reverse_charge')
.range(from, to)
)
// Fetch invoice items
const invoiceIds = invoices.map(inv => inv.id)
let invoiceItems: IntrastatInvoiceItem[] = []
if (invoiceIds.length > 0) {
const BATCH_SIZE = 200
for (let i = 0; i < invoiceIds.length; i += BATCH_SIZE) {
const batch = invoiceIds.slice(i, i + BATCH_SIZE)
const { data: items } = await supabase
.from('invoice_items')
.select('id, invoice_id, description, quantity, unit_price, total, total_sek')
.in('invoice_id', batch)
if (items) invoiceItems.push(...(items as IntrastatInvoiceItem[]))
}
}
// Fetch customers
const customerIds = [...new Set(invoices.map(inv => inv.customer_id))]
let customers: IntrastatCustomer[] = []
if (customerIds.length > 0) {
const { data: customerData } = await supabase
.from('customers')
.select('id, name, country, vat_number')
.eq('user_id', user.id)
.in('id', customerIds)
customers = (customerData || []) as IntrastatCustomer[]
}
// Fetch product metadata
const { data: productData } = await supabase
.from('extension_data')
.select('key, value')
.eq('user_id', user.id)
.eq('extension_id', 'export/intrastat')
.ilike('key', 'product:%')
const products: ProductMetadata[] = (productData || []).map((d: { key: string; value: Record<string, unknown> }) => ({
productId: d.key.replace('product:', ''),
cnCode: (d.value.cn_code as string) || null,
description: (d.value.description as string) || '',
netWeightKg: d.value.net_weight_kg !== undefined ? Number(d.value.net_weight_kg) : null,
countryOfOrigin: (d.value.country_of_origin as string) || 'SE',
supplementaryUnit: d.value.supplementary_unit !== undefined ? Number(d.value.supplementary_unit) : null,
supplementaryUnitType: (d.value.supplementary_unit_type as string) || null,
}))
// Fetch settings
const { data: settingsData } = await supabase
.from('extension_data')
.select('value')
.eq('user_id', user.id)
.eq('extension_id', 'export/intrastat')
.eq('key', 'settings')
.maybeSingle()
const settings = settingsData?.value as Record<string, unknown> | undefined
const report = generateIntrastatReport({
invoices,
invoiceItems,
customers,
products,
reporterVatNumber,
reporterName: company.company_name || '',
year,
month,
defaultTransactionNature: (settings?.default_transaction_nature as string) || '11',
defaultDeliveryTerms: (settings?.default_delivery_terms as string) || 'FCA',
})
const content = generateSCBCsv(report)
const filename = generateSCBFilename(report)
return new NextResponse(content, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
},
})
} catch (err) {
console.error('Error generating Intrastat download:', err)
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to generate download' },
{ status: 500 },
)
}
}
@@ -1,214 +0,0 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
generateIntrastatReport,
type IntrastatInvoice,
type IntrastatCustomer,
type IntrastatInvoiceItem,
type ProductMetadata,
} from '@/extensions/export/intrastat/lib/intrastat-engine'
import { getMonthPeriod } from '@/extensions/export/eu-sales-list/lib/eu-sales-list-engine'
/**
* GET /api/extensions/export/intrastat/report
*
* Generate an Intrastat declaration report for the specified month.
*
* Query params:
* year (required) — Fiscal year
* month (required) — 1-12 (Intrastat is always monthly)
*/
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 yearStr = searchParams.get('year')
const monthStr = searchParams.get('month')
if (!yearStr || !monthStr) {
return NextResponse.json({ error: 'year and month are required' }, { status: 400 })
}
const year = parseInt(yearStr, 10)
const month = parseInt(monthStr, 10)
if (isNaN(year) || year < 2000 || year > 2100) {
return NextResponse.json({ error: 'Invalid year' }, { status: 400 })
}
if (isNaN(month) || month < 1 || month > 12) {
return NextResponse.json({ error: 'Invalid month' }, { status: 400 })
}
const period = getMonthPeriod(year, month)
try {
// Fetch company settings
const { data: company } = await supabase
.from('company_settings')
.select('company_name, org_number, vat_number')
.eq('user_id', user.id)
.single()
if (!company) {
return NextResponse.json({ error: 'Company settings not found' }, { status: 404 })
}
const reporterVatNumber = company.vat_number || `SE${(company.org_number || '').replace(/\D/g, '')}01`
// Fetch reverse-charge invoices for the period
const invoices = await fetchAllRows<IntrastatInvoice>(({ from, to }) =>
supabase
.from('invoices')
.select('id, invoice_number, invoice_date, status, vat_treatment, moms_ruta, currency, total_sek, subtotal_sek, subtotal, document_type, credited_invoice_id, customer_id')
.eq('user_id', user.id)
.gte('invoice_date', period.start)
.lte('invoice_date', period.end)
.in('status', ['sent', 'paid', 'overdue'])
.eq('vat_treatment', 'reverse_charge')
.range(from, to)
)
// Fetch invoice items for those invoices
const invoiceIds = invoices.map(inv => inv.id)
let invoiceItems: IntrastatInvoiceItem[] = []
if (invoiceIds.length > 0) {
const BATCH_SIZE = 200
for (let i = 0; i < invoiceIds.length; i += BATCH_SIZE) {
const batch = invoiceIds.slice(i, i + BATCH_SIZE)
const { data: items } = await supabase
.from('invoice_items')
.select('id, invoice_id, description, quantity, unit_price, total, total_sek')
.in('invoice_id', batch)
if (items) invoiceItems.push(...(items as IntrastatInvoiceItem[]))
}
}
// Fetch customers
const customerIds = [...new Set(invoices.map(inv => inv.customer_id))]
let customers: IntrastatCustomer[] = []
if (customerIds.length > 0) {
const { data: customerData } = await supabase
.from('customers')
.select('id, name, country, vat_number')
.eq('user_id', user.id)
.in('id', customerIds)
customers = (customerData || []) as IntrastatCustomer[]
}
// Fetch product metadata from extension_data
const { data: productData } = await supabase
.from('extension_data')
.select('key, value')
.eq('user_id', user.id)
.eq('extension_id', 'export/intrastat')
.ilike('key', 'product:%')
const products: ProductMetadata[] = (productData || []).map((d: { key: string; value: Record<string, unknown> }) => ({
productId: d.key.replace('product:', ''),
cnCode: (d.value.cn_code as string) || null,
description: (d.value.description as string) || '',
netWeightKg: d.value.net_weight_kg !== undefined ? Number(d.value.net_weight_kg) : null,
countryOfOrigin: (d.value.country_of_origin as string) || 'SE',
supplementaryUnit: d.value.supplementary_unit !== undefined ? Number(d.value.supplementary_unit) : null,
supplementaryUnitType: (d.value.supplementary_unit_type as string) || null,
}))
// Fetch extension settings
const { data: settingsData } = await supabase
.from('extension_data')
.select('value')
.eq('user_id', user.id)
.eq('extension_id', 'export/intrastat')
.eq('key', 'settings')
.maybeSingle()
const settings = settingsData?.value as Record<string, unknown> | undefined
const defaultTransactionNature = (settings?.default_transaction_nature as string) || '11'
const defaultDeliveryTerms = (settings?.default_delivery_terms as string) || 'FCA'
// Calculate prior cumulative value (rolling 12 months excluding current)
const priorCumulativeValue = await calculatePriorCumulative(supabase, user.id, year, month)
const report = generateIntrastatReport({
invoices,
invoiceItems,
customers,
products,
reporterVatNumber,
reporterName: company.company_name || '',
year,
month,
defaultTransactionNature,
defaultDeliveryTerms,
priorCumulativeValue,
})
return NextResponse.json({ data: report })
} catch (err) {
console.error('Error generating Intrastat report:', err)
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to generate report' },
{ status: 500 },
)
}
}
/**
* Calculate the cumulative dispatch value for the 11 months prior to the
* current period (rolling 12-month window for threshold monitoring).
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function calculatePriorCumulative(supabase: any, userId: string, year: number, month: number): Promise<number> {
// Calculate 11-month lookback window
let startMonth = month - 11
let startYear = year
while (startMonth < 1) {
startMonth += 12
startYear--
}
const startDate = `${startYear}-${String(startMonth).padStart(2, '0')}-01`
// End date is the day before the current period
let prevMonth = month - 1
let prevYear = year
if (prevMonth < 1) {
prevMonth = 12
prevYear--
}
const lastDay = new Date(prevYear, prevMonth, 0).getDate()
const endDate = `${prevYear}-${String(prevMonth).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`
if (startDate > endDate) return 0
// Sum total_sek for reverse_charge invoices to EU in the lookback window
const { data, error } = await supabase
.from('invoices')
.select('total_sek, subtotal_sek, subtotal')
.eq('user_id', userId)
.gte('invoice_date', startDate)
.lte('invoice_date', endDate)
.in('status', ['sent', 'paid', 'overdue'])
.eq('vat_treatment', 'reverse_charge')
.eq('moms_ruta', '35')
if (error || !data) return 0
let total = 0
for (const inv of data) {
if (inv.subtotal_sek !== null) {
total += Number(inv.subtotal_sek) || 0
} else {
total += Number(inv.subtotal) || 0
}
}
return Math.round(total * 100) / 100
}

Some files were not shown because too many files have changed in this diff Show More