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

248 lines
7.9 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('accepts the settings display name when companies.name is stale', async () => {
// Regression: the UI shows company_settings.company_name (the dialog,
// label and the enable-gate all use it), but companies.name can be stale.
// The server must accept the displayed name, not just the raw column.
mockAuth('user-1')
mockService({
companies: [{ data: { id: 'c1', name: 'Gammalt namn', archived_at: null }, error: null }],
company_members: [{ data: { role: 'owner' }, error: null }],
company_settings: [{ data: { company_name: 'Nytt namn' }, error: null }],
})
const req = createMockRequest('/api/company/c1/delete', {
method: 'POST',
body: { confirm_name: 'Nytt namn' },
})
const { status } = await parseJsonResponse(
await POST(req, createMockRouteParams({ id: 'c1' }))
)
expect(status).toBe(200)
})
it('rejects the stale companies.name when a settings name exists (only the displayed name is accepted)', async () => {
// Security: the UI only ever shows company_settings.company_name when set, so
// the server must not accept the stale companies.name as an alternative
// confirmation — that would be a delete path the user was never shown.
mockAuth('user-1')
mockService({
companies: [{ data: { id: 'c1', name: 'Gammalt namn', archived_at: null }, error: null }],
company_members: [{ data: { role: 'owner' }, error: null }],
company_settings: [{ data: { company_name: 'Nytt namn' }, error: null }],
})
const req = createMockRequest('/api/company/c1/delete', {
method: 'POST',
body: { confirm_name: 'Gammalt namn' },
})
const { status } = await parseJsonResponse(
await POST(req, createMockRouteParams({ id: 'c1' }))
)
expect(status).toBe(400)
})
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' })
})
})