e89f2c402d
* 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>
128 lines
4.4 KiB
TypeScript
128 lines
4.4 KiB
TypeScript
import { createClient } from '@/lib/supabase/server'
|
|
import { NextResponse } from 'next/server'
|
|
import { didTaxFieldsChange, regenerateTaxDeadlinesForUser } from '@/lib/tax/deadline-generator'
|
|
import { validateBody } from '@/lib/api/validate'
|
|
import { UpdateSettingsSchema } from '@/lib/api/schemas'
|
|
import { requireCompanyId } from '@/lib/company/context'
|
|
|
|
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 companyId = await requireCompanyId(supabase, user.id)
|
|
|
|
const { data, error } = await supabase
|
|
.from('company_settings')
|
|
.select('*')
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (error) {
|
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
|
}
|
|
|
|
return NextResponse.json({ data })
|
|
}
|
|
|
|
export async function PUT(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)
|
|
|
|
// 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, vat_number, pays_salaries, fiscal_year_start_month, onboarding_complete')
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
const validation = await validateBody(request, UpdateSettingsSchema)
|
|
if (!validation.success) return validation.response
|
|
const body = validation.data
|
|
|
|
// Lock company_name and org_number after onboarding is complete
|
|
if (oldSettings && (oldSettings as Record<string, unknown>).onboarding_complete === true) {
|
|
delete (body as Record<string, unknown>).company_name
|
|
delete (body as Record<string, unknown>).org_number
|
|
}
|
|
|
|
// Validate: enskild firma must use calendar year (BFL 3 kap.)
|
|
const effectiveEntityType = body.entity_type || oldSettings?.entity_type
|
|
const effectiveFYStartMonth = body.fiscal_year_start_month ?? oldSettings?.fiscal_year_start_month
|
|
if (effectiveEntityType === 'enskild_firma' && effectiveFYStartMonth && effectiveFYStartMonth !== 1) {
|
|
return NextResponse.json(
|
|
{ error: 'Enskild firma måste använda kalenderår (BFL 3 kap.)' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 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)
|
|
.eq('company_id', companyId)
|
|
.select()
|
|
.single()
|
|
|
|
if (error) {
|
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
|
}
|
|
|
|
// Check if tax-relevant fields changed and regenerate deadlines
|
|
if (oldSettings && didTaxFieldsChange(oldSettings, data)) {
|
|
try {
|
|
await regenerateTaxDeadlinesForUser(supabase, companyId, {
|
|
entity_type: data.entity_type,
|
|
moms_period: data.moms_period,
|
|
f_skatt: data.f_skatt,
|
|
vat_registered: data.vat_registered,
|
|
pays_salaries: data.pays_salaries ?? false,
|
|
fiscal_year_start_month: data.fiscal_year_start_month,
|
|
})
|
|
console.log('Tax deadlines regenerated after settings change')
|
|
} catch (err) {
|
|
console.error('Failed to regenerate tax deadlines:', err)
|
|
// Don't fail the settings update if deadline generation fails
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({ data })
|
|
}
|