Files
accounted/app/api/company/[id]/delete/route.ts
T
MattssonandClaude Opus 4.8 0ca9c25aba Add/user feedback (#679)
* feat(bookkeeping): make blocked fiscal-year creation actionable

When creating a new räkenskapsår is blocked because a prior period is
still open, the "Skapa räkenskapsår" dialog no longer dead-ends on an
English toast. The API now returns the canonical bilingual error envelope
with the blocking periods (id/name/dates) under details, and the dialog
renders a Swedish panel that locks them inline (reversible locked_at) via
the existing /lock endpoint and retries creation.

The guard rule is unchanged and remains BFL-compliant: BFL 6 kap allows
löpande bokföring of the new year in parallel with the prior year's
bokslut, so a lock (not a full close) is sufficient and reversible.

- Add PERIOD_CREATE_BLOCKED_BY_OPEN_PERIODS structured error code
- Return envelope + details.blockingPeriods from the 409 (was English string)
- CreatePeriodDialog: inline "lås och skapa" panel + lock-and-retry
- Update route tests for the new envelope shape

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(ui): prevent mouse wheel from mutating number inputs

A focused <input type="number"> would change its value on scroll,
silently turning e.g. a 20000 salary into 19998. Blur number inputs
on wheel so the page scrolls instead of editing the value. Applied
at the Input primitive so all number fields are protected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(salary): auto-derive skattetabell and kolumn for employees

Replace the opaque manual "Skattetabell (29-42)" and "Kolumn (1-6)" inputs
on the employee form with a self-deriving flow: the user picks their
folkbokföringskommun from a searchable dropdown and the tax table fills
itself in, while the column derives from the personnummer we already collect.

- Add a searchable municipality picker (MunicipalityCombobox) backed by a
  new cached GET /api/salary/tax-tables/kommuner endpoint.
- Wrap the whole "Skatt" card in a self-contained EmployeeTaxCard used by
  both the create and edit pages, with InfoTooltips and named column options.
- deriveTaxColumn(): auto-select column 1 for under-66 employees; leave the
  ambiguous 66+ case (pension vs working senior) to a clearly-named manual
  choice.
- Fix fetchKommunTaxRates() to page through all ~1300 församling rows instead
  of a single 500-row page (which silently dropped ~200 kommuner, incl.
  Göteborg) and normalize the uppercase names to title case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(import): correct CSV amount-column guess and surface skipped rows

Manual CSV column-mapping auto-guess walked each data row right-to-left
and picked the first numeric cell as the amount, so on the common
...;Belopp;Saldo layout it grabbed the trailing running-balance column.
Extract the guess into a pure, tested suggestColumnMapping(): match
header labels first (belopp/amount -> amount, saldo/balance -> balance),
auto-fill the balance field, and fall back to value heuristics that skip
the balance column and prefer a column carrying negative values.

Also surface stats.skipped_rows + parse warnings in BankFileConfirmStep -
the manual-mapping path skips the preview step that was the only place
they showed, so skipped rows were silently dropped from view.

Add a unit test reproducing the Saldo-as-amount regression.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: add "Save as draft" functionality for invoices

- Implemented a new feature to allow users to save invoices as unnumbered drafts without generating an invoice number until finalized.
- Added a `save_as_draft` flag to the CreateInvoiceInput schema to handle draft saving logic.
- Updated the invoice creation API to skip number allocation when saving as a draft.
- Introduced a new endpoint for finalizing drafts, which allocates an invoice number and emits an `invoice.created` event.
- Enhanced the UI to include a "Save as draft" button, with loading states and tooltips.
- Updated tests to cover the new draft saving and finalization logic, including race conditions for concurrent modifications.
- Added relevant error handling for draft finalization and deletion scenarios.

* feat(employee): add employment start and end date fields to employee forms

* feat: enhance invoice and salary run handling with improved validation and event logging

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 17:26:40 +02:00

175 lines
6.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 the company's display name.
* The UI shows company_settings.company_name (companies.name may be stale),
* so we validate against that, falling back to companies.name. Either value
* is accepted so the confirm gate never blocks a legitimate deletion.
* - 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 the exact name the UI displays. The dashboard layout
// resolves the displayed name as `company_settings.company_name || companies.name`
// (companies.name may be stale) and CompanyDangerZone gates on that value, so
// the server must accept ONLY that single name. Accepting the stale
// companies.name as an alternative would open a confirmation path the user was
// never shown — weakening the gate on an irreversible action (ASVS V8.2.1).
// Case-sensitive trim, mirror of the client-side check.
const { data: companySettings } = await service
.from('company_settings')
.select('company_name')
.eq('company_id', companyId)
.maybeSingle()
const displayName = (companySettings?.company_name || company.name).trim()
const typed = confirm_name.trim()
if (typed !== displayName) {
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
}