Files
accounted/app/api/settings/route.ts
T
Mattsson a1a816b4a5 Delete features (#218)
* Implement company and account deletion features

- Add event types for company and account deletion to CoreEvent.
- Enhance Supabase middleware to handle company context resolution and cookie management for archived companies.
- Create API routes for deleting accounts and companies, including necessary validations and event emissions.
- Implement tests for account and company deletion endpoints to ensure proper functionality and error handling.
- Add retention notice component to inform users about bookkeeping data retention during destructive actions.
- Create database migrations to support soft deletion of companies and anonymization of user accounts, ensuring compliance with retention laws.

* feat: enhance account deletion process and update user notifications

* Add service client for onboarding completion check and update escape hatch visibility

* Enhance invite flow and email handling for company members

* Refactor company context and RLS policies for active company isolation

- Update `switchCompany` to remove unnecessary revalidation as client handles navigation.
- Revise `getActiveCompanyId` to prioritize `user_preferences` and validate against non-archived memberships.
- Modify `setActiveCompany` to ensure `user_preferences` is the authoritative source while maintaining cookie compatibility.
- Enhance middleware to resolve active company using `user_preferences` and fallback to first non-archived membership.
- Introduce new API route `/api/company/current` to fetch the active company ID for cross-tab synchronization.
- Implement `CompanyTabSync` component for real-time active company enforcement across tabs.
- Create migration for RLS policies to enforce single-active-company isolation using `current_active_company_id()`.

* feat: implement viewer role enforcement for write permissions

- Added `useCanWrite` hook to determine if the current user has write permissions based on their role in the active company.
- Updated various components (JournalEntryForm, CustomerForm, DeadlineForm, etc.) to disable write actions and show a lock icon with a tooltip for users without write permissions.
- Introduced `requireWritePermission` function to enforce write permissions at the API level, returning a 403 response for viewers.
- Created tests to verify the behavior of the viewer role and write permissions.
- Added database migration to enforce read-only access for viewers at the database level.
2026-04-11 17:06:32 +02:00

145 lines
5.0 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: 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 })
}