fa7d4075cf
* feat(accounting): update accounting method validation and messaging for aktiebolag and enskild firma * Remove AI subsystem and related code - Deleted AI proposals and requests persistence logic from `lib/ai/proposals/persist.ts`. - Removed re-validation logic for proposals in `lib/ai/proposals/re-validate.ts`. - Cleaned up schemas related to AI flows in `lib/api/schemas.ts`. - Removed AI-related fields from bookkeeping engine in `lib/bookkeeping/engine.ts`. - Eliminated AI event types from `lib/events/types.ts`. - Updated tests to reflect the removal of AI-related functionality in `lib/extensions/__tests__/sectors.test.ts`. - Adjusted initialization logic in `lib/init.ts` to exclude AI proposal handler registration. - Cleaned up transaction ingestion logic in `lib/transactions/ingest.ts` to remove AI flow checks. - Updated helper functions in `tests/helpers.ts` to remove AI-related settings. - Removed AI-related types and interfaces from `types/index.ts`. - Added migration script to drop AI-related tables and settings from the database. * fix(migrations): ensure foreign key constraint is dropped before removing AI tables * feat(invoice-inbox): implement deterministic invoice field extraction and inbox provisioning - Added `extract-invoice-fields.ts` for extracting fields from PDF invoices using regex and pdfjs-dist, replacing the previous AI classifier. - Introduced `inbox-provisioning.ts` to manage company inbox addresses and rotation of inboxes using Supabase RPCs. - Created `resend-inbound.ts` for handling inbound email events and attachments via the Resend API. - Defined the extension manifest for the invoice inbox, specifying required environment variables and descriptions. - Migrated database schema to remove AI-related columns and tighten the status enum in `invoice_inbox_items`. * feat(invoice-inbox): remove AI-specific columns and tighten status enum * fix(skattekonto): remove manual entry creation reference from transaction input * fix(schemas): remove accounting method validation for aktiebolag in UpdateSettingsSchema
137 lines
4.7 KiB
TypeScript
137 lines
4.7 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'
|
|
import { requireWritePermission } from '@/lib/auth/require-write'
|
|
|
|
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 })
|
|
}
|
|
|
|
// Fall back to companies.entity_type if company_settings.entity_type is null
|
|
let responseData = data
|
|
if (data && !data.entity_type) {
|
|
const { data: company } = await supabase
|
|
.from('companies')
|
|
.select('entity_type')
|
|
.eq('id', companyId)
|
|
.single()
|
|
if (company?.entity_type) {
|
|
responseData = { ...data, entity_type: company.entity_type }
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({ data: responseData })
|
|
}
|
|
|
|
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 writeCheck = await requireWritePermission(supabase, user.id)
|
|
if (!writeCheck.ok) return writeCheck.response
|
|
|
|
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: 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 })
|
|
}
|