Files
accounted/app/api/company/[id]/delete/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

157 lines
5.1 KiB
TypeScript

import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { ensureInitialized } from '@/lib/init'
import { requireAuth } from '@/lib/auth/require-auth'
import { validateBody } from '@/lib/api/validate'
import { eventBus } from '@/lib/events'
import { createLogger } from '@/lib/logger'
const log = createLogger('api/company/delete')
ensureInitialized()
const DeleteCompanySchema = z.object({
confirm_name: z.string().min(1),
})
/**
* POST /api/company/[id]/delete
*
* Soft-delete a company. Sets archived_at + archived_by. The underlying
* bookkeeping data is retained for 7 years per BFL 7 kap. 2§. All reads
* flow through user_company_ids() which filters archived rows, so the
* company disappears from the user's UI immediately.
*
* Rules:
* - Only callers with role='owner' in company_members may delete.
* - The body must include confirm_name matching companies.name exactly.
* - Already-archived companies return 404 (treated as not found).
*/
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id: companyId } = await params
const auth = await requireAuth()
if (auth.error) return auth.error
const { user, supabase } = auth
const result = await validateBody(request, DeleteCompanySchema)
if (!result.success) return result.response
const { confirm_name } = result.data
// Service client for writes that must bypass RLS (audit_log insert,
// user_preferences clearing). All queries still filter by company_id
// and user.id for defense in depth.
const service = createServiceClient()
// 1. Fetch company — must exist and be active. Query via service client
// because we need the raw row regardless of RLS visibility, but we still
// enforce membership below.
const { data: company, error: fetchError } = await service
.from('companies')
.select('id, name, archived_at')
.eq('id', companyId)
.maybeSingle()
if (fetchError) {
log.error('Failed to fetch company', { companyId, error: fetchError.message })
return NextResponse.json({ error: 'Kunde inte hämta företag.' }, { status: 500 })
}
if (!company || company.archived_at) {
return NextResponse.json({ error: 'Företaget hittades inte.' }, { status: 404 })
}
// 2. Caller must be an owner of this company
const { data: membership, error: membershipError } = await service
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (membershipError) {
log.error('Failed to fetch membership', { companyId, error: membershipError.message })
return NextResponse.json({ error: 'Kunde inte verifiera behörighet.' }, { status: 500 })
}
if (!membership) {
return NextResponse.json({ error: 'Företaget hittades inte.' }, { status: 404 })
}
if (membership.role !== 'owner') {
return NextResponse.json(
{ error: 'Endast ägaren kan radera ett företag.' },
{ status: 403 }
)
}
// 3. Confirm name matches exactly (case-sensitive trim)
if (confirm_name.trim() !== company.name.trim()) {
return NextResponse.json(
{ error: 'Företagsnamnet stämmer inte överens.' },
{ status: 400 }
)
}
// 4. Soft delete
const archivedAt = new Date().toISOString()
const { error: updateError } = await service
.from('companies')
.update({ archived_at: archivedAt, archived_by: user.id })
.eq('id', companyId)
if (updateError) {
log.error('Failed to archive company', { companyId, error: updateError.message })
return NextResponse.json({ error: 'Kunde inte radera företaget.' }, { status: 500 })
}
// 5. Clear user_preferences.active_company_id if it pointed here so the
// middleware falls through to another membership next request.
await service
.from('user_preferences')
.update({ active_company_id: null })
.eq('user_id', user.id)
.eq('active_company_id', companyId)
// 6. Write audit log row. companies has no auto-audit trigger, so do it
// explicitly. Service client bypasses audit_log RLS (no INSERT policy).
await service.from('audit_log').insert({
user_id: user.id,
company_id: companyId,
action: 'DELETE',
table_name: 'companies',
record_id: companyId,
actor_id: user.id,
old_state: { archived_at: null },
new_state: { archived_at: archivedAt, archived_by: user.id },
description: `Company archived: ${company.name}`,
})
// 7. Emit event
await eventBus.emit({
type: 'company.deleted',
payload: { companyId, userId: user.id, archivedAt },
})
// 8. Build response and clear company cookie if it matched
const response = NextResponse.json({ data: { companyId, archivedAt } })
const cookieCompanyId = request.headers.get('cookie')?.match(/gnubok-company-id=([^;]+)/)?.[1]
if (cookieCompanyId === companyId) {
response.cookies.set('gnubok-company-id', '', {
path: '/',
maxAge: 0,
})
}
// Ignore supabase server-client cookie warnings; the response is what
// the browser sees. RLS session isn't relevant here.
void supabase
return response
}