* feat: multi-tenant company refactor (GNU-19) Introduce companies table, company_members, and user_preferences to support multiple companies per user. All data scoping changes from user_id to company_id across the entire codebase. Key changes: - Database migration: new tables, company_id on 40+ tables, backfill, RLS rewrite from user_id to company-member-based, updated RPCs - Types: Company, CompanyMember, CompanyRole, UserPreferences types; company_id added to all entity interfaces; companyId on all events - Engine: all 7 core functions take companyId; storno, period, year-end services updated; 16 report generators updated - Middleware: company context resolution (cookie → prefs → first company) - API routes: ~120 routes updated with requireCompanyId() - Frontend: CompanyProvider context, layout/dashboard/onboarding updated - Extensions: context factory, 9 extensions, all lib files updated - Tests: 1880 tests passing, all helpers updated with company_id defaults Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add database migrations for multi-tenant company and team system (GNU-19) Adds company_invitations, company creation RPC, team_members, account deletion RPC, and teams table refactor migrations. Updates base multi-tenant migration with cascading FKs and onboarding_step column. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add team types and update core infrastructure for multi-tenancy (GNU-19) Adds TeamRole, MemberSource, and Team types. Refactors Supabase service client to be stateless, updates middleware for team-aware routing, extends CompanyContext with team/role fields, and updates extension service types to accept companyId. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: thread company_id through business logic functions (GNU-19) Replaces user_id scoping with company_id across all lib modules: bookkeeping, documents, transactions, invoices, reconciliation, tax, deadlines, and import. Updates corresponding tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: thread company_id through API routes and extensions (GNU-19) Updates all existing API routes to extract and pass companyId. Updates enable-banking and arcim-migration extensions for company-scoped transaction ingestion and sync. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add company and team management API routes (GNU-19) Adds CRUD endpoints for company members, company invitations, team members, and team invitations. Includes invite token utilities, email templates, and company switch server action. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add team/company UI components, pages, and dashboard updates (GNU-19) Adds CompanySwitcher, ConsultantEmptyState, Step0RoleChoice, company members and team management panels. Updates dashboard layout for team-aware routing, onboarding for multi-step role choice, and auth callback for team invite acceptance. Ignores supabase/.branches/. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add null guards for company in import page (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move appUrl declaration to outer scope in invite route (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add optional chaining for company.name in members section (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add optional chaining for second company.name in members section (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add null guards for company in extension components (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: pass companyId to executeSIEImport in arcim-migration extension (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: update tests to use companyId instead of userId and improve type handling --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
136 lines
4.4 KiB
TypeScript
136 lines
4.4 KiB
TypeScript
import { createClient } from '@/lib/supabase/server'
|
|
import { NextResponse } from 'next/server'
|
|
import { eventBus } from '@/lib/events'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { ingestTransactions, type RawTransaction } from '@/lib/transactions/ingest'
|
|
import { generateExternalId } from '@/lib/import/bank-file/parser'
|
|
import { requireCompanyId } from '@/lib/company/context'
|
|
import type { ParsedBankTransaction, BankFileFormatId } from '@/lib/import/bank-file/types'
|
|
import type { Transaction } from '@/types'
|
|
|
|
ensureInitialized()
|
|
|
|
interface ExecuteRequest {
|
|
transactions: ParsedBankTransaction[]
|
|
format: BankFileFormatId
|
|
filename: string
|
|
file_hash: string
|
|
skip_duplicates: boolean
|
|
auto_categorize: boolean
|
|
}
|
|
|
|
/**
|
|
* POST /api/import/bank-file/execute
|
|
*
|
|
* Executes the import of confirmed bank transactions.
|
|
* Records import in bank_file_imports, calls ingestTransactions(),
|
|
* emits transaction.synced event.
|
|
*/
|
|
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 companyId = await requireCompanyId(supabase, user.id)
|
|
|
|
const body: ExecuteRequest = await request.json()
|
|
const { transactions, format, filename, file_hash, skip_duplicates: _skip_duplicates = true, auto_categorize: _auto_categorize = true } = body
|
|
|
|
if (!transactions || transactions.length === 0) {
|
|
return NextResponse.json({ error: 'No transactions to import' }, { status: 400 })
|
|
}
|
|
|
|
try {
|
|
// Create import record
|
|
const { data: importRecord, error: importError } = await supabase
|
|
.from('bank_file_imports')
|
|
.upsert({
|
|
user_id: user.id,
|
|
company_id: companyId,
|
|
filename,
|
|
file_hash,
|
|
file_format: format,
|
|
transaction_count: transactions.length,
|
|
status: 'processing',
|
|
date_from: transactions.map(t => t.date).sort()[0] || null,
|
|
date_to: transactions.map(t => t.date).sort().reverse()[0] || null,
|
|
}, {
|
|
onConflict: 'user_id,file_hash',
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (importError) {
|
|
console.error('Failed to create import record:', importError)
|
|
return NextResponse.json({ error: 'Failed to create import record' }, { status: 500 })
|
|
}
|
|
|
|
// Convert parsed transactions to RawTransaction format
|
|
const rawTransactions: RawTransaction[] = transactions.map((tx, index) => ({
|
|
date: tx.date,
|
|
description: tx.description,
|
|
amount: tx.amount,
|
|
currency: tx.currency || 'SEK',
|
|
external_id: generateExternalId(tx, format, index),
|
|
reference: tx.reference || null,
|
|
import_source: format === 'camt053' ? 'camt053' : `csv_${format}`,
|
|
}))
|
|
|
|
// Run ingestion pipeline
|
|
const ingestResult = await ingestTransactions(supabase, companyId, user.id, rawTransactions)
|
|
|
|
// Update import record with results
|
|
await supabase
|
|
.from('bank_file_imports')
|
|
.update({
|
|
imported_count: ingestResult.imported,
|
|
duplicate_count: ingestResult.duplicates,
|
|
matched_count: ingestResult.auto_matched_invoices,
|
|
status: ingestResult.errors > 0 && ingestResult.imported === 0 ? 'failed' : 'completed',
|
|
error_message: ingestResult.errors > 0
|
|
? `${ingestResult.errors} transactions failed to import`
|
|
: null,
|
|
})
|
|
.eq('id', importRecord.id)
|
|
|
|
// Emit event with newly imported transactions
|
|
if (ingestResult.imported > 0 && ingestResult.transaction_ids.length > 0) {
|
|
try {
|
|
const { data: importedTransactions } = await supabase
|
|
.from('transactions')
|
|
.select('*')
|
|
.in('id', ingestResult.transaction_ids)
|
|
|
|
if (importedTransactions && importedTransactions.length > 0) {
|
|
await eventBus.emit({
|
|
type: 'transaction.synced',
|
|
payload: {
|
|
transactions: importedTransactions as Transaction[],
|
|
userId: user.id,
|
|
companyId,
|
|
},
|
|
})
|
|
}
|
|
} catch {
|
|
// Non-critical event emission
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
data: {
|
|
import_id: importRecord.id,
|
|
...ingestResult,
|
|
},
|
|
})
|
|
} catch (error) {
|
|
console.error('Bank file execute error:', error)
|
|
return NextResponse.json(
|
|
{ error: error instanceof Error ? error.message : 'Import failed' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|