fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,155 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, 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(),
}))
import { createClient, createServiceClient } from '@/lib/supabase/server'
import { POST } from '../route'
const mockCreateClient = vi.mocked(createClient)
const mockCreateServiceClient = vi.mocked(createServiceClient)
function mockAuth(
user: { id: string; email: string | null } | null,
rpcResult: { data?: unknown; error?: unknown } = { data: null, error: null }
) {
const signOut = vi.fn().mockResolvedValue({ error: null })
const rpc = vi.fn().mockResolvedValue(rpcResult)
mockCreateClient.mockResolvedValue({
auth: {
getUser: vi.fn().mockResolvedValue({ data: { user } }),
signOut,
},
rpc,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
return { rpc, signOut }
}
function mockServiceClient(blockers: { id: string; name: string }[] = []) {
const updateUserById = vi.fn().mockResolvedValue({ data: {}, error: null })
const adminSignOut = vi.fn().mockResolvedValue({ data: null, error: null })
const chain = {
select: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
is: vi.fn().mockResolvedValue({
data: blockers.map((b) => ({ companies: { id: b.id, name: b.name } })),
error: null,
}),
}
mockCreateServiceClient.mockReturnValue({
from: vi.fn().mockReturnValue(chain),
auth: {
admin: {
updateUserById,
signOut: adminSignOut,
},
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
return { updateUserById, adminSignOut }
}
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
describe('POST /api/account/delete', () => {
it('returns 401 when unauthenticated', async () => {
mockAuth(null)
const req = createMockRequest('/api/account/delete', {
method: 'POST',
body: { confirm_email: 'u@example.com' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(401)
})
it('returns 400 when confirm_email does not match', async () => {
mockAuth({ id: 'user-1', email: 'right@example.com' })
const req = createMockRequest('/api/account/delete', {
method: 'POST',
body: { confirm_email: 'wrong@example.com' },
})
const { status, body } = await parseJsonResponse(await POST(req))
expect(status).toBe(400)
expect(body).toHaveProperty('error')
})
it('returns 409 with blockers when RPC raises P0001', async () => {
mockAuth(
{ id: 'user-1', email: 'u@example.com' },
{ data: null, error: { code: 'P0001', message: 'blocked' } }
)
mockServiceClient([{ id: 'c1', name: 'Acme AB' }])
const req = createMockRequest('/api/account/delete', {
method: 'POST',
body: { confirm_email: 'u@example.com' },
})
const { status, body } = await parseJsonResponse<{
error: string
blockers: { id: string; name: string }[]
}>(await POST(req))
expect(status).toBe(409)
expect(body.blockers).toEqual([{ id: 'c1', name: 'Acme AB' }])
})
it('anonymizes, bans, signs out, and emits event on happy path', async () => {
const { rpc } = mockAuth({ id: 'user-1', email: 'u@example.com' })
const { updateUserById, adminSignOut } = mockServiceClient()
const emitted: unknown[] = []
eventBus.on('account.deleted', (payload) => {
emitted.push(payload)
})
const req = createMockRequest('/api/account/delete', {
method: 'POST',
body: { confirm_email: 'u@example.com' },
})
const { status, body } = await parseJsonResponse<{ success: boolean }>(
await POST(req)
)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(rpc).toHaveBeenCalledWith('anonymize_user_account', {
target_user_id: 'user-1',
})
expect(updateUserById).toHaveBeenCalledWith(
'user-1',
expect.objectContaining({ ban_duration: expect.any(String) })
)
const updatePayload = updateUserById.mock.calls[0][1]
// Email must NOT be scrubbed: retaining it is what blocks re-signup
// with the same address. Recovery goes through support instead.
expect(updatePayload).not.toHaveProperty('email')
// Metadata is NOT wiped here: GoTrue merges metadata maps, so passing {}
// was a no-op. The anonymize_user_account RPC scrubs auth.users directly
// (migration 20260724150000).
expect(updatePayload).not.toHaveProperty('user_metadata')
expect(updatePayload).not.toHaveProperty('app_metadata')
expect(adminSignOut).toHaveBeenCalledWith('user-1', 'global')
expect(emitted).toHaveLength(1)
expect(emitted[0]).toMatchObject({ userId: 'user-1' })
})
})
+138
View File
@@ -0,0 +1,138 @@
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/account/delete')
ensureInitialized()
const DeleteAccountSchema = z.object({
confirm_email: z.string().email(),
})
/**
* POST /api/account/delete
*
* Anonymizes the calling user's account. The auth.users row is retained
* (banned for ~100 years) as a tombstone so FKs into BFL-retained
* bookkeeping data (companies.created_by, audit_log.user_id, etc.) stay
* valid. Memberships are removed, profile PII is stripped, and a global
* signout forces all sessions to end.
*
* Precondition: the user must own zero non-archived companies. The RPC
* enforces this at the DB level and raises SQLSTATE P0001 with a message
* if the precondition fails: we return 409 in that case.
*
* Not wrapped in withRouteContext: deletion must work for users with zero
* companies, so there is no company context to resolve. requireAuth() is
* used directly so MFA (AAL2) is still enforced on hosted: a stolen AAL1
* cookie must not be able to destroy the account. BankID-linked users are
* exempt from the AAL2 gate (BankID is inherently 2FA, see shouldEnforceMfa).
*/
export async function POST(request: Request) {
const auth = await requireAuth()
if (auth.error) return auth.error
const { user, supabase } = auth
const result = await validateBody(request, DeleteAccountSchema)
if (!result.success) return result.response
const { confirm_email } = result.data
if (!user.email || confirm_email.trim().toLowerCase() !== user.email.toLowerCase()) {
return NextResponse.json(
{ error: 'E-postadressen stämmer inte överens med ditt konto.' },
{ status: 400 }
)
}
// Anonymize in the DB. Runs as SECURITY DEFINER and checks auth.uid()
// internally, so we don't need service role here.
const { error: rpcError } = await supabase.rpc('anonymize_user_account', {
target_user_id: user.id,
})
if (rpcError) {
// P0001 = precondition violation from our RPC: user still owns active
// companies. Re-fetch the blockers and return 409 so the UI can show
// the list inline.
if (rpcError.code === 'P0001') {
const service = createServiceClient()
const { data: blockers } = await service
.from('company_members')
.select('company_id, companies!inner(id, name, archived_at)')
.eq('user_id', user.id)
.eq('role', 'owner')
.is('companies.archived_at', null)
const list = (blockers ?? []).map((b) => {
const company = (b.companies as unknown) as { id: string; name: string }
return { id: company.id, name: company.name }
})
return NextResponse.json(
{
error: 'Du måste radera eller överlåta dina företag innan du kan radera kontot.',
blockers: list,
},
{ status: 409 }
)
}
log.error('anonymize_user_account failed', { userId: user.id, error: rpcError.message })
return NextResponse.json(
{ error: 'Kunde inte radera kontot. Försök igen.' },
{ status: 500 }
)
}
// Ban the tombstone row ~100 years so login is impossible. The DB function
// can't set the ban (GoTrue-managed), so we do it here.
//
// Note: auth.users.email is intentionally NOT scrubbed. The original
// address is retained as a legitimate-interest tombstone so that:
// (1) re-signup with the same email is blocked by Supabase's unique
// constraint: deletion must feel permanent, not trivially
// reversible by re-registering
// (2) support can verify identity when a former user asks to recover
// BFL-retained räkenskapsinformation
// This must be documented in the privacy policy under legitimate
// interest (GDPR Art. 6(1)(f)). The email is never read by the app
// after this point: login is impossible (row is banned) and the
// profile is anonymized, so no UI ever surfaces it.
//
// user_metadata / app_metadata PII is scrubbed by the RPC itself, NOT
// here: GoTrue's admin update MERGES metadata maps, so the previous
// updateUserById(..., { user_metadata: {}, app_metadata: {} }) call was
// a silent no-op that left the full name on the tombstone (found on
// prod 2026-07-24, repaired by migration 20260724150000).
const service = createServiceClient()
try {
await service.auth.admin.updateUserById(user.id, {
ban_duration: '876000h',
})
} catch (err) {
log.error('Failed to ban anonymized user', { userId: user.id, err })
}
try {
await service.auth.admin.signOut(user.id, 'global')
} catch (err) {
log.error('Failed to global sign out anonymized user', { userId: user.id, err })
}
const deletedAt = new Date().toISOString()
await eventBus.emit({
type: 'account.deleted',
payload: { userId: user.id, deletedAt },
})
// Best-effort: clear the caller's session cookie too.
await supabase.auth.signOut().catch(() => {})
return NextResponse.json({ success: true })
}
@@ -0,0 +1,425 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandResultByHost: vi.fn(async () => ({ brand: null, lookupFailed: false })),
}))
import { POST } from '../route'
function mockUserClient(opts: {
user: { id: string; email?: string } | null
updateUserError?: { message: string; status?: number; code?: string } | null
// What GoTrue returns for the fresh user (the pending-change fields the
// claims fast path lacks). Defaults to "no pending change".
freshUser?: {
new_email?: string
email_change_sent_at?: string
} | null
// Outcome of claim_email_change_request: true (won, default), false
// (another request holds the claim), or an error object (RPC failed).
claim?: boolean | { message: string; code?: string }
}) {
const updateUser = vi.fn().mockResolvedValue({
data: {},
error: opts.updateUserError ?? null,
})
const rpc = vi.fn().mockImplementation(async (name: string) => {
if (name === 'claim_email_change_request') {
const claim = opts.claim ?? true
return typeof claim === 'boolean'
? { data: claim, error: null }
: { data: null, error: claim }
}
return { data: null, error: null }
})
const getUser = vi.fn().mockResolvedValue({
data: {
user:
opts.freshUser === null
? null
: { id: opts.user?.id, email: opts.user?.email, ...(opts.freshUser ?? {}) },
},
error: null,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const supabase = { auth: { updateUser, getUser }, rpc } as any
if (opts.user) {
requireAuthMock.mockResolvedValue({ user: opts.user, supabase, error: null })
} else {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
return { updateUser, getUser, rpc }
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('POST /api/account/email', () => {
it('returns 401 when unauthenticated', async () => {
mockUserClient({ user: null })
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'new@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(401)
})
it('returns 400 for an invalid email', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'not-an-email' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(400)
expect(updateUser).not.toHaveBeenCalled()
})
it('returns 400 when the new email equals the current one (case-insensitive)', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'Old@Testbrand.example' },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'old@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(body.error).toBe('Det är redan din e-postadress.')
expect(updateUser).not.toHaveBeenCalled()
})
it('requests the change via the user session with a callback redirect', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'New@Testbrand.example' },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean; pending_email: string }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.ok).toBe(true)
// Normalized to lowercase before it reaches Supabase.
expect(body.data?.pending_email).toBe('new@testbrand.example')
expect(updateUser).toHaveBeenCalledTimes(1)
const [attrs, options] = updateUser.mock.calls[0]
expect(attrs).toEqual({ email: 'new@testbrand.example' })
// flow=email_change routes the stock GoTrue redirect (message/error/code)
// to the email-change status page in /auth/callback.
expect(String(options.emailRedirectTo)).toMatch(
/\/auth\/callback\?flow=email_change$/,
)
})
it('short-circuits a repeat request while the pending mails are fresh', async () => {
const { updateUser } = mockUserClient({
user: {
id: 'user-1',
email: 'old@testbrand.example',
new_email: 'pending@testbrand.example',
email_change_sent_at: new Date(Date.now() - 60_000).toISOString(),
} as { id: string; email?: string },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'Pending@Testbrand.example' },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean; pending_email: string }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.pending_email).toBe('pending@testbrand.example')
expect(updateUser).not.toHaveBeenCalled()
})
it('re-sends when the pending change is stale (expired-link recovery)', async () => {
const { updateUser } = mockUserClient({
user: {
id: 'user-1',
email: 'old@testbrand.example',
new_email: 'pending@testbrand.example',
email_change_sent_at: new Date(
Date.now() - 2 * 60 * 60 * 1000,
).toISOString(),
} as { id: string; email?: string },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'pending@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(200)
expect(updateUser).toHaveBeenCalledTimes(1)
})
it('re-sends when the pending change has no sent timestamp', async () => {
const { updateUser } = mockUserClient({
user: {
id: 'user-1',
email: 'old@testbrand.example',
new_email: 'pending@testbrand.example',
} as { id: string; email?: string },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'pending@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(200)
expect(updateUser).toHaveBeenCalledTimes(1)
})
it('reads pending state from GoTrue when the session claims lack it (fresh: no-op)', async () => {
// The claims fast path carries no new_email; before this the route
// re-issued tokens on every re-submit and voided the mails just sent.
const { updateUser, getUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
freshUser: {
new_email: 'pending@testbrand.example',
email_change_sent_at: new Date(Date.now() - 3 * 60_000).toISOString(),
},
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'pending@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean; pending_email: string; resent: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.resent).toBe(false)
expect(getUser).toHaveBeenCalledTimes(1)
expect(updateUser).not.toHaveBeenCalled()
})
it('reads pending state from GoTrue when the session claims lack it (stale: re-send)', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
freshUser: {
new_email: 'pending@testbrand.example',
email_change_sent_at: new Date(
Date.now() - 2 * 60 * 60 * 1000,
).toISOString(),
},
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'pending@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{
data?: { resent: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.resent).toBe(true)
expect(updateUser).toHaveBeenCalledTimes(1)
})
it('requests a different address even while another change is pending and fresh', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
freshUser: {
new_email: 'pending@testbrand.example',
email_change_sent_at: new Date(Date.now() - 60_000).toISOString(),
},
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'other@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(200)
expect(updateUser).toHaveBeenCalledTimes(1)
expect(updateUser.mock.calls[0][0]).toEqual({ email: 'other@testbrand.example' })
})
it('does not consult GoTrue when the claims already carry the pending change', async () => {
const { updateUser, getUser } = mockUserClient({
user: {
id: 'user-1',
email: 'old@testbrand.example',
new_email: 'pending@testbrand.example',
email_change_sent_at: new Date(Date.now() - 60_000).toISOString(),
} as { id: string; email?: string },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'pending@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(200)
expect(getUser).not.toHaveBeenCalled()
expect(updateUser).not.toHaveBeenCalled()
})
it('claims the address atomically before calling GoTrue', async () => {
const { updateUser, rpc } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'new@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(200)
expect(rpc).toHaveBeenCalledWith('claim_email_change_request', {
p_email: 'new@testbrand.example',
p_window_seconds: 30 * 60,
})
// Claim strictly before the GoTrue call.
expect(rpc.mock.invocationCallOrder[0]).toBeLessThan(
updateUser.mock.invocationCallOrder[0],
)
expect(rpc).not.toHaveBeenCalledWith('release_email_change_request')
})
it('answers already-pending without calling GoTrue when a concurrent request holds the claim', async () => {
// Both requests read "nothing pending" from GoTrue; only the claim
// winner may re-issue the tokens.
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
claim: false,
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'new@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean; pending_email: string; resent: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data).toEqual({
ok: true,
pending_email: 'new@testbrand.example',
resent: false,
})
expect(updateUser).not.toHaveBeenCalled()
})
it('proceeds without the claim when the RPC itself fails', async () => {
const { updateUser, rpc } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
claim: { message: 'function does not exist', code: '42883' },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'new@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(200)
expect(updateUser).toHaveBeenCalledTimes(1)
expect(rpc).not.toHaveBeenCalledWith('release_email_change_request')
})
it('releases the claim when GoTrue refuses the change', async () => {
const { rpc } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
updateUserError: {
message: 'AAL2 session is required',
status: 403,
code: 'insufficient_aal',
},
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'new@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(400)
expect(rpc).toHaveBeenCalledWith('release_email_change_request')
})
it('returns 409 when the address already belongs to another account', async () => {
mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
updateUserError: {
message: 'A user with this email address has already been registered',
status: 422,
code: 'email_exists',
},
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'taken@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(409)
expect(body.error).toBe('E-postadressen används redan av ett annat konto.')
})
it('returns 400 and surfaces the AAL2 error when Supabase rejects the update', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
updateUserError: {
message:
'AAL2 session is required to update email or password when MFA is enabled',
status: 422,
},
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'new@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(updateUser).toHaveBeenCalled()
expect(body.error).toContain('AAL2')
})
})
+190
View File
@@ -0,0 +1,190 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import {
BrandLookupFailedError,
resolveRequestAppOrigin,
} from '@/lib/domains/trusted-app-origin'
import { validateBody } from '@/lib/api/validate'
import { createLogger } from '@/lib/logger'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const log = createLogger('api/account/email')
const ChangeEmailSchema = z.object({
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
})
// How long a pending change is considered fresh enough that re-submitting the
// same address is a no-op instead of a re-send. Kept well under the token
// expiry so a user with a dead link can always get new mails.
const FRESH_PENDING_MS = 30 * 60 * 1000
/**
* POST /api/account/email
*
* Server-routed login-email change. Always writes via the USER session so
* Supabase's AAL2 guard fires: an email change is a credential rotation, and
* a stolen AAL1 cookie must not be able to move the account to another
* mailbox. (Contrast app/api/account/password/route.ts, whose first-time-set
* path may bypass AAL2 because there is no existing credential to protect;
* an email change always has one.)
*
* Nothing changes immediately: with secure email change enabled, Supabase
* sends `email_change_current` to the old address and `email_change` to the
* new one (templates in lib/email/auth-templates.ts via the send-email hook),
* and the address flips only after confirmation. The links verify through
* /auth/callback, which already handles type=email_change.
*
* The account itself is keyed by user id everywhere (company_members,
* user_preferences, ...), so a confirmed change moves nothing but the login
* identifier and contact address. profiles.email mirrors auth.users.email via
* the sync_profile_email trigger (migration 20260828191950), so member lists,
* notification recipients, and AGI/KU contact fields follow the change.
*/
export async function POST(request: Request) {
const { user, supabase, error: authError } = await requireAuth()
if (authError) return authError
const result = await validateBody(request, ChangeEmailSchema)
if (!result.success) return result.response
const { email } = result.data
if (user.email && email === user.email.toLowerCase()) {
return NextResponse.json(
{ error: 'Det är redan din e-postadress.' },
{ status: 400 },
)
}
// Re-requesting the address that is already awaiting confirmation is a
// no-op success ONLY while the pending mails are fresh (protects the send
// rate limit against double-clicks). Once they are older than that, the
// confirmation links may have expired and the user's only recovery path is
// re-running the change, so fall through to GoTrue, which restarts the
// change and re-sends both mails.
//
// new_email/email_change_sent_at live on the GoTrue user, not in the JWT,
// so they are absent on the claims-mapped fast path of requireAuth. Reading
// them from the claims alone made every re-submit look like a brand-new
// request: GoTrue re-issued both tokens and voided the links the user was
// about to click, which is exactly the "link invalid" loop users hit after
// pressing the button twice. Fetch the fresh user when the claims carry no
// pending state; the extra round trip is fine on a route this rare.
let pendingEmail = user.new_email
let pendingSentAt = user.email_change_sent_at
if (!pendingEmail) {
const { data } = await supabase.auth.getUser()
pendingEmail = data?.user?.new_email
pendingSentAt = data?.user?.email_change_sent_at
}
if (pendingEmail && email === pendingEmail.toLowerCase()) {
const sentAt = pendingSentAt ? Date.parse(pendingSentAt) : Number.NaN
const fresh =
Number.isFinite(sentAt) && Date.now() - sentAt < FRESH_PENDING_MS
if (fresh) {
return NextResponse.json({
data: { ok: true, pending_email: email, resent: false },
})
}
}
// Trusted-origin resolution against the brands table, not request.url:
// behind a proxy request.url can be an internal origin (dead confirmation
// links on self-hosted), and auth links may never follow an
// attacker-chosen host. Registered brand hosts pass through so the mail
// carries the right brand.
//
// flow=email_change marks the callback so the stock GoTrue links (verified
// on the GoTrue host, returned here via redirect_to with ?message=, ?error=
// or ?code= instead of a token_hash) land on the email-change status page
// rather than the silent login bounce. The Send Email hook preserves this
// query on its token_hash links, so both link styles share the marker.
let origin: string
try {
origin = await resolveRequestAppOrigin(request)
} catch (err) {
if (!(err instanceof BrandLookupFailedError)) throw err
// Refuse rather than send a wrong-brand confirmation pair; nothing has
// been claimed or sent yet, so a retry is clean.
log.warn('email change refused: brand lookup failed', { userId: user.id })
return NextResponse.json(
{ error: 'Tillfälligt fel. Försök igen om en stund.' },
{ status: 503 },
)
}
// Cross-instance gate (migration 20260903083000). The pending-state read
// above is not atomic: two concurrent requests (two tabs, a retried fetch)
// can both see nothing pending, and each updateUser re-issues the tokens
// and voids the other's mails. claim_email_change_request is one
// INSERT ... ON CONFLICT row lock per user, so exactly one caller per
// address per window proceeds; the rest answer "already pending" and send
// nothing. A different address always wins the claim. Best effort: if the
// RPC itself fails, fall through to GoTrue rather than block the change.
const { data: claimed, error: claimError } = await supabase.rpc(
'claim_email_change_request',
{ p_email: email, p_window_seconds: FRESH_PENDING_MS / 1000 },
)
if (claimError) {
log.warn('email change claim failed; proceeding without it', {
userId: user.id,
code: claimError.code,
})
} else if (claimed === false) {
return NextResponse.json({
data: { ok: true, pending_email: email, resent: false },
})
}
const { error: updateError } = await supabase.auth.updateUser(
{ email },
{ emailRedirectTo: `${origin}/auth/callback?flow=email_change` },
)
if (updateError) {
log.warn('email change request failed', {
userId: user.id,
code: updateError.code,
status: updateError.status,
})
// GoTrue sent nothing, so the claim must not block a retry (after MFA,
// with another address, once the network is back).
if (!claimError) {
const { error: releaseError } = await supabase.rpc('release_email_change_request')
if (releaseError) {
log.warn('email change claim release failed', {
userId: user.id,
code: releaseError.code,
})
}
}
// Addresses are unique per auth user: a change to an already-registered
// address is refused by GoTrue, never merged. Accounts are consolidated
// via company invitations, not email changes.
if (
updateError.code === 'email_exists' ||
/already.*registered/i.test(updateError.message ?? '')
) {
return NextResponse.json(
{ error: 'E-postadressen används redan av ett annat konto.' },
{ status: 409 },
)
}
return NextResponse.json(
{
error:
getUserErrorMessage(updateError) ||
'Kunde inte begära e-poständring. Försök igen.',
},
{ status: 400 },
)
}
log.info('email change requested', { userId: user.id })
return NextResponse.json({
data: { ok: true, pending_email: email, resent: true },
})
}
@@ -0,0 +1,304 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: vi.fn(),
}))
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
import { createServiceClient } from '@/lib/supabase/server'
import { POST } from '../route'
const mockCreateServiceClient = vi.mocked(createServiceClient)
type AuthMetadata = Record<string, unknown>
function mockUserClient(opts: {
user: { id: string; app_metadata?: AuthMetadata } | null
updateUserError?: { message: string; status?: number; code?: string } | null
}) {
const updateUser = vi.fn().mockResolvedValue({
data: {},
error: opts.updateUserError ?? null,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const supabase = { auth: { updateUser } } as any
if (opts.user) {
requireAuthMock.mockResolvedValue({ user: opts.user, supabase, error: null })
} else {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
return { updateUser }
}
function mockService(opts: {
priorAppMetadata?: AuthMetadata
// Returned-error from admin.updateUserById when called with { password }
passwordSetError?: { message: string; status?: number; code?: string } | null
// Thrown error from admin.updateUserById when called with { app_metadata }
flagFlipError?: Error | null
}) {
const updateUserById = vi
.fn()
.mockImplementation((_id: string, args: Record<string, unknown>) => {
if ('password' in args) {
return Promise.resolve({
data: {},
error: opts.passwordSetError ?? null,
})
}
if (opts.flagFlipError) return Promise.reject(opts.flagFlipError)
return Promise.resolve({ data: {}, error: null })
})
const getUserById = vi.fn().mockResolvedValue({
data: { user: { app_metadata: opts.priorAppMetadata ?? {} } },
})
mockCreateServiceClient.mockReturnValue({
auth: { admin: { getUserById, updateUserById } },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
return { getUserById, updateUserById }
}
const STRONG_PASSWORD = 'StrongP@ssword1'
function flagFlipCall(updateUserById: ReturnType<typeof vi.fn>) {
return updateUserById.mock.calls.find(
([, args]) => args && typeof args === 'object' && 'app_metadata' in args,
)
}
function passwordSetCall(updateUserById: ReturnType<typeof vi.fn>) {
return updateUserById.mock.calls.find(
([, args]) => args && typeof args === 'object' && 'password' in args,
)
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('POST /api/account/password', () => {
it('returns 401 when unauthenticated', async () => {
mockUserClient({ user: null })
mockService({})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(401)
})
it('returns 400 when password is too weak', async () => {
mockUserClient({ user: { id: 'user-1', app_metadata: { has_password: true } } })
mockService({ priorAppMetadata: { has_password: true } })
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: 'weak' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(400)
})
describe('first-time set (has_password !== true)', () => {
it('writes the password via admin API and flips the flag', async () => {
const { updateUser } = mockUserClient({
user: {
id: 'user-1',
app_metadata: { has_password: false, bankid_linked: true },
},
})
const { updateUserById } = mockService({
priorAppMetadata: { has_password: false, bankid_linked: true },
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.ok).toBe(true)
// Did NOT go through the user session: that path would fail with AAL2.
expect(updateUser).not.toHaveBeenCalled()
// Password set via admin
expect(passwordSetCall(updateUserById)).toEqual([
'user-1',
{ password: STRONG_PASSWORD },
])
// Flag flipped, siblings preserved
expect(flagFlipCall(updateUserById)).toEqual([
'user-1',
{
app_metadata: {
has_password: true,
bankid_linked: true,
},
},
])
})
it('treats unset has_password as first-time set', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1' /* no app_metadata */ },
})
const { updateUserById } = mockService({})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(200)
expect(updateUser).not.toHaveBeenCalled()
expect(passwordSetCall(updateUserById)).toBeDefined()
})
it('returns 400 and skips flag flip when the admin password set fails', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: false } },
})
const { updateUserById } = mockService({
priorAppMetadata: { has_password: false },
passwordSetError: { message: 'Password too weak', status: 400 },
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(body.error).toBe('Något gick fel. Försök igen.')
expect(updateUser).not.toHaveBeenCalled()
expect(flagFlipCall(updateUserById)).toBeUndefined()
})
it('still returns success when the flag flip fails after admin password set', async () => {
mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: false } },
})
mockService({
priorAppMetadata: { has_password: false },
flagFlipError: new Error('admin down'),
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.ok).toBe(true)
})
})
describe('change-password (has_password === true)', () => {
it('writes via the user session so Supabase enforces AAL2', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: true } },
})
const { updateUserById } = mockService({
priorAppMetadata: { has_password: true, provider: 'email' },
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.ok).toBe(true)
// Used user session, NOT admin API for the password itself
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
expect(passwordSetCall(updateUserById)).toBeUndefined()
// Flag is still flipped (idempotent) with siblings preserved
expect(flagFlipCall(updateUserById)).toEqual([
'user-1',
{
app_metadata: {
has_password: true,
provider: 'email',
},
},
])
})
it('returns 400 and skips flag flip when Supabase rejects the password update', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: true } },
updateUserError: { message: 'Password too similar to old', status: 400 },
})
const { updateUserById } = mockService({
priorAppMetadata: { has_password: true },
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(body.error).toBe('Något gick fel. Försök igen.')
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
expect(flagFlipCall(updateUserById)).toBeUndefined()
})
it('surfaces the AAL2 error verbatim so the client can step up via /mfa/verify', async () => {
mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: true } },
updateUserError: {
message:
'AAL2 session is required to update email or password when MFA is enabled',
status: 422,
},
})
mockService({ priorAppMetadata: { has_password: true } })
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(body.error).toContain('AAL2')
})
})
})
+119
View File
@@ -0,0 +1,119 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { validateBody } from '@/lib/api/validate'
import { createLogger } from '@/lib/logger'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const log = createLogger('api/account/password')
const SetPasswordSchema = z.object({
password: z
.string()
.min(8, 'Lösenordet måste vara minst 8 tecken')
.refine(
(v) =>
/[a-z]/.test(v) &&
/[A-Z]/.test(v) &&
/[0-9]/.test(v) &&
/[^a-zA-Z0-9]/.test(v),
'Lösenordet måste innehålla versaler, gemener, siffror och specialtecken',
),
})
/**
* POST /api/account/password
*
* Server-routed password set/change, then flips `app_metadata.has_password =
* true` via the service client (clients can't write app_metadata).
*
* Two paths depending on whether the user already has a real password:
*
* - First-time set (`app_metadata.has_password !== true`): write via the
* admin API. BankID-only users (and legacy users whose `has_password`
* flag was set to false by the backfill) sit at AAL1 with a TOTP factor
* enrolled, and `updateUser` on the user session would be rejected with
* "AAL2 session is required to update email or password when MFA is
* enabled". Setting an initial password has no existing credential to
* protect, so bypassing AAL2 is safe.
*
* - Change-password (`app_metadata.has_password === true`): write via the
* user session so Supabase's AAL2 guard still fires. A stolen AAL1
* cookie must not be able to rotate a known password.
*
* This route is the single write path for setting a password. SecuritySettings,
* the reset-password page, and the /account/set-password page all funnel
* through here so the flag stays in sync: see lib/auth/has-password.ts.
*
* If the password update succeeds but the flag write fails, we log and still
* return success: the user has a working password and the banner will show one
* more time, but a retry will re-flip the flag.
*/
export async function POST(request: Request) {
const { user, supabase, error: authError } = await requireAuth()
if (authError) return authError
const result = await validateBody(request, SetPasswordSchema)
if (!result.success) return result.response
const { password } = result.data
const isFirstTimeSet = user.app_metadata?.has_password !== true
const service = createServiceClient()
let updateError:
| { message?: string; status?: number; code?: string }
| null
| undefined = null
if (isFirstTimeSet) {
const { error } = await service.auth.admin.updateUserById(user.id, {
password,
})
updateError = error
} else {
const { error } = await supabase.auth.updateUser({ password })
updateError = error
}
if (updateError) {
log.warn('password update failed', {
userId: user.id,
isFirstTimeSet,
code: updateError.code,
status: updateError.status,
})
return NextResponse.json(
{
error:
getUserErrorMessage(updateError) ||
'Kunde inte uppdatera lösenord. Försök igen.',
},
{ status: 400 },
)
}
// Read-merge-write so we don't wipe sibling app_metadata keys.
// updateUserById replaces app_metadata wholesale (see lib/auth/has-password.ts
// and the comment in app/api/account/delete/route.ts).
let flagWriteOk = false
try {
const { data: u } = await service.auth.admin.getUserById(user.id)
const prior = u?.user?.app_metadata ?? {}
await service.auth.admin.updateUserById(user.id, {
app_metadata: { ...prior, has_password: true },
})
flagWriteOk = true
} catch (err) {
log.error('failed to flip has_password flag after successful password set', {
userId: user.id,
err,
})
// Don't surface the failure: the user has a working password. The
// banner will show once more and a retry will succeed.
}
log.info('password set', { userId: user.id, isFirstTimeSet, flagWriteOk })
return NextResponse.json({ data: { ok: true } })
}
+102
View File
@@ -0,0 +1,102 @@
/**
* Tests for POST /api/agent/composer.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const checkRateMock = vi.fn()
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({
guardSandbox: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
requireCapability: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/keys', () => ({
CAPABILITY: { ai: 'ai' },
}))
const composeMock = vi.fn()
vi.mock('@/lib/agent/composer', () => ({
composeAgentProfile: (...args: unknown[]) => composeMock(...args),
}))
import { POST } from '../composer/route'
const routeParams = { params: Promise.resolve({}) }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
checkRateMock.mockResolvedValue({ ok: true })
})
describe('POST /api/agent/composer', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
const res = await POST(req, routeParams)
expect(res.status).toBe(401)
})
it('returns 429 when rate limited', async () => {
checkRateMock.mockResolvedValue({ ok: false, retryAfterSec: 30 })
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
const res = await POST(req, routeParams)
expect(res.status).toBe(429)
expect(res.headers.get('Retry-After')).toBe('30')
})
it('refuses a viewer with 403 (composer rewrites the profile)', async () => {
enqueue({ data: { role: 'viewer' } })
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
expect(composeMock).not.toHaveBeenCalled()
})
it('runs the composer for a non-viewer member', async () => {
enqueue({ data: { role: 'owner' } })
composeMock.mockResolvedValue({ company_id: 'company-1', profile_summary: 'Byggd' })
const req = createMockRequest('/api/agent/composer', {
method: 'POST',
body: { dry_run: true },
})
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(200)
expect(body.data.profile_summary).toBe('Byggd')
expect(composeMock).toHaveBeenCalledWith(expect.anything(), 'company-1', { dryRun: true })
})
})
@@ -0,0 +1,176 @@
/**
* Tests for GET /api/agent/conversations and GET/PATCH /api/agent/conversations/[id].
*
* Uses a filter-capturing Supabase mock so the user-scoping regression is
* locked in: RLS on agent_conversations is company-scoped, so the explicit
* .eq('user_id', …) filter in the list route is the only thing preventing
* team members from seeing each other's conversation titles/previews.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { GET as listGET } from '../conversations/route'
import { GET as detailGET, PATCH as detailPATCH } from '../conversations/[id]/route'
interface CapturedCall {
method: string
args: unknown[]
}
/** Chainable builder that records every call and resolves queued results per from(). */
function createCapturingSupabase(results: { data?: unknown; error?: unknown }[]) {
const calls: CapturedCall[] = []
let idx = 0
const makeBuilder = () => {
const result = results[idx++] ?? { data: null, error: null }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const b: any = {}
for (const m of ['select', 'eq', 'is', 'or', 'order', 'limit', 'insert', 'update', 'maybeSingle', 'single']) {
b[m] = (...args: unknown[]) => {
calls.push({ method: m, args })
return b
}
}
b.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null, count: null })
return b
}
const supabase = {
from: (table: string) => {
calls.push({ method: 'from', args: [table] })
return makeBuilder()
},
}
return { supabase, calls }
}
const routeParams = { params: Promise.resolve({}) }
const idParams = { params: Promise.resolve({ id: 'conv-1' }) }
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/agent/conversations', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await listGET(createMockRequest('/api/agent/conversations'), routeParams)
expect(res.status).toBe(401)
})
it('returns 400 for a non-numeric limit', async () => {
const { supabase } = createCapturingSupabase([])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const req = createMockRequest('/api/agent/conversations', { searchParams: { limit: 'abc' } })
const { status } = await parseJsonResponse(await listGET(req, routeParams))
expect(status).toBe(400)
})
it('filters the list by BOTH company_id and the calling user_id', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: [{ id: 'conv-1', title: 'Min konversation' }] },
])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const req = createMockRequest('/api/agent/conversations')
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
await listGET(req, routeParams)
)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
expect(eqCalls).toContainEqual(['company_id', 'company-1'])
// Privacy regression guard: without this filter, company-scoped RLS lets
// every member read colleagues' titles and last_message_preview.
expect(eqCalls).toContainEqual(['user_id', 'user-1'])
})
})
describe('GET /api/agent/conversations/[id]', () => {
it('returns 404 when the conversation is not owned by the caller', async () => {
// Ownership is part of the fetch (.eq user_id) — a non-owned id resolves null.
const { supabase, calls } = createCapturingSupabase([{ data: null }])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await detailGET(createMockRequest('/api/agent/conversations/conv-1'), idParams)
)
expect(status).toBe(404)
expect(body.error.code).toBe('CONVERSATION_NOT_FOUND')
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
expect(eqCalls).toContainEqual(['user_id', 'user-1'])
})
it('returns the conversation with its messages for the owner', async () => {
const { supabase } = createCapturingSupabase([
{ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1', title: 'T' } },
{ data: { role: 'member' } },
{ data: [{ id: 'm1', role: 'user', content: 'Hej' }] },
])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const { status, body } = await parseJsonResponse<{
data: { conversation: { id: string }; messages: unknown[] }
}>(await detailGET(createMockRequest('/api/agent/conversations/conv-1'), idParams))
expect(status).toBe(200)
expect(body.data.conversation.id).toBe('conv-1')
expect(body.data.messages).toHaveLength(1)
})
})
describe('PATCH /api/agent/conversations/[id]', () => {
it('returns 400 when the body has nothing to update', async () => {
const { supabase } = createCapturingSupabase([])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const req = createMockRequest('/api/agent/conversations/conv-1', {
method: 'PATCH',
body: {},
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await detailPATCH(req, idParams)
)
expect(status).toBe(400)
expect(body.error.code).toBe('NOTHING_TO_UPDATE')
})
it('updates pin state for an owned conversation', async () => {
const { supabase } = createCapturingSupabase([
{ data: { user_id: 'user-1', company_id: 'company-1' } },
{ data: { id: 'conv-1', pinned: true } },
])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const req = createMockRequest('/api/agent/conversations/conv-1', {
method: 'PATCH',
body: { pinned: true },
})
const { status, body } = await parseJsonResponse<{ data: { pinned: boolean } }>(
await detailPATCH(req, idParams)
)
expect(status).toBe(200)
expect(body.data.pinned).toBe(true)
})
})
+184
View File
@@ -0,0 +1,184 @@
/**
* Tests for POST /api/agent/feedback.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const emitMock = vi.fn()
vi.mock('@/lib/events/bus', () => ({
eventBus: { emit: (...args: unknown[]) => emitMock(...args) },
}))
import { POST } from '../feedback/route'
const routeParams = { params: Promise.resolve({}) }
const CONVERSATION_ID = '11111111-2222-4333-8444-555555555555'
const body = (over: Record<string, unknown> = {}) => ({
conversation_id: CONVERSATION_ID,
sentiment: 'negative',
...over,
})
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('POST /api/agent/feedback', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
expect((await POST(req, routeParams)).status).toBe(401)
expect(emitMock).not.toHaveBeenCalled()
})
it('returns 400 for a sentiment outside the two votes the UI can send', async () => {
const req = createMockRequest('/api/agent/feedback', {
method: 'POST',
body: body({ sentiment: 'furious' }),
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(400)
expect(emitMock).not.toHaveBeenCalled()
})
it('returns 400 when the conversation id is not a uuid', async () => {
const req = createMockRequest('/api/agent/feedback', {
method: 'POST',
body: body({ conversation_id: 'not-a-uuid' }),
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(400)
})
it('404s on a conversation belonging to another user', async () => {
// Same hole that /api/agent/invoke had: the id is caller-supplied, so
// without the ownership check a member could file feedback against a
// colleague's thread and the triage backlog would carry a conversation the
// reporter never saw.
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'someone-else',
company_id: 'company-1',
intent_id: 'general.help',
},
})
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(404)
expect(emitMock).not.toHaveBeenCalled()
})
it('404s on a conversation in another company', async () => {
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-2',
intent_id: 'general.help',
},
})
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
expect((await parseJsonResponse(await POST(req, routeParams))).status).toBe(404)
expect(emitMock).not.toHaveBeenCalled()
})
it('404s when the conversation does not exist', async () => {
enqueue({ data: null })
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
expect((await parseJsonResponse(await POST(req, routeParams))).status).toBe(404)
})
it('emits agent.feedback with actorType user on the happy path', async () => {
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'vat.review',
},
})
const req = createMockRequest('/api/agent/feedback', {
method: 'POST',
body: body({ sentiment: 'positive', message_index: 4 }),
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(200)
expect(emitMock).toHaveBeenCalledOnce()
const event = emitMock.mock.calls[0]![0] as {
type: string
payload: Record<string, unknown>
}
// Same event type the MCP tool emits, so chat votes land in the backlog
// the product team already reads instead of a second place.
expect(event.type).toBe('agent.feedback')
expect(event.payload.sentiment).toBe('positive')
expect(event.payload.actorType).toBe('user')
expect(event.payload.actorId).toBe('user-1')
expect(event.payload.companyId).toBe('company-1')
expect(event.payload.sessionId).toBe(CONVERSATION_ID)
// Traceable to an answer: a thumbs-down that cannot be tied to a turn is a
// number, not a report.
expect(event.payload.context).toContain('vat.review')
expect(event.payload.context).toContain('#4')
})
it('never carries user free text into the telemetry log', async () => {
// A comment box here would put whatever the user typed, in an accounting
// product, verbatim into event_log under telemetry retention: client
// names, personnummer, case details. The field is not accepted, and a
// caller that sends one anyway must not have it stored.
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'general.help',
},
})
const req = createMockRequest('/api/agent/feedback', {
method: 'POST',
body: body({ comment: 'Anna Andersson 19850101-1234 fick fel konto' }),
})
await POST(req, routeParams)
const event = emitMock.mock.calls[0]![0] as { payload: { context: string } }
expect(event.payload.context).not.toContain('Anna Andersson')
expect(event.payload.context).not.toContain('19850101')
expect(JSON.stringify(event.payload)).not.toContain('19850101')
})
})
+282
View File
@@ -0,0 +1,282 @@
/**
* Tests for POST /api/agent/invoke, focused on conversation ownership.
*
* RLS on agent_conversations/agent_messages is company-scoped, not user-scoped
* (migration 20260517204000), so the route itself has to prove that a resumed
* conversation_id belongs to the caller. Without that check, a member could
* post a colleague's conversation id and have their history loaded into the
* prompt (and their own turns appended to it).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const checkRateMock = vi.fn()
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({
guardSandbox: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
requireCapability: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/keys', () => ({
CAPABILITY: { ai: 'ai' },
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
const getIntentMock = vi.fn()
vi.mock('@/lib/agent/intents/registry', () => ({
getIntent: (...args: unknown[]) => getIntentMock(...args),
}))
// Deployment-level AI availability (distinct from the per-company paywall).
// Default: available, so the ownership tests below exercise the real flow.
const aiStatusMock = vi.fn()
vi.mock('@/lib/ai', () => ({
getAiStatus: () => aiStatusMock(),
}))
const runChatTurnMock = vi.fn()
vi.mock('@/lib/agent/chat/run-turn', () => ({
runChatTurn: (...args: unknown[]) => runChatTurnMock(...args),
friendlyModelError: () => 'Något gick fel hos assistenten.',
}))
import { POST } from '../invoke/route'
const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111'
function body(overrides: Record<string, unknown> = {}) {
return {
intent_id: 'general.help',
user_message: 'Hur gick juli?',
...overrides,
}
}
/**
* Queue the reads the route performs before it resolves the conversation.
*
* Ownership is validated ahead of every side effect and of the company/profile
* reads, so a rejected request costs exactly one membership read plus the
* conversation lookup.
*/
function enqueuePreamble() {
enqueue({ data: { role: 'owner' } }) // company_members
}
/** The company + profile reads that only happen once a request is accepted. */
function enqueueAcceptedTail() {
enqueue({ data: { name: 'Nordvik Bygg AB' } }) // companies
enqueue({ data: { full_name: 'Johan Nordvik' } }) // profiles
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
checkRateMock.mockResolvedValue({ ok: true })
getIntentMock.mockReturnValue({ id: 'general.help', sheetTitle: 'Assistenten' })
runChatTurnMock.mockResolvedValue(undefined)
aiStatusMock.mockReturnValue({ configured: true, assistantAvailable: true, provider: 'bedrock' })
})
describe('POST /api/agent/invoke', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 400 on an invalid body', async () => {
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: { intent_id: '' } }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 400 for an unknown intent', async () => {
getIntentMock.mockReturnValue(undefined)
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(400)
})
// A self-host without an AI key, or on an OpenAI-compatible endpoint the
// chat loop does not speak yet: say so up front with a distinct code, never
// open a stream that dies on the first model call, never confuse it with
// the paywall.
it('returns 503 ai_unconfigured when the deployment has no assistant backend', async () => {
aiStatusMock.mockReturnValue({ configured: false, assistantAvailable: false, provider: 'bedrock' })
enqueuePreamble()
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status, body: json } = await parseJsonResponse<{ error: string; code: string }>(res)
expect(status).toBe(503)
expect(json.code).toBe('ai_unconfigured')
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 403 when the user is not a member of the company', async () => {
enqueue({ data: null }) // company_members: no row
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
})
it('returns 404 when resuming a conversation owned by another user', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-2', // someone else in the same company
company_id: 'company-1',
intent_id: 'general.help',
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status, body: json } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(404)
expect(json.error).toBe('Konversationen hittades inte.')
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 404 when resuming a conversation from another company', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1', // same user...
company_id: 'company-2', // ...but a company other than the active one
intent_id: 'general.help',
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 404 when the conversation does not exist', async () => {
enqueuePreamble()
enqueue({ data: null })
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 400 when the conversation belongs to a different intent', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'vat.review', // tool loadout differs from general.help
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('runs the turn when the caller owns the conversation', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'general.help',
},
})
enqueueAcceptedTail()
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
expect(res.status).toBe(200)
// The route streams NDJSON; draining it is enough to know the turn ran.
await res.text()
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
})
it('hands the first-turn profile summary to the turn instead of re-reading it', async () => {
// On a first turn the route reads agent_profiles to build the intent's
// prompt template. run-turn needs the same value for the system prompt, so
// it is passed through rather than read a second time.
getIntentMock.mockReturnValue({
id: 'general.help',
sheetTitle: 'Assistenten',
capture: vi.fn().mockResolvedValue({ some: 'context' }),
promptTemplate: vi.fn().mockReturnValue('templated first turn'),
})
enqueuePreamble()
enqueue({ data: { id: CONVERSATION_ID } }) // conversation insert
enqueueAcceptedTail()
enqueue({ data: { profile_summary: 'Byggkonsult, K2' } }) // agent_profiles
enqueue({ data: [] }) // agent_memory
const res = await POST(
createMockRequest('/api/agent/invoke', {
method: 'POST',
body: { intent_id: 'general.help' }, // no user_message => first turn
}),
)
await res.text()
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
const args = runChatTurnMock.mock.calls[0]![0] as {
preloadedProfileSummary?: string | null
userMessage: string
userMessageHidden?: boolean
}
expect(args.preloadedProfileSummary).toBe('Byggkonsult, K2')
expect(args.userMessage).toBe('templated first turn')
expect(args.userMessageHidden).toBe(true)
})
})
+150
View File
@@ -0,0 +1,150 @@
/**
* Tests for GET/POST /api/agent/memory and PATCH /api/agent/memory/[id].
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET, POST } from '../memory/route'
import { PATCH } from '../memory/[id]/route'
const routeParams = { params: Promise.resolve({}) }
const idParams = { params: Promise.resolve({ id: 'mem-1' }) }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('GET /api/agent/memory', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/api/agent/memory'), routeParams)
expect(res.status).toBe(401)
})
it('returns 400 for an unknown kind filter', async () => {
const req = createMockRequest('/api/agent/memory', { searchParams: { kind: 'gossip' } })
const { status } = await parseJsonResponse(await GET(req, routeParams))
expect(status).toBe(400)
})
it('lists memory entries', async () => {
enqueue({ data: [{ id: 'mem-1', kind: 'fact', content: 'Fakturerar i SEK' }] })
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
await GET(createMockRequest('/api/agent/memory'), routeParams)
)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
})
})
describe('POST /api/agent/memory', () => {
it('rejects a viewer in the target company with 403', async () => {
// requireWrite passed for the ACTIVE company, but the body targets a
// company where the caller is only a viewer — the re-check must refuse.
enqueue({ data: { role: 'viewer' } })
const req = createMockRequest('/api/agent/memory', {
method: 'POST',
body: { company_id: '7f3e0b1a-9c4d-4a2b-8f6e-1d2c3b4a5e6f', content: 'Ett minne' },
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
})
it('rejects an invalid body with 400', async () => {
const req = createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'x' }, // below min length 2
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(400)
})
it('inserts a memory entry for the active company', async () => {
enqueue({ data: { role: 'admin' } }) // membership re-check
enqueue({ data: { id: 'mem-2', kind: 'fact', content: 'Ett minne' } })
const req = createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'Ett minne' },
})
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(200)
expect(body.data.id).toBe('mem-2')
})
})
describe('PATCH /api/agent/memory/[id]', () => {
it('returns 400 when the body has nothing to update', async () => {
const req = createMockRequest('/api/agent/memory/mem-1', { method: 'PATCH', body: {} })
const { status } = await parseJsonResponse(await PATCH(req, idParams))
expect(status).toBe(400)
})
it('returns 404 when the memory row does not exist', async () => {
enqueue({ data: null })
const req = createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_pinned: true },
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, idParams)
)
expect(status).toBe(404)
expect(body.error.code).toBe('MEMORY_NOT_FOUND')
})
it('updates a memory entry', async () => {
enqueue({ data: { company_id: 'company-1' } }) // row lookup
enqueue({ data: { role: 'member' } }) // membership re-check
enqueue({ data: { id: 'mem-1', is_pinned: true } }) // update
const req = createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_pinned: true },
})
const { status, body } = await parseJsonResponse<{ data: { is_pinned: boolean } }>(
await PATCH(req, idParams)
)
expect(status).toBe(200)
expect(body.data.is_pinned).toBe(true)
})
})
@@ -0,0 +1,92 @@
/**
* Tests for POST /api/agent/onboarding/stream — auth surface only.
*
* The composer pipeline itself is exercised via lib tests; here we lock in
* the guard order: 401, membership 403, and the viewer refusal (the pipeline
* upserts agent_profiles, so viewers must not be able to trigger it).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: vi.fn().mockResolvedValue({ ok: true }),
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
vi.mock('@/lib/entitlements/has-capability', () => ({
requireCapability: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
// Pipeline internals — never reached in these tests, stubbed so the module loads.
vi.mock('@/lib/agent/composer/inputs', () => ({
gatherComposerInputs: vi.fn(),
inputsToSourceSignals: vi.fn(),
}))
vi.mock('@/lib/agent/composer/atom-selection', () => ({
selectAtoms: vi.fn(),
filterRedundantQuestions: vi.fn(),
}))
vi.mock('@/lib/agent/composer/narrative', () => ({ writeNarrative: vi.fn() }))
vi.mock('@/lib/agent/composer/fallback', () => ({
fallbackAtomSelection: vi.fn(),
fallbackNarrative: vi.fn(),
}))
vi.mock('@/lib/agent/composer/prewarm', () => ({ preWarmAtomCache: vi.fn() }))
vi.mock('@/lib/agent/composer/client', () => ({ OPUS_MODEL: 'opus-test' }))
vi.mock('@/lib/agent/composer/tic-fetch', () => ({ ensureTicSnapshot: vi.fn() }))
vi.mock('@/lib/supabase/server', () => ({ createClient: vi.fn() }))
import { createClient } from '@/lib/supabase/server'
import { POST } from '../onboarding/stream/route'
const mockCreateClient = vi.mocked(createClient)
function mockAuth(userId: string | null, membership: { role: string } | null) {
mockCreateClient.mockResolvedValue({
auth: {
getUser: vi.fn().mockResolvedValue({ data: { user: userId ? { id: userId } : null } }),
},
from: vi.fn().mockReturnValue({
select: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
maybeSingle: vi.fn().mockResolvedValue({ data: membership, error: null }),
}),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('POST /api/agent/onboarding/stream', () => {
it('returns 401 when not authenticated', async () => {
mockAuth(null, null)
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
const res = await POST(req)
expect(res.status).toBe(401)
})
it('returns 403 for a non-member', async () => {
mockAuth('user-1', null)
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(403)
})
it('refuses a viewer with 403 (pipeline upserts agent_profiles)', async () => {
mockAuth('user-1', { role: 'viewer' })
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: string }>(await POST(req))
expect(status).toBe(403)
expect(body.error).toContain('läsbehörighet')
})
})
+149
View File
@@ -0,0 +1,149 @@
/**
* Tests for GET/PATCH /api/agent/profile and POST /api/agent/profile/verify.
*
* Covers the role model: reads allow any member, mutations (PATCH, verify)
* refuse viewers — the same rule verify always had, now enforced on PATCH too.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { GET, PATCH } from '../profile/route'
import { POST as VERIFY } from '../profile/verify/route'
const routeParams = { params: Promise.resolve({}) }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
})
describe('GET /api/agent/profile', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/api/agent/profile'), routeParams)
expect(res.status).toBe(401)
})
it('returns 403 when the caller is not a member of the target company', async () => {
enqueue({ data: null }) // membership lookup
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await GET(createMockRequest('/api/agent/profile'), routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('NOT_COMPANY_MEMBER')
})
it('returns the profile for a member (viewers may read)', async () => {
enqueue({ data: { role: 'viewer' } })
enqueue({ data: { company_id: 'company-1', profile_summary: 'Konsultbolag' } })
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
await GET(createMockRequest('/api/agent/profile'), routeParams)
)
expect(status).toBe(200)
expect(body.data.profile_summary).toBe('Konsultbolag')
})
})
describe('PATCH /api/agent/profile', () => {
it('refuses a viewer with 403 (profile mutation)', async () => {
enqueue({ data: { role: 'viewer' } })
const req = createMockRequest('/api/agent/profile', {
method: 'PATCH',
body: { profile_summary: 'Nytt sammandrag' },
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
})
it('returns 404 when the company has no agent_profile row', async () => {
enqueue({ data: { role: 'admin' } })
enqueue({ data: null }) // current profile lookup
const req = createMockRequest('/api/agent/profile', {
method: 'PATCH',
body: { profile_summary: 'Nytt sammandrag' },
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(404)
expect(body.error.code).toBe('AGENT_PROFILE_NOT_FOUND')
})
it('returns 400 when the body contains nothing to update', async () => {
enqueue({ data: { role: 'admin' } })
enqueue({ data: { field_overrides: null } })
const req = createMockRequest('/api/agent/profile', { method: 'PATCH', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(400)
expect(body.error.code).toBe('NOTHING_TO_UPDATE')
})
it('merges field_overrides and updates the profile', async () => {
enqueue({ data: { role: 'admin' } })
enqueue({ data: { field_overrides: { old: { value: 1, overridden_at: 'x' } } } })
enqueue({ data: { company_id: 'company-1', profile_summary: 'Uppdaterad' } })
const req = createMockRequest('/api/agent/profile', {
method: 'PATCH',
body: { profile_summary: 'Uppdaterad', field_overrides: { vat_period: 'quarterly' } },
})
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(200)
expect(body.data.profile_summary).toBe('Uppdaterad')
})
})
describe('POST /api/agent/profile/verify', () => {
it('refuses a viewer with 403', async () => {
enqueue({ data: { role: 'viewer' } })
const req = createMockRequest('/api/agent/profile/verify', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await VERIFY(req, routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
})
it('stamps verified_at for a non-viewer member', async () => {
enqueue({ data: { role: 'owner' } })
enqueue({ data: { company_id: 'company-1', verified_at: '2026-07-03T00:00:00Z', verified_by_user_id: 'user-1' } })
const req = createMockRequest('/api/agent/profile/verify', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ data: { verified_by_user_id: string } }>(
await VERIFY(req, routeParams)
)
expect(status).toBe(200)
expect(body.data.verified_by_user_id).toBe('user-1')
})
})
+224
View File
@@ -0,0 +1,224 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
const checkRate = vi.fn()
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: () => checkRate(),
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
const requireCapability = vi.fn()
vi.mock('@/lib/entitlements/has-capability', () => ({ requireCapability: () => requireCapability() }))
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
const aiStatus = vi.fn()
vi.mock('@/lib/ai', () => ({ getAiStatus: () => aiStatus() }))
const answer = vi.fn()
vi.mock('@/lib/agent/ask/ask-service', () => ({ answerAssistantQuestion: (...a: unknown[]) => answer(...a) }))
const resolveConv = vi.fn()
const loadHistory = vi.fn()
const persistUser = vi.fn()
const persistAssistant = vi.fn()
vi.mock('@/lib/agent/ask/persist', () => ({
resolveChatConversation: (...a: unknown[]) => resolveConv(...a),
loadChatHistory: (...a: unknown[]) => loadHistory(...a),
persistUserTurn: (...a: unknown[]) => persistUser(...a),
persistAssistantTurn: (...a: unknown[]) => persistAssistant(...a),
}))
import { POST, maxDuration } from '../route'
import { EmptyModelAnswerError } from '@/lib/agent/ask/errors'
const membershipChain = { select: () => membershipChain, eq: () => membershipChain, maybeSingle: async () => ({ data: { user_id: 'user-1' } }) }
const supabase = { from: () => membershipChain }
beforeEach(() => {
vi.clearAllMocks()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
checkRate.mockResolvedValue({ ok: true })
requireCapability.mockResolvedValue(null)
aiStatus.mockReturnValue({ configured: true, assistantAvailable: false, provider: 'openai-compatible' })
answer.mockResolvedValue({ answer: 'Svar', model: 'qwen3.8' })
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-9', created: true })
loadHistory.mockResolvedValue([])
persistUser.mockResolvedValue(undefined)
persistAssistant.mockResolvedValue(undefined)
})
const body = (o: Record<string, unknown> = {}) => ({ question: 'Hur gick juli?', ...o })
describe('POST /api/agent/ask', () => {
it('declares a 300s function budget so a tool-loop answer is not killed mid-turn', () => {
expect(maxDuration).toBe(300)
})
it('401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
expect((await POST(createMockRequest('/api/agent/ask', { method: 'POST', body: body() }))).status).toBe(401)
})
it('429 when rate limited', async () => {
checkRate.mockResolvedValue({ ok: false })
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(429)
})
it('400 on an empty question', async () => {
expect((await POST(createMockRequest('/x', { method: 'POST', body: { question: '' } }))).status).toBe(400)
})
it('403 when the company lacks the ai capability (paywall)', async () => {
requireCapability.mockResolvedValue(NextResponse.json({ error: 'pay' }, { status: 403 }))
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(403)
})
// The key behaviour: this endpoint runs on ANY configured backend, so it is
// available even when the streaming chat (assistantAvailable) is not, e.g.
// on a local OpenAI-compatible model.
it('answers on an openai-compatible backend where the streaming chat would 503', async () => {
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ context: 'Resultat juli: +12 000' }) }))
const { status, body: b } = await parseJsonResponse<{ data: { answer: string; model: string } }>(res)
expect(status).toBe(200)
expect(b.data).toEqual({ answer: 'Svar', model: 'qwen3.8' })
expect(answer).toHaveBeenCalledWith(expect.objectContaining({ companyId: 'company-1', question: 'Hur gick juli?', pageContext: 'Resultat juli: +12 000' }))
})
it('503 ai_unconfigured when no backend is configured at all', async () => {
aiStatus.mockReturnValue({ configured: false })
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
expect(status).toBe(503)
expect(b.code).toBe('ai_unconfigured')
expect(answer).not.toHaveBeenCalled()
})
it('502s with a Swedish message when the model answers empty (the silent-stop bug)', async () => {
answer.mockRejectedValue(new EmptyModelAnswerError('claude-sonnet-5'))
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
const { status, body: b } = await parseJsonResponse<{ error: string; code: string }>(res)
expect(status).toBe(502)
expect(b.error).toBe('Assistenten gav inget svar. Försök igen.')
expect(b.code).toBe('empty_model_answer')
})
it('stateless (no persist): never touches the conversation tables', async () => {
await POST(createMockRequest('/x', { method: 'POST', body: body() }))
expect(resolveConv).not.toHaveBeenCalled()
expect(persistUser).not.toHaveBeenCalled()
expect(persistAssistant).not.toHaveBeenCalled()
})
describe('persist: true (chat console)', () => {
it('creates/resumes the thread, writes both turns, returns the conversation id', async () => {
const res = await POST(
createMockRequest('/x', {
method: 'POST',
body: body({ persist: true, context_ref: 'report:vat:2026-07' }),
}),
)
const { status, body: b } = await parseJsonResponse<{
data: { answer: string; model: string; conversation_id: string }
}>(res)
expect(status).toBe(200)
expect(b.data.conversation_id).toBe('conv-9')
expect(b.data.answer).toBe('Svar')
// Order matters: resolve → user turn → answer → assistant turn.
expect(resolveConv).toHaveBeenCalledWith(
supabase,
'user-1',
'company-1',
undefined,
'Hur gick juli?',
'report:vat:2026-07',
)
expect(persistUser).toHaveBeenCalledWith(supabase, 'conv-9', 'Hur gick juli?')
expect(answer).toHaveBeenCalled()
expect(persistAssistant).toHaveBeenCalledWith(supabase, 'conv-9', 'Svar')
// A thread created by this very request has no earlier turns to load.
expect(loadHistory).not.toHaveBeenCalled()
expect(answer.mock.calls[0][0].history).toEqual([])
})
it('a resumed thread answers with its earlier turns, read before the new question is written', async () => {
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-7', created: false })
const history = [
{ role: 'user', text: 'Vad är min största utgift?' },
{ role: 'assistant', text: '12 345 kr på 5010.' },
]
const order: string[] = []
loadHistory.mockImplementation(async () => {
order.push('load')
return history
})
persistUser.mockImplementation(async () => {
order.push('persist')
})
const res = await POST(
createMockRequest('/x', {
method: 'POST',
body: body({ persist: true, conversation_id: '11111111-1111-4111-8111-111111111111', question: 'Och förra månaden?' }),
}),
)
expect(res.status).toBe(200)
expect(loadHistory).toHaveBeenCalledWith(supabase, 'conv-7')
expect(order).toEqual(['load', 'persist'])
expect(answer).toHaveBeenCalledWith(
expect.objectContaining({ conversationId: 'conv-7', question: 'Och förra månaden?', history }),
)
})
it('resumes with a supplied conversation_id', async () => {
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-7', created: false })
const res = await POST(
createMockRequest('/x', {
method: 'POST',
body: body({ persist: true, conversation_id: '11111111-1111-4111-8111-111111111111' }),
}),
)
const { status, body: b } = await parseJsonResponse<{ data: { conversation_id: string } }>(res)
expect(status).toBe(200)
expect(b.data.conversation_id).toBe('conv-7')
expect(resolveConv).toHaveBeenCalledWith(
supabase,
'user-1',
'company-1',
'11111111-1111-4111-8111-111111111111',
'Hur gick juli?',
undefined,
)
})
it("404s on a conversation that isn't the user's, without answering or persisting", async () => {
resolveConv.mockResolvedValue({ ok: false, reason: 'not_found' })
const res = await POST(
createMockRequest('/x', {
method: 'POST',
body: body({ persist: true, conversation_id: '22222222-2222-4222-8222-222222222222' }),
}),
)
expect(res.status).toBe(404)
expect(persistUser).not.toHaveBeenCalled()
expect(answer).not.toHaveBeenCalled()
expect(persistAssistant).not.toHaveBeenCalled()
})
it('502s on an empty answer, keeps the question, never persists a blank assistant turn', async () => {
answer.mockRejectedValue(new EmptyModelAnswerError('claude-sonnet-5'))
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ persist: true }) }))
const { status, body: b } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(502)
expect(b.error).toBe('Assistenten gav inget svar. Försök igen.')
// The user turn is written before the model call (retry keeps the
// question), but no empty assistant turn may ever land in the thread.
expect(persistUser).toHaveBeenCalled()
expect(persistAssistant).not.toHaveBeenCalled()
})
it('still 503s (no write) when no backend is configured', async () => {
aiStatus.mockReturnValue({ configured: false })
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ persist: true }) }))
expect(res.status).toBe(503)
expect(resolveConv).not.toHaveBeenCalled()
expect(persistUser).not.toHaveBeenCalled()
})
})
})
+191
View File
@@ -0,0 +1,191 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { ensureInitialized } from '@/lib/init'
import { requireAuth } from '@/lib/auth/require-auth'
import { getActiveCompanyId } from '@/lib/company/context'
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
import { guardSandbox } from '@/lib/sandbox/guard'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { getAiStatus } from '@/lib/ai'
import { createLogger } from '@/lib/logger'
import { answerAssistantQuestion } from '@/lib/agent/ask/ask-service'
import { EmptyModelAnswerError } from '@/lib/agent/ask/errors'
import {
resolveChatConversation,
loadChatHistory,
persistUserTurn,
persistAssistantTurn,
} from '@/lib/agent/ask/persist'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
// The assistant answers over the read-only MCP tools, which are registered
// into the agent tool registry by the mcp-server extension at load. Without
// this the registry is empty and the assistant falls back to snapshot-only,
// so a hosted deploy would silently lose its ledger tools.
ensureInitialized()
const log = createLogger('api.agent.ask')
// A tool-loop answer can take minutes (several model turns, each preceded by
// real report reads). The plan default cap would kill the function mid-answer
// and the client would see a silent empty stop; 300 s matches the other
// long-running model surfaces (app/api/receipt-hunt/run).
export const maxDuration = 300
// The Swedish body AskConsole's !res.ok branch renders verbatim.
const EMPTY_ANSWER_MESSAGE = 'Assistenten gav inget svar. Försök igen.'
/**
* POST /api/agent/ask: a single-call, provider-agnostic assistant answer over a
* bounded read-only tool loop.
*
* Unlike POST /api/agent/invoke (the streaming Anthropic chat runtime, which
* is gated on `assistantAvailable` and only runs on the Anthropic family),
* this endpoint answers through getAiService().generateText, so it runs on ANY
* configured backend, including an OpenAI-compatible local model. It is
* therefore gated on `configured`, not `assistantAvailable`. The service
* attaches the read-only MCP tools so it can fetch real figures (audit Option
* A / rip): a page posts its context and a question, gets one answer back.
*/
const Schema = z.object({
question: z.string().min(1).max(4000),
context: z.string().max(24_000).optional(),
tier: z.enum(['assistant', 'heavy']).optional(),
company_id: z.string().uuid().optional(),
// Chat-console persistence (opt-in). When `persist` is true, the turn is
// written to agent_conversations/agent_messages so the /chat sidebar keeps
// working. Page-scoped one-off actions (a report page asking a question)
// omit it and stay stateless. `conversation_id` resumes an existing
// general.help thread; omitted means "create one". `context_ref` binds a
// fresh thread to a page ("report:vat:2026-07") for the context chip.
persist: z.boolean().optional(),
conversation_id: z.string().uuid().nullable().optional(),
context_ref: z.string().max(200).nullable().optional(),
})
export async function POST(request: Request): Promise<Response> {
const { user, supabase, error } = await requireAuth()
if (error) return error
const rate = await checkAgentRateLimit(supabase, user.id)
if (!rate.ok) return NextResponse.json(agentRateLimitResponseBody(rate), { status: 429 })
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
}
const parsed = Schema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Ogiltig fråga.', type: 'validation_error' }, { status: 400 })
}
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
if (!companyId) return NextResponse.json({ error: 'No active company' }, { status: 400 })
const { data: membership } = await supabase
.from('company_members')
.select('user_id')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
if (capBlocked) return capBlocked
// Distinct from the paywall: no AI backend configured at all. Unlike the
// chat loop, ANY provider works here, so we gate on `configured`.
if (!getAiStatus().configured) {
return NextResponse.json(
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
{ status: 503 },
)
}
// Stateless page-scoped ask: one answer, nothing written.
if (parsed.data.persist !== true) {
try {
const result = await answerAssistantQuestion({
supabase,
companyId,
userId: user.id,
question: parsed.data.question,
pageContext: parsed.data.context,
tier: parsed.data.tier,
})
return NextResponse.json({ data: result })
} catch (err) {
if (err instanceof EmptyModelAnswerError) {
// Already logged with model + usage by ask-service.
return NextResponse.json(
{ error: EMPTY_ANSWER_MESSAGE, code: 'empty_model_answer' },
{ status: 502 },
)
}
log.error('assistant ask failed', err, { companyId, persist: false })
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
}
}
// Persisted chat-console turn: resolve/create the thread, write the question,
// answer once, write the answer. Resolve BEFORE the model call so a bad
// conversation id 404s without spending a request; the user turn is written
// before the answer so a mid-call failure still leaves the question in the
// thread (the user can retry), matching the streaming runtime's semantics.
try {
const resolved = await resolveChatConversation(
supabase,
user.id,
companyId,
parsed.data.conversation_id,
parsed.data.question,
parsed.data.context_ref,
)
if (!resolved.ok) {
return NextResponse.json({ error: 'Konversationen hittades inte.' }, { status: 404 })
}
const { conversationId } = resolved
// A resumed thread carries its earlier turns into the model call; read
// them BEFORE the new question is written so it is not sent twice. A
// thread created just now has nothing to load.
const history = resolved.created ? [] : await loadChatHistory(supabase, conversationId)
await persistUserTurn(supabase, conversationId, parsed.data.question)
const result = await answerAssistantQuestion({
supabase,
companyId,
userId: user.id,
conversationId,
question: parsed.data.question,
pageContext: parsed.data.context,
tier: parsed.data.tier,
history,
})
// answerAssistantQuestion throws EmptyModelAnswerError on an empty answer,
// so an empty assistant turn is never persisted: the thread keeps the
// question (retryable) but records no blank reply.
await persistAssistantTurn(supabase, conversationId, result.answer)
return NextResponse.json({ data: { ...result, conversation_id: conversationId } })
} catch (err) {
if (err instanceof EmptyModelAnswerError) {
// Already logged with model + usage by ask-service.
return NextResponse.json(
{ error: EMPTY_ANSWER_MESSAGE, code: 'empty_model_answer' },
{ status: 502 },
)
}
log.error('assistant ask failed', err, { companyId, persist: true })
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
}
}
@@ -0,0 +1,140 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
const checkRate = vi.fn()
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: () => checkRate(),
agentRateLimitResponseBody: () => ({ error: 'rate' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
const requireCapability = vi.fn()
vi.mock('@/lib/entitlements/has-capability', () => ({ requireCapability: () => requireCapability() }))
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
const aiStatus = vi.fn()
vi.mock('@/lib/ai', () => ({ getAiStatus: () => aiStatus() }))
const gatherCandidates = vi.fn()
vi.mock('@/lib/agent/categorize/candidates', () => ({ gatherCandidates: (...a: unknown[]) => gatherCandidates(...a) }))
const gatherUnderlag = vi.fn()
vi.mock('@/lib/agent/categorize/underlag', () => ({ gatherUnderlag: (...a: unknown[]) => gatherUnderlag(...a) }))
const selectAccount = vi.fn()
vi.mock('@/lib/agent/categorize/select-account', () => ({ selectAccount: (...a: unknown[]) => selectAccount(...a) }))
import { POST } from '../route'
// supabase router: membership + transactions + companies + company_settings.
function makeSupabase(opts: { tx?: unknown; member?: boolean } = {}) {
return {
auth: { getUser: vi.fn() },
from(table: string) {
const rows: Record<string, unknown> = {
company_members: opts.member === false ? null : { user_id: 'user-1' },
transactions: opts.tx === undefined ? { id: 'tx-1' } : opts.tx,
companies: { entity_type: 'aktiebolag' },
company_settings: { vat_registered: true },
}
const chain = {
select: () => chain,
eq: () => chain,
maybeSingle: async () => ({ data: rows[table] ?? null }),
}
return chain
},
}
}
const supabase = makeSupabase()
const VALID_TX = '11111111-1111-4111-8111-111111111111'
const body = (o: Record<string, unknown> = {}) => ({ transaction_id: VALID_TX, ...o })
beforeEach(() => {
vi.clearAllMocks()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
checkRate.mockResolvedValue({ ok: true })
requireCapability.mockResolvedValue(null)
aiStatus.mockReturnValue({ configured: true })
gatherCandidates.mockResolvedValue([{ account: '5410', label: 'Material', vatTreatment: 'standard_25', source: 'counterparty_template', confidence: 0.9 }])
gatherUnderlag.mockResolvedValue('Kvitto: Biltema, totalt 499 SEK.')
selectAccount.mockResolvedValue({
account: '5410', category: null, vatTreatment: 'standard_25', reverseCharge: false,
confidence: 0.86, modelConfidence: 'high', agreement: 1, reasoning: 'r',
choice: { kind: 'candidate', account: '5410' }, model: 'qwen3.8', fromCandidate: true,
})
})
describe('POST /api/agent/categorize', () => {
it('401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(401)
expect(selectAccount).not.toHaveBeenCalled()
})
it('resolves the session through requireAuth (withRouteContext), never a hand-rolled getUser()', async () => {
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
expect(requireAuthMock).toHaveBeenCalledTimes(1)
expect(supabase.auth.getUser).not.toHaveBeenCalled()
})
it('403 when the body names a company the caller is not a member of', async () => {
const other = '22222222-2222-4222-8222-222222222222'
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ member: false }), error: null })
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ company_id: other }) }), createMockRouteParams({}))
expect(res.status).toBe(403)
expect(selectAccount).not.toHaveBeenCalled()
})
it('uses the active company without a membership round trip when no override is given', async () => {
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
expect(res.status).toBe(200)
expect(gatherCandidates).toHaveBeenCalledWith(expect.anything(), 'company-1', expect.anything())
})
it('429 when rate limited', async () => {
checkRate.mockResolvedValue({ ok: false })
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(429)
})
it('400 on a missing/invalid transaction_id', async () => {
expect((await POST(createMockRequest('/x', { method: 'POST', body: {} }), createMockRouteParams({}))).status).toBe(400)
expect((await POST(createMockRequest('/x', { method: 'POST', body: { transaction_id: 'nope' } }), createMockRouteParams({}))).status).toBe(400)
})
it('403 without the ai capability', async () => {
requireCapability.mockResolvedValue(NextResponse.json({ error: 'pay' }, { status: 403 }))
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(403)
})
it('503 when no backend is configured', async () => {
aiStatus.mockReturnValue({ configured: false })
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
expect(status).toBe(503)
expect(b.code).toBe('ai_unconfigured')
expect(selectAccount).not.toHaveBeenCalled()
})
it('404 when the transaction is not found / not this company', async () => {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ tx: null }), error: null })
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
expect(res.status).toBe(404)
expect(selectAccount).not.toHaveBeenCalled()
})
it('returns the selection + candidate slate on the happy path', async () => {
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ samples: 3, underlag: 'Biltema AB 499 kr' }) }), createMockRouteParams({}))
const { status, body: b } = await parseJsonResponse<{
data: { account: string; confidence: number; candidates: { account: string }[] }
}>(res)
expect(status).toBe(200)
expect(b.data.account).toBe('5410')
expect(b.data.confidence).toBe(0.86)
expect(b.data.candidates[0].account).toBe('5410')
// A caller-supplied underlag is used verbatim (no server gather).
expect(gatherUnderlag).not.toHaveBeenCalled()
expect(selectAccount).toHaveBeenCalledWith(
expect.objectContaining({ entityType: 'aktiebolag', vatRegistered: true, underlag: 'Biltema AB 499 kr', samples: 3 }),
)
})
it('gathers underlag server-side when the caller did not supply it', async () => {
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
expect(gatherUnderlag).toHaveBeenCalled()
expect(selectAccount).toHaveBeenCalledWith(
expect.objectContaining({ underlag: 'Kvitto: Biltema, totalt 499 SEK.' }),
)
})
})
@@ -0,0 +1,107 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
const guardSandbox = vi.fn()
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: () => guardSandbox() }))
import { POST } from '../route'
const inserts: Record<string, unknown>[] = []
// company_settings.maybeSingle() feeds the consent gate; company_members
// feeds the membership check. Default: a member of an opted-in company.
function makeSupabase(membership: unknown = { user_id: 'user-1' }, optedIn = true) {
return {
from(table: string) {
const chain = {
select: () => chain,
eq: () => chain,
maybeSingle: async () =>
table === 'company_settings'
? { data: { data_analysis_opt_in: optedIn }, error: null }
: { data: membership, error: null },
insert: async (payload: Record<string, unknown>) => {
if (table === 'categorize_calibration_samples') inserts.push(payload)
return { error: null }
},
}
return chain
},
}
}
const supabase = makeSupabase()
const body = (o: Record<string, unknown> = {}) => ({ confidence: 0.9, booked_account: '5410', ...o })
beforeEach(() => {
vi.clearAllMocks()
inserts.length = 0
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
guardSandbox.mockResolvedValue(null)
})
describe('POST /api/agent/categorize/outcome', () => {
it('401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(401)
})
it('400 on an invalid body', async () => {
expect((await POST(createMockRequest('/x', { method: 'POST', body: { confidence: 2 } }))).status).toBe(400)
expect((await POST(createMockRequest('/x', { method: 'POST', body: { booked_account: '5410' } }))).status).toBe(400)
})
it('403 without company membership', async () => {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase(null), error: null })
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(403)
})
it('skips sandbox bookings (204, no sample)', async () => {
guardSandbox.mockResolvedValue(NextResponse.json({ error: 'sandbox' }, { status: 403 }))
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
expect(res.status).toBe(204)
expect(inserts).toHaveLength(0)
})
it('skips companies that have not opted in to data analysis (204, no sample)', async () => {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ user_id: 'user-1' }, false), error: null })
const res = await POST(
createMockRequest('/x', { method: 'POST', body: body({ proposed_account: '5410', booked_account: '5410' }) }),
)
expect(res.status).toBe(204)
expect(inserts).toHaveLength(0)
})
it('logs was_correct=true when the proposed account was booked (opted-in company)', async () => {
const res = await POST(
createMockRequest('/x', {
method: 'POST',
body: body({ proposed_account: '5410', booked_account: '5410', confidence: 0.86, source: 'counterparty_template', amount: 499 }),
}),
)
expect(res.status).toBe(204)
expect(inserts).toHaveLength(1)
expect(inserts[0]).toMatchObject({
company_id: 'company-1',
confidence: 0.86,
proposed_account: '5410',
booked_account: '5410',
was_correct: true,
source: 'counterparty_template',
amount: 499,
})
})
it('logs was_correct=false when the user booked a different account', async () => {
await POST(createMockRequest('/x', { method: 'POST', body: body({ proposed_account: '5410', booked_account: '6110' }) }))
expect(inserts[0].was_correct).toBe(false)
})
it('logs was_correct=false when there was no proposed account', async () => {
await POST(createMockRequest('/x', { method: 'POST', body: body({ proposed_account: null, booked_account: '5410' }) }))
expect(inserts[0].was_correct).toBe(false)
})
})
+89
View File
@@ -0,0 +1,89 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { getActiveCompanyId } from '@/lib/company/context'
import { isDataAnalysisOptedIn } from '@/lib/company/data-analysis'
import { guardSandbox } from '@/lib/sandbox/guard'
/**
* POST /api/agent/categorize/outcome: log one calibration sample.
*
* Called (fire-and-forget) after a user books an AI proposal: it records the
* confidence the model reported and whether the proposed account was the one
* actually booked. That corpus is what lib/agent/categorize/calibration.ts
* later fits an isotonic calibrator on, so "säker" can be made to mean ~right.
*
* Telemetry only: it never posts anything and is gated on auth + membership.
* Sandbox bookings run on seed data, so they are silently skipped (a 204) to
* keep the corpus clean. The corpus is read across companies, so it only
* collects from companies that opted in to data analysis
* (company_settings.data_analysis_opt_in, #1346): everyone else gets the same
* silent 204 and no row.
*/
const Schema = z.object({
company_id: z.string().uuid().optional(),
confidence: z.number().min(0).max(1),
proposed_account: z.string().max(20).nullable().optional(),
booked_account: z.string().min(1).max(20),
agreement: z.number().min(0).max(1).nullable().optional(),
model_confidence: z.enum(['high', 'medium', 'low']).nullable().optional(),
source: z.string().max(40).nullable().optional(),
amount: z.number().nullable().optional(),
})
const noContent = () => new Response(null, { status: 204 })
export async function POST(request: Request): Promise<Response> {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
}
const parsed = Schema.safeParse(body)
if (!parsed.success) return NextResponse.json({ error: 'Invalid body' }, { status: 400 })
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
if (!companyId) return noContent()
const { data: membership } = await supabase
.from('company_members')
.select('user_id')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
// Sandbox bookings are seed data: don't pollute the calibration corpus.
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return noContent()
// Consent gate: the corpus is analysed across companies, so a company that
// has not opted in contributes nothing (default false, no grandfathering).
if (!(await isDataAnalysisOptedIn(supabase, companyId))) return noContent()
const proposed = parsed.data.proposed_account ?? null
// Best-effort: a failed telemetry insert must never surface to the user.
try {
await supabase.from('categorize_calibration_samples').insert({
company_id: companyId,
confidence: parsed.data.confidence,
agreement: parsed.data.agreement ?? null,
model_confidence: parsed.data.model_confidence ?? null,
source: parsed.data.source ?? null,
proposed_account: proposed,
booked_account: parsed.data.booked_account,
was_correct: proposed !== null && proposed === parsed.data.booked_account,
amount: parsed.data.amount ?? null,
})
} catch {
// swallow
}
return noContent()
}
+132
View File
@@ -0,0 +1,132 @@
import { NextResponse } from 'next/server'
import { parseEntityType } from '@/lib/company/entity-type'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
import { guardSandbox } from '@/lib/sandbox/guard'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { getAiStatus } from '@/lib/ai'
import { gatherCandidates } from '@/lib/agent/categorize/candidates'
import { gatherUnderlag } from '@/lib/agent/categorize/underlag'
import { selectAccount } from '@/lib/agent/categorize/select-account'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import type { EntityType, Transaction } from '@/types'
/**
* POST /api/agent/categorize: a provider-agnostic booking proposal for one
* transaction — the auto-booking cascade end to end (Tier 1 retrieval → Tier 2
* selector), minus the write.
*
* It gathers the deterministic candidate accounts (counterparty templates,
* rules, history) with NO model call, then has the model SELECT among them
* (self-consistency sampled), and returns the proposed account + VAT +
* confidence + reasoning + the candidate slate. It never posts anything: the
* caller (the transaction row) renders the proposal as an approval card.
*
* Runs on any configured backend (Bedrock or a local model), so it is gated on
* `configured`, not `assistantAvailable` — same as /api/agent/ask.
*/
const Schema = z.object({
transaction_id: z.string().uuid(),
company_id: z.string().uuid().optional(),
/** Extracted receipt/invoice text, if the caller already has it. */
underlag: z.string().max(24_000).optional(),
/** Self-consistency samples (default 3). */
samples: z.number().int().min(1).max(5).optional(),
})
// withRouteContext enforces auth (MFA on hosted) and resolves the active
// company; the body may still name another company the caller belongs to.
export const POST = withRouteContext(
'agent.categorize',
async (request, { user, supabase, companyId: activeCompanyId }) => {
const rate = await checkAgentRateLimit(supabase, user.id)
if (!rate.ok) return NextResponse.json(agentRateLimitResponseBody(rate), { status: 429 })
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
}
const parsed = Schema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Ogiltig förfrågan.', type: 'validation_error' }, { status: 400 })
}
const companyId = parsed.data.company_id ?? activeCompanyId
// The wrapper already guarantees membership of the active company; an
// explicit company_id override must be verified the same way.
if (companyId !== activeCompanyId) {
const { data: membership } = await supabase
.from('company_members')
.select('user_id')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
if (capBlocked) return capBlocked
if (!getAiStatus().configured) {
return NextResponse.json(
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
{ status: 503 },
)
}
const { data: tx } = await supabase
.from('transactions')
.select('id, merchant_name, description, original_description, amount, date, currency, category, is_business, document_id')
.eq('id', parsed.data.transaction_id)
.eq('company_id', companyId)
.maybeSingle()
if (!tx) return NextResponse.json({ error: 'Transaktionen hittades inte.' }, { status: 404 })
const [{ data: company }, { data: settings }] = await Promise.all([
supabase.from('companies').select('entity_type').eq('id', companyId).maybeSingle(),
supabase.from('company_settings').select('vat_registered').eq('company_id', companyId).maybeSingle(),
])
try {
// Gather the matched receipt/invoice text when the caller didn't supply it:
// this is what lifts the cold-start case — the model reads the actual
// supplier + line items, not just the bank line. Best-effort; '' if none.
const underlag =
parsed.data.underlag ??
(await gatherUnderlag(
supabase,
companyId,
(tx as Transaction).id,
(tx as { document_id?: string | null }).document_id,
))
const candidates = await gatherCandidates(supabase, companyId, tx as Transaction)
const selection = await selectAccount({
transaction: {
merchantName: (tx as Transaction).merchant_name,
description: (tx as Transaction).description,
amount: (tx as Transaction).amount,
date: (tx as Transaction).date,
currency: (tx as Transaction).currency,
},
underlag,
candidates,
entityType: parseEntityType(company?.entity_type),
vatRegistered: settings?.vat_registered ?? false,
samples: parsed.data.samples,
})
return NextResponse.json({ data: { ...selection, candidates } })
} catch (err) {
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
}
},
)
+103
View File
@@ -0,0 +1,103 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
import { composeAgentProfile } from '@/lib/agent/composer'
import { guardSandbox } from '@/lib/sandbox/guard'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
const BodySchema = z.object({
// Optional override; if absent we use the user's active_company_id.
company_id: z.string().uuid().optional(),
// dry_run=true returns the composed profile without writing to agent_profiles.
dry_run: z.boolean().optional(),
})
// POST /api/agent/composer
//
// Runs the specialized accountant composer pipeline for a company:
// 1. Gathers TIC snapshot, optional SIE summary, optional banking summary.
// 2. Calls Opus 4.7 to select horizontal/vertical/modifier atoms.
// 3. Calls Sonnet 4.6 to write the Swedish profile_summary.
// 4. Persists to agent_profiles (skipped on dry_run).
// 5. Fires fire-and-forget cache pre-warm.
//
// Auth: must be a non-viewer member of the target company (it rewrites the
// company's agent_profile unless dry_run).
//
// Plan ref: dev_docs/specialized-agent-plan.md §6.
export const POST = withRouteContext('agent.composer.run', async (request, ctx) => {
const { supabase, companyId: activeCompanyId, user } = ctx
const rate = await checkAgentRateLimit(supabase, user.id)
if (!rate.ok) {
return NextResponse.json(agentRateLimitResponseBody(rate), {
status: 429,
headers: rate.retryAfterSec ? { 'Retry-After': String(rate.retryAfterSec) } : undefined,
})
}
// Tolerant parse: ops callers POST with an empty body, which is valid here.
const raw = await request.json().catch(() => ({}))
const parsed = BodySchema.safeParse(raw)
if (!parsed.success) {
return NextResponse.json(
{
error: 'Validation failed',
type: 'validation_error',
errors: parsed.error.issues.map((issue) => ({
field: issue.path.join('.'),
message: issue.message,
code: issue.code,
})),
},
{ status: 400 },
)
}
const body = parsed.data
const companyId = body.company_id ?? activeCompanyId
// Defense in depth alongside RLS: confirm membership before composing, and
// require a non-viewer role: the composer rewrites agent_profiles.
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) {
return NextResponse.json(
{
error: {
code: 'NOT_COMPANY_MEMBER',
message: 'Du är inte medlem i detta företag.',
message_en: 'Not a member of this company.',
},
},
{ status: 403 },
)
}
if (membership.role === 'viewer') {
return NextResponse.json(
{
error: {
code: 'WRITE_PERMISSION_REQUIRED',
message: 'Du har endast läsbehörighet i detta företag.',
message_en: 'You only have read access in this company.',
},
},
{ status: 403 },
)
}
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
if (capBlocked) return capBlocked
const composed = await composeAgentProfile(supabase, companyId, { dryRun: body.dry_run })
return NextResponse.json({ data: composed })
})
@@ -0,0 +1,61 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, createMockRouteParams, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: (...a: unknown[]) => requireAuthMock(...a) }))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({ requireWritePermission: vi.fn().mockResolvedValue({ ok: true }) }))
const rejectPending = vi.fn()
vi.mock('@/lib/agent/pending/reject-conversation-pending', () => ({
rejectPendingForConversation: (...a: unknown[]) => rejectPending(...a),
}))
import { POST } from '../reject-pending/route'
const params = () => createMockRouteParams({ id: 'conv-1' })
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: mockSupabase, error: null })
rejectPending.mockResolvedValue(3)
})
describe('POST /api/agent/conversations/[id]/reject-pending', () => {
it('401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({ user: null, supabase: mockSupabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
expect((await parseJsonResponse(res)).status).toBe(401)
})
it('404 when the conversation is not the caller’s', async () => {
enqueue({ data: null }) // conversation ownership lookup misses
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
expect(res.status).toBe(404)
expect(rejectPending).not.toHaveBeenCalled()
})
it('404 when the caller is no longer a member of the company', async () => {
enqueue({ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1' } }) // owns it
enqueue({ data: null }) // membership lookup misses
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
expect(res.status).toBe(404)
expect(rejectPending).not.toHaveBeenCalled()
})
it('clears the conversation’s pending proposals and returns the count', async () => {
enqueue({ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1' } })
enqueue({ data: { role: 'owner' } })
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
const { status, body } = await parseJsonResponse<{ data: { cleared: number } }>(res)
expect(status).toBe(200)
expect(body.data.cleared).toBe(3)
expect(rejectPending).toHaveBeenCalledWith(mockSupabase, 'company-1', 'conv-1')
})
})
@@ -0,0 +1,50 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { rejectPendingForConversation } from '@/lib/agent/pending/reject-conversation-pending'
// POST /api/agent/conversations/[id]/reject-pending
//
// Rejects every still-pending proposal the assistant staged in this
// conversation — the chat's "clear the proposals I didn't approve" action, so
// users don't have to reject leftovers one by one in Granskning.
const notFound = () =>
NextResponse.json(
{
error: {
code: 'CONVERSATION_NOT_FOUND',
message: 'Konversationen hittades inte.',
message_en: 'Conversation not found.',
},
},
{ status: 404 },
)
export const POST = withRouteContext(
'agent.conversations.reject_pending',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, user } = ctx
// Conversations are user-scoped: prove ownership before touching its rows.
const { data: conv } = await supabase
.from('agent_conversations')
.select('id, company_id, user_id')
.eq('id', id)
.eq('user_id', user.id)
.maybeSingle()
if (!conv) return notFound()
// Defense in depth alongside RLS: still a member of the conversation's company.
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', conv.company_id)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return notFound()
const cleared = await rejectPendingForConversation(supabase, conv.company_id as string, id)
return NextResponse.json({ data: { cleared } })
},
)
+165
View File
@@ -0,0 +1,165 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { rejectPendingForConversation } from '@/lib/agent/pending/reject-conversation-pending'
// GET /api/agent/conversations/[id]
//
// Returns one conversation + its messages in chronological order. The chat
// page hydrates with this on mount; the agent loop then continues via
// /api/agent/invoke with the conversation_id.
//
// PATCH /api/agent/conversations/[id]
//
// Updates pin/archive state or title. The chat list relies on these.
const PatchSchema = z.object({
pinned: z.boolean().nullable().optional(),
archived: z.boolean().nullable().optional(),
title: z.string().min(1).max(200).nullable().optional(),
})
const notFound = () =>
NextResponse.json(
{
error: {
code: 'CONVERSATION_NOT_FOUND',
message: 'Konversationen hittades inte.',
message_en: 'Conversation not found.',
},
},
{ status: 404 },
)
export const GET = withRouteContext(
'agent.conversations.get',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, user } = ctx
// Conversations are user-scoped: fetched by ownership rather than the
// active company, so a user can open their own conversations in any
// company they belong to.
const { data: conv, error: convErr } = await supabase
.from('agent_conversations')
.select(
'id, company_id, user_id, intent_id, context_ref, title, pinned, archived, last_message_at, created_at',
)
.eq('id', id)
.eq('user_id', user.id)
.maybeSingle()
if (convErr) throw convErr
if (!conv) return notFound()
// Defense in depth alongside RLS: the caller must still be a member of
// the conversation's company (they may have been removed since).
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', conv.company_id)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return notFound()
const { data: messages, error: msgErr } = await supabase
.from('agent_messages')
.select('id, role, content, tool_use_id, hidden, created_at')
.eq('conversation_id', id)
.order('created_at', { ascending: true })
if (msgErr) throw msgErr
// Proposals this conversation staged that nobody has answered yet.
//
// Approval cards ride on the streamed `staged_operation` events, which are
// not persisted, so a resumed thread rendered the tool trace and the answer
// but silently dropped the card: the proposal then sat in Granskning for
// its full 30 days with nothing in the conversation pointing at it.
// run-turn stamps agent_metadata.conversation_id on every staged row, so
// the still-open ones can be re-attached here.
const { data: staged, error: stagedErr } = await supabase
.from('pending_operations')
.select('id, operation_type, title, risk_level, preview_data, created_at')
.eq('company_id', conv.company_id)
.eq('status', 'pending')
.eq('agent_metadata->>conversation_id', id)
.order('created_at', { ascending: true })
// Do not swallow this: silently returning an empty list would drop the very
// proposals this query exists to restore, and the thread would look like it
// never staged anything. Same handling as the message query above.
if (stagedErr) throw stagedErr
return NextResponse.json({
data: {
conversation: conv,
messages: messages ?? [],
staged_operations: staged ?? [],
},
})
},
)
export const PATCH = withRouteContext(
'agent.conversations.update',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, user, log } = ctx
const validation = await validateBody(request, PatchSchema, {
log,
operation: 'agent.conversations.update',
})
if (!validation.success) return validation.response
const body = validation.data
const update: Record<string, unknown> = {}
if (body.pinned != null) update.pinned = body.pinned
if (body.archived != null) update.archived = body.archived
if (body.title != null) update.title = body.title
if (Object.keys(update).length === 0) {
return NextResponse.json(
{
error: {
code: 'NOTHING_TO_UPDATE',
message: 'Inget att uppdatera.',
message_en: 'Nothing to update.',
},
},
{ status: 400 },
)
}
// Defense in depth: verify ownership before update so a 404 is returned
// (instead of relying solely on RLS, which would silently 0-row).
const { data: existing } = await supabase
.from('agent_conversations')
.select('user_id, company_id')
.eq('id', id)
.eq('user_id', user.id)
.maybeSingle()
if (!existing) return notFound()
const { data, error } = await supabase
.from('agent_conversations')
.update(update)
.eq('id', id)
.eq('user_id', user.id)
.eq('company_id', existing.company_id)
.select('id, intent_id, context_ref, title, pinned, archived, last_message_at, created_at')
.single()
if (error) throw error
// Archiving a thread means "I'm done with it": clear any proposals the
// assistant staged here that the user never acted on, so they don't linger
// in Granskning. Best-effort — a failure here must not fail the archive.
if (body.archived === true) {
try {
await rejectPendingForConversation(supabase, existing.company_id as string, id)
} catch {
// ignored
}
}
return NextResponse.json({ data })
},
)
@@ -0,0 +1,121 @@
/**
* GET /api/agent/conversations/[id] returns the conversation's still-open
* proposals alongside its messages.
*
* Approval cards live in streamed events that are never persisted, so without
* these rows a resumed thread renders the tool trace and the answer but drops
* the card, and the proposal waits out its 30-day expiry in Granskning with
* nothing in the conversation pointing at it.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createMockRequest,
createMockRouteParams,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, enqueueMany, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
import { GET } from '../[id]/route'
const CONV = { id: 'conv-1', company_id: 'company-1', user_id: 'user-1', intent_id: 'general.help' }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: mockSupabase, error: null })
})
describe('GET /api/agent/conversations/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(
createMockRequest('/api/agent/conversations/conv-1'),
createMockRouteParams({ id: 'conv-1' }),
)
expect((await parseJsonResponse(res)).status).toBe(401)
})
it('returns 404 for a conversation the caller does not own', async () => {
enqueue({ data: null }) // conversation lookup filters on user_id
const res = await GET(
createMockRequest('/api/agent/conversations/conv-1'),
createMockRouteParams({ id: 'conv-1' }),
)
expect((await parseJsonResponse(res)).status).toBe(404)
})
it('returns unanswered proposals alongside the messages', async () => {
enqueueMany([
{ data: CONV }, // conversation
{ data: { role: 'owner' } }, // company_members
{ data: [{ role: 'assistant', content: [] }] }, // agent_messages
{
data: [
{
id: 'op-1',
operation_type: 'gnubok_categorize_transaction',
title: 'Kontering: Circle K',
risk_level: 'low',
preview_data: {},
},
],
}, // pending_operations
])
const res = await GET(
createMockRequest('/api/agent/conversations/conv-1'),
createMockRouteParams({ id: 'conv-1' }),
)
const { status, body } = await parseJsonResponse<{
data: { staged_operations: { id: string }[]; messages: unknown[] }
}>(res)
expect(status).toBe(200)
expect(body.data.messages).toHaveLength(1)
expect(body.data.staged_operations).toHaveLength(1)
expect(body.data.staged_operations[0]!.id).toBe('op-1')
})
it('returns an empty list rather than failing when nothing is staged', async () => {
enqueueMany([
{ data: CONV },
{ data: { role: 'owner' } },
{ data: [] },
{ data: null }, // no rows at all
])
const res = await GET(
createMockRequest('/api/agent/conversations/conv-1'),
createMockRouteParams({ id: 'conv-1' }),
)
const { status, body } = await parseJsonResponse<{
data: { staged_operations: unknown[] }
}>(res)
expect(status).toBe(200)
expect(body.data.staged_operations).toEqual([])
})
})
+71
View File
@@ -0,0 +1,71 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateQuery } from '@/lib/api/validate'
// GET /api/agent/conversations
//
// Query params:
// archived: 'true' | 'false' (default 'false')
// pinned: 'true' filters to pinned only
// intent: 'general.help' (or any intent id), filter
// q: case-insensitive substring match on title/context_ref
// limit: 1..200, default 50
//
// Returns: { data: [{ id, intent_id, context_ref, title, pinned, archived,
// last_message_at, created_at }] }
//
// Ordered: pinned first (within archived bucket), then last_message_at desc.
// Used by the /chat sidebar and "resume conversation" UI in the sheet.
const ListQuerySchema = z.object({
archived: z.enum(['true', 'false']).default('false'),
pinned: z.enum(['true', 'false']).optional(),
intent: z.string().min(1).optional(),
q: z.string().optional(),
limit: z.coerce.number().int().min(1).max(200).default(50),
})
export const GET = withRouteContext('agent.conversations.list', async (request, ctx) => {
const { supabase, companyId, user, log } = ctx
const validated = validateQuery(request, ListQuerySchema, {
log,
operation: 'agent.conversations.list',
})
if (!validated.success) return validated.response
const { archived, pinned, intent, limit } = validated.data
const q = validated.data.q?.trim() ?? ''
let query = supabase
.from('agent_conversations')
.select(
'id, intent_id, context_ref, title, pinned, archived, last_message_at, last_message_preview, created_at',
)
.eq('company_id', companyId)
// Conversations are user-scoped within a company — one member must not
// see another's (see [id]/route.ts). The RLS policy is company-scoped,
// so this filter is what actually prevents cross-member leakage of
// titles and last_message_preview snippets.
.eq('user_id', user.id)
.eq('archived', archived === 'true')
if (pinned === 'true') query = query.eq('pinned', true)
if (intent) query = query.eq('intent_id', intent)
if (q.length > 0) {
// Pattern is sanitized via Postgres' percent-handling; ilike accepts the
// % wildcard and we only inject the user's substring between them.
const safe = q.replace(/[%_]/g, (m) => `\\${m}`)
query = query.or(`title.ilike.%${safe}%,context_ref.ilike.%${safe}%`)
}
// Sort: pinned first, then most recent message.
query = query
.order('pinned', { ascending: false })
.order('last_message_at', { ascending: false, nullsFirst: false })
.limit(limit)
const { data, error } = await query
if (error) throw error
return NextResponse.json({ data: data ?? [] })
})
+108
View File
@@ -0,0 +1,108 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { ensureInitialized } from '@/lib/init'
import { eventBus } from '@/lib/events/bus'
// The event bus is a module-level singleton and extension handlers are wired
// by this call. Without it at module level the emit below goes nowhere and the
// vote is silently dropped, which is exactly the failure this route exists to
// fix.
ensureInitialized()
// POST /api/agent/feedback
//
// A thumbs-up or thumbs-down on one assistant answer.
//
// The buttons have existed since the message-actions pass but were wired to
// nothing: they animated, and the vote died in component state. An affordance
// that looks like it reports something and does not is worse than no
// affordance, because it spends the user's goodwill once and silently.
//
// This emits the SAME `agent.feedback` event the gnubok_feedback MCP tool
// emits, with actorType 'user'. The product team already queries event_log for
// that type, so votes from the chat land in the existing triage flow rather
// than in a second place someone has to remember to look at. That is also why
// there is no migration here: event_log takes the payload as jsonb and already
// treats agent.* as telemetry with the longer retention.
const BodySchema = z.object({
conversation_id: z.string().uuid(),
sentiment: z.enum(['positive', 'negative']),
// Which answer, so a vote can be traced to the turn it was about.
message_index: z.number().int().min(0).optional(),
})
export const POST = withRouteContext(
'agent.feedback.create',
async (request, ctx) => {
const { supabase, companyId, user, log } = ctx
const validation = await validateBody(request, BodySchema, {
log,
operation: 'agent.feedback.create',
})
if (!validation.success) return validation.response
const body = validation.data
// The conversation id comes from the client, so it is checked the same way
// /api/agent/invoke checks it: without this, any member could attach
// feedback to another member's thread, and the triage backlog would carry
// rows whose conversation the reporter never saw.
const { data: conversation } = await supabase
.from('agent_conversations')
.select('id, user_id, company_id, intent_id')
.eq('id', body.conversation_id)
.maybeSingle()
if (
!conversation ||
conversation.user_id !== user.id ||
conversation.company_id !== companyId
) {
return NextResponse.json(
{
error: {
code: 'CONVERSATION_NOT_FOUND',
message: 'Konversationen hittades inte.',
message_en: 'Conversation not found.',
},
},
{ status: 404 },
)
}
await eventBus.emit({
type: 'agent.feedback',
payload: {
// Deliberately NOT free text. A comment box here would put whatever
// the user typed, in an accounting product, verbatim into event_log
// under telemetry retention: names, personnummer, client details. The
// vote carries only what it needs to be actionable, which is the intent
// and which answer it was about. If a comment field is ever wanted, it
// needs its own data-classification and redaction decision first, made
// with the UI in front of it rather than as an unused parameter.
context: [
`Chattbetyg på svar i ${conversation.intent_id}.`,
body.message_index === undefined ? null : `(svar #${body.message_index})`,
]
.filter(Boolean)
.join(' '),
sentiment: body.sentiment,
suggestion: null,
toolName: null,
skillSlug: null,
sessionId: conversation.id,
actorType: 'user',
actorId: user.id,
actorLabel: null,
userId: user.id,
companyId,
},
})
return NextResponse.json({ data: { recorded: true } })
},
{ requireWrite: true },
)
+370
View File
@@ -0,0 +1,370 @@
import { createClient } 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 { getActiveCompanyId } from '@/lib/company/context'
import { getIntent } from '@/lib/agent/intents/registry'
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
import { runChatTurn, friendlyModelError } from '@/lib/agent/chat/run-turn'
import { getAiStatus } from '@/lib/ai'
import { guardSandbox } from '@/lib/sandbox/guard'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
// Make sure extensions are loaded: the chat loop dispatches against the
// agent tool registry which is populated by the mcp-server extension at load.
ensureInitialized()
// Deep turns (thinking at high/xhigh effort, up to 12 tool iterations, a
// 15-27k-token prompt prefix) can outlive the plan default duration cap; a
// function killed mid-stream closes the NDJSON stream cleanly, which the chat
// used to render as silent success. 300 s matches the other long-running model
// surfaces (app/api/receipt-hunt/run, app/api/agent/ask).
export const maxDuration = 300
// Hard cap on the per-turn user input. Generous for a chat composer (about
// 5k words / 20 pages) but bounds Bedrock token cost if the rate limiter is
// ever fail-open and a client floods large payloads.
const MAX_USER_MESSAGE_LEN = 20_000
const BodySchema = z.object({
intent_id: z.string().min(1).max(200),
// Existing conversation to resume; if omitted, the route creates one. The
// chat sheet's React state holds the conversation id as `string | null`
// and serializes `null` on the first turn, so accept null alongside
// undefined and treat both as "no existing conversation".
conversation_id: z.string().uuid().nullable().optional(),
// Optional company override; defaults to active_company_id.
company_id: z.string().uuid().nullable().optional(),
// The user's message (or, on the first turn, this is empty and we send the
// intent's prompt template instead). Capped to bound LLM cost.
user_message: z.string().max(MAX_USER_MESSAGE_LEN).nullable().optional(),
// Intent-specific capture args (e.g. { transaction_id: '...' } for
// transaction.categorization). Used only on the first turn to build the
// prompt template. Each value is bounded so capture inputs can't be a
// megabyte each; the dispatcher rejects oversize values upfront.
intent_args: z
.record(z.string().max(120), z.unknown())
.nullable()
.optional()
.refine(
(v) => {
if (!v) return true
try {
return JSON.stringify(v).length <= MAX_USER_MESSAGE_LEN
} catch {
return false
}
},
{ message: 'intent_args too large' },
),
// Optional context_ref for the conversation row, e.g. 'transaction:<id>'.
context_ref: z.string().max(200).nullable().optional(),
// When true (and user_message is provided), persist the turn but flag it
// hidden so it doesn't render as a user bubble on resume. Used by the chat's
// rejection-correction flow (ApprovalCard → AgentChat) to feed the agent a
// synthetic correction without showing it as something the user typed.
user_message_hidden: z.boolean().nullable().optional(),
})
// POST /api/agent/invoke
//
// Streams NDJSON events from the chat loop. Each line is a JSON object whose
// `kind` identifies the event type: see lib/agent/chat/run-turn.ts StreamEvent.
//
// Auth: the user must be a member of the resolved company.
//
// Plan ref: dev_docs/specialized-agent-plan.md §9 (chat loop).
export async function POST(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
// Generous per-user rate limit: bounds runaway Bedrock spend (loop-firing
// sessions). Fails open on infra error.
const rate = await checkAgentRateLimit(supabase, user.id)
if (!rate.ok) {
return NextResponse.json(agentRateLimitResponseBody(rate), {
status: 429,
headers: rate.retryAfterSec ? { 'Retry-After': String(rate.retryAfterSec) } : undefined,
})
}
let body: z.infer<typeof BodySchema>
try {
body = BodySchema.parse(await request.json())
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? getUserErrorMessage(err) : 'Invalid body' },
{ status: 400 },
)
}
const intent = getIntent(body.intent_id)
if (!intent) {
return NextResponse.json({ error: `Unknown intent: ${body.intent_id}` }, { status: 400 })
}
const companyId = body.company_id ?? (await getActiveCompanyId(supabase, user.id))
if (!companyId) return NextResponse.json({ error: 'No active company' }, { status: 400 })
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
// No Anthropic Bedrock calls in the sandbox: the demo runs entirely on
// seed data and the assistant is gated to a "look, don't touch" preview.
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
if (capBlocked) return capBlocked
// Distinct from the paywall: the deployment has no AI backend the chat
// loop can run on (no credentials, or an OpenAI-compatible endpoint, which
// the loop does not speak yet). Answer up front instead of opening a
// stream that dies on the first model call.
if (!getAiStatus().assistantAvailable) {
return NextResponse.json(
{
error: 'Assistenten är inte konfigurerad på den här installationen.',
code: 'ai_unconfigured',
},
{ status: 503 },
)
}
// Resolve the conversation BEFORE any side effect below (the onboarding
// intake stamp): a request that is about to be rejected must not write.
let conversationId = body.conversation_id ?? null
if (conversationId) {
// A resumed conversation id comes straight from the client, so ownership
// has to be proven here. RLS on agent_conversations/agent_messages is
// COMPANY-scoped (migration 20260517204000), not user-scoped, so RLS alone
// would happily load a colleague's thread into the prompt and append this
// user's turns to it. The conversations list route filters on user_id for
// exactly this reason; the same rule applies to the turn itself.
//
// The company check matters too: a user who belongs to several companies
// must not resume a thread from company B while the turn runs with company
// A's ledger, tools and staged operations.
const { data: conv } = await supabase
.from('agent_conversations')
.select('id, user_id, company_id, intent_id')
.eq('id', conversationId)
.maybeSingle()
if (!conv || conv.user_id !== user.id || conv.company_id !== companyId) {
// Same response for "doesn't exist" and "isn't yours": a 403 here would
// confirm that someone else's conversation id is real.
return NextResponse.json({ error: 'Konversationen hittades inte.' }, { status: 404 })
}
// The intent decides the tool loadout and the system prompt. Letting a
// resumed thread switch intent mid-conversation would swap the tool
// whitelist under history the model has already been shown.
if (conv.intent_id !== body.intent_id) {
return NextResponse.json(
{ error: 'Konversationen hör till ett annat sammanhang.' },
{ status: 400 },
)
}
}
// onboarding.intake completion signal: once the user has actually
// engaged (typed a real reply, not the auto-fired greeting prompt that
// mounts the chat), stamp intake_completed_at on the profile so re-entry
// logic and opportunistic follow-up logic in other intents can tell the
// intake happened. Idempotent: the IS NULL guard ensures we never
// overwrite the first engagement timestamp. Best-effort: failure here
// doesn't break the chat; the next user turn retries.
if (
body.intent_id === 'onboarding.intake' &&
typeof body.user_message === 'string' &&
body.user_message.trim().length > 0 &&
body.user_message_hidden !== true
) {
try {
await supabase
.from('agent_profiles')
.update({ intake_completed_at: new Date().toISOString() })
.eq('company_id', companyId)
.is('intake_completed_at', null)
} catch {
// ignored: see comment above
}
}
// Load lightweight company + user signals for the system prompt.
const [{ data: company }, { data: profile }] = await Promise.all([
supabase.from('companies').select('name').eq('id', companyId).single(),
supabase.from('profiles').select('full_name').eq('id', user.id).single(),
])
const companyName = company?.name ?? ''
const firstName = profile?.full_name?.split(' ')[0] ?? null
// Create the conversation row when this is a fresh thread.
if (!conversationId) {
const { data: newConv, error: convErr } = await supabase
.from('agent_conversations')
.insert({
company_id: companyId,
user_id: user.id,
intent_id: body.intent_id,
context_ref: body.context_ref ?? null,
title: intent.sheetTitle,
})
.select('id')
.single()
if (convErr || !newConv) {
return NextResponse.json(
{ error: getUserErrorMessage(convErr) ?? 'Failed to create conversation' },
{ status: 500 },
)
}
conversationId = newConv.id as string
}
// Compute the user message to send to Anthropic. On the first turn (no
// user_message provided), we run the intent's capture + promptTemplate
// pipeline so the prompt is anchored on the page context the user
// clicked from.
let effectiveUserMessage = body.user_message ?? ''
// When the caller didn't supply a user_message, we synthesize one from the
// intent's promptTemplate. Mark that synthetic turn hidden so the UI
// doesn't render the template scaffolding as a user bubble on resume. The
// client can also explicitly request a hidden turn (rejection correction)
// even when it DID supply a user_message.
let userMessageHidden = body.user_message_hidden === true
// Set on a first turn, where the prompt template needs it anyway; handed to
// runChatTurn so the system prompt reuses it instead of re-reading.
let preloadedProfileSummary: string | null | undefined
if (!effectiveUserMessage) {
try {
const captured = await intent.capture(body.intent_args ?? {}, {
supabase,
userId: user.id,
companyId,
})
const [profileSummary, memory] = await Promise.all([
loadProfileSummary(supabase, companyId),
loadRankedMemory(supabase, companyId, 30),
])
effectiveUserMessage = intent.promptTemplate({
captured,
profileSummary,
activeMemory: memory,
})
// Hand it to the turn so it doesn't re-read it for the system prompt.
preloadedProfileSummary = profileSummary
userMessageHidden = true
} catch (err) {
return NextResponse.json(
{
error:
err instanceof Error
? `Capture failed: ${getUserErrorMessage(err)}`
: 'Capture failed',
},
{ status: 500 },
)
}
}
// Stream: NDJSON events from the chat loop.
const encoder = new TextEncoder()
// Conversation id is set above; capture into a non-null local for the
// streaming closure's first emission.
const convId: string = conversationId
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
const emit = (event: unknown): boolean => {
try {
controller.enqueue(encoder.encode(JSON.stringify(event) + '\n'))
return true
} catch {
return false
}
}
// Surface the conversation id so the client can resume with it.
emit({ kind: 'conversation', conversation_id: convId })
try {
await runChatTurn({
supabase,
userId: user.id,
companyId,
companyName,
firstName,
intent,
conversationId: convId,
userMessage: effectiveUserMessage,
userMessageHidden,
persist: true,
preloadedProfileSummary,
emit: (event) => emit(event),
})
} catch (err) {
// run-turn already emitted a friendly error before re-throwing; emit a
// normalized one here too so this outer catch never overwrites it with a
// raw AWS SDK string.
emit({
kind: 'error',
message: friendlyModelError(err),
})
} finally {
try {
controller.close()
} catch {
// Already closed
}
}
},
})
return new Response(stream, {
headers: {
'Content-Type': 'application/x-ndjson; charset=utf-8',
'Cache-Control': 'no-store',
'X-Accel-Buffering': 'no',
},
})
}
async function loadProfileSummary(
supabase: Awaited<ReturnType<typeof createClient>>,
companyId: string,
): Promise<string | null> {
const { data } = await supabase
.from('agent_profiles')
.select('profile_summary')
.eq('company_id', companyId)
.maybeSingle()
return (data?.profile_summary as string | null) ?? null
}
async function loadRankedMemory(
supabase: Awaited<ReturnType<typeof createClient>>,
companyId: string,
cap: number,
): Promise<{ content: string; kind: string }[]> {
const { data } = await supabase
.from('agent_memory')
.select('content, kind, relevance_score, last_accessed_at')
.eq('company_id', companyId)
.eq('is_active', true)
.order('relevance_score', { ascending: false })
.order('last_accessed_at', { ascending: false, nullsFirst: false })
.limit(cap)
return (data ?? []).map((r: { content: string; kind: string }) => ({
content: r.content,
kind: r.kind,
}))
}
@@ -0,0 +1,88 @@
/**
* Tests for GET /api/agent/knowledge (the "Vad din agent vet" data source for
* the Kunskap tab in the assistant settings hub). Exercises the route through
* the real withRouteContext wrapper, mocking auth/company and the three
* ledger-context builders. Covers auth 401, no-company 400, and the happy path
* aggregation shape.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
const getActiveCompanyIdMock = vi.fn()
const getCompanyDisplayNameMock = vi.fn()
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
getCompanyDisplayName: (...args: unknown[]) => getCompanyDisplayNameMock(...args),
}))
const buildLedgerContextMock = vi.fn()
vi.mock('@/lib/agent-context/ledger-context', () => ({
buildLedgerContext: (...args: unknown[]) => buildLedgerContextMock(...args),
}))
const buildDeepEntitiesMock = vi.fn()
vi.mock('@/lib/agent-context/ledger-deep', () => ({
buildDeepEntities: (...args: unknown[]) => buildDeepEntitiesMock(...args),
}))
const buildAgentCompetenceMock = vi.fn()
vi.mock('@/lib/agent-context/agent-competence', () => ({
buildAgentCompetence: (...args: unknown[]) => buildAgentCompetenceMock(...args),
}))
import { GET } from '../route'
describe('GET /api/agent/knowledge', () => {
beforeEach(() => {
vi.clearAllMocks()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
getActiveCompanyIdMock.mockResolvedValue('company-1')
getCompanyDisplayNameMock.mockResolvedValue('Acme AB')
buildLedgerContextMock.mockResolvedValue({ meta: { coverage: {} }, explicit_rules: [], vat_profile: {}, conventions: {} })
buildDeepEntitiesMock.mockResolvedValue({ counterparty_entities: [], supplier_entities: [] })
buildAgentCompetenceMock.mockResolvedValue({ atoms: [], facts: [] })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 400 when there is no active company', async () => {
getActiveCompanyIdMock.mockResolvedValue(null)
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('aggregates the ledger context, deep entities, competence and company name', async () => {
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{
data: { context: unknown; deep: unknown; competence: unknown; companyName: string }
}>(res)
expect(status).toBe(200)
expect(body.data.companyName).toBe('Acme AB')
expect(body.data.context).toEqual({ meta: { coverage: {} }, explicit_rules: [], vat_profile: {}, conventions: {} })
expect(body.data.deep).toEqual({ counterparty_entities: [], supplier_entities: [] })
expect(body.data.competence).toEqual({ atoms: [], facts: [] })
// each builder was called with the resolved supabase + companyId
expect(buildLedgerContextMock).toHaveBeenCalledWith(supabase, 'company-1')
expect(buildDeepEntitiesMock).toHaveBeenCalledWith(supabase, 'company-1')
expect(buildAgentCompetenceMock).toHaveBeenCalledWith(supabase, 'company-1')
})
})
+30
View File
@@ -0,0 +1,30 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getCompanyDisplayName } from '@/lib/company/context'
import { buildLedgerContext } from '@/lib/agent-context/ledger-context'
import { buildDeepEntities } from '@/lib/agent-context/ledger-deep'
import { buildAgentCompetence } from '@/lib/agent-context/agent-competence'
// GET /api/agent/knowledge
//
// Read-only transparency surface for "Vad din agent vet": the exact ledger
// context the AI agent reads before booking, plus the deep entity-resolved
// profile and the agent's competence. Powers the Kunskap tab in the assistant
// settings hub (client-fetched so it renders identically in the full-page
// settings rail and the routed settings modal, which both mount the same
// propless content component). Derived per request from live bookings; never
// cached, so a fixed profile can't go stale.
export const GET = withRouteContext('agent.knowledge.get', async (_request, ctx) => {
const { supabase, companyId } = ctx
const [context, deep, competence, companyName] = await Promise.all([
buildLedgerContext(supabase, companyId),
buildDeepEntities(supabase, companyId),
buildAgentCompetence(supabase, companyId),
getCompanyDisplayName(supabase, companyId),
])
return NextResponse.json({
data: { context, deep, competence, companyName: companyName ?? '' },
})
})
+94
View File
@@ -0,0 +1,94 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
// PATCH /api/agent/memory/[id]
//
// Mutate a single memory entry. Powers the list/edit/pin/dismiss affordances
// on /settings/agent-memory (plan §11).
//
// content: edit the durable text (kind never changes; that would
// muddle the audit lineage). Append-only is preserved by
// superseded_by chains when an upstream caller wants it; the
// transparency UI is allowed to overwrite in place because
// the row's `updated_at` already documents the edit.
// is_pinned: boost into the top-N prompt block regardless of score.
// is_active: false = dismiss (removes from ranking pool); true = restore.
//
// RLS scopes to user_company_ids(); we ALSO re-verify membership for the
// row's company_id as defense in depth before mutating.
const PatchSchema = z
.object({
content: z.string().min(2).max(2000).optional(),
is_pinned: z.boolean().optional(),
is_active: z.boolean().optional(),
})
.refine(
(v) => v.content !== undefined || v.is_pinned !== undefined || v.is_active !== undefined,
{ message: 'Nothing to update' },
)
const notFound = () =>
NextResponse.json(
{
error: {
code: 'MEMORY_NOT_FOUND',
message: 'Minnet hittades inte.',
message_en: 'Memory not found.',
},
},
{ status: 404 },
)
export const PATCH = withRouteContext(
'agent.memory.update',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, user, log } = ctx
const validation = await validateBody(request, PatchSchema, {
log,
operation: 'agent.memory.update',
})
if (!validation.success) return validation.response
const body = validation.data
const update: Record<string, unknown> = {}
if (body.content !== undefined) update.content = body.content
if (body.is_pinned !== undefined) update.is_pinned = body.is_pinned
if (body.is_active !== undefined) update.is_active = body.is_active
// Look up the row's company_id and re-check membership before mutating.
const { data: existing } = await supabase
.from('agent_memory')
.select('company_id')
.eq('id', id)
.maybeSingle()
if (!existing) return notFound()
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', existing.company_id)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return notFound()
const { data, error } = await supabase
.from('agent_memory')
.update(update)
.eq('id', id)
.eq('company_id', existing.company_id)
.select(
'id, kind, content, source, source_ref, relevance_score, is_pinned, is_active, last_accessed_at, created_at, updated_at',
)
.maybeSingle()
if (error) throw error
if (!data) return notFound()
return NextResponse.json({ data })
},
{ requireWrite: true },
)
@@ -0,0 +1,300 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
createMockRouteParams,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
const getActiveCompanyIdMock = vi.fn()
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
}))
const requireWritePermissionMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWritePermissionMock(...args),
}))
import { GET, POST } from '../route'
import { PATCH } from '../[id]/route'
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
getActiveCompanyIdMock.mockResolvedValue('company-1')
requireWritePermissionMock.mockResolvedValue({ ok: true })
})
describe('GET /api/agent/memory', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
const { status, body } = await parseJsonResponse<{ error: string }>(response)
expect(status).toBe(401)
expect(body.error).toBe('Unauthorized')
})
it('returns 400 when no active company', async () => {
getActiveCompanyIdMock.mockResolvedValue(null)
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
})
it('returns rows for the active company', async () => {
const rows = [
{
id: 'mem-1',
kind: 'fact',
content: 'Räkenskapsår jan-dec',
source: 'composer',
source_ref: null,
relevance_score: 0.5,
is_pinned: false,
is_active: true,
last_accessed_at: null,
created_at: '2026-05-10T09:00:00Z',
updated_at: '2026-05-10T09:00:00Z',
},
]
enqueue({ data: rows })
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
const { status, body } = await parseJsonResponse<{ data: typeof rows }>(response)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
expect(body.data[0].id).toBe('mem-1')
})
it('does not require write permission for read', async () => {
enqueue({ data: [] })
await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
expect(requireWritePermissionMock).not.toHaveBeenCalled()
})
})
describe('POST /api/agent/memory', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const response = await POST(
createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'hello world' },
}),
createMockRouteParams({}),
)
expect(response.status).toBe(401)
})
it('blocks viewers via requireWritePermission', async () => {
const { NextResponse } = await import('next/server')
requireWritePermissionMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
})
const response = await POST(
createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'hello world' },
}),
createMockRouteParams({}),
)
expect(response.status).toBe(403)
})
it('rejects too-short content', async () => {
const response = await POST(
createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'x' },
}),
createMockRouteParams({}),
)
expect(response.status).toBe(400)
})
it('inserts and returns the row on happy path', async () => {
const inserted = {
id: 'mem-2',
kind: 'fact',
content: 'En sak att komma ihåg',
source: 'user_taught',
source_ref: null,
relevance_score: 1,
is_pinned: false,
is_active: true,
last_accessed_at: null,
created_at: '2026-05-18T10:00:00Z',
updated_at: '2026-05-18T10:00:00Z',
}
// Defense-in-depth: body company_id membership re-check happens after
// requireWritePermission. POST flow now is: (1) company_members lookup,
// (2) insert.
enqueue({ data: { role: 'member' } })
enqueue({ data: inserted })
const response = await POST(
createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'En sak att komma ihåg' },
}),
createMockRouteParams({}),
)
const { status, body } = await parseJsonResponse<{ data: typeof inserted }>(response)
expect(status).toBe(200)
expect(body.data.id).toBe('mem-2')
})
it('rejects when user is a viewer in the target company', async () => {
enqueue({ data: { role: 'viewer' } })
const response = await POST(
createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'En sak att komma ihåg' },
}),
createMockRouteParams({}),
)
expect(response.status).toBe(403)
})
})
describe('PATCH /api/agent/memory/[id]', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const response = await PATCH(
createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_pinned: true },
}),
createMockRouteParams({ id: 'mem-1' }),
)
expect(response.status).toBe(401)
})
it('blocks viewers via requireWritePermission', async () => {
const { NextResponse } = await import('next/server')
requireWritePermissionMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
})
const response = await PATCH(
createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_pinned: true },
}),
createMockRouteParams({ id: 'mem-1' }),
)
expect(response.status).toBe(403)
})
it('rejects empty patch body', async () => {
const response = await PATCH(
createMockRequest('/api/agent/memory/mem-1', { method: 'PATCH', body: {} }),
createMockRouteParams({ id: 'mem-1' }),
)
expect(response.status).toBe(400)
})
it('returns 404 when row not found / not visible via RLS', async () => {
// Row lookup returns null → defense-in-depth 404 before update.
enqueue({ data: null })
const response = await PATCH(
createMockRequest('/api/agent/memory/mem-x', {
method: 'PATCH',
body: { is_pinned: true },
}),
createMockRouteParams({ id: 'mem-x' }),
)
expect(response.status).toBe(404)
})
it('returns 404 when user has no membership in row company', async () => {
enqueue({ data: { company_id: 'company-2' } })
enqueue({ data: null }) // company_members lookup
const response = await PATCH(
createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_pinned: true },
}),
createMockRouteParams({ id: 'mem-1' }),
)
expect(response.status).toBe(404)
})
it('pins a row', async () => {
const updated = {
id: 'mem-1',
kind: 'fact',
content: 'X',
source: 'composer',
source_ref: null,
relevance_score: 0.5,
is_pinned: true,
is_active: true,
last_accessed_at: null,
created_at: '2026-05-10T09:00:00Z',
updated_at: '2026-05-18T10:00:00Z',
}
// PATCH flow: (1) row lookup, (2) membership lookup, (3) update.
enqueue({ data: { company_id: 'company-1' } })
enqueue({ data: { role: 'member' } })
enqueue({ data: updated })
const response = await PATCH(
createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_pinned: true },
}),
createMockRouteParams({ id: 'mem-1' }),
)
const { status, body } = await parseJsonResponse<{ data: typeof updated }>(response)
expect(status).toBe(200)
expect(body.data.is_pinned).toBe(true)
})
it('dismisses a row by setting is_active=false', async () => {
const updated = {
id: 'mem-1',
kind: 'fact',
content: 'X',
source: 'composer',
source_ref: null,
relevance_score: 0.5,
is_pinned: false,
is_active: false,
last_accessed_at: null,
created_at: '2026-05-10T09:00:00Z',
updated_at: '2026-05-18T10:00:00Z',
}
enqueue({ data: { company_id: 'company-1' } })
enqueue({ data: { role: 'member' } })
enqueue({ data: updated })
const response = await PATCH(
createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_active: false },
}),
createMockRouteParams({ id: 'mem-1' }),
)
const { status, body } = await parseJsonResponse<{ data: typeof updated }>(response)
expect(status).toBe(200)
expect(body.data.is_active).toBe(false)
})
it('rejects content shorter than 2 chars', async () => {
const response = await PATCH(
createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { content: 'x' },
}),
createMockRouteParams({ id: 'mem-1' }),
)
expect(response.status).toBe(400)
})
})
+135
View File
@@ -0,0 +1,135 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody, validateQuery } from '@/lib/api/validate'
// GET /api/agent/memory
//
// Lists memory entries for the active company, ordered by pin > relevance >
// recency. Powers /settings/agent-memory (transparency UI per plan §11).
//
// Query params:
// include_dismissed: 'true' includes is_active=false rows (audit view).
// kind: filter by kind.
// limit: 1..200, default 200 (matches the storage cap).
//
// POST /api/agent/memory
//
// Inserts a memory entry for the company. Used by Phase B's free-text seed
// memory field ("Lägg till om ditt företag (valfritt)") to capture
// foundational facts as `kind=fact`, `source=user_taught` with an elevated
// relevance score so they land in the top-30 prompt block.
//
// Also usable from /settings/agent-memory ("Lägg till minne" affordance) and
// post-Phase 4 explicit "Kom ihåg det här" surfaces.
const KIND = ['fact', 'preference', 'pattern', 'correction'] as const
const SOURCE = ['composer', 'user_taught', 'agent_learned', 'derived'] as const
const MEMORY_COLUMNS =
'id, kind, content, source, source_ref, relevance_score, is_pinned, is_active, last_accessed_at, created_at, updated_at'
const ListQuerySchema = z.object({
include_dismissed: z.enum(['true', 'false']).optional(),
kind: z.enum(KIND).optional(),
limit: z.coerce.number().int().min(1).max(200).default(200),
})
const BodySchema = z.object({
company_id: z.string().uuid().optional(),
content: z.string().min(2).max(2000),
kind: z.enum(KIND).default('fact'),
source: z.enum(SOURCE).default('user_taught'),
source_ref: z.string().max(200).optional(),
// Default 1.0 keeps user-taught entries above composer-derived (0.5) by
// default; conversation-time captures can land anywhere in [0, 1].
relevance_score: z.number().min(0).max(1).default(1.0),
})
export const GET = withRouteContext('agent.memory.list', async (request, ctx) => {
const { supabase, companyId, log } = ctx
const validated = validateQuery(request, ListQuerySchema, {
log,
operation: 'agent.memory.list',
})
if (!validated.success) return validated.response
const { include_dismissed, kind, limit } = validated.data
let query = supabase
.from('agent_memory')
.select(MEMORY_COLUMNS)
.eq('company_id', companyId)
if (include_dismissed !== 'true') query = query.eq('is_active', true)
if (kind) query = query.eq('kind', kind)
query = query
.order('is_active', { ascending: false })
.order('is_pinned', { ascending: false })
.order('relevance_score', { ascending: false })
.order('last_accessed_at', { ascending: false, nullsFirst: false })
.order('created_at', { ascending: false })
.limit(limit)
const { data, error } = await query
if (error) throw error
return NextResponse.json({ data: data ?? [] })
})
export const POST = withRouteContext(
'agent.memory.create',
async (request, ctx) => {
const { supabase, companyId: activeCompanyId, user, log } = ctx
const validation = await validateBody(request, BodySchema, {
log,
operation: 'agent.memory.create',
})
if (!validation.success) return validation.response
const body = validation.data
const companyId = body.company_id ?? activeCompanyId
// requireWrite (wrapper option) checks the *active* company's role; if
// the caller passes a different company_id in the body, re-check
// membership + non-viewer role for THAT company specifically.
const { data: bodyMembership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!bodyMembership || bodyMembership.role === 'viewer') {
return NextResponse.json(
{
error: {
code: 'WRITE_PERMISSION_REQUIRED',
message: 'Du har endast läsbehörighet i detta företag.',
message_en: 'You only have read access in this company.',
},
},
{ status: 403 },
)
}
const { data, error } = await supabase
.from('agent_memory')
.insert({
company_id: companyId,
kind: body.kind,
content: body.content,
source: body.source,
source_ref: body.source_ref ?? null,
relevance_score: body.relevance_score,
is_active: true,
created_by_user_id: user.id,
})
.select(MEMORY_COLUMNS)
.single()
if (error) throw error
return NextResponse.json({ data })
},
{ requireWrite: true },
)
+297
View File
@@ -0,0 +1,297 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { getActiveCompanyId } from '@/lib/company/context'
import { guardSandbox } from '@/lib/sandbox/guard'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
import { gatherComposerInputs, inputsToSourceSignals } from '@/lib/agent/composer/inputs'
import { selectAtoms } from '@/lib/agent/composer/atom-selection'
import { writeNarrative } from '@/lib/agent/composer/narrative'
import { fallbackAtomSelection, fallbackNarrative } from '@/lib/agent/composer/fallback'
import { filterRedundantQuestions } from '@/lib/agent/composer/atom-selection'
import { preWarmAtomCache } from '@/lib/agent/composer/prewarm'
import { OPUS_MODEL } from '@/lib/agent/composer/client'
import { ensureTicSnapshot } from '@/lib/agent/composer/tic-fetch'
import type { AtomSelection } from '@/lib/agent/composer/schemas'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { withTimeout } from '@/lib/utils'
const BodySchema = z.object({
company_id: z.string().uuid().optional(),
})
// 10s: the user is on a wait-screen with visible progress, so we can afford
// the longer budget. The prior 5s clipped legitimate fetches (TIC fans out to
// ~13 Lens calls upstream) into the fallback bucket while still burning the
// in-flight upstream calls against quota. See actions.ts:182-189 for the
// May 2026 incident context.
const TIC_BUDGET_MS = 10_000
// Bedrock cold-starts can take 2-3s before the first token, plus the actual
// Opus selection call typically lands at 10-14s. 15s was too tight and put
// real Opus calls into the fallback bucket on the first turn of the day.
const SELECT_BUDGET_MS = 25_000
const NARRATIVE_BUDGET_MS = 8_000
// Per-step event shape streamed as NDJSON. Each line is one JSON object.
type Step = 'tic' | 'select' | 'narrative' | 'finalize' | 'prewarm'
type Status = 'in_progress' | 'success' | 'fallback' | 'skipped' | 'error'
type StreamEvent =
| { step: Step; status: Status }
| { step: 'select'; status: 'success' | 'fallback'; selection: AtomSelection }
| { step: 'narrative'; status: 'success' | 'fallback'; narrative: string }
| { step: 'finalize'; status: 'success'; profile: ProfilePayload }
| { step: 'error'; status: 'error'; message: string }
interface ProfilePayload {
company_id: string
horizontal_atoms: string[]
vertical_atoms: string[]
modifier_atoms: string[]
is_multi_vertical: boolean
profile_summary: string
verification_questions: string[]
uncertainty_notes: string[]
composer_model: string
composed_at: string
}
// POST /api/agent/onboarding/stream
//
// Streams real-timed progress for the agent build sequence (plan §7 Phase A).
// Each step runs on its actual latency: no artificial delays. On timeout or
// failure, the step emits `fallback` and the pipeline continues with a
// deterministic default so the user always reaches Phase B.
//
// Response: application/x-ndjson, one JSON event per line.
export async function POST(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
// Generous per-user rate limit: bounds reload-spam of the onboarding build
// (each run fires 2 LLM calls). Fails open on infra error.
const rate = await checkAgentRateLimit(supabase, user.id)
if (!rate.ok) {
return NextResponse.json(agentRateLimitResponseBody(rate), {
status: 429,
headers: rate.retryAfterSec ? { 'Retry-After': String(rate.retryAfterSec) } : undefined,
})
}
let body: z.infer<typeof BodySchema>
try {
body = BodySchema.parse(await request.json().catch(() => ({})))
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? getUserErrorMessage(err) : 'Invalid body' },
{ status: 400 },
)
}
const companyId = body.company_id ?? (await getActiveCompanyId(supabase, user.id))
if (!companyId) {
return NextResponse.json({ error: 'No active company' }, { status: 400 })
}
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) {
return NextResponse.json({ error: 'Not a member of this company' }, { status: 403 })
}
// The pipeline upserts agent_profiles — a mutation, so viewers are refused
// (same rule as /api/agent/profile and /verify).
if (membership.role === 'viewer') {
return NextResponse.json(
{ error: 'Du har endast läsbehörighet i detta företag.' },
{ status: 403 },
)
}
// No live composer run for sandbox companies: they ship with a pre-built
// verified agent_profile so the chrome is visible without burning Bedrock.
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
if (capBlocked) return capBlocked
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
const encoder = new TextEncoder()
const send = (event: StreamEvent) => {
try {
controller.enqueue(encoder.encode(JSON.stringify(event) + '\n'))
} catch {
// Stream was cancelled (user navigated away). Subsequent enqueues
// would throw: we just stop emitting.
}
}
try {
// Step 1: TIC: read companies.tic_snapshot; if missing or stale,
// live-fetch from the TIC extension (cookies forwarded from the
// incoming request) and persist. Falls through gracefully when TIC is
// disabled, the company has no org_number, or the request times out.
send({ step: 'tic', status: 'in_progress' })
const cookieHeader = request.headers.get('cookie') ?? ''
// SSRF guard: derive origin from NEXT_PUBLIC_APP_URL (a required env
// var per CLAUDE.md) instead of request.headers.host. On self-hosted
// Docker the Host header can be attacker-controlled and would
// otherwise let an attacker redirect the cookie-bearing TIC fetch to
// a host they control.
const appUrl = process.env.NEXT_PUBLIC_APP_URL?.replace(/\/+$/, '') ?? ''
const fallbackHost = request.headers.get('host') ?? 'localhost:3000'
const fallbackProto =
request.headers.get('x-forwarded-proto') ??
(fallbackHost.startsWith('localhost') ? 'http' : 'https')
const origin = appUrl || `${fallbackProto}://${fallbackHost}`
const ticResult = await withTimeout(
// upgradeV1: agent build is the consumer of the v2-only sections;
// bounded to companies actively creating an agent, so the TIC
// budget stays safe even when upgrading pre-v2 snapshots.
// timeoutMs: lift the internal fetch signal to match the outer
// budget: otherwise the 5s default fires first and we get the
// pre-fix behavior even with the longer outer budget.
ensureTicSnapshot({
supabase,
companyId,
cookieHeader,
origin,
upgradeV1: true,
timeoutMs: TIC_BUDGET_MS,
}),
TIC_BUDGET_MS,
).catch(() => ({ snapshot: null, source: 'fallback' as const }))
send({
step: 'tic',
status: ticResult.snapshot ? 'success' : 'fallback',
})
// Gather inputs once: used by select + narrative + persistence.
const inputs = await gatherComposerInputs(supabase, companyId)
// Step 2: Opus atom selection with timeout + deterministic fallback.
send({ step: 'select', status: 'in_progress' })
let selection: AtomSelection
try {
selection = await withTimeout(selectAtoms(inputs), SELECT_BUDGET_MS)
send({ step: 'select', status: 'success', selection })
} catch {
selection = fallbackAtomSelection(inputs)
send({ step: 'select', status: 'fallback', selection })
}
// Filter verification questions deterministically regardless of which
// path produced the selection. fallbackAtomSelection generates a
// generic template that doesn't know about KÄNDA FAKTA; the Opus
// path is also re-filtered in case the model strayed. Cheap belt-
// and-braces: same function used for both.
selection.verification_questions = filterRedundantQuestions(
selection.verification_questions,
inputs,
selection.modifier_atoms,
)
// Step 3: Sonnet narrative with timeout + plain fallback.
send({ step: 'narrative', status: 'in_progress' })
let narrative: string
try {
narrative = await withTimeout(writeNarrative(inputs, selection), NARRATIVE_BUDGET_MS)
send({ step: 'narrative', status: 'success', narrative })
} catch {
narrative = fallbackNarrative(inputs)
send({ step: 'narrative', status: 'fallback', narrative })
}
// Step 4: Persist the profile so Phase B has a row to edit.
const composedAt = new Date().toISOString()
const sourceSignals = inputsToSourceSignals(inputs)
const { error: upsertErr } = await supabase
.from('agent_profiles')
.upsert(
{
company_id: companyId,
horizontal_atoms: selection.horizontal_atoms,
vertical_atoms: selection.vertical_atoms,
modifier_atoms: selection.modifier_atoms,
profile_summary: narrative,
source_signals: sourceSignals,
// Persist so the Phase C intake agent can read them server-
// side when the chat opens. Plan §7 Phase C.
verification_questions: selection.verification_questions,
composed_at: composedAt,
composer_model: OPUS_MODEL,
composer_version: 1,
},
{ onConflict: 'company_id' },
)
if (upsertErr) {
send({ step: 'error', status: 'error', message: getUserErrorMessage(upsertErr) })
return
}
send({
step: 'finalize',
status: 'success',
profile: {
company_id: companyId,
horizontal_atoms: selection.horizontal_atoms,
vertical_atoms: selection.vertical_atoms,
modifier_atoms: selection.modifier_atoms,
is_multi_vertical: selection.is_multi_vertical,
profile_summary: narrative,
verification_questions: selection.verification_questions,
uncertainty_notes: selection.uncertainty_notes,
composer_model: OPUS_MODEL,
composed_at: composedAt,
},
})
// Step 5: fire-and-forget cache pre-warm. The client renders the
// review card already; pre-warm just buys a faster first chat turn.
send({ step: 'prewarm', status: 'in_progress' })
const allIds = [
...selection.horizontal_atoms,
...selection.vertical_atoms,
...selection.modifier_atoms,
]
if (allIds.length > 0) {
const { data: rows } = await supabase
.from('agent_atom_registry')
.select('id, body')
.in('id', allIds)
const bodies = (rows ?? [])
.map((r: { body: string | null }) => r.body ?? '')
.filter((b: string) => b.length > 0)
void preWarmAtomCache({ atomBodies: bodies })
}
send({ step: 'prewarm', status: 'success' })
} catch (err) {
send({
step: 'error',
status: 'error',
message: err instanceof Error ? getUserErrorMessage(err) : 'Composer pipeline failed',
})
} finally {
try {
controller.close()
} catch {
// Already closed.
}
}
},
})
return new Response(stream, {
headers: {
'Content-Type': 'application/x-ndjson; charset=utf-8',
'Cache-Control': 'no-store',
'X-Accel-Buffering': 'no',
},
})
}
+176
View File
@@ -0,0 +1,176 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody, validateQuery } from '@/lib/api/validate'
// GET /api/agent/profile?company_id=...
// PATCH same path
//
// GET returns the composed profile + the source verification_questions stored
// alongside it (read from agent_profiles row).
//
// PATCH updates field_overrides (timestamped, merged with existing) and
// optionally rewrites the atom arrays from the review UI. Does not touch
// verified_at: that flows through /verify. Requires a non-viewer role in
// the target company (same rule as /verify: it mutates the profile).
const AtomArrays = z.object({
horizontal_atoms: z.array(z.string()).optional(),
vertical_atoms: z.array(z.string()).optional(),
modifier_atoms: z.array(z.string()).optional(),
})
const PatchBody = z.object({
company_id: z.string().uuid().optional(),
field_overrides: z.record(z.string(), z.unknown()).optional(),
atoms: AtomArrays.optional(),
profile_summary: z.string().min(1).max(2000).optional(),
// Agent personalization: name shown on the FAB and chat headers, and
// avatar key into the static AVATAR_OPTIONS registry. Both nullable so
// the user can clear them back to defaults.
display_name: z.string().min(1).max(60).nullable().optional(),
avatar_id: z.string().max(60).nullable().optional(),
})
const GetQuerySchema = z.object({
company_id: z.string().uuid().optional(),
})
const forbidden = (code: 'NOT_COMPANY_MEMBER' | 'WRITE_PERMISSION_REQUIRED') =>
NextResponse.json(
{
error:
code === 'NOT_COMPANY_MEMBER'
? {
code,
message: 'Du är inte medlem i detta företag.',
message_en: 'Not a member of this company.',
}
: {
code,
message: 'Du har endast läsbehörighet i detta företag.',
message_en: 'You only have read access in this company.',
},
},
{ status: 403 },
)
export const GET = withRouteContext('agent.profile.get', async (request, ctx) => {
const { supabase, companyId: activeCompanyId, user, log } = ctx
const validated = validateQuery(request, GetQuerySchema, {
log,
operation: 'agent.profile.get',
})
if (!validated.success) return validated.response
const companyId = validated.data.company_id ?? activeCompanyId
// Defense in depth alongside RLS: confirm membership before reading.
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return forbidden('NOT_COMPANY_MEMBER')
const { data, error } = await supabase
.from('agent_profiles')
.select(
'company_id, horizontal_atoms, vertical_atoms, modifier_atoms, profile_summary, source_signals, field_overrides, composed_at, composer_model, composer_version, verified_at, verified_by_user_id, display_name, avatar_id',
)
.eq('company_id', companyId)
.maybeSingle()
if (error) throw error
if (!data) return NextResponse.json({ data: null })
return NextResponse.json({ data })
})
export const PATCH = withRouteContext('agent.profile.update', async (request, ctx) => {
const { supabase, companyId: activeCompanyId, user, log } = ctx
const validation = await validateBody(request, PatchBody, {
log,
operation: 'agent.profile.update',
})
if (!validation.success) return validation.response
const body = validation.data
const companyId = body.company_id ?? activeCompanyId
// RLS guards reads/updates by company_id; defense in depth: confirm
// membership AND a non-viewer role (this mutates the company's profile;
// same rule /verify already enforces).
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership) return forbidden('NOT_COMPANY_MEMBER')
if (membership.role === 'viewer') return forbidden('WRITE_PERMISSION_REQUIRED')
// Load current overrides to merge timestamp-stamped entries. Avoids round-trip
// when caller sends only an atom-array change.
const { data: current } = await supabase
.from('agent_profiles')
.select('field_overrides')
.eq('company_id', companyId)
.single()
if (!current) {
return NextResponse.json(
{
error: {
code: 'AGENT_PROFILE_NOT_FOUND',
message: 'Det finns ingen agentprofil för detta företag.',
message_en: 'agent_profile not found for this company.',
},
},
{ status: 404 },
)
}
const update: Record<string, unknown> = {}
if (body.field_overrides && Object.keys(body.field_overrides).length > 0) {
const merged: Record<string, { value: unknown; overridden_at: string }> = {
...((current.field_overrides as Record<string, { value: unknown; overridden_at: string }>) ?? {}),
}
const now = new Date().toISOString()
for (const [k, v] of Object.entries(body.field_overrides)) {
merged[k] = { value: v, overridden_at: now }
}
update.field_overrides = merged
}
if (body.atoms?.horizontal_atoms) update.horizontal_atoms = body.atoms.horizontal_atoms
if (body.atoms?.vertical_atoms) update.vertical_atoms = body.atoms.vertical_atoms
if (body.atoms?.modifier_atoms) update.modifier_atoms = body.atoms.modifier_atoms
if (body.profile_summary) update.profile_summary = body.profile_summary
if (body.display_name !== undefined) update.display_name = body.display_name
if (body.avatar_id !== undefined) update.avatar_id = body.avatar_id
if (Object.keys(update).length === 0) {
return NextResponse.json(
{
error: {
code: 'NOTHING_TO_UPDATE',
message: 'Inget att uppdatera.',
message_en: 'Nothing to update.',
},
},
{ status: 400 },
)
}
const { data, error } = await supabase
.from('agent_profiles')
.update(update)
.eq('company_id', companyId)
.select(
'company_id, horizontal_atoms, vertical_atoms, modifier_atoms, profile_summary, field_overrides',
)
.single()
if (error) throw error
return NextResponse.json({ data })
})
+72
View File
@@ -0,0 +1,72 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
// POST /api/agent/profile/verify
//
// Stamps verified_at + verified_by_user_id on agent_profiles when the user
// clicks "Det här ser rätt ut, kör" in Phase B. Idempotent: re-verifying
// updates the timestamp; this is desirable for "Bygg om" rebuild flows.
const BodySchema = z.object({
company_id: z.string().uuid().optional(),
})
export const POST = withRouteContext('agent.profile.verify', async (request, ctx) => {
const { supabase, companyId: activeCompanyId, user } = ctx
// Tolerant parse: the review card POSTs with an empty body when verifying
// the active company.
const raw = await request.json().catch(() => ({}))
const parsed = BodySchema.safeParse(raw)
if (!parsed.success) {
return NextResponse.json(
{
error: 'Validation failed',
type: 'validation_error',
errors: parsed.error.issues.map((issue) => ({
field: issue.path.join('.'),
message: issue.message,
code: issue.code,
})),
},
{ status: 400 },
)
}
const companyId = parsed.data.company_id ?? activeCompanyId
// Defense in depth alongside RLS: confirm membership for the target
// company; a non-viewer role is required to stamp verified_at.
const { data: membership } = await supabase
.from('company_members')
.select('role')
.eq('company_id', companyId)
.eq('user_id', user.id)
.maybeSingle()
if (!membership || membership.role === 'viewer') {
return NextResponse.json(
{
error: {
code: 'WRITE_PERMISSION_REQUIRED',
message: 'Du har endast läsbehörighet i detta företag.',
message_en: 'You only have read access in this company.',
},
},
{ status: 403 },
)
}
const { data, error } = await supabase
.from('agent_profiles')
.update({
verified_at: new Date().toISOString(),
verified_by_user_id: user.id,
})
.eq('company_id', companyId)
.select('company_id, verified_at, verified_by_user_id')
.single()
if (error) throw error
return NextResponse.json({ data })
})
+107
View File
@@ -0,0 +1,107 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateQuery } from '@/lib/api/validate'
// GET /api/agent/skills
//
// Read-only transparency surface for the in-app bookkeeping assistant's domain
// knowledge ("atoms"). Powers /settings/agent-skills: the companion to
// /settings/agent-memory. Memory is what the assistant *learned* about this
// company (user-editable); skills are the Swedish-accounting expertise it
// *ships* with: authored in .claude/skills/**/SKILL.md, seeded into
// agent_atom_registry, read-only for users, curated via mcp_exposed.
//
// Two shapes off one route:
// (no params) → metadata for every active + exposed atom, each flagged
// active-for-this-company. Bodies omitted so the list payload
// stays small.
// ?slug=<id> → the full SKILL.md body for one atom, loaded on expand.
//
// "Active for this company": horizontal atoms are regulatory and shared by
// every Swedish company, so always active. Vertical/modifier atoms are active
// only when the composer selected them into this company's agent_profile:
// others are shown dormant so the user sees both the full library and what's
// tuned for them. The profile arrays store full ids ("vertical/konsult-it"),
// matched directly against agent_atom_registry.id (see lib/agent/chat/system-prompt.ts).
interface AtomMeta {
id: string
tier: 'horizontal' | 'vertical' | 'modifier'
title: string
description: string
active: boolean
}
const QuerySchema = z.object({
slug: z.string().min(1).optional(),
})
export const GET = withRouteContext('agent.skills.list', async (request, ctx) => {
const { supabase, companyId, log } = ctx
const validated = validateQuery(request, QuerySchema, {
log,
operation: 'agent.skills.list',
})
if (!validated.success) return validated.response
const { slug } = validated.data
// Detail: one atom's body, fetched lazily when the user expands a card.
// The atom registry is global product content (not tenant data), so no
// company filter applies here.
if (slug) {
const { data, error } = await supabase
.from('agent_atom_registry')
.select('id, title, body, is_active, mcp_exposed')
.eq('id', slug)
.maybeSingle()
if (error) throw error
if (!data || !data.is_active || !data.mcp_exposed) {
return NextResponse.json(
{
error: {
code: 'SKILL_NOT_FOUND',
message: 'Kunskapen hittades inte.',
message_en: 'Skill not found.',
},
},
{ status: 404 },
)
}
return NextResponse.json({ data: { id: data.id, title: data.title, body: data.body ?? '' } })
}
// List: metadata for every visible atom + which are active for this company.
const { data: atoms, error } = await supabase
.from('agent_atom_registry')
.select('id, tier, title, description')
.eq('is_active', true)
.eq('mcp_exposed', true)
.is('parent_atom_id', null) // show top-level skills only; reference children are internal
.order('tier', { ascending: true })
.order('title', { ascending: true })
if (error) throw error
const { data: profile } = await supabase
.from('agent_profiles')
.select('vertical_atoms, modifier_atoms')
.eq('company_id', companyId)
.maybeSingle()
const verticalActive = new Set((profile?.vertical_atoms as string[] | null) ?? [])
const modifierActive = new Set((profile?.modifier_atoms as string[] | null) ?? [])
const result: AtomMeta[] = (atoms ?? []).map((a) => {
const tier = a.tier as AtomMeta['tier']
const active =
tier === 'horizontal'
? true
: tier === 'vertical'
? verticalActive.has(a.id)
: modifierActive.has(a.id)
return { id: a.id, tier, title: a.title, description: a.description, active }
})
return NextResponse.json({ data: result })
})
+193
View File
@@ -0,0 +1,193 @@
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { validateBody } from '@/lib/api/validate'
import { UpdateArticleSchema } from '@/lib/api/schemas'
import { withRouteContext } from '@/lib/api/with-route-context'
import { checkRevenueAccount } from '@/lib/articles/validate-revenue-account'
import { AccountsNotInChartError, accountsNotInChartResponse } from '@/lib/bookkeeping/errors'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { Article } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
export const GET = withRouteContext(
'article.get',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ articleId: id })
const { data, error } = await supabase
.from('articles')
.select('*')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (error) {
if (error.code === 'PGRST116') {
return errorResponseFromCode('ARTICLE_NOT_FOUND', opLog, { requestId })
}
opLog.error('article fetch failed', error)
return errorResponseFromCode('INTERNAL_ERROR', opLog, {
requestId,
details: { reason: getUserErrorMessage(error) },
})
}
return NextResponse.json({ data })
},
)
export const PATCH = withRouteContext(
'article.update',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const opLog = log.child({ articleId: id })
const result = await validateBody(request, UpdateArticleSchema, {
log: opLog,
operation: 'article.update',
})
if (!result.success) return result.response
const body = result.data
// Same activate-and-retry contract as POST /api/articles: a class 1-3 account
// that just isn't activated yet returns ACCOUNTS_NOT_IN_CHART.
if (body.revenue_account) {
const status = await checkRevenueAccount(supabase, companyId!, body.revenue_account)
if (status === 'activatable') {
return accountsNotInChartResponse(new AccountsNotInChartError([body.revenue_account]))
}
if (status === 'invalid') {
return errorResponseFromCode('ARTICLE_REVENUE_ACCOUNT_INVALID', opLog, { requestId })
}
}
// Sparse update: only the fields the caller actually sent.
const updateData: Record<string, unknown> = {}
for (const key of [
'name', 'name_en', 'type', 'unit', 'price_excl_vat', 'vat_rate',
'currency', 'revenue_account', 'cost_price', 'ean', 'housework_type',
'notes', 'article_number', 'active',
] as const) {
if (body[key] !== undefined) updateData[key] = body[key]
}
const { data, error } = await supabase
.from('articles')
.update(updateData)
.eq('id', id)
.eq('company_id', companyId)
.select()
.single()
if (error) {
if (error.code === 'PGRST116') {
return errorResponseFromCode('ARTICLE_NOT_FOUND', opLog, { requestId })
}
if (error.code === '23505') {
return errorResponseFromCode('ARTICLE_DUPLICATE_NUMBER', opLog, {
requestId,
details: { articleNumber: body.article_number },
})
}
opLog.error('article update failed', error)
return errorResponseFromCode('ARTICLE_UPDATE_FAILED', opLog, {
requestId,
details: { reason: getUserErrorMessage(error) },
})
}
await eventBus.emit({
type: 'article.updated',
payload: { article: data as Article, companyId: companyId!, userId: user.id },
})
return NextResponse.json({ data })
},
{ requireWrite: true },
)
// Articles are master data, while invoice lines hold frozen copies of the
// accounting values. An article may therefore be deleted only while no invoice
// line references it. The preflight also covers draft invoices.
export const DELETE = withRouteContext(
'article.delete',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const opLog = log.child({ articleId: id })
const { error: articleError } = await supabase
.from('articles')
.select('id')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (articleError) {
if (articleError.code === 'PGRST116') {
return errorResponseFromCode('ARTICLE_NOT_FOUND', opLog, { requestId })
}
opLog.error('article lookup before delete failed', articleError)
return errorResponseFromCode('ARTICLE_DELETE_FAILED', opLog, {
requestId,
details: { reason: getUserErrorMessage(articleError) },
})
}
// invoice_items has NO company_id column: filtering on it made PostgREST
// 42703 here, which the error branch below turned into ARTICLE_DELETE_FAILED
// for EVERY delete (support: odinaero.se). Tenancy is already enforced by
// the article lookup above: article_id is a UUID owned by this company.
const { count: usageCount, error: usageError } = await supabase
.from('invoice_items')
.select('id', { count: 'exact', head: true })
.eq('article_id', id)
if (usageError) {
opLog.error('article usage check failed', usageError)
return errorResponseFromCode('ARTICLE_DELETE_FAILED', opLog, {
requestId,
details: { reason: getUserErrorMessage(usageError) },
})
}
if ((usageCount ?? 0) > 0) {
return errorResponseFromCode('ARTICLE_IN_USE', opLog, { requestId })
}
const { error: deleteError, count: deletedCount } = await supabase
.from('articles')
.delete({ count: 'exact' })
.eq('id', id)
.eq('company_id', companyId)
if (deleteError) {
if (deleteError.code === '23503') {
return errorResponseFromCode('ARTICLE_IN_USE', opLog, { requestId })
}
opLog.error('article delete failed', deleteError)
return errorResponseFromCode('ARTICLE_DELETE_FAILED', opLog, {
requestId,
details: { reason: getUserErrorMessage(deleteError) },
})
}
if (deletedCount === 0) {
return errorResponseFromCode('ARTICLE_NOT_FOUND', opLog, { requestId })
}
await eventBus.emit({
type: 'article.deleted',
payload: { articleId: id, companyId, userId: user.id },
})
return NextResponse.json({ success: true })
},
{ requireWrite: true },
)
+205
View File
@@ -0,0 +1,205 @@
/**
* Tests for GET/PATCH/DELETE /api/articles/[id] (artikelregister).
*
* DELETE permanently removes only articles that have never been used on an
* invoice line. PATCH is a sparse update.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
import { eventBus } from '@/lib/events'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET, PATCH, DELETE } from '../[id]/route'
describe('GET/PATCH/DELETE /api/articles/[id]', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('GET returns 404 when the article is not found', async () => {
enqueue({ data: null, error: { code: 'PGRST116', message: 'not found' } })
const response = await GET(createMockRequest('/api/articles/a1'), createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(404)
expect(body.error.code).toBe('ARTICLE_NOT_FOUND')
})
it('PATCH updates a field and returns the row', async () => {
enqueue({ data: { id: 'a1', name: 'Konsulttimme', price_excl_vat: 1500 } })
const request = createMockRequest('/api/articles/a1', {
method: 'PATCH',
body: { price_excl_vat: 1500 },
})
const response = await PATCH(request, createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{ data: { price_excl_vat: number } }>(response)
expect(status).toBe(200)
expect(body.data.price_excl_vat).toBe(1500)
})
// The article detail page's Inaktivera/Aktivera button sends nothing but the
// flag, so an active-only body must be a valid sparse update on its own.
it('PATCH toggles active on its own without any other field', async () => {
enqueue({ data: { id: 'a1', name: 'Konsulttimme', active: false } })
const request = createMockRequest('/api/articles/a1', {
method: 'PATCH',
body: { active: false },
})
const response = await PATCH(request, createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{ data: { active: boolean } }>(response)
expect(status).toBe(200)
expect(body.data.active).toBe(false)
// Only the articles update: no revenue-account lookup is triggered by a
// body that carries nothing but the flag.
expect(supabase.from).toHaveBeenCalledTimes(1)
expect(supabase.from).toHaveBeenCalledWith('articles')
})
it('PATCH answers ACCOUNTS_NOT_IN_CHART for a BAS class-3 account missing from the chart', async () => {
// chart_of_accounts lookup: no row, but 3999 is a known BAS class-3
// account → activatable via the activate-and-retry dialog flow.
enqueue({ data: null })
const request = createMockRequest('/api/articles/a1', {
method: 'PATCH',
body: { revenue_account: '3999' },
})
const response = await PATCH(request, createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{
error: { code: string; account_numbers: string[] }
}>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('ACCOUNTS_NOT_IN_CHART')
expect(body.error.account_numbers).toEqual(['3999'])
})
it('PATCH rejects a 3xxx revenue_account unknown to both chart and BAS catalogue', async () => {
// No chart row and 3041 is not in the BAS reference → invalid, no dialog.
enqueue({ data: null })
const request = createMockRequest('/api/articles/a1', {
method: 'PATCH',
body: { revenue_account: '3041' },
})
const response = await PATCH(request, createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('ARTICLE_REVENUE_ACCOUNT_INVALID')
})
it('DELETE returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await DELETE(
createMockRequest('/api/articles/a1', { method: 'DELETE' }),
createMockRouteParams({ id: 'a1' }),
)
expect(response.status).toBe(401)
})
it('DELETE returns 404 when the article is not found', async () => {
enqueue({ data: null, error: { code: 'PGRST116', message: 'not found' } })
const response = await DELETE(
createMockRequest('/api/articles/a1', { method: 'DELETE' }),
createMockRouteParams({ id: 'a1' }),
)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(404)
expect(body.error.code).toBe('ARTICLE_NOT_FOUND')
})
it('DELETE rejects an article used on an invoice line', async () => {
enqueue({ data: { id: 'a1' }, error: null })
enqueue({ data: null, error: null, count: 1 })
const response = await DELETE(
createMockRequest('/api/articles/a1', { method: 'DELETE' }),
createMockRouteParams({ id: 'a1' }),
)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('ARTICLE_IN_USE')
expect(supabase.from).toHaveBeenCalledTimes(2)
})
it('DELETE permanently removes an unused article', async () => {
enqueue({ data: { id: 'a1' }, error: null })
enqueue({ data: null, error: null, count: 0 })
enqueue({ data: null, error: null, count: 1 })
const emitSpy = vi.spyOn(eventBus, 'emit')
const response = await DELETE(
createMockRequest('/api/articles/a1', { method: 'DELETE' }),
createMockRouteParams({ id: 'a1' }),
)
const { status, body } = await parseJsonResponse<{ success: boolean }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(supabase.from).toHaveBeenNthCalledWith(1, 'articles')
expect(supabase.from).toHaveBeenNthCalledWith(2, 'invoice_items')
expect(supabase.from).toHaveBeenNthCalledWith(3, 'articles')
expect(emitSpy).toHaveBeenCalledWith({
type: 'article.deleted',
payload: { articleId: 'a1', companyId: 'company-1', userId: 'user-1' },
})
})
})
describe('DELETE usage-check query shape', () => {
it('must not filter invoice_items by company_id (column does not exist)', async () => {
// Regression pin for the odinaero support case: invoice_items has no
// company_id column, so filtering on it made PostgREST answer 42703 and
// the route mapped that to ARTICLE_DELETE_FAILED for EVERY delete. The
// queued supabase mock swallows chained filters, so no behavioral mock
// test can catch a phantom column: pin the source instead. Tenancy is
// enforced by the preceding articles lookup.
const fs = await import('node:fs')
const path = await import('node:path')
const src = fs.readFileSync(path.resolve(__dirname, '../[id]/route.ts'), 'utf8')
const usageBlock = src.slice(src.indexOf("from('invoice_items')"))
const firstQuery = usageBlock.slice(0, usageBlock.indexOf('usageError'))
expect(firstQuery).not.toContain("eq('company_id'")
})
})
+168
View File
@@ -0,0 +1,168 @@
/**
* Tests for GET/POST /api/articles (artikelregister).
*
* Exercises the route through the real withRouteContext wrapper, mocking only
* its auth/company/write dependencies and injecting a queued Supabase mock via
* requireAuth. Covers: list, validation (400), revenue-account guard (400),
* and the happy-path create with auto-numbering.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET, POST } from '../route'
describe('GET/POST /api/articles', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('GET lists the company articles', async () => {
enqueue({ data: [{ id: 'a1', name: 'Konsulttimme' }, { id: 'a2', name: 'Licens' }] })
const response = await GET(createMockRequest('/api/articles'), { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(response)
expect(status).toBe(200)
expect(body.data).toHaveLength(2)
})
it('POST rejects an invalid body (missing name) with 400', async () => {
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { price_excl_vat: 100 },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
})
it('POST rejects a 3xxx revenue_account unknown to both chart and BAS catalogue', async () => {
// Non-3xxx numbers are already stopped by the Zod schema; the route-level
// 'invalid' branch covers 3xxx numbers that exist nowhere, no chart row
// and not in the BAS reference (3041 is not a BAS 2026 account).
enqueue({ data: null })
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { name: 'Frakt', price_excl_vat: 100, revenue_account: '3041' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('ARTICLE_REVENUE_ACCOUNT_INVALID')
})
it('POST answers ACCOUNTS_NOT_IN_CHART for a BAS class-3 account missing from the chart', async () => {
// No chart row, but 3999 is a known BAS class-3 account → activatable, so
// the client can run the activate-and-retry dialog flow.
enqueue({ data: null })
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { name: 'Frakt', price_excl_vat: 100, revenue_account: '3999' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{
error: { code: string; account_numbers: string[] }
}>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('ACCOUNTS_NOT_IN_CHART')
expect(body.error.account_numbers).toEqual(['3999'])
})
it('POST answers ACCOUNTS_NOT_IN_CHART for an inactive class-3 chart account', async () => {
enqueue({ data: { account_class: 3, is_active: false } })
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { name: 'Frakt', price_excl_vat: 100, revenue_account: '3001' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('ACCOUNTS_NOT_IN_CHART')
})
it('POST accepts a revenue_account that is active class 3 in the chart', async () => {
// 1st DB hit: chart_of_accounts lookup → active class-3 row.
enqueue({ data: { account_class: 3, is_active: true } })
// 2nd DB hit: insert ... returning the row.
enqueue({ data: { id: 'a1', name: 'Frakt', article_number: '3', revenue_account: '3001' } })
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { name: 'Frakt', price_excl_vat: 100, revenue_account: '3001' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: { revenue_account: string } }>(response)
expect(status).toBe(200)
expect(body.data.revenue_account).toBe('3001')
})
it('POST accepts a posting account that is active class 2 in the chart', async () => {
enqueue({ data: { account_class: 2, is_active: true } })
enqueue({ data: { id: 'a1', name: 'Deposition', article_number: '4', revenue_account: '2897' } })
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { name: 'Deposition', price_excl_vat: 1000, vat_rate: 0, revenue_account: '2897' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: { revenue_account: string } }>(response)
expect(status).toBe(200)
expect(body.data.revenue_account).toBe('2897')
})
it('POST creates an article and auto-assigns a number', async () => {
// 1st DB hit: insert ... returning the row (article_number still null).
enqueue({ data: { id: 'a1', name: 'Konsulttimme', article_number: null, type: 'tjanst', vat_rate: 25 } })
// 2nd DB hit: generate_article_number RPC returns the assigned number.
enqueue({ data: '7' })
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { name: 'Konsulttimme', price_excl_vat: 1200, vat_rate: 25 },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: { id: string; article_number: string } }>(response)
expect(status).toBe(200)
expect(body.data.id).toBe('a1')
expect(body.data.article_number).toBe('7')
})
})
+125
View File
@@ -0,0 +1,125 @@
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { validateBody } from '@/lib/api/validate'
import { CreateArticleSchema } from '@/lib/api/schemas'
import { withRouteContext } from '@/lib/api/with-route-context'
import { ensureArticleNumber } from '@/lib/articles/ensure-article-number'
import { checkRevenueAccount } from '@/lib/articles/validate-revenue-account'
import { AccountsNotInChartError, accountsNotInChartResponse } from '@/lib/bookkeeping/errors'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import type { Article } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
// GET /api/articles: list the active company's articles. `?include_inactive=1`
// returns soft-deactivated ones too (the register page can show an archive view).
export const GET = withRouteContext(
'article.list',
async (request, ctx) => {
const { supabase, companyId } = ctx
const includeInactive = new URL(request.url).searchParams.get('include_inactive') === '1'
// Article registers can exceed PostgREST's silent 1000-row cap (imported
// product catalogs), so paginate. The secondary order on id gives the
// stable total order .range() paging requires — name alone is not unique.
// Errors thrown here surface via the wrapper's canonical envelope.
const data = await fetchAllRows(({ from, to }) => {
let query = supabase
.from('articles')
.select('*')
.eq('company_id', companyId)
if (!includeInactive) query = query.eq('active', true)
return query
.order('name', { ascending: true })
.order('id', { ascending: true })
.range(from, to)
})
return NextResponse.json({ data })
},
)
export const POST = withRouteContext(
'article.create',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const result = await validateBody(request, CreateArticleSchema, {
log,
operation: 'article.create',
})
if (!result.success) return result.response
const body = result.data
// Guard the optional posting-account override against the chart of accounts.
// A class 1-3 account that merely isn't activated yet gets the standard
// ACCOUNTS_NOT_IN_CHART envelope so the client can offer activate-and-retry.
if (body.revenue_account) {
const status = await checkRevenueAccount(supabase, companyId!, body.revenue_account)
if (status === 'activatable') {
return accountsNotInChartResponse(new AccountsNotInChartError([body.revenue_account]))
}
if (status === 'invalid') {
return errorResponseFromCode('ARTICLE_REVENUE_ACCOUNT_INVALID', log, { requestId })
}
}
const { data, error } = await supabase
.from('articles')
.insert({
user_id: user.id,
company_id: companyId,
name: body.name,
name_en: body.name_en ?? null,
type: body.type ?? 'tjanst',
unit: body.unit ?? 'st',
price_excl_vat: body.price_excl_vat,
vat_rate: body.vat_rate ?? 25,
currency: body.currency ?? 'SEK',
revenue_account: body.revenue_account ?? null,
cost_price: body.cost_price ?? null,
ean: body.ean ?? null,
housework_type: body.housework_type ?? null,
notes: body.notes ?? null,
article_number: body.article_number ?? null,
})
.select()
.single()
if (error) {
if (error.code === '23505') {
return errorResponseFromCode('ARTICLE_DUPLICATE_NUMBER', log, {
requestId,
details: { articleNumber: body.article_number },
})
}
log.error('article insert failed', error)
return errorResponseFromCode('ARTICLE_CREATE_FAILED', log, {
requestId,
details: { reason: getUserErrorMessage(error) },
})
}
// Auto-number when the caller didn't supply one. Non-fatal: an unnumbered
// article is still usable and can be numbered later.
if (!data.article_number) {
try {
data.article_number = await ensureArticleNumber(supabase, companyId!, data.id)
} catch (err) {
log.warn('article number assignment failed', err as Error, { articleId: data.id })
}
}
await eventBus.emit({
type: 'article.created',
payload: { article: data as Article, companyId: companyId!, userId: user.id },
})
return NextResponse.json({ data })
},
{ requireWrite: true },
)
+78
View File
@@ -0,0 +1,78 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse } from '@/lib/errors/get-structured-error'
import { validateBody } from '@/lib/api/validate'
import { disposeAsset } from '@/lib/bokslut/assets/asset-service'
const VAT_TREATMENTS = [
'standard_25',
'reverse_charge',
'export',
'exempt',
] as const
const DisposeAssetSchema = z
.object({
disposal_type: z.enum(['sale', 'scrap', 'business_transfer']),
disposed_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
disposed_proceeds: z.number().nonnegative(),
proceeds_account: z.string().regex(/^\d{4}$/).optional(),
fiscal_period_id: z.string().uuid(),
vat_treatment: z.enum(VAT_TREATMENTS).optional(),
jamkning_original_input_vat: z.number().nonnegative().optional(),
jamkning_original_deduction_percent: z.number().min(0).max(100).optional(),
business_transfer_confirmed: z.boolean().optional(),
adjustment_document_confirmed: z.boolean().optional(),
})
.superRefine((value, ctx) => {
if (value.disposal_type === 'scrap' && value.disposed_proceeds !== 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['disposed_proceeds'],
message: 'disposed_proceeds måste vara 0 vid utrangering.',
})
}
if (value.disposal_type === 'sale' && value.disposed_proceeds > 0 && !value.vat_treatment) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['vat_treatment'],
message: 'vat_treatment krävs vid försäljning.',
})
}
if (value.disposal_type !== 'sale' && value.vat_treatment !== undefined) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['vat_treatment'],
message: 'vat_treatment får bara anges vid försäljning.',
})
}
const hasVat = value.jamkning_original_input_vat !== undefined
const hasPercent = value.jamkning_original_deduction_percent !== undefined
if (hasVat !== hasPercent) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: hasVat
? ['jamkning_original_deduction_percent']
: ['jamkning_original_input_vat'],
message: 'Ursprungsmoms och ursprunglig avdragsprocent måste anges tillsammans.',
})
}
})
export const POST = withRouteContext(
'assets.dispose',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const validation = await validateBody(request, DisposeAssetSchema)
if (!validation.success) return validation.response
try {
const result = await disposeAsset(supabase, companyId, user.id, id, validation.data)
return NextResponse.json({ data: result })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
{ requireWrite: true },
)
+216
View File
@@ -0,0 +1,216 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse } from '@/lib/errors/get-structured-error'
import { validateBody } from '@/lib/api/validate'
import { K3ComponentSchema } from '@/lib/api/schemas'
import {
getAsset,
updateAsset,
defaultAccountsForCategory,
} from '@/lib/bokslut/assets/asset-service'
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
import {
findK2ExcludedAccount,
k2ExcludedAccountMessages,
} from '@/lib/bokslut/assets/k2-account-guard'
import type { AssetCategory, WritableDepreciationMethod } from '@/types'
const ASSET_CATEGORIES: readonly AssetCategory[] = [
'immaterial',
'building',
'land_improvement',
'machinery',
'equipment',
'vehicle',
'computer',
'other_tangible',
] as const
const DEPRECIATION_METHODS: readonly WritableDepreciationMethod[] = [
'linear',
] as const
const UpdateAssetSchema = z
.object({
name: z.string().min(1).optional(),
notes: z.string().nullable().optional(),
// Acquisition-basis corrections. The service (updateAsset) only permits
// these while the asset is neither disposed nor depreciated, returning
// ASSET_CORRECTION_BLOCKED (409) otherwise: they redefine the
// depreciation basis, so a post-posting change must go through storno.
category: z
.enum(ASSET_CATEGORIES as unknown as [AssetCategory, ...AssetCategory[]])
.optional(),
acquisition_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
acquisition_cost: z.number().positive().optional(),
salvage_value: z.number().nonnegative().optional(),
useful_life_months: z.number().int().positive().optional(),
depreciation_method: z
.enum(DEPRECIATION_METHODS as unknown as [
WritableDepreciationMethod,
...WritableDepreciationMethod[],
])
.optional(),
restvarde_target: z.null().optional(),
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
// K3 component depreciation. Accepting `null` lets the caller clear an
// existing breakdown (the engine then falls back to depreciation_method).
// Per-component validation runs whenever the field is set to a non-null
// value; the cross-sum check needs the asset's acquisition_cost so it runs
// in the PATCH handler below, which can read the existing row.
k3_components: z.array(K3ComponentSchema).nullable().optional(),
})
export const GET = withRouteContext(
'assets.get',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
try {
const asset = await getAsset(supabase, companyId, id)
if (!asset) {
return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 })
}
return NextResponse.json({ data: asset })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
)
export const PATCH = withRouteContext(
'assets.update',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const validation = await validateBody(request, UpdateAssetSchema)
if (!validation.success) return validation.response
// K3 component depreciation gating + cross-sum check.
// The Zod refinement cannot see the existing asset's acquisition_cost,
// so we do both the framework check and the sum validation here at
// route level before delegating to updateAsset().
if (validation.data.k3_components !== undefined && validation.data.k3_components !== null) {
const [{ data: company }, existing] = await Promise.all([
supabase
.from('companies')
.select('accounting_framework')
.eq('id', companyId)
.single(),
getAsset(supabase, companyId, id),
])
if (!company || company.accounting_framework !== 'k3') {
return NextResponse.json(
{
error: {
code: 'K3_REQUIRED_FOR_COMPONENTS',
message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).',
},
},
{ status: 422 },
)
}
if (!existing) {
return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 })
}
// Validate against the cost that will be in effect after this PATCH —
// a body that changes acquisition_cost and k3_components together must
// sum to the NEW cost, not the stored one.
const { errors } = validateComponents({
acquisition_cost: validation.data.acquisition_cost ?? Number(existing.acquisition_cost),
k3_components: validation.data.k3_components,
})
if (errors.length > 0) {
return NextResponse.json(
{
error: {
code: 'INVALID_K3_COMPONENTS',
message: errors.join(' '),
},
},
{ status: 400 },
)
}
}
// K2_EXCLUDED_ACCOUNT gate: when the patch touches the category or the
// asset/accumulated accounts, the asset must not END UP on an account the
// BAS reference flags as k2_excluded ("Ej K2") unless the company applies
// K3. The guard supplies the message, citing BFNAR 2016:10 punkt 10.4
// only for the egenupparbetade-immateriella group and staying generic for
// the other Ej K2 accounts (uppskjuten skatt, verkligt värde, ...), which
// this route can reach: UpdateAssetSchema has no BAS range refinement, so
// an explicit override outside the category range lands here first.
// The final accounts mirror updateAsset()'s resolution: a category
// change without explicit accounts realigns the triple to the new
// category's framework-aware defaults, so recategorizing to "Immateriell
// tillgång" lands a K2 company on the acquired pair 1090/1099 and passes.
// Only a deliberate override onto an Ej K2 account trips the gate.
// Patches that leave category and accounts alone skip the gate entirely,
// so legacy assets already sitting on an excluded account stay editable
// (name, notes, useful life, ...).
const touchesAccounts =
validation.data.category !== undefined ||
validation.data.bas_asset_account !== undefined ||
validation.data.bas_accumulated_account !== undefined
if (touchesAccounts) {
const [{ data: company }, existing] = await Promise.all([
supabase
.from('companies')
// entity_type rides along on the same fetch: the rejection wording
// must not cite BFNAR 2016:10 at an enskild firma, which prepares no
// årsredovisning under K2. See lib/bokslut/assets/k2-account-guard.ts.
.select('accounting_framework, entity_type')
.eq('id', companyId)
.single(),
getAsset(supabase, companyId, id),
])
if (!company || company.accounting_framework !== 'k3') {
if (!existing) {
return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 })
}
const finalCategory = validation.data.category ?? existing.category
const categoryDefaultsApply =
validation.data.category !== undefined &&
validation.data.category !== existing.category &&
validation.data.bas_asset_account === undefined &&
validation.data.bas_accumulated_account === undefined &&
validation.data.bas_expense_account === undefined
const defaults = defaultAccountsForCategory(
finalCategory,
company?.accounting_framework,
)
const excluded = findK2ExcludedAccount([
validation.data.bas_asset_account ??
(categoryDefaultsApply ? defaults.asset : existing.bas_asset_account),
validation.data.bas_accumulated_account ??
(categoryDefaultsApply ? defaults.accumulated : existing.bas_accumulated_account),
])
if (excluded) {
const messages = k2ExcludedAccountMessages(excluded, company?.entity_type)
return NextResponse.json(
{
error: {
code: 'K2_EXCLUDED_ACCOUNT',
message: messages.message_sv,
message_en: messages.message_en,
},
},
{ status: 422 },
)
}
}
}
try {
const asset = await updateAsset(supabase, companyId, id, validation.data)
return NextResponse.json({ data: asset })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
{ requireWrite: true },
)
+112
View File
@@ -0,0 +1,112 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
const { supabase, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/bokslut/assets/asset-service', () => ({
disposeAsset: vi.fn(),
}))
import { disposeAsset } from '@/lib/bokslut/assets/asset-service'
import { POST } from '../[id]/dispose/route'
const mockDisposeAsset = vi.mocked(disposeAsset)
const routeParams = { params: Promise.resolve({ id: 'asset-1' }) }
const validBody = {
disposal_type: 'sale',
disposed_at: '2026-06-30',
disposed_proceeds: 125_000,
proceeds_account: '1930',
fiscal_period_id: '11111111-1111-4111-8111-111111111111',
vat_treatment: 'standard_25',
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('POST /api/assets/[id]/dispose', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(
createMockRequest('/api/assets/asset-1/dispose', { method: 'POST', body: validBody }),
routeParams,
)
expect(response.status).toBe(401)
expect(mockDisposeAsset).not.toHaveBeenCalled()
})
it('returns 400 for inconsistent scrapping proceeds', async () => {
const response = await POST(
createMockRequest('/api/assets/asset-1/dispose', {
method: 'POST',
body: { ...validBody, disposal_type: 'scrap', disposed_proceeds: 100, vat_treatment: undefined },
}),
routeParams,
)
expect(response.status).toBe(400)
expect(mockDisposeAsset).not.toHaveBeenCalled()
})
it('returns 404 when the asset does not exist', async () => {
mockDisposeAsset.mockRejectedValue(Object.assign(new Error('Asset not found'), { code: 'ASSET_NOT_FOUND' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(
createMockRequest('/api/assets/asset-1/dispose', { method: 'POST', body: validBody }),
routeParams,
),
)
expect(status).toBe(404)
expect(body.error.code).toBe('ASSET_NOT_FOUND')
})
it('returns the atomically posted disposal', async () => {
mockDisposeAsset.mockResolvedValue({
asset: { id: 'asset-1', disposed_at: '2026-06-30' },
disposal_entry: { id: 'entry-1', status: 'posted', voucher_number: 42 },
gain_or_loss: 10_000,
} as Awaited<ReturnType<typeof disposeAsset>>)
const { status, body } = await parseJsonResponse<{ data: { gain_or_loss: number } }>(
await POST(
createMockRequest('/api/assets/asset-1/dispose', { method: 'POST', body: validBody }),
routeParams,
),
)
expect(status).toBe(200)
expect(body.data.gain_or_loss).toBe(10_000)
expect(mockDisposeAsset).toHaveBeenCalledWith(
supabase,
'company-1',
'user-1',
'asset-1',
validBody,
)
})
})
+633
View File
@@ -0,0 +1,633 @@
/**
* Tests for GET/PATCH /api/assets/[id].
*
* Exercises the routes through the real withRouteContext wrapper, mocking the
* asset service and auth/company dependencies. The K3 component cross-sum
* validation runs the REAL validateComponents so the regression case (body
* changes acquisition_cost and k3_components together — sum must match the
* NEW cost) is covered end to end.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
// Keep DEFAULT_ACCOUNTS_BY_CATEGORY (and other pure exports) real: the routes
// resolve category-default accounts through it for the K2_EXCLUDED_ACCOUNT
// framework gate. Only the service functions that hit Supabase are mocked.
vi.mock('@/lib/bokslut/assets/asset-service', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/bokslut/assets/asset-service')>()
return {
...actual,
createAsset: vi.fn(),
listAssets: vi.fn(),
getAsset: vi.fn(),
updateAsset: vi.fn(),
}
})
import { createAsset, getAsset, updateAsset } from '@/lib/bokslut/assets/asset-service'
import { GET, PATCH } from '../[id]/route'
import { POST } from '../route'
const mockGetAsset = vi.mocked(getAsset)
const mockUpdateAsset = vi.mocked(updateAsset)
const mockCreateAsset = vi.mocked(createAsset)
const routeParams = { params: Promise.resolve({ id: 'asset-1' }) }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('GET /api/assets/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/api/assets/asset-1'), routeParams)
expect(res.status).toBe(401)
})
it('returns 404 when the asset does not exist', async () => {
mockGetAsset.mockResolvedValue(null)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await GET(createMockRequest('/api/assets/asset-1'), routeParams)
)
expect(status).toBe(404)
expect(body.error.code).toBe('ASSET_NOT_FOUND')
})
})
describe('POST /api/assets', () => {
it('rejects legacy per-asset tax depreciation methods with 400', async () => {
const response = await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Maskin',
category: 'machinery',
acquisition_date: '2025-01-01',
acquisition_cost: 100_000,
useful_life_months: 60,
depreciation_method: 'declining_balance_30',
},
}))
expect(response.status).toBe(400)
})
it('creates a valid asset with ordinary linear depreciation', async () => {
mockCreateAsset.mockResolvedValue({ id: 'asset-new', depreciation_method: 'linear' } as never)
const response = await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Maskin',
category: 'machinery',
acquisition_date: '2025-01-01',
acquisition_cost: 100_000,
useful_life_months: 60,
depreciation_method: 'linear',
},
}))
expect(response.status).toBe(200)
expect(mockCreateAsset).toHaveBeenCalledWith(
supabase,
'company-1',
'user-1',
expect.objectContaining({ depreciation_method: 'linear' }),
)
})
// K2 forbids only EGENUPPARBETADE immateriella tillgångar; an ACQUIRED one
// (a bought licence, a trademark) is lawful, so the category defaults now
// resolve to the acquired pair 1090/1099 for a non-K3 company and the gate
// must let the create through. See
// .claude/skills/swedish-year-end-closing/references/k2-vs-k3.md:24.
it('lets a K2 company create an immaterial asset on the category defaults', async () => {
enqueue({ data: { accounting_framework: 'k2' } })
mockCreateAsset.mockResolvedValue({ id: 'asset-licence' } as never)
const response = await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Programvarulicens',
category: 'immaterial',
acquisition_date: '2025-01-01',
acquisition_cost: 100_000,
useful_life_months: 60,
},
}))
expect(response.status).toBe(200)
// No accounts in the body: the service resolves 1090/1099 itself, so the
// client never has to know the rule (asset-service.test.ts pins the pair).
expect(mockCreateAsset).toHaveBeenCalledWith(
supabase,
'company-1',
'user-1',
expect.objectContaining({ category: 'immaterial' }),
)
const [, , , input] = mockCreateAsset.mock.calls[0]
expect(input.bas_asset_account).toBeUndefined()
expect(input.bas_accumulated_account).toBeUndefined()
})
// Only a deliberate override onto an Ej K2 account is still unlawful.
it.each([
['1010', '1039'],
['1011', '1039'],
['1012', '1039'],
['1018', '1039'],
['1019', '1039'],
['1081', '1039'],
])(
'rejects a K2 company explicitly overriding onto %s with 422',
async (assetAccount, accumulatedAccount) => {
enqueue({ data: { accounting_framework: 'k2', entity_type: 'aktiebolag' } })
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string }
}>(
await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Utvecklingsprojekt',
category: 'immaterial',
acquisition_date: '2025-01-01',
acquisition_cost: 50_000,
useful_life_months: 60,
bas_asset_account: assetAccount,
bas_accumulated_account: accumulatedAccount,
},
}))
)
expect(status).toBe(422)
expect(body.error.code).toBe('K2_EXCLUDED_ACCOUNT')
expect(body.error.message).toContain(assetAccount)
// All six are kontogrupp 10 and the company is an AB preparing an
// årsredovisning, so the punkt 10.4 citation applies.
expect(body.error.message).toContain('BFNAR 2016:10 punkt 10.4')
expect(mockCreateAsset).not.toHaveBeenCalled()
},
)
// companies.accounting_framework is NOT NULL DEFAULT 'k2', so an enskild
// firma runs into the same gate. It prepares a förenklat årsbokslut, not an
// årsredovisning under BFNAR 2016:10, so the K2 citation would be a false
// legal claim and "use K3 instead" an impossible remedy. The block stands;
// the wording drops both and keeps the actionable 1090 remedy.
it('rejects an enskild firma on 1010 without citing BFNAR 2016:10 or K3', async () => {
enqueue({ data: { accounting_framework: 'k2', entity_type: 'enskild_firma' } })
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en: string }
}>(
await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Utvecklingsprojekt',
category: 'immaterial',
acquisition_date: '2025-01-01',
acquisition_cost: 50_000,
useful_life_months: 60,
bas_asset_account: '1010',
bas_accumulated_account: '1039',
},
}))
)
expect(status).toBe(422)
expect(body.error.code).toBe('K2_EXCLUDED_ACCOUNT')
expect(body.error.message).toContain('1010')
expect(body.error.message).not.toContain('BFNAR 2016:10')
expect(body.error.message).not.toContain('10.4')
expect(body.error.message).not.toContain('K3')
expect(body.error.message_en).not.toContain('BFNAR 2016:10')
expect(body.error.message_en).not.toContain('K3')
// Still actionable: the lawful account, and what the system did.
expect(body.error.message).toContain('1090')
expect(body.error.message).toContain('anläggningsregistret')
expect(mockCreateAsset).not.toHaveBeenCalled()
})
it('rejects a K2 company overriding the ACCUMULATED account onto 1019 with 422', async () => {
enqueue({ data: { accounting_framework: 'k2' } })
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(
await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Patent',
category: 'immaterial',
acquisition_date: '2025-01-01',
acquisition_cost: 50_000,
useful_life_months: 60,
bas_asset_account: '1030',
bas_accumulated_account: '1019',
},
}))
)
expect(status).toBe(422)
expect(body.error.code).toBe('K2_EXCLUDED_ACCOUNT')
expect(body.error.message).toContain('1019')
expect(mockCreateAsset).not.toHaveBeenCalled()
})
// Switching regelverk drags in komponentavskrivning and uppskjuten skatt and
// rewrites the whole årsredovisning: it is never the remedy for one account.
// The rejection must also not assert which framework the company applies,
// since the companies read behind it discards its error.
it('does not tell the user to switch accounting framework in the rejection', async () => {
enqueue({ data: { accounting_framework: 'k2' } })
const { body } = await parseJsonResponse<{
error: { message: string; message_en: string }
}>(
await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Utvecklingsprojekt',
category: 'immaterial',
acquisition_date: '2025-01-01',
acquisition_cost: 50_000,
useful_life_months: 60,
bas_asset_account: '1010',
bas_accumulated_account: '1039',
},
}))
)
expect(body.error.message).not.toContain('Byt regelverk')
expect(body.error.message).not.toContain('Inställningar')
expect(body.error.message).not.toContain('företaget tillämpar')
expect(body.error.message_en).not.toContain('Switch the accounting framework')
expect(body.error.message_en).not.toContain('Settings')
// It points at the lawful account instead.
expect(body.error.message).toContain('1090')
expect(body.error.message_en).toContain('1090')
})
it('accepts a K2 company creating an immaterial asset on a purchased pair (1030/1039)', async () => {
enqueue({ data: { accounting_framework: 'k2' } })
mockCreateAsset.mockResolvedValue({ id: 'asset-patent' } as never)
const response = await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Patent',
category: 'immaterial',
acquisition_date: '2025-01-01',
acquisition_cost: 80_000,
useful_life_months: 60,
bas_asset_account: '1030',
bas_accumulated_account: '1039',
},
}))
expect(response.status).toBe(200)
expect(mockCreateAsset).toHaveBeenCalledWith(
supabase,
'company-1',
'user-1',
expect.objectContaining({ bas_asset_account: '1030' }),
)
})
it('accepts a K3 company creating an immaterial asset on the 1010/1019 defaults', async () => {
enqueue({ data: { accounting_framework: 'k3' } })
mockCreateAsset.mockResolvedValue({ id: 'asset-dev' } as never)
const response = await POST(createMockRequest('/api/assets', {
method: 'POST',
body: {
name: 'Utvecklingsutgifter plattform',
category: 'immaterial',
acquisition_date: '2025-01-01',
acquisition_cost: 100_000,
useful_life_months: 60,
},
}))
expect(response.status).toBe(200)
expect(mockCreateAsset).toHaveBeenCalled()
})
})
describe('PATCH /api/assets/[id]', () => {
it('rejects legacy per-asset tax depreciation methods with 400', async () => {
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: { depreciation_method: 'declining_balance_30' },
})
const { status } = await parseJsonResponse(await PATCH(req, routeParams))
expect(status).toBe(400)
expect(mockUpdateAsset).not.toHaveBeenCalled()
})
it('rejects an invalid body (non-positive acquisition_cost) with 400', async () => {
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: { acquisition_cost: -5 },
})
const { status } = await parseJsonResponse(await PATCH(req, routeParams))
expect(status).toBe(400)
expect(mockUpdateAsset).not.toHaveBeenCalled()
})
it('rejects k3_components for a K2 company with 422', async () => {
enqueue({ data: { accounting_framework: 'k2' } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockGetAsset.mockResolvedValue({ id: 'asset-1', acquisition_cost: 100000 } as any)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: {
k3_components: [{ name: 'Stomme', cost: 100000, useful_life_months: 600 }],
},
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(422)
expect(body.error.code).toBe('K3_REQUIRED_FOR_COMPONENTS')
expect(mockUpdateAsset).not.toHaveBeenCalled()
})
it('validates the component sum against the NEW acquisition_cost when both change', async () => {
// Regression: stored cost is 100 000 but the PATCH raises it to 120 000.
// Components summing to 120 000 must pass — previously they were checked
// against the stale stored cost and wrongly rejected.
enqueue({ data: { accounting_framework: 'k3' } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockGetAsset.mockResolvedValue({ id: 'asset-1', acquisition_cost: 100000 } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockUpdateAsset.mockResolvedValue({ id: 'asset-1', acquisition_cost: 120000 } as any)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: {
acquisition_cost: 120000,
k3_components: [
{ name: 'Stomme', cost: 90000, useful_life_months: 600 },
{ name: 'Tak', cost: 30000, useful_life_months: 240 },
],
},
})
const { status } = await parseJsonResponse(await PATCH(req, routeParams))
expect(status).toBe(200)
expect(mockUpdateAsset).toHaveBeenCalled()
})
it('rejects components that sum to the OLD cost when the PATCH changes the cost', async () => {
enqueue({ data: { accounting_framework: 'k3' } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockGetAsset.mockResolvedValue({ id: 'asset-1', acquisition_cost: 100000 } as any)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: {
acquisition_cost: 120000,
k3_components: [{ name: 'Stomme', cost: 100000, useful_life_months: 600 }],
},
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(400)
expect(body.error.code).toBe('INVALID_K3_COMPONENTS')
expect(mockUpdateAsset).not.toHaveBeenCalled()
})
it('rejects a K2 company patching the asset account onto 1010 with 422', async () => {
enqueue({ data: { accounting_framework: 'k2', entity_type: 'aktiebolag' } })
mockGetAsset.mockResolvedValue({
id: 'asset-1',
category: 'immaterial',
bas_asset_account: '1030',
bas_accumulated_account: '1039',
bas_expense_account: '7813',
} as never)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: { bas_asset_account: '1010' },
})
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(422)
expect(body.error.code).toBe('K2_EXCLUDED_ACCOUNT')
expect(body.error.message).toContain('1010')
// AB on the companies row, so the K2 citation is the right one here.
expect(body.error.message).toContain('BFNAR 2016:10 punkt 10.4')
expect(mockUpdateAsset).not.toHaveBeenCalled()
})
it('rejects a K2 company recategorizing AND overriding onto 1010 with 422', async () => {
// Explicit accounts suppress the realign in updateAsset(), so the gate has
// to evaluate the override rather than the (now lawful) category defaults.
enqueue({ data: { accounting_framework: 'k2' } })
mockGetAsset.mockResolvedValue({
id: 'asset-1',
category: 'equipment',
bas_asset_account: '1220',
bas_accumulated_account: '1229',
bas_expense_account: '7832',
} as never)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: {
category: 'immaterial',
bas_asset_account: '1010',
bas_accumulated_account: '1019',
},
})
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(422)
expect(body.error.code).toBe('K2_EXCLUDED_ACCOUNT')
expect(body.error.message).toContain('1010')
expect(mockUpdateAsset).not.toHaveBeenCalled()
})
// The Ej K2 flag also covers accounts that have nothing to do with
// intangibles (uppskjuten skatt, verkligt värde, säkringsredovisning, ...).
// PATCH can reach them: UpdateAssetSchema has no BAS range refinement, so an
// override outside the category range hits this gate before updateAsset()
// raises its range error. Those rejections must NOT claim punkt 10.4.
it('rejects a K2 company patching onto 1370 without citing the intangible rule', async () => {
enqueue({ data: { accounting_framework: 'k2', entity_type: 'aktiebolag' } })
mockGetAsset.mockResolvedValue({
id: 'asset-1',
category: 'immaterial',
bas_asset_account: '1030',
bas_accumulated_account: '1039',
bas_expense_account: '7813',
} as never)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: { bas_asset_account: '1370' },
})
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en: string }
}>(await PATCH(req, routeParams))
expect(status).toBe(422)
expect(body.error.code).toBe('K2_EXCLUDED_ACCOUNT')
expect(body.error.message).toContain('1370')
expect(body.error.message).toContain('Ej K2')
expect(body.error.message).toContain('K3')
expect(body.error.message).not.toContain('10.4')
expect(body.error.message).not.toContain('egenupparbetade')
expect(body.error.message_en).toContain('Ej K2')
expect(body.error.message_en).not.toContain('10.4')
expect(body.error.message_en).not.toContain('intangible')
expect(mockUpdateAsset).not.toHaveBeenCalled()
})
// The concrete case this route used to break: a K2 aktiebolag bought a
// software licence, first filed it as "Inventarier", and now recategorizes
// it to "Immateriell tillgång" from a dialog that sends only the changed
// field and has no account inputs. K2 forbids EGENUPPARBETADE intangibles
// only, so this is lawful and the defaults must land on the acquired pair.
it('lets a K2 company recategorize to immaterial (defaults land on 1090/1099)', async () => {
enqueue({ data: { accounting_framework: 'k2' } })
mockGetAsset.mockResolvedValue({
id: 'asset-1',
category: 'equipment',
bas_asset_account: '1220',
bas_accumulated_account: '1229',
bas_expense_account: '7832',
} as never)
mockUpdateAsset.mockResolvedValue({
id: 'asset-1',
category: 'immaterial',
bas_asset_account: '1090',
bas_accumulated_account: '1099',
} as never)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: { category: 'immaterial' },
})
const { status, body } = await parseJsonResponse<{
data: { bas_asset_account: string; bas_accumulated_account: string }
}>(await PATCH(req, routeParams))
expect(status).toBe(200)
expect(body.data.bas_asset_account).toBe('1090')
expect(body.data.bas_accumulated_account).toBe('1099')
// The route forwards the bare category patch: updateAsset realigns the
// triple itself (asset-service.test.ts pins the realigned pair).
expect(mockUpdateAsset).toHaveBeenCalledWith(supabase, 'company-1', 'asset-1', {
category: 'immaterial',
})
})
it('allows a K2 company moving a legacy 1010 asset onto a purchased pair', async () => {
enqueue({ data: { accounting_framework: 'k2' } })
mockGetAsset.mockResolvedValue({
id: 'asset-1',
category: 'immaterial',
bas_asset_account: '1010',
bas_accumulated_account: '1019',
bas_expense_account: '7811',
} as never)
mockUpdateAsset.mockResolvedValue({ id: 'asset-1', bas_asset_account: '1030' } as never)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: { bas_asset_account: '1030', bas_accumulated_account: '1039' },
})
const { status } = await parseJsonResponse(await PATCH(req, routeParams))
expect(status).toBe(200)
expect(mockUpdateAsset).toHaveBeenCalled()
})
it('allows a K3 company patching the asset account onto 1010', async () => {
enqueue({ data: { accounting_framework: 'k3' } })
mockGetAsset.mockResolvedValue({
id: 'asset-1',
category: 'immaterial',
bas_asset_account: '1030',
bas_accumulated_account: '1039',
bas_expense_account: '7813',
} as never)
mockUpdateAsset.mockResolvedValue({ id: 'asset-1', bas_asset_account: '1010' } as never)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: { bas_asset_account: '1010', bas_accumulated_account: '1019' },
})
const { status } = await parseJsonResponse(await PATCH(req, routeParams))
expect(status).toBe(200)
expect(mockUpdateAsset).toHaveBeenCalled()
})
it('skips the framework gate for patches that touch neither category nor accounts', async () => {
// No company row enqueued and getAsset unmocked: if the gate ran anyway
// it would resolve a null company (treated as K2) and 404 on the missing
// asset. A 200 therefore proves the name-only patch never hit the gate,
// which keeps legacy K2 assets already sitting on 1010 editable.
mockUpdateAsset.mockResolvedValue({ id: 'asset-1', name: 'Nytt namn' } as never)
const req = createMockRequest('/api/assets/asset-1', {
method: 'PATCH',
body: { name: 'Nytt namn' },
})
const { status } = await parseJsonResponse(await PATCH(req, routeParams))
expect(status).toBe(200)
expect(mockUpdateAsset).toHaveBeenCalled()
})
})
+272
View File
@@ -0,0 +1,272 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse } from '@/lib/errors/get-structured-error'
import { validateBody } from '@/lib/api/validate'
import { K3ComponentSchema } from '@/lib/api/schemas'
import {
createAsset,
listAssets,
defaultAccountsForCategory,
} from '@/lib/bokslut/assets/asset-service'
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
import {
findK2ExcludedAccount,
k2ExcludedAccountMessages,
} from '@/lib/bokslut/assets/k2-account-guard'
import type { AssetCategory, WritableDepreciationMethod } from '@/types'
const ASSET_CATEGORIES: readonly AssetCategory[] = [
'immaterial',
'building',
'land_improvement',
'machinery',
'equipment',
'vehicle',
'computer',
'other_tangible',
] as const
const DEPRECIATION_METHODS: readonly WritableDepreciationMethod[] = [
'linear',
] as const
const CreateAssetSchema = z
.object({
name: z.string().min(1),
category: z.enum(ASSET_CATEGORIES as unknown as [AssetCategory, ...AssetCategory[]]),
acquisition_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
// Positive: a zero-value asset would dodge the depreciation engine and
// create a no-op row that confuses the balance sheet.
acquisition_cost: z.number().positive(),
salvage_value: z.number().nonnegative().optional(),
useful_life_months: z.number().int().positive(),
depreciation_method: z
.enum(DEPRECIATION_METHODS as unknown as [
WritableDepreciationMethod,
...WritableDepreciationMethod[],
])
.optional(),
restvarde_target: z.null().optional(),
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
// K3 component depreciation (BFNAR 2012:1 ch.17.4). Only meaningful for
// companies with accounting_framework='k3': the route handler rejects
// K3_REQUIRED_FOR_COMPONENTS for K2 companies. When present, the engine
// dispatches to per-component linear depreciation instead of the
// asset-level depreciation_method.
k3_components: z.array(K3ComponentSchema).nullable().optional(),
notes: z.string().optional(),
})
.superRefine((value, ctx) => {
// Defense-in-depth: when the user overrides BAS accounts, refuse anything
// outside the legitimate range for the asset category so the chart stays
// BAS-aligned and INK2R mappings continue to work.
validateBasOverrides(value, ctx)
validateK3Components(value, ctx)
})
function validateK3Components(
value: {
acquisition_cost: number
k3_components?: { name: string; cost: number; useful_life_months: number; salvage_value?: number }[] | null
},
ctx: z.RefinementCtx,
): void {
if (value.k3_components === undefined || value.k3_components === null) return
const { errors } = validateComponents({
acquisition_cost: value.acquisition_cost,
k3_components: value.k3_components,
})
for (const message of errors) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['k3_components'],
message,
})
}
}
function validateBasOverrides(
value: {
category: AssetCategory
bas_asset_account?: string
bas_accumulated_account?: string
bas_expense_account?: string
},
ctx: z.RefinementCtx,
): void {
const ranges = BAS_RANGES_BY_CATEGORY[value.category]
if (value.bas_asset_account && !inRange(value.bas_asset_account, ranges.asset)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['bas_asset_account'],
message: `Account must be in range ${ranges.asset[0]}-${ranges.asset[1]} for ${value.category}`,
})
}
if (
value.bas_accumulated_account &&
!inRange(value.bas_accumulated_account, ranges.accumulated)
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['bas_accumulated_account'],
message: `Account must be in range ${ranges.accumulated[0]}-${ranges.accumulated[1]} for ${value.category}`,
})
}
if (value.bas_expense_account && !inRange(value.bas_expense_account, ranges.expense)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['bas_expense_account'],
message: `Account must be in range ${ranges.expense[0]}-${ranges.expense[1]} for ${value.category}`,
})
}
// Anskaffningskonto and ackumulerade-avskrivningar-konto live in the same
// class range (e.g. 1010-1099 for immaterial, 1100-1199 for buildings), so
// a user could pick the same account for both. That would silently net
// acquisition cost against accumulated depreciation in one bucket and
// break the INK2R 720x mappings. Force them apart.
if (
value.bas_asset_account &&
value.bas_accumulated_account &&
value.bas_asset_account === value.bas_accumulated_account
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['bas_accumulated_account'],
message:
'Anskaffningskonto och ackumulerade-avskrivningar-konto måste vara olika konton.',
})
}
}
const BAS_RANGES_BY_CATEGORY: Record<
AssetCategory,
{ asset: [string, string]; accumulated: [string, string]; expense: [string, string] }
> = {
immaterial: { asset: ['1010', '1099'], accumulated: ['1010', '1099'], expense: ['7810', '7819'] },
building: { asset: ['1100', '1199'], accumulated: ['1100', '1199'], expense: ['7820', '7829'] },
land_improvement:{ asset: ['1150', '1159'], accumulated: ['1150', '1159'], expense: ['7820', '7829'] },
machinery: { asset: ['1210', '1219'], accumulated: ['1210', '1219'], expense: ['7830', '7839'] },
equipment: { asset: ['1220', '1229'], accumulated: ['1220', '1229'], expense: ['7830', '7839'] },
vehicle: { asset: ['1240', '1249'], accumulated: ['1240', '1249'], expense: ['7830', '7839'] },
computer: { asset: ['1250', '1259'], accumulated: ['1250', '1259'], expense: ['7830', '7839'] },
other_tangible: { asset: ['1280', '1299'], accumulated: ['1280', '1299'], expense: ['7830', '7839'] },
}
function inRange(account: string, range: [string, string]): boolean {
return account >= range[0] && account <= range[1]
}
export const GET = withRouteContext('assets.list', async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const url = new URL(request.url)
const activeOnly = url.searchParams.get('active') === 'true'
try {
const data = await listAssets(supabase, companyId, { activeOnly })
// Annotate each asset with whether any depreciation has been posted
// against it. The UI uses this to lock the acquisition-basis fields
// (date/cost/category): once avskrivningar are booked a correction must
// go through storno (the service enforces the same rule server-side).
const postedAssetIds = new Set<string>()
if (data.length > 0) {
const { data: posted, error } = await supabase
.from('depreciation_schedules')
.select('asset_id')
.eq('company_id', companyId)
.in(
'asset_id',
data.map((a) => a.id),
)
.not('journal_entry_id', 'is', null)
if (error) throw new Error(`Failed to load depreciation status: ${error.message}`)
for (const row of (posted ?? []) as { asset_id: string }[]) {
postedAssetIds.add(row.asset_id)
}
}
const annotated = data.map((asset) => ({
...asset,
has_posted_depreciation: postedAssetIds.has(asset.id),
}))
return NextResponse.json({ data: annotated })
} catch (err) {
return errorResponse(err, log, { requestId })
}
})
export const POST = withRouteContext(
'assets.create',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const validation = await validateBody(request, CreateAssetSchema)
if (!validation.success) return validation.response
// Framework gates. One companies fetch serves both checks:
// 1. K3_REQUIRED_FOR_COMPONENTS: K3 component depreciation is only
// meaningful when the company applies the K3 framework. Reject the
// write with 422 (Unprocessable Entity) rather than silently dropping
// the field so the user knows their input was discarded.
// 2. K2_EXCLUDED_ACCOUNT: accounts flagged k2_excluded ("Ej K2") in the
// BAS reference may not carry assets under K2. Checked on the RESOLVED
// accounts, mirroring what createAsset() will persist: an explicit
// override, or the framework-aware category default (a non-K3 company's
// immaterial default is the acquired pair 1090/1099, which is lawful,
// so only a deliberate override can trip this). The guard supplies the
// message: the egenupparbetade group cites BFNAR 2016:10 punkt 10.4,
// other Ej K2 accounts do not, and an enskild firma gets neither, since
// K2 is not its regelverk. entity_type rides along on the same fetch.
const { data: company } = await supabase
.from('companies')
.select('accounting_framework, entity_type')
.eq('id', companyId)
.single()
const isK3Company = company?.accounting_framework === 'k3'
if (
validation.data.k3_components !== undefined &&
validation.data.k3_components !== null &&
!isK3Company
) {
return NextResponse.json(
{
error: {
code: 'K3_REQUIRED_FOR_COMPONENTS',
message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).',
},
},
{ status: 422 },
)
}
if (!isK3Company) {
const defaults = defaultAccountsForCategory(
validation.data.category,
company?.accounting_framework,
)
const excluded = findK2ExcludedAccount([
validation.data.bas_asset_account ?? defaults.asset,
validation.data.bas_accumulated_account ?? defaults.accumulated,
])
if (excluded) {
const messages = k2ExcludedAccountMessages(excluded, company?.entity_type)
return NextResponse.json(
{
error: {
code: 'K2_EXCLUDED_ACCOUNT',
message: messages.message_sv,
message_en: messages.message_en,
},
},
{ status: 422 },
)
}
}
try {
const asset = await createAsset(supabase, companyId, user.id, validation.data)
return NextResponse.json({ data: asset })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
{ requireWrite: true },
)
@@ -0,0 +1,37 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool } from '@/tests/pg/setup'
import { insertAuthUser } from '@/tests/pg/fixtures'
describe('audit-log.pg: append-only immutability', () => {
it('rejects UPDATE on audit_log rows', async () => {
const userId = await insertAuthUser()
const auditId = randomUUID()
await getPool().query(
`INSERT INTO public.audit_log (id, user_id, action, description)
VALUES ($1, $2, 'SECURITY_EVENT', 'pg-real seed')`,
[auditId, userId],
)
await expect(
getPool().query(
`UPDATE public.audit_log SET description = 'tampered' WHERE id = $1`,
[auditId],
),
).rejects.toThrow(/cannot be modified or deleted/i)
})
it('rejects DELETE on audit_log rows', async () => {
const userId = await insertAuthUser()
const auditId = randomUUID()
await getPool().query(
`INSERT INTO public.audit_log (id, user_id, action, description)
VALUES ($1, $2, 'SECURITY_EVENT', 'pg-real seed')`,
[auditId, userId],
)
await expect(
getPool().query(`DELETE FROM public.audit_log WHERE id = $1`, [auditId]),
).rejects.toThrow(/cannot be modified or deleted/i)
})
})
+139
View File
@@ -0,0 +1,139 @@
/**
* Tests for GET /api/audit-trail.
*
* Exercises the route through the real withRouteContext wrapper, mocking its
* auth/company dependencies and the audit service. Covers: auth 401, query
* validation 400, filter passthrough, and the canonical 500 envelope.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/core/audit/audit-service', () => ({
getAuditLog: vi.fn(),
}))
import { getAuditLog } from '@/lib/core/audit/audit-service'
import { GET } from '../route'
const mockGetAuditLog = vi.mocked(getAuditLog)
const routeParams = { params: Promise.resolve({}) }
beforeEach(() => {
vi.clearAllMocks()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: {}, error: null })
})
describe('GET /api/audit-trail', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/audit-trail')
const { status, body } = await parseJsonResponse(await GET(req, routeParams))
expect(status).toBe(401)
expect(body).toEqual({ error: 'Unauthorized' })
})
it('returns 400 for an unknown action filter', async () => {
const req = createMockRequest('/api/audit-trail', {
searchParams: { action: 'NOT_AN_ACTION' },
})
const { status } = await parseJsonResponse(await GET(req, routeParams))
expect(status).toBe(400)
expect(mockGetAuditLog).not.toHaveBeenCalled()
})
it('returns 400 for a non-numeric page', async () => {
const req = createMockRequest('/api/audit-trail', {
searchParams: { page: 'abc' },
})
const { status } = await parseJsonResponse(await GET(req, routeParams))
expect(status).toBe(400)
expect(mockGetAuditLog).not.toHaveBeenCalled()
})
it('returns audit log with data and count, defaulting pagination', async () => {
const entries = [
{ id: '1', action: 'INSERT', table_name: 'journal_entries', created_at: '2024-01-01T00:00:00Z' },
{ id: '2', action: 'COMMIT', table_name: 'journal_entries', created_at: '2024-01-02T00:00:00Z' },
]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockGetAuditLog.mockResolvedValue({ data: entries as any, count: 2 })
const req = createMockRequest('/api/audit-trail')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { status, body } = await parseJsonResponse<{ data: any[]; count: number }>(
await GET(req, routeParams)
)
expect(status).toBe(200)
expect(body.data).toHaveLength(2)
expect(body.count).toBe(2)
expect(mockGetAuditLog).toHaveBeenCalledWith(
expect.anything(),
'company-1',
expect.objectContaining({ page: 1, pageSize: 50 })
)
})
it('passes query param filters to getAuditLog', async () => {
mockGetAuditLog.mockResolvedValue({ data: [], count: 0 })
const req = createMockRequest('/api/audit-trail', {
searchParams: {
action: 'INSERT',
table_name: 'journal_entries',
record_id: 'rec-1',
from_date: '2024-01-01',
to_date: '2024-12-31',
page: '2',
page_size: '25',
},
})
await GET(req, routeParams)
expect(mockGetAuditLog).toHaveBeenCalledWith(
expect.anything(),
'company-1',
{
action: 'INSERT',
table_name: 'journal_entries',
record_id: 'rec-1',
from_date: '2024-01-01',
to_date: '2024-12-31',
page: 2,
pageSize: 25,
}
)
})
it('returns the canonical error envelope on service failure', async () => {
mockGetAuditLog.mockRejectedValue(new Error('DB error'))
const req = createMockRequest('/api/audit-trail')
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await GET(req, routeParams)
)
expect(status).toBe(500)
expect(body.error.code).toBe('INTERNAL_ERROR')
})
})
+30
View File
@@ -0,0 +1,30 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateQuery } from '@/lib/api/validate'
import { AuditTrailQuerySchema } from '@/lib/api/schemas'
import { getAuditLog } from '@/lib/core/audit/audit-service'
// GET /api/audit-trail — paginated audit log for the active company.
// The audit log is written exclusively by SECURITY DEFINER triggers; this
// endpoint is read-only.
export const GET = withRouteContext(
'audit_trail.list',
async (request, ctx) => {
const { supabase, companyId, log } = ctx
const query = validateQuery(request, AuditTrailQuerySchema, {
log,
operation: 'audit_trail.list',
})
if (!query.success) return query.response
const { page, page_size, ...filters } = query.data
const result = await getAuditLog(supabase, companyId, {
...filters,
page,
pageSize: page_size,
})
return NextResponse.json({ data: result.data, count: result.count })
},
)
@@ -0,0 +1,360 @@
/**
* Tests for POST /api/auth/email-hook (Supabase Send Email hook).
*
* Unauthenticated by design: the guard is the Standard Webhooks signature.
* Signature material is computed with node:crypto exactly like Supabase does.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { createHmac, randomBytes } from 'node:crypto'
import type { Brand } from '@/lib/branding/resolve'
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandByHost: vi.fn(),
// The one registry read: the trusted-origin resolver classifies the
// redirect_to host through it, and the hook reads the sender brand from it.
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
// Imported by lib/email/brand-sender (not called on the hook path).
resolveBrandForCompany: vi.fn(),
}))
const CANONICAL = 'https://app.gnubok.se'
/** The one registered brand host in these tests; everything else is unknown. */
const BRAND_HOST = 'app.siffra.se'
vi.mock('@/lib/branding/service', () => ({
getBranding: () => ({ appName: 'Accounted', appUrl: 'https://app.gnubok.se' }),
}))
const sendEmailMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/email/service', () => ({
getEmailService: () => ({ sendEmail: sendEmailMock, isConfigured: () => true }),
}))
import { POST } from '../route'
const KEY = randomBytes(24)
const SECRET = `v1,whsec_${KEY.toString('base64')}`
function makeBrand(overrides: Partial<Brand> = {}): Brand {
return {
id: 'brand-1',
teamId: 'team-1',
domain: 'app.siffra.se',
appName: 'Siffra',
logoUrl: null,
brandColor: '#123456',
chromeColor: null,
fontKey: 'default',
supportEmail: 'support@siffra.se',
authEmailFrom: 'noreply@post.siffra.se',
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
...overrides,
}
}
function signedRequest(rawBody: string, opts?: { badSignature?: boolean; headers?: Record<string, string> }): Request {
const id = 'msg_1'
const timestamp = String(Math.floor(Date.now() / 1000))
const signature = createHmac('sha256', KEY)
.update(`${id}.${timestamp}.${rawBody}`)
.digest('base64')
return new Request('http://localhost:3000/api/auth/email-hook', {
method: 'POST',
body: rawBody,
headers: {
'content-type': 'application/json',
'webhook-id': id,
'webhook-timestamp': timestamp,
'webhook-signature': opts?.badSignature ? 'v1,AAAA' : `v1,${signature}`,
...opts?.headers,
},
})
}
function hookPayload(overrides?: {
user?: Record<string, unknown>
email_data?: Record<string, unknown>
}): string {
return JSON.stringify({
user: { email: 'user@example.se', ...overrides?.user },
email_data: {
token: '123456',
token_hash: 'hash-1',
redirect_to: 'https://app.gnubok.se/auth/callback?next=/reset-password',
email_action_type: 'recovery',
site_url: 'https://app.gnubok.se',
...overrides?.email_data,
},
})
}
const ORIGINAL_APP_URL = process.env.NEXT_PUBLIC_APP_URL
beforeEach(() => {
vi.clearAllMocks()
process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET = SECRET
process.env.NEXT_PUBLIC_APP_URL = CANONICAL
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
brand: host === BRAND_HOST ? makeBrand() : null,
lookupFailed: false,
}))
sendEmailMock.mockResolvedValue({ success: true, messageId: 'msg-1' })
})
afterEach(() => {
delete process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
if (ORIGINAL_APP_URL === undefined) delete process.env.NEXT_PUBLIC_APP_URL
else process.env.NEXT_PUBLIC_APP_URL = ORIGINAL_APP_URL
})
describe('POST /api/auth/email-hook', () => {
it('returns 500 when the hook secret is not configured', async () => {
delete process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(500)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('returns 401 for an invalid signature', async () => {
const res = await POST(signedRequest(hookPayload(), { badSignature: true }))
expect(res.status).toBe(401)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('returns 400 for a signed but malformed payload', async () => {
const res = await POST(signedRequest('not-json'))
expect(res.status).toBe(400)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('sends canonical recovery mail linking to the originating host (no brand)', async () => {
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({})
expect(sendEmailMock).toHaveBeenCalledTimes(1)
const options = sendEmailMock.mock.calls[0][0]
expect(options.to).toBe('user@example.se')
expect(options.subject).toBe('Återställ ditt lösenord')
expect(options.fromName).toBeUndefined()
expect(options.fromAddress).toBeUndefined()
expect(options.replyTo).toBeUndefined()
// token_hash + verifyOtp pattern on the originating host, preserving the
// existing next=/reset-password query.
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Freset-password')
expect(options.text).toContain('token_hash=hash-1')
expect(options.text).toContain('type=recovery')
})
it('brands the mail from the redirect_to host and rides the verified brand sender', async () => {
const res = await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'signup',
redirect_to: 'https://app.siffra.se/auth/callback',
},
}),
),
)
expect(res.status).toBe(200)
expect(resolveBrandResultByHostMock).toHaveBeenCalledWith('app.siffra.se')
const options = sendEmailMock.mock.calls[0][0]
expect(options.fromName).toBe('Siffra')
expect(options.fromAddress).toBe('noreply@post.siffra.se')
expect(options.replyTo).toBe('support@siffra.se')
expect(options.html).toContain('Siffra')
expect(options.html).not.toMatch(/accounted/i)
expect(options.text).toContain('https://app.siffra.se/auth/callback?token_hash=hash-1')
expect(options.text).toContain('type=signup')
})
it('uses the via-fallback for a brand without a verified sender domain', async () => {
resolveBrandResultByHostMock.mockResolvedValue({
brand: makeBrand({ senderDomainStatus: 'pending' }),
lookupFailed: false,
})
await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'magiclink',
redirect_to: 'https://app.siffra.se/auth/callback',
},
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.fromName).toBe('Siffra')
expect(options.fromAddress).toBeUndefined()
})
it('sends two mails for a secure email change', async () => {
await POST(
signedRequest(
hookPayload({
user: { email: 'current@example.se', new_email: 'new@example.se' },
email_data: {
email_action_type: 'email_change',
token_hash: 'hash-new-address',
token_hash_new: 'hash-current-address',
redirect_to: 'https://app.gnubok.se/auth/callback',
},
}),
),
)
expect(sendEmailMock).toHaveBeenCalledTimes(2)
const first = sendEmailMock.mock.calls[0][0]
const second = sendEmailMock.mock.calls[1][0]
// token_hash confirms at the NEW address, token_hash_new at the current.
expect(first.to).toBe('new@example.se')
expect(first.text).toContain('token_hash=hash-new-address')
expect(second.to).toBe('current@example.se')
expect(second.text).toContain('token_hash=hash-current-address')
})
it('sends the OTP code for reauthentication without a link', async () => {
await POST(
signedRequest(
hookPayload({
email_data: { email_action_type: 'reauthentication', token: '424242' },
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.subject).toBe('Din verifieringskod')
expect(options.text).toContain('424242')
expect(options.text).not.toContain('token_hash=')
})
it('builds the callback URL when redirect_to points at a plain path', async () => {
await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'magiclink',
redirect_to: 'https://app.gnubok.se/settings/account',
},
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Fsettings%2Faccount')
expect(options.text).toContain('type=magiclink')
})
it('returns 500 when the email provider fails, so Supabase retries', async () => {
sendEmailMock.mockResolvedValue({ success: false, error: 'provider down' })
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(500)
})
describe('redirect_to destinations (signature proves the sender, not the destination)', () => {
it.each([
['an unknown host', 'https://evil.example/auth/callback?next=/reset-password'],
['a lookalike of a registered host', 'https://app.siffra.se.evil.example/auth/callback'],
['a registered host on a non-default port', 'https://app.siffra.se:8443/auth/callback'],
['a credential-bearing URL', 'https://app.siffra.se@evil.example/auth/callback'],
// URL.origin drops userinfo: the host alone would pass as trusted.
['credentials on a registered host', 'https://evil.example@app.siffra.se/auth/callback?next=/x'],
['credentials on the canonical host', 'https://user:pw@app.gnubok.se/auth/callback?next=/x'],
['a malformed value', 'not a url'],
])('links %s to the canonical callback without the requested path', async (_label, redirectTo) => {
const res = await POST(
signedRequest(hookPayload({ email_data: { redirect_to: redirectTo } })),
)
expect(res.status).toBe(200)
const options = sendEmailMock.mock.calls[0][0]
expect(options.text).toContain(
'https://app.gnubok.se/auth/callback?token_hash=hash-1&type=recovery',
)
expect(options.text).not.toContain('evil.example')
expect(options.text).not.toContain(':8443')
expect(options.text).not.toContain('next=')
// Canonical link means canonical sender: brand and destination agree.
expect(options.fromName).toBeUndefined()
expect(options.fromAddress).toBeUndefined()
})
it('upgrades http on a registered brand host to https and drops the requested path', async () => {
await POST(
signedRequest(
hookPayload({
email_data: { redirect_to: 'http://app.siffra.se/auth/callback?next=/settings' },
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.text).toContain(
'https://app.siffra.se/auth/callback?token_hash=hash-1&type=recovery',
)
expect(options.text).not.toContain('http://')
expect(options.text).not.toContain('next=')
expect(options.fromName).toBe('Siffra')
})
it('keeps the requested path on a registered brand host', async () => {
await POST(
signedRequest(
hookPayload({
email_data: { redirect_to: 'https://app.siffra.se/auth/callback?next=%2Freset-password' },
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.text).toContain(
'https://app.siffra.se/auth/callback?next=%2Freset-password&token_hash=hash-1',
)
expect(options.fromName).toBe('Siffra')
})
it('falls back to the canonical callback when redirect_to is missing', async () => {
await POST(signedRequest(hookPayload({ email_data: { redirect_to: undefined } })))
const options = sendEmailMock.mock.calls[0][0]
expect(options.text).toContain('https://app.gnubok.se/auth/callback?token_hash=hash-1')
})
it('returns 500 without sending when the brand read fails after the origin resolved', async () => {
// First read (origin classification) succeeds, second (sender) fails:
// never platform-branded mail carrying a brand link.
resolveBrandResultByHostMock
.mockResolvedValueOnce({ brand: makeBrand(), lookupFailed: false })
.mockResolvedValueOnce({ brand: null, lookupFailed: true })
const res = await POST(
signedRequest(
hookPayload({ email_data: { redirect_to: 'https://app.siffra.se/auth/callback' } }),
),
)
expect(res.status).toBe(500)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('still sends canonical mail when the brand read fails on the canonical origin', async () => {
resolveBrandResultByHostMock.mockResolvedValue({ brand: null, lookupFailed: true })
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(200)
const options = sendEmailMock.mock.calls[0][0]
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Freset-password')
expect(options.fromName).toBeUndefined()
})
it('returns 500 without sending when the brand registry cannot be read', async () => {
resolveBrandResultByHostMock.mockResolvedValue({ brand: null, lookupFailed: true })
const res = await POST(
signedRequest(
hookPayload({ email_data: { redirect_to: 'https://app.siffra.se/auth/callback' } }),
),
)
expect(res.status).toBe(500)
expect(sendEmailMock).not.toHaveBeenCalled()
})
})
})
+280
View File
@@ -0,0 +1,280 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { createLogger } from '@/lib/logger'
import { getEmailService } from '@/lib/email/service'
import { getBranding } from '@/lib/branding/service'
import { resolveBrandResultByHost } from '@/lib/branding/resolve'
import { getSenderForBrand } from '@/lib/email/brand-sender'
import { buildAuthEmail } from '@/lib/email/auth-templates'
import { verifyStandardWebhookSignature } from '@/lib/email/standard-webhook'
import {
BrandLookupFailedError,
getCanonicalAppOrigin,
resolveTrustedAppOrigin,
} from '@/lib/domains/trusted-app-origin'
// Loads the email extension so getEmailService() returns the Resend
// implementation instead of the noop default.
ensureInitialized()
const log = createLogger('auth-email-hook')
/**
* POST /api/auth/email-hook: Supabase Auth "Send Email" hook (WL-05, WL-13).
*
* When enabled in Supabase (Auth > Hooks > Send Email, pointing at this URL
* with the shared secret in SUPABASE_SEND_EMAIL_HOOK_SECRET), Supabase stops
* sending auth mail itself and this endpoint sends every auth mail (signup
* confirmation, recovery, magic link, invite, email change, reauthentication)
* through the platform email service, branded per the requesting host: the
* brand is resolved from the trusted redirect_to origin, so a
* reset requested on app.partner.se is sent in the partner's brand and links
* back to app.partner.se. Unknown hosts get canonical platform mail.
*
* Unauthenticated by design (server-to-server): authenticity comes from the
* Standard Webhooks signature, not a session, exactly like the Stripe and
* Resend webhook routes. The raw body is verified byte-for-byte before
* parsing. The signature proves WHO sent the payload, not that every
* destination in it should be followed: redirect_to is GoTrue's already
* allowlisted referrer, but that allowlist is a glob configured by hand, so
* the origin is resolved here again through lib/domains/trusted-app-origin
* (canonical, this deployment's own Vercel hosts, or a registered brand
* domain). Anything else gets a canonical link, and the token never rides
* to a host this deployment does not serve. This endpoint is
* availability-critical once the hook is enabled:
* any internal failure returns 500 so Supabase retries (up to 3 times within
* a 5 second budget); success returns 200 {} fast.
*
* Until the hook is switched on in Supabase this route is dormant and auth
* mail keeps flowing from Supabase unchanged.
*/
// verifyOtp types our /auth/callback confirm route accepts. Unknown action
// types fall back to the generic 'email' type rather than dropping the mail.
const VERIFY_TYPES = new Set([
'signup',
'recovery',
'magiclink',
'invite',
'email_change',
'email',
])
interface SendEmailHookPayload {
user?: {
email?: string | null
new_email?: string | null
email_new?: string | null
} | null
email_data?: {
token?: string
token_hash?: string
token_new?: string
token_hash_new?: string
redirect_to?: string
email_action_type?: string
site_url?: string
} | null
}
/**
* Build the verify URL on the ORIGINATING host using the token_hash +
* verifyOtp pattern (browser- and host-independent, per the WL-05 research):
* /auth/callback consumes token_hash + type server-side and then honors the
* `next` path. If redirect_to already points at /auth/callback (our client
* flows do), its query (e.g. next=/reset-password) is preserved.
*
* `origin` is the already-trusted application origin; `redirectUrl` is the
* requested redirect_to only when it sits on that origin, else null (the
* link then lands on the origin's /auth/callback with no `next`).
*/
function buildActionUrl(
origin: string,
redirectUrl: URL | null,
tokenHash: string,
actionType: string,
): string {
const verifyType = VERIFY_TYPES.has(actionType) ? actionType : 'email'
let url: URL
if (redirectUrl && redirectUrl.pathname === '/auth/callback') {
url = new URL(redirectUrl.toString())
} else {
url = new URL('/auth/callback', origin)
if (redirectUrl) {
const next = redirectUrl.pathname + redirectUrl.search
if (next && next !== '/') url.searchParams.set('next', next)
}
}
url.searchParams.set('token_hash', tokenHash)
url.searchParams.set('type', verifyType)
return url.toString()
}
/**
* The requested redirect_to, kept only when its origin is one this
* deployment serves. The comparison is on the resolved origin, so an http
* link to a hosted domain, a lookalike host, a non-default port or a
* credential-bearing URL all collapse to the canonical /auth/callback.
* Throws BrandLookupFailedError when the brands table cannot be read.
*/
async function resolveRedirect(
requested: string | undefined,
): Promise<{ origin: string; redirectUrl: URL | null }> {
let requestedUrl: URL | null = null
if (requested) {
try {
requestedUrl = new URL(requested)
} catch {
requestedUrl = null
}
}
// URL.origin drops userinfo, so a credential-bearing redirect on a served
// host would pass the origin comparison and be cloned into the link with
// the credentials still in it. No flow of ours ever sends one: treat it as
// untrusted outright (canonical link, no next), never as a served host.
if (requestedUrl && (requestedUrl.username || requestedUrl.password)) {
log.warn('redirect_to carries credentials; linking to the canonical origin', {
host: requestedUrl.hostname,
})
requestedUrl = null
}
const origin = await resolveTrustedAppOrigin(requestedUrl?.origin ?? null)
if (requestedUrl && requestedUrl.origin === origin) {
return { origin, redirectUrl: requestedUrl }
}
if (requestedUrl) {
// Hostname only: the URL may carry a query, never log the token side.
log.warn('redirect_to origin is not a served host; linking to the canonical origin', {
host: requestedUrl.hostname,
})
}
return { origin, redirectUrl: null }
}
export async function POST(request: Request) {
const secret = process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
if (!secret) {
log.error('SUPABASE_SEND_EMAIL_HOOK_SECRET is not configured', undefined)
return NextResponse.json({ error: 'Hook not configured' }, { status: 500 })
}
const rawBody = await request.text()
const verified = verifyStandardWebhookSignature({
secret,
payload: rawBody,
id: request.headers.get('webhook-id'),
timestamp: request.headers.get('webhook-timestamp'),
signature: request.headers.get('webhook-signature'),
})
if (!verified) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 })
}
let payload: SendEmailHookPayload
try {
payload = JSON.parse(rawBody) as SendEmailHookPayload
} catch {
return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })
}
const emailData = payload.email_data ?? {}
const actionType = emailData.email_action_type || ''
const recipient = payload.user?.email || null
if (!recipient) {
return NextResponse.json({ error: 'Missing recipient' }, { status: 400 })
}
// Brand from the RESOLVED host: redirect_to carries the tenant origin, and
// the sender identity must match the host the link lands on. A lookup
// failure is a 500 so Supabase retries rather than sending a mail whose
// link would land on the wrong domain.
let resolved: Awaited<ReturnType<typeof resolveRedirect>>
try {
resolved = await resolveRedirect(emailData.redirect_to)
} catch (err) {
if (!(err instanceof BrandLookupFailedError)) throw err
log.error('brand lookup failed while resolving redirect_to', err, { host: err.host })
return NextResponse.json({ error: 'Origin lookup failed' }, { status: 500 })
}
const { origin, redirectUrl } = resolved
// A brand host whose row cannot be read right now (a second registry read
// can fail after the first succeeded) must not get platform-branded mail
// carrying a brand link: 500, Supabase retries. On the canonical origin a
// failed read is the platform sender either way, so it does not block.
const brandResult = await resolveBrandResultByHost(new URL(origin).hostname)
if (brandResult.lookupFailed && origin !== getCanonicalAppOrigin()) {
log.error('brand lookup failed for the resolved origin', undefined, { origin })
return NextResponse.json({ error: 'Origin lookup failed' }, { status: 500 })
}
const brand = brandResult.brand
const sender = getSenderForBrand(brand)
const appName = brand?.appName ?? getBranding().appName
// Compose the mail(s) for this hook invocation.
const mails: Array<{ to: string; actionType: string; actionUrl?: string; otpCode?: string }> = []
if (actionType === 'reauthentication') {
if (!emailData.token) {
return NextResponse.json({ error: 'Missing token' }, { status: 400 })
}
mails.push({ to: recipient, actionType, otpCode: emailData.token })
} else if (actionType === 'email_change') {
// Secure email change sends TWO mails from one invocation. Documented
// reversal: token_hash confirms at the NEW address, token_hash_new at
// the CURRENT one.
if (!emailData.token_hash) {
return NextResponse.json({ error: 'Missing token_hash' }, { status: 400 })
}
const newEmail = payload.user?.new_email || payload.user?.email_new || recipient
mails.push({
to: newEmail,
actionType: 'email_change',
actionUrl: buildActionUrl(origin, redirectUrl, emailData.token_hash, 'email_change'),
})
if (emailData.token_hash_new) {
mails.push({
to: recipient,
actionType: 'email_change_current',
actionUrl: buildActionUrl(origin, redirectUrl, emailData.token_hash_new, 'email_change'),
})
}
} else {
if (!emailData.token_hash) {
return NextResponse.json({ error: 'Missing token_hash' }, { status: 400 })
}
mails.push({
to: recipient,
actionType,
actionUrl: buildActionUrl(origin, redirectUrl, emailData.token_hash, actionType),
})
}
const emailService = getEmailService()
for (const mail of mails) {
const built = buildAuthEmail({
actionType: mail.actionType,
appName,
actionUrl: mail.actionUrl,
otpCode: mail.otpCode,
})
const result = await emailService.sendEmail({
to: mail.to,
subject: built.subject,
html: built.html,
text: built.text,
fromName: sender.fromName ?? undefined,
fromAddress: sender.fromAddress ?? undefined,
replyTo: sender.replyTo ?? undefined,
})
if (!result.success) {
// Non-2xx makes Supabase retry, which is the recovery we want: auth
// mail must not be silently dropped.
log.error('auth mail send failed', new Error(result.error ?? 'unknown'), {
actionType: mail.actionType,
})
return NextResponse.json({ error: 'Send failed' }, { status: 500 })
}
}
return NextResponse.json({})
}
@@ -0,0 +1,217 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { NextResponse } from 'next/server'
import {
createSessionTimeoutState,
signSessionTimeoutState,
verifySessionTimeoutState,
} from '@/lib/auth/session-timeout'
import { SESSION_TIMEOUT_COOKIE } from '@/lib/auth/session-timeout-shared'
const mocks = vi.hoisted(() => ({
requireAuth: vi.fn(),
cookieValue: undefined as string | undefined,
}))
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: mocks.requireAuth,
}))
vi.mock('next/headers', () => ({
cookies: vi.fn(async () => ({
get: (name: string) => name === SESSION_TIMEOUT_COOKIE && mocks.cookieValue
? { name, value: mocks.cookieValue }
: undefined,
})),
}))
import { GET, POST } from '../route'
const preference = { autoLogout: false, error: null as unknown }
const supabase = {
auth: {
getClaims: vi.fn(async () => ({
data: { claims: { session_id: 'session-1' } },
})),
},
from: vi.fn(() => ({
select: vi.fn(() => ({
eq: vi.fn(() => ({
maybeSingle: vi.fn(async () => ({
data: preference.error ? null : { auto_logout: preference.autoLogout },
error: preference.error,
})),
})),
})),
})),
}
describe('session heartbeat route', () => {
beforeEach(() => {
vi.clearAllMocks()
process.env.SESSION_TIMEOUT_SECRET = 'heartbeat-test-secret'
process.env.NEXT_PUBLIC_SESSION_IDLE_TIMEOUT_MS = '30000'
process.env.NEXT_PUBLIC_SESSION_ABSOLUTE_TIMEOUT_MS = '60000'
process.env.NEXT_PUBLIC_SESSION_WARNING_MS = '10000'
mocks.requireAuth.mockResolvedValue({
user: { id: 'user-1' },
supabase,
error: null,
})
mocks.cookieValue = undefined
preference.autoLogout = false
preference.error = null
})
async function setState(args?: {
startedAt?: number
lastActivityAt?: number
sessionId?: string
autoLogout?: boolean
}) {
const state = {
...createSessionTimeoutState({
userId: 'user-1',
sessionId: args?.sessionId ?? 'session-1',
method: 'password',
// Default the opt-in to true: most cases here exercise enforcement.
autoLogout: args?.autoLogout ?? true,
now: args?.startedAt ?? Date.now(),
}),
...(args?.lastActivityAt === undefined
? {}
: { lastActivityAt: args.lastActivityAt }),
}
mocks.cookieValue = (await signSessionTimeoutState(state)) ?? undefined
return state
}
it('returns the server-authoritative timeout state without extending it on GET', async () => {
const state = await setState()
const response = await GET()
expect(response.status).toBe(200)
await expect(response.json()).resolves.toMatchObject({
data: {
enabled: true,
startedAt: state.startedAt,
lastActivityAt: state.lastActivityAt,
},
})
expect(response.cookies.get(SESSION_TIMEOUT_COOKIE)).toBeUndefined()
})
it('advances activity and rotates the signed cookie on POST', async () => {
const state = await setState({ startedAt: Date.now() - 1000 })
const response = await POST()
expect(response.status).toBe(200)
const rotated = response.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
expect(rotated).toBeTruthy()
await expect(verifySessionTimeoutState(rotated)).resolves.toMatchObject({
startedAt: state.startedAt,
lastActivityAt: expect.any(Number),
})
})
it('rejects an expired state', async () => {
const now = Date.now()
await setState({ startedAt: now - 60_000, lastActivityAt: now - 1 })
const expired = await GET()
expect(expired.status).toBe(401)
expect(expired.headers.get('x-session-timeout-reason')).toBe('absolute')
})
it('initializes fresh state for a missing or mismatched cookie like middleware', async () => {
const missing = await GET()
expect(missing.status).toBe(200)
const initialized = missing.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
expect(initialized).toBeTruthy()
await expect(verifySessionTimeoutState(initialized)).resolves.toMatchObject({
userId: 'user-1',
sessionId: 'session-1',
})
await setState({ sessionId: 'another-session' })
const mismatch = await GET()
expect(mismatch.status).toBe(200)
const reminted = mismatch.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
expect(reminted).toBeTruthy()
await expect(verifySessionTimeoutState(reminted)).resolves.toMatchObject({
sessionId: 'session-1',
})
})
it('reports enabled: false and never expires an opted-out session', async () => {
const now = Date.now()
// Times that would be long expired if enforcement applied.
await setState({
startedAt: now - 120_000,
lastActivityAt: now - 120_000,
autoLogout: false,
})
const response = await GET()
expect(response.status).toBe(200)
await expect(response.json()).resolves.toMatchObject({
data: { enabled: false },
})
})
it('upgrades a pre-toggle cookie in place, keeping its timers', async () => {
preference.autoLogout = true
const startedAt = Date.now() - 5_000
const legacy: Record<string, unknown> = {
...createSessionTimeoutState({
userId: 'user-1',
sessionId: 'session-1',
method: 'password',
autoLogout: true,
now: startedAt,
}),
}
delete legacy.autoLogout
mocks.cookieValue =
(await signSessionTimeoutState(
legacy as Parameters<typeof signSessionTimeoutState>[0],
)) ?? undefined
const response = await GET()
expect(response.status).toBe(200)
const upgraded = response.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
expect(upgraded).toBeTruthy()
await expect(verifySessionTimeoutState(upgraded)).resolves.toMatchObject({
startedAt,
autoLogout: true,
})
})
it('answers without persisting a snapshot when the preference read fails', async () => {
preference.error = { message: 'connection reset' }
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const response = await GET()
expect(response.status).toBe(200)
await expect(response.json()).resolves.toMatchObject({
data: { enabled: false },
})
// No cookie: the unknown preference must not be baked into a snapshot.
expect(response.cookies.get(SESSION_TIMEOUT_COOKIE)).toBeUndefined()
errorSpy.mockRestore()
})
it('passes through the existing authentication error', async () => {
mocks.requireAuth.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect((await GET()).status).toBe(401)
})
})
+145
View File
@@ -0,0 +1,145 @@
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'
import type { SupabaseClient } from '@supabase/supabase-js'
import { requireAuth } from '@/lib/auth/require-auth'
import {
createSessionTimeoutState,
evaluateSessionTimeout,
fetchAutoLogoutPreference,
getSessionTimeoutConfig,
sessionStateMatchesUser,
sessionStateNeedsRemint,
sessionTimeoutCookieOptions,
signSessionTimeoutState,
toSessionTimeoutClientState,
verifySessionTimeoutState,
} from '@/lib/auth/session-timeout'
import {
SESSION_AUTH_METHOD_HINT_COOKIE,
SESSION_TIMEOUT_COOKIE,
isSessionAuthMethod,
type SessionTimeoutReason,
} from '@/lib/auth/session-timeout-shared'
export const dynamic = 'force-dynamic'
async function getSessionId(supabase: SupabaseClient): Promise<string | null> {
if (typeof supabase.auth.getClaims !== 'function') return null
try {
const { data } = await supabase.auth.getClaims()
return typeof data?.claims?.session_id === 'string'
? data.claims.session_id
: null
} catch {
return null
}
}
function expiredResponse(reason: SessionTimeoutReason): NextResponse {
const response = NextResponse.json(
{ error: { code: 'SESSION_EXPIRED', reason } },
{ status: 401 },
)
response.headers.set('X-Session-Timeout-Reason', reason)
response.headers.set('Cache-Control', 'no-store')
return response
}
async function heartbeat(updateActivity: boolean): Promise<NextResponse> {
const auth = await requireAuth()
if (auth.error) return auth.error
const config = getSessionTimeoutConfig()
const now = Date.now()
if (!config.enabled) {
return NextResponse.json({
data: {
enabled: false,
idleTimeoutMs: 0,
absoluteTimeoutMs: 0,
warningMs: 0,
serverNow: now,
startedAt: now,
lastActivityAt: now,
method: 'password',
},
})
}
const cookieStore = await cookies()
const encodedState = cookieStore.get(SESSION_TIMEOUT_COOKIE)?.value
const state = await verifySessionTimeoutState(encodedState)
const sessionId = await getSessionId(auth.supabase)
const stateMatches =
state !== null && sessionStateMatchesUser(state, auth.user.id, sessionId)
if (!state || !stateMatches || sessionStateNeedsRemint(state)) {
// Mirror middleware initialization: a missing, session-mismatched, or
// pre-toggle cookie means the timeout state has not been established
// for this session yet, not that the session expired.
const hintedMethod = cookieStore.get(SESSION_AUTH_METHOD_HINT_COOKIE)?.value
const autoLogout = await fetchAutoLogoutPreference(auth.supabase, auth.user.id)
const freshState = state && stateMatches
? { ...state, autoLogout: autoLogout ?? false }
: createSessionTimeoutState({
userId: auth.user.id,
sessionId,
method: isSessionAuthMethod(hintedMethod) ? hintedMethod : 'password',
autoLogout: autoLogout ?? false,
now,
})
const response = NextResponse.json({
data: toSessionTimeoutClientState(freshState, config, now),
})
response.headers.set('Cache-Control', 'no-store')
// Unknown preference (failed read): answer this poll without persisting
// a fail-open snapshot; the next resync retries the read (mirrors the
// middleware).
if (autoLogout !== null) {
const signedFresh = await signSessionTimeoutState(freshState)
if (signedFresh) {
response.cookies.set(
SESSION_TIMEOUT_COOKIE,
signedFresh,
sessionTimeoutCookieOptions(),
)
}
}
return response
}
const reason = evaluateSessionTimeout(state, config, now)
if (reason) return expiredResponse(reason)
const nextState = updateActivity
? { ...state, lastActivityAt: now }
: state
const response = NextResponse.json({
data: toSessionTimeoutClientState(nextState, config, now),
})
response.headers.set('Cache-Control', 'no-store')
if (updateActivity) {
const signedNext = await signSessionTimeoutState(nextState)
if (signedNext) {
response.cookies.set(
SESSION_TIMEOUT_COOKIE,
signedNext,
sessionTimeoutCookieOptions(),
)
}
}
return response
}
export async function GET(): Promise<NextResponse> {
return heartbeat(false)
}
export async function POST(): Promise<NextResponse> {
return heartbeat(true)
}
@@ -0,0 +1,101 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { parseJsonResponse } from '@/tests/helpers'
const resetPasswordForEmailMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
auth: { resetPasswordForEmail: resetPasswordForEmailMock },
})),
}))
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
}))
import { POST } from '../route'
function makeRequest(body: unknown, headers: Record<string, string> = {}): Request {
return new Request('https://internal/api/auth/password-reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(body),
})
}
const ORIGINAL_APP_URL = process.env.NEXT_PUBLIC_APP_URL
beforeEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.test'
resetPasswordForEmailMock.mockResolvedValue({ data: {}, error: null })
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
brand: host === 'app.testbrand.example' ? { domain: host } : null,
lookupFailed: false,
}))
})
afterEach(() => {
if (ORIGINAL_APP_URL === undefined) delete process.env.NEXT_PUBLIC_APP_URL
else process.env.NEXT_PUBLIC_APP_URL = ORIGINAL_APP_URL
})
describe('POST /api/auth/password-reset', () => {
it('400s on invalid body', async () => {
const res = await POST(makeRequest({ email: 'not-an-email' }))
expect(res.status).toBe(400)
expect(resetPasswordForEmailMock).not.toHaveBeenCalled()
})
it('sends the recovery callback on a registered brand host', async () => {
const res = await POST(
makeRequest(
{ email: ' Kund@Example.COM ', captchaToken: 'tok' },
{ host: 'internal', 'x-forwarded-host': 'app.testbrand.example' },
),
)
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(res.status).toBe(200)
expect(json.data.status).toBe('sent')
expect(resetPasswordForEmailMock).toHaveBeenCalledWith('kund@example.com', {
redirectTo: 'https://app.testbrand.example/auth/callback?next=/reset-password',
captchaToken: 'tok',
})
})
it('falls back to the canonical callback for an unregistered host', async () => {
await POST(makeRequest({ email: 'kund@example.com' }, { host: 'attacker.test' }))
expect(resetPasswordForEmailMock).toHaveBeenCalledWith('kund@example.com', {
redirectTo: 'https://app.accounted.test/auth/callback?next=/reset-password',
})
})
it('503s (fail safe) when the brand lookup errors, without calling GoTrue', async () => {
resolveBrandResultByHostMock.mockResolvedValue({ brand: null, lookupFailed: true })
const res = await POST(
makeRequest({ email: 'kund@example.com' }, { host: 'app.testbrand.example' }),
)
const { body: json } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(res.status).toBe(503)
expect(json.error.code).toBe('brand_lookup_failed')
expect(resetPasswordForEmailMock).not.toHaveBeenCalled()
})
it('maps a GoTrue error to the canonical envelope with its status', async () => {
resetPasswordForEmailMock.mockResolvedValue({
data: null,
error: { code: 'over_email_send_rate_limit', message: 'rate limit', status: 429 },
})
const res = await POST(makeRequest({ email: 'kund@example.com' }, { host: 'app.accounted.test' }))
const { body: json } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
expect(res.status).toBe(429)
expect(json.error.code).toBe('over_email_send_rate_limit')
expect(json.error.message).toBeTruthy()
})
})
+93
View File
@@ -0,0 +1,93 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { createClient } from '@/lib/supabase/server'
import { validateBody } from '@/lib/api/validate'
import {
BrandLookupFailedError,
buildPasswordResetRedirectTo,
requestHost,
} from '@/lib/domains/trusted-app-origin'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { createLogger } from '@/lib/logger'
const log = createLogger('auth-password-reset')
/**
* POST /api/auth/password-reset: request a password recovery mail.
*
* Moved server-side so the recovery callback is resolved against the brands
* table (lib/domains/trusted-app-origin.ts) instead of a domain list compiled
* into the browser bundle. The login page used to call
* supabase.auth.resetPasswordForEmail directly with a redirectTo it validated
* against NEXT_PUBLIC_WHITELABEL_DOMAINS; every new brand then needed that
* env var updated and a redeploy, and when that was forgotten the mail went
* out canonical-branded to the canonical host. Here the request host decides:
* a registered brand host gets its own callback (and, through the Send Email
* hook, its own brand), everything else gets the canonical one.
*
* Anonymous by design: a user asking for a reset has no session, so no
* withRouteContext / requireAuth. Abuse is bounded exactly as the direct
* GoTrue call was: the forwarded Turnstile token (verified by GoTrue) plus
* GoTrue's own recovery rate limits. A signed-in user may also call this
* (the login page is reachable while signed in); the cookie-backed client
* carries their session and GoTrue behaves the same either way.
*
* The response never says whether the address exists: GoTrue answers 200 for
* unknown addresses and this route passes that through unchanged.
*/
const PasswordResetSchema = z.object({
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
captchaToken: z.string().max(4096).nullish(),
})
export async function POST(request: Request) {
const validation = await validateBody(request, PasswordResetSchema)
if (!validation.success) return validation.response
const { email, captchaToken } = validation.data
let redirectTo: string
try {
redirectTo = await buildPasswordResetRedirectTo(requestHost(request))
} catch (err) {
if (!(err instanceof BrandLookupFailedError)) throw err
// Transient brands-table error: fail safe like /api/auth/signup. A
// canonical fallback here would mail a white-label user a wrong-brand
// link; 503 tells the client to retry instead.
return NextResponse.json(
{
error: {
code: 'brand_lookup_failed',
message: 'Tillfälligt fel. Försök igen om en stund.',
message_en: 'Temporary error. Please try again shortly.',
},
},
{ status: 503 },
)
}
const supabase = await createClient()
const { error } = await supabase.auth.resetPasswordForEmail(email, {
redirectTo,
...(captchaToken ? { captchaToken } : {}),
})
if (error) {
log.warn('resetPasswordForEmail rejected', { status: error.status, code: error.code })
// Same envelope as /api/auth/signup: the login page feeds it to
// classifyAuthError (keyed on code and HTTP status) and localizes the
// display message through getErrorMessage.
return NextResponse.json(
{
error: {
code: error.code ?? 'auth_error',
message: getErrorMessage(error, { context: 'auth', locale: 'sv' }),
message_en: getErrorMessage(error, { context: 'auth', locale: 'en' }),
},
},
{ status: error.status && error.status >= 400 ? error.status : 400 },
)
}
return NextResponse.json({ data: { status: 'sent' } })
}
+191
View File
@@ -0,0 +1,191 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { parseJsonResponse } from '@/tests/helpers'
const signUpMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({ auth: { signUp: signUpMock } })),
}))
const gateMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/auth/brand-signup-gate', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@/lib/auth/brand-signup-gate')>()
return {
...actual,
evaluateBrandSignupGate: (...args: unknown[]) => gateMock(...args),
}
})
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
}))
import { POST } from '../route'
function makeRequest(
body: unknown,
headers: Record<string, string> = {},
): Request {
return new Request('https://internal/api/auth/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(body),
})
}
const validBody = { email: 'kund@example.com', password: 'Str0ng!Pass' }
beforeEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.se'
// app.testbrand.example is a registered brand host; app.accounted.se is
// the canonical host and never consults the registry.
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
brand: host === 'app.testbrand.example' ? { domain: host } : null,
lookupFailed: false,
}))
gateMock.mockResolvedValue({ allowed: true, brand: null, via: 'no_brand' })
signUpMock.mockResolvedValue({
data: { user: { identities: [{ id: 'i1' }] }, session: null },
error: null,
})
})
describe('POST /api/auth/signup', () => {
it('400s on invalid body', async () => {
const res = await POST(makeRequest({ email: 'not-an-email', password: 'x' }))
expect(res.status).toBe(400)
expect(signUpMock).not.toHaveBeenCalled()
})
it('403s with signup_not_allowed when the gate blocks', async () => {
gateMock.mockResolvedValue({ allowed: false, brand: { id: 'brand-1' } })
const res = await POST(
makeRequest(validBody, { host: 'app.testbrand.example' }),
)
const { body: json } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(res.status).toBe(403)
expect(json.error.code).toBe('signup_not_allowed')
expect(signUpMock).not.toHaveBeenCalled()
})
it('503s (fail safe) when the brand lookup errors, without creating an account', async () => {
gateMock.mockResolvedValue({ allowed: false, brand: null, lookupFailed: true })
const res = await POST(
makeRequest(validBody, { host: 'app.testbrand.example' }),
)
const { body: json } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(res.status).toBe(503)
expect(json.error.code).toBe('brand_lookup_failed')
expect(signUpMock).not.toHaveBeenCalled()
})
it('feeds the gate the forwarded host, normalized email and invite cookie', async () => {
await POST(
makeRequest(
{ ...validBody, email: ' Kund@Example.COM ' },
{
host: 'internal',
'x-forwarded-host': 'app.testbrand.example',
cookie: 'gnubok-invite-token=gnubok_inv_x',
},
),
)
expect(gateMock).toHaveBeenCalledWith({
host: 'app.testbrand.example',
email: 'kund@example.com',
inviteToken: 'gnubok_inv_x',
})
})
it('signs up with a confirmation callback on the originating host', async () => {
const res = await POST(
makeRequest(validBody, {
'x-forwarded-host': 'app.testbrand.example',
'x-forwarded-proto': 'https',
}),
)
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(res.status).toBe(200)
expect(json.data.status).toBe('confirmation_sent')
expect(signUpMock).toHaveBeenCalledWith({
email: 'kund@example.com',
password: 'Str0ng!Pass',
options: {
emailRedirectTo: 'https://app.testbrand.example/auth/callback',
},
})
})
it('forwards the captcha token and a safe next path', async () => {
await POST(
makeRequest(
{ ...validBody, captchaToken: 'tok', next: '/api/mcp-oauth/authorize?x=1' },
{ host: 'app.accounted.se' },
),
)
const call = signUpMock.mock.calls[0][0]
expect(call.options.captchaToken).toBe('tok')
expect(call.options.emailRedirectTo).toBe(
'https://app.accounted.se/auth/callback?next=%2Fapi%2Fmcp-oauth%2Fauthorize%3Fx%3D1',
)
})
it('drops an unsafe next path instead of forwarding it', async () => {
await POST(
makeRequest(
{ ...validBody, next: 'https://evil.example.com/phish' },
{ host: 'app.accounted.se' },
),
)
const call = signUpMock.mock.calls[0][0]
expect(call.options.emailRedirectTo).toBe(
'https://app.accounted.se/auth/callback',
)
})
it('maps a GoTrue error to the canonical envelope', async () => {
signUpMock.mockResolvedValue({
data: { user: null, session: null },
error: { code: 'weak_password', message: 'Password is too weak', status: 422 },
})
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
const { body: json } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
expect(res.status).toBe(422)
expect(json.error.code).toBe('weak_password')
})
it('reports duplicate for the obfuscated existing-account response', async () => {
signUpMock.mockResolvedValue({
data: { user: { identities: [] }, session: null },
error: null,
})
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(json.data.status).toBe('duplicate')
})
it('reports session for auto-confirmed signups', async () => {
signUpMock.mockResolvedValue({
data: { user: { identities: [{ id: 'i1' }] }, session: { access_token: 'x' } },
error: null,
})
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(json.data.status).toBe('session')
})
})
+135
View File
@@ -0,0 +1,135 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { createClient } from '@/lib/supabase/server'
import { validateBody } from '@/lib/api/validate'
import {
evaluateBrandSignupGate,
readInviteTokenFromCookieHeader,
} from '@/lib/auth/brand-signup-gate'
import { safeReturnTo } from '@/lib/auth/safe-return-to'
import { resolveTrustedAppOrigin } from '@/lib/domains/trusted-app-origin'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { createLogger } from '@/lib/logger'
const log = createLogger('auth-signup')
/**
* POST /api/auth/signup: email+password signup, moved server-side so the
* invite-only brand-domain gate (lib/auth/brand-signup-gate.ts) cannot be
* bypassed. The register page used to call supabase.auth.signUp straight
* from the browser; that call never touched Next.js, so any host-based
* gating there would have been cosmetic. This route is now the only
* email-signup path on every host: on canonical and open-brand hosts the
* behavior is byte-identical to the old direct call (same GoTrue request,
* same captcha, same emailRedirectTo shape), on invite-only brand hosts it
* refuses with signup_not_allowed unless the email is allowlisted or a
* valid invite cookie rides along.
*
* Anonymous by design: there is no session to authenticate at signup time,
* so no withRouteContext / requireAuth. Abuse is bounded the same way the
* direct GoTrue call was: the forwarded Turnstile token (verified by
* GoTrue) plus GoTrue's own signup rate limits.
*/
const SignupSchema = z.object({
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
password: z.string().min(8).max(256),
captchaToken: z.string().max(4096).nullish(),
/** Post-signup resume path (MCP OAuth consent); same-origin enforced. */
next: z.string().max(2048).nullish(),
})
export async function POST(request: Request) {
const validation = await validateBody(request, SignupSchema)
if (!validation.success) return validation.response
const { email, password, captchaToken } = validation.data
const host =
request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? ''
// The invite cookie is set by /invite/[token] before it redirects to
// /register, so an invitee's signup carries it automatically.
const inviteToken = readInviteTokenFromCookieHeader(request.headers.get('cookie'))
const gate = await evaluateBrandSignupGate({ host, email, inviteToken })
if (!gate.allowed && 'lookupFailed' in gate) {
// Transient brands-table error: fail safe, do not create the account.
// 503 tells the client to retry rather than the misleading "not allowed".
return NextResponse.json(
{
error: {
code: 'brand_lookup_failed',
message: 'Tillfälligt fel. Försök igen om en stund.',
message_en: 'Temporary error. Please try again shortly.',
},
},
{ status: 503 },
)
}
if (!gate.allowed) {
return NextResponse.json(
{
error: {
code: 'signup_not_allowed',
// Brand-neutral copy: the interstitial on the register page owns
// the user-facing story; this message is the API-level fallback.
message: 'Registrering på den här domänen kräver inbjudan.',
message_en: 'Signing up on this domain requires an invitation.',
},
},
{ status: 403 },
)
}
// Confirmation links must land back on the ORIGINATING host (WL-05 brand
// mail resolves its brand from this URL). The host is resolved through the
// same registry as every other auth link (canonical, this deployment's
// own Vercel hosts, or a registered brand domain); anything else falls
// back to the canonical origin rather than following the raw header.
const confirmationCallback = new URL(
'/auth/callback',
await resolveTrustedAppOrigin(host),
)
const nextPath = safeReturnTo(validation.data.next ?? null, '/')
if (nextPath !== '/') confirmationCallback.searchParams.set('next', nextPath)
const supabase = await createClient()
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: confirmationCallback.toString(),
...(captchaToken ? { captchaToken } : {}),
},
})
if (error) {
log.warn('signUp rejected', { status: error.status, code: error.code })
// The register page feeds this envelope to classifyAuthError, which
// keys on the GoTrue code (and the HTTP status); the display message is
// localized through getErrorMessage like every other auth surface.
return NextResponse.json(
{
error: {
code: error.code ?? 'auth_error',
message: getErrorMessage(error, { context: 'auth', locale: 'sv' }),
message_en: getErrorMessage(error, { context: 'auth', locale: 'en' }),
},
},
{ status: error.status && error.status >= 400 ? error.status : 400 },
)
}
// Supabase obfuscates duplicate signups (anti-enumeration): a confirmed
// existing email returns a user with identities: [] and sends no mail.
// Surface that as a distinct status so the page can skip the misleading
// "check your email" screen; the information is the same the browser call
// exposed, so nothing new leaks.
const status = data.session
? 'session'
: data.user && (data.user.identities?.length ?? 0) === 0
? 'duplicate'
: 'confirmation_sent'
return NextResponse.json({ data: { status } })
}
+315
View File
@@ -0,0 +1,315 @@
/**
* Tests for POST /api/billing/checkout.
*
* Exercises the route through the real withRouteContext wrapper, mocking
* auth/company, the Stripe client, and the service-role Supabase client.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase: serviceSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
// Keep sandboxBlockedResponse real; stub only the DB-backed guardSandbox so the
// route's company_settings read doesn't need a live supabase mock.
const guardSandboxMock = vi.fn()
vi.mock('@/lib/sandbox/guard', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/sandbox/guard')>()
return { ...actual, guardSandbox: (...args: unknown[]) => guardSandboxMock(...args) }
})
const customersCreate = vi.fn()
const sessionsCreate = vi.fn()
vi.mock('@/lib/stripe/client', () => ({
getStripe: () => ({
customers: { create: customersCreate },
checkout: { sessions: { create: sessionsCreate } },
}),
priceIdForPlan: vi.fn().mockReturnValue('price_123'),
}))
import { POST } from '../checkout/route'
const routeParams = { params: Promise.resolve({}) }
// The trusted-origin resolver reads the brands table; pin one registered
// brand host so the return-URL tests exercise the real resolver logic.
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
}))
const originalAppUrl = process.env.NEXT_PUBLIC_APP_URL
beforeEach(() => {
vi.clearAllMocks()
reset()
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.test'
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
brand: host === 'portal.brand.test' ? { domain: host } : null,
lookupFailed: false,
}))
guardSandboxMock.mockResolvedValue(null)
requireAuthMock.mockResolvedValue({
user: { id: 'user-1', email: 'u@example.com', is_anonymous: false },
supabase: {},
error: null,
})
})
afterEach(() => {
if (originalAppUrl === undefined) delete process.env.NEXT_PUBLIC_APP_URL
else process.env.NEXT_PUBLIC_APP_URL = originalAppUrl
})
describe('POST /api/billing/checkout', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const res = await POST(req, routeParams)
expect(res.status).toBe(401)
})
it('blocks an anonymous (demo) user with 403 and never touches Stripe', async () => {
requireAuthMock.mockResolvedValue({
user: { id: 'anon-1', email: null, is_anonymous: true },
supabase: {},
error: null,
})
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ sandbox_blocked?: boolean }>(
await POST(req, routeParams),
)
expect(status).toBe(403)
expect(body.sandbox_blocked).toBe(true)
expect(customersCreate).not.toHaveBeenCalled()
expect(sessionsCreate).not.toHaveBeenCalled()
// The cheap identity check short-circuits before the DB-backed guard.
expect(guardSandboxMock).not.toHaveBeenCalled()
})
it('blocks a sandbox company with 403 and never touches Stripe', async () => {
const { sandboxBlockedResponse } = await import('@/lib/sandbox/guard')
guardSandboxMock.mockResolvedValue(sandboxBlockedResponse())
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: { plan: 'monthly' } })
const { status, body } = await parseJsonResponse<{ sandbox_blocked?: boolean }>(
await POST(req, routeParams),
)
expect(status).toBe(403)
expect(body.sandbox_blocked).toBe(true)
expect(guardSandboxMock).toHaveBeenCalledWith(expect.anything(), 'company-1')
expect(customersCreate).not.toHaveBeenCalled()
expect(sessionsCreate).not.toHaveBeenCalled()
})
it('rejects an unknown plan with 400', async () => {
const req = createMockRequest('/api/billing/checkout', {
method: 'POST',
body: { plan: 'weekly' },
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(400)
expect(sessionsCreate).not.toHaveBeenCalled()
})
it('reuses an existing Stripe customer and returns the checkout URL', async () => {
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: null }) // no trial grant
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', {
method: 'POST',
body: { plan: 'yearly' },
})
const { status, body } = await parseJsonResponse<{ url: string }>(await POST(req, routeParams))
expect(status).toBe(200)
expect(body.url).toBe('https://stripe.test/session')
expect(customersCreate).not.toHaveBeenCalled()
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
customer: 'cus_existing',
client_reference_id: 'company-1',
})
)
// No trial grant → billing starts immediately, no Stripe trial.
expect(sessionsCreate.mock.calls[0][0].subscription_data.trial_end).toBeUndefined()
})
it('enables automatic VAT, tax-id collection and address capture on the session', async () => {
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: null }) // no trial grant
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: { plan: 'monthly' } })
await POST(req, routeParams)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
automatic_tax: { enabled: true },
tax_id_collection: { enabled: true },
billing_address_collection: 'required',
customer_update: { name: 'auto', address: 'auto' },
}),
)
})
it('creates a Stripe customer when none exists yet', async () => {
enqueue({ data: null }) // no existing subscription row
enqueue({ data: null }) // no trial grant
enqueue({ data: null }) // upsert result
customersCreate.mockResolvedValue({ id: 'cus_new' })
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ url: string }>(await POST(req, routeParams))
expect(status).toBe(200)
expect(body.url).toBe('https://stripe.test/session')
expect(customersCreate).toHaveBeenCalledWith(
expect.objectContaining({ metadata: { company_id: 'company-1' } })
)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({ customer: 'cus_new' })
)
})
it('defers the first charge to the trial end when the trial has >48h left', async () => {
const trialEnd = new Date(Date.now() + 10 * 24 * 3600 * 1000).toISOString()
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: { expires_at: trialEnd } }) // active trial grant
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(200)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
subscription_data: expect.objectContaining({
metadata: { company_id: 'company-1' },
trial_end: Math.floor(new Date(trialEnd).getTime() / 1000),
}),
})
)
})
it('bills immediately when the trial is inside the 48h Stripe floor', async () => {
const trialEnd = new Date(Date.now() + 24 * 3600 * 1000).toISOString()
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: { expires_at: trialEnd } }) // trial ends tomorrow
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(200)
expect(sessionsCreate.mock.calls[0][0].subscription_data.trial_end).toBeUndefined()
})
it('bills immediately when the trial has already expired', async () => {
const trialEnd = new Date(Date.now() - 24 * 3600 * 1000).toISOString()
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: { expires_at: trialEnd } }) // lapsed trial
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(200)
expect(sessionsCreate.mock.calls[0][0].subscription_data.trial_end).toBeUndefined()
})
it('fails closed (500, no Stripe session) when the trial lookup errors', async () => {
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: null, error: { message: 'boom' } }) // trial lookup fails
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(req, routeParams),
)
expect(status).toBe(500)
expect(body.error.code).toBe('TRIAL_LOOKUP_FAILED')
expect(sessionsCreate).not.toHaveBeenCalled()
})
describe('return URLs', () => {
function checkoutFrom(url: string) {
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: null }) // no trial grant
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
return POST(createMockRequest(url, { method: 'POST', body: {} }), routeParams)
}
it('returns to the canonical app when checkout starts there', async () => {
const { status } = await parseJsonResponse(
await checkoutFrom('https://app.accounted.test/api/billing/checkout'),
)
expect(status).toBe(200)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
success_url: 'https://app.accounted.test/settings/billing?success=1',
cancel_url: 'https://app.accounted.test/settings/billing?canceled=1',
}),
)
})
it('returns to a registered white-label host when checkout starts there', async () => {
const { status } = await parseJsonResponse(
await checkoutFrom('https://portal.brand.test/api/billing/checkout'),
)
expect(status).toBe(200)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
success_url: 'https://portal.brand.test/settings/billing?success=1',
cancel_url: 'https://portal.brand.test/settings/billing?canceled=1',
}),
)
})
it('falls back to the canonical app for an unregistered or spoofed host', async () => {
const { status } = await parseJsonResponse(
await checkoutFrom('https://portal.brand.test.attacker.test/api/billing/checkout'),
)
expect(status).toBe(200)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
success_url: 'https://app.accounted.test/settings/billing?success=1',
cancel_url: 'https://app.accounted.test/settings/billing?canceled=1',
}),
)
})
})
})
+184
View File
@@ -0,0 +1,184 @@
/**
* Tests for POST /api/billing/portal.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase: serviceSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
// Keep sandboxBlockedResponse real; stub only the DB-backed guardSandbox.
const guardSandboxMock = vi.fn()
vi.mock('@/lib/sandbox/guard', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/sandbox/guard')>()
return { ...actual, guardSandbox: (...args: unknown[]) => guardSandboxMock(...args) }
})
const portalCreate = vi.fn()
vi.mock('@/lib/stripe/client', () => ({
getStripe: () => ({
billingPortal: { sessions: { create: portalCreate } },
}),
}))
import { POST } from '../portal/route'
const routeParams = { params: Promise.resolve({}) }
// The trusted-origin resolver reads the brands table; pin one registered
// brand host so the return-URL tests exercise the real resolver logic.
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
}))
const originalAppUrl = process.env.NEXT_PUBLIC_APP_URL
beforeEach(() => {
vi.clearAllMocks()
reset()
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.test'
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
brand: host === 'portal.brand.test' ? { domain: host } : null,
lookupFailed: false,
}))
guardSandboxMock.mockResolvedValue(null)
requireAuthMock.mockResolvedValue({ user: { id: 'user-1', is_anonymous: false }, supabase: {}, error: null })
})
afterEach(() => {
if (originalAppUrl === undefined) delete process.env.NEXT_PUBLIC_APP_URL
else process.env.NEXT_PUBLIC_APP_URL = originalAppUrl
})
describe('POST /api/billing/portal', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const res = await POST(req, routeParams)
expect(res.status).toBe(401)
})
it('blocks an anonymous (demo) user with 403 and never touches Stripe', async () => {
requireAuthMock.mockResolvedValue({
user: { id: 'anon-1', is_anonymous: true },
supabase: {},
error: null,
})
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ sandbox_blocked?: boolean }>(
await POST(req, routeParams),
)
expect(status).toBe(403)
expect(body.sandbox_blocked).toBe(true)
expect(portalCreate).not.toHaveBeenCalled()
expect(guardSandboxMock).not.toHaveBeenCalled()
})
it('blocks a sandbox company with 403 and never touches Stripe', async () => {
const { sandboxBlockedResponse } = await import('@/lib/sandbox/guard')
guardSandboxMock.mockResolvedValue(sandboxBlockedResponse())
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ sandbox_blocked?: boolean }>(
await POST(req, routeParams),
)
expect(status).toBe(403)
expect(body.sandbox_blocked).toBe(true)
expect(guardSandboxMock).toHaveBeenCalledWith(expect.anything(), 'company-1')
expect(portalCreate).not.toHaveBeenCalled()
})
it('returns 400 with NO_SUBSCRIPTION when the company has no Stripe customer', async () => {
enqueue({ data: null })
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(400)
expect(body.error.code).toBe('NO_SUBSCRIPTION')
expect(portalCreate).not.toHaveBeenCalled()
})
it('returns the portal URL for a company with a Stripe customer', async () => {
enqueue({ data: { stripe_customer_id: 'cus_1' } })
portalCreate.mockResolvedValue({ url: 'https://stripe.test/portal' })
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ url: string }>(await POST(req, routeParams))
expect(status).toBe(200)
expect(body.url).toBe('https://stripe.test/portal')
expect(portalCreate).toHaveBeenCalledWith(
expect.objectContaining({ customer: 'cus_1' })
)
})
describe('return URL', () => {
function portalFrom(url: string) {
enqueue({ data: { stripe_customer_id: 'cus_1' } })
portalCreate.mockResolvedValue({ url: 'https://stripe.test/portal' })
return POST(createMockRequest(url, { method: 'POST' }), routeParams)
}
it('comes back to the canonical app when opened there', async () => {
const { status } = await parseJsonResponse(
await portalFrom('https://app.accounted.test/api/billing/portal'),
)
expect(status).toBe(200)
expect(portalCreate).toHaveBeenCalledWith({
customer: 'cus_1',
return_url: 'https://app.accounted.test/settings/billing',
})
})
it('comes back to a registered white-label host when opened there', async () => {
const { status } = await parseJsonResponse(
await portalFrom('https://portal.brand.test/api/billing/portal'),
)
expect(status).toBe(200)
expect(portalCreate).toHaveBeenCalledWith(
expect.objectContaining({ return_url: 'https://portal.brand.test/settings/billing' }),
)
})
it('falls back to the canonical app for an unregistered or spoofed host', async () => {
const { status } = await parseJsonResponse(
await portalFrom('https://portal.brand.test.attacker.test/api/billing/portal'),
)
expect(status).toBe(200)
expect(portalCreate).toHaveBeenCalledWith(
expect.objectContaining({ return_url: 'https://app.accounted.test/settings/billing' }),
)
})
})
})
+216
View File
@@ -0,0 +1,216 @@
/**
* Tests for GET /api/billing/status.
*
* Focus: the isPaying classification. 'trialing' must count as paying since
* checkout defers the first charge to the trial end (the card is committed),
* while a company with no subscription stays on the upgrade path.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { parseJsonResponse } from '@/tests/helpers'
type TableResult = { data: unknown; error?: unknown }
function makeSupabase(byTable: Record<string, TableResult>) {
const chainFor = (table: string) => {
const result = byTable[table] ?? { data: null, error: null }
const chain: unknown = new Proxy(
{},
{
get(_t, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null })
}
return () => chain
},
},
)
return chain
}
return { from: (t: string) => chainFor(t) }
}
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/sandbox/guard', () => ({
isSandboxCompany: vi.fn().mockResolvedValue(false),
}))
// Service client for the WL-10 team-agreement lookup (end clients cannot read
// the byrå team or its grants under RLS, so the route uses the service role).
let serviceByTable: Record<string, TableResult> = {}
const createServiceClientMock = vi.fn(() => makeSupabase(serviceByTable))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => createServiceClientMock(),
createClient: vi.fn(),
}))
import { GET } from '../status/route'
interface StatusBody {
isPaying: boolean
trialEndsAt: string | null
isDemo: boolean
teamAgreement?: { teamName: string }
}
function authAs(byTable: Record<string, TableResult>) {
requireAuthMock.mockResolvedValue({
user: { id: 'user-1', is_anonymous: false },
supabase: makeSupabase(byTable),
error: null,
})
}
beforeEach(() => {
vi.clearAllMocks()
serviceByTable = {}
})
describe('GET /api/billing/status', () => {
it('treats a trialing subscription as paying (card committed via deferred checkout)', async () => {
authAs({
company_subscriptions: { data: { status: 'trialing' } },
capability_grants: { data: { expires_at: '2099-01-01T00:00:00Z' } },
})
const { status, body } = await parseJsonResponse<StatusBody>(await GET())
expect(status).toBe(200)
expect(body.isPaying).toBe(true)
})
it('keeps a card-less product trial on the upgrade path with its expiry', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: { expires_at: '2099-01-01T00:00:00Z' } },
})
const { status, body } = await parseJsonResponse<StatusBody>(await GET())
expect(status).toBe(200)
expect(body.isPaying).toBe(false)
expect(body.trialEndsAt).toBe('2099-01-01T00:00:00Z')
})
it('treats an active subscription as paying', async () => {
authAs({
company_subscriptions: { data: { status: 'active' } },
capability_grants: { data: null },
})
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(true)
})
it('treats a canceled subscription as not paying', async () => {
authAs({
company_subscriptions: { data: { status: 'canceled' } },
capability_grants: { data: null },
})
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(false)
})
})
// WL-10 billing honesty: a non-paying company under a byrå team with an
// active team-scoped manual grant gets the additive teamAgreement field.
describe('GET /api/billing/status team agreement', () => {
it('returns teamAgreement for a byrå-covered non-paying company', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: null }] },
}
const { status, body } = await parseJsonResponse<StatusBody>(await GET())
expect(status).toBe(200)
expect(body.isPaying).toBe(false)
expect(body.teamAgreement).toEqual({ teamName: 'Siffran AB' })
})
it('accepts a future-dated grant expiry', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: '2099-01-01T00:00:00Z' }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.teamAgreement).toEqual({ teamName: 'Siffran AB' })
})
it('ignores an expired team grant (grace lapsed: standard paywall)', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: '2020-01-01T00:00:00Z' }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(false)
expect(body.teamAgreement).toBeUndefined()
})
it('ignores a personal team even with a manual grant', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Personal', kind: 'personal' } },
capability_grants: { data: [{ expires_at: null }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.teamAgreement).toBeUndefined()
})
it('leaves a teamless company unchanged', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: { expires_at: '2099-01-01T00:00:00Z' } },
})
serviceByTable = {
companies: { data: { team_id: null } },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(false)
expect(body.trialEndsAt).toBe('2099-01-01T00:00:00Z')
expect(body.teamAgreement).toBeUndefined()
expect('teamAgreement' in (body as object)).toBe(false)
})
it('never consults the team path for a paying company', async () => {
authAs({
company_subscriptions: { data: { status: 'active' } },
capability_grants: { data: null },
})
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(true)
expect(body.teamAgreement).toBeUndefined()
expect(createServiceClientMock).not.toHaveBeenCalled()
})
})
+154
View File
@@ -0,0 +1,154 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { createServiceClient } from '@/lib/supabase/server'
import { getStripe, priceIdForPlan } from '@/lib/stripe/client'
import { guardSandbox, sandboxBlockedResponse } from '@/lib/sandbox/guard'
import { resolveRequestAppOrigin } from '@/lib/domains/trusted-app-origin'
const CheckoutSchema = z.object({
plan: z.enum(['monthly', 'yearly']).default('monthly'),
})
/**
* Create a Stripe subscription Checkout Session and return its hosted URL.
* The client redirects to it; provisioning happens via the webhook on
* checkout.session.completed (never trust the success redirect for fulfilment).
*
* company_subscriptions is read/written via the service client on purpose —
* the row is webhook-owned and not member-readable under RLS; every query
* still filters by the membership-validated companyId.
*/
export const POST = withRouteContext('billing.checkout', async (request, ctx) => {
const { user, supabase, companyId, log } = ctx
// Demo accounts must never reach Stripe. An anonymous user has no real
// identity to bill, and a sandbox company must never charge a token (same
// doctrine as lib/sandbox/guard.ts: no real external side effects). Both
// checks run before any Stripe call: this is the gap that let an anonymous
// demo user create a live Stripe customer.
if (user.is_anonymous) return sandboxBlockedResponse()
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const validation = await validateBody(request, CheckoutSchema, {
log,
operation: 'billing.checkout',
})
if (!validation.success) return validation.response
const { plan } = validation.data
const priceId = priceIdForPlan(plan)
if (!priceId) {
return NextResponse.json(
{
error: {
code: 'STRIPE_NOT_CONFIGURED',
message: 'Betalning är inte konfigurerad. Kontakta supporten.',
message_en: 'Stripe price not configured.',
},
},
{ status: 500 },
)
}
const stripe = getStripe()
const service = createServiceClient()
// Reuse the company's Stripe customer if we already created one, and read
// the trial expiry for the deferred-first-charge decision below. Independent
// reads, so one round-trip batch.
const [{ data: existing }, { data: trialGrant, error: trialGrantError }] = await Promise.all([
service
.from('company_subscriptions')
.select('stripe_customer_id')
.eq('company_id', companyId)
.maybeSingle(),
service
.from('capability_grants')
.select('expires_at')
.eq('company_id', companyId)
.eq('source', 'trial')
.order('expires_at', { ascending: false })
.limit(1)
.maybeSingle(),
])
// Fail closed on an uncertain trial state: proceeding on a lookup error
// would silently charge immediately after the UI promised "0 kr idag".
if (trialGrantError) {
return NextResponse.json(
{
error: {
code: 'TRIAL_LOOKUP_FAILED',
message: 'Kunde inte läsa din provperiod. Försök igen om en stund.',
message_en: 'Could not resolve the trial state. Try again shortly.',
},
},
{ status: 500 },
)
}
// Defer the first charge to the end of an active trial. The company already
// holds the paid capabilities free until then, so charging at checkout would
// bill for days it already has; instead the subscription starts as
// 'trialing' (which grants access via the webhook, see subscription-sync)
// and the first charge lands when the product trial ends. Stripe Checkout
// requires trial_end to be at least 48h in the future; closer than that, or
// with no active trial, billing starts immediately.
const trialExpiry = (trialGrant as { expires_at: string | null } | null)?.expires_at ?? null
const trialExpiryMs = trialExpiry ? new Date(trialExpiry).getTime() : null
const STRIPE_MIN_TRIAL_END_MS = 49 * 3600 * 1000 // Stripe's 48h floor + 1h clock margin
const trialEnd =
trialExpiryMs && trialExpiryMs - Date.now() > STRIPE_MIN_TRIAL_END_MS
? Math.floor(trialExpiryMs / 1000)
: undefined
let customerId = (existing as { stripe_customer_id: string | null } | null)?.stripe_customer_id ?? null
if (!customerId) {
const customer = await stripe.customers.create({
email: user.email ?? undefined,
metadata: { company_id: companyId },
})
customerId = customer.id
await service
.from('company_subscriptions')
.upsert({ company_id: companyId, stripe_customer_id: customerId }, { onConflict: 'company_id' })
}
// Return the user to the host they started on. Sessions are per domain, so
// sending a white-label user back to the canonical app would land them on a
// foreign-branded login with no session. The origin is resolved against the
// brands table; an unknown or spoofed host falls back to the
// canonical app URL. The paths stay fixed: never accept a caller-supplied
// return URL here.
const appOrigin = await resolveRequestAppOrigin(request)
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
// Swedish VAT: the Price is net (tax_behavior=exclusive in Stripe), so Stripe
// Tax adds 25% moms for SE customers and applies reverse charge for EU-B2B with
// a valid VAT number. automatic_tax carries onto the created subscription, so
// renewals (and the first charge after a deferred trial) stay taxed. The rate
// can only compute with a customer address, and a compliant momsfaktura needs
// it too; customer_update persists the address + tax id onto the pre-created
// customer for future invoices.
automatic_tax: { enabled: true },
tax_id_collection: { enabled: true },
billing_address_collection: 'required',
customer_update: { name: 'auto', address: 'auto' },
client_reference_id: companyId,
metadata: { company_id: companyId },
subscription_data: {
metadata: { company_id: companyId },
...(trialEnd ? { trial_end: trialEnd } : {}),
},
allow_promotion_codes: true,
success_url: `${appOrigin}/settings/billing?success=1`,
cancel_url: `${appOrigin}/settings/billing?canceled=1`,
})
return NextResponse.json({ url: session.url })
})
+58
View File
@@ -0,0 +1,58 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { createServiceClient } from '@/lib/supabase/server'
import { getStripe } from '@/lib/stripe/client'
import { guardSandbox, sandboxBlockedResponse } from '@/lib/sandbox/guard'
import { resolveRequestAppOrigin } from '@/lib/domains/trusted-app-origin'
/**
* Create a Stripe Billing Customer Portal session so the user can manage,
* upgrade/downgrade, or cancel their subscription. Stripe handles all the
* compliance/PCI surface: we never build those flows ourselves.
*
* company_subscriptions is read via the service client on purpose: the row
* is webhook-owned and not member-readable under RLS; the query still filters
* by the membership-validated companyId.
*/
export const POST = withRouteContext('billing.portal', async (request, ctx) => {
const { user, supabase, companyId } = ctx
// Demo accounts must never reach Stripe (see billing/checkout for the full
// rationale). Defense in depth: a demo tenant should never own a portal
// session even if a stray customer row exists.
if (user.is_anonymous) return sandboxBlockedResponse()
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const service = createServiceClient()
const { data: sub } = await service
.from('company_subscriptions')
.select('stripe_customer_id')
.eq('company_id', companyId)
.maybeSingle()
const customerId = (sub as { stripe_customer_id: string | null } | null)?.stripe_customer_id
if (!customerId) {
return NextResponse.json(
{
error: {
code: 'NO_SUBSCRIPTION',
message: 'Det finns inget abonnemang att hantera.',
message_en: 'No subscription to manage.',
},
},
{ status: 400 },
)
}
// Same host the user started on (see billing/checkout): a registered
// white-label host stays on its brand, anything else returns to the
// canonical app. The path is fixed.
const appOrigin = await resolveRequestAppOrigin(request)
const portal = await getStripe().billingPortal.sessions.create({
customer: customerId,
return_url: `${appOrigin}/settings/billing`,
})
return NextResponse.json({ url: portal.url })
})
+81
View File
@@ -0,0 +1,81 @@
import { NextResponse } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { requireCompanyId } from '@/lib/company/context'
import { isStripeConfigured } from '@/lib/stripe/client'
import { isSandboxCompany } from '@/lib/sandbox/guard'
import { getTeamAgreement, type TeamAgreement } from '@/lib/entitlements/team-agreement'
/**
* Billing status for the client-rendered billing section (which lives inside the
* settings modal Dialog and can't read the DB server-side). Returns whether the
* company is paying, whether Stripe checkout is configured, and the trial expiry
* (for the days-left urgency banner). Read-only.
*
* WL-10: a non-paying company covered by its byrå team's agreement (active
* team-scoped manual grant) additionally gets `teamAgreement: { teamName }`,
* which the settings surface renders as "Ingår i <byråns namn>s avtal"
* instead of the upgrade pitch. Additive field: absent for everyone else.
*/
export async function GET() {
const { user, supabase, error } = await requireAuth()
if (error) return error
let companyId: string | null = null
try {
companyId = await requireCompanyId(supabase, user.id)
} catch {
companyId = null
}
// Demo accounts (anonymous user or sandbox company) can't check out, so the
// client hides the upgrade CTA rather than showing a button that only errors.
let isDemo = user.is_anonymous === true
if (companyId && !isDemo) {
isDemo = await isSandboxCompany(supabase, companyId)
}
let isPaying = false
let trialEndsAt: string | null = null
let teamAgreement: TeamAgreement | null = null
if (companyId) {
const { data: sub } = await supabase
.from('company_subscriptions')
.select('status')
.eq('company_id', companyId)
.maybeSingle()
const status = (sub as { status: string | null } | null)?.status ?? null
// Paying = a real subscription. Includes 'trialing': checkout defers the
// first charge to the product-trial end, so a Stripe-trialing subscription
// means the card is already committed and the user should see the manage
// view, not the upgrade pitch. Companies without a subscription (product
// trial only, no card) stay on the upgrade path.
isPaying = status === 'active' || status === 'past_due' || status === 'trialing'
const { data: trial } = await supabase
.from('capability_grants')
.select('expires_at')
.eq('company_id', companyId)
.eq('source', 'trial')
.order('expires_at', { ascending: false })
.limit(1)
.maybeSingle()
trialEndsAt = (trial as { expires_at: string | null } | null)?.expires_at ?? null
// Team entitlement (WL-10): only consulted when the company isn't paying
// on its own subscription. Service client by necessity: end clients are
// not members of the byrå team, so RLS hides the team and its grants
// from the user's session.
if (!isPaying) {
teamAgreement = await getTeamAgreement(createServiceClient(), companyId)
}
}
return NextResponse.json({
isPaying,
configured: isStripeConfigured(),
trialEndsAt,
isDemo,
...(teamAgreement ? { teamAgreement } : {}),
})
}
@@ -0,0 +1,106 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
vi.mock('@/lib/reports/opening-balances', () => ({
getOpeningBalances: vi.fn(),
}))
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { getOpeningBalances } from '@/lib/reports/opening-balances'
import { GET } from '../route'
function request(searchParams: Record<string, string>) {
return createMockRequest('/api/bookkeeping/account-balances', { searchParams })
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(getOpeningBalances).mockResolvedValue({
balances: new Map(),
obEntryId: null,
})
})
describe('GET /api/bookkeeping/account-balances', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect((await GET(request({ accounts: '1930', as_of: '2026-06-30' }), {
params: Promise.resolve({}),
})).status).toBe(401)
})
it('returns 400 for an invalid account number', async () => {
const { supabase } = createQueuedMockSupabase()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
expect((await GET(request({ accounts: 'not-an-account', as_of: '2026-06-30' }), {
params: Promise.resolve({}),
})).status).toBe(400)
})
it('returns zero balances when no fiscal period contains the date', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: null })
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const { status, body } = await parseJsonResponse<{
data: Array<{ account_number: string; balance: number }>
}>(await GET(request({ accounts: '1930', as_of: '2026-06-30' }), {
params: Promise.resolve({}),
}))
expect(status).toBe(200)
expect(body.data).toEqual([{ account_number: '1930', balance: 0 }])
})
it('combines opening balances with aggregated period activity', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{
data: {
id: 'period-1',
period_start: '2026-01-01',
period_end: '2026-12-31',
opening_balance_entry_id: 'opening-1',
},
},
{ data: [{ account_number: '1930', account_class: 1 }] },
{ data: [{ account_number: '1930', debit: 250, credit: 50 }] },
])
vi.mocked(getOpeningBalances).mockResolvedValue({
balances: new Map([['1930', { debit: 1_000, credit: 0 }]]),
obEntryId: 'opening-1',
})
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const { status, body } = await parseJsonResponse<{
data: Array<{ account_number: string; balance: number }>
}>(await GET(request({ accounts: '1930', as_of: '2026-06-30' }), {
params: Promise.resolve({}),
}))
expect(status).toBe(200)
expect(body.data).toEqual([{ account_number: '1930', balance: 1_200 }])
expect(supabase.rpc).toHaveBeenCalledWith('get_account_period_activity', {
p_company_id: 'company-1',
p_start: '2026-01-01',
p_end: '2026-06-30',
p_accounts: ['1930'],
p_exclude_journal_entry_id: 'opening-1',
})
})
})
@@ -0,0 +1,139 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateQuery } from '@/lib/api/validate'
import { AccountBalancesQuerySchema } from '@/lib/api/schemas'
import { getOpeningBalances } from '@/lib/reports/opening-balances'
/**
* Per-account saldo as of a date. Used by the journal-entry form to show
* each account's balance before the draft entry is posted.
*
* Mirrors the trial-balance model:
* - Balance-sheet accounts (class 1-2): IB + period activity through as_of.
* - P&L accounts (class 3-8): period activity only (P&L resets
* each räkenskapsår; carrying a
* since-inception sum would violate
* BFNAR 2013:2).
*
* IB is sourced via getOpeningBalances() so SIE-imported and year-end-closed
* companies behave identically. The opening-balance entry is excluded from
* period activity to avoid double-counting its lines.
*/
export const GET = withRouteContext('bookkeeping.account_balances', async (request, ctx) => {
const { supabase, companyId, log } = ctx
const params = validateQuery(request, AccountBalancesQuerySchema, {
log,
operation: 'bookkeeping.account_balances',
})
if (!params.success) return params.response
const { accounts, as_of } = params.data
// Find the fiscal period containing as_of (any state: we want a reference
// saldo even for closed/locked periods).
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('id, period_start, period_end, opening_balance_entry_id')
.eq('company_id', companyId)
.lte('period_start', as_of)
.gte('period_end', as_of)
.order('period_start', { ascending: false })
.limit(1)
.maybeSingle()
if (periodError) {
log.error('fiscal period lookup failed', { companyId, as_of, error: periodError.message })
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
// No period anchor → no meaningful IB, return zeros so the UI degrades cleanly.
if (!period) {
return NextResponse.json({
data: accounts.map((account_number) => ({ account_number, balance: 0 })),
})
}
const { data: coaRows, error: coaError } = await supabase
.from('chart_of_accounts')
.select('account_number, account_class')
.eq('company_id', companyId)
.in('account_number', accounts)
if (coaError) {
log.error('chart of accounts lookup failed', { companyId, error: coaError.message })
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
const accountClass = new Map<string, number>()
for (const row of coaRows ?? []) {
accountClass.set(row.account_number, row.account_class)
}
let openingBalances: Map<string, { debit: number; credit: number }>
let obEntryId: string | null
try {
const result = await getOpeningBalances(supabase, companyId, {
period_start: period.period_start,
opening_balance_entry_id: period.opening_balance_entry_id,
})
openingBalances = result.balances
obEntryId = result.obEntryId
} catch (err) {
log.error('opening-balance computation failed', {
companyId,
period_id: period.id,
error: err instanceof Error ? err.message : String(err),
})
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
// Sum activity from period_start through as_of, excluding the OB entry
// (its lines are already in openingBalances).
const { data: activityRows, error: activityError } = await supabase.rpc(
'get_account_period_activity',
{
p_company_id: companyId,
p_start: period.period_start,
p_end: as_of,
p_accounts: accounts,
p_exclude_journal_entry_id: obEntryId,
},
)
if (activityError) {
log.error('period activity lookup failed', {
companyId,
period_id: period.id,
error: activityError.message,
})
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
const periodActivity = new Map<string, { debit: number; credit: number }>()
for (const row of activityRows ?? []) {
periodActivity.set(row.account_number, {
debit: Number(row.debit) || 0,
credit: Number(row.credit) || 0,
})
}
return NextResponse.json({
data: accounts.map((account_number) => {
// Fall back to inferring class from the first digit for accounts not in
// the company's COA (e.g. system accounts the user typed manually).
const klass = accountClass.get(account_number) ?? (parseInt(account_number[0], 10) || 0)
const isBalanceSheet = klass >= 1 && klass <= 2
const ib = isBalanceSheet
? openingBalances.get(account_number) || { debit: 0, credit: 0 }
: { debit: 0, credit: 0 }
const activity = periodActivity.get(account_number) || { debit: 0, credit: 0 }
const net = ib.debit - ib.credit + activity.debit - activity.credit
return {
account_number,
balance: Math.round(net * 100) / 100,
}
}),
})
})
+136
View File
@@ -0,0 +1,136 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateQuery } from '@/lib/api/validate'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
// GET /api/bookkeeping/account-totals?from=3000&to=3999[&date_from=..&date_to=..&group_by=month]
//
// Sums posted debit/credit per account in an account-number range, optionally
// bucketed by month. Both the entry list and the per-batch line fetches are
// paginated — PostgREST caps unpaginated selects at 1000 rows, which would
// silently under-count totals for companies with large journals.
const QuerySchema = z.object({
from: z.string().regex(/^\d{4}$/, 'from must be a 4-digit account number'),
to: z.string().regex(/^\d{4}$/, 'to must be a 4-digit account number'),
date_from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
date_to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
group_by: z.enum(['month']).optional(),
})
export const GET = withRouteContext('bookkeeping.account_totals', async (request, ctx) => {
const { supabase, companyId, log } = ctx
const validated = validateQuery(request, QuerySchema, {
log,
operation: 'bookkeeping.account_totals',
})
if (!validated.success) return validated.response
const { from, to, date_from: dateFrom, date_to: dateTo, group_by: groupBy } = validated.data
// Posted entries in range — paginated (large journals exceed 1000 entries).
const entries = await fetchAllRows<{ id: string; entry_date: string }>(({ from: f, to: t }) => {
let query = supabase
.from('journal_entries')
.select('id, entry_date')
.eq('company_id', companyId)
.eq('status', 'posted')
if (dateFrom) query = query.gte('entry_date', dateFrom)
if (dateTo) query = query.lte('entry_date', dateTo)
return query.order('id', { ascending: true }).range(f, t)
})
if (entries.length === 0) {
return NextResponse.json({ totals: [], monthly: groupBy === 'month' ? [] : undefined })
}
const entryIds = entries.map((e) => e.id)
const entryDateMap = new Map(entries.map((e) => [e.id, e.entry_date]))
// Fetch lines in id-batches to avoid URL length limits; each batch is
// itself paginated (200 entries can easily carry >1000 lines).
const batchSize = 200
const allLines: Array<{
journal_entry_id: string
account_number: string
debit_amount: number
credit_amount: number
}> = []
for (let i = 0; i < entryIds.length; i += batchSize) {
const batch = entryIds.slice(i, i + batchSize)
const lines = await fetchAllRows<{
journal_entry_id: string
account_number: string
debit_amount: number
credit_amount: number
}>(({ from: f, to: t }) =>
supabase
.from('journal_entry_lines')
.select('journal_entry_id, account_number, debit_amount, credit_amount')
.in('journal_entry_id', batch)
.gte('account_number', from)
.lte('account_number', to)
.order('id', { ascending: true })
.range(f, t)
)
allLines.push(...lines)
}
// Aggregate by account
const accountTotals = new Map<string, { debit: number; credit: number }>()
for (const line of allLines) {
const existing = accountTotals.get(line.account_number) || { debit: 0, credit: 0 }
existing.debit += Number(line.debit_amount) || 0
existing.credit += Number(line.credit_amount) || 0
accountTotals.set(line.account_number, existing)
}
const totals = Array.from(accountTotals.entries())
.map(([account_number, bal]) => ({
account_number,
debit: Math.round(bal.debit * 100) / 100,
credit: Math.round(bal.credit * 100) / 100,
net: Math.round((bal.debit - bal.credit) * 100) / 100,
}))
.sort((a, b) => a.account_number.localeCompare(b.account_number))
// Monthly grouping
if (groupBy === 'month') {
const monthlyMap = new Map<string, Map<string, { debit: number; credit: number }>>()
for (const line of allLines) {
const entryDate = entryDateMap.get(line.journal_entry_id)
if (!entryDate) continue
const month = entryDate.slice(0, 7)
if (!monthlyMap.has(month)) {
monthlyMap.set(month, new Map())
}
const monthAccounts = monthlyMap.get(month)!
const existing = monthAccounts.get(line.account_number) || { debit: 0, credit: 0 }
existing.debit += Number(line.debit_amount) || 0
existing.credit += Number(line.credit_amount) || 0
monthAccounts.set(line.account_number, existing)
}
const monthlyFlat = Array.from(monthlyMap.entries())
.sort(([a], [b]) => a.localeCompare(b))
.flatMap(([month, accounts]) =>
Array.from(accounts.entries()).map(([account_number, bal]) => ({
month,
account_number,
debit: Math.round(bal.debit * 100) / 100,
credit: Math.round(bal.credit * 100) / 100,
net: Math.round((bal.debit - bal.credit) * 100) / 100,
}))
)
return NextResponse.json({ totals, monthly: monthlyFlat })
}
return NextResponse.json({ totals })
})
@@ -0,0 +1,172 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { sparsePatchBody } from '@/lib/api/sparse-patch'
import { UpdateAccountSchema } from '@/lib/api/schemas'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import {
defaultRateForVatTreatment,
isVatTreatmentAllowedForAccountClass,
} from '@/lib/vat/account-vat-treatment'
// DELETE hard-deletes an unused, non-system account; accounts referenced by
// this company's journal entries must be deactivated instead (PUT is_active).
// Response shapes are legacy `{ error: string }` — the kontoplan UI renders
// them directly.
export const DELETE = withRouteContext(
'bookkeeping.accounts.delete',
async (_request, ctx, { params }: { params: Promise<{ number: string }> }) => {
const { number } = await params
const { supabase, companyId } = ctx
// Fetch the account to check if it's a system account
const { data: account, error: fetchError } = await supabase
.from('chart_of_accounts')
.select('id, is_system_account')
.eq('company_id', companyId)
.eq('account_number', number)
.single()
if (fetchError || !account) {
return NextResponse.json({ error: 'Kontot hittades inte' }, { status: 404 })
}
if (account.is_system_account) {
return NextResponse.json(
{ error: 'Systemkonton kan inte tas bort' },
{ status: 400 }
)
}
// Check if the account is referenced in THIS company's journal entries.
// journal_entry_lines has no company_id column, so the scope has to come
// from the parent entry: a user can be a member of several companies, and
// another company's usage of the same BAS number must not block deletion
// here.
//
// This used to be a `journal_entries!inner(company_id)` head+count query.
// PostgREST compiles that embed into a correlated LATERAL join, so the
// count walked the ENTIRE journal_entry_lines table across all tenants to
// answer a single-account question (see lib/bookkeeping/entry-lines.ts).
// fetchEntryLines cannot replace it (it returns rows, not a count), so the
// count moves into SQL: get_account_usage_counts is the same
// company-scoped aggregate the kontoplan usage column and the prune dialog
// already run (migration 20260704110000, covering index 20260706120000),
// and it counts lines on ALL entry statuses, exactly like the old query.
const { data: usage, error: usageError } = await supabase.rpc('get_account_usage_counts', {
p_company_id: companyId,
})
if (usageError) {
return NextResponse.json({ error: getUserErrorMessage(usageError) }, { status: 500 })
}
const count = ((usage ?? []) as { account_number: string; usage_count: number }[]).find(
(row) => row.account_number === number,
)?.usage_count
if (count && count > 0) {
return NextResponse.json(
{ error: 'Kontot kan inte tas bort eftersom det används i bokförda verifikationer. Inaktivera det istället.' },
{ status: 400 }
)
}
const { error: deleteError } = await supabase
.from('chart_of_accounts')
.delete()
.eq('id', account.id)
.eq('company_id', companyId)
if (deleteError) {
return NextResponse.json({ error: getUserErrorMessage(deleteError) }, { status: 500 })
}
return NextResponse.json({ success: true })
},
{ requireWrite: true },
)
export const PUT = withRouteContext(
'bookkeeping.accounts.update',
async (request, ctx, { params }: { params: Promise<{ number: string }> }) => {
const { number } = await params
const { supabase, companyId, log } = ctx
// The body is spread straight into .update(), so only the fields the
// caller actually named may reach it. UpdateAccountSchema carries no
// .default() today, so sparsePatchBody is a no-op here: it is the
// structural guarantee that adding one later cannot make a PUT that
// renames an account also rewrite its VAT code or SRU mapping. An
// explicit null (clearing sru_code, VAT defaults, or descriptions)
// still survives.
const validation = await validateBody(request, sparsePatchBody(UpdateAccountSchema), {
log,
operation: 'bookkeeping.accounts.update',
})
if (!validation.success) return validation.response
const body = validation.data
const accountClass = parseInt(number[0])
if (
body.default_vat_treatment &&
!isVatTreatmentAllowedForAccountClass(body.default_vat_treatment, accountClass)
) {
return NextResponse.json(
{ error: 'Momskoden kan inte användas för den här kontoklassen.' },
{ status: 400 },
)
}
if (body.default_vat_treatment && body.default_vat_rate === undefined) {
const { data: current, error: currentError } = await supabase
.from('chart_of_accounts')
.select('default_vat_rate')
.eq('company_id', companyId)
.eq('account_number', number)
.single()
if (currentError) {
if (currentError.code === 'PGRST116') {
return NextResponse.json({ error: 'Kontot hittades inte' }, { status: 404 })
}
return NextResponse.json({ error: getUserErrorMessage(currentError) }, { status: 500 })
}
if (current.default_vat_rate == null) {
body.default_vat_rate = defaultRateForVatTreatment(
body.default_vat_treatment,
accountClass,
)
}
} else if (body.default_vat_treatment && body.default_vat_rate === null) {
body.default_vat_rate = defaultRateForVatTreatment(
body.default_vat_treatment,
accountClass,
)
}
if (Object.keys(body).length === 0) {
return NextResponse.json({ error: 'Inget att uppdatera' }, { status: 400 })
}
const { data, error } = await supabase
.from('chart_of_accounts')
.update(body)
.eq('company_id', companyId)
.eq('account_number', number)
.select()
.single()
if (error) {
// PGRST116 = zero rows — the account doesn't exist in this company.
if (error.code === 'PGRST116') {
return NextResponse.json({ error: 'Kontot hittades inte' }, { status: 404 })
}
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)
@@ -0,0 +1,758 @@
/**
* Tests for /api/bookkeeping/accounts (list/create), /[number] (update/delete)
* /activate and /deactivate.
*
* The DELETE usage check is asserted with a call-capturing mock: the count
* query must be scoped to the caller's company via the journal_entries join —
* without it, another company's use of the same BAS number (same user,
* multiple memberships under RLS) wrongly blocks deletion.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET as listGET, POST as createPOST } from '../route'
import { DELETE, PUT } from '../[number]/route'
import { POST as activatePOST } from '../activate/route'
import { POST as deactivatePOST } from '../deactivate/route'
interface CapturedCall {
method: string
args: unknown[]
}
/** Chainable builder recording calls; resolves queued {data,error,count} per from()/rpc(). */
function createCapturingSupabase(
results: { data?: unknown; error?: unknown; count?: number | null }[]
) {
const calls: CapturedCall[] = []
let idx = 0
const makeBuilder = () => {
const result = results[idx++] ?? { data: null, error: null, count: null }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const b: any = {}
for (const m of ['select', 'eq', 'in', 'gte', 'lte', 'is', 'order', 'limit', 'range', 'insert', 'update', 'delete', 'maybeSingle', 'single']) {
b[m] = (...args: unknown[]) => {
calls.push({ method: m, args })
return b
}
}
b.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null, count: result.count ?? null })
return b
}
const supabase = {
from: (table: string) => {
calls.push({ method: 'from', args: [table] })
return makeBuilder()
},
rpc: (...args: unknown[]) => {
calls.push({ method: 'rpc', args })
const result = results[idx++] ?? { data: null, error: null, count: null }
return Promise.resolve({ data: result.data ?? null, error: result.error ?? null })
},
}
return { supabase, calls }
}
const routeParams = { params: Promise.resolve({}) }
const numberParams = { params: Promise.resolve({ number: '5010' }) }
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
function auth(supabase: unknown) {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
}
describe('GET /api/bookkeeping/accounts', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await listGET(createMockRequest('/api/bookkeeping/accounts'), routeParams)
expect(res.status).toBe(401)
})
it('returns 400 for a non-numeric class filter', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', { searchParams: { class: 'abc' } })
const { status } = await parseJsonResponse(await listGET(req, routeParams))
expect(status).toBe(400)
})
it('lists accounts via the single-round-trip RPC', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: [{ account_number: '1930', account_name: 'Företagskonto' }] },
])
auth(supabase)
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
await listGET(createMockRequest('/api/bookkeeping/accounts'), routeParams)
)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
const rpcCall = calls.find((c) => c.method === 'rpc')
expect(rpcCall?.args).toEqual([
'list_company_accounts',
{ p_company_id: 'company-1', p_active_only: true, p_account_class: null },
])
// The RPC path must not also hit the table: exactly one round trip.
expect(calls.some((c) => c.method === 'from')).toBe(false)
})
it('maps ?class=3&active=false onto the RPC arguments', async () => {
const { supabase, calls } = createCapturingSupabase([{ data: [] }])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', {
searchParams: { class: '3', active: 'false' },
})
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
await listGET(req, routeParams)
)
expect(status).toBe(200)
expect(body.data).toEqual([])
const rpcCall = calls.find((c) => c.method === 'rpc')
expect(rpcCall?.args[1]).toEqual({
p_company_id: 'company-1',
p_active_only: false,
p_account_class: 3,
})
})
it('falls back to the paged fetch when the RPC is not deployed (PGRST202)', async () => {
const { supabase, calls } = createCapturingSupabase([
{ error: { code: 'PGRST202', message: 'function not found in schema cache' } },
{ data: [{ account_number: '1930', account_name: 'Företagskonto' }] },
])
auth(supabase)
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
await listGET(createMockRequest('/api/bookkeeping/accounts'), routeParams)
)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
expect(calls.filter((c) => c.method === 'from').map((c) => c.args)).toContainEqual([
'chart_of_accounts',
])
expect(calls.filter((c) => c.method === 'eq').map((c) => c.args)).toContainEqual([
'company_id',
'company-1',
])
})
it('returns the legacy 500 { error: string } on a non-fallback RPC error', async () => {
const { supabase, calls } = createCapturingSupabase([
{ error: { code: 'XX000', message: 'boom' } },
])
auth(supabase)
const { status, body } = await parseJsonResponse<{ error: string }>(
await listGET(createMockRequest('/api/bookkeeping/accounts'), routeParams)
)
expect(status).toBe(500)
expect(typeof body.error).toBe('string')
// A non-deploy error must NOT silently fall back to the paged fetch.
expect(calls.some((c) => c.method === 'from')).toBe(false)
})
})
describe('POST /api/bookkeeping/accounts', () => {
it('returns 409 with a Swedish message on duplicate account number', async () => {
const { supabase } = createCapturingSupabase([{ error: { code: '23505', message: 'dup' } }])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', {
method: 'POST',
body: {
account_number: '5010',
account_name: 'Lokalhyra',
account_type: 'expense',
normal_balance: 'debit',
},
})
const { status, body } = await parseJsonResponse<{ error: string }>(
await createPOST(req, routeParams)
)
expect(status).toBe(409)
expect(body.error).toContain('5010')
})
it('keeps the plain 409 when the colliding account is active', async () => {
const { supabase } = createCapturingSupabase([
{ error: { code: '23505', message: 'dup' } },
{ data: { is_active: true } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', {
method: 'POST',
body: {
account_number: '5010',
account_name: 'Lokalhyra',
account_type: 'expense',
normal_balance: 'debit',
},
})
const { status, body } = await parseJsonResponse<{ error: string }>(
await createPOST(req, routeParams)
)
expect(status).toBe(409)
expect(typeof body.error).toBe('string')
})
it('returns ACCOUNT_EXISTS_INACTIVE when the colliding account is deactivated', async () => {
const { supabase, calls } = createCapturingSupabase([
{ error: { code: '23505', message: 'dup' } },
{ data: { is_active: false } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', {
method: 'POST',
body: {
account_number: '3910',
account_name: 'Hyresintäkter egen',
account_type: 'revenue',
normal_balance: 'credit',
},
})
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; details?: { account_number?: string } }
}>(await createPOST(req, routeParams))
expect(status).toBe(409)
expect(body.error.code).toBe('ACCOUNT_EXISTS_INACTIVE')
expect(body.error.message).toContain('3910')
expect(body.error.details?.account_number).toBe('3910')
// The is_active lookup must be company-scoped, not a bare account_number
// match: the same number exists under every other company too.
const eqArgs = calls.filter((c) => c.method === 'eq').map((c) => c.args)
expect(eqArgs).toContainEqual(['company_id', 'company-1'])
expect(eqArgs).toContainEqual(['account_number', '3910'])
})
it('forwards default_vat_rate into the insert', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { account_number: '3740', default_vat_rate: 0 } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', {
method: 'POST',
body: {
account_number: '3740',
account_name: 'Öres- och kronutjämning',
account_type: 'revenue',
normal_balance: 'debit',
default_vat_rate: 0,
},
})
const { status } = await parseJsonResponse(await createPOST(req, routeParams))
expect(status).toBe(200)
const insertArg = calls.find((c) => c.method === 'insert')?.args[0] as {
default_vat_rate?: number | null
}
expect(insertArg?.default_vat_rate).toBe(0)
})
it('forwards default_vat_treatment into the insert', async () => {
const { supabase, calls } = createCapturingSupabase([{
data: { account_number: '4056', default_vat_treatment: 'reverse_charge_eu_goods' },
}])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', {
method: 'POST',
body: {
account_number: '4056',
account_name: 'Inköp varor EU',
account_type: 'expense',
normal_balance: 'debit',
default_vat_treatment: 'reverse_charge_eu_goods',
},
})
expect((await createPOST(req, routeParams)).status).toBe(200)
const insertArg = calls.find((c) => c.method === 'insert')?.args[0] as {
default_vat_treatment?: string | null
}
expect(insertArg.default_vat_treatment).toBe('reverse_charge_eu_goods')
})
it('derives the booking rate when a treatment is set without one', async () => {
const { supabase, calls } = createCapturingSupabase([{ data: { account_number: '4056' } }])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', {
method: 'POST',
body: {
account_number: '4056',
account_name: 'Inköp varor EU',
account_type: 'expense',
normal_balance: 'debit',
default_vat_treatment: 'reverse_charge_eu_goods',
},
})
expect((await createPOST(req, routeParams)).status).toBe(200)
const insertArg = calls.find((c) => c.method === 'insert')?.args[0] as {
default_vat_rate?: number | null
}
expect(insertArg.default_vat_rate).toBe(0.25)
})
it('rejects a treatment that cannot apply to the account class', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts', {
method: 'POST',
body: {
account_number: '4056',
account_name: 'Inköp varor EU',
account_type: 'expense',
normal_balance: 'debit',
default_vat_treatment: 'standard_25',
},
})
expect((await createPOST(req, routeParams)).status).toBe(400)
})
})
describe('DELETE /api/bookkeeping/accounts/[number]', () => {
it('scopes the usage check to the company via the usage-counts RPC', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { id: 'acc-1', is_system_account: false } }, // account fetch
{ data: [{ account_number: '4010', usage_count: 7 }] }, // usage counts (not 5010)
{ data: null }, // delete
])
auth(supabase)
const { status } = await parseJsonResponse(
await DELETE(createMockRequest('/api/bookkeeping/accounts/5010'), numberParams)
)
expect(status).toBe(200)
// The company scope is an RPC argument now, not a filter on an embed:
// another company's use of the same BAS number can never be counted here.
const rpcCalls = calls.filter((c) => c.method === 'rpc').map((c) => c.args)
expect(rpcCalls).toContainEqual(['get_account_usage_counts', { p_company_id: 'company-1' }])
const selectArgs = calls.filter((c) => c.method === 'select').map((c) => c.args[0])
expect(selectArgs).not.toContain('id, journal_entries!inner(company_id)')
})
it('refuses deleting an account used in this company with 400', async () => {
const { supabase } = createCapturingSupabase([
{ data: { id: 'acc-1', is_system_account: false } },
{ data: [{ account_number: '5010', usage_count: 3 }] },
])
auth(supabase)
const { status, body } = await parseJsonResponse<{ error: string }>(
await DELETE(createMockRequest('/api/bookkeeping/accounts/5010'), numberParams)
)
expect(status).toBe(400)
expect(body.error).toContain('Inaktivera')
})
it('refuses deleting a system account', async () => {
const { supabase } = createCapturingSupabase([
{ data: { id: 'acc-1', is_system_account: true } },
])
auth(supabase)
const { status } = await parseJsonResponse(
await DELETE(createMockRequest('/api/bookkeeping/accounts/5010'), numberParams)
)
expect(status).toBe(400)
})
})
describe('PUT /api/bookkeeping/accounts/[number]', () => {
it('returns 400 when the body has nothing to update', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/5010', { method: 'PUT', body: {} })
const { status } = await parseJsonResponse(await PUT(req, numberParams))
expect(status).toBe(400)
})
it('maps zero-rows (PGRST116) to 404', async () => {
const { supabase } = createCapturingSupabase([
{ error: { code: 'PGRST116', message: 'no rows' } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/5010', {
method: 'PUT',
body: { account_name: 'Nytt namn' },
})
const { status, body } = await parseJsonResponse<{ error: string }>(await PUT(req, numberParams))
expect(status).toBe(404)
expect(body.error).toBe('Kontot hittades inte')
})
it('updates the account', async () => {
const { supabase } = createCapturingSupabase([
{ data: { account_number: '5010', account_name: 'Nytt namn' } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/5010', {
method: 'PUT',
body: { account_name: 'Nytt namn' },
})
const { status, body } = await parseJsonResponse<{ data: { account_name: string } }>(
await PUT(req, numberParams)
)
expect(status).toBe(200)
expect(body.data.account_name).toBe('Nytt namn')
})
it('forwards default_vat_rate into the update', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { account_number: '3740', default_vat_rate: 0 } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/3740', {
method: 'PUT',
body: { default_vat_rate: 0 },
})
const { status } = await parseJsonResponse(
await PUT(req, { params: Promise.resolve({ number: '3740' }) })
)
expect(status).toBe(200)
const updateArg = calls.find((c) => c.method === 'update')?.args[0] as {
default_vat_rate?: number | null
}
expect(updateArg?.default_vat_rate).toBe(0)
})
it('preserves an existing booking rate when updating only the treatment', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { default_vat_rate: 0.12 } },
{ data: { account_number: '3041', default_vat_treatment: 'standard_25' } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/3041', {
method: 'PUT',
body: { default_vat_treatment: 'standard_25' },
})
expect((await PUT(req, { params: Promise.resolve({ number: '3041' }) })).status).toBe(200)
const updateArg = calls.find((c) => c.method === 'update')?.args[0] as {
default_vat_treatment?: string | null
default_vat_rate?: number | null
}
expect(updateArg.default_vat_treatment).toBe('standard_25')
expect(updateArg.default_vat_rate).toBeUndefined()
})
it('derives the booking rate when treatment is updated and the stored rate is unset', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { default_vat_rate: null } },
{
data: {
account_number: '4056',
default_vat_treatment: 'reverse_charge_eu_goods',
default_vat_rate: 0.25,
},
},
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/4056', {
method: 'PUT',
body: { default_vat_treatment: 'reverse_charge_eu_goods' },
})
expect((await PUT(req, { params: Promise.resolve({ number: '4056' }) })).status).toBe(200)
const updateArg = calls.find((c) => c.method === 'update')?.args[0] as {
default_vat_rate?: number | null
}
expect(updateArg.default_vat_rate).toBe(0.25)
})
// The body is spread straight into .update(), so the write set must be
// exactly what the caller named. UpdateAccountSchema carries no .default()
// today; these two lock the property in so adding one cannot turn a rename
// into a silent rewrite of the VAT code and SRU mapping.
it('writes only the field the caller named', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { account_number: '5010', account_name: 'Nytt namn' } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/5010', {
method: 'PUT',
body: { account_name: 'Nytt namn' },
})
expect((await parseJsonResponse(await PUT(req, numberParams))).status).toBe(200)
const updateArg = calls.find((c) => c.method === 'update')?.args[0] as Record<string, unknown>
expect(Object.keys(updateArg)).toEqual(['account_name'])
})
it('keeps an explicit null so sru_code can be cleared', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { account_number: '5010', sru_code: null } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/5010', {
method: 'PUT',
body: { sru_code: null },
})
expect((await parseJsonResponse(await PUT(req, numberParams))).status).toBe(200)
const updateArg = calls.find((c) => c.method === 'update')?.args[0] as Record<string, unknown>
expect(updateArg).toEqual({ sru_code: null })
})
it('drops unknown keys instead of forwarding them to the update', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { account_number: '5010' } },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/5010', {
method: 'PUT',
body: { account_name: 'Nytt namn', is_system_account: true, company_id: 'other' },
})
expect((await parseJsonResponse(await PUT(req, numberParams))).status).toBe(200)
const updateArg = calls.find((c) => c.method === 'update')?.args[0] as Record<string, unknown>
expect(Object.keys(updateArg)).toEqual(['account_name'])
})
})
describe('POST /api/bookkeeping/accounts/activate', () => {
it('returns 400 (not a crash) on invalid JSON', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
const req = new Request('http://localhost/api/bookkeeping/accounts/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: '{not json',
})
const { status, body } = await parseJsonResponse<{ error: string }>(
await activatePOST(req, routeParams)
)
expect(status).toBe(400)
expect(body.error).toBe('account_numbers array required')
})
it('returns 400 when account_numbers is missing or empty', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/activate', {
method: 'POST',
body: { account_numbers: [] },
})
const { status } = await parseJsonResponse(await activatePOST(req, routeParams))
expect(status).toBe(400)
})
it('activates a known BAS account and buckets unknown numbers', async () => {
const { supabase } = createCapturingSupabase([
{ data: [] }, // existing lookup — none in chart
{ data: [{ account_number: '1930' }] }, // insert result
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/activate', {
method: 'POST',
body: { account_numbers: ['1930', '0000'] },
})
const { status, body } = await parseJsonResponse<{
activated: number
unknown: string[]
}>(await activatePOST(req, routeParams))
expect(status).toBe(200)
expect(body.activated).toBe(1)
expect(body.unknown).toEqual(['0000'])
})
// The only route back for a deactivated account: it is in the chart, so the
// insert path would hit the unique constraint. It must be flipped back on
// instead, including for custom numbers the BAS reference has never heard of.
it('reactivates an existing inactive account instead of inserting it', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: [{ account_number: '3910', is_active: false }] }, // existing lookup
{ data: [{ account_number: '3910' }] }, // update result
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/activate', {
method: 'POST',
body: { account_numbers: ['3910'] },
})
const { status, body } = await parseJsonResponse<{
activated: number
reactivated: number
skipped: number
unknown: string[]
}>(await activatePOST(req, routeParams))
expect(status).toBe(200)
expect(body.reactivated).toBe(1)
expect(body.activated).toBe(0)
expect(body.unknown).toEqual([])
expect(calls.find((c) => c.method === 'update')?.args[0]).toEqual({ is_active: true })
expect(calls.some((c) => c.method === 'insert')).toBe(false)
})
it('skips an account that is already active', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: [{ account_number: '1930', is_active: true }] },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/activate', {
method: 'POST',
body: { account_numbers: ['1930'] },
})
const { status, body } = await parseJsonResponse<{
activated: number
reactivated: number
skipped: number
}>(await activatePOST(req, routeParams))
expect(status).toBe(200)
expect(body.skipped).toBe(1)
expect(body.reactivated).toBe(0)
expect(calls.some((c) => c.method === 'update')).toBe(false)
expect(calls.some((c) => c.method === 'insert')).toBe(false)
})
})
describe('POST /api/bookkeeping/accounts/deactivate', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/bookkeeping/accounts/deactivate', {
method: 'POST',
body: { account_numbers: ['4010'] },
})
const res = await deactivatePOST(req, routeParams)
expect(res.status).toBe(401)
})
it('returns 400 when account_numbers is missing or empty', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/deactivate', {
method: 'POST',
body: { account_numbers: [] },
})
const { status, body } = await parseJsonResponse<{ error: string }>(
await deactivatePOST(req, routeParams)
)
expect(status).toBe(400)
expect(body.error).toBe('account_numbers array required')
})
it('returns 403 for a viewer', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const req = createMockRequest('/api/bookkeeping/accounts/deactivate', {
method: 'POST',
body: { account_numbers: ['4010'] },
})
const res = await deactivatePOST(req, routeParams)
expect(res.status).toBe(403)
})
// The post-migration sweep: only never-used, non-system, active accounts
// flip; everything else is reported back so the UI can say what it skipped.
it('deactivates the never-used accounts and reports what it skipped', async () => {
const { supabase, calls } = createCapturingSupabase([
{
data: [
{ account_number: '4010', is_active: true, is_system_account: false }, // unused
{ account_number: '4020', is_active: true, is_system_account: false }, // unused
{ account_number: '5010', is_active: true, is_system_account: false }, // used
{ account_number: '1930', is_active: true, is_system_account: true }, // system
{ account_number: '6110', is_active: false, is_system_account: false }, // already off
],
},
{ data: [{ account_number: '5010', usage_count: 12 }] }, // get_account_usage_counts
{ data: [{ account_number: '4010' }, { account_number: '4020' }] }, // update result
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/deactivate', {
method: 'POST',
body: { account_numbers: ['4010', '4020', '5010', '1930', '6110', '9999'] },
})
const { status, body } = await parseJsonResponse<{
deactivated: number
skipped_system: string[]
skipped_used: string[]
skipped_inactive: number
unknown: string[]
}>(await deactivatePOST(req, routeParams))
expect(status).toBe(200)
expect(body.deactivated).toBe(2)
expect(body.skipped_used).toEqual(['5010'])
expect(body.skipped_system).toEqual(['1930'])
expect(body.skipped_inactive).toBe(1)
expect(body.unknown).toEqual(['9999'])
// Usage is read through the company-scoped RPC, never an embed.
expect(calls.find((c) => c.method === 'rpc')?.args).toEqual([
'get_account_usage_counts',
{ p_company_id: 'company-1' },
])
// The update is scoped to the company and to exactly the unused set.
const updateCall = calls.find((c) => c.method === 'update')
expect(updateCall?.args).toEqual([{ is_active: false }])
const inAfterUpdate = calls.slice(calls.indexOf(updateCall!)).find((c) => c.method === 'in')
expect(inAfterUpdate?.args).toEqual(['account_number', ['4010', '4020']])
})
it('includes used accounts only when include_used is set', async () => {
const { supabase } = createCapturingSupabase([
{ data: [{ account_number: '5010', is_active: true, is_system_account: false }] },
{ data: [{ account_number: '5010', usage_count: 3 }] },
{ data: [{ account_number: '5010' }] },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/deactivate', {
method: 'POST',
body: { account_numbers: ['5010'], include_used: true },
})
const { status, body } = await parseJsonResponse<{ deactivated: number; skipped_used: string[] }>(
await deactivatePOST(req, routeParams)
)
expect(status).toBe(200)
expect(body.deactivated).toBe(1)
expect(body.skipped_used).toEqual([])
})
it('skips the update entirely when nothing qualifies', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: [{ account_number: '5010', is_active: true, is_system_account: false }] },
{ data: [{ account_number: '5010', usage_count: 3 }] },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/deactivate', {
method: 'POST',
body: { account_numbers: ['5010'] },
})
const { status, body } = await parseJsonResponse<{ deactivated: number; skipped_used: string[] }>(
await deactivatePOST(req, routeParams)
)
expect(status).toBe(200)
expect(body.deactivated).toBe(0)
expect(body.skipped_used).toEqual(['5010'])
expect(calls.find((c) => c.method === 'update')).toBeUndefined()
})
})
@@ -0,0 +1,257 @@
/**
* Tests for /api/bookkeeping/accounts/usage and /prune.
*
* The prune execute phase is the safety-critical part: the client's
* account_numbers list is a selection, not an authority. The tests assert
* that used accounts, system accounts, and unknown numbers sent by the
* client are skipped/reported — only freshly re-verified unused accounts
* reach the DELETE.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET as usageGET } from '../usage/route'
import { POST as prunePOST } from '../prune/route'
interface CapturedCall {
method: string
args: unknown[]
}
/**
* Chainable builder recording calls; resolves queued {data,error} per
* from()/rpc() invocation, in call order.
*/
function createCapturingSupabase(results: { data?: unknown; error?: unknown }[]) {
const calls: CapturedCall[] = []
let idx = 0
const nextResult = () => results[idx++] ?? { data: null, error: null }
const makeBuilder = () => {
const result = nextResult()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const b: any = {}
for (const m of ['select', 'eq', 'in', 'order', 'range', 'insert', 'update', 'delete']) {
b[m] = (...args: unknown[]) => {
calls.push({ method: m, args })
return b
}
}
b.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null })
return b
}
const supabase = {
from: (table: string) => {
calls.push({ method: 'from', args: [table] })
return makeBuilder()
},
rpc: (fn: string, params: unknown) => {
calls.push({ method: 'rpc', args: [fn, params] })
const result = nextResult()
return Promise.resolve({ data: result.data ?? null, error: result.error ?? null })
},
}
return { supabase, calls }
}
const routeParams = { params: Promise.resolve({}) }
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
function auth(supabase: unknown) {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
}
function unauthenticated() {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
// Chart fixture: one system account, one used BAS account, one unused BAS
// account from the seed, one unused imported custom account.
const chartAccounts = [
{ account_number: '1930', account_name: 'Företagskonto', account_class: 1, plan_type: 'k1', is_active: true, is_system_account: true },
{ account_number: '3001', account_name: 'Försäljning', account_class: 3, plan_type: 'k1', is_active: true, is_system_account: false },
{ account_number: '5410', account_name: 'Förbrukningsinventarier', account_class: 5, plan_type: 'k1', is_active: true, is_system_account: false },
{ account_number: '19301', account_name: 'Sparkonto (import)', account_class: 1, plan_type: 'full_bas', is_active: true, is_system_account: false },
]
const usageRows = [
{ account_number: '1930', usage_count: 12 },
{ account_number: '3001', usage_count: 4 },
]
describe('GET /api/bookkeeping/accounts/usage', () => {
it('returns 401 when not authenticated', async () => {
unauthenticated()
const res = await usageGET(createMockRequest('/api/bookkeeping/accounts/usage'), routeParams)
expect(res.status).toBe(401)
})
it('returns per-account usage counts from the RPC, company-scoped', async () => {
const { supabase, calls } = createCapturingSupabase([{ data: usageRows }])
auth(supabase)
const { status, body } = await parseJsonResponse<{ data: typeof usageRows }>(
await usageGET(createMockRequest('/api/bookkeeping/accounts/usage'), routeParams),
)
expect(status).toBe(200)
expect(body.data).toEqual(usageRows)
expect(calls.filter((c) => c.method === 'rpc').map((c) => c.args)).toContainEqual([
'get_account_usage_counts',
{ p_company_id: 'company-1' },
])
})
it('returns 500 when the RPC fails', async () => {
const { supabase } = createCapturingSupabase([{ error: { message: 'boom' } }])
auth(supabase)
const res = await usageGET(createMockRequest('/api/bookkeeping/accounts/usage'), routeParams)
expect(res.status).toBe(500)
})
})
describe('POST /api/bookkeeping/accounts/prune', () => {
it('returns 401 when not authenticated', async () => {
unauthenticated()
const req = createMockRequest('/api/bookkeeping/accounts/prune', {
method: 'POST',
body: { dry_run: true },
})
const res = await prunePOST(req, routeParams)
expect(res.status).toBe(401)
})
it('returns 400 when dry_run is false and account_numbers is missing', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/prune', {
method: 'POST',
body: { dry_run: false },
})
const { status } = await parseJsonResponse(await prunePOST(req, routeParams))
expect(status).toBe(400)
})
it('dry_run returns unused non-system accounts as deletable, the rest as used', async () => {
const { supabase } = createCapturingSupabase([
{ data: chartAccounts }, // chart_of_accounts page
{ data: usageRows }, // usage RPC
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/prune', {
method: 'POST',
body: { dry_run: true },
})
const { status, body } = await parseJsonResponse<{
data: {
deletable: Array<{ account_number: string; in_bas_reference: boolean }>
used: Array<{ account_number: string; usage_count: number }>
}
}>(await prunePOST(req, routeParams))
expect(status).toBe(200)
const deletableNumbers = body.data.deletable.map((a) => a.account_number).sort()
// Unused + non-system: the seeded 5410 and the imported 19301.
expect(deletableNumbers).toEqual(['19301', '5410'])
// BAS-vs-custom marker drives the dialog's default selection.
expect(body.data.deletable.find((a) => a.account_number === '5410')?.in_bas_reference).toBe(true)
expect(body.data.deletable.find((a) => a.account_number === '19301')?.in_bas_reference).toBe(false)
// Used + system accounts land in the informational remainder.
const usedNumbers = body.data.used.map((a) => a.account_number)
expect(usedNumbers).toContain('1930')
expect(usedNumbers).toContain('3001')
expect(body.data.used.find((a) => a.account_number === '3001')?.usage_count).toBe(4)
})
it('execute deletes only re-verified unused accounts and skips the rest', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: chartAccounts },
{ data: usageRows },
{ data: null }, // delete chunk
])
auth(supabase)
// Client asks for a used account (3001), a system account (1930), an
// unknown number (9999) and two legitimately deletable ones.
const req = createMockRequest('/api/bookkeeping/accounts/prune', {
method: 'POST',
body: { dry_run: false, account_numbers: ['3001', '1930', '9999', '5410', '19301'] },
})
const { status, body } = await parseJsonResponse<{
data: { deleted: string[]; skipped: string[]; not_found: string[] }
}>(await prunePOST(req, routeParams))
expect(status).toBe(200)
expect(body.data.deleted.sort()).toEqual(['19301', '5410'])
expect(body.data.skipped.sort()).toEqual(['1930', '3001'])
expect(body.data.not_found).toEqual(['9999'])
// The DELETE is company-scoped, guards system accounts, and only carries
// the re-verified numbers.
const inCalls = calls.filter((c) => c.method === 'in').map((c) => c.args)
expect(inCalls).toContainEqual(['account_number', ['5410', '19301']])
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
expect(eqCalls).toContainEqual(['is_system_account', false])
})
it('execute with nothing deletable deletes nothing and reports the skips', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: chartAccounts },
{ data: usageRows },
])
auth(supabase)
const req = createMockRequest('/api/bookkeeping/accounts/prune', {
method: 'POST',
body: { dry_run: false, account_numbers: ['3001'] },
})
const { status, body } = await parseJsonResponse<{
data: { deleted: string[]; skipped: string[] }
}>(await prunePOST(req, routeParams))
expect(status).toBe(200)
expect(body.data.deleted).toEqual([])
expect(body.data.skipped).toEqual(['3001'])
expect(calls.filter((c) => c.method === 'delete')).toHaveLength(0)
})
it('returns 403 when the member lacks write permission', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const req = createMockRequest('/api/bookkeeping/accounts/prune', {
method: 'POST',
body: { dry_run: true },
})
const res = await prunePOST(req, routeParams)
expect(res.status).toBe(403)
})
})
@@ -0,0 +1,201 @@
/**
* Tests for GET /api/bookkeeping/accounts/reference and /bas-lookup.
*
* reference: the chart query must carry a stable unique order — a full-BAS
* chart exceeds fetchAllRows' 1000-row page size and unordered .range()
* paging can duplicate/skip rows on page boundaries.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { GET as referenceGET } from '../reference/route'
import { GET as basLookupGET } from '../bas-lookup/route'
const routeParams = { params: Promise.resolve({}) }
function createCapturingSupabase(results: { data?: unknown; error?: unknown }[]) {
const calls: { method: string; args: unknown[] }[] = []
let idx = 0
const makeBuilder = () => {
const result = results[idx++] ?? { data: null, error: null }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const b: any = {}
for (const m of ['select', 'eq', 'in', 'order', 'range', 'maybeSingle', 'single']) {
b[m] = (...args: unknown[]) => {
calls.push({ method: m, args })
return b
}
}
b.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null, count: null })
return b
}
return {
supabase: { from: () => makeBuilder() },
calls,
}
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/bookkeeping/accounts/reference', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await referenceGET(createMockRequest('/api/bookkeeping/accounts/reference'), routeParams)
expect(res.status).toBe(401)
})
it('pages the chart with a stable account_number order and returns activation status', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: [{ account_number: '1930', is_active: true, is_system_account: false }] },
])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const { status, body } = await parseJsonResponse<{
data: Array<{ account_number: string; is_active: boolean; is_system_account: boolean }>
}>(await referenceGET(createMockRequest('/api/bookkeeping/accounts/reference'), routeParams))
expect(status).toBe(200)
// The route returns only the company's activation rows; the BAS catalog is
// merged client-side against the bundled reference data.
const row = body.data.find((a) => a.account_number === '1930')
expect(row?.is_active).toBe(true)
expect(row?.is_system_account).toBe(false)
// Paging-stability regression guard.
expect(calls.filter((c) => c.method === 'order').map((c) => c.args[0])).toContain(
'account_number'
)
})
})
/**
* bas-lookup answers "can this number be activated at all?", which is what
* gates ActivateAccountsDialog's confirm button. It consults the company's own
* chart first, so a custom (non-BAS) account the company deactivated still
* comes back known — before that it read as unknown and the button stayed dead.
*/
describe('GET /api/bookkeeping/accounts/bas-lookup', () => {
function authWith(chartRows: unknown[]) {
const { supabase, calls } = createCapturingSupabase([{ data: chartRows }])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
return calls
}
beforeEach(() => {
authWith([])
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await basLookupGET(
createMockRequest('/api/bookkeeping/accounts/bas-lookup'),
routeParams
)
expect(res.status).toBe(401)
})
it('resolves known BAS numbers and flags unknown ones', async () => {
const req = createMockRequest('/api/bookkeeping/accounts/bas-lookup', {
searchParams: { numbers: '1930,0000' },
})
const { status, body } = await parseJsonResponse<{
data: Array<{ account_number: string; known: boolean; in_chart: boolean }>
}>(await basLookupGET(req, routeParams))
expect(status).toBe(200)
const bas = body.data.find((a) => a.account_number === '1930')
expect(bas?.known).toBe(true)
// Known from the static catalog, not held by the company: activating it
// inserts a new row rather than reviving one.
expect(bas?.in_chart).toBe(false)
expect(body.data.find((a) => a.account_number === '0000')?.known).toBe(false)
})
it('reports a deactivated custom account as known and in the chart', async () => {
const calls = authWith([
{
account_number: '3910',
account_name: 'Hyresintäkter egen',
account_class: 3,
account_type: 'revenue',
is_active: false,
},
])
const req = createMockRequest('/api/bookkeeping/accounts/bas-lookup', {
searchParams: { numbers: '3910' },
})
const { status, body } = await parseJsonResponse<{
data: Array<{
account_number: string
account_name: string | null
known: boolean
in_chart: boolean
is_active: boolean
}>
}>(await basLookupGET(req, routeParams))
expect(status).toBe(200)
// 3910 is not in the BAS catalog: without the chart read this was known:false.
const row = body.data[0]
expect(row.known).toBe(true)
expect(row.in_chart).toBe(true)
expect(row.is_active).toBe(false)
expect(row.account_name).toBe('Hyresintäkter egen')
// Defense in depth alongside RLS: another company's chart must not answer.
expect(calls.filter((c) => c.method === 'eq').map((c) => c.args)).toContainEqual([
'company_id',
'company-1',
])
})
it("prefers the company's own account name over the BAS catalog name", async () => {
authWith([
{
account_number: '1930',
account_name: 'Företagskonto SEB',
account_class: 1,
account_type: 'asset',
is_active: true,
},
])
const req = createMockRequest('/api/bookkeeping/accounts/bas-lookup', {
searchParams: { numbers: '1930' },
})
const { body } = await parseJsonResponse<{
data: Array<{ account_name: string | null; in_chart: boolean }>
}>(await basLookupGET(req, routeParams))
expect(body.data[0].account_name).toBe('Företagskonto SEB')
expect(body.data[0].in_chart).toBe(true)
})
it('rejects an oversized numbers list with 400', async () => {
const many = Array.from({ length: 2001 }, (_, i) => String(10000 + i)).join(',')
const req = createMockRequest('/api/bookkeeping/accounts/bas-lookup', {
searchParams: { numbers: many },
})
const { status } = await parseJsonResponse(await basLookupGET(req, routeParams))
expect(status).toBe(400)
})
})
@@ -0,0 +1,130 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* POST /api/bookkeeping/accounts/activate
*
* Batch-activate BAS accounts for a user. Accepts { account_numbers: string[] }.
* - Inserts rows from BAS reference for accounts not yet in the chart.
* - Reactivates (is_active=true) accounts that already exist but are inactive.
* - Skips anything already active.
* - Returns { activated, reactivated, skipped, unknown } so callers can react.
*
* Strings that aren't known BAS numbers are reported in `unknown` (not
* rejected) so activate-and-retry flows can surface them; the schema only
* bounds type and size.
*/
const ActivateSchema = z.object({
account_numbers: z.array(z.string().min(1).max(10)).min(1).max(2000),
})
export const POST = withRouteContext(
'bookkeeping.accounts.activate',
async (request, ctx) => {
const { supabase, companyId, user } = ctx
const raw = await request.json().catch(() => null)
const parsed = ActivateSchema.safeParse(raw)
if (!parsed.success) {
return NextResponse.json({ error: 'account_numbers array required' }, { status: 400 })
}
const uniqueNumbers = [...new Set(parsed.data.account_numbers)]
// Fetch existing rows with current is_active state
const { data: existing, error: fetchError } = await supabase
.from('chart_of_accounts')
.select('account_number, is_active')
.eq('company_id', companyId)
.in('account_number', uniqueNumbers)
if (fetchError) {
return NextResponse.json({ error: getUserErrorMessage(fetchError) }, { status: 500 })
}
const existingByNumber = new Map<string, boolean>(
(existing || []).map((a) => [a.account_number, a.is_active])
)
const toReactivate: string[] = []
const toInsert: Array<NonNullable<ReturnType<typeof buildInsertRow>>> = []
const unknown: string[] = []
let skipped = 0
for (const num of uniqueNumbers) {
if (existingByNumber.has(num)) {
if (existingByNumber.get(num) === true) {
skipped += 1
} else {
toReactivate.push(num)
}
continue
}
const row = buildInsertRow(num, user.id, companyId)
if (row) {
toInsert.push(row)
} else {
unknown.push(num)
}
}
let reactivatedRows: { account_number: string }[] = []
if (toReactivate.length > 0) {
const { data, error } = await supabase
.from('chart_of_accounts')
.update({ is_active: true })
.eq('company_id', companyId)
.in('account_number', toReactivate)
.select('account_number')
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
reactivatedRows = data || []
}
let insertedRows: { account_number: string }[] = []
if (toInsert.length > 0) {
const { data, error } = await supabase
.from('chart_of_accounts')
.insert(toInsert)
.select('account_number')
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
insertedRows = data || []
}
return NextResponse.json({
data: [...insertedRows, ...reactivatedRows],
activated: insertedRows.length,
reactivated: reactivatedRows.length,
skipped,
unknown,
})
},
{ requireWrite: true },
)
function buildInsertRow(accountNumber: string, userId: string, companyId: string) {
const ref = getBASReference(accountNumber)
if (!ref) return null
return {
user_id: userId,
company_id: companyId,
account_number: ref.account_number,
account_name: ref.account_name,
account_class: ref.account_class,
account_group: ref.account_group,
account_type: ref.account_type,
normal_balance: ref.normal_balance,
plan_type: 'full_bas' as const,
is_active: true,
is_system_account: false,
description: ref.description,
sru_code: ref.sru_code,
sort_order: parseInt(ref.account_number),
}
}
@@ -0,0 +1,63 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const mockAuth = vi.fn()
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn().mockResolvedValue({
from: vi.fn(),
auth: { getUser: () => mockAuth() },
}),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { GET } from '../route'
function mkReq() {
return new Request('http://localhost/api/bookkeeping/accounts/bas-catalog')
}
function mkParams() {
return { params: Promise.resolve({}) }
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/bookkeeping/accounts/bas-catalog', () => {
it('returns 401 when not authenticated', async () => {
mockAuth.mockResolvedValue({ data: { user: null } })
const res = await GET(mkReq(), mkParams())
expect(res.status).toBe(401)
})
it('returns the full BAS catalogue with the projected fields', async () => {
mockAuth.mockResolvedValue({ data: { user: { id: 'user-1' } } })
const res = await GET(mkReq(), mkParams())
const body = await res.json()
expect(res.status).toBe(200)
expect(Array.isArray(body.data)).toBe(true)
// The real BAS 2026 chart is ~1,276 accounts.
expect(body.data.length).toBeGreaterThan(1000)
const it = body.data.find((a: { account_number: string }) => a.account_number === '6540')
expect(it).toMatchObject({
account_number: '6540',
account_name: 'IT-tjänster',
account_class: 6,
account_group: '65',
})
expect(typeof it.description).toBe('string')
})
it('sets a client cache header (static reference data)', async () => {
mockAuth.mockResolvedValue({ data: { user: { id: 'user-1' } } })
const res = await GET(mkReq(), mkParams())
expect(res.headers.get('Cache-Control')).toContain('max-age=')
})
})
@@ -0,0 +1,31 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { BAS_REFERENCE } from '@/lib/bookkeeping/bas-reference'
/**
* GET /api/bookkeeping/accounts/bas-catalog
*
* The full BAS 2026 catalogue (~1,276 accounts), projected to the fields the
* AccountCombobox needs to search and render. This lets the manual bookkeeping
* flow surface accounts by name even when they aren't in the company's chart
* yet: selecting one routes through the existing activate-on-commit rail
* (ACCOUNTS_NOT_IN_CHART → ActivateAccountsDialog → /accounts/activate).
*
* The payload is static reference data for the deploy and identical for every
* company, so it's cached hard on the client. Wrapped in withRouteContext so it
* stays behind auth (MFA on hosted) like every other bookkeeping route.
*/
export const GET = withRouteContext('bookkeeping.accounts.bas_catalog', async () => {
const data = BAS_REFERENCE.map((a) => ({
account_number: a.account_number,
account_name: a.account_name,
account_class: a.account_class,
account_group: a.account_group,
description: a.description,
}))
return NextResponse.json(
{ data },
{ headers: { 'Cache-Control': 'private, max-age=86400' } },
)
})
@@ -0,0 +1,104 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
interface ChartRow {
account_number: string
account_name: string
account_class: number | null
account_type: string | null
is_active: boolean | null
}
/**
* GET /api/bookkeeping/accounts/bas-lookup?numbers=5010,2641
*
* Resolves account numbers to a human-readable label plus whether they can be
* activated at all. Used by ActivateAccountsDialog to render the list before
* the user confirms.
*
* Two sources, company first:
* 1. The company's own chart_of_accounts. A row here is activatable even if
* it isn't a standard BAS account (custom accounts) and even if it is
* currently deactivated: POST /accounts/activate reactivates it. The
* company's own account_name wins, since it may have been renamed.
* 2. The static BAS reference, for accounts not yet added to the chart.
*
* Numbers in neither source are returned with account_name=null and
* known=false so the UI can flag them as non-BAS and offer "create".
*
* `in_chart` / `is_active` let callers tell "will be added" from "will be
* reactivated". Consulting the company chart is why this route resolves a
* company context (it was a pure in-memory reference lookup before).
*/
export const GET = withRouteContext('bookkeeping.accounts.bas-lookup', async (request, ctx) => {
const { supabase, companyId } = ctx
const { searchParams } = new URL(request.url)
const raw = searchParams.get('numbers') || ''
const numbers = [...new Set(raw.split(',').map((s) => s.trim()).filter(Boolean))]
if (numbers.length === 0) {
return NextResponse.json({ data: [] })
}
// The BAS catalogue is ~1,276 accounts — anything past that is abuse.
if (numbers.length > 2000) {
return NextResponse.json({ error: 'Too many account numbers' }, { status: 400 })
}
// Paginated: `numbers` can hold up to 2000 entries and PostgREST silently
// caps an unranged select at 1000 rows. A truncated chart read would report
// accounts that ARE in the chart as known:false / in_chart:false, so the
// dialog would offer "create" for an account that already exists.
let chartRows: ChartRow[]
try {
chartRows = await fetchAllRows<ChartRow>(
({ from, to }) =>
supabase
.from('chart_of_accounts')
.select('account_number, account_name, account_class, account_type, is_active')
.eq('company_id', companyId)
.in('account_number', numbers)
// Paging is only stable under a unique total order.
.order('account_number', { ascending: true })
.range(from, to),
{ dedupeBy: (row) => row.account_number },
)
} catch (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
const inChart = new Map(chartRows.map((row) => [row.account_number, row]))
const data = numbers.map((num) => {
const own = inChart.get(num)
if (own) {
return {
account_number: own.account_number,
account_name: own.account_name,
account_class: own.account_class,
account_type: own.account_type,
known: true,
in_chart: true,
is_active: own.is_active,
}
}
const ref = getBASReference(num)
if (!ref) {
return { account_number: num, account_name: null, known: false, in_chart: false, is_active: false }
}
return {
account_number: ref.account_number,
account_name: ref.account_name,
account_class: ref.account_class,
account_type: ref.account_type,
known: true,
in_chart: false,
is_active: false,
}
})
return NextResponse.json({ data })
})
@@ -0,0 +1,127 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* POST /api/bookkeeping/accounts/deactivate
*
* Batch-deactivate accounts in the company's chart. Accepts
* { account_numbers: string[], include_used?: boolean }. The mirror of
* /activate, built for the post-migration sweep (#2186): a chart imported from
* a previous system carries hundreds of accounts that were never posted to,
* and a short chart is what keeps manual bookings from landing on the wrong
* one.
*
* - System accounts are never deactivated here (skipped_system).
* - Accounts with postings are skipped unless include_used is true
* (skipped_used): deactivating a used account is legal and reversible, but
* it hides balances from the kontoplan, so the bulk path defaults to the
* never-used set and leaves used accounts to the per-row toggle with its
* confirm. Usage comes from get_account_usage_counts, the same company-
* scoped RPC the DELETE guard and the prune dialog read.
* - Already-inactive numbers are counted in skipped_inactive; numbers not in
* the chart at all are reported in `unknown` rather than rejected.
*/
const DeactivateSchema = z.object({
account_numbers: z.array(z.string().min(1).max(10)).min(1).max(2000),
include_used: z.boolean().optional().default(false),
})
interface ChartRow {
account_number: string
is_active: boolean
is_system_account: boolean
}
export const POST = withRouteContext(
'bookkeeping.accounts.deactivate',
async (request, ctx) => {
const { supabase, companyId } = ctx
const raw = await request.json().catch(() => null)
const parsed = DeactivateSchema.safeParse(raw)
if (!parsed.success) {
return NextResponse.json({ error: 'account_numbers array required' }, { status: 400 })
}
const uniqueNumbers = [...new Set(parsed.data.account_numbers)]
const includeUsed = parsed.data.include_used
const { data: existing, error: fetchError } = await supabase
.from('chart_of_accounts')
.select('account_number, is_active, is_system_account')
.eq('company_id', companyId)
.in('account_number', uniqueNumbers)
if (fetchError) {
return NextResponse.json({ error: getUserErrorMessage(fetchError) }, { status: 500 })
}
const { data: usage, error: usageError } = await supabase.rpc('get_account_usage_counts', {
p_company_id: companyId,
})
if (usageError) {
return NextResponse.json({ error: getUserErrorMessage(usageError) }, { status: 500 })
}
// Accounts never posted to are simply absent from the RPC result.
const usedNumbers = new Set<string>(
((usage ?? []) as { account_number: string }[]).map((u) => u.account_number),
)
const byNumber = new Map<string, ChartRow>(
((existing || []) as ChartRow[]).map((a) => [a.account_number, a]),
)
const toDeactivate: string[] = []
const skippedSystem: string[] = []
const skippedUsed: string[] = []
const unknown: string[] = []
let skippedInactive = 0
for (const num of uniqueNumbers) {
const row = byNumber.get(num)
if (!row) {
unknown.push(num)
continue
}
if (!row.is_active) {
skippedInactive += 1
continue
}
if (row.is_system_account) {
skippedSystem.push(num)
continue
}
if (usedNumbers.has(num) && !includeUsed) {
skippedUsed.push(num)
continue
}
toDeactivate.push(num)
}
let deactivatedRows: { account_number: string }[] = []
if (toDeactivate.length > 0) {
const { data, error } = await supabase
.from('chart_of_accounts')
.update({ is_active: false })
.eq('company_id', companyId)
.in('account_number', toDeactivate)
.select('account_number')
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
deactivatedRows = data || []
}
return NextResponse.json({
data: deactivatedRows,
deactivated: deactivatedRows.length,
skipped_system: skippedSystem,
skipped_used: skippedUsed,
skipped_inactive: skippedInactive,
unknown,
})
},
{ requireWrite: true },
)
+163
View File
@@ -0,0 +1,163 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { PruneAccountsSchema } from '@/lib/api/schemas'
import { isStandardBASAccount } from '@/lib/bookkeeping/bas-reference'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
// POST /api/bookkeeping/accounts/prune — bulk cleanup of unused accounts
// ("Rensa oanvända konton"), for charts bloated by an import from an old
// system.
//
// Two phases:
// { dry_run: true }
// → returns the deletable set (non-system accounts with zero journal
// usage) plus the used remainder, without changing anything.
// { dry_run: false, account_numbers: [...] }
// → deletes the requested accounts, re-verifying every guard server-side.
// The client list is a selection from the preview, not an authority:
// anything failing re-check at execute time is skipped and reported,
// never deleted and never an error.
//
// A used account can never be deleted through this path — its verifikat are
// immutable under BFL and their lines must keep resolving to an account.
// Deactivation (PUT is_active=false on the single-account route) remains the
// only way to hide those. Draft usage also blocks deletion: a draft line
// still references the account. Opening balances need no separate check —
// IB is booked as a verifikat (source_type 'opening_balance'), so the journal
// usage count covers it. (The account_balances cache table was dropped in
// migration 20240101000027.)
//
// Like the sibling single-account DELETE, there is a small window between
// the usage re-check and the delete where a concurrent posting could slip
// in; journal_entry_lines reference accounts by number (account_id is ON
// DELETE SET NULL), so the entry itself is never damaged — the account row
// would just need re-adding from the BAS catalog.
//
// Response shapes are legacy `{ data }` / `{ error: string }` — consumed by
// the kontoplan UI alongside the sibling account routes.
interface ChartAccountRow {
account_number: string
account_name: string
account_class: number
plan_type: string | null
is_active: boolean
is_system_account: boolean
}
const DELETE_CHUNK_SIZE = 200
export const POST = withRouteContext(
'bookkeeping.accounts.prune',
async (request, ctx) => {
const { supabase, companyId, log } = ctx
const validation = await validateBody(request, PruneAccountsSchema, {
log,
operation: 'bookkeeping.accounts.prune',
})
if (!validation.success) return validation.response
const { dry_run, account_numbers } = validation.data
try {
// A full imported chart can exceed PostgREST's 1000-row page — paginate.
const accounts = (await fetchAllRows(({ from, to }) =>
supabase
.from('chart_of_accounts')
.select(
'account_number, account_name, account_class, plan_type, is_active, is_system_account',
)
.eq('company_id', companyId)
.order('account_number')
.range(from, to),
)) as ChartAccountRow[]
const { data: usage, error: usageError } = await supabase.rpc(
'get_account_usage_counts',
{ p_company_id: companyId },
)
if (usageError) {
return NextResponse.json({ error: getUserErrorMessage(usageError) }, { status: 500 })
}
const usageByAccount = new Map<string, number>(
(usage ?? []).map((u: { account_number: string; usage_count: number }) => [
u.account_number,
Number(u.usage_count),
]),
)
const isDeletable = (a: ChartAccountRow) =>
!a.is_system_account && !usageByAccount.has(a.account_number)
if (dry_run) {
const deletable = accounts.filter(isDeletable).map((a) => ({
account_number: a.account_number,
account_name: a.account_name,
account_class: a.account_class,
plan_type: a.plan_type,
is_active: a.is_active,
in_bas_reference: isStandardBASAccount(a.account_number),
}))
const used = accounts
.filter((a) => !isDeletable(a))
.map((a) => ({
account_number: a.account_number,
account_name: a.account_name,
is_system_account: a.is_system_account,
usage_count: usageByAccount.get(a.account_number) ?? 0,
}))
return NextResponse.json({ data: { deletable, used } })
}
// Execute: intersect the requested selection with the freshly computed
// deletable set — guards are re-verified here, not trusted from the
// preview the client saw.
const requested = [...new Set(account_numbers ?? [])]
const deletableSet = new Set(accounts.filter(isDeletable).map((a) => a.account_number))
const existingSet = new Set(accounts.map((a) => a.account_number))
const toDelete = requested.filter((n) => deletableSet.has(n))
const skipped = requested.filter((n) => existingSet.has(n) && !deletableSet.has(n))
const notFound = requested.filter((n) => !existingSet.has(n))
for (let i = 0; i < toDelete.length; i += DELETE_CHUNK_SIZE) {
const chunk = toDelete.slice(i, i + DELETE_CHUNK_SIZE)
const { error: deleteError } = await supabase
.from('chart_of_accounts')
.delete()
.eq('company_id', companyId)
.eq('is_system_account', false)
.in('account_number', chunk)
if (deleteError) {
// Report what was already deleted so the UI can refresh honestly.
return NextResponse.json(
{
error: getUserErrorMessage(deleteError),
data: { deleted: toDelete.slice(0, i), skipped, not_found: notFound },
},
{ status: 500 },
)
}
}
log.info('unused accounts pruned', {
deleted: toDelete.length,
skipped: skipped.length,
notFound: notFound.length,
})
return NextResponse.json({
data: { deleted: toDelete, skipped, not_found: notFound },
})
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? getUserErrorMessage(error) : 'Failed to prune accounts' },
{ status: 500 },
)
}
},
{ requireWrite: true },
)
@@ -0,0 +1,39 @@
import { NextResponse } from 'next/server'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* GET /api/bookkeeping/accounts/reference
*
* Returns the company's chart-of-accounts activation status: one lightweight
* row per account it holds (active or not), shaped
* `{ account_number, is_active, is_system_account }`.
*
* The BAS catalog itself is static and already bundled into the client
* (lib/bookkeeping/bas-reference); the kontoplan UI merges this activation
* list against that bundled catalog to render the "BAS-katalog" tab. We
* deliberately do NOT re-send the full ~1,300-account catalog over the wire on
* every page load; the browser already has that payload.
*/
export const GET = withRouteContext('bookkeeping.accounts.reference', async (_request, ctx) => {
const { supabase, companyId } = ctx
// Paginated with a stable unique order: a full-BAS chart exceeds the
// 1000-row page size, and unordered .range() paging can duplicate or skip
// rows on page boundaries (see fetch-all.ts ordering invariant).
try {
const userAccounts = await fetchAllRows<{ account_number: string; is_active: boolean; is_system_account: boolean }>(({ from, to }) =>
supabase
.from('chart_of_accounts')
.select('account_number, is_active, is_system_account')
.eq('company_id', companyId)
.order('account_number', { ascending: true })
.range(from, to)
)
return NextResponse.json({ data: userAccounts })
} catch (error) {
return NextResponse.json({ error: error instanceof Error ? getUserErrorMessage(error) : 'Failed to fetch accounts' }, { status: 500 })
}
})
+165
View File
@@ -0,0 +1,165 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody, validateQuery } from '@/lib/api/validate'
import { CreateAccountSchema } from '@/lib/api/schemas'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import {
defaultRateForVatTreatment,
isVatTreatmentAllowedForAccountClass,
} from '@/lib/vat/account-vat-treatment'
// Response shapes are legacy `{ data }` / `{ error: string }` — several pages
// (import, supplier-invoices, article form) consume the list directly.
const ListQuerySchema = z.object({
class: z.coerce.number().int().min(1).max(8).optional(),
active: z.enum(['true', 'false']).optional(),
})
export const GET = withRouteContext('bookkeeping.accounts.list', async (request, ctx) => {
const { supabase, companyId, log } = ctx
const validated = validateQuery(request, ListQuerySchema, {
log,
operation: 'bookkeeping.accounts.list',
})
if (!validated.success) return validated.response
const accountClass = validated.data.class
const activeOnly = validated.data.active !== 'false'
try {
// Single-round-trip path: the RPC aggregates the whole list into one json
// scalar server-side, bypassing PostgREST's 1000-row page cap. Large
// charts (95/1250 prod companies exceed 1000 active accounts) previously
// paid 2-5 sequential cross-region round trips through fetchAllRows.
const rpc = await supabase.rpc('list_company_accounts', {
p_company_id: companyId,
p_active_only: activeOnly,
p_account_class: accountClass ?? null,
})
if (!rpc.error) return NextResponse.json({ data: rpc.data ?? [] })
if (rpc.error.code === 'PGRST202' || rpc.error.code === '42883' || rpc.error.code === '42501') {
// Function not deployed yet (self-hosted instance not migrated, or the
// deploy-ordering window before the branching merge applies the
// migration) or EXECUTE not granted: fall back to the paged fetch.
// Mirrors the load-bearing fallback in lib/company/context.ts.
log.warn('list_company_accounts RPC unavailable, falling back to paged fetch', {
code: rpc.error.code,
})
} else {
throw new Error(rpc.error.message)
}
const data = await fetchAllRows(({ from, to }) => {
let query = supabase
.from('chart_of_accounts')
.select('*')
.eq('company_id', companyId)
.order('sort_order')
if (activeOnly) {
query = query.eq('is_active', true)
}
if (accountClass !== undefined) {
query = query.eq('account_class', accountClass)
}
return query.range(from, to)
})
return NextResponse.json({ data })
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? getUserErrorMessage(error) : 'Failed to fetch accounts' },
{ status: 500 },
)
}
})
export const POST = withRouteContext(
'bookkeeping.accounts.create',
async (request, ctx) => {
const { supabase, companyId, user, log } = ctx
const validation = await validateBody(request, CreateAccountSchema, {
log,
operation: 'bookkeeping.accounts.create',
})
if (!validation.success) return validation.response
const body = validation.data
const accountClass = parseInt(body.account_number[0])
if (
body.default_vat_treatment &&
!isVatTreatmentAllowedForAccountClass(body.default_vat_treatment, accountClass)
) {
return NextResponse.json(
{ error: 'Momskoden kan inte användas för den här kontoklassen.' },
{ status: 400 },
)
}
const defaultVatRate = body.default_vat_treatment && body.default_vat_rate == null
? defaultRateForVatTreatment(body.default_vat_treatment, accountClass)
: body.default_vat_rate ?? null
const { data, error } = await supabase
.from('chart_of_accounts')
.insert({
user_id: user.id,
company_id: companyId,
account_number: body.account_number,
account_name: body.account_name,
account_class: accountClass,
account_group: body.account_number.substring(0, 2),
account_type: body.account_type,
normal_balance: body.normal_balance,
plan_type: body.plan_type || 'k1',
is_system_account: false,
description: body.description || null,
default_vat_code: body.default_vat_code || null,
default_vat_rate: defaultVatRate,
default_vat_treatment: body.default_vat_treatment ?? null,
sru_code: body.sru_code || null,
sort_order: parseInt(body.account_number),
})
.select()
.single()
if (error) {
if (error.code === '23505') {
// The unique constraint counts deactivated rows, so "already exists"
// covers two very different situations. Only look up which one it is
// on the failing path: the happy path stays a single insert.
const { data: existing } = await supabase
.from('chart_of_accounts')
.select('is_active')
.eq('company_id', companyId)
.eq('account_number', body.account_number)
.maybeSingle()
if (existing && existing.is_active === false) {
// Re-creating can never succeed here; the caller must reactivate
// instead. The distinct code is what AddAccountDialog keys on to
// offer that as a one-click action rather than a dead end.
return errorResponseFromCode('ACCOUNT_EXISTS_INACTIVE', log, {
status: 409,
messageSv: `Kontonummer ${body.account_number} finns redan i din kontoplan men är inaktiverat.`,
details: { account_number: body.account_number },
})
}
return NextResponse.json(
{ error: `Kontonummer ${body.account_number} finns redan i din kontoplan.` },
{ status: 409 },
)
}
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)
@@ -0,0 +1,25 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
// GET /api/bookkeeping/accounts/usage — per-account posting counts for the
// active company, from the get_account_usage_counts RPC. Accounts that have
// never been posted to are absent from the result; that absence is the
// "unused" signal the kontoplan UI and the prune flow key on.
//
// Response shapes are legacy `{ data }` / `{ error: string }` — consumed by
// the kontoplan UI alongside the sibling account routes.
export const GET = withRouteContext('bookkeeping.accounts.usage', async (_request, ctx) => {
const { supabase, companyId } = ctx
const { data, error } = await supabase.rpc('get_account_usage_counts', {
p_company_id: companyId,
})
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data: data ?? [] })
})
@@ -0,0 +1,125 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
import {
AccrualNothingToDissolveError,
AccrualScheduleNotActiveError,
AccrualScheduleNotFoundError,
} from '@/lib/bookkeeping/accruals/errors'
const { supabase: mockSupabase, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
const mockDissolveScheduleNow = vi.fn()
vi.mock('@/lib/bookkeeping/accruals/service', () => ({
dissolveScheduleNow: (...args: unknown[]) => mockDissolveScheduleNow(...args),
}))
import { POST } from '../route'
describe('POST /api/bookkeeping/accruals/[id]/dissolve', () => {
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
function dissolveRequest() {
return POST(
createMockRequest('/api/bookkeeping/accruals/sched-1/dissolve', { method: 'POST' }),
createMockRouteParams({ id: 'sched-1' }),
)
}
it('returns the dissolution result on success', async () => {
mockDissolveScheduleNow.mockResolvedValue({ journalEntryId: 'je-1', amount: 2000 })
const { status, body } = await parseJsonResponse<{
data: { journalEntryId: string; amount: number }
}>(await dissolveRequest())
expect(status).toBe(200)
expect(body.data).toEqual({ journalEntryId: 'je-1', amount: 2000 })
})
it('maps the typed not-found error to 404 ACCRUAL_NOT_FOUND', async () => {
mockDissolveScheduleNow.mockRejectedValue(new AccrualScheduleNotFoundError())
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await dissolveRequest(),
)
expect(status).toBe(404)
expect(body.error.code).toBe('ACCRUAL_NOT_FOUND')
})
it('maps the typed not-active error to 400 ACCRUAL_NOT_ACTIVE', async () => {
mockDissolveScheduleNow.mockRejectedValue(new AccrualScheduleNotActiveError('cancelled'))
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { currentStatus: string } }
}>(await dissolveRequest())
expect(status).toBe(400)
expect(body.error.code).toBe('ACCRUAL_NOT_ACTIVE')
expect(body.error.details.currentStatus).toBe('cancelled')
})
it('maps the typed nothing-to-dissolve error to 400 ACCRUAL_NOTHING_TO_DISSOLVE', async () => {
mockDissolveScheduleNow.mockRejectedValue(new AccrualNothingToDissolveError())
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await dissolveRequest(),
)
expect(status).toBe(400)
expect(body.error.code).toBe('ACCRUAL_NOTHING_TO_DISSOLVE')
})
it('falls back to ACCRUAL_DISSOLVE_FAILED for untyped errors, carrying a Swedish reason as-is', async () => {
mockDissolveScheduleNow.mockRejectedValue(new Error('Ingen öppen räkenskapsperiod för 2026-01-01'))
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { reason: string } }
}>(await dissolveRequest())
expect(status).toBe(400)
expect(body.error.code).toBe('ACCRUAL_DISSOLVE_FAILED')
// The engine's own Swedish sentence reaches the user (issue #2086); it
// used to be dropped for lacking a getErrorMessage keyword.
expect(body.error.details.reason).toBe('Ingen öppen räkenskapsperiod för 2026-01-01')
})
it('falls back to ACCRUAL_DISSOLVE_FAILED with the generic reason for untyped technical errors', async () => {
mockDissolveScheduleNow.mockRejectedValue(new Error('boom'))
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { reason: string } }
}>(await dissolveRequest())
expect(status).toBe(400)
expect(body.error.code).toBe('ACCRUAL_DISSOLVE_FAILED')
expect(body.error.details.reason).toBe('Något gick fel. Försök igen.')
})
})
@@ -0,0 +1,65 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { dissolveScheduleNow } from '@/lib/bookkeeping/accruals/service'
import {
ACCRUAL_NOTHING_TO_DISSOLVE,
ACCRUAL_SCHEDULE_NOT_ACTIVE,
ACCRUAL_SCHEDULE_NOT_FOUND,
isAccrualError,
} from '@/lib/bookkeeping/accruals/errors'
ensureInitialized()
/**
* POST /api/bookkeeping/accruals/[id]/dissolve
*
* "Lös upp nu": books the schedule's remaining months in ONE verifikat dated
* today (clamped by lock date) and completes the schedule. Used when the
* underlying service ends early or the user wants the rest expensed now.
* Cancelling-with-storno only happens via the credit flows: a standalone
* cancel would strand the interim-account balance.
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'accruals.dissolve',
async (_request, ctx, { params }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
try {
const result = await dissolveScheduleNow(supabase, companyId!, user.id, id)
// Manual financial write: log the acting user for auditability.
log.info('accrual schedule dissolved', {
userId: user.id,
companyId,
scheduleId: id,
amount: result.amount,
journalEntryId: result.journalEntryId,
})
return NextResponse.json({ data: result })
} catch (err) {
// Typed domain errors carry a stable code: never match Swedish prose.
if (isAccrualError(err)) {
switch (err.code) {
case ACCRUAL_SCHEDULE_NOT_FOUND:
return errorResponseFromCode('ACCRUAL_NOT_FOUND', log, { requestId })
case ACCRUAL_SCHEDULE_NOT_ACTIVE:
return errorResponseFromCode('ACCRUAL_NOT_ACTIVE', log, {
requestId,
details: { currentStatus: err.currentStatus },
})
case ACCRUAL_NOTHING_TO_DISSOLVE:
return errorResponseFromCode('ACCRUAL_NOTHING_TO_DISSOLVE', log, { requestId })
}
}
log.error('accrual dissolve failed', err as Error, { entityId: id })
return errorResponseFromCode('ACCRUAL_DISSOLVE_FAILED', log, {
requestId,
details: { reason: getErrorMessage(err) },
})
}
},
{ requireWrite: true },
)
@@ -0,0 +1,66 @@
/**
* Tests for GET /api/bookkeeping/accruals — status filter validation and the
* due_count derivation.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET } from '../route'
const routeParams = { params: Promise.resolve({}) }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
})
describe('GET /api/bookkeeping/accruals', () => {
it('returns 400 for an unknown status filter', async () => {
const req = createMockRequest('/api/bookkeeping/accruals', {
searchParams: { status: 'garbage' },
})
const { status } = await parseJsonResponse(await GET(req, routeParams))
expect(status).toBe(400)
})
it('lists schedules and counts due pending installments', async () => {
enqueue({
data: [
{
id: 'sched-1',
status: 'active',
created_at: '2026-01-01T00:00:00Z',
installments: [
{ id: 'i1', period_month: '2020-01-01', status: 'pending' },
{ id: 'i2', period_month: '2099-01-01', status: 'pending' },
{ id: 'i3', period_month: '2020-02-01', status: 'posted' },
],
},
],
})
const { status, body } = await parseJsonResponse<{ data: unknown[]; due_count: number }>(
await GET(createMockRequest('/api/bookkeeping/accruals'), routeParams)
)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
// Only the past-month pending installment counts as due.
expect(body.due_count).toBe(1)
})
})
@@ -0,0 +1,155 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: vi.fn(() => null),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
let installmentsResult: {
data: Array<{ company_id: string }> | null
error: { message: string } | null
} = { data: [], error: null }
// The route loads company ids through fetchAllRows, which appends
// .range(from, to) per page: the mock slices the fixture so pagination
// (>1000 rows) is exercised for real.
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: vi.fn(() => ({
from: vi.fn(() => {
const chain: Record<string, unknown> = {}
let from = 0
let to = Number.MAX_SAFE_INTEGER
chain.select = vi.fn(() => chain)
chain.eq = vi.fn(() => chain)
chain.lte = vi.fn(() => chain)
chain.order = vi.fn(() => chain)
chain.range = vi.fn((f: number, t: number) => {
from = f
to = t
return chain
})
chain.then = (resolve: (v: unknown) => unknown) => {
const result = installmentsResult.error
? { data: null, error: installmentsResult.error }
: { data: (installmentsResult.data ?? []).slice(from, to + 1), error: null }
return Promise.resolve(result).then(resolve)
}
return chain
}),
})),
}))
const mockPostDueInstallments = vi.fn()
vi.mock('@/lib/bookkeeping/accruals/service', () => ({
postDueInstallments: (...args: unknown[]) => mockPostDueInstallments(...args),
}))
import { GET } from '../route'
function cronRequest(): Request {
return new Request('http://localhost:3000/api/bookkeeping/accruals/post-due/cron')
}
beforeEach(() => {
vi.clearAllMocks()
installmentsResult = { data: [], error: null }
})
describe('GET /api/bookkeeping/accruals/post-due/cron', () => {
it('runs once per distinct company and aggregates results', async () => {
installmentsResult = {
data: [
{ company_id: 'company-1' },
{ company_id: 'company-1' },
{ company_id: 'company-2' },
],
error: null,
}
mockPostDueInstallments
.mockResolvedValueOnce({ posted: 2, failed: 0, skipped: 0, errors: [] })
.mockResolvedValueOnce({ posted: 1, failed: 0, skipped: 0, errors: [] })
const response = await GET(cronRequest())
const json = await response.json()
expect(mockPostDueInstallments).toHaveBeenCalledTimes(2)
expect(mockPostDueInstallments.mock.calls.map((c) => c[1])).toEqual([
'company-1',
'company-2',
])
expect(json.success).toBe(true)
expect(json.total).toBe(2)
expect(json.succeeded).toBe(2)
expect(json.results).toEqual([
{ companyId: 'company-1', posted: 2, failed: 0, skipped: 0 },
{ companyId: 'company-2', posted: 1, failed: 0, skipped: 0 },
])
})
it('paginates past the 1000-row PostgREST cap so no company is starved', async () => {
// 1000 rows for company-1 fill the first page exactly; company-2's single
// row only exists on page 2 and would be dropped by an unpaginated select.
installmentsResult = {
data: [
...Array.from({ length: 1000 }, () => ({ company_id: 'company-1' })),
{ company_id: 'company-2' },
],
error: null,
}
mockPostDueInstallments.mockResolvedValue({ posted: 1, failed: 0, skipped: 0, errors: [] })
const response = await GET(cronRequest())
const json = await response.json()
expect(json.success).toBe(true)
expect(mockPostDueInstallments).toHaveBeenCalledTimes(2)
expect(mockPostDueInstallments.mock.calls.map((c) => c[1])).toEqual([
'company-1',
'company-2',
])
})
it('isolates a failing company so the rest still run', async () => {
installmentsResult = {
data: [{ company_id: 'company-1' }, { company_id: 'company-2' }],
error: null,
}
mockPostDueInstallments
.mockRejectedValueOnce(new Error('database exploded'))
.mockResolvedValueOnce({ posted: 1, failed: 0, skipped: 0, errors: [] })
const response = await GET(cronRequest())
const json = await response.json()
expect(json.success).toBe(true)
expect(json.succeeded).toBe(1)
expect(json.failed).toBe(1)
expect(json.failures).toEqual([{ index: 0, error: 'database exploded' }])
expect(mockPostDueInstallments).toHaveBeenCalledTimes(2)
})
it('returns 500 when the due query fails', async () => {
installmentsResult = { data: null, error: { message: 'boom' } }
const response = await GET(cronRequest())
expect(response.status).toBe(500)
expect(mockPostDueInstallments).not.toHaveBeenCalled()
})
it('rejects unauthorized callers', async () => {
const { verifyCronSecret } = await import('@/lib/auth/cron')
const { NextResponse } = await import('next/server')
vi.mocked(verifyCronSecret).mockReturnValueOnce(
NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
)
const response = await GET(cronRequest())
expect(response.status).toBe(401)
expect(mockPostDueInstallments).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,98 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withCronContext } from '@/lib/api/with-cron-context'
import { createServiceClient } from '@/lib/supabase/server'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { postDueInstallments } from '@/lib/bookkeeping/accruals/service'
import { firstOfMonth } from '@/lib/bookkeeping/accruals/compute'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
/**
* GET /api/bookkeeping/accruals/post-due/cron, daily 05:15 UTC.
*
* Posts the monthly periodiseringsverifikat (source_type 'accrual') for every
* pending installment whose calendar month has begun. Companies run in
* isolated try/catch; one company's failure never blocks the rest. Per-
* installment failures are recorded on the row (last_error) by the service
* and retried on the next run: the periodiseringar page surfaces them.
*
* Idempotency: posting flips the installment pending→posted with a CAS
* claim, so a cron retry (or a concurrent manual "Bokför förfallna") can
* never double-book a month.
*/
export const GET = withCronContext('cron.accrual_postings', async (_request, ctx) => {
const supabase = createServiceClient()
const todayIso = new Date().toISOString().slice(0, 10)
// fetchAllRows pages past PostgREST's 1000-row cap: a single unpaginated
// select would silently drop companies once total due installments exceed
// the cap, permanently starving the ones sorted last.
let rows: Array<{ company_id: string }>
try {
rows = await fetchAllRows<{ company_id: string }>(({ from, to }) =>
supabase
.from('accrual_schedule_installments')
.select('company_id')
.eq('status', 'pending')
.lte('period_month', firstOfMonth(todayIso))
.order('id', { ascending: true })
.range(from, to),
)
} catch (error) {
ctx.log.error('failed to load due accrual installments', error as Error)
return NextResponse.json(
{ success: false, error: error instanceof Error ? getUserErrorMessage(error) : 'unknown' },
{ status: 500 },
)
}
const companyIds = Array.from(new Set(rows.map((row) => row.company_id)))
ctx.log.info('accrual posting cron starting', {
companyCount: companyIds.length,
todayIso,
})
const results: Array<{
companyId: string
posted: number
failed: number
skipped: number
}> = []
const summary = await ctx.forEach('company', companyIds, async (companyId, itemCtx) => {
const result = await postDueInstallments(supabase, companyId)
results.push({
companyId,
posted: result.posted,
failed: result.failed,
skipped: result.skipped,
})
if (result.failed > 0) {
itemCtx.log.warn('some accrual installments failed to post', {
companyId,
failed: result.failed,
})
}
})
ctx.log.info('accrual posting cron summary', {
total: summary.total,
succeeded: summary.succeeded,
failed: summary.failed,
posted: results.reduce((sum, r) => sum + r.posted, 0),
})
return NextResponse.json({
success: true,
total: summary.total,
succeeded: summary.succeeded,
failed: summary.failed,
failures: summary.failures,
results,
})
})
export const POST = GET
@@ -0,0 +1,28 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { postDueInstallments } from '@/lib/bookkeeping/accruals/service'
ensureInitialized()
/**
* POST /api/bookkeeping/accruals/post-due
*
* Manual "Bokför förfallna periodiseringar" for the active company:
* complements the daily cron (same service, same CAS idempotency), so the
* user never has to wait for the nightly run after creating a schedule with
* elapsed months or after fixing a blocked installment.
*/
export const POST = withRouteContext(
'accruals.post_due',
async (_request, ctx) => {
const { user, supabase, companyId } = ctx
const result = await postDueInstallments(supabase, companyId!, {
userId: user.id,
})
return NextResponse.json({ data: result })
},
{ requireWrite: true },
)
+69
View File
@@ -0,0 +1,69 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateQuery } from '@/lib/api/validate'
import { errorResponse } from '@/lib/errors/get-structured-error'
import { firstOfMonth } from '@/lib/bookkeeping/accruals/compute'
import type { AccrualSchedule, AccrualScheduleInstallment } from '@/types'
ensureInitialized()
const ListQuerySchema = z.object({
status: z.enum(['active', 'completed', 'cancelled', 'all']).default('active'),
})
/**
* GET /api/bookkeeping/accruals?status=active|completed|cancelled|all
*
* Schedules with their installments for the periodiseringar page, plus a
* `due_count` of pending installments whose month has begun (drives the
* "Bokför förfallna" banner).
*/
export const GET = withRouteContext(
'accruals.list',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const validated = validateQuery(request, ListQuerySchema, {
log,
operation: 'accruals.list',
})
if (!validated.success) return validated.response
const { status } = validated.data
let query = supabase
.from('accrual_schedules')
.select('*, installments:accrual_schedule_installments(*)')
.eq('company_id', companyId)
.order('created_at', { ascending: false })
if (status !== 'all') {
query = query.eq('status', status)
}
const { data, error } = await query
if (error) {
log.error('failed to list accrual schedules', error)
return errorResponse(error, log, { requestId })
}
const todayMonth = firstOfMonth(new Date().toISOString().slice(0, 10))
let dueCount = 0
const schedules = ((data ?? []) as Array<
AccrualSchedule & { installments: AccrualScheduleInstallment[] }
>).map((schedule) => {
const installments = [...(schedule.installments ?? [])].sort((a, b) =>
a.period_month.localeCompare(b.period_month),
)
if (schedule.status === 'active') {
dueCount += installments.filter(
(i) => i.status === 'pending' && i.period_month <= todayMonth,
).length
}
return { ...schedule, installments }
})
return NextResponse.json({ data: schedules, due_count: dueCount })
},
)
@@ -0,0 +1,243 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
import { createClient } from '@/lib/supabase/server'
import { PATCH } from '../route'
function patchRequest(body: unknown): Request {
return createMockRequest('/api/bookkeeping/fiscal-periods/period-1', {
method: 'PATCH',
body,
})
}
/**
* Mocks the chain of supabase calls the PATCH route makes:
* 1. from('fiscal_periods').select('*').eq.eq.single() → existing period (null = 404)
* 2. from('journal_entries').select(count, head).eq.eq.in() → posted entry count
* 3. from('fiscal_periods').select(count, head).eq.neq.lt() → earlier-period count
* 4. from('companies').select('entity_type').eq.single() → entity type
* 5. from('fiscal_periods').select('id, name').eq.neq.lte.gte.limit() → overlap
* 6. from('fiscal_periods').update().eq.eq.select.single() → updated row
*/
function buildMockSupabase(options: {
user?: { id: string } | null
period?: { id: string; period_start: string; period_end: string; locked_at: string | null; is_closed: boolean } | null
entityType?: 'aktiebolag' | 'enskild_firma'
postedEntryCount?: number
earlierPeriodCount?: number
overlapping?: Array<{ id: string; name: string }>
}) {
const {
user = { id: 'user-1' },
period = { id: 'p1', period_start: '2020-01-01', period_end: '2020-12-31', locked_at: null, is_closed: false },
entityType = 'enskild_firma',
postedEntryCount = 0,
earlierPeriodCount = 0,
overlapping = [],
} = options
let fiscalPeriodsCall = 0
const supabase = {
auth: {
getUser: vi.fn().mockResolvedValue({ data: { user } }),
},
from: vi.fn().mockImplementation((table: string) => {
if (table === 'journal_entries') {
return {
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
in: vi.fn().mockResolvedValue({ count: postedEntryCount, error: null }),
}),
}),
}),
}
}
if (table === 'companies') {
return {
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({ data: { entity_type: entityType }, error: null }),
}),
}),
}
}
if (table === 'fiscal_periods') {
fiscalPeriodsCall++
const callNum = fiscalPeriodsCall
return {
select: vi.fn().mockImplementation((_sel: string, opts?: { count?: string; head?: boolean }) => {
if (callNum === 1) {
return {
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({
data: period,
error: period ? null : { message: 'not found' },
}),
}),
}),
}
}
if (opts?.head) {
return {
eq: vi.fn().mockReturnValue({
neq: vi.fn().mockReturnValue({
lt: vi.fn().mockResolvedValue({ count: earlierPeriodCount, error: null }),
}),
}),
}
}
return {
eq: vi.fn().mockReturnValue({
neq: vi.fn().mockReturnValue({
lte: vi.fn().mockReturnValue({
gte: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue({ data: overlapping, error: null }),
}),
}),
}),
}),
}
}),
update: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
select: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({ data: period, error: null }),
}),
}),
}),
}),
}
}
return {}
}),
}
;(createClient as ReturnType<typeof vi.fn>).mockResolvedValue(supabase)
return supabase
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('PATCH /api/bookkeeping/fiscal-periods/[id]', () => {
describe('standard guards', () => {
it('returns 401 when not authenticated', async () => {
buildMockSupabase({ user: null })
const res = await PATCH(patchRequest({ period_end: '2020-12-31' }), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(401)
})
it('returns 400 when body is malformed', async () => {
buildMockSupabase({})
const res = await PATCH(patchRequest({ period_start: 'not-a-date' }), createMockRouteParams({ id: 'p1' }))
expect(res.status).toBe(400)
})
it('returns 404 when period does not exist', async () => {
buildMockSupabase({ period: null })
const res = await PATCH(patchRequest({ period_end: '2020-12-31' }), createMockRouteParams({ id: 'missing' }))
expect(res.status).toBe(404)
})
})
describe('enskild firma: BFL 3 kap.', () => {
it('allows förlängt räkenskapsår (15 mån, 4 okt 2020 → 31 dec 2021) on the first period', async () => {
buildMockSupabase({ earlierPeriodCount: 0 })
const res = await PATCH(
patchRequest({ period_start: '2020-10-04', period_end: '2021-12-31' }),
createMockRouteParams({ id: 'p1' }),
)
expect(res.status).toBe(200)
})
it('rejects EF first period when slutdatum is not 31 december', async () => {
buildMockSupabase({ earlierPeriodCount: 0 })
const res = await PATCH(
patchRequest({ period_start: '2020-10-04', period_end: '2021-11-30' }),
createMockRouteParams({ id: 'p1' }),
)
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error).toMatch(/31 december/)
})
it('rejects EF subsequent period when startdatum is not 1 januari', async () => {
buildMockSupabase({
period: { id: 'p2', period_start: '2026-01-01', period_end: '2026-12-31', locked_at: null, is_closed: false },
earlierPeriodCount: 1,
})
const res = await PATCH(
patchRequest({ period_start: '2026-02-01', period_end: '2026-12-31' }),
createMockRouteParams({ id: 'p2' }),
)
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error).toMatch(/kalenderår/)
})
it('accepts EF subsequent period running 1 jan to 31 dec', async () => {
buildMockSupabase({
period: { id: 'p2', period_start: '2026-01-01', period_end: '2026-12-31', locked_at: null, is_closed: false },
earlierPeriodCount: 1,
})
const res = await PATCH(
patchRequest({ period_start: '2026-01-01', period_end: '2026-12-31' }),
createMockRouteParams({ id: 'p2' }),
)
expect(res.status).toBe(200)
})
// Locks in the implicit "EF subsequent period is always exactly 12 months"
// rule. The start-must-be-1-jan + end-must-be-31-dec guards together force
// a 12-month span; this test catches a future refactor that loosens either.
it('rejects EF subsequent period when slutdatum is not 31 december', async () => {
buildMockSupabase({
period: { id: 'p2', period_start: '2026-01-01', period_end: '2026-12-31', locked_at: null, is_closed: false },
earlierPeriodCount: 1,
})
const res = await PATCH(
patchRequest({ period_start: '2026-01-01', period_end: '2027-01-31' }),
createMockRouteParams({ id: 'p2' }),
)
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error).toMatch(/31 december/)
})
// Defense-in-depth: the EF end-date guard runs before validatePeriodDuration.
// A 24-month first period (2020-01-01 → 2021-12-31) ends on 31 dec, so the EF
// guard passes: duration validation must catch it as BFL 3 kap. caps the
// first period at 18 months.
it('rejects a 24-month first period via the duration cap', async () => {
buildMockSupabase({ earlierPeriodCount: 0 })
const res = await PATCH(
patchRequest({ period_start: '2020-01-01', period_end: '2021-12-31' }),
createMockRouteParams({ id: 'p1' }),
)
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error).toMatch(/18 months/)
})
})
})
@@ -0,0 +1,173 @@
import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest'
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
const mockCreateClient = vi.fn()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => mockCreateClient(),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
const mockGetCompanyEntityType = vi.fn()
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
getCompanyEntityType: (...args: unknown[]) => mockGetCompanyEntityType(...args),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
const mockBuildAccrualsProposal = vi.fn()
const mockDetectPeriodisering = vi.fn()
vi.mock('@/lib/bokslut/accruals/accrual-detector', async () => {
const actual =
(await vi.importActual('@/lib/bokslut/accruals/accrual-detector')) as Record<string, unknown>
return {
...actual,
buildAccrualsProposal: (...args: unknown[]) => mockBuildAccrualsProposal(...args),
}
})
vi.mock('@/lib/bokslut/accruals/auto-detect', () => ({
detectPeriodisering: (...args: unknown[]) => mockDetectPeriodisering(...args),
}))
const mockUser = { id: 'user-1', email: 'test@test.se' }
// The route module pulls in the bookkeeping engine and accrual detector; that
// parse can take seconds under full-suite parallel load. Warm it once here so
// no individual test's default 5s timeout has to absorb the import cost.
let GET: typeof import('../route').GET
beforeAll(async () => {
;({ GET } = await import('../route'))
}, 30_000)
/** Minimal supabase mock: auth only. The entity_type resolution is mocked at
* the getCompanyEntityType boundary (company_settings-primary with a
* companies fallback lives inside lib/company/context, tested there). */
function mockSupabase() {
return {
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: mockUser } }) },
from: vi.fn(() => ({
select: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
single: vi.fn().mockResolvedValue({ data: null, error: { message: 'not found' } }),
maybeSingle: vi.fn().mockResolvedValue({ data: null, error: null }),
})),
}
}
beforeEach(() => {
vi.clearAllMocks()
mockCreateClient.mockResolvedValue(mockSupabase())
mockGetCompanyEntityType.mockResolvedValue('aktiebolag')
})
describe('GET /api/bookkeeping/fiscal-periods/[id]/accruals', () => {
it('returns 401 when unauthenticated', async () => {
mockCreateClient.mockResolvedValue({
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: null } }) },
})
const res = await GET(
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
createMockRouteParams({ id: 'period-1' }),
)
expect(res.status).toBe(401)
})
it('returns the snapshot plus autoDetected suggestions', async () => {
mockBuildAccrualsProposal.mockResolvedValue({
fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
proposals: [],
})
mockDetectPeriodisering.mockResolvedValue([
{
source_invoice_id: 'sup-1',
source_type: 'supplier_invoice',
original_amount: 12000,
periodisering_amount: 6000,
parsed_start: '2025-07-01',
parsed_end: '2026-06-30',
confidence: 'high',
reason: 'Mock reason',
source_label: 'Test Supplier',
suggested_prepaid_account: '1710',
suggested_deferred_account: null,
},
])
const res = await GET(
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
createMockRouteParams({ id: 'period-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { autoDetected: unknown[] } }>(res)
expect(status).toBe(200)
expect(body.data.autoDetected).toHaveLength(1)
// The route resolves the company's entity_type and threads it through so
// the materiality wording cites the right regelverk (K1 vs K2).
expect(mockDetectPeriodisering).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'period-1',
{ entityType: 'aktiebolag' },
)
})
it('threads entity_type enskild_firma to the detector', async () => {
mockGetCompanyEntityType.mockResolvedValue('enskild_firma')
mockBuildAccrualsProposal.mockResolvedValue({
fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
proposals: [],
})
mockDetectPeriodisering.mockResolvedValue([])
const res = await GET(
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
createMockRouteParams({ id: 'period-1' }),
)
expect(res.status).toBe(200)
expect(mockDetectPeriodisering).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'period-1',
{ entityType: 'enskild_firma' },
)
})
it('falls back to null entityType when the entity type cannot be resolved', async () => {
mockGetCompanyEntityType.mockResolvedValue(null)
mockBuildAccrualsProposal.mockResolvedValue({
fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
proposals: [],
})
mockDetectPeriodisering.mockResolvedValue([])
const res = await GET(
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
createMockRouteParams({ id: 'period-1' }),
)
expect(res.status).toBe(200)
expect(mockDetectPeriodisering).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'period-1',
{ entityType: null },
)
})
it('still returns the snapshot when auto-detect throws', async () => {
mockBuildAccrualsProposal.mockResolvedValue({
fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
proposals: [],
})
mockDetectPeriodisering.mockRejectedValue(new Error('boom'))
const res = await GET(
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
createMockRouteParams({ id: 'period-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { autoDetected: unknown[] } }>(res)
expect(status).toBe(200)
expect(body.data.autoDetected).toEqual([])
})
})
@@ -0,0 +1,313 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getCompanyEntityType } from '@/lib/company/context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { validateBody } from '@/lib/api/validate'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import {
buildAccrualsProposal,
proposeAccruedInterest,
proposeAccruedUtility,
proposeAuditFee,
proposeManualAccrued,
proposeManualPrepaid,
proposeRevenueDeferral,
proposeVacationLiabilityChange,
} from '@/lib/bokslut/accruals/accrual-detector'
import { detectPeriodisering } from '@/lib/bokslut/accruals/auto-detect'
import type { PeriodiseringEntityType } from '@/lib/bokslut/accruals/auto-detect'
import type { AccrualProposal } from '@/lib/bokslut/accruals/types'
import type { JournalEntry } from '@/types'
export const GET = withRouteContext(
'period.accruals_preview',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
try {
// Run the two independent scans in parallel so the wizard's first
// paint isn't gated on the slower auto-detect query.
const [proposal, autoDetected] = await Promise.all([
buildAccrualsProposal(supabase, companyId, id),
(async () => {
// Entity type picks the regelverk the materiality wording cites:
// K1 (BFNAR 2006:1) for enskild firma, K2 (BFNAR 2016:10) for AB.
// Resolved via getCompanyEntityType: company_settings is the
// read-primary source (what the user edits in Settings), with
// companies.entity_type as the fallback.
const entityType = await getCompanyEntityType(supabase, companyId)
return detectPeriodisering(supabase, companyId, id, {
entityType: (entityType as PeriodiseringEntityType | null) ?? null,
})
})().catch((err) => {
// Auto-detect is best-effort: a malformed invoice description
// shouldn't break the rest of the preflight. Log + return empty.
log.warn('auto-detect failed', { error: (err as Error)?.message })
return []
}),
])
return NextResponse.json({ data: { ...proposal, autoDetected } })
} catch (err) {
const message = err instanceof Error ? err.message : ''
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
return errorResponse(err, log, { requestId })
}
},
)
// Defense-in-depth on caller-supplied account numbers. The wizard sends
// accounts from a closed template list, but the API accepts them as plain
// strings so we constrain the BAS class per accrual kind:
// - cost accounts (5xxx-8xxx) for expense legs
// - revenue accounts (3xxx) for revenue legs
// - 17xx for förutbetalda kostnader (prepaid)
// - 29xx for upplupna poster (accrued / deferred)
// Anything outside these ranges is rejected with 400 before reaching the
// engine: keeps a compromised browser session from posting arbitrary
// balance-sheet hits.
const EXPENSE_ACCOUNT_RE = /^[5-8]\d{3}$/
const REVENUE_ACCOUNT_RE = /^3\d{3}$/
const PostItemSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('vacation_liability_change') }),
z.object({
kind: z.literal('audit_fee'),
amount: z.number().positive(),
liability_account: z.enum(['2991', '2992']).optional(),
}),
z.object({
kind: z.literal('manual_prepaid_expense'),
amount: z.number().positive(),
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
prepaid_account: z.string().regex(/^17\d{2}$/),
description: z.string().min(1),
}),
z.object({
kind: z.literal('manual_accrued_expense'),
amount: z.number().positive(),
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
accrued_account: z.string().regex(/^29\d{2}$/),
description: z.string().min(1),
}),
z.object({
kind: z.literal('deferred_revenue'),
amount: z.number().positive(),
revenue_account: z.string().regex(REVENUE_ACCOUNT_RE),
deferred_account: z.string().regex(/^29\d{2}$/),
description: z.string().min(1),
}),
z.object({
kind: z.literal('accrued_interest'),
amount: z.number().positive(),
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
accrued_account: z.string().regex(/^29\d{2}$/),
description: z.string().min(1),
}),
z.object({
kind: z.literal('accrued_utility'),
amount: z.number().positive(),
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
accrued_account: z.string().regex(/^29\d{2}$/),
description: z.string().min(1),
}),
])
const PostBodySchema = z.object({
items: z.array(PostItemSchema).min(1),
})
export const POST = withRouteContext(
'period.accruals_post',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const validation = await validateBody(request, PostBodySchema)
if (!validation.success) return validation.response
try {
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('id, name, period_end, is_closed, locked_at, closing_entry_id')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (periodError || !period) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
if (period.is_closed || period.closing_entry_id || period.locked_at) {
return errorResponseFromCode('PERIOD_LOCKED', log, { requestId })
}
const created: { kind: string; entry: JournalEntry; reverses_on: string | null }[] = []
const skipped: { kind: string; existing_entry_id: string; reason: string }[] = []
for (const item of validation.data.items) {
// Idempotency: refuse to post a duplicate accrual of the same kind for
// the same period. Without this, re-running the wizard (or a retried
// request after a flaky network) would create duplicate entries that
// distort both the balance sheet and the trial balance.
const existingId = await findExistingAccrualEntry(supabase, companyId, id, item)
if (existingId) {
skipped.push({
kind: item.kind,
existing_entry_id: existingId,
reason: 'already_posted',
})
continue
}
let proposal: AccrualProposal | null = null
switch (item.kind) {
case 'vacation_liability_change':
proposal = await proposeVacationLiabilityChange(supabase, companyId, id, {
closingDate: period.period_end,
})
break
case 'audit_fee':
proposal = proposeAuditFee({
amount: item.amount,
closingDate: period.period_end,
liabilityAccount: item.liability_account,
})
break
case 'manual_prepaid_expense':
proposal = proposeManualPrepaid({
amount: item.amount,
expenseAccount: item.expense_account,
prepaidAccount: item.prepaid_account,
description: item.description,
closingDate: period.period_end,
})
break
case 'manual_accrued_expense':
proposal = proposeManualAccrued({
amount: item.amount,
expenseAccount: item.expense_account,
accruedAccount: item.accrued_account,
description: item.description,
closingDate: period.period_end,
})
break
case 'deferred_revenue':
proposal = proposeRevenueDeferral({
amount: item.amount,
revenueAccount: item.revenue_account,
deferredAccount: item.deferred_account,
description: item.description,
closingDate: period.period_end,
})
break
case 'accrued_interest':
proposal = proposeAccruedInterest({
amount: item.amount,
expenseAccount: item.expense_account,
accruedAccount: item.accrued_account,
description: item.description,
closingDate: period.period_end,
})
break
case 'accrued_utility':
proposal = proposeAccruedUtility({
amount: item.amount,
expenseAccount: item.expense_account,
accruedAccount: item.accrued_account,
description: item.description,
closingDate: period.period_end,
})
break
}
if (!proposal) continue
// Mark the entry's description with the reversal date so future
// bookkeepers (and a future cron) can spot the periodisering. The
// accrual_reversals cron is follow-up infra: once it lands, the
// entry's source_type or a metadata column can drive the auto-flip.
//
// Vacation-liability adjustments deliberately have empty reverses_on
// since 2920 carries forward: emit a different description in that
// case so future readers don't expect a Jan 1 reversal.
const description = proposal.reverses_on
? `Periodisering: ${proposal.label} (vänds ${proposal.reverses_on})`
: `Bokslutsjustering: ${proposal.label}`
const entry = await createJournalEntry(supabase, companyId, user.id, {
fiscal_period_id: id,
entry_date: period.period_end,
description,
source_type: 'manual',
voucher_series: 'A',
lines: proposal.lines,
})
created.push({ kind: item.kind, entry, reverses_on: proposal.reverses_on })
}
return NextResponse.json({ data: { created, skipped } })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
{ requireWrite: true },
)
type PostItem = z.infer<typeof PostItemSchema>
/**
* Find a previously-posted accrual journal entry for the same kind in the
* same period, used by the POST handler to enforce idempotency. Matches
* on the description prefix that each calculator emits (see
* accrual-detector.ts and the POST handler's description construction).
*
* For manual prepaid/accrued the dedup key includes the user-supplied
* description, so different items with different descriptions don't collide.
*/
async function findExistingAccrualEntry(
supabase: Awaited<ReturnType<typeof import('@/lib/supabase/server')['createClient']>>,
companyId: string,
fiscalPeriodId: string,
item: PostItem,
): Promise<string | null> {
let pattern: string
switch (item.kind) {
case 'vacation_liability_change':
pattern = '%semesterlöneskuld%'
break
case 'audit_fee': {
const account = item.liability_account ?? '2992'
pattern = account === '2991' ? '%arvode för bokslut%' : '%arvode för revision%'
break
}
case 'manual_prepaid_expense':
pattern = `Periodisering: Förutbetald kostnad: ${escapeLike(item.description)}%`
break
case 'manual_accrued_expense':
pattern = `Periodisering: Upplupen kostnad: ${escapeLike(item.description)}%`
break
case 'deferred_revenue':
pattern = `Periodisering: Förutbetald intäkt: ${escapeLike(item.description)}%`
break
case 'accrued_interest':
pattern = `Periodisering: Upplupen ränta: ${escapeLike(item.description)}%`
break
case 'accrued_utility':
pattern = `Periodisering: Upplupen förbrukning: ${escapeLike(item.description)}%`
break
}
const { data } = await supabase
.from('journal_entries')
.select('id')
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('status', 'posted')
.ilike('description', pattern)
.limit(1)
return (data?.[0]?.id as string | undefined) ?? null
}
function escapeLike(s: string): string {
return s.replace(/[\\%_]/g, (c) => `\\${c}`)
}
@@ -0,0 +1,167 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/bokslut/arsredovisning/model', () => ({
buildCanonicalAnnualReport: vi.fn(),
}))
vi.mock('@/lib/bokslut/arsredovisning/profile-service', () => ({
upsertAnnualReportProfile: vi.fn(),
}))
import { buildCanonicalAnnualReport } from '@/lib/bokslut/arsredovisning/model'
import { upsertAnnualReportProfile } from '@/lib/bokslut/arsredovisning/profile-service'
import { GET, PATCH } from '../route'
const params = { params: Promise.resolve({ id: 'period-1' }) }
const model = {
report: {
accounting_framework: 'k2',
forvaltningsberattelse: {
proposed_dividend: 0,
resultatdisposition_amounts: { total: 100 },
},
},
profile: { company_id: 'company-1', fiscal_period_id: 'period-1' },
disclosures: {},
eligibility: {
k2_eligible: true,
digital_filing_eligible: true,
size_classification: 'smaller',
k2_relief_rule: 'eligible',
issues: [],
digital_issues: [],
},
validation: { stage: 'draft', ok: true, error_count: 0, warning_count: 0, issues: [] },
}
function setup() {
const mock = createQueuedMockSupabase()
requireAuthMock.mockResolvedValue({
user: { id: 'user-1' },
supabase: mock.supabase,
error: null,
})
vi.mocked(buildCanonicalAnnualReport).mockResolvedValue(model as never)
vi.mocked(upsertAnnualReportProfile).mockResolvedValue(model.profile as never)
return mock
}
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('annual report compliance route', () => {
it('returns 401 without authentication', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect((await GET(createMockRequest('/x'), params)).status).toBe(401)
})
it('returns 400 for an empty patch', async () => {
setup()
const response = await PATCH(
createMockRequest('/x', { method: 'PATCH', body: {} }),
params,
)
expect(response.status).toBe(400)
})
it('returns 404 for another company period', async () => {
// GET has no periodExists preflight: the 404 comes from the report
// builder throwing 'Fiscal period not found' (same company_id filter).
setup()
vi.mocked(buildCanonicalAnnualReport).mockRejectedValue(
new Error('Fiscal period not found'),
)
expect((await GET(createMockRequest('/x'), params)).status).toBe(404)
})
it('maps unexpected builder failures to the generic error envelope', async () => {
setup()
vi.mocked(buildCanonicalAnnualReport).mockRejectedValue(new Error('boom'))
expect((await GET(createMockRequest('/x'), params)).status).toBe(500)
})
it('returns the canonical compliance result', async () => {
setup()
const { status, body } = await parseJsonResponse<{ data: typeof model }>(
await GET(createMockRequest('/x'), params),
)
expect(status).toBe(200)
expect(body.data.validation.ok).toBe(true)
})
it('keeps the periodExists preflight on PATCH (404 before any write)', async () => {
const { enqueue } = setup()
enqueue({ data: null })
const response = await PATCH(
createMockRequest('/x', {
method: 'PATCH',
body: { is_public_limited_company: false },
}),
params,
)
expect(response.status).toBe(404)
expect(upsertAnnualReportProfile).not.toHaveBeenCalled()
})
it('persists legal facts and confirmation timestamps', async () => {
const { enqueue } = setup()
enqueue({ data: { id: 'period-1' } })
const response = await PATCH(
createMockRequest('/x', {
method: 'PATCH',
body: { is_public_limited_company: false, k2_assessment_confirmed: true },
}),
params,
)
expect(response.status).toBe(200)
expect(upsertAnnualReportProfile).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
'period-1',
expect.objectContaining({
is_public_limited_company: false,
k2_assessment_confirmed_at: expect.any(String),
}),
)
})
it('records explicit representative roster confirmation', async () => {
const { enqueue } = setup()
enqueue({ data: { id: 'period-1' } })
const response = await PATCH(
createMockRequest('/x', {
method: 'PATCH',
body: { signer_roster_confirmed: true },
}),
params,
)
expect(response.status).toBe(200)
expect(upsertAnnualReportProfile).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
'period-1',
expect.objectContaining({ signer_roster_confirmed_at: expect.any(String) }),
)
})
})
@@ -0,0 +1,134 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import type { SupabaseClient } from '@supabase/supabase-js'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { buildCanonicalAnnualReport } from '@/lib/bokslut/arsredovisning/model'
import { getAnnualReportCapabilities } from '@/lib/bokslut/arsredovisning/capabilities'
import { upsertAnnualReportProfile } from '@/lib/bokslut/arsredovisning/profile-service'
const NullableBoolean = z.boolean().nullable()
const PatchSchema = z
.object({
is_public_limited_company: NullableBoolean.optional(),
is_in_liquidation: NullableBoolean.optional(),
securities_traded_on_regulated_market: NullableBoolean.optional(),
is_parent_company: NullableBoolean.optional(),
parent_group_size: z.enum(['none', 'small', 'large']).nullable().optional(),
prepares_consolidated_accounts: NullableBoolean.optional(),
has_foreign_branch: NullableBoolean.optional(),
has_crypto_assets: NullableBoolean.optional(),
has_share_based_payments: NullableBoolean.optional(),
has_convertible_debt: NullableBoolean.optional(),
building_revenue_share_pct: z.number().min(0).max(100).nullable().optional(),
has_material_deferred_tax: NullableBoolean.optional(),
reporting_currency: z.enum(['SEK', 'EUR']).optional(),
auditor_report_required: NullableBoolean.optional(),
auditor_report_included: z.boolean().optional(),
dividend_prudence_confirmed: NullableBoolean.optional(),
narrative_confirmed: z.boolean().optional(),
k2_assessment_confirmed: z.boolean().optional(),
signer_roster_confirmed: z.boolean().optional(),
})
.strict()
.refine((value) => Object.keys(value).length > 0, { message: 'At least one field is required' })
async function periodExists(
supabase: SupabaseClient,
companyId: string,
fiscalPeriodId: string,
): Promise<boolean> {
const { data } = await supabase
.from('fiscal_periods')
.select('id')
.eq('id', fiscalPeriodId)
.eq('company_id', companyId)
.maybeSingle()
return Boolean(data)
}
function responseData(model: Awaited<ReturnType<typeof buildCanonicalAnnualReport>>) {
return {
profile: model.profile,
disclosures: model.disclosures,
eligibility: model.eligibility,
validation: model.validation,
capabilities: getAnnualReportCapabilities(model.report.accounting_framework, model.eligibility),
report_summary: {
proposed_dividend: model.report.forvaltningsberattelse.proposed_dividend,
distributable_equity:
model.report.forvaltningsberattelse.resultatdisposition_amounts.total,
},
}
}
export const GET = withRouteContext(
'period.arsredovisning_compliance_get',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
try {
const model = await buildCanonicalAnnualReport(supabase, companyId, id, {
stage: 'draft',
includeIxbrl: false,
})
return NextResponse.json({ data: responseData(model) })
} catch (err) {
// No periodExists preflight here: buildArsredovisningData applies the
// same company_id filter and throws 'Fiscal period not found' for
// missing/foreign periods, so mapping that message (mirroring the data
// route) yields the identical 404 envelope without the extra round
// trip. PATCH keeps the preflight since it guards the profile upsert
// before any write.
const message = err instanceof Error ? err.message : ''
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
return errorResponse(err, log, { requestId })
}
},
)
export const PATCH = withRouteContext(
'period.arsredovisning_compliance_patch',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const validation = await validateBody(request, PatchSchema)
if (!validation.success) return validation.response
try {
if (!(await periodExists(supabase, companyId, id))) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
const {
narrative_confirmed,
k2_assessment_confirmed,
signer_roster_confirmed,
...profileFields
} = validation.data
const now = new Date().toISOString()
await upsertAnnualReportProfile(supabase, companyId, user.id, id, {
...profileFields,
...(narrative_confirmed !== undefined
? { narrative_confirmed_at: narrative_confirmed ? now : null }
: {}),
...(k2_assessment_confirmed !== undefined
? { k2_assessment_confirmed_at: k2_assessment_confirmed ? now : null }
: {}),
...(signer_roster_confirmed !== undefined
? { signer_roster_confirmed_at: signer_roster_confirmed ? now : null }
: {}),
})
const model = await buildCanonicalAnnualReport(supabase, companyId, id, {
stage: 'draft',
includeIxbrl: false,
})
return NextResponse.json({ data: responseData(model) })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
{ requireWrite: true },
)
@@ -0,0 +1,162 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/bokslut/ixbrl/build-input', () => ({
buildIxbrlInput: vi.fn(),
}))
import { createClient } from '@/lib/supabase/server'
import { createQueuedMockSupabase } from '@/tests/helpers'
import { buildIxbrlInput } from '@/lib/bokslut/ixbrl/build-input'
import { makeInput } from '@/lib/bokslut/ixbrl/__tests__/fixtures'
import { GET } from '../route'
import { GET as GET_VALIDATE } from '../validate/route'
function mkReq(query = '') {
return new Request(
`http://localhost/api/bookkeeping/fiscal-periods/period-1/arsredovisning/ixbrl${query}`,
)
}
function mkParams(id = 'period-1') {
return { params: Promise.resolve({ id }) }
}
function authedSupabase() {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: { id: 'user-1' } } })
vi.mocked(createClient).mockResolvedValue(supabase as never)
return supabase
}
describe('GET /api/bookkeeping/fiscal-periods/[id]/arsredovisning/ixbrl', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns 401 when unauthenticated', async () => {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: null } })
vi.mocked(createClient).mockResolvedValue(supabase as never)
const res = await GET(mkReq(), mkParams())
expect(res.status).toBe(401)
})
it('returns 404 when the period is missing', async () => {
authedSupabase()
vi.mocked(buildIxbrlInput).mockRejectedValue(new Error('Fiscal period not found'))
const res = await GET(mkReq(), mkParams())
expect(res.status).toBe(404)
})
it('returns the generated XHTML inline for iframe preview', async () => {
authedSupabase()
vi.mocked(buildIxbrlInput).mockResolvedValue(makeInput())
const res = await GET(mkReq(), mkParams())
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toContain('application/xhtml+xml')
expect(res.headers.get('Content-Disposition')).toContain('inline')
expect(res.headers.get('Cache-Control')).toContain('no-store')
const body = await res.text()
expect(body).toContain('<?xml version="1.0" encoding="utf-8"?>')
expect(body).toContain('se-k2-ab-risbs-2024-09-12.xsd')
expect(body).toContain('ID_DATUM_UNDERTECKNANDE_FASTSTALLELSEINTYG')
})
it('serves as attachment with ?download=1 and forwards utdelning', async () => {
authedSupabase()
vi.mocked(buildIxbrlInput).mockResolvedValue(makeInput())
const res = await GET(mkReq('?download=1&utdelning=50000'), mkParams())
expect(res.status).toBe(200)
expect(res.headers.get('Content-Disposition')).toContain('attachment')
expect(res.headers.get('Content-Disposition')).toContain('arsredovisning-2025-12-31.xhtml')
expect(vi.mocked(buildIxbrlInput)).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'period-1',
{ proposedDividend: 50000 },
)
})
it('returns 500 envelope when generation explodes', async () => {
authedSupabase()
const broken = makeInput()
broken.entryPointId = 'okant-entry-point'
vi.mocked(buildIxbrlInput).mockResolvedValue(broken)
const res = await GET(mkReq(), mkParams())
expect(res.status).toBe(500)
})
})
describe('GET /api/bookkeeping/fiscal-periods/[id]/arsredovisning/ixbrl/validate', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns ok with no errors for the happy-path fixture', async () => {
authedSupabase()
const input = makeInput()
// Keep date rules deterministic: the fixture period ends 2025-12-31 and
// AGM is 2026-03-15, both in the past relative to the suite's clock.
vi.mocked(buildIxbrlInput).mockResolvedValue(input)
const res = await GET_VALIDATE(mkReq('/validate'), mkParams())
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.ok).toBe(true)
expect(body.data.error_count).toBe(0)
expect(body.data.generated_bytes).toBeGreaterThan(10_000)
expect(body.data.entry_point).toBe('k2-ab-risbs-2024-09-12')
})
it('reports rule violations as issues without failing the request', async () => {
authedSupabase()
const input = makeInput()
input.underskrifter.signers = []
input.totals.tillgangar = { current: 1, previous: 1 }
vi.mocked(buildIxbrlInput).mockResolvedValue(input)
const res = await GET_VALIDATE(mkReq('/validate'), mkParams())
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.ok).toBe(false)
const issueCodes = body.data.issues.map((issue: { code: string }) => issue.code)
expect(issueCodes).toContain('1107')
expect(issueCodes).toContain('3005')
})
it('surfaces generation failures as ACC-GEN issues', async () => {
authedSupabase()
const broken = makeInput()
broken.rr = {} as never
broken.totals = { ...broken.totals }
// Force a generation error by pointing at a non-existent entry point.
broken.entryPointId = 'okant-entry-point'
vi.mocked(buildIxbrlInput).mockResolvedValue(broken)
const res = await GET_VALIDATE(mkReq('/validate'), mkParams())
expect(res.status).toBe(200)
const body = await res.json()
const issueCodes = body.data.issues.map((issue: { code: string }) => issue.code)
expect(issueCodes).toContain('ACC-GEN')
expect(body.data.ok).toBe(false)
})
it('returns 404 when the period is missing', async () => {
authedSupabase()
vi.mocked(buildIxbrlInput).mockRejectedValue(new Error('Fiscal period not found'))
const res = await GET_VALIDATE(mkReq('/validate'), mkParams())
expect(res.status).toBe(404)
})
})
@@ -0,0 +1,67 @@
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { buildIxbrlInput } from '@/lib/bokslut/ixbrl/build-input'
import { generateK2IxbrlDocument } from '@/lib/bokslut/ixbrl/document/k2-document'
import { getVersionIxbrlInput } from '@/lib/bokslut/arsredovisning/version-ixbrl'
/**
* GET /api/bookkeeping/fiscal-periods/:id/arsredovisning/ixbrl
*
* Generates the iXBRL (XHTML) årsredovisning for the period. The document IS
* the presentation (per TILLAMPNINGSANVISNING): the wizard renders it in an
* iframe as the authoritative preview, and `?download=1` exports the same
* bytes for validation and the company's archive. The XHTML file is not a
* standalone manual filing path: digital filing goes through connected
* software and the paper fallback is a certified copy sent by post.
*
* Query params:
* - download=1 → Content-Disposition: attachment
* - utdelning=N → proposed dividend in whole SEK for the resultatdisposition
*/
export const GET = withRouteContext(
'period.arsredovisning_ixbrl',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
try {
const url = new URL(request.url)
const download = url.searchParams.get('download') === '1'
const versionId = url.searchParams.get('version')
const utdelningRaw = url.searchParams.get('utdelning')
const proposedDividend = utdelningRaw ? Number(utdelningRaw) : undefined
const input = versionId
? await getVersionIxbrlInput(supabase, companyId, id, versionId)
: await buildIxbrlInput(supabase, companyId, id, {
proposedDividend:
proposedDividend !== undefined && Number.isFinite(proposedDividend)
? proposedDividend
: undefined,
})
if (!input) return errorResponseFromCode('NOT_FOUND', log, { requestId })
const { xhtml, warnings } = generateK2IxbrlDocument(input)
const safePeriodEnd = input.period.end.replace(/[^\w.-]/g, '_')
const filename = `arsredovisning-${safePeriodEnd}.xhtml`
return new Response(xhtml, {
headers: {
// Served as XHTML so iframe preview renders the inline XBRL
// document exactly as Bolagsverket will present it.
'Content-Type': 'application/xhtml+xml; charset=utf-8',
'Content-Disposition': `${download ? 'attachment' : 'inline'}; filename="${filename}"`,
'Cache-Control': 'private, no-store, no-cache, must-revalidate',
Pragma: 'no-cache',
// Generation warnings surfaced without disturbing the body.
'X-Ixbrl-Warning-Count': String(warnings.length),
...(versionId ? { 'X-Annual-Report-Version': versionId } : {}),
},
})
} catch (err) {
const message = err instanceof Error ? err.message : ''
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
return errorResponse(err, log, { requestId })
}
},
)
@@ -0,0 +1,84 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { buildIxbrlInput } from '@/lib/bokslut/ixbrl/build-input'
import { generateK2IxbrlDocument } from '@/lib/bokslut/ixbrl/document/k2-document'
import { runPreflightChecks, type PreflightIssue } from '@/lib/bokslut/ixbrl/validate/rules'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { getVersionIxbrlInput } from '@/lib/bokslut/arsredovisning/version-ixbrl'
/**
* GET /api/bookkeeping/fiscal-periods/:id/arsredovisning/ixbrl/validate
*
* Layer-1 validation (local mirror of Bolagsverket kontrollera, GUIDE
* Appendix E) + a generation dry-run so taxonomy-level problems (unknown
* concept, context mismatch) surface as issues instead of a 500 in the
* preview. Layer 3 (the real kontrollera call) lives in the bolagsverket
* extension and runs in the Skicka in step.
*/
export const GET = withRouteContext(
'period.arsredovisning_ixbrl_validate',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
try {
const url = new URL(request.url)
const versionId = url.searchParams.get('version')
const utdelningRaw = url.searchParams.get('utdelning')
const proposedDividend = utdelningRaw ? Number(utdelningRaw) : undefined
const input = versionId
? await getVersionIxbrlInput(supabase, companyId, id, versionId)
: await buildIxbrlInput(supabase, companyId, id, {
proposedDividend:
proposedDividend !== undefined && Number.isFinite(proposedDividend)
? proposedDividend
: undefined,
})
if (!input) return errorResponseFromCode('NOT_FOUND', log, { requestId })
const result = runPreflightChecks(input)
// Generation dry-run: a document that cannot even be generated must
// block, with the reason in the issue list rather than a raw error.
const issues: PreflightIssue[] = [...result.issues]
let generatedBytes = 0
try {
const { xhtml } = generateK2IxbrlDocument(input)
generatedBytes = Buffer.byteLength(xhtml, 'utf8')
if (generatedBytes >= 5 * 1024 * 1024) {
issues.push({
code: '5006',
severity: 'error',
message: 'Dokumentet överstiger Bolagsverkets maxstorlek 5 MB.',
})
}
} catch (genErr) {
issues.push({
code: 'ACC-GEN',
severity: 'error',
message: `iXBRL-dokumentet kunde inte genereras: ${genErr instanceof Error ? getUserErrorMessage(genErr) : 'okänt fel'}`,
})
}
const errors = issues.filter((issue) => issue.severity === 'error')
return NextResponse.json({
data: {
ok: errors.length === 0,
issues,
error_count: errors.length,
warning_count: issues.length - errors.length,
generated_bytes: generatedBytes,
entry_point: input.entryPointId,
period: input.period,
annual_report_version_id: versionId,
},
})
} catch (err) {
const message = err instanceof Error ? err.message : ''
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
return errorResponse(err, log, { requestId })
}
},
)
@@ -0,0 +1,212 @@
/**
* Tests for GET/POST /api/bookkeeping/fiscal-periods/[id]/arsredovisning/narrative.
*
* Regression focus: the narrative must stay editable after the fiscal period
* is closed/locked (Verkställ bokslut). The normal flow closes the books
* BEFORE the årsredovisning text is written, so gating the save on the
* period lock made every legitimate save fail. Edits are refused only once
* a Bolagsverket submission for the period is registrerad.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET, POST } from '../route'
const idParams = { params: Promise.resolve({ id: 'period-1' }) }
const narrativeRow = {
id: 'narrative-1',
company_id: 'company-1',
fiscal_period_id: 'period-1',
description: 'Bolaget bedriver konsultverksamhet.',
important_events: null,
resultatdisposition: null,
agm_date: null,
long_term_debt_over_five_years: null,
securities_pledged: null,
contingent_liabilities: null,
parent_company_name: null,
parent_company_org_number: null,
parent_company_city: null,
updated_at: '2026-01-15T10:00:00Z',
}
function setupSupabase() {
const mock = createQueuedMockSupabase()
requireAuthMock.mockResolvedValue({
user: { id: 'user-1' },
supabase: mock.supabase,
error: null,
})
return mock
}
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('GET /api/bookkeeping/fiscal-periods/[id]/arsredovisning/narrative', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/x'), idParams)
expect(res.status).toBe(401)
})
it('returns 404 when the period does not belong to the company', async () => {
const { enqueue } = setupSupabase()
enqueue({ data: null }) // fiscal_periods ownership check
const res = await GET(createMockRequest('/x'), idParams)
expect(res.status).toBe(404)
})
it('returns the persisted narrative', async () => {
const { enqueue } = setupSupabase()
enqueue({ data: { id: 'period-1' } }) // fiscal_periods ownership check
enqueue({ data: narrativeRow }) // getNarrative
const { status, body } = await parseJsonResponse<{ data: typeof narrativeRow }>(
await GET(createMockRequest('/x'), idParams),
)
expect(status).toBe(200)
expect(body.data.description).toBe('Bolaget bedriver konsultverksamhet.')
})
})
describe('POST /api/bookkeeping/fiscal-periods/[id]/arsredovisning/narrative', () => {
const postReq = (body: unknown) => createMockRequest('/x', { method: 'POST', body })
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(postReq({ description: 'x' }), idParams)
expect(res.status).toBe(401)
})
it('returns 403 when the caller lacks write permission', async () => {
setupSupabase()
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
})
const res = await POST(postReq({ description: 'x' }), idParams)
expect(res.status).toBe(403)
})
it('returns 400 on invalid payload', async () => {
setupSupabase()
const res = await POST(postReq({ agm_date: '2026-13-99' }), idParams)
expect(res.status).toBe(400)
})
it('returns 400 for a personnummer-shaped parent company org number', async () => {
setupSupabase()
const res = await POST(postReq({ parent_company_org_number: '19850101-1234' }), idParams)
expect(res.status).toBe(400)
})
it('accepts a foreign parent company registration identifier', async () => {
const { enqueue } = setupSupabase()
enqueue({ data: { id: 'period-1' } }) // fiscal_periods ownership check
enqueue({ data: null }) // no registrerad submission
enqueue({ data: { ...narrativeRow, parent_company_org_number: 'CHE-123.456.789' } }) // upsert
enqueue({ data: null }) // clear narrative confirmation
const { status, body } = await parseJsonResponse<{ data: typeof narrativeRow }>(
await POST(postReq({ parent_company_org_number: 'CHE-123.456.789' }), idParams),
)
expect(status).toBe(200)
expect(body.data.parent_company_org_number).toBe('CHE-123.456.789')
})
it('returns 400 for a fractional or negative medelantal anställda override', async () => {
setupSupabase()
expect((await POST(postReq({ medelantal_anstallda_override: 1.5 }), idParams)).status).toBe(400)
setupSupabase()
expect((await POST(postReq({ medelantal_anstallda_override: -1 }), idParams)).status).toBe(400)
})
it('saves a whole-number medelantal anställda override and lets null clear it', async () => {
const { enqueue } = setupSupabase()
enqueue({ data: { id: 'period-1' } }) // fiscal_periods ownership check
enqueue({ data: null }) // no registrerad submission
enqueue({ data: { ...narrativeRow, medelantal_anstallda_override: 1 } }) // upsert
enqueue({ data: null }) // clear narrative confirmation
const { status, body } = await parseJsonResponse<{
data: typeof narrativeRow & { medelantal_anstallda_override: number | null }
}>(await POST(postReq({ medelantal_anstallda_override: 1 }), idParams))
expect(status).toBe(200)
expect(body.data.medelantal_anstallda_override).toBe(1)
const cleared = setupSupabase()
cleared.enqueue({ data: { id: 'period-1' } })
cleared.enqueue({ data: null })
cleared.enqueue({ data: { ...narrativeRow, medelantal_anstallda_override: null } })
cleared.enqueue({ data: null })
const res = await POST(postReq({ medelantal_anstallda_override: null }), idParams)
expect(res.status).toBe(200)
})
it('returns 400 when the payload contains an unknown field', async () => {
setupSupabase()
const res = await POST(
postReq({ description: 'x', annual_report_version_id: 'forged-version' }),
idParams,
)
expect(res.status).toBe(400)
})
it('returns 404 when the period does not belong to the company', async () => {
const { enqueue } = setupSupabase()
enqueue({ data: null }) // fiscal_periods ownership check
const res = await POST(postReq({ description: 'x' }), idParams)
expect(res.status).toBe(404)
})
it('saves the narrative for a closed/locked period (regression)', async () => {
const { enqueue } = setupSupabase()
// The ownership check no longer selects lock columns: a closed period
// (Verkställ bokslut done) must still accept narrative saves.
enqueue({ data: { id: 'period-1' } }) // fiscal_periods ownership check
enqueue({ data: null }) // no registrerad submission
enqueue({ data: narrativeRow }) // upsert
enqueue({ data: null }) // clear narrative confirmation
const { status, body } = await parseJsonResponse<{ data: typeof narrativeRow }>(
await POST(postReq({ description: 'Bolaget bedriver konsultverksamhet.' }), idParams),
)
expect(status).toBe(200)
expect(body.data.description).toBe('Bolaget bedriver konsultverksamhet.')
})
it('refuses the save once the årsredovisning is registered at Bolagsverket', async () => {
const { enqueue } = setupSupabase()
enqueue({ data: { id: 'period-1' } }) // fiscal_periods ownership check
enqueue({ data: { id: 'submission-1' } }) // registrerad submission exists
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(postReq({ description: 'x' }), idParams),
)
expect(status).toBe(409)
expect(body.error.code).toBe('ARSREDOVISNING_REGISTERED')
})
})
@@ -0,0 +1,204 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { validateBody } from '@/lib/api/validate'
import {
getNarrative,
upsertNarrative,
} from '@/lib/bokslut/arsredovisning/narrative-service'
import {
isValidParentCompanyIdentifier,
PARENT_COMPANY_IDENTIFIER_ERROR,
} from '@/lib/bokslut/arsredovisning/parent-company-identifier'
// Strip non-printable control characters that would corrupt PDF output or
// mislead a human reader of the årsredovisning. Whitelist printable ASCII
// + every byte ≥ 0x20 (covers Latin-1 + UTF-8 multi-byte sequences) while
// allowing tab/LF/CR for legitimate line breaks.
const stripControlChars = (s: string): string =>
s.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '')
const sanitizedText = (max: number) =>
z
.string()
.max(max)
.transform(stripControlChars)
const PostSchema = z.object({
// Match the DB CHECK lengths exactly so a payload that would fail at the
// storage layer instead returns a clean 400 here. Free-text fields are
// rendered verbatim into the årsredovisning PDF, so we strip ASCII
// control bytes (NUL, ESC, etc.) at the schema layer: otherwise a
// tampered payload could corrupt PDF output or hide content from auditors.
description: sanitizedText(4000).nullable().optional(),
important_events: sanitizedText(4000).nullable().optional(),
resultatdisposition: sanitizedText(2000).nullable().optional(),
proposed_dividend: z
.number()
.min(0)
.max(1_000_000_000_000)
.nullable()
.optional()
.transform((value) =>
value === null || value === undefined ? value : Math.round(value * 100) / 100,
),
// ISO YYYY-MM-DD per the DATE column; null clears it. Validate as a
// real calendar date (not just regex) so '2024-13-99' returns 400 from
// the API instead of bubbling up as a Postgres 500.
agm_date: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.refine(
(s) => {
const d = new Date(`${s}T00:00:00Z`)
return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s
},
{ message: 'Invalid calendar date' },
)
.nullable()
.optional(),
// Disclosure fields per ÅRL 5:13-15 § + BFNAR koncernförhållanden. All
// optional; null clears the override and the builder falls back to
// boilerplate ("Inga." / "Inga skulder förfaller efter mer än fem år.").
// Cap at 1 trillion SEK, well above any realistic Swedish company's
// long-term debt (Volvo Group ~500 G SEK), prevents overflow in PDF
// formatting and downstream numeric handling.
long_term_debt_over_five_years: z
.number()
.min(0)
.max(1_000_000_000_000)
.nullable()
.optional(),
securities_pledged: sanitizedText(4000).nullable().optional(),
contingent_liabilities: sanitizedText(4000).nullable().optional(),
parent_company_name: sanitizedText(200).nullable().optional(),
// Swedish organisationsnummer or a foreign parent's registration identifier
// (a Swiss holding's CHE-number was refused as "ej personnummer" on
// 2026-08-20). Rules live in parent-company-identifier.ts; personnummer-
// shaped values stay rejected. Empty string clears the override.
parent_company_org_number: z
.union([
z.literal(''),
z.string().max(40).refine(isValidParentCompanyIdentifier, {
message: PARENT_COMPANY_IDENTIFIER_ERROR,
}),
])
.nullable()
.optional(),
parent_company_city: sanitizedText(100).nullable().optional(),
// ÅRL 5:20 §: manual medelantal anställda. Null clears the override and
// the note falls back to the FTE average over the employees table. Whole
// employees only (the K2 note and the iXBRL fact are integers); the cap
// matches the DB CHECK.
medelantal_anstallda_override: z.number().int().min(0).max(100_000).nullable().optional(),
long_term_debt_over_five_years_confirmed: z.boolean().optional(),
securities_pledged_confirmed: z.boolean().optional(),
contingent_liabilities_confirmed: z.boolean().optional(),
parent_company_confirmed: z.boolean().optional(),
agm_disposition_outcome: z
.enum(['proposal_approved', 'alternative_decision'])
.nullable()
.optional(),
agm_disposition_decision: sanitizedText(2000).nullable().optional(),
}).strict().superRefine((value, ctx) => {
if (
value.agm_disposition_outcome === 'alternative_decision' &&
!value.agm_disposition_decision?.trim()
) {
ctx.addIssue({
code: 'custom',
path: ['agm_disposition_decision'],
message: 'Årsstämmans alternativa beslut måste beskrivas.',
})
}
})
export const GET = withRouteContext(
'period.arsredovisning_narrative_get',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
try {
// Mirror the POST handler's period-ownership pre-check so a valid
// JWT for company A can't probe / enumerate company B's period IDs
// through this endpoint.
const { data: period } = await supabase
.from('fiscal_periods')
.select('id')
.eq('id', id)
.eq('company_id', companyId)
.maybeSingle()
if (!period) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
const data = await getNarrative(supabase, companyId, id)
return NextResponse.json({ data })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
)
export const POST = withRouteContext(
'period.arsredovisning_narrative_post',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const validation = await validateBody(request, PostSchema)
if (!validation.success) return validation.response
try {
// Verify the fiscal period belongs to the authenticated company before
// writing: defense-in-depth alongside RLS, gives a cleaner 404 than
// the RLS rejection envelope.
//
// Deliberately NOT gated on the bookkeeping period lock: the narrative
// is årsredovisning document text (ÅRL 6 kap.), not räkenskapsinformation
// in the journal, and the normal flow closes the period BEFORE the
// årsredovisning is written. The document freezes when it is filed:
// a Bolagsverket submission registered for this period makes the text
// read-only (what was uploaded is already immutable via the
// arsredovisning_submissions trigger + stored document).
const { data: period } = await supabase
.from('fiscal_periods')
.select('id')
.eq('id', id)
.eq('company_id', companyId)
.maybeSingle()
if (!period) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
// Only 'registrerad' freezes the text. 'avslutad' (case closed WITHOUT
// registration, e.g. withdrawn or rejected) deliberately stays
// editable: the document was never registered at Bolagsverket and a
// refiling needs amendable narrative text.
const { data: registered, error: registeredError } = await supabase
.from('arsredovisning_submissions')
.select('id')
.eq('company_id', companyId)
.eq('fiscal_period_id', id)
.eq('status', 'registrerad')
.limit(1)
.maybeSingle()
if (registeredError) {
throw new Error(`Failed to check submission status: ${registeredError.message}`)
}
if (registered) {
return errorResponseFromCode('ARSREDOVISNING_REGISTERED', log, { requestId })
}
const data = await upsertNarrative(supabase, companyId, user.id, id, validation.data)
const { error: confirmationError } = await supabase
.from('annual_report_profiles')
.update({ narrative_confirmed_at: null })
.eq('company_id', companyId)
.eq('fiscal_period_id', id)
if (confirmationError) {
throw new Error(`Failed to clear narrative confirmation: ${confirmationError.message}`)
}
return NextResponse.json({ data })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
{ requireWrite: true },
)
@@ -0,0 +1,88 @@
import { renderToBuffer } from '@react-pdf/renderer'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { buildCanonicalAnnualReport } from '@/lib/bokslut/arsredovisning/model'
import { getAnnualReportVersion } from '@/lib/bokslut/arsredovisning/version-service'
import { ArsredovisningPDF } from '@/lib/bokslut/arsredovisning/arsredovisning-pdf'
import { ArsredovisningK3PDF } from '@/lib/bokslut/arsredovisning/arsredovisning-k3-pdf'
import type { ArsredovisningData } from '@/lib/bokslut/arsredovisning/types'
export const GET = withRouteContext(
'period.arsredovisning_pdf',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
try {
// Narrative edits come from arsredovisning_narratives now, loaded
// inside buildArsredovisningData. The URL stays clean, no narrative
// text in query params, access logs, or browser history.
const versionId = new URL(request.url).searchParams.get('version')
let versionStatus: string | null = null
let data: ArsredovisningData
if (versionId) {
const version = await getAnnualReportVersion(supabase, companyId, id, versionId)
if (!version) {
return errorResponseFromCode('NOT_FOUND', log, { requestId })
}
versionStatus = version.summary.status
data = structuredClone(version.report_data)
const { data: signatureRows, error: signatureError } = await supabase
.from('arsredovisning_signature_requests')
.select('role, signer_name, signed_at')
.eq('company_id', companyId)
.eq('fiscal_period_id', id)
.eq('annual_report_version_id', versionId)
.order('created_at', { ascending: true })
if (signatureError) {
throw new Error(`Failed to load version signatures: ${signatureError.message}`)
}
data.signatures = (signatureRows ?? []).map((signature) => ({
role: signature.role,
name: signature.signer_name,
signed_at: signature.signed_at,
}))
} else {
const model = await buildCanonicalAnnualReport(supabase, companyId, id, {
stage: 'draft',
includeIxbrl: false,
})
data = model.report
}
// Dispatch on the framework recorded in the data. K3 documents need
// the additional kassaflöde + equity-changes pages + richer noter
// that ArsredovisningK3PDF renders. K2 (the default) keeps the
// existing template byte-for-byte unchanged.
const PdfComponent =
data.accounting_framework === 'k3'
? ArsredovisningK3PDF
: ArsredovisningPDF
const pdfBuffer = await renderToBuffer(PdfComponent({ data }))
// "-utkast" suffix mirrors the existing PDF routes; the file becomes
// "fastställd" only after the signature flow records all signatures.
// Sanitize the dynamic segment so a stray quote / newline in the date
// (defensive, unlikely to ever happen) can't break the header.
const safePeriodEnd = data.fiscal_period.period_end.replace(/[^\w.-]/g, '_')
const suffix = versionStatus && ['signed', 'filed', 'registered'].includes(versionStatus)
? 'papperskopia'
: 'utkast'
const filename = `arsredovisning-${safePeriodEnd}-${suffix}.pdf`
return new Response(new Uint8Array(pdfBuffer), {
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': `inline; filename="${filename}"`,
// ÅR contains company financials + officer names: don't let any
// intermediary cache the document.
'Cache-Control': 'private, no-store, no-cache, must-revalidate',
'Pragma': 'no-cache',
...(versionId ? { 'X-Annual-Report-Version': versionId } : {}),
},
})
} catch (err) {
const message = err instanceof Error ? err.message : ''
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
return errorResponse(err, log, { requestId })
}
},
)
@@ -0,0 +1,38 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { buildCanonicalAnnualReport } from '@/lib/bokslut/arsredovisning/model'
import { getAnnualReportCapabilities } from '@/lib/bokslut/arsredovisning/capabilities'
export const GET = withRouteContext(
'period.arsredovisning_data',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
try {
const model = await buildCanonicalAnnualReport(supabase, companyId, id, {
stage: 'draft',
includeIxbrl: false,
})
return NextResponse.json({
data: model.report,
compliance: {
profile: model.profile,
disclosures: model.disclosures,
eligibility: model.eligibility,
validation: model.validation,
capabilities: getAnnualReportCapabilities(
model.report.accounting_framework,
model.eligibility,
),
},
})
} catch (err) {
const message = err instanceof Error ? err.message : ''
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
}
return errorResponse(err, log, { requestId })
}
},
)
@@ -0,0 +1,197 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
const requireWriteMock = vi.fn()
const createServiceClientMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => createServiceClientMock(),
}))
import { DELETE, PATCH } from '../route'
const versionId = '123e4567-e89b-12d3-a456-426614174000'
const params = {
params: Promise.resolve({ id: 'period-1', signatureId: 'signature-1' }),
}
const signedBody = {
status: 'signed',
annual_report_version_id: versionId,
signing_method: 'paper_original',
evidence_reference: 'archive:A-1',
signed_at: '2026-03-01T10:00:00.000Z',
}
function setup() {
const mock = createQueuedMockSupabase()
requireAuthMock.mockResolvedValue({
user: { id: 'user-1' },
supabase: mock.supabase,
error: null,
})
createServiceClientMock.mockReturnValue(mock.supabase)
return mock
}
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('annual report signature transition', () => {
it('returns 401 without authentication', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect(
(
await PATCH(
createMockRequest('/x', { method: 'PATCH', body: signedBody }),
params,
)
).status,
).toBe(401)
})
it('returns 400 when signed evidence is missing', async () => {
setup()
const response = await PATCH(
createMockRequest('/x', { method: 'PATCH', body: { status: 'signed' } }),
params,
)
expect(response.status).toBe(400)
})
it('returns 400 for a free-text evidence reference', async () => {
setup()
const response = await PATCH(
createMockRequest('/x', {
method: 'PATCH',
body: { ...signedBody, evidence_reference: 'Original i arkiv A-1' },
}),
params,
)
expect(response.status).toBe(400)
})
it('returns 409 when the version is not ready for signature', async () => {
const { enqueue } = setup()
enqueue({ data: null })
const response = await PATCH(
createMockRequest('/x', { method: 'PATCH', body: signedBody }),
params,
)
expect(response.status).toBe(409)
})
it('stores version-bound signature evidence', async () => {
const { enqueue } = setup()
enqueue({
data: {
id: versionId,
status: 'ready_for_signature',
finalized_at: '2026-03-01T08:00:00.000Z',
},
})
enqueue({ data: { id: 'signature-1', annual_report_version_id: versionId, status: 'pending' } })
enqueue({
data: {
id: 'signature-1',
company_id: 'company-1',
fiscal_period_id: 'period-1',
status: 'signed',
signing_method: 'paper_original',
evidence_reference: 'archive:A-1',
},
})
const { status, body } = await parseJsonResponse<{
data: { status: string; evidence_reference: string }
}>(
await PATCH(
createMockRequest('/x', { method: 'PATCH', body: signedBody }),
params,
),
)
expect(status).toBe(200)
expect(body.data.status).toBe('signed')
expect(body.data.evidence_reference).toBe('archive:A-1')
expect(createServiceClientMock).toHaveBeenCalledOnce()
})
it('rejects a signature date before the version was finalized', async () => {
const { enqueue } = setup()
enqueue({
data: {
id: versionId,
status: 'ready_for_signature',
finalized_at: '2026-03-02T08:00:00.000Z',
},
})
enqueue({ data: { id: 'signature-1', annual_report_version_id: versionId, status: 'pending' } })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(
createMockRequest('/x', { method: 'PATCH', body: signedBody }),
params,
),
)
expect(status).toBe(400)
expect(body.error.code).toBe('ARSREDOVISNING_SIGNATURE_DATE_INVALID')
expect(createServiceClientMock).not.toHaveBeenCalled()
})
it('rejects a future signature date', async () => {
const { enqueue } = setup()
enqueue({
data: {
id: versionId,
status: 'ready_for_signature',
finalized_at: '2026-03-01T08:00:00.000Z',
},
})
enqueue({ data: { id: 'signature-1', annual_report_version_id: versionId, status: 'pending' } })
const response = await PATCH(
createMockRequest('/x', {
method: 'PATCH',
body: { ...signedBody, signed_at: '2999-03-01T10:00:00.000Z' },
}),
params,
)
expect(response.status).toBe(400)
})
})
describe('annual report draft signer removal', () => {
it('returns 401 without authentication', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect((await DELETE(createMockRequest('/x', { method: 'DELETE' }), params)).status).toBe(401)
})
it('returns 409 when the signer is already bound to a version', async () => {
const { enqueue } = setup()
enqueue({ data: null, error: null })
expect((await DELETE(createMockRequest('/x', { method: 'DELETE' }), params)).status).toBe(409)
})
it('removes an unbound pending signer', async () => {
const { enqueue } = setup()
enqueue({ data: { id: 'signature-1' }, error: null })
expect((await DELETE(createMockRequest('/x', { method: 'DELETE' }), params)).status).toBe(204)
})
})
@@ -0,0 +1,178 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { validateBody } from '@/lib/api/validate'
import { markSignatureSigned } from '@/lib/bokslut/arsredovisning/signature-service'
import { getSwedishLocalDate } from '@/lib/bookkeeping/engine'
import { createServiceClient } from '@/lib/supabase/server'
// PATCH transitions: pending → signed (manual entry for the paper / outside-
// BankID flow) or pending → declined. Real BankID wiring lands in a future
// phase and uses the same UPDATE with the BankID callback as trigger.
//
// Hardening on every UPDATE:
// - .eq('id', signatureId) + .eq('company_id', companyId)
// - .eq('fiscal_period_id', id from URL): enforces the REST contract so
// /periods/A/signatures/SIG_FROM_B can't bypass the path scope
// - .eq('status', 'pending'): state-machine guard so a signed or declined
// row can't be flipped back
const EvidenceReferenceSchema = z
.string()
.trim()
.min(1)
.max(128)
.regex(/^(archive|document|receipt):[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/)
const PatchSchema = z.discriminatedUnion('status', [
z.object({
status: z.literal('signed'),
annual_report_version_id: z.string().uuid(),
signing_method: z.enum(['paper_original', 'advanced_e_signature', 'bankid']),
evidence_reference: EvidenceReferenceSchema,
signed_at: z.string().datetime().optional(),
}).strict(),
z.object({ status: z.literal('declined') }).strict(),
])
function isSignatureDateAllowed(signedAt: string, finalizedAt: string): boolean {
const signedDate = getSwedishLocalDate(new Date(signedAt))
const finalizedDate = getSwedishLocalDate(new Date(finalizedAt))
const today = getSwedishLocalDate()
return signedDate >= finalizedDate && signedDate <= today
}
export const PATCH = withRouteContext(
'period.arsredovisning_signature_patch',
async (
request,
ctx,
{ params }: { params: Promise<{ id: string; signatureId: string }> },
) => {
const { id: fiscalPeriodId, signatureId } = await params
const { supabase, companyId, log, requestId } = ctx
const validation = await validateBody(request, PatchSchema)
if (!validation.success) return validation.response
try {
if (validation.data.status === 'signed') {
const { data: version, error: versionError } = await supabase
.from('annual_report_versions')
.select('id, status, finalized_at')
.eq('id', validation.data.annual_report_version_id)
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('status', 'ready_for_signature')
.maybeSingle()
if (versionError) {
throw new Error(`Failed to load annual report version: ${versionError.message}`)
}
if (!version?.finalized_at) {
return errorResponseFromCode('ARSREDOVISNING_VERSION_NOT_SIGNABLE', log, {
requestId,
})
}
const { data: requestRow, error: requestError } = await supabase
.from('arsredovisning_signature_requests')
.select('id, annual_report_version_id, status')
.eq('id', signatureId)
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('status', 'pending')
.maybeSingle()
if (requestError) {
throw new Error(`Failed to load annual report signature: ${requestError.message}`)
}
if (
!requestRow ||
(requestRow.annual_report_version_id !== null &&
requestRow.annual_report_version_id !== validation.data.annual_report_version_id)
) {
return NextResponse.json(
{ error: { code: 'SIGNATURE_INVALID_TRANSITION' } },
{ status: 409 },
)
}
const signedAt = validation.data.signed_at ?? new Date().toISOString()
if (!isSignatureDateAllowed(signedAt, version.finalized_at)) {
return errorResponseFromCode('ARSREDOVISNING_SIGNATURE_DATE_INVALID', log, {
requestId,
})
}
const data = await markSignatureSigned(createServiceClient(), companyId, signatureId, {
fiscalPeriodId,
annualReportVersionId: validation.data.annual_report_version_id,
signingMethod: validation.data.signing_method,
evidenceReference: validation.data.evidence_reference,
evidenceRecordedBy: ctx.user.id,
signedAt,
})
return NextResponse.json({ data })
}
const { data, error } = await createServiceClient()
.from('arsredovisning_signature_requests')
.update({ status: 'declined' as const })
.eq('id', signatureId)
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('status', 'pending')
.select('*')
.maybeSingle()
if (error) {
throw new Error(`Failed to update signature: ${error.message}`)
}
if (!data) {
// No row matched: either it doesn't exist, belongs to another
// company / period, or is already signed/declined. Return 409 so
// the client knows the transition is invalid rather than "missing".
return NextResponse.json(
{ error: { code: 'SIGNATURE_INVALID_TRANSITION' } },
{ status: 409 },
)
}
return NextResponse.json({ data })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
{ requireWrite: true },
)
export const DELETE = withRouteContext(
'period.arsredovisning_signature_delete',
async (
_request,
ctx,
{ params }: { params: Promise<{ id: string; signatureId: string }> },
) => {
const { id: fiscalPeriodId, signatureId } = await params
const { supabase, companyId, log, requestId } = ctx
try {
const { data, error } = await supabase
.from('arsredovisning_signature_requests')
.delete()
.eq('id', signatureId)
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('status', 'pending')
.is('annual_report_version_id', null)
.select('id')
.maybeSingle()
if (error) throw new Error(`Failed to remove annual report signer: ${error.message}`)
if (!data) {
return NextResponse.json(
{ error: { code: 'ARSREDOVISNING_SIGNER_ROSTER_LOCKED' } },
{ status: 409 },
)
}
return new NextResponse(null, { status: 204 })
} catch (err) {
return errorResponse(err, log, { requestId })
}
},
{ requireWrite: true },
)
@@ -0,0 +1,102 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET, POST } from '../route'
const params = { params: Promise.resolve({ id: 'period-1' }) }
const validBody = { role: 'Styrelseledamot', signer_name: 'Anna Andersson' }
function setup() {
const mock = createQueuedMockSupabase()
requireAuthMock.mockResolvedValue({
user: { id: 'user-1' },
supabase: mock.supabase,
error: null,
})
return mock
}
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('annual report signer roster route', () => {
it('returns 401 without authentication', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect((await GET(createMockRequest('/x'), params)).status).toBe(401)
})
it('returns 400 for an invalid signer', async () => {
setup()
const response = await POST(
createMockRequest('/x', { method: 'POST', body: { role: 'Administrator' } }),
params,
)
expect(response.status).toBe(400)
})
it('returns 404 for another company period', async () => {
const { enqueue } = setup()
enqueue({ data: null, error: null })
const response = await POST(
createMockRequest('/x', { method: 'POST', body: validBody }),
params,
)
expect(response.status).toBe(404)
})
it('returns 409 for a duplicate unbound signer', async () => {
const { enqueue } = setup()
enqueue({ data: { id: 'period-1' }, error: null })
enqueue({ data: { id: 'signature-existing' }, error: null })
const response = await POST(
createMockRequest('/x', { method: 'POST', body: validBody }),
params,
)
expect(response.status).toBe(409)
})
it('creates a new unbound signer roster slot', async () => {
const { enqueue } = setup()
enqueue({ data: { id: 'period-1' }, error: null })
enqueue({ data: null, error: null })
enqueue({
data: {
id: 'signature-1',
company_id: 'company-1',
fiscal_period_id: 'period-1',
role: 'Styrelseledamot',
signer_name: 'Anna Andersson',
status: 'pending',
annual_report_version_id: null,
},
error: null,
})
const { status, body } = await parseJsonResponse<{
data: { id: string; annual_report_version_id: null }
}>(
await POST(createMockRequest('/x', { method: 'POST', body: validBody }), params),
)
expect(status).toBe(200)
expect(body.data).toMatchObject({ id: 'signature-1', annual_report_version_id: null })
})
})

Some files were not shown because too many files have changed in this diff Show More