feat: complete multi-tenant refactor + settings validation + fiscal period API (#156)
* feat: complete multi-tenant refactor for reconciliation, arcim, settings validation - Migrate bank-reconciliation to company_id (all functions + tests) - Migrate arcim-migration entity mappers and orchestrator to company_id - Fix enable-banking reconciliation calls to use companyId - Add Swedish law validation to settings schema: - VAT number required when VAT-registered (ML 11 kap. 8§) - Moms period required when VAT-registered (SFL 26 kap.) - Aktiebolag must use accrual accounting (BFNAR 2006:1) - Fix fiscal year period creation: always 12 months after first year (BFL 3 kap.) - Add plusgiro, website, pays_salaries fields to CompanySettings - Add plusgiro to invoice PDF template - Add fiscal period CRUD and opening balances API routes - Add frame-src CSP directive for future iframe embedding - Fix unlinked_1930_lines RPC to use company_id parameter - Update CLAUDE.md documentation Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address PR review findings (P1 + P2) - Fix reconciliation events emitting companyId as userId — thread actual userId through runReconciliation and manualLink - Move VAT cross-field validation (vat_number, moms_period) from schema refinements to route handler where effective stored state is available, preventing false rejection on partial updates - Add plusgiro format validation regex (N-N pattern) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
fad4899cb4
commit
e89f2c402d
@@ -0,0 +1,67 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getOpeningBalances } from '@/lib/reports/opening-balances'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
const { id } = await params
|
||||
|
||||
// Fetch the fiscal period
|
||||
const { data: period, error: periodError } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, opening_balance_entry_id')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (periodError || !period) {
|
||||
return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Get opening balances
|
||||
const { balances } = await getOpeningBalances(supabase, companyId, period)
|
||||
|
||||
// Fetch account names for the accounts that have balances
|
||||
const accountNumbers = Array.from(balances.keys())
|
||||
|
||||
if (accountNumbers.length === 0) {
|
||||
return NextResponse.json({ data: [] })
|
||||
}
|
||||
|
||||
const { data: accounts } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.select('account_number, account_name')
|
||||
.eq('company_id', companyId)
|
||||
.in('account_number', accountNumbers)
|
||||
|
||||
const accountNameMap = new Map(
|
||||
(accounts || []).map(a => [a.account_number, a.account_name])
|
||||
)
|
||||
|
||||
// Build response with account names and net balances
|
||||
const data = accountNumbers
|
||||
.sort()
|
||||
.map(accountNumber => {
|
||||
const bal = balances.get(accountNumber)!
|
||||
const net = Math.round((bal.debit - bal.credit) * 100) / 100
|
||||
return {
|
||||
account_number: accountNumber,
|
||||
account_name: accountNameMap.get(accountNumber) || accountNumber,
|
||||
balance: net,
|
||||
}
|
||||
})
|
||||
.filter(row => row.balance !== 0)
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { validatePeriodDuration } from '@/lib/bookkeeping/validate-period-duration'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { z } from 'zod'
|
||||
|
||||
const UpdateFiscalPeriodSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
period_start: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Startdatum måste vara i format ÅÅÅÅ-MM-DD').optional(),
|
||||
period_end: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Slutdatum måste vara i format ÅÅÅÅ-MM-DD').optional(),
|
||||
})
|
||||
|
||||
export async function PATCH(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await params
|
||||
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 validation = await validateBody(request, UpdateFiscalPeriodSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// Fetch the period
|
||||
const { data: period, error: fetchError } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('*')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (fetchError || !period) {
|
||||
return NextResponse.json({ error: 'Räkenskapsår hittades inte' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Cannot edit locked or closed periods
|
||||
if (period.locked_at) {
|
||||
return NextResponse.json({ error: 'Kan inte ändra ett låst räkenskapsår' }, { status: 400 })
|
||||
}
|
||||
if (period.is_closed) {
|
||||
return NextResponse.json({ error: 'Kan inte ändra ett stängt räkenskapsår' }, { status: 400 })
|
||||
}
|
||||
|
||||
// If dates are being changed, check for existing journal entries
|
||||
if (body.period_start || body.period_end) {
|
||||
const { count: entryCount } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.eq('fiscal_period_id', id)
|
||||
.in('status', ['posted', 'reversed'])
|
||||
|
||||
if (entryCount && entryCount > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: `Kan inte ändra datum: ${entryCount} bokförda verifikationer finns i perioden. Ta bort eller flytta dem först.` },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const newStart = body.period_start || period.period_start
|
||||
const newEnd = body.period_end || period.period_end
|
||||
|
||||
// Validate period duration (max 18 months per BFL 3 kap.)
|
||||
const durationError = validatePeriodDuration(newStart, newEnd)
|
||||
if (durationError) {
|
||||
return NextResponse.json({ error: durationError }, { status: 400 })
|
||||
}
|
||||
|
||||
// Check for overlapping periods (excluding this one)
|
||||
const { data: overlapping } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, name')
|
||||
.eq('company_id', companyId)
|
||||
.neq('id', id)
|
||||
.lte('period_start', newEnd)
|
||||
.gte('period_end', newStart)
|
||||
.limit(1)
|
||||
|
||||
if (overlapping && overlapping.length > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: `Överlappar med befintligt räkenskapsår: ${overlapping[0].name}` },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Build update object
|
||||
const updates: Record<string, unknown> = {}
|
||||
if (body.name) updates.name = body.name
|
||||
if (body.period_start) updates.period_start = body.period_start
|
||||
if (body.period_end) updates.period_end = body.period_end
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
return NextResponse.json({ data: period })
|
||||
}
|
||||
|
||||
const { data: updated, error: updateError } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.update(updates)
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (updateError) {
|
||||
// Database CHECK constraints will catch invalid month boundaries
|
||||
const msg = updateError.message
|
||||
if (msg.includes('period_start') || msg.includes('period_end')) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Perioden måste börja den 1:a i en månad och sluta sista dagen i en månad' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
return NextResponse.json({ error: msg }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: updated })
|
||||
}
|
||||
@@ -174,7 +174,7 @@ export async function GET(request: Request) {
|
||||
// Batch reconciliation sweep when SIE overlap detected
|
||||
if (sieOverlap && totalImported > 0) {
|
||||
try {
|
||||
await runReconciliation(supabase, connection.user_id, {
|
||||
await runReconciliation(supabase, connection.company_id, {
|
||||
dateFrom: fromDate,
|
||||
dateTo: toDate,
|
||||
})
|
||||
|
||||
@@ -43,7 +43,7 @@ export async function PUT(request: Request) {
|
||||
// Fetch current settings to check for tax-relevant changes
|
||||
const { data: oldSettings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('entity_type, moms_period, f_skatt, vat_registered, pays_salaries, fiscal_year_start_month, onboarding_complete')
|
||||
.select('entity_type, moms_period, f_skatt, vat_registered, vat_number, pays_salaries, fiscal_year_start_month, onboarding_complete')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
@@ -67,6 +67,33 @@ export async function PUT(request: Request) {
|
||||
)
|
||||
}
|
||||
|
||||
// Validate: aktiebolag must use accrual accounting (BFNAR 2006:1)
|
||||
if (effectiveEntityType === 'aktiebolag' && body.accounting_method === 'cash') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Aktiebolag måste använda faktureringsmetoden (BFNAR 2006:1)' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Validate: VAT-registered must have VAT number (ML 11 kap. 8§) and moms period (SFL 26 kap.)
|
||||
const effectiveVatRegistered = body.vat_registered ?? oldSettings?.vat_registered
|
||||
if (effectiveVatRegistered === true) {
|
||||
const effectiveVatNumber = body.vat_number ?? oldSettings?.vat_number
|
||||
if (!effectiveVatNumber) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Momsregistreringsnummer krävs när företaget är momsregistrerat (ML 11 kap. 8§)' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
const effectiveMomsPeriod = body.moms_period ?? oldSettings?.moms_period
|
||||
if (!effectiveMomsPeriod) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Momsperiod krävs när företaget är momsregistrerat (SFL 26 kap.)' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('company_settings')
|
||||
.update(body)
|
||||
|
||||
Reference in New Issue
Block a user