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
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,136 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const mockSupabase = {
auth: { getUser: vi.fn() },
from: vi.fn(),
}
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 { PATCH } from '../route'
const mockUser = { id: 'user-1', email: '[email protected]' }
const params = { params: Promise.resolve({ id: 'key-1' }) }
/**
* Chainable proxy over .update().eq().eq().is().select().maybeSingle().
* Records the update payload and every .eq()/.is() filter, so the tests can
* assert on tenant scoping rather than trusting it.
*/
function setupFrom(result: { data?: unknown; error?: unknown }) {
const updateSpy = vi.fn()
const filters: Array<[string, unknown]> = []
mockSupabase.from.mockImplementation(() => {
const chain: Record<string, unknown> = {}
const handler: ProxyHandler<object> = {
get(_t, prop) {
if (prop === 'update') {
return (payload: unknown) => {
updateSpy(payload)
return new Proxy(chain, handler)
}
}
if (prop === 'eq' || prop === 'is') {
return (col: string, val: unknown) => {
filters.push([col, val])
return new Proxy(chain, handler)
}
}
if (prop === 'maybeSingle' || prop === 'single') {
return () =>
Promise.resolve({ data: result.data ?? null, error: result.error ?? null })
}
return () => new Proxy(chain, handler)
},
}
return new Proxy(chain, handler)
})
return { updateSpy, filters }
}
function patch(body: unknown) {
return createMockRequest('/api/settings/api-keys/key-1', { method: 'PATCH', body })
}
beforeEach(() => {
vi.clearAllMocks()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
getActiveCompanyIdMock.mockResolvedValue('company-1')
requireWritePermissionMock.mockResolvedValue({ ok: true })
})
describe('PATCH /api/settings/api-keys/[id]', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await PATCH(patch({ unattended_commit_limit: 5000 }), params)
expect(res.status).toBe(401)
})
it('sets a ceiling and scopes the update to the active company and unrevoked keys', async () => {
const { updateSpy, filters } = setupFrom({
data: { id: 'key-1', unattended_commit_limit: 5000 },
})
const res = await PATCH(patch({ unattended_commit_limit: 5000 }), params)
const { status, body } = await parseJsonResponse<{
data: { unattended_commit_limit: number }
}>(res)
expect(status).toBe(200)
expect(body.data.unattended_commit_limit).toBe(5000)
expect(updateSpy).toHaveBeenCalledWith({ unattended_commit_limit: 5000 })
// Tenant scoping is the whole security story of this route: without the
// company_id filter, any authenticated user could raise any key's
// authority by guessing an id.
expect(filters).toContainEqual(['company_id', 'company-1'])
expect(filters).toContainEqual(['id', 'key-1'])
expect(filters).toContainEqual(['revoked_at', null])
})
it('accepts null to clear the ceiling', async () => {
const { updateSpy } = setupFrom({ data: { id: 'key-1', unattended_commit_limit: null } })
const res = await PATCH(patch({ unattended_commit_limit: null }), params)
expect(res.status).toBe(200)
expect(updateSpy).toHaveBeenCalledWith({ unattended_commit_limit: null })
})
it('rejects zero, negatives and non-numbers with 400', async () => {
setupFrom({ data: { id: 'key-1' } })
for (const bad of [0, -1, '5000', {}]) {
const res = await PATCH(patch({ unattended_commit_limit: bad }), params)
expect(res.status).toBe(400)
}
})
it('requires the field rather than treating an empty body as "clear it"', async () => {
setupFrom({ data: { id: 'key-1' } })
const res = await PATCH(patch({}), params)
expect(res.status).toBe(400)
})
it('returns 404 when the key belongs to another company or is revoked', async () => {
setupFrom({ data: null })
const res = await PATCH(patch({ unattended_commit_limit: 5000 }), params)
expect(res.status).toBe(404)
})
it('returns 500 when the update fails', async () => {
setupFrom({ error: { message: 'boom' } })
const res = await PATCH(patch({ unattended_commit_limit: 5000 }), params)
expect(res.status).toBe(500)
})
})
+82
View File
@@ -0,0 +1,82 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* Approval authority in SEK: the largest amount this key may commit with no
* human in the loop. null clears the ceiling (unlimited, the default).
*
* Bounded at 1 000 000 000 so a typo cannot store a number the numeric(14,2)
* column would reject at insert time with a raw Postgres error. The DB CHECK
* (> 0) is the real guarantee; this is the friendly message in front of it.
*/
const patchSchema = z.object({
unattended_commit_limit: z.number().positive().max(1_000_000_000).nullable(),
})
/**
* DELETE /api/settings/api-keys/[id]: Revoke an API key (soft delete)
*/
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
'api_key.revoke',
async (_request, ctx, { params }) => {
const { id } = await params
const { supabase, companyId } = ctx
const { error } = await supabase
.from('api_keys')
.update({ revoked_at: new Date().toISOString() })
.eq('id', id)
.eq('company_id', companyId)
.is('revoked_at', null)
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ success: true })
},
{ requireWrite: true },
)
/**
* PATCH /api/settings/api-keys/[id]: set the key's unattended commit limit.
*
* Deliberately narrow: name and scopes are NOT editable here. Silently
* widening a key's scopes after the fact would defeat the point of showing the
* scope list at creation, and the separation-of-duties check
* (findStageApproveConflict) runs only on POST.
*/
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
'api_key.update',
async (request, ctx, { params }) => {
const { id } = await params
const { supabase, companyId } = ctx
const validation = await validateBody(request, patchSchema)
if (!validation.success) return validation.response
// Revoked keys are deliberately excluded: raising a limit on a key that no
// longer authenticates reads as re-enabling it, and it does not.
const { data, error } = await supabase
.from('api_keys')
.update({ unattended_commit_limit: validation.data.unattended_commit_limit })
.eq('id', id)
.eq('company_id', companyId)
.is('revoked_at', null)
.select('id, unattended_commit_limit')
.maybeSingle()
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
if (!data) {
return NextResponse.json({ error: 'API-nyckeln hittades inte.' }, { status: 404 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)
@@ -0,0 +1,246 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
// ── Mocks ──────────────────────────────────────────────────────────
// withRouteContext resolves auth via requireAuth (createClient under the hood),
// the active company via getActiveCompanyId, and the write gate via
// requireWritePermission. Mock all three so we can drive each branch.
const mockSupabase = {
auth: { getUser: vi.fn() },
from: vi.fn(),
}
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 { POST } from '../route'
const mockUser = { id: 'user-1', email: '[email protected]' }
// Records the payload passed to .insert(), and lets us program the count
// returned by the quota pre-check and the row returned by the insert.
function setupFrom(opts: {
count?: number | null
insertResult?: { data?: unknown; error?: unknown }
}) {
const insertSpy = vi.fn()
mockSupabase.from.mockImplementation(() => {
// The quota pre-check: .select(..., { head: true }).eq().is() → resolves
// to { count }. The insert: .insert().select().single() → resolves to the
// row. We expose both via a single chainable proxy whose terminal value
// depends on whether insert() was called.
let isInsert = false
const result = () =>
isInsert
? Promise.resolve({
data: opts.insertResult?.data ?? null,
error: opts.insertResult?.error ?? null,
})
: Promise.resolve({ count: opts.count ?? 0, data: null, error: null })
const chain: Record<string, unknown> = {}
const handler: ProxyHandler<object> = {
get(_t, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) => resolve(result() as unknown)
}
if (prop === 'insert') {
return (payload: unknown) => {
isInsert = true
insertSpy(payload)
return new Proxy(chain, handler)
}
}
if (prop === 'single' || prop === 'maybeSingle') {
return () => result()
}
return () => new Proxy(chain, handler)
},
}
return new Proxy(chain, handler)
})
return { insertSpy }
}
beforeEach(() => {
vi.clearAllMocks()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
getActiveCompanyIdMock.mockResolvedValue('company-1')
requireWritePermissionMock.mockResolvedValue({ ok: true })
})
describe('POST /api/settings/api-keys', () => {
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(
createMockRequest('/api/settings/api-keys', {
method: 'POST',
body: { name: 'k', scopes: ['reports:read'] },
}),
)
expect(res.status).toBe(401)
})
it('returns 400 for an invalid scope', async () => {
setupFrom({ count: 0 })
const res = await POST(
createMockRequest('/api/settings/api-keys', {
method: 'POST',
body: { name: 'k', scopes: ['totally:bogus'] },
}),
)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(400)
expect(body.error.code).toBe('API_KEY_SCOPE_INVALID')
})
it('returns 400 for the reserved OAuth marker name (would fake a Claude connection)', async () => {
const { insertSpy } = setupFrom({ count: 0 })
const res = await POST(
createMockRequest('/api/settings/api-keys', {
method: 'POST',
body: { name: ' MCP-klient (OAuth) ', scopes: ['reports:read'] },
}),
{ params: Promise.resolve({}) },
)
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { field: string; reason: string } }
}>(res)
expect(status).toBe(400)
expect(body.error.code).toBe('VALIDATION_ERROR')
expect(body.error.details).toMatchObject({ field: 'name', reason: 'reserved' })
expect(insertSpy).not.toHaveBeenCalled()
})
it('returns 409 API_KEY_SOD_CONFLICT for stage+approve without acknowledgement', async () => {
setupFrom({ count: 0 })
const res = await POST(
createMockRequest('/api/settings/api-keys', {
method: 'POST',
body: {
name: 'k',
scopes: ['invoices:write', 'pending_operations:approve'],
},
}),
)
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { conflicting_scope: string; approve_scope: string } }
}>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('API_KEY_SOD_CONFLICT')
expect(body.error.details.conflicting_scope).toBe('invoices:write')
expect(body.error.details.approve_scope).toBe('pending_operations:approve')
})
it('records sod_acknowledged_at/by in the insert when acknowledge_sod is true', async () => {
const { insertSpy } = setupFrom({
count: 0,
insertResult: {
data: {
id: 'ak-1',
key_prefix: 'gnubok_sk_abcd',
name: 'k',
scopes: ['invoices:write', 'pending_operations:approve'],
created_at: '2026-06-05T10:00:00Z',
},
},
})
const res = await POST(
createMockRequest('/api/settings/api-keys', {
method: 'POST',
body: {
name: 'k',
scopes: ['invoices:write', 'pending_operations:approve'],
acknowledge_sod: true,
},
}),
)
const { status, body } = await parseJsonResponse<{ data: { key: string } }>(res)
expect(status).toBe(200)
expect(body.data.key).toMatch(/^gnubok_sk_/)
expect(insertSpy).toHaveBeenCalledTimes(1)
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
expect(payload.sod_acknowledged_by).toBe('user-1')
expect(typeof payload.sod_acknowledged_at).toBe('string')
// ISO timestamp
expect(payload.sod_acknowledged_at).toMatch(/^\d{4}-\d{2}-\d{2}T/)
})
it('creates a clean key without approve scope and does not set SoD fields', async () => {
const { insertSpy } = setupFrom({
count: 0,
insertResult: {
data: {
id: 'ak-2',
key_prefix: 'gnubok_sk_efgh',
name: 'reader',
scopes: ['reports:read'],
created_at: '2026-06-05T10:00:00Z',
},
},
})
const res = await POST(
createMockRequest('/api/settings/api-keys', {
method: 'POST',
body: { name: 'reader', scopes: ['reports:read'] },
}),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
expect(payload).not.toHaveProperty('sod_acknowledged_at')
expect(payload).not.toHaveProperty('sod_acknowledged_by')
expect(payload.scopes).toEqual(['reports:read'])
// Default mode is live, bound to the active company.
expect(payload.mode).toBe('live')
expect(payload.company_id).toBe('company-1')
})
it('creates a test key bound to the active company with mode=test', async () => {
const { insertSpy } = setupFrom({
count: 0,
insertResult: {
data: {
id: 'ak-3',
key_prefix: 'gnubok_sk_test_abc',
name: 'pilot',
scopes: ['reports:read'],
mode: 'test',
created_at: '2026-06-05T10:00:00Z',
},
},
})
const res = await POST(
createMockRequest('/api/settings/api-keys', {
method: 'POST',
body: { name: 'pilot', scopes: ['reports:read'], mode: 'test' },
}),
)
const { status, body } = await parseJsonResponse<{ data: { key: string } }>(res)
expect(status).toBe(200)
// Real generateApiKey('test') runs: the returned secret carries the infix.
expect(body.data.key).toMatch(/^gnubok_sk_test_/)
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
expect(payload.mode).toBe('test')
// Test keys are simulation-only: they bind to the active company (the v1
// wrapper forces dry-run so they never persist).
expect(payload.company_id).toBe('company-1')
})
})
+166
View File
@@ -0,0 +1,166 @@
import { NextResponse } from 'next/server'
import {
generateApiKey,
DEFAULT_SCOPES,
OAUTH_MCP_KEY_NAME,
validateScopes,
findStageApproveConflict,
} from '@/lib/auth/api-keys'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { ApiKeyMode, ApiKeyScope } from '@/lib/auth/api-keys'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/** GET /api/settings/api-keys: list the company's API keys (key value never returned). */
export const GET = withRouteContext(
'api_key.list',
async (_request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
// Both live and test keys for the active company. (Test keys are bound to the
// active company too: they're simulation-only, so they never write real data.)
const { data, error } = await supabase
.from('api_keys')
.select('id, key_prefix, name, scopes, mode, rate_limit_rpm, unattended_commit_limit, last_used_at, revoked_at, created_at')
.eq('company_id', companyId)
.order('created_at', { ascending: false })
if (error) {
log.error('api_keys list failed', error)
return errorResponse(error, log, { requestId })
}
return NextResponse.json({ data })
},
)
/**
* POST /api/settings/api-keys: create a new API key.
*
* Returns the full key exactly once; after this the prefix is the only
* stored representation.
*/
export const POST = withRouteContext(
'api_key.create',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
let name = 'Unnamed key'
let scopes: ApiKeyScope[] = DEFAULT_SCOPES
let acknowledgeSod = false
let mode: ApiKeyMode = 'live'
try {
const body = await request.json()
if (body.name && typeof body.name === 'string') {
name = body.name.slice(0, 100)
}
acknowledgeSod = body.acknowledge_sod === true
if (body.mode === 'test') mode = 'test'
const parsed = validateScopes(body.scopes)
if (parsed) {
scopes = parsed
} else if (body.scopes !== undefined) {
return errorResponseFromCode('API_KEY_SCOPE_INVALID', log, {
requestId,
details: { received: body.scopes },
})
}
} catch {
// Empty body: use defaults.
}
// The OAuth token route's key name is the marker the Hem checklist reads
// as "connected to Claude" (there is no source column). A hand-minted key
// with that name would tick the step without any connection, so the name
// is reserved for the OAuth path.
if (name.trim() === OAUTH_MCP_KEY_NAME) {
return errorResponseFromCode('VALIDATION_ERROR', log, {
requestId,
details: { field: 'name', reason: 'reserved', reserved: OAUTH_MCP_KEY_NAME },
})
}
// Both live and test keys bind to the active company. A test key is
// simulation-only (the v1 wrapper forces dry-run on every write) so it can
// safely point at the real company without ever persisting anything.
// Segregation of duties: warn + require explicit acknowledgement (not block)
// when a single key both stages bookkeeping AND can approve it. Surfacing a
// 409 lets the UI raise an explicit confirm dialog and the agent inform the
// user before re-POSTing with acknowledge_sod: true.
const conflictingScope = findStageApproveConflict(scopes)
if (conflictingScope && !acknowledgeSod) {
return errorResponseFromCode('API_KEY_SOD_CONFLICT', log, {
requestId,
details: {
conflicting_scope: conflictingScope,
approve_scope: 'pending_operations:approve',
},
})
}
const sodAcknowledgedAt = conflictingScope ? new Date().toISOString() : null
const { count } = await supabase
.from('api_keys')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.is('revoked_at', null)
if (count !== null && count >= 10) {
return errorResponseFromCode('API_KEY_QUOTA_EXCEEDED', log, {
requestId,
details: { activeCount: count, limit: 10 },
})
}
const { key, hash, prefix } = generateApiKey(mode)
const { data, error } = await supabase
.from('api_keys')
.insert({
user_id: user.id,
company_id: companyId,
key_hash: hash,
key_prefix: prefix,
name,
scopes,
mode,
...(sodAcknowledgedAt
? { sod_acknowledged_at: sodAcknowledgedAt, sod_acknowledged_by: user.id }
: {}),
})
.select('id, key_prefix, name, scopes, mode, created_at')
.single()
if (error) {
log.error('api_key insert failed', error)
return errorResponseFromCode('API_KEY_CREATE_FAILED', log, {
requestId,
details: { reason: getUserErrorMessage(error) },
})
}
if (sodAcknowledgedAt) {
// High-risk security event: the creator self-attested the stage+approve
// combination. The durable record is the sod_acknowledged_* pair on the
// key row; this structured entry additionally lands the acceptance in
// the logging pipeline (ASVS V16.1.1 / SOC 2 CC6.1).
log.warn('api_key.sod_acknowledged', {
keyId: data.id,
keyPrefix: data.key_prefix,
conflictingScope,
scopes,
acknowledgedBy: user.id,
companyId,
})
}
return NextResponse.json({
data: {
...data,
key, // only time the full key is returned
},
})
},
{ requireWrite: true },
)
@@ -0,0 +1,284 @@
/**
* Tests for PUT /api/settings/booking-templates/[id].
*
* The validated body is spread straight into .update(), so the write set must
* be exactly the fields the caller named. UpdateBookingTemplateSchema carries
* no .default() today, so this route was never exploitable; the tests lock in
* the property so a future .default() on the schema cannot turn a rename into a
* silent rewrite of the template's lines, category, or entity_type.
*/
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 { PUT } from '../route'
interface CapturedCall {
method: string
args: unknown[]
}
/** Chainable builder recording calls; resolves queued {data,error} 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', '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 })
return b
}
return {
supabase: {
from: (table: string) => {
calls.push({ method: 'from', args: [table] })
return makeBuilder()
},
},
calls,
}
}
const idParams = { params: Promise.resolve({ id: 'tpl-1' }) }
const validLines = [
{ account: '5010', label: 'Hyra', side: 'debit', type: 'business' },
{ account: '1930', label: 'Bank', side: 'credit', type: 'settlement' },
]
/** The pre-update fetch result for a template owned by the active company. */
const OWN_TEMPLATE = {
data: { id: 'tpl-1', company_id: 'company-1', team_id: null, is_system: false },
}
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
function auth(supabase: unknown) {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
}
function updatePayload(calls: CapturedCall[]): Record<string, unknown> {
return calls.find((c) => c.method === 'update')?.args[0] as Record<string, unknown>
}
describe('PUT /api/settings/booking-templates/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
expect((await PUT(req, idParams)).status).toBe(401)
})
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/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
expect((await PUT(req, idParams)).status).toBe(403)
})
it('returns 400 for an invalid body', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
// A template needs at least two lines (double entry).
body: { lines: [validLines[0]] },
})
const { status } = await parseJsonResponse(await PUT(req, idParams))
expect(status).toBe(400)
})
it('returns 500 when the update fails', async () => {
const { supabase } = createCapturingSupabase([OWN_TEMPLATE, { error: { message: 'boom' } }])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
const { status } = await parseJsonResponse(await PUT(req, idParams))
expect(status).toBe(500)
})
it('returns 404 when the template does not exist', async () => {
// .single() used to turn zero rows into a PGRST116 ERROR, so not-found
// surfaced as 500 and the 404 branch was dead.
const { supabase, calls } = createCapturingSupabase([{ data: null }])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
const { status, body } = await parseJsonResponse<{ error: string }>(await PUT(req, idParams))
expect(status).toBe(404)
expect(body.error).toBe('Mallen hittades inte')
expect(calls.find((c) => c.method === 'update')).toBeUndefined()
})
it("returns 404 for another company's template without touching it", async () => {
// RLS is membership-wide: a user who belongs to companies A and B can see
// B's templates while acting in A. The route must scope to the ACTIVE
// company, so B's template reads as not-found here and no update runs.
const { supabase, calls } = createCapturingSupabase([
{ data: { id: 'tpl-1', company_id: 'company-2', team_id: null, is_system: false } },
])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
const { status, body } = await parseJsonResponse<{ error: string }>(await PUT(req, idParams))
expect(status).toBe(404)
expect(body.error).toBe('Mallen hittades inte')
expect(calls.find((c) => c.method === 'update')).toBeUndefined()
})
it('returns 404 for a system template', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { id: 'tpl-1', company_id: null, team_id: null, is_system: true } },
])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
const { status } = await parseJsonResponse(await PUT(req, idParams))
expect(status).toBe(404)
expect(calls.find((c) => c.method === 'update')).toBeUndefined()
})
it("updates a team template shared with the active company's team", async () => {
// Team templates carry company_id NULL: a blind company_id filter would
// have broken them. The scope check goes through the company's team_id.
const { supabase, calls } = createCapturingSupabase([
{ data: { id: 'tpl-1', company_id: null, team_id: 'team-1', is_system: false } },
{ data: { team_id: 'team-1' } }, // companies lookup
{ data: { id: 'tpl-1', name: 'Nytt namn' } }, // update
])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
const { status } = await parseJsonResponse(await PUT(req, idParams))
expect(status).toBe(200)
expect(updatePayload(calls)).toEqual({ name: 'Nytt namn' })
})
it("returns 404 for another team's template", async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { id: 'tpl-1', company_id: null, team_id: 'team-other', is_system: false } },
{ data: { team_id: 'team-1' } }, // companies lookup
])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
const { status } = await parseJsonResponse(await PUT(req, idParams))
expect(status).toBe(404)
expect(calls.find((c) => c.method === 'update')).toBeUndefined()
})
it('updates the template on the happy path', async () => {
const { supabase } = createCapturingSupabase([
OWN_TEMPLATE,
{ data: { id: 'tpl-1', name: 'Nytt namn' } },
])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
const { status, body } = await parseJsonResponse<{ data: { name: string } }>(
await PUT(req, idParams),
)
expect(status).toBe(200)
expect(body.data.name).toBe('Nytt namn')
})
it('writes only the field the caller named', async () => {
const { supabase, calls } = createCapturingSupabase([OWN_TEMPLATE, { data: { id: 'tpl-1' } }])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
expect((await PUT(req, idParams)).status).toBe(200)
expect(Object.keys(updatePayload(calls))).toEqual(['name'])
})
it('leaves lines, category and entity_type alone on a name-only update', async () => {
const { supabase, calls } = createCapturingSupabase([OWN_TEMPLATE, { data: { id: 'tpl-1' } }])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn' },
})
await PUT(req, idParams)
const payload = updatePayload(calls)
for (const field of ['lines', 'category', 'entity_type', 'description']) {
expect(payload, `${field} must not be written by a name-only PUT`).not.toHaveProperty(field)
}
})
it('takes a supplied lines array wholesale', async () => {
const { supabase, calls } = createCapturingSupabase([OWN_TEMPLATE, { data: { id: 'tpl-1' } }])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { lines: validLines },
})
expect((await PUT(req, idParams)).status).toBe(200)
expect(updatePayload(calls)).toEqual({ lines: validLines })
})
it('drops unknown keys instead of forwarding them to the update', async () => {
const { supabase, calls } = createCapturingSupabase([OWN_TEMPLATE, { data: { id: 'tpl-1' } }])
auth(supabase)
const req = createMockRequest('/api/settings/booking-templates/tpl-1', {
method: 'PUT',
body: { name: 'Nytt namn', is_system: false, company_id: 'other' },
})
expect((await PUT(req, idParams)).status).toBe(200)
expect(Object.keys(updatePayload(calls))).toEqual(['name'])
})
})
@@ -0,0 +1,198 @@
/**
* Tests for POST/DELETE /api/settings/booking-templates/[id]/hide.
*
* Hiding is opt-in and per-company: a hide row is written for the ACTIVE
* company only, and only for system templates (company/team templates have a
* real delete path already). The tests lock in both properties, plus the
* idempotent unhide.
*/
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 { POST, DELETE } from '../route'
interface CapturedCall {
method: string
args: unknown[]
}
/** Chainable builder recording calls; resolves queued {data,error} 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', 'upsert', 'delete', 'maybeSingle']) {
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
}
return {
supabase: {
from: (table: string) => {
calls.push({ method: 'from', args: [table] })
return makeBuilder()
},
},
calls,
}
}
const idParams = { params: Promise.resolve({ id: 'tpl-1' }) }
const SYSTEM_TEMPLATE = {
data: { id: 'tpl-1', is_system: true, is_active: true },
}
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
function auth(supabase: unknown) {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
}
function req(method: 'POST' | 'DELETE') {
return createMockRequest('/api/settings/booking-templates/tpl-1/hide', { method })
}
describe('POST /api/settings/booking-templates/[id]/hide', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect((await POST(req('POST'), idParams)).status).toBe(401)
})
it('returns 403 for a viewer', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
expect((await POST(req('POST'), idParams)).status).toBe(403)
})
it('returns 404 when the template does not exist', async () => {
const { supabase, calls } = createCapturingSupabase([{ data: null }])
auth(supabase)
const { status } = await parseJsonResponse(await POST(req('POST'), idParams))
expect(status).toBe(404)
expect(calls.find((c) => c.method === 'upsert')).toBeUndefined()
})
it('returns 404 for a retired (inactive) template', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { id: 'tpl-1', is_system: true, is_active: false } },
])
auth(supabase)
const { status } = await parseJsonResponse(await POST(req('POST'), idParams))
expect(status).toBe(404)
expect(calls.find((c) => c.method === 'upsert')).toBeUndefined()
})
it('returns 400 for a non-system template', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: { id: 'tpl-1', is_system: false, is_active: true } },
])
auth(supabase)
const { status } = await parseJsonResponse(await POST(req('POST'), idParams))
expect(status).toBe(400)
expect(calls.find((c) => c.method === 'upsert')).toBeUndefined()
})
it('returns 500 when the upsert fails', async () => {
const { supabase } = createCapturingSupabase([
SYSTEM_TEMPLATE,
{ error: { message: 'boom' } },
])
auth(supabase)
const { status } = await parseJsonResponse(await POST(req('POST'), idParams))
expect(status).toBe(500)
})
it('hides a system template for the active company on the happy path', async () => {
const { supabase, calls } = createCapturingSupabase([SYSTEM_TEMPLATE, { data: null }])
auth(supabase)
const { status } = await parseJsonResponse(await POST(req('POST'), idParams))
expect(status).toBe(200)
const upsert = calls.find((c) => c.method === 'upsert')
expect(upsert?.args[0]).toEqual({
template_id: 'tpl-1',
company_id: 'company-1',
hidden_by: 'user-1',
})
// ignoreDuplicates is load-bearing: the table has no UPDATE policy, so a
// DO UPDATE conflict arm would be rejected by RLS on a concurrent re-hide.
expect(upsert?.args[1]).toEqual({
onConflict: 'template_id,company_id',
ignoreDuplicates: true,
})
})
})
describe('DELETE /api/settings/booking-templates/[id]/hide', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect((await DELETE(req('DELETE'), idParams)).status).toBe(401)
})
it('returns 403 for a viewer', async () => {
const { supabase } = createCapturingSupabase([])
auth(supabase)
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
expect((await DELETE(req('DELETE'), idParams)).status).toBe(403)
})
it('returns 500 when the delete fails', async () => {
const { supabase } = createCapturingSupabase([{ error: { message: 'boom' } }])
auth(supabase)
const { status } = await parseJsonResponse(await DELETE(req('DELETE'), idParams))
expect(status).toBe(500)
})
it('unhides scoped to the active company, idempotently', async () => {
// Zero deleted rows is still success: unhide may race a double click.
const { supabase, calls } = createCapturingSupabase([{ data: null }])
auth(supabase)
const { status } = await parseJsonResponse(await DELETE(req('DELETE'), idParams))
expect(status).toBe(200)
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
expect(eqCalls).toContainEqual(['template_id', 'tpl-1'])
expect(eqCalls).toContainEqual(['company_id', 'company-1'])
})
})
@@ -0,0 +1,82 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* POST /api/settings/booking-templates/[id]/hide
*
* Hide a system template for the current company. Opt-in and per-company:
* nothing is hidden by default, and a hide row never affects any other
* company. Company/team templates are excluded on purpose: they already have
* a real delete path, and hiding them would just be a confusing second one.
*
* DELETE /api/settings/booking-templates/[id]/hide
*
* Unhide (restore) the template for the current company.
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'booking_template.hide',
async (_request, ctx, { params }) => {
const { id } = await params
const { supabase, companyId, user } = ctx
// Only an existing, active SYSTEM template can be hidden. RLS on
// booking_template_hidden scopes the write to the active company; this
// check scopes it to the right kind of template.
const { data: template, error: templateError } = await supabase
.from('booking_template_library')
.select('id, is_system, is_active')
.eq('id', id)
.maybeSingle()
if (templateError) {
return NextResponse.json({ error: getUserErrorMessage(templateError) }, { status: 500 })
}
if (!template || !template.is_active) {
return NextResponse.json({ error: 'Template not found' }, { status: 404 })
}
if (!template.is_system) {
return NextResponse.json({ error: 'Only system templates can be hidden' }, { status: 400 })
}
// ignoreDuplicates makes the conflict arm DO NOTHING. The table has no
// UPDATE policy (insert-or-delete only), so a DO UPDATE arm would be
// rejected by RLS and turn a concurrent re-hide into a 500.
const { error } = await supabase
.from('booking_template_hidden')
.upsert(
{ template_id: id, company_id: companyId, hidden_by: user.id },
{ onConflict: 'template_id,company_id', ignoreDuplicates: true },
)
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data: { success: true } })
},
{ requireWrite: true },
)
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
'booking_template.unhide',
async (_request, ctx, { params }) => {
const { id } = await params
const { supabase, companyId } = ctx
// Deleting a row that does not exist is a no-op success: unhide is
// idempotent, and the panel may race a double click.
const { error } = await supabase
.from('booking_template_hidden')
.delete()
.eq('template_id', id)
.eq('company_id', companyId)
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data: { success: true } })
},
{ requireWrite: true },
)
@@ -0,0 +1,94 @@
import { BookingTemplateLineSchema, BookingTemplateCategorySchema, BookingTemplateEntityTypeSchema } from '@/lib/bookkeeping/booking-template-schemas'
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { z } from 'zod'
import { validateBody } from '@/lib/api/validate'
import { sparsePatchBody } from '@/lib/api/sparse-patch'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const UpdateBookingTemplateSchema = z.object({
name: z.string().min(1).max(200).optional(),
description: z.string().max(2000).optional(),
category: BookingTemplateCategorySchema.optional(),
entity_type: BookingTemplateEntityTypeSchema.optional(),
lines: z.array(BookingTemplateLineSchema).min(2).optional(),
})
/**
* PUT /api/settings/booking-templates/[id]
* Update a non-system template belonging to the active company (or its team).
*/
export const PUT = withRouteContext<{ params: Promise<{ id: string }> }>(
'booking_template.update',
async (request, ctx, { params }) => {
const { id } = await params
const { supabase, companyId } = ctx
// result.data is spread straight into .update(), so it must carry only the
// fields the caller named. UpdateBookingTemplateSchema has no .default()
// today; sparsePatchBody makes that a structural property rather than a
// thing a future edit to the schema can quietly undo.
const result = await validateBody(request, sparsePatchBody(UpdateBookingTemplateSchema))
if (!result.success) return result.response
// Read the template first so a missing row is a clean 404: .single() on
// the update chain reported zero rows as a PGRST116 ERROR, which fell into
// the 500 branch and left the 404 below unreachable.
const { data: existing, error: fetchError } = await supabase
.from('booking_template_library')
.select('id, company_id, team_id, is_system')
.eq('id', id)
.maybeSingle()
if (fetchError) {
return NextResponse.json({ error: getUserErrorMessage(fetchError) }, { status: 500 })
}
// System templates are never editable (customize duplicates them instead);
// reported as not-found rather than forbidden, matching the RLS view.
if (!existing || existing.is_system) {
return NextResponse.json({ error: 'Mallen hittades inte' }, { status: 404 })
}
// Defense in depth alongside RLS (which is membership-wide): only
// templates scoped to the ACTIVE company, or shared with its team, are
// editable in this context. Without this, a user who belongs to several
// companies could edit company B's template while acting in company A.
// Team templates carry company_id NULL, so a plain company_id filter on
// the update would break them: check the applicable scope explicitly.
if (existing.company_id) {
if (existing.company_id !== companyId) {
return NextResponse.json({ error: 'Mallen hittades inte' }, { status: 404 })
}
} else if (existing.team_id) {
const { data: company } = await supabase
.from('companies')
.select('team_id')
.eq('id', companyId)
.maybeSingle()
if (!company?.team_id || company.team_id !== existing.team_id) {
return NextResponse.json({ error: 'Mallen hittades inte' }, { status: 404 })
}
} else {
// Non-system template with neither company nor team scope should not
// exist; refuse rather than let anyone edit an orphan.
return NextResponse.json({ error: 'Mallen hittades inte' }, { status: 404 })
}
// RLS prevents updating system templates; is_system is re-checked here so
// the guard holds even on a service-role client.
const { data, error } = await supabase
.from('booking_template_library')
.update(result.data)
.eq('id', id)
.eq('is_system', false)
.select()
.maybeSingle()
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
// The row can vanish between the scope check and the update.
if (!data) return NextResponse.json({ error: 'Mallen hittades inte' }, { status: 404 })
return NextResponse.json({ data })
},
{ requireWrite: true },
)
@@ -0,0 +1,38 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* POST /api/settings/booking-templates/[id]/touch
*
* Record that this template was applied by the current company. Upserts the
* (template_id, company_id) row in booking_template_usage, refreshing
* last_used_at. Used by the template pickers to drive MRU ordering.
*
* Fire-and-forget from the client: errors are non-fatal.
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'booking_template.touch',
async (_request, ctx, { params }) => {
const { id } = await params
const { supabase, companyId } = ctx
const { error } = await supabase
.from('booking_template_usage')
.upsert(
{
template_id: id,
company_id: companyId,
last_used_at: new Date().toISOString(),
},
{ onConflict: 'template_id,company_id' },
)
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data: { success: true } })
},
{ requireWrite: true },
)
@@ -0,0 +1,104 @@
/**
* Tests for GET /api/settings/booking-templates.
*
* Focused on the is_hidden decoration: every row carries the per-company flag,
* a failed hidden lookup falls back to "nothing hidden" (showing extra
* templates is the safe direction), and hidden rows are still RETURNED so the
* settings panel can offer restore; filtering is the pickers' job.
*/
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('11111111-1111-4111-8111-111111111111'),
requireCompanyId: vi.fn().mockResolvedValue('11111111-1111-4111-8111-111111111111'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET } from '../route'
/** Chainable builder resolving queued {data,error} per from() in call order. */
function createQueuedSupabase(results: { data?: unknown; error?: 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', 'or', 'order', 'maybeSingle']) {
b[m] = () => b
}
b.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null })
return b
}
return { from: () => makeBuilder() }
}
const TEMPLATES = [
{ id: 'tpl-1', name: 'Bankavgift', is_system: true },
{ id: 'tpl-2', name: 'Eget uttag', is_system: true },
]
beforeEach(() => {
vi.clearAllMocks()
})
function auth(supabase: unknown) {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
}
const req = () => createMockRequest('/api/settings/booking-templates', { method: 'GET' })
describe('GET /api/settings/booking-templates', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
expect((await GET(req(), { params: Promise.resolve({}) })).status).toBe(401)
})
it('marks hidden templates but still returns them', async () => {
// from() order: companies, then library / usage / hidden.
const supabase = createQueuedSupabase([
{ data: { team_id: null } },
{ data: TEMPLATES },
{ data: [] },
{ data: [{ template_id: 'tpl-2' }] },
])
auth(supabase)
const { status, body } = await parseJsonResponse<{
data: { id: string; is_hidden: boolean }[]
}>(await GET(req(), { params: Promise.resolve({}) }))
expect(status).toBe(200)
expect(body.data).toHaveLength(2)
expect(body.data.find((t) => t.id === 'tpl-1')?.is_hidden).toBe(false)
expect(body.data.find((t) => t.id === 'tpl-2')?.is_hidden).toBe(true)
})
it('falls back to nothing hidden when the hidden lookup fails', async () => {
const supabase = createQueuedSupabase([
{ data: { team_id: null } },
{ data: TEMPLATES },
{ data: [] },
{ error: { message: 'boom' } },
])
auth(supabase)
const { status, body } = await parseJsonResponse<{
data: { is_hidden: boolean }[]
}>(await GET(req(), { params: Promise.resolve({}) }))
expect(status).toBe(200)
expect(body.data.every((t) => t.is_hidden === false)).toBe(true)
})
})
@@ -0,0 +1,33 @@
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/settings/booking-templates/export
* Export company + team templates as JSON (excludes system templates).
* Useful for sharing templates between unrelated companies.
*/
export const GET = withRouteContext(
'booking_template.export',
async (_request, ctx) => {
const { supabase, companyId } = ctx
const { data, error } = await supabase
.from('booking_template_library')
.select('name, description, category, entity_type, lines')
.eq('company_id', companyId)
.eq('is_active', true)
.eq('is_system', false)
.order('category')
.order('name')
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
return new NextResponse(JSON.stringify({ version: 1, templates: data }, null, 2), {
headers: {
'Content-Type': 'application/json',
'Content-Disposition': 'attachment; filename="bokforingsmallar.json"',
},
})
},
)
@@ -0,0 +1,67 @@
import { BookingTemplateLineSchema, BookingTemplateCategorySchema, BookingTemplateEntityTypeSchema } from '@/lib/bookkeeping/booking-template-schemas'
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { z } from 'zod'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const ImportTemplateSchema = z.object({
name: z.string().min(1).max(200),
description: z.string().max(2000).default(''),
category: BookingTemplateCategorySchema.default('other'),
entity_type: BookingTemplateEntityTypeSchema.default('all'),
lines: z.array(BookingTemplateLineSchema).min(2),
})
const ImportPayloadSchema = z.object({
version: z.number(),
templates: z.array(ImportTemplateSchema).min(1).max(100),
})
/**
* POST /api/settings/booking-templates/import
* Import templates from JSON (exported from another company).
* Creates company-scoped templates for the active company.
*/
export const POST = withRouteContext(
'booking_template.import',
async (request, ctx) => {
const { supabase, user, companyId } = ctx
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
}
const parsed = ImportPayloadSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid import format', details: parsed.error.issues },
{ status: 400 },
)
}
const rows = parsed.data.templates.map((t) => ({
company_id: companyId,
team_id: null,
created_by: user.id,
name: t.name,
description: t.description,
category: t.category,
entity_type: t.entity_type,
lines: t.lines,
is_system: false,
}))
const { data, error } = await supabase
.from('booking_template_library')
.insert(rows)
.select()
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
return NextResponse.json({ data, imported: data?.length ?? 0 }, { status: 201 })
},
{ requireWrite: true },
)
+202
View File
@@ -0,0 +1,202 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { z } from 'zod'
import { validateBody } from '@/lib/api/validate'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { UUID_RE } from '@/lib/invariants/uuid'
import {
BookingTemplateCategorySchema,
BookingTemplateEntityTypeSchema,
BookingTemplateLineSchema,
} from '@/lib/bookkeeping/booking-template-schemas'
// The GET scope below builds a PostgREST .or() filter by string interpolation.
// Guard every interpolated id against a strict UUID shape (UUID_RE) so a
// tainted value can never inject filter syntax. Both ids are server-derived
// (companyId from membership, teamId from a DB column), so this is
// defense-in-depth.
const CreateBookingTemplateSchema = z.object({
name: z.string().min(1).max(200),
description: z.string().max(2000).default(''),
category: BookingTemplateCategorySchema.default('other'),
entity_type: BookingTemplateEntityTypeSchema.default('all'),
lines: z.array(BookingTemplateLineSchema).min(2),
team_id: z.string().uuid().optional(),
})
/**
* GET /api/settings/booking-templates
* Returns all templates visible to the current user:
* system + company + team templates.
*
* Ordering: most recently used (per current company) first, then by category
* and name for never-used templates. Usage is tracked in
* booking_template_usage via POST /[id]/touch.
*/
export const GET = withRouteContext(
'booking_template.list',
async (_request, ctx) => {
const { supabase, companyId } = ctx
// Resolve the team this company belongs to (if any) so team-shared
// templates stay visible while this company is selected.
const { data: company } = await supabase
.from('companies')
.select('team_id')
.eq('id', companyId)
.maybeSingle()
const teamId = company?.team_id ?? null
// The wrapper only ever resolves a real membership UUID, but assert the
// shape before interpolating it into the .or() filter.
if (!UUID_RE.test(companyId)) {
return NextResponse.json({ error: 'Invalid company context' }, { status: 400 })
}
// Scope to the SELECTED company: system + this company + this company's team.
// RLS (btl_select) is membership-wide: it returns templates from *every*
// company the user belongs to: so the active-company narrowing must happen
// here in the API layer (mirrors counterparty-templates). Without this, a
// user who owns several companies sees all of their templates merged.
// Only interpolate a team id that passes the strict UUID guard.
const scope = [
'is_system.eq.true',
`company_id.eq.${companyId}`,
...(teamId && UUID_RE.test(teamId) ? [`team_id.eq.${teamId}`] : []),
].join(',')
const [templatesRes, usageRes, hiddenRes] = await Promise.all([
supabase
.from('booking_template_library')
.select('*')
.eq('is_active', true)
.or(scope)
.order('category')
.order('name'),
supabase
.from('booking_template_usage')
.select('template_id, last_used_at')
.eq('company_id', companyId),
supabase
.from('booking_template_hidden')
.select('template_id')
.eq('company_id', companyId),
])
if (templatesRes.error) {
return NextResponse.json({ error: getUserErrorMessage(templatesRes.error) }, { status: 500 })
}
// usage lookup failing is non-fatal: we just fall back to default ordering
const usageByTemplate = new Map<string, string>()
if (!usageRes.error && usageRes.data) {
for (const row of usageRes.data) {
usageByTemplate.set(row.template_id, row.last_used_at)
}
}
// hidden lookup failing is also non-fatal: falling back to "nothing
// hidden" shows extra templates, which is the safe direction.
const hiddenIds = new Set<string>()
if (!hiddenRes.error && hiddenRes.data) {
for (const row of hiddenRes.data) {
hiddenIds.add(row.template_id)
}
}
const templates = templatesRes.data ?? []
const decorated = templates.map((t) => ({
...t,
last_used_at: usageByTemplate.get(t.id) ?? null,
is_hidden: hiddenIds.has(t.id),
}))
// Stable-sort: templates with last_used_at come first (most-recent first).
// Templates without usage keep their category/name order from the query.
// ISO 8601 timestamps are fixed-width ASCII: plain relational comparison
// is correct and avoids any locale-dependent behaviour from localeCompare.
decorated.sort((a, b) => {
const aUsed = a.last_used_at
const bUsed = b.last_used_at
if (aUsed && bUsed) {
if (bUsed > aUsed) return -1
if (bUsed < aUsed) return 1
return 0
}
if (aUsed) return -1
if (bUsed) return 1
return 0
})
return NextResponse.json({ data: decorated })
},
)
/**
* POST /api/settings/booking-templates
* Create a company-scoped or team-scoped template.
*/
export const POST = withRouteContext(
'booking_template.create',
async (request, ctx) => {
const { supabase, user } = ctx
const result = await validateBody(request, CreateBookingTemplateSchema)
if (!result.success) return result.response
const body = result.data
const companyId = body.team_id ? null : ctx.companyId
const { data, error } = await supabase
.from('booking_template_library')
.insert({
company_id: companyId,
team_id: body.team_id ?? null,
created_by: user.id,
name: body.name,
description: body.description,
category: body.category,
entity_type: body.entity_type,
lines: body.lines,
is_system: false,
})
.select()
.single()
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
return NextResponse.json({ data }, { status: 201 })
},
{ requireWrite: true },
)
/**
* DELETE /api/settings/booking-templates
* Soft-delete a template by id (company or team scope only, never system).
*/
export const DELETE = withRouteContext(
'booking_template.delete',
async (request, ctx) => {
const { supabase } = ctx
let id: string | undefined
try {
const body = await request.json()
id = body?.id
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 })
}
if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 })
// RLS prevents deleting system templates (btl_delete policy checks NOT is_system)
const { error } = await supabase
.from('booking_template_library')
.update({ is_active: false })
.eq('id', id)
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
return NextResponse.json({ data: { success: true } })
},
{ requireWrite: true },
)
@@ -0,0 +1,76 @@
/**
* Tests for the pack sync cron.
*
* The route itself is thin; what matters is that it fails CLOSED. A cron that
* reports success while the catalogue failed to load would let a broken deploy
* sit unnoticed until someone opened the template picker.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: vi.fn(() => null),
}))
const syncSystemPacks = vi.fn()
vi.mock('@/lib/packs/sync', () => ({
syncSystemPacks: (...args: unknown[]) => syncSystemPacks(...args),
}))
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(() => ({ __service: true })),
}))
const OK_RESULT = {
inserted: ['a'], updated: ['b'], unchanged: ['c', 'd'], retired: [], errors: [], dryRun: false,
}
async function callRoute() {
const { GET } = await import('../route')
return GET(new Request('https://example.test/api/settings/booking-templates/sync/cron') as never, {} as never)
}
beforeEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-key'
})
describe('GET /api/settings/booking-templates/sync/cron', () => {
it('returns the sync counts on success', async () => {
syncSystemPacks.mockResolvedValueOnce(OK_RESULT)
const res = await callRoute()
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data).toMatchObject({ inserted: 1, updated: 1, unchanged: 2, retired: 0 })
})
it('names the retired slugs, so a retirement is never silent', async () => {
syncSystemPacks.mockResolvedValueOnce({ ...OK_RESULT, retired: ['gammal-mall'] })
const body = await (await callRoute()).json()
expect(body.data.retired_slugs).toEqual(['gammal-mall'])
})
it('fails when the catalogue is invalid instead of reporting success', async () => {
// syncSystemPacks writes nothing in this case, so the previous catalogue
// stands. The cron must still go red: a silent 200 would hide a bad deploy.
syncSystemPacks.mockResolvedValueOnce({
...OK_RESULT,
inserted: [], updated: [], unchanged: [],
errors: ['packs/x.yaml: meta.slug: slug must be lowercase kebab-case'],
})
const res = await callRoute()
expect(res.status).toBeGreaterThanOrEqual(500)
})
it('fails when Supabase configuration is missing', async () => {
delete process.env.SUPABASE_SERVICE_ROLE_KEY
const res = await callRoute()
expect(res.status).toBeGreaterThanOrEqual(500)
expect(syncSystemPacks).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,65 @@
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { syncSystemPacks } from '@/lib/packs/sync'
/**
* GET /api/settings/booking-templates/sync/cron
*
* Reconciles the system booking templates in the database with `packs/*.yaml`
* (schedule in vercel.json). The packs ship with the deploy; this is what makes
* the deployed catalogue the one companies actually see, so editing a template
* is a file change plus a deploy rather than a migration.
*
* Idempotent by construction: a database already matching the packs performs
* zero writes, so running it more often than needed costs one SELECT.
*
* Deliberately a cron rather than boot-time work: a sync on every cold start
* would have every serverless instance racing to write the same rows, and a
* bad catalogue would be re-applied continuously instead of once a day where
* it is visible in the logs.
*
* Service-role client, no company context: system templates belong to no
* company and RLS forbids writing them from a user session (btl_insert /
* btl_update both exclude is_system rows).
*/
// The catalogue is small (tens of rows); this never approaches the budget.
export const maxDuration = 60
export const GET = withCronContext('cron.booking_templates_sync', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
const result = await syncSystemPacks(supabase)
if (result.errors.length) {
// A catalogue that fails to load is a deploy problem, not a data problem:
// syncSystemPacks writes nothing in that case, so the previous state stands.
ctx.log.error('pack sync aborted: catalogue invalid', { errors: result.errors })
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Pack catalogue invalid', errors: result.errors },
})
}
return NextResponse.json({
data: {
inserted: result.inserted.length,
updated: result.updated.length,
unchanged: result.unchanged.length,
retired: result.retired.length,
retired_slugs: result.retired,
},
})
})
@@ -0,0 +1,302 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
const { supabase, enqueue, reset, findCall } = 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),
}))
const findCounterpartyTemplateMock = vi.fn()
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
findCounterpartyTemplate: (...args: unknown[]) => findCounterpartyTemplateMock(...args),
}))
import { GET, DELETE, PATCH } from '../route'
describe('GET /api/settings/counterparty-templates', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const request = createMockRequest('/api/settings/counterparty-templates')
const response = await GET(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(401)
})
it('lists active templates without a counterparty param', async () => {
enqueue({ data: [{ id: 't1', counterparty_name: 'anthropic' }], error: null })
const request = createMockRequest('/api/settings/counterparty-templates')
const response = await GET(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: Array<{ id: string }> }>(response)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
expect(findCounterpartyTemplateMock).not.toHaveBeenCalled()
})
it('runs the tiered matcher against a name probe in counterparty mode', async () => {
findCounterpartyTemplateMock.mockResolvedValue({
template: { id: 't1', counterparty_name: 'circle k', debit_account: '5611', credit_account: '1930' },
matchMethod: 'exact_normalized',
confidence: 0.9,
})
const request = createMockRequest('/api/settings/counterparty-templates?counterparty=Circle%20K')
const response = await GET(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{
data: { template: { debit_account: string }; match_method: string; confidence: number }
}>(response)
expect(status).toBe(200)
expect(body.data.template.debit_account).toBe('5611')
expect(body.data.match_method).toBe('exact_normalized')
expect(body.data.confidence).toBe(0.9)
const probe = findCounterpartyTemplateMock.mock.calls[0][2] as { description: string }
expect(probe.description).toBe('Circle K')
})
it('returns null data when the matcher finds nothing', async () => {
findCounterpartyTemplateMock.mockResolvedValue(null)
const request = createMockRequest('/api/settings/counterparty-templates?counterparty=Unknown')
const response = await GET(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: null }>(response)
expect(status).toBe(200)
expect(body.data).toBeNull()
})
it('rejects an oversized counterparty name', async () => {
const request = createMockRequest(
`/api/settings/counterparty-templates?counterparty=${'a'.repeat(201)}`
)
const response = await GET(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
expect(findCounterpartyTemplateMock).not.toHaveBeenCalled()
})
})
describe('DELETE /api/settings/counterparty-templates', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const request = createMockRequest('/api/settings/counterparty-templates', {
method: 'DELETE',
body: { id: 't1' },
})
const response = await DELETE(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(401)
})
it('returns 403 for a viewer without write permission', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const request = createMockRequest('/api/settings/counterparty-templates', {
method: 'DELETE',
body: { id: 't1' },
})
const response = await DELETE(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(403)
})
it('soft-deletes the template on the happy path', async () => {
enqueue({ error: null }) // update is_active: false
const request = createMockRequest('/api/settings/counterparty-templates', {
method: 'DELETE',
body: { id: 't1' },
})
const response = await DELETE(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: { success: boolean } }>(response)
expect(status).toBe(200)
expect(body.data.success).toBe(true)
})
})
describe('PATCH /api/settings/counterparty-templates', () => {
const TEMPLATE_ID = '11111111-1111-4111-8111-111111111111'
const TWIN_ID = '22222222-2222-4222-8222-222222222222'
const existing = {
id: TEMPLATE_ID,
company_id: 'company-1',
counterparty_name: 'spotify ab stockholm 4471',
counterparty_aliases: ['spotify ab stockholm 4471 kortköp'],
is_active: true,
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
function patch(body: unknown) {
const request = createMockRequest('/api/settings/counterparty-templates', {
method: 'PATCH',
body,
})
return PATCH(request, { params: Promise.resolve({}) })
}
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const { status } = await parseJsonResponse(await patch({ id: TEMPLATE_ID, counterparty_name: 'Spotify' }))
expect(status).toBe(401)
})
it('returns 403 for a viewer without write permission', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const { status } = await parseJsonResponse(await patch({ id: TEMPLATE_ID, counterparty_name: 'Spotify' }))
expect(status).toBe(403)
})
it('returns 400 for an empty name', async () => {
const { status } = await parseJsonResponse(await patch({ id: TEMPLATE_ID, counterparty_name: ' ' }))
expect(status).toBe(400)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 for a name that is too long', async () => {
const { status } = await parseJsonResponse(
await patch({ id: TEMPLATE_ID, counterparty_name: 'a'.repeat(101) }),
)
expect(status).toBe(400)
})
it('returns 400 for a one-character name', async () => {
const { status } = await parseJsonResponse(await patch({ id: TEMPLATE_ID, counterparty_name: 'S' }))
expect(status).toBe(400)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 404 when the template is not in the active company', async () => {
enqueue({ data: null }) // lookup by id + company
const { status } = await parseJsonResponse(await patch({ id: TEMPLATE_ID, counterparty_name: 'Spotify' }))
expect(status).toBe(404)
expect(findCall('categorization_templates', 'update')).toBeUndefined()
})
it('returns 409 when another active template already has the name', async () => {
enqueue({ data: existing }) // lookup by id
enqueue({ data: { id: TWIN_ID, is_active: true } }) // twin lookup
const { status } = await parseJsonResponse(await patch({ id: TEMPLATE_ID, counterparty_name: 'Spotify' }))
expect(status).toBe(409)
expect(findCall('categorization_templates', 'update')).toBeUndefined()
})
it('removes a soft-deleted twin instead of refusing the rename', async () => {
enqueue({ data: existing }) // lookup by id
enqueue({ data: { id: TWIN_ID, is_active: false } }) // inactive twin
enqueue({ error: null }) // delete twin
enqueue({ data: { ...existing, counterparty_name: 'spotify' } }) // update
const { status } = await parseJsonResponse(await patch({ id: TEMPLATE_ID, counterparty_name: 'Spotify' }))
expect(status).toBe(200)
expect(findCall('categorization_templates', 'delete')).toBeDefined()
expect(findCall('categorization_templates', 'update')).toBeDefined()
})
it('renames, lowercases the key and keeps the old name as an alias', async () => {
enqueue({ data: existing }) // lookup by id
enqueue({ data: null }) // no twin
enqueue({
data: {
...existing,
counterparty_name: 'spotify',
counterparty_aliases: [...existing.counterparty_aliases, existing.counterparty_name],
},
}) // update
const { status, body } = await parseJsonResponse<{
data: { counterparty_name: string; counterparty_aliases: string[] }
}>(await patch({ id: TEMPLATE_ID, counterparty_name: ' Spotify ' }))
expect(status).toBe(200)
expect(body.data.counterparty_name).toBe('spotify')
const payload = findCall('categorization_templates', 'update')?.[0] as {
counterparty_name: string
counterparty_aliases: string[]
}
expect(payload.counterparty_name).toBe('spotify')
expect(payload.counterparty_aliases).toContain('spotify ab stockholm 4471')
expect(payload.counterparty_aliases).toContain('spotify ab stockholm 4471 kortköp')
expect(findCall('categorization_templates', 'delete')).toBeUndefined()
})
it('returns 409 when the update loses the race on the unique name', async () => {
enqueue({ data: existing }) // lookup by id
enqueue({ data: null }) // no twin at check time
enqueue({ data: null, error: { code: '23505', message: 'duplicate key value' } }) // update
const { status } = await parseJsonResponse(await patch({ id: TEMPLATE_ID, counterparty_name: 'Spotify' }))
expect(status).toBe(409)
})
it('is a no-op when the name is unchanged', async () => {
enqueue({ data: existing }) // lookup by id
const { status } = await parseJsonResponse(
await patch({ id: TEMPLATE_ID, counterparty_name: 'Spotify AB Stockholm 4471' }),
)
expect(status).toBe(200)
expect(findCall('categorization_templates', 'update')).toBeUndefined()
})
})
@@ -0,0 +1,187 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { findCounterpartyTemplate } from '@/lib/bookkeeping/counterparty-templates'
import type { CategorizationTemplate, Transaction } from '@/types'
const RenameCounterpartyTemplateSchema = z.object({
id: z.string().uuid(),
counterparty_name: z.string().trim().min(1).max(100),
})
/**
* Stored names are lowercase, single-spaced keys (the matcher compares them
* against normalized bank descriptions). A user-typed name gets the same
* shape; display re-capitalizes through formatCounterpartyName().
*/
function toTemplateKey(input: string): string {
return input.toLowerCase().replace(/\s+/g, ' ').trim()
}
export const GET = withRouteContext(
'counterparty_template.list',
async (request, { supabase, companyId }) => {
// ?counterparty=<raw name> switches to single-match mode: run the same
// tiered matcher (alias / normalized / token-subset / fuzzy) the booking
// flows use, against a name instead of a transaction. The matcher only
// reads `merchant_name || description` and `id` off the transaction, so a
// probe object is sufficient; building a name-based variant of the matcher
// here would just drift from the real one.
const counterparty = new URL(request.url).searchParams.get('counterparty')?.trim()
if (counterparty) {
if (counterparty.length > 200) {
return NextResponse.json({ error: 'counterparty too long' }, { status: 400 })
}
const probe = { id: 'probe', merchant_name: null, description: counterparty } as unknown as Transaction
const match = await findCounterpartyTemplate(supabase, companyId, probe)
return NextResponse.json({
data: match
? { template: match.template, match_method: match.matchMethod, confidence: match.confidence }
: null,
})
}
const { data, error } = await supabase
.from('categorization_templates')
.select('*')
.eq('company_id', companyId)
.eq('is_active', true)
.order('occurrence_count', { ascending: false })
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
return NextResponse.json({ data })
},
)
export const DELETE = withRouteContext(
'counterparty_template.delete',
async (request, { supabase, companyId }) => {
let id: string | undefined
try {
const body = await request.json()
id = body?.id
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 })
}
if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 })
const { error } = await supabase
.from('categorization_templates')
.update({ is_active: false })
.eq('id', id)
.eq('company_id', companyId)
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
return NextResponse.json({ data: { success: true } })
},
{ requireWrite: true },
)
/**
* PATCH /api/settings/counterparty-templates
* Rename a learned template. The old name is kept as an alias so both the
* matcher (alias tier) and the learn path (findTemplateByKey) keep landing on
* this row for the merchant it was learned from.
*/
export const PATCH = withRouteContext(
'counterparty_template.rename',
async (request, { supabase, companyId, log, requestId }) => {
const validation = await validateBody(request, RenameCounterpartyTemplateSchema)
if (!validation.success) return validation.response
const { id } = validation.data
const newName = toTemplateKey(validation.data.counterparty_name)
if (newName.length < 2) {
return errorResponseFromCode('VALIDATION_ERROR', log, {
requestId,
messageSv: 'Namnet måste vara minst två tecken',
messageEn: 'The name must be at least two characters',
})
}
const { data: existing, error: fetchError } = await supabase
.from('categorization_templates')
.select('*')
.eq('id', id)
.eq('company_id', companyId)
.eq('is_active', true)
.maybeSingle()
if (fetchError) {
return NextResponse.json({ error: getUserErrorMessage(fetchError) }, { status: 500 })
}
if (!existing) {
return errorResponseFromCode('NOT_FOUND', log, {
requestId,
messageSv: 'Mallen hittades inte',
messageEn: 'Template not found',
})
}
const current = existing as CategorizationTemplate
if (current.counterparty_name === newName) {
return NextResponse.json({ data: current })
}
// (company_id, counterparty_name) is UNIQUE and includes soft-deleted
// rows. An active twin is a real conflict the user can see and resolve;
// an inactive twin is invisible to them, so it is removed instead of
// blocking the rename (a learned pattern, not a retention-bound record).
const { data: twin, error: twinError } = await supabase
.from('categorization_templates')
.select('id, is_active')
.eq('company_id', companyId)
.eq('counterparty_name', newName)
.neq('id', id)
.maybeSingle()
if (twinError) {
return NextResponse.json({ error: getUserErrorMessage(twinError) }, { status: 500 })
}
if (twin?.is_active) {
return errorResponseFromCode('CONFLICT', log, {
requestId,
messageSv: 'Det finns redan en mall med det här namnet',
messageEn: 'A template with this name already exists',
})
}
if (twin) {
const { error: purgeError } = await supabase
.from('categorization_templates')
.delete()
.eq('id', twin.id)
.eq('company_id', companyId)
if (purgeError) {
return NextResponse.json({ error: getUserErrorMessage(purgeError) }, { status: 500 })
}
}
const aliases = [...(current.counterparty_aliases || [])]
if (!aliases.includes(current.counterparty_name)) aliases.push(current.counterparty_name)
const { data: updated, error: updateError } = await supabase
.from('categorization_templates')
.update({ counterparty_name: newName, counterparty_aliases: aliases })
.eq('id', id)
.eq('company_id', companyId)
.select('*')
.single()
if (updateError) {
// Lost the race against another rename or the learn path: the unique
// (company_id, counterparty_name) index rejected the new name.
if ((updateError as { code?: string }).code === '23505') {
return errorResponseFromCode('CONFLICT', log, {
requestId,
messageSv: 'Det finns redan en mall med det här namnet',
messageEn: 'A template with this name already exists',
})
}
return NextResponse.json({ error: getUserErrorMessage(updateError) }, { status: 500 })
}
return NextResponse.json({ data: updated })
},
{ requireWrite: true },
)
@@ -0,0 +1,61 @@
/**
* Tests for /api/settings/eu-trade-signal — ledger-derived EU sales signal.
*/
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 fetchEntryLinesMock = vi.fn()
vi.mock('@/lib/bookkeeping/entry-lines', () => ({
fetchEntryLines: (...args: unknown[]) => fetchEntryLinesMock(...args),
}))
import { GET } from '../route'
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/settings/eu-trade-signal', () => {
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/settings/eu-trade-signal'), {})
expect(res.status).toBe(401)
})
it('reports EU sales when the ledger has postings on the PS accounts', async () => {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: {}, error: null })
fetchEntryLinesMock.mockResolvedValue([{ account_number: '3308' }])
const { status, body } = await parseJsonResponse<{ data: { has_eu_sales: boolean } }>(
await GET(createMockRequest('/api/settings/eu-trade-signal'), {})
)
expect(status).toBe(200)
expect(body.data.has_eu_sales).toBe(true)
})
it('reports no EU sales for an empty result', async () => {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: {}, error: null })
fetchEntryLinesMock.mockResolvedValue([])
const { status, body } = await parseJsonResponse<{ data: { has_eu_sales: boolean } }>(
await GET(createMockRequest('/api/settings/eu-trade-signal'), {})
)
expect(status).toBe(200)
expect(body.data.has_eu_sales).toBe(false)
})
})
+43
View File
@@ -0,0 +1,43 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
/**
* Accounts whose postings indicate EU B2B sales: 3108 goods, 3308 services,
* 3107 triangulation. Same set the periodisk sammanställning report keys on.
*/
const EU_SALES_ACCOUNTS = ['3108', '3308', '3107']
/** How far back to look for EU sales postings. */
const LOOKBACK_MONTHS = 15
/**
* GET /api/settings/eu-trade-signal
*
* Derived suggestion signal for the tax settings page: companies with EU
* sales in the ledger have a statutory periodisk sammanställning obligation
* (SFL 35 kap.), but the driving settings flags are opt-in and easily left
* off. The settings UI uses this to prompt the user to confirm EU trade and
* PS registration; it never flips the flags itself.
*/
export const GET = withRouteContext(
'settings.eu_trade_signal',
async (_request, { supabase, companyId }) => {
const since = new Date()
since.setMonth(since.getMonth() - LOOKBACK_MONTHS)
const sinceStr = since.toISOString().split('T')[0]
const lines = await fetchEntryLines<{ account_number: string }>({
supabase,
lineColumns: 'account_number',
filterEntries: (q: EntryLinesQuery) =>
q
.eq('company_id', companyId)
.in('status', ['posted', 'reversed'])
.gte('entry_date', sinceStr),
filterLines: (q: EntryLinesQuery) => q.in('account_number', EU_SALES_ACCOUNTS),
})
return NextResponse.json({ data: { has_eu_sales: lines.length > 0 } })
},
)
@@ -0,0 +1,175 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, 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),
}))
const storageBucket = {
upload: vi.fn().mockResolvedValue({ data: {}, error: null }),
list: vi.fn().mockResolvedValue({ data: [], error: null }),
remove: vi.fn().mockResolvedValue({ data: [], error: null }),
}
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: () => ({
storage: { from: vi.fn().mockReturnValue(storageBucket) },
}),
}))
import { DELETE, POST } from '../route'
function makeFontRequest(
size = 8,
signature: number[] = [0x00, 0x01, 0x00, 0x00],
name = 'brand.ttf',
): Request {
const bytes = new Uint8Array(size)
bytes.set(signature.slice(0, size))
const formData = new FormData()
formData.append('file', new File([bytes], name, { type: 'font/ttf' }))
return new Request('http://localhost/api/settings/invoice-font', {
method: 'POST',
body: formData,
})
}
describe('POST /api/settings/invoice-font', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(makeFontRequest(), { params: Promise.resolve({}) })
expect(response.status).toBe(401)
})
it('returns 403 for a viewer without write permission', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const response = await POST(makeFontRequest(), { params: Promise.resolve({}) })
expect(response.status).toBe(403)
})
it('returns 400 for a file with an invalid font signature', async () => {
const response = await POST(
makeFontRequest(8, [0x25, 0x50, 0x44, 0x46]),
{ params: Promise.resolve({}) },
)
expect(response.status).toBe(400)
})
it('returns 400 when the font exceeds 5 MB', async () => {
const response = await POST(
makeFontRequest(5 * 1024 * 1024 + 1),
{ params: Promise.resolve({}) },
)
const { body } = await parseJsonResponse<{ error: string }>(response)
expect(response.status).toBe(400)
expect(body.error).toContain('5 MB')
})
it('returns 404 when company settings do not exist', async () => {
enqueue({ error: { code: 'PGRST116', message: 'No rows returned' } })
const response = await POST(makeFontRequest(), { params: Promise.resolve({}) })
expect(response.status).toBe(404)
expect(storageBucket.remove).toHaveBeenCalled()
})
it('uploads a valid TTF and selects it for invoice PDFs', async () => {
enqueue({ error: null })
const response = await POST(makeFontRequest(), { params: Promise.resolve({}) })
const { body } = await parseJsonResponse<{
data: { invoice_font_family: string; invoice_custom_font_name: string }
}>(response)
expect(response.status).toBe(200)
expect(body.data).toMatchObject({
invoice_font_family: 'Custom',
invoice_custom_font_name: 'brand.ttf',
})
expect(storageBucket.upload).toHaveBeenCalledWith(
expect.stringMatching(/^company-1\/invoice-font-\d+\.ttf$/),
expect.any(Buffer),
expect.objectContaining({ contentType: 'font/ttf' }),
)
})
it('uploads a valid WOFF with its normalized content type', async () => {
enqueue({ error: null })
const response = await POST(
makeFontRequest(8, [0x77, 0x4f, 0x46, 0x46], 'brand.woff'),
{ params: Promise.resolve({}) },
)
expect(response.status).toBe(200)
expect(storageBucket.upload).toHaveBeenCalledWith(
expect.stringMatching(/^company-1\/invoice-font-\d+\.woff$/),
expect.any(Buffer),
expect.objectContaining({ contentType: 'font/woff' }),
)
})
})
describe('DELETE /api/settings/invoice-font', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('removes the custom font and restores Helvetica', async () => {
enqueue({ error: null })
const response = await DELETE(
new Request('http://localhost/api/settings/invoice-font', { method: 'DELETE' }),
{ params: Promise.resolve({}) },
)
const { body } = await parseJsonResponse<{
data: { invoice_font_family: string; invoice_custom_font_path: null }
}>(response)
expect(response.status).toBe(200)
expect(body.data).toEqual({
invoice_font_family: 'Helvetica',
invoice_custom_font_path: null,
invoice_custom_font_name: null,
})
})
})
+151
View File
@@ -0,0 +1,151 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { createServiceClient } from '@/lib/supabase/server'
import {
INVOICE_FONT_UPLOAD_MAX_BYTES,
INVOICE_FONT_UPLOAD_MAX_MB,
} from '@/lib/invoices/branding-constants'
import {
detectInvoiceFontFileFormat,
getInvoiceFontContentType,
} from '@/lib/invoices/font-files'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const ALLOWED_EXTENSIONS = new Set(['ttf', 'woff'])
function safeDisplayName(fileName: string, extension: string): string {
const baseName = fileName.split(/[\\/]/).pop() ?? `invoice-font.${extension}`
const cleaned = baseName.replace(/[\u0000-\u001f\u007f]/g, '').trim()
return (cleaned || `invoice-font.${extension}`).slice(0, 200)
}
export const POST = withRouteContext(
'settings.invoice-font.upload',
async (request, { supabase, companyId }) => {
const formData = await request.formData()
const file = formData.get('file')
if (!(file instanceof File)) {
return NextResponse.json({ error: 'Ingen typsnittsfil angiven.' }, { status: 400 })
}
const extension = file.name.split('.').pop()?.toLowerCase() ?? ''
if (!ALLOWED_EXTENSIONS.has(extension)) {
return NextResponse.json(
{ error: 'Otillåten filtyp. Tillåtna format är TTF och WOFF.' },
{ status: 400 },
)
}
if (file.size > INVOICE_FONT_UPLOAD_MAX_BYTES) {
return NextResponse.json(
{ error: `Filen är för stor (max ${INVOICE_FONT_UPLOAD_MAX_MB} MB).` },
{ status: 400 },
)
}
const bytes = Buffer.from(await file.arrayBuffer())
const format = detectInvoiceFontFileFormat(bytes)
if (!format || format !== extension) {
return NextResponse.json(
{ error: 'Filen är inte ett giltigt TTF- eller WOFF-typsnitt.' },
{ status: 400 },
)
}
const fileName = `invoice-font-${Date.now()}.${format}`
const storagePath = `${companyId}/${fileName}`
const serviceClient = createServiceClient()
const bucket = serviceClient.storage.from('invoice-fonts')
const { error: uploadError } = await bucket.upload(storagePath, bytes, {
contentType: getInvoiceFontContentType(format),
upsert: false,
})
if (uploadError) {
return NextResponse.json(
{ error: `Uppladdning misslyckades: ${getUserErrorMessage(uploadError)}` },
{ status: 500 },
)
}
const displayName = safeDisplayName(file.name, format)
const { error: updateError } = await supabase
.from('company_settings')
.update({
invoice_font_family: 'Custom',
invoice_custom_font_path: storagePath,
invoice_custom_font_name: displayName,
})
.eq('company_id', companyId)
.select('company_id')
.single()
if (updateError) {
await bucket.remove([storagePath])
if (updateError.code === 'PGRST116') {
return NextResponse.json({ error: 'Inställningarna hittades inte.' }, { status: 404 })
}
return NextResponse.json(
{ error: getUserErrorMessage(updateError) },
{ status: 500 },
)
}
const { data: existing } = await bucket.list(companyId)
const obsoletePaths = (existing ?? [])
.filter((stored) => stored.name !== fileName)
.map((stored) => `${companyId}/${stored.name}`)
if (obsoletePaths.length > 0) await bucket.remove(obsoletePaths)
return NextResponse.json({
data: {
invoice_font_family: 'Custom',
invoice_custom_font_path: storagePath,
invoice_custom_font_name: displayName,
},
})
},
{ requireWrite: true },
)
export const DELETE = withRouteContext(
'settings.invoice-font.delete',
async (_request, { supabase, companyId }) => {
const { error: updateError } = await supabase
.from('company_settings')
.update({
invoice_font_family: 'Helvetica',
invoice_custom_font_path: null,
invoice_custom_font_name: null,
})
.eq('company_id', companyId)
.select('company_id')
.single()
if (updateError) {
if (updateError.code === 'PGRST116') {
return NextResponse.json({ error: 'Inställningarna hittades inte.' }, { status: 404 })
}
return NextResponse.json(
{ error: getUserErrorMessage(updateError) },
{ status: 500 },
)
}
const serviceClient = createServiceClient()
const bucket = serviceClient.storage.from('invoice-fonts')
const { data: existing } = await bucket.list(companyId)
if (existing && existing.length > 0) {
await bucket.remove(existing.map((stored) => `${companyId}/${stored.name}`))
}
return NextResponse.json({
data: {
invoice_font_family: 'Helvetica',
invoice_custom_font_path: null,
invoice_custom_font_name: null,
},
})
},
{ requireWrite: true },
)
@@ -0,0 +1,98 @@
/**
* Tests for /api/settings/ku-signal — ledger-derived kontrolluppgifter signal.
*/
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 fetchEntryLinesMock = vi.fn()
vi.mock('@/lib/bookkeeping/entry-lines', () => ({
fetchEntryLines: (...args: unknown[]) => fetchEntryLinesMock(...args),
}))
import { GET } from '../route'
function supabaseWithEntityType(entityType: string | null) {
return {
from: vi.fn(() => ({
select: vi.fn(() => ({
eq: vi.fn(() => ({
maybeSingle: vi.fn(async () => ({ data: entityType ? { entity_type: entityType } : null })),
})),
})),
})),
}
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/settings/ku-signal', () => {
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/settings/ku-signal'), {})
expect(res.status).toBe(401)
})
it('reports a KU signal when an aktiebolag has utdelning/ägarlån postings', async () => {
requireAuthMock.mockResolvedValue({
user: { id: 'user-1' },
supabase: supabaseWithEntityType('aktiebolag'),
error: null,
})
fetchEntryLinesMock.mockResolvedValue([{ account_number: '2898' }])
const { status, body } = await parseJsonResponse<{ data: { has_ku_signal: boolean } }>(
await GET(createMockRequest('/api/settings/ku-signal'), {})
)
expect(status).toBe(200)
expect(body.data.has_ku_signal).toBe(true)
})
it('reports no signal for an empty result', async () => {
requireAuthMock.mockResolvedValue({
user: { id: 'user-1' },
supabase: supabaseWithEntityType('aktiebolag'),
error: null,
})
fetchEntryLinesMock.mockResolvedValue([])
const { status, body } = await parseJsonResponse<{ data: { has_ku_signal: boolean } }>(
await GET(createMockRequest('/api/settings/ku-signal'), {})
)
expect(status).toBe(200)
expect(body.data.has_ku_signal).toBe(false)
})
it('never signals for enskild firma, even with matching postings', async () => {
requireAuthMock.mockResolvedValue({
user: { id: 'user-1' },
supabase: supabaseWithEntityType('enskild_firma'),
error: null,
})
fetchEntryLinesMock.mockResolvedValue([{ account_number: '2893' }])
const { status, body } = await parseJsonResponse<{ data: { has_ku_signal: boolean } }>(
await GET(createMockRequest('/api/settings/ku-signal'), {})
)
expect(status).toBe(200)
expect(body.data.has_ku_signal).toBe(false)
// The ledger query is skipped entirely for non-AB companies.
expect(fetchEntryLinesMock).not.toHaveBeenCalled()
})
})
+66
View File
@@ -0,0 +1,66 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
/**
* Accounts whose postings indicate a kontrolluppgifter obligation:
* 2898 outtagen vinstutdelning (KU31 on utdelning), 2393/2893 lån från
* närstående (KU20 on interest paid to the owner). 2091 is deliberately NOT
* a signal: every closed year moves balanserad vinst, so it would flag
* nearly all aktiebolag.
*/
const KU_SIGNAL_ACCOUNTS = ['2898', '2393', '2893']
/** How far back to look for KU-relevant postings. */
const LOOKBACK_MONTHS = 15
/**
* GET /api/settings/ku-signal
*
* Derived suggestion signal for the tax settings page: an aktiebolag whose
* ledger shows utdelning or ägarlån postings likely owes kontrolluppgifter
* on 31 January (SFL 24 kap. 1 §), but KU31 is never covered by AGI so the
* obligation is easy to miss. The settings UI uses this to prompt the user
* to enable the KU deadline; it never flips the flag itself (mirrors the
* EU-trade signal from the periodisk sammanställning suggestion).
*/
export const GET = withRouteContext(
'settings.ku_signal',
async (_request, { supabase, companyId, log }) => {
// Kontrolluppgifter for utdelning/ägarlån only exist for aktiebolag; an
// enskild firma has no shareholder to report on.
const { data: settings, error: settingsError } = await supabase
.from('company_settings')
.select('entity_type')
.eq('company_id', companyId)
.maybeSingle()
if (settingsError) {
// Best-effort signal: treat as "no signal" but keep the failure
// observable for forensics.
log.warn('ku-signal: company_settings lookup failed', {
code: settingsError.code,
})
}
if (settings?.entity_type !== 'aktiebolag') {
return NextResponse.json({ data: { has_ku_signal: false } })
}
const since = new Date()
since.setMonth(since.getMonth() - LOOKBACK_MONTHS)
const sinceStr = since.toISOString().split('T')[0]
const lines = await fetchEntryLines<{ account_number: string }>({
supabase,
lineColumns: 'account_number',
filterEntries: (q: EntryLinesQuery) =>
q
.eq('company_id', companyId)
.in('status', ['posted', 'reversed'])
.gte('entry_date', sinceStr),
filterLines: (q: EntryLinesQuery) => q.in('account_number', KU_SIGNAL_ACCOUNTS),
})
return NextResponse.json({ data: { has_ku_signal: lines.length > 0 } })
},
)
@@ -0,0 +1,202 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse, createQueuedMockSupabase } 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),
}))
const logosBucket = {
list: vi.fn().mockResolvedValue({ data: [], error: null }),
remove: vi.fn().mockResolvedValue({ data: [], error: null }),
upload: vi.fn().mockResolvedValue({ data: {}, error: null }),
getPublicUrl: vi.fn().mockReturnValue({ data: { publicUrl: 'https://cdn.example.com/logo.png' } }),
}
const serviceStorage = {
from: vi.fn().mockReturnValue(logosBucket),
}
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: () => ({ storage: serviceStorage }),
}))
import { POST } from '../route'
const PNG_MAGIC = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
const JPEG_MAGIC = [0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46]
// RIFF <size> WEBP
const WEBP_MAGIC = [0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50]
const SVG_SOURCE = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(document.cookie)</script></svg>'
/** A buffer of `size` bytes that starts with `magic` (zero-padded). */
function withMagic(magic: number[], size = 64): Uint8Array<ArrayBuffer> {
const bytes = new Uint8Array(new ArrayBuffer(Math.max(size, magic.length)))
bytes.set(magic)
return bytes
}
function makeFormRequest(content: BlobPart, type = 'image/png', name = 'logo.png'): Request {
const fd = new FormData()
fd.append('file', new File([content], name, { type }))
return new Request('http://localhost/api/settings/logo', { method: 'POST', body: fd })
}
const params = { params: Promise.resolve({}) }
describe('POST /api/settings/logo', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC)), params)
const { status } = await parseJsonResponse(response)
expect(status).toBe(401)
})
it('returns 403 for a viewer without write permission', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC)), params)
const { status } = await parseJsonResponse(response)
expect(status).toBe(403)
})
it('returns 400 when no file is attached', async () => {
const fd = new FormData()
const response = await POST(
new Request('http://localhost/api/settings/logo', { method: 'POST', body: fd }),
params,
)
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
})
it('returns 400 for an unsupported file type', async () => {
const response = await POST(makeFormRequest(new Uint8Array(3), 'application/pdf', 'logo.pdf'), params)
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
expect(logosBucket.upload).not.toHaveBeenCalled()
})
it('refuses SVG even when declared as image/svg+xml (public bucket, script-capable format)', async () => {
const response = await POST(makeFormRequest(SVG_SOURCE, 'image/svg+xml', 'logo.svg'), params)
const { status, body } = await parseJsonResponse<{ error: string }>(response)
expect(status).toBe(400)
expect(body.error).toBe('Otillåten filtyp. Tillåtna: PNG, JPG, WebP.')
expect(logosBucket.upload).not.toHaveBeenCalled()
})
it('refuses SVG bytes smuggled under a declared image/png type', async () => {
const response = await POST(makeFormRequest(SVG_SOURCE, 'image/png', 'logo.png'), params)
const { status, body } = await parseJsonResponse<{ error: string }>(response)
expect(status).toBe(400)
expect(body.error).toContain('PNG, JPG, WebP')
expect(logosBucket.upload).not.toHaveBeenCalled()
})
it('refuses an HTML document declared as an image', async () => {
const response = await POST(
makeFormRequest('<!doctype html><script>alert(1)</script>', 'image/jpeg', 'logo.jpg'),
params,
)
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
expect(logosBucket.upload).not.toHaveBeenCalled()
})
it('refuses a PDF declared as an image', async () => {
const response = await POST(makeFormRequest('%PDF-1.4\n%%EOF', 'image/png', 'logo.png'), params)
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
expect(logosBucket.upload).not.toHaveBeenCalled()
})
it('returns 400 when the logo exceeds 10 MB', async () => {
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC, 10 * 1024 * 1024 + 1)), params)
const { status, body } = await parseJsonResponse<{ error: string }>(response)
expect(status).toBe(400)
expect(body.error).toContain('10 MB')
})
it('accepts a logo larger than the previous 2 MB limit', async () => {
enqueue({ error: null }) // company_settings update
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC, 2 * 1024 * 1024 + 1)), params)
const { status } = await parseJsonResponse(response)
expect(status).toBe(200)
})
it('uploads a PNG under its sniffed type and returns the public url on the happy path', async () => {
enqueue({ error: null }) // company_settings update
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC)), params)
const { status, body } = await parseJsonResponse<{ data: { logo_url: string } }>(response)
expect(status).toBe(200)
expect(body.data.logo_url).toBe('https://cdn.example.com/logo.png')
expect(logosBucket.upload).toHaveBeenCalledTimes(1)
const [path, , options] = logosBucket.upload.mock.calls[0] as [string, Buffer, { contentType: string }]
expect(path).toMatch(/^company-1\/logo-\d+\.png$/)
expect(options.contentType).toBe('image/png')
})
it('stores the type the bytes prove, not the declared one (JPEG declared as PNG)', async () => {
enqueue({ error: null })
const response = await POST(makeFormRequest(withMagic(JPEG_MAGIC), 'image/png', 'logo.png'), params)
const { status } = await parseJsonResponse(response)
expect(status).toBe(200)
const [path, , options] = logosBucket.upload.mock.calls[0] as [string, Buffer, { contentType: string }]
expect(path).toMatch(/\.jpg$/)
expect(options.contentType).toBe('image/jpeg')
})
it('accepts WebP by magic bytes', async () => {
enqueue({ error: null })
const response = await POST(makeFormRequest(withMagic(WEBP_MAGIC), 'image/webp', 'logo.webp'), params)
const { status } = await parseJsonResponse(response)
expect(status).toBe(200)
const [path, , options] = logosBucket.upload.mock.calls[0] as [string, Buffer, { contentType: string }]
expect(path).toMatch(/\.webp$/)
expect(options.contentType).toBe('image/webp')
})
})
+118
View File
@@ -0,0 +1,118 @@
import { NextResponse } from 'next/server'
import { createServiceClient } from '@/lib/supabase/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { LOGO_UPLOAD_MAX_BYTES, LOGO_UPLOAD_MAX_MB } from '@/lib/invoices/branding-constants'
import { detectFileMagic } from '@/lib/core/documents/document-service'
/**
* Raster formats only, decided by the file's magic bytes (detectFileMagic),
* never by the client-declared Content-Type. The logos bucket is PUBLIC and
* the object is served under the type stored here: an SVG (or an HTML file
* declared as an image) would be a script-capable document on a public URL,
* so SVG is not accepted at all and a declared type that disagrees with the
* bytes is ignored in favour of the bytes.
*/
const LOGO_TYPE_EXTENSIONS: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/webp': 'webp',
}
const LOGO_TYPE_ERROR = 'Otillåten filtyp. Tillåtna: PNG, JPG, WebP.'
export const POST = withRouteContext(
'settings.logo.upload',
async (request, { supabase, companyId }) => {
const formData = await request.formData()
const file = formData.get('file') as File | null
if (!file) {
return NextResponse.json({ error: 'Ingen fil angiven' }, { status: 400 })
}
if (file.size > LOGO_UPLOAD_MAX_BYTES) {
return NextResponse.json({ error: `Filen är för stor (max ${LOGO_UPLOAD_MAX_MB} MB).` }, { status: 400 })
}
const buffer = Buffer.from(await file.arrayBuffer())
const detectedType = detectFileMagic(new Uint8Array(buffer))
const ext = detectedType ? LOGO_TYPE_EXTENSIONS[detectedType] : undefined
if (!detectedType || !ext) {
return NextResponse.json({ error: LOGO_TYPE_ERROR }, { status: 400 })
}
const storagePath = `${companyId}/logo-${Date.now()}.${ext}`
const serviceClient = createServiceClient()
// Remove any previous logo files for this company so we don't pile up orphans.
const { data: existing } = await serviceClient.storage
.from('logos')
.list(companyId)
if (existing && existing.length > 0) {
await serviceClient.storage
.from('logos')
.remove(existing.map((f) => `${companyId}/${f.name}`))
}
const { error: uploadError } = await serviceClient.storage
.from('logos')
.upload(storagePath, buffer, {
contentType: detectedType,
upsert: true,
})
if (uploadError) {
return NextResponse.json({ error: `Uppladdning misslyckades: ${getUserErrorMessage(uploadError)}` }, { status: 500 })
}
const { data: urlData } = serviceClient.storage
.from('logos')
.getPublicUrl(storagePath)
// Update company settings
const { error: updateError } = await supabase
.from('company_settings')
.update({ logo_url: urlData.publicUrl })
.eq('company_id', companyId)
if (updateError) {
return NextResponse.json({ error: 'Kunde inte uppdatera inställningar' }, { status: 500 })
}
return NextResponse.json({ data: { logo_url: urlData.publicUrl } })
},
{ requireWrite: true },
)
export const DELETE = withRouteContext(
'settings.logo.delete',
async (_request, { supabase, companyId }) => {
// Get current logo path
const { data: settings } = await supabase
.from('company_settings')
.select('logo_url')
.eq('company_id', companyId)
.single()
if (settings?.logo_url) {
const serviceClient = createServiceClient()
const { data: existing } = await serviceClient.storage
.from('logos')
.list(companyId)
if (existing && existing.length > 0) {
await serviceClient.storage
.from('logos')
.remove(existing.map((f) => `${companyId}/${f.name}`))
}
}
// Clear logo_url
await supabase
.from('company_settings')
.update({ logo_url: null })
.eq('company_id', companyId)
return NextResponse.json({ data: { logo_url: null } })
},
{ requireWrite: true },
)
@@ -0,0 +1,86 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRouteParams, parseJsonResponse, createQueuedMockSupabase } 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),
}))
const appendMock = vi.fn()
vi.mock('@/lib/processing-history/append', () => ({
appendProcessingHistory: (...args: unknown[]) => appendMock(...args),
}))
import { DELETE } from '../route'
describe('DELETE /api/settings/oauth-clients/[id]', () => {
const routeParams = createMockRouteParams({ id: 'reg-1' })
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
appendMock.mockResolvedValue(undefined)
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await DELETE(new Request('http://localhost/x', { method: 'DELETE' }), routeParams)
const { status } = await parseJsonResponse(response)
expect(status).toBe(401)
})
it('returns 403 for a viewer without write permission', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const response = await DELETE(new Request('http://localhost/x', { method: 'DELETE' }), routeParams)
const { status } = await parseJsonResponse(response)
expect(status).toBe(403)
})
it('returns 404 when the registration is unknown or already revoked', async () => {
enqueue({ data: [] }) // update ... returning no rows
const response = await DELETE(new Request('http://localhost/x', { method: 'DELETE' }), routeParams)
const { status } = await parseJsonResponse(response)
expect(status).toBe(404)
})
it('revokes the registration and appends an audit event on the happy path', async () => {
enqueue({
data: [{ id: 'reg-1', redirect_uri: 'https://app.example.com/cb', client_name: 'My App' }],
})
const response = await DELETE(new Request('http://localhost/x', { method: 'DELETE' }), routeParams)
const { status, body } = await parseJsonResponse<{ success: boolean }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(appendMock).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,68 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* DELETE /api/settings/oauth-clients/[id]: revoke a redirect URI
* registration. Soft-delete via revoked_at so the audit trail survives
* and the same URI can be re-registered later.
*
* Emits an audit event so revocations are visible in processing_history:
* revoking an OAuth client is a security-relevant access-control change
* (SOC 2 CC7.2). Returns 404 when the row is unknown or already revoked
* so callers can surface failures rather than treating "no-op" as success.
*/
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
'oauth_client.delete',
async (_request, { supabase, user, companyId, log }, { params }) => {
const { id } = await params
const { data: rows, error } = await supabase
.from('oauth_client_registrations')
.update({ revoked_at: new Date().toISOString() })
.eq('id', id)
.eq('user_id', user.id)
.is('revoked_at', null)
.select('id, redirect_uri, client_name')
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
if (!rows || rows.length === 0) {
return NextResponse.json(
{ error: 'OAuth-klient hittades inte eller är redan återkallad.' },
{ status: 404 }
)
}
// Audit the revocation. Failure to append must not break the user flow:
// the revocation has already happened in the DB. We log the appendError
// so a systematic outage is visible in operations rather than silently
// degraded.
try {
await appendProcessingHistory({
companyId,
correlationId: id,
aggregateType: 'System',
aggregateId: id,
eventType: 'OAuthClientRevoked',
payload: {
client_id: id,
// Note: redirect_uri may contain a host the user identifies with their
// own infrastructure but is not PII per Art. 4(1). Stored to satisfy
// SOC 2 CC7.2 "what was revoked" evidence trail.
redirect_uri: rows[0].redirect_uri,
},
actor: { type: 'user', id: user.id },
occurredAt: new Date(),
})
} catch (auditErr) {
log.warn('Failed to append OAuthClientRevoked audit event', auditErr)
}
return NextResponse.json({ success: true })
},
{ requireWrite: true },
)
@@ -0,0 +1,85 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } 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 { POST } from '../route'
describe('POST /api/settings/oauth-clients', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const request = createMockRequest('/api/settings/oauth-clients', {
method: 'POST',
body: { client_name: 'My App', redirect_uri: 'https://app.example.com/cb' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(401)
})
it('returns 403 for a viewer without write permission', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const request = createMockRequest('/api/settings/oauth-clients', {
method: 'POST',
body: { client_name: 'My App', redirect_uri: 'https://app.example.com/cb' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(403)
})
it('registers a redirect uri scoped to the current user on the happy path', async () => {
enqueue({
data: {
id: 'reg-1',
client_name: 'My App',
redirect_uri: 'https://app.example.com/cb',
created_at: '2026-01-01T00:00:00Z',
},
})
const request = createMockRequest('/api/settings/oauth-clients', {
method: 'POST',
body: { client_name: 'My App', redirect_uri: 'https://app.example.com/cb' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(response)
expect(status).toBe(200)
expect(body.data.id).toBe('reg-1')
})
})
+90
View File
@@ -0,0 +1,90 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { z } from 'zod'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* GET /api/settings/oauth-clients: list the current user's registered
* redirect URIs.
* POST /api/settings/oauth-clients: register a new redirect URI for use
* with the MCP OAuth flow.
*
* Built-in patterns (claude.ai, claude.com, localhost) bypass this table
* entirely: registrations here are only for self-hosted custom apps.
*/
const RegistrationSchema = z.object({
client_name: z.string().trim().min(1).max(100),
// Reject loopback first (covers http:// too) so the user gets the helpful
// "already allowed" message instead of being told to use https for localhost.
// Non-loopback URIs must use https.
redirect_uri: z
.string()
.url('redirect_uri must be a valid URL')
.refine(
(u) => !/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|::1)(:|\/|$)/i.test(u),
'localhost är redan tillåtet utan registrering'
)
.refine((u) => u.startsWith('https://'), 'redirect_uri måste använda https://')
.max(500),
})
export const GET = withRouteContext(
'oauth_client.list',
async (_request, { supabase, user }) => {
const { data, error } = await supabase
.from('oauth_client_registrations')
.select('id, client_name, redirect_uri, created_at, revoked_at')
.eq('user_id', user.id)
.order('created_at', { ascending: false })
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data })
},
)
export const POST = withRouteContext(
'oauth_client.create',
async (request, { supabase, user }) => {
let body: z.infer<typeof RegistrationSchema>
try {
const json = await request.json()
body = RegistrationSchema.parse(json)
} catch (err) {
const message =
err instanceof z.ZodError
? err.issues[0]?.message ?? 'Ogiltig redirect URI'
: err instanceof SyntaxError
? 'Ogiltig JSON i request body'
: 'Ogiltig redirect URI'
return NextResponse.json({ error: message }, { status: 400 })
}
const { data, error } = await supabase
.from('oauth_client_registrations')
.insert({
user_id: user.id,
client_name: body.client_name,
redirect_uri: body.redirect_uri,
})
.select('id, client_name, redirect_uri, created_at')
.single()
if (error) {
// Unique-index violation on redirect_uri → 409
if (error.code === '23505') {
return NextResponse.json(
{ error: 'Den här redirect URI:n är redan registrerad.' },
{ status: 409 }
)
}
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)

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