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

206 lines
6.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
import { eventBus } from '@/lib/events'
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: vi.fn(),
}))
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: vi.fn(),
}))
import { createServiceClient } from '@/lib/supabase/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { POST } from '../route'
const mockRequireAuth = vi.mocked(requireAuth)
const mockCreateServiceClient = vi.mocked(createServiceClient)
type Row = { data: unknown; error: unknown }
function mockService(rowsByTable: Record<string, Row[]>) {
const insertSpy = vi.fn().mockResolvedValue({ data: null, error: null })
const updateSpies: Record<string, ReturnType<typeof vi.fn>> = {}
const from = vi.fn().mockImplementation((table: string) => {
const queue = rowsByTable[table] ?? []
const next = queue.shift() ?? { data: null, error: null }
const updateFn = vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockResolvedValue({ data: null, error: null }),
then: (resolve: (v: unknown) => void) => resolve({ data: null, error: null }),
}),
})
updateSpies[table] = updateFn
return {
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
maybeSingle: vi.fn().mockResolvedValue(next),
}),
maybeSingle: vi.fn().mockResolvedValue(next),
}),
}),
update: updateFn,
insert: insertSpy,
}
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockCreateServiceClient.mockReturnValue({ from } as any)
return { from, insertSpy, updateSpies }
}
function mockAuth(userId: string | null) {
if (userId) {
mockRequireAuth.mockResolvedValue({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
user: { id: userId, email: 'u@example.com' } as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
supabase: {} as any,
error: null,
})
} else {
mockRequireAuth.mockResolvedValue({
user: null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
supabase: {} as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error: { status: 401 } as any,
})
}
}
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
describe('POST /api/company/[id]/delete', () => {
it('returns 401 when unauthenticated', async () => {
mockAuth(null)
const req = createMockRequest('/api/company/c1/delete', {
method: 'POST',
body: { confirm_name: 'Acme' },
})
const res = await POST(req, createMockRouteParams({ id: 'c1' }))
// requireAuth already returned a NextResponse error
expect(res).toBeDefined()
})
it('returns 400 when confirm_name does not match', async () => {
mockAuth('user-1')
mockService({
companies: [{ data: { id: 'c1', name: 'Acme AB', archived_at: null }, error: null }],
company_members: [{ data: { role: 'owner' }, error: null }],
})
const req = createMockRequest('/api/company/c1/delete', {
method: 'POST',
body: { confirm_name: 'Wrong Name' },
})
const { status, body } = await parseJsonResponse(
await POST(req, createMockRouteParams({ id: 'c1' }))
)
expect(status).toBe(400)
expect(body).toHaveProperty('error')
})
it('returns 403 when caller is member but not owner', async () => {
mockAuth('user-1')
mockService({
companies: [{ data: { id: 'c1', name: 'Acme AB', archived_at: null }, error: null }],
company_members: [{ data: { role: 'member' }, error: null }],
})
const req = createMockRequest('/api/company/c1/delete', {
method: 'POST',
body: { confirm_name: 'Acme AB' },
})
const { status } = await parseJsonResponse(
await POST(req, createMockRouteParams({ id: 'c1' }))
)
expect(status).toBe(403)
})
it('returns 404 when company is already archived', async () => {
mockAuth('user-1')
mockService({
companies: [
{
data: {
id: 'c1',
name: 'Acme AB',
archived_at: '2026-01-01T00:00:00Z',
},
error: null,
},
],
})
const req = createMockRequest('/api/company/c1/delete', {
method: 'POST',
body: { confirm_name: 'Acme AB' },
})
const { status } = await parseJsonResponse(
await POST(req, createMockRouteParams({ id: 'c1' }))
)
expect(status).toBe(404)
})
it('archives company, writes audit log, emits event on happy path', async () => {
mockAuth('user-1')
const { insertSpy, updateSpies } = mockService({
companies: [{ data: { id: 'c1', name: 'Acme AB', archived_at: null }, error: null }],
company_members: [{ data: { role: 'owner' }, error: null }],
})
const emitted: unknown[] = []
eventBus.on('company.deleted', (payload) => {
emitted.push(payload)
})
const req = createMockRequest('/api/company/c1/delete', {
method: 'POST',
body: { confirm_name: 'Acme AB' },
})
const { status, body } = await parseJsonResponse<{
data: { companyId: string; archivedAt: string }
}>(await POST(req, createMockRouteParams({ id: 'c1' })))
expect(status).toBe(200)
expect(body.data.companyId).toBe('c1')
expect(body.data.archivedAt).toBeTruthy()
// Verified the companies.update was called (archived_at + archived_by)
expect(updateSpies.companies).toHaveBeenCalledWith(
expect.objectContaining({
archived_at: expect.any(String),
archived_by: 'user-1',
})
)
// Audit log row written
expect(insertSpy).toHaveBeenCalledWith(
expect.objectContaining({
action: 'DELETE',
table_name: 'companies',
record_id: 'c1',
user_id: 'user-1',
})
)
// Event emitted
expect(emitted).toHaveLength(1)
expect(emitted[0]).toMatchObject({ companyId: 'c1', userId: 'user-1' })
})
})