Files
accounted/app/api/company/[id]/delete/route.ts
T
MattssonandClaude Fable 5.1 6ea92f3152 feat(zettle): sync paid purchases into webshop_orders (#2445)
Community PR #2416 by @olofpinzke, adopted and finished by maintainers (rebased so every commit is signed).

Why the problem occurred: no Zettle integration; POS sales only reached the books as bank descriptors while Woo/Shopify already had order underlag via webshop_orders. The contributor's version also failed at the database (platform CHECKs listed only woocommerce/shopify), which the mocked unit tests never saw.
What was simplified: reused the Orders/book/invoice path instead of a new inbox; Finance API payouts/fees deferred. Sales the one-account, revenue-per-rate model cannot book (split tender, gift cards, tips) import unbookable with a "bokför manuellt" title instead of guessing accounts. Reset parity uses the rename-and-wrap pattern instead of re-issuing the reset body.
Why this solution: per-purchase rows give the radunderlag BFL verifikat need and the bulk-book path exists; daily kassarapport aggregation and Finance API fees/payouts are the follow-up (DECISIONS.md). Skeptic-refuted paths fixed before merge: concurrent refresh-token rotation (sync claim), cron offset paging (candidate snapshot), platform CHECKs, writer-role gate, migration-reset parity, white-label return origin re-validated at callback, VAT net from product rows.

Not live until ZETTLE_CLIENT_ID / ZETTLE_CLIENT_SECRET / ZETTLE_CREDENTIALS_ENCRYPTION_KEY are set on Vercel and a Zettle developer app is registered with the callback redirect URI.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WtYqzKPoTSRHskYYdf7MwB
2026-09-09 11:19:39 +02:00

286 lines
9.8 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
* exactly as the UI shows it: company_settings.company_name, falling back
* to companies.name only when no settings row exists. ONLY that single
* name is accepted (see step 3) — accepting alternates would weaken the
* confirmation gate on an irreversible action.
* - 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. Revoke the company's store connections. The store-uniqueness indexes
// (e.g. woocommerce_connections_store_active_uniq) allow a store to be
// actively connected to at most ONE company, and user_company_ids() hides
// archived companies, so an 'active' row left behind would block
// reconnecting the store from any new company with no user-reachable
// disconnect. Same status flip as the manual disconnect paths, secrets
// nulled. Non-fatal: the archive already happened, but never silent.
// .neq('revoked') rather than pending/active: 'error'-state rows also
// carry credentials and are just as unreachable after the archive. Each
// update carries its payload as an object literal so the phantom-column
// scanner can resolve every column.
const revokes = [
{
table: 'woocommerce_connections',
result: await service
.from('woocommerce_connections')
.update({
status: 'revoked',
disconnected_at: archivedAt,
consumer_key_encrypted: null,
consumer_secret_encrypted: null,
oauth_state: null,
})
.eq('company_id', companyId)
.neq('status', 'revoked')
.select('id'),
},
{
table: 'shopify_connections',
result: await service
.from('shopify_connections')
.update({
status: 'revoked',
disconnected_at: archivedAt,
client_id_encrypted: null,
client_secret_encrypted: null,
})
.eq('company_id', companyId)
.neq('status', 'revoked')
.select('id'),
},
{
table: 'zettle_connections',
result: await service
.from('zettle_connections')
.update({
status: 'revoked',
disconnected_at: archivedAt,
refresh_token_encrypted: null,
oauth_state: null,
})
.eq('company_id', companyId)
.neq('status', 'revoked')
.select('id'),
},
{
table: 'stripe_connections',
result: await service
.from('stripe_connections')
.update({
status: 'revoked',
disconnected_at: archivedAt,
oauth_state: null,
})
.eq('company_id', companyId)
.neq('status', 'revoked')
.select('id'),
},
]
for (const { table, result } of revokes) {
if (result.error) {
log.error('Failed to revoke store connections on company archive', {
companyId,
table,
error: result.error.message,
})
continue
}
// Credential revocation is a compliance-critical mutation: audit it like
// the archive itself (the tables have no auto-audit trigger). Non-fatal,
// same doctrine as the archive's own audit write below.
for (const row of (result.data ?? []) as Array<{ id: string }>) {
const { error: revokeAuditError } = await service.from('audit_log').insert({
user_id: user.id,
company_id: companyId,
action: 'UPDATE',
table_name: table,
record_id: row.id,
actor_id: user.id,
new_state: { status: 'revoked', disconnected_at: archivedAt },
description: `Store connection revoked on company archive: ${company.name}`,
})
if (revokeAuditError) {
log.error('Failed to write audit_log row for connection revocation', {
companyId,
table,
error: revokeAuditError.message,
})
}
}
}
// 7. Write audit log row. companies has no auto-audit trigger, so do it
// explicitly. Service client bypasses audit_log RLS (no INSERT policy).
// The archive already happened — don't fail the request, but an audit
// write failing on an irreversible action must never be silent.
const { error: auditError } = 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}`,
})
if (auditError) {
log.error('Failed to write audit_log row for company archive', {
companyId,
error: auditError.message,
})
}
// 8. Emit event
await eventBus.emit({
type: 'company.deleted',
payload: { companyId, userId: user.id, archivedAt },
})
// 9. 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
}