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

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,239 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const mockEmit = vi.fn().mockResolvedValue(undefined)
vi.mock('@/lib/events', () => ({ eventBus: { emit: (...a: unknown[]) => mockEmit(...a) } }))
const mockFetchAllRows = vi.fn()
vi.mock('@/lib/supabase/fetch-all', () => ({
fetchAllRows: (...a: unknown[]) => mockFetchAllRows(...a),
}))
const mockEnsureArticleNumber = vi.fn().mockResolvedValue('AUTO-1')
vi.mock('@/lib/articles/ensure-article-number', () => ({
ensureArticleNumber: (...a: unknown[]) => mockEnsureArticleNumber(...a),
}))
const mockCheckRevenueAccount = vi.fn().mockResolvedValue('ok')
vi.mock('@/lib/articles/validate-revenue-account', () => ({
checkRevenueAccount: (...a: unknown[]) => mockCheckRevenueAccount(...a),
}))
import { POST } from '../execute/route'
const mockUser = { id: 'user-1', email: '[email protected]' }
function row(overrides: Record<string, unknown> = {}) {
return {
row_index: 2,
name: 'Konsulttimme',
name_en: null,
article_number: null,
type: 'tjanst',
unit: 'tim',
price_excl_vat: 950,
vat_rate: 25,
revenue_account: null,
cost_price: null,
ean: null,
housework_type: null,
notes: null,
...overrides,
}
}
function makeRequest(body: unknown) {
return createMockRequest('/api/import/articles/execute', { method: 'POST', body })
}
describe('POST /api/import/articles/execute', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
mockFetchAllRows.mockResolvedValue([])
mockCheckRevenueAccount.mockResolvedValue('ok')
mockEnsureArticleNumber.mockResolvedValue('AUTO-1')
})
it('returns 401 for unauthenticated requests', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(makeRequest({ rows: [row()], update_duplicates: false }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 400 for an empty rows array', async () => {
const res = await POST(makeRequest({ rows: [], update_duplicates: false }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('creates new articles and emits article.created', async () => {
enqueue({ data: { id: 'a1', name: 'Konsulttimme', article_number: null } })
enqueue({ data: { id: 'a2', name: 'Skruv', article_number: 'A-200' } })
const res = await POST(makeRequest({
rows: [row(), row({ row_index: 3, name: 'Skruv', article_number: 'A-200', type: 'vara' })],
update_duplicates: false,
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.created).toBe(2)
expect(body.data.failed).toBe(0)
expect(mockEmit).toHaveBeenCalledTimes(2)
// The numberless row gets auto-numbered; the one with A-200 does not.
expect(mockEnsureArticleNumber).toHaveBeenCalledTimes(1)
})
it('skips a duplicate matched by article number when update_duplicates is false', async () => {
mockFetchAllRows.mockResolvedValue([{ id: 'x', name: 'Existing', article_number: 'A-1' }])
const res = await POST(makeRequest({
rows: [row({ article_number: 'A-1' })],
update_duplicates: false,
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.skipped).toBe(1)
expect(body.data.created).toBe(0)
})
it('updates a duplicate matched by article number when update_duplicates is true', async () => {
mockFetchAllRows.mockResolvedValue([{ id: 'x', name: 'Old', article_number: 'A-1' }])
enqueue({ data: { id: 'x', name: 'New name', article_number: 'A-1' } })
const res = await POST(makeRequest({
rows: [row({ article_number: 'A-1', name: 'New name' })],
update_duplicates: true,
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.updated).toBe(1)
expect(body.data.created).toBe(0)
})
it('matches a duplicate by name (case-insensitive)', async () => {
mockFetchAllRows.mockResolvedValue([{ id: 'x', name: 'Konsulttimme', article_number: null }])
const res = await POST(makeRequest({
rows: [row({ name: 'KONSULTTIMME' })],
update_duplicates: false,
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.skipped).toBe(1)
})
it('treats a 23505 unique violation as a soft skip', async () => {
enqueue({ data: null, error: { code: '23505', message: 'duplicate key' } })
const res = await POST(makeRequest({
rows: [row({ article_number: 'A-DUP' })],
update_duplicates: false,
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.skipped).toBe(1)
expect(body.data.failed).toBe(0)
})
it('drops an inactive/unknown revenue account and records a warning', async () => {
mockCheckRevenueAccount.mockResolvedValue('activatable')
enqueue({ data: { id: 'a1', name: 'Konsulttimme', article_number: 'A-1' } })
const res = await POST(makeRequest({
rows: [row({ article_number: 'A-1', revenue_account: '3999' })],
update_duplicates: false,
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.created).toBe(1)
expect(body.data.warnings.length).toBeGreaterThan(0)
expect(body.data.warnings[0]).toContain('3999')
})
})
describe('POST /api/import/articles/execute currency handling', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
mockFetchAllRows.mockResolvedValue([])
mockCheckRevenueAccount.mockResolvedValue('ok')
mockEnsureArticleNumber.mockResolvedValue('AUTO-1')
})
it('imports a valid Valuta code and defaults missing to SEK', async () => {
// First queued result: lazy currencies reference read.
enqueue({ data: [{ code: 'SEK' }, { code: 'EUR' }, { code: 'USD' }] })
enqueue({ data: { id: 'a1', name: 'EU-tjanst', article_number: 'A-1', currency: 'EUR' } })
enqueue({ data: { id: 'a2', name: 'Svensk tjanst', article_number: 'A-2', currency: 'SEK' } })
const res = await POST(makeRequest({
rows: [
row({ name: 'EU-tjanst', article_number: 'A-1', currency: 'EUR' }),
row({ row_index: 3, name: 'Svensk tjanst', article_number: 'A-2', currency: null }),
],
update_duplicates: false,
}))
const { status, body } = await parseJsonResponse<{ data: { created: number; warnings: string[] } }>(res)
expect(status).toBe(200)
expect(body.data.created).toBe(2)
expect(body.data.warnings).toEqual([])
const inserts = mockSupabase.from.mock.calls.filter((c: unknown[]) => c[0] === 'articles')
expect(inserts.length).toBeGreaterThan(0)
})
it('drops a code missing from the currencies table with a warning', async () => {
enqueue({ data: [{ code: 'SEK' }, { code: 'EUR' }] })
enqueue({ data: { id: 'a1', name: 'X', article_number: 'A-1', currency: 'SEK' } })
const res = await POST(makeRequest({
rows: [row({ article_number: 'A-1', currency: 'XXX' })],
update_duplicates: false,
}))
const { status, body } = await parseJsonResponse<{ data: { warnings: string[] } }>(res)
expect(status).toBe(200)
expect(body.data.warnings.some((w) => w.includes('XXX'))).toBe(true)
})
it('rejects a malformed currency shape at validation', async () => {
const res = await POST(makeRequest({
rows: [row({ currency: 'EURO' })],
update_duplicates: false,
}))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
})
+258
View File
@@ -0,0 +1,258 @@
import { normalizeNameKey as nameKey } from '@/lib/import/shared/column-utils'
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { eventBus } from '@/lib/events'
import { validateBody } from '@/lib/api/validate'
import { ArticleImportExecuteSchema } from '@/lib/api/schemas'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { ensureArticleNumber } from '@/lib/articles/ensure-article-number'
import { checkRevenueAccount, type RevenueAccountStatus } from '@/lib/articles/validate-revenue-account'
import type { Article } from '@/types'
import type { ArticleImportExecuteResult } from '@/lib/import/articles/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
interface ExistingArticle {
id: string
name: string
article_number: string | null
}
/**
* POST /api/import/articles/execute
*
* Imports validated article rows. Duplicates (matched by article number, then
* by name) are either updated (merge: only non-empty fields overwrite) or
* skipped based on `update_duplicates`. An optional BAS revenue-account override
* is kept only when it is an active class-3 account; unknown/inactive accounts
* are dropped (with a warning) rather than mutating the chart of accounts.
*/
export const POST = withRouteContext(
'register_import.articles.execute',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const result = await validateBody(request, ArticleImportExecuteSchema, {
log,
operation: 'register_import.articles.execute',
})
if (!result.success) return result.response
const { rows, update_duplicates } = result.data
const opLog = log.child({ rowCount: rows.length, updateDuplicates: update_duplicates })
if (rows.length === 0) {
return errorResponseFromCode('REG_IMPORT_NO_ROWS', opLog, { requestId })
}
try {
const existingRaw = await fetchAllRows(({ from, to }) =>
supabase
.from('articles')
.select('id, name, article_number')
.eq('company_id', companyId)
.range(from, to),
)
const existing = existingRaw as unknown as ExistingArticle[]
const byNumber = new Map<string, ExistingArticle>()
const byName = new Map<string, ExistingArticle>()
for (const a of existing) {
if (a.article_number) byNumber.set(a.article_number, a)
const nk = nameKey(a.name)
if (nk && !byName.has(nk)) byName.set(nk, a)
}
// Revenue-account validation is cached per distinct account so a large
// import doesn't re-query the chart for every row.
const accountStatusCache = new Map<string, RevenueAccountStatus>()
const droppedAccounts = new Set<string>()
const warnings: string[] = []
// Currency codes are validated against the currencies reference table
// (the same set the articles.currency FK enforces): unknown codes are
// dropped with a warning instead of failing the row on a FK violation.
// Loaded lazily: most files carry no Valuta column at all. If the
// reference read fails, codes pass through and the FK stays the backstop.
let validCurrencies: Set<string> | null | undefined
const droppedCurrencies = new Set<string>()
const resolveCurrency = async (code: string | null | undefined): Promise<string | null> => {
if (!code) return null
if (validCurrencies === undefined) {
const { data: currencyRows } = await supabase.from('currencies').select('code')
validCurrencies = currencyRows
? new Set((currencyRows as { code: string }[]).map((c) => c.code))
: null
}
if (!validCurrencies || validCurrencies.has(code)) return code
if (!droppedCurrencies.has(code)) {
droppedCurrencies.add(code)
warnings.push(`Valutan ${code} stöds inte, ignorerades: priset importerades som SEK.`)
}
return null
}
const resolveRevenueAccount = async (acc: string | null): Promise<string | null> => {
if (!acc) return null
let status = accountStatusCache.get(acc)
if (!status) {
status = await checkRevenueAccount(supabase, companyId!, acc)
accountStatusCache.set(acc, status)
}
if (status === 'ok') return acc
if (!droppedAccounts.has(acc)) {
droppedAccounts.add(acc)
warnings.push(
status === 'activatable'
? `Försäljningskonto ${acc} är inte aktiverat i kontoplanen. Artiklar importerades utan kontoöverstyrning.`
: `Försäljningskonto ${acc} är ogiltigt, ignorerades.`,
)
}
return null
}
const created: Article[] = []
const updated: Article[] = []
let skipped = 0
const errors: { row_index: number; name: string; reason: string }[] = []
for (const row of rows) {
const nk = nameKey(row.name)
const match =
(row.article_number ? byNumber.get(row.article_number) : undefined) ??
(nk ? byName.get(nk) : undefined) ??
null
const revenueAccount = await resolveRevenueAccount(row.revenue_account)
const currency = await resolveCurrency(row.currency)
if (match) {
if (!update_duplicates) {
skipped++
continue
}
// Merge mode: overwrite only fields the file clearly carries a value
// for. type/unit/vat_rate carry parser defaults that can't be told
// apart from "absent", so they are left untouched to avoid clobbering.
const merged: Record<string, unknown> = {}
if (row.name) merged.name = row.name
if (row.name_en) merged.name_en = row.name_en
if (row.price_excl_vat > 0) merged.price_excl_vat = row.price_excl_vat
if (row.cost_price !== null) merged.cost_price = row.cost_price
if (row.ean) merged.ean = row.ean
if (row.housework_type) merged.housework_type = row.housework_type
if (row.notes) merged.notes = row.notes
if (revenueAccount) merged.revenue_account = revenueAccount
// Only when the file explicitly carries a valid currency: absence
// must never reset an existing non-SEK article to SEK.
if (currency) merged.currency = currency
if (Object.keys(merged).length === 0) {
skipped++
continue
}
const { data, error } = await supabase
.from('articles')
.update(merged)
.eq('id', match.id)
.eq('company_id', companyId)
.select()
.single()
if (error) {
errors.push({ row_index: row.row_index, name: row.name, reason: getUserErrorMessage(error) })
continue
}
if (data) updated.push(data as Article)
continue
}
// No match, create.
const { data, error } = await supabase
.from('articles')
.insert({
user_id: user.id,
company_id: companyId,
name: row.name,
name_en: row.name_en,
type: row.type,
unit: row.unit || 'st',
price_excl_vat: row.price_excl_vat,
currency: currency ?? 'SEK',
vat_rate: row.vat_rate,
revenue_account: revenueAccount,
cost_price: row.cost_price,
ean: row.ean,
housework_type: row.housework_type,
notes: row.notes,
article_number: row.article_number,
})
.select()
.single()
if (error) {
// Unique violation on (company_id, article_number): treat as a soft
// skip (manual number collided with an existing or in-batch article).
if (error.code === '23505') {
skipped++
continue
}
errors.push({ row_index: row.row_index, name: row.name, reason: getUserErrorMessage(error) })
continue
}
if (data) {
// Auto-number when the file didn't supply one. Non-fatal: an
// unnumbered article is still usable and can be numbered later.
if (!data.article_number) {
try {
data.article_number = await ensureArticleNumber(supabase, companyId!, data.id)
} catch (err) {
opLog.warn('article number assignment failed', err as Error, { articleId: data.id })
}
}
created.push(data as Article)
// Track newly inserted number + name so later rows in the same batch
// dedup against them too.
const newArticle = data as ExistingArticle
if (newArticle.article_number) byNumber.set(newArticle.article_number, newArticle)
const nk = nameKey(newArticle.name)
if (nk && !byName.has(nk)) byName.set(nk, newArticle)
}
}
// Emit events for downstream listeners (non-blocking).
for (const a of created) {
await eventBus.emit({
type: 'article.created',
payload: { article: a, companyId: companyId!, userId: user.id },
})
}
const response: ArticleImportExecuteResult = {
success: errors.length === 0,
created: created.length,
updated: updated.length,
skipped,
failed: errors.length,
errors,
warnings,
}
opLog.info('article import complete', response)
return NextResponse.json({ data: response })
} catch (err) {
opLog.error('article import execute failed', err as Error)
return errorResponseFromCode('REG_IMPORT_EXECUTE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
{ requireWrite: true },
)
+130
View File
@@ -0,0 +1,130 @@
import { NextResponse } from 'next/server'
import { parseArticlesFile } from '@/lib/import/articles/parser'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { ArticleColumnOverridesSchema } from '@/lib/api/schemas'
import type {
AnnotatedArticleRow,
ArticleImportParseResult,
DetectedArticleColumns,
} from '@/lib/import/articles/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { normalizeNameKey as nameKey } from '@/lib/import/shared/column-utils'
const ALLOWED_EXTENSIONS = ['.xlsx', '.xls', '.csv', '.ods']
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
/**
* POST /api/import/articles/parse
*
* Accepts an Excel/CSV file via FormData, auto-detects columns, parses rows,
* and annotates each row with any duplicate-match against existing articles
* (by article number first, then by name).
*/
export const POST = withRouteContext(
'register_import.articles.parse',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const formData = await request.formData()
const file = formData.get('file') as File | null
const columnOverridesRaw = formData.get('column_overrides') as string | null
if (!file) {
return errorResponseFromCode('REG_IMPORT_NO_FILE', log, { requestId })
}
if (file.size > MAX_FILE_SIZE) {
return errorResponseFromCode('REG_IMPORT_FILE_TOO_LARGE', log, {
requestId,
details: { sizeMb: +(file.size / 1024 / 1024).toFixed(1) },
})
}
const ext = '.' + file.name.split('.').pop()?.toLowerCase()
if (!ALLOWED_EXTENSIONS.includes(ext)) {
return errorResponseFromCode('REG_IMPORT_INVALID_FORMAT', log, {
requestId,
details: { extension: ext, allowed: ALLOWED_EXTENSIONS },
})
}
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
let columnOverrides: DetectedArticleColumns | undefined
if (columnOverridesRaw) {
let raw: unknown
try {
raw = JSON.parse(columnOverridesRaw)
} catch {
return errorResponseFromCode('REG_IMPORT_INVALID_COLUMN_OVERRIDES', opLog, { requestId })
}
// Validate shape/indices before trusting it to drive the parser.
const parsed = ArticleColumnOverridesSchema.safeParse(raw)
if (!parsed.success) {
return errorResponseFromCode('REG_IMPORT_INVALID_COLUMN_OVERRIDES', opLog, { requestId })
}
columnOverrides = parsed.data
}
try {
const buffer = await file.arrayBuffer()
const parsed = parseArticlesFile(buffer, file.name, columnOverrides)
// Fetch existing articles for duplicate detection.
const existing = await fetchAllRows(({ from, to }) =>
supabase
.from('articles')
.select('id, name, article_number')
.eq('company_id', companyId)
.range(from, to),
)
const byNumber = new Map<string, { id: string; name: string }>()
const byName = new Map<string, { id: string; name: string }>()
for (const a of existing) {
if (a.article_number) byNumber.set(String(a.article_number), { id: a.id, name: a.name })
const nk = nameKey(a.name)
if (nk && !byName.has(nk)) byName.set(nk, { id: a.id, name: a.name })
}
let duplicateCount = 0
const annotated: AnnotatedArticleRow[] = parsed.rows.map((r) => {
let match: AnnotatedArticleRow['duplicate_match'] = null
if (r.article_number && byNumber.has(r.article_number)) {
const e = byNumber.get(r.article_number)!
match = { article_id: e.id, matched_by: 'article_number', existing_name: e.name }
} else {
const nk = nameKey(r.name)
if (nk && byName.has(nk)) {
const e = byName.get(nk)!
match = { article_id: e.id, matched_by: 'name', existing_name: e.name }
}
}
if (match) duplicateCount++
return { ...r, duplicate_match: match }
})
const result: ArticleImportParseResult = {
filename: parsed.filename,
sheet_name: parsed.sheet_name,
total_rows: annotated.length,
detected_columns: parsed.detected_columns,
headers: parsed.headers,
preview_rows: parsed.preview_rows,
rows: annotated,
duplicate_count: duplicateCount,
warnings: parsed.warnings,
}
return NextResponse.json({ data: result })
} catch (err) {
opLog.error('article import parse failed', err as Error)
return errorResponseFromCode('REG_IMPORT_PARSE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
)
@@ -0,0 +1,198 @@
/**
* Tests for DELETE /api/import/bank-file/[id]/undo.
*
* Exercises the route through the real withRouteContext wrapper, mocking its
* auth/company/write dependencies and the undoBankFileImport service. Covers:
* 401, 403 viewer, 403 non-owner/admin (RPC 42501 mapped to
* BANK_FILE_UNDO_FORBIDDEN), 404 unknown import (BANK_FILE_UNDO_NOT_FOUND),
* the success passthrough with the skip report, and the
* BANK_FILE_UNDO_FAILED envelope with the service's Swedish reason.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
const { supabase, 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 undoBankFileImportMock = vi.fn()
vi.mock('@/lib/import/bank-file/undo', () => ({
undoBankFileImport: (...args: unknown[]) => undoBankFileImportMock(...args),
}))
import { DELETE } from '../route'
const routeParams = () => createMockRouteParams({ id: 'import-1' })
describe('DELETE /api/import/bank-file/[id]/undo', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await DELETE(
createMockRequest('/api/import/bank-file/import-1/undo', { method: 'DELETE' }),
routeParams(),
)
expect(response.status).toBe(401)
expect(undoBankFileImportMock).not.toHaveBeenCalled()
})
it('returns 403 for a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const response = await DELETE(
createMockRequest('/api/import/bank-file/import-1/undo', { method: 'DELETE' }),
routeParams(),
)
expect(response.status).toBe(403)
expect(undoBankFileImportMock).not.toHaveBeenCalled()
})
it('maps the RPC role rejection to BANK_FILE_UNDO_FORBIDDEN (403)', async () => {
undoBankFileImportMock.mockResolvedValue({
success: false,
deletedTransactions: 0,
skippedBooked: 0,
skippedMatchHistory: 0,
forbidden: true,
error: 'Endast ägare eller administratörer kan ångra en bankfilsimport',
})
const response = await DELETE(
createMockRequest('/api/import/bank-file/import-1/undo', { method: 'DELETE' }),
routeParams(),
)
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en: string }
}>(response)
expect(status).toBe(403)
expect(body.error.code).toBe('BANK_FILE_UNDO_FORBIDDEN')
expect(body.error.message).toBe(
'Endast ägare eller administratörer kan ångra en bankfilsimport.',
)
})
it('maps an unknown import to BANK_FILE_UNDO_NOT_FOUND (404)', async () => {
undoBankFileImportMock.mockResolvedValue({
success: false,
deletedTransactions: 0,
skippedBooked: 0,
skippedMatchHistory: 0,
notFound: true,
error: 'Importen hittades inte',
})
const response = await DELETE(
createMockRequest('/api/import/bank-file/import-1/undo', { method: 'DELETE' }),
routeParams(),
)
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en: string }
}>(response)
expect(status).toBe(404)
expect(body.error.code).toBe('BANK_FILE_UNDO_NOT_FOUND')
expect(body.error.message).toBe('Bankfilsimporten kunde inte hittas.')
expect(body.error.message_en).toBe('Bank file import not found.')
})
it('passes through the deletion report on a successful undo', async () => {
undoBankFileImportMock.mockResolvedValue({
success: true,
deletedTransactions: 212,
skippedBooked: 3,
skippedMatchHistory: 2,
})
const response = await DELETE(
createMockRequest('/api/import/bank-file/import-1/undo', { method: 'DELETE' }),
routeParams(),
)
const { status, body } = await parseJsonResponse<{
success: boolean
deletedTransactions: number
skippedBooked: number
skippedMatchHistory: number
}>(response)
expect(status).toBe(200)
expect(body).toEqual({
success: true,
deletedTransactions: 212,
skippedBooked: 3,
skippedMatchHistory: 2,
})
expect(undoBankFileImportMock).toHaveBeenCalledWith(
supabase,
'company-1',
'import-1',
'user-1',
)
})
it('returns the BANK_FILE_UNDO_FAILED envelope when the service refuses', async () => {
undoBankFileImportMock.mockResolvedValue({
success: false,
deletedTransactions: 0,
skippedBooked: 0,
skippedMatchHistory: 0,
error: 'Kan bara ångra slutförda importer (status: processing)',
})
const response = await DELETE(
createMockRequest('/api/import/bank-file/import-1/undo', { method: 'DELETE' }),
routeParams(),
)
const { status, body } = await parseJsonResponse<{
error: {
code: string
message: string
message_en: string
details?: { reason?: string }
}
}>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('BANK_FILE_UNDO_FAILED')
expect(body.error.message).toBe('Bankfilsimporten kunde inte ångras.')
expect(body.error.message_en).toBe('Failed to undo bank file import.')
expect(body.error.details?.reason).toBe(
'Kan bara ångra slutförda importer (status: processing)',
)
})
})
@@ -0,0 +1,65 @@
import { NextResponse } from 'next/server'
import { undoBankFileImport } from '@/lib/import/bank-file/undo'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
// Bulk-deleting a large batch (a full-year CSV is thousands of rows) can take
// longer than the default function timeout. Match the bank-file execute route
// so the serverless function doesn't kill the request first.
export const maxDuration = 300
/**
* DELETE /api/import/bank-file/[id]/undo
*
* Undo a completed bank file import: hard-deletes the batch's unbooked
* transactions, INCLUDING ignored ones, and marks the bank_file_imports row
* 'undone' so the same file can be re-imported cleanly (the execute route's
* upsert reuses the row). Rows it never touches, reported in the response:
* - booked rows (verifikat-anchored, direct or via payment/voucher links):
* räkenskapsinformation; unlink or storno, never delete.
* - unbooked rows with payment_match_log history: the log is append-only
* (BFL 7 kap) and cascades on delete, so the parent row must stay; it can
* be ignored instead. Same rule as DELETE /api/transactions/[id].
* Owner/admin only (enforced by the undo_bank_file_import RPC's actor gate;
* requireWrite blocks viewers before that).
*/
export const DELETE = withRouteContext(
'bank_file.undo',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, user, log, requestId } = ctx
const opLog = log.child({ bankFileImportId: id })
const result = await undoBankFileImport(supabase, companyId!, id, user.id)
if (!result.success) {
if (result.notFound) {
// 404, not 400: the id names no import in this company (same
// semantics as the SIE import routes' 'Import not found').
return errorResponseFromCode('BANK_FILE_UNDO_NOT_FOUND', opLog, { requestId })
}
if (result.forbidden) {
return errorResponseFromCode('BANK_FILE_UNDO_FORBIDDEN', opLog, { requestId })
}
return errorResponseFromCode('BANK_FILE_UNDO_FAILED', opLog, {
requestId,
details: { reason: result.error },
})
}
opLog.info('bank file import undone', {
actor: user.id,
deletedTransactions: result.deletedTransactions,
skippedBooked: result.skippedBooked,
skippedMatchHistory: result.skippedMatchHistory,
})
return NextResponse.json({
success: true,
deletedTransactions: result.deletedTransactions,
skippedBooked: result.skippedBooked,
skippedMatchHistory: result.skippedMatchHistory,
})
},
{ requireWrite: true },
)
@@ -0,0 +1,171 @@
/**
* Tests for GET /api/import/bank-file (the bank file import list).
*
* Exercises the route through the real withRouteContext wrapper, mocking only
* its auth/company dependencies and injecting a queued Supabase mock via
* requireAuth. Covers: 401, the { data, count, limit, offset } happy-path
* shape, the status filter, and the 500 path returning a Swedish error.
* Mirrors the GET /api/import/sie list test.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
import { eventBus } from '@/lib/events'
const { supabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { GET } from '../route'
// Next.js 16 always passes a params promise, even on static routes.
const staticParams = () => createMockRouteParams({})
const makeImportRow = (overrides: Record<string, unknown> = {}) => ({
id: 'import-1',
company_id: 'company-1',
filename: 'kontoutdrag-2026.csv',
file_format: 'swedbank',
transaction_count: 212,
imported_count: 208,
duplicate_count: 4,
matched_count: 12,
status: 'completed',
created_at: '2026-08-01T08:59:00Z',
updated_at: '2026-08-01T09:00:00Z',
...overrides,
})
describe('GET /api/import/bank-file', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
})
it('returns 401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await GET(createMockRequest('/api/import/bank-file'), staticParams())
expect(response.status).toBe(401)
})
it('returns { data, count, limit, offset } with defaults', async () => {
const rows = [makeImportRow(), makeImportRow({ id: 'import-2', status: 'undone' })]
enqueue({ data: rows, count: 2 })
const response = await GET(createMockRequest('/api/import/bank-file'), staticParams())
const { status, body } = await parseJsonResponse<{
data: { id: string }[]
count: number
limit: number
offset: number
}>(response)
expect(status).toBe(200)
expect(body.data).toHaveLength(2)
expect(body.data[0].id).toBe('import-1')
expect(body.count).toBe(2)
expect(body.limit).toBe(20)
expect(body.offset).toBe(0)
// Scoped to the active company; ordered newest-first; default range 0-19.
expect(findCalls('bank_file_imports', 'eq')).toContainEqual(['company_id', 'company-1'])
expect(findCalls('bank_file_imports', 'order')).toContainEqual([
'created_at',
{ ascending: false },
])
expect(findCalls('bank_file_imports', 'range')).toContainEqual([0, 19])
})
it('applies the status filter and custom limit/offset', async () => {
enqueue({ data: [makeImportRow()], count: 1 })
const response = await GET(
createMockRequest('/api/import/bank-file', {
searchParams: { status: 'completed', limit: '5', offset: '10' },
}),
staticParams(),
)
const { status, body } = await parseJsonResponse<{ limit: number; offset: number }>(response)
expect(status).toBe(200)
expect(body.limit).toBe(5)
expect(body.offset).toBe(10)
expect(findCalls('bank_file_imports', 'eq')).toContainEqual(['status', 'completed'])
expect(findCalls('bank_file_imports', 'range')).toContainEqual([10, 14])
})
it.each([
{ name: 'non-numeric limit', searchParams: { limit: 'abc' } },
{ name: 'partial-integer limit', searchParams: { limit: '12abc' } },
{ name: 'negative limit', searchParams: { limit: '-1' } },
{ name: 'zero limit', searchParams: { limit: '0' } },
{ name: 'limit above the cap', searchParams: { limit: '101' } },
{ name: 'negative offset', searchParams: { offset: '-5' } },
{ name: 'non-numeric offset', searchParams: { offset: 'NaN' } },
{ name: 'unknown status', searchParams: { status: 'sabotage' } },
])('returns a mapped 400 for $name', async ({ searchParams }) => {
const response = await GET(
createMockRequest('/api/import/bank-file', { searchParams }),
staticParams(),
)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('BANK_FILE_LIST_INVALID_QUERY')
// Invalid input must never reach the query builder.
expect(findCalls('bank_file_imports', 'range')).toEqual([])
})
it('accepts the boundary values limit=1, limit=100 and offset=0', async () => {
enqueue({ data: [], count: 0 })
enqueue({ data: [], count: 0 })
const min = await GET(
createMockRequest('/api/import/bank-file', { searchParams: { limit: '1', offset: '0' } }),
staticParams(),
)
expect(min.status).toBe(200)
const max = await GET(
createMockRequest('/api/import/bank-file', { searchParams: { limit: '100' } }),
staticParams(),
)
expect(max.status).toBe(200)
expect(findCalls('bank_file_imports', 'range')).toContainEqual([0, 0])
expect(findCalls('bank_file_imports', 'range')).toContainEqual([0, 99])
})
it('returns 500 with a Swedish error message on a database error', async () => {
enqueue({ data: null, error: { message: 'connection reset by peer' } })
const response = await GET(createMockRequest('/api/import/bank-file'), staticParams())
const { status, body } = await parseJsonResponse<{ error: string }>(response)
expect(status).toBe(500)
expect(typeof body.error).toBe('string')
// The raw driver message must not leak; the mapped message is Swedish.
expect(body.error).not.toContain('connection reset')
expect(body.error).toBe('Något gick fel. Försök igen.')
})
})
@@ -0,0 +1,125 @@
/**
* Tests for POST /api/import/bank-file/check-duplicates: the advisory
* duplicate preview the bank-file wizard calls after every (re-)parse.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
import { generateExternalId } from '@/lib/import/bank-file/parser'
import type { DuplicatePreviewResult } from '@/lib/transactions/dedup-preview'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { POST } from '../route'
const mockUser = { id: 'user-1', email: '[email protected]' }
const TX = {
date: '2024-06-15',
description: 'ICA Maxi Solna',
amount: -250.0,
currency: 'SEK',
}
function makeRequest(body: unknown) {
return createMockRequest('/api/import/bank-file/check-duplicates', {
method: 'POST',
body,
})
}
describe('POST /api/import/bank-file/check-duplicates', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
it('returns 401 when unauthenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(makeRequest({ transactions: [TX], format: 'lunar' }))
expect(res.status).toBe(401)
})
it('returns 400 when transactions or format is missing', async () => {
const noFormat = await POST(makeRequest({ transactions: [TX] }))
expect(noFormat.status).toBe(400)
const noTransactions = await POST(makeRequest({ format: 'lunar' }))
expect(noTransactions.status).toBe(400)
const emptyTransactions = await POST(makeRequest({ transactions: [], format: 'lunar' }))
expect(emptyTransactions.status).toBe(400)
})
it('returns 400 for an unknown format id', async () => {
const res = await POST(makeRequest({ transactions: [TX], format: 'not_a_bank' }))
expect(res.status).toBe(400)
})
it('returns 400 when the transactions array exceeds the 20000-row cap', async () => {
const oversized = Array.from({ length: 20001 }, () => TX)
const res = await POST(makeRequest({ transactions: oversized, format: 'lunar' }))
expect(res.status).toBe(400)
})
it('flags rows whose server-computed external_id already exists (id parity with execute)', async () => {
// The stored id is computed with the SAME derivation the execute route
// uses: generateExternalId(tx, format, index). The route only collides on
// it if its own server-side computation is byte-identical.
const storedId = generateExternalId(TX, 'lunar', 0)
enqueue({ data: [] }) // booked map
enqueue({ data: [] }) // unbooked map
enqueue({ data: [{ external_id: storedId }] }) // external_id chunk
const res = await POST(makeRequest({
transactions: [TX, { ...TX, description: 'Coop Stockholm', amount: -99.5 }],
format: 'lunar',
}))
const { status, body } = await parseJsonResponse<{ data: DuplicatePreviewResult }>(res)
expect(status).toBe(200)
expect(body.data.duplicate_row_indexes).toEqual([0])
expect(body.data.duplicate_count).toBe(1)
expect(body.data.by_reason).toEqual({ external_id: 1, content_bridge: 0 })
})
it('flags content-bridge duplicates against stored rows (happy path)', async () => {
enqueue({ data: [] }) // booked map
enqueue({
data: [{
date: TX.date, amount: TX.amount,
original_description: TX.description, description: TX.description,
import_source: 'enable_banking', currency: 'SEK',
}],
}) // unbooked map: PSD2 twin of row 0
enqueue({ data: [] }) // external_id chunk: no Layer-1 hit
const res = await POST(makeRequest({
transactions: [TX, { ...TX, description: 'Coop Stockholm' }],
format: 'lunar',
}))
const { status, body } = await parseJsonResponse<{ data: DuplicatePreviewResult }>(res)
expect(status).toBe(200)
expect(body.data.duplicate_row_indexes).toEqual([0])
expect(body.data.by_reason).toEqual({ external_id: 0, content_bridge: 1 })
})
})
@@ -0,0 +1,61 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { BankFileCheckDuplicatesSchema } from '@/lib/api/schemas'
import { generateExternalId } from '@/lib/import/bank-file/parser'
import { previewDuplicates } from '@/lib/transactions/dedup-preview'
import type { ParsedBankTransaction } from '@/lib/import/bank-file/types'
/**
* POST /api/import/bank-file/check-duplicates
*
* Read-only duplicate preview for the bank-file import wizard: given the
* parsed rows and their format, reports which rows execute-side ingest will
* skip as duplicates (exact external_id collisions + the content bridge), so
* the wizard can warn BEFORE the user confirms instead of silently importing
* fewer rows than promised.
*
* A dedicated endpoint rather than part of /parse because the generic_csv
* path re-parses client-side after column mapping and never re-hits the parse
* route. The result is ADVISORY: execute's own ingest result stays
* authoritative (see lib/transactions/dedup-preview.ts for the deliberate
* preview/execute differences), and nothing is written here.
*/
export const POST = withRouteContext(
'bank_file.check_duplicates',
async (request, ctx) => {
const { supabase, companyId, log } = ctx
const validation = await validateBody(request, BankFileCheckDuplicatesSchema, {
log,
operation: 'bank_file.check_duplicates',
})
if (!validation.success) return validation.response
const { transactions, format } = validation.data
// Identical id derivation to the execute route: generateExternalId over
// the same rows in the same order, so preview Layer-1 collides on exactly
// the ids execute will collide on.
const raws = transactions.map((tx, index) => ({
date: tx.date,
description: tx.description,
amount: tx.amount,
currency: tx.currency || 'SEK',
external_id: generateExternalId(
{
date: tx.date,
description: tx.description,
amount: tx.amount,
currency: tx.currency || 'SEK',
raw_line: tx.raw_line ?? undefined,
} satisfies ParsedBankTransaction,
format,
index,
),
}))
const preview = await previewDuplicates(supabase, companyId, raws)
return NextResponse.json({ data: preview })
},
)
@@ -0,0 +1,179 @@
/**
* Tests for POST /api/import/bank-file/execute, focused on the SIE-overlap
* behavior: a bank file covering a period a completed SIE import already
* booked must (a) suppress auto-categorization to prevent double-booking and
* (b) trigger the per-account reconciliation sweep and stamp its summary,
* because CSV is how a migrator gets pre-PSD2 history into the system.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const getCompanyRoleMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
getCompanyRole: (...args: unknown[]) => getCompanyRoleMock(...args),
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const ingestMock = vi.fn()
vi.mock('@/lib/transactions/ingest', () => ({
ingestTransactions: (...args: unknown[]) => ingestMock(...args),
}))
const sweepMock = vi.fn()
vi.mock('@/lib/reconciliation/unattended-sweep', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/reconciliation/unattended-sweep')>()
return {
...actual,
runUnattendedReconciliationSweep: (...args: unknown[]) => sweepMock(...args),
}
})
import { POST } from '../route'
const emptyParams = { params: Promise.resolve({}) }
function makeBody(overrides: Record<string, unknown> = {}) {
return {
transactions: [
{ date: '2025-03-10', description: 'Hyra mars', amount: -12000, currency: 'SEK' },
{ date: '2025-01-05', description: 'Kundbetalning', amount: 25000, currency: 'SEK' },
],
format: 'seb',
filename: 'kontoutdrag.csv',
file_hash: 'abc123',
skip_duplicates: true,
auto_categorize: true,
...overrides,
}
}
function emptyIngestResult(overrides: Record<string, unknown> = {}) {
return {
imported: 2,
duplicates: 0,
reconciled: 0,
auto_categorized: 0,
auto_matched_invoices: 0,
errors: 0,
transaction_ids: ['t-1', 't-2'],
...overrides,
}
}
function emptySweepResult(overrides: Record<string, unknown> = {}) {
return {
accounts: [],
applied: 1,
errors: 0,
skippedBelowThreshold: 1,
suggested: 1,
unmatched: 0,
...overrides,
}
}
describe('POST /api/import/bank-file/execute (SIE overlap)', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'owner', companyId: 'company-1' })
ingestMock.mockResolvedValue(emptyIngestResult())
sweepMock.mockResolvedValue(emptySweepResult())
})
it('returns 401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const request = createMockRequest('/api/import/bank-file/execute', {
method: 'POST',
body: makeBody(),
})
const response = await POST(request, emptyParams)
expect(response.status).toBe(401)
})
it('suppresses auto-categorization, runs the sweep over the file window, and stamps the summary on SIE overlap', async () => {
enqueue({ data: { id: 'import-1' } }) // bank_file_imports upsert
enqueue({ data: { id: 'sie-1' } }) // sie_imports overlap: found
enqueue({ data: null }) // bank_file_imports status update
enqueue({ data: null }) // sie_sweep stamp update
enqueue({ data: [{ id: 't-1' }, { id: 't-2' }] }) // imported tx for event
const request = createMockRequest('/api/import/bank-file/execute', {
method: 'POST',
body: makeBody(),
})
const response = await POST(request, emptyParams)
const { status } = await parseJsonResponse(response)
expect(status).toBe(200)
// Ingest was told to skip auto-categorization (double-booking guard).
const ingestOptions = ingestMock.mock.calls[0][4] as Record<string, unknown>
expect(ingestOptions.skipAutoCategorization).toBe(true)
// Sweep ran over the file's own date window (min/max of its rows).
expect(sweepMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', {
dateFrom: '2025-01-05',
dateTo: '2025-03-10',
})
})
it('runs no sweep and keeps categorization when there is no SIE overlap', async () => {
enqueue({ data: { id: 'import-1' } }) // upsert
enqueue({ data: null }) // sie_imports overlap: none
enqueue({ data: null }) // status update
enqueue({ data: [{ id: 't-1' }] }) // imported tx for event
const request = createMockRequest('/api/import/bank-file/execute', {
method: 'POST',
body: makeBody(),
})
const response = await POST(request, emptyParams)
expect(response.status).toBe(200)
const ingestOptions = ingestMock.mock.calls[0][4] as Record<string, unknown>
expect(ingestOptions.skipAutoCategorization).toBeUndefined()
// Every inserted row is stamped with the batch id so the owner/admin
// "undo this import" action can scope its bulk delete exactly.
expect(ingestOptions.bankFileImportId).toBe('import-1')
expect(sweepMock).not.toHaveBeenCalled()
})
it('never sweeps for a viewer (raw insert only)', async () => {
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'viewer', companyId: 'company-1' })
enqueue({ data: { id: 'import-1' } }) // upsert
enqueue({ data: { id: 'sie-1' } }) // overlap found
enqueue({ data: null }) // status update
enqueue({ data: [{ id: 't-1' }] }) // imported tx for event
const request = createMockRequest('/api/import/bank-file/execute', {
method: 'POST',
body: makeBody(),
})
const response = await POST(request, emptyParams)
expect(response.status).toBe(200)
const ingestOptions = ingestMock.mock.calls[0][4] as Record<string, unknown>
expect(ingestOptions.rawInsertOnly).toBe(true)
expect(sweepMock).not.toHaveBeenCalled()
})
})
+240
View File
@@ -0,0 +1,240 @@
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { ingestTransactions } from '@/lib/transactions/ingest'
import type { RawTransaction } from '@/types'
import { generateExternalId } from '@/lib/import/bank-file/parser'
import type { IngestOptions } from '@/types'
import { getCompanyRole } from '@/lib/auth/require-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { ParsedBankTransaction, BankFileFormatId } from '@/lib/import/bank-file/types'
import type { Transaction } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import {
runUnattendedReconciliationSweep,
toSweepSummary,
} from '@/lib/reconciliation/unattended-sweep'
ensureInitialized()
// Bank-file imports run a sequential, per-row ingest (insert + invoice/supplier
// matching + FX lookup). A full-year file (300+ rows) takes ~85s of server time,
// which sits right on the platform's default function limit and gets killed
// mid-run: the import "spins then aborts" for the user. Give it the same 5-minute
// budget the SIE import route uses (app/api/import/sie/execute/route.ts).
export const maxDuration = 300
interface ExecuteRequest {
transactions: ParsedBankTransaction[]
format: BankFileFormatId
filename: string
file_hash: string
skip_duplicates: boolean
auto_categorize: boolean
settlement_account?: string
}
/**
* POST /api/import/bank-file/execute
*
* Executes the import of confirmed bank transactions. Records the import in
* `bank_file_imports`, calls `ingestTransactions`, and emits `transaction.synced`.
*/
export const POST = withRouteContext(
'bank_file.execute',
async (request, ctx) => {
const { user, supabase, log, requestId } = ctx
// We still call getCompanyRole because viewers are allowed through with
// rawInsertOnly behavior: `requireWrite: true` would block them.
const roleCheck = await getCompanyRole(supabase, user.id)
if (!roleCheck.ok) {
// Inject the request id for traceability and pass through.
if (!roleCheck.response.headers.get('X-Request-Id')) {
roleCheck.response.headers.set('X-Request-Id', requestId)
}
return roleCheck.response
}
const { role, companyId } = roleCheck
const body: ExecuteRequest = await request.json()
const {
transactions, format, filename, file_hash,
skip_duplicates: _skip_duplicates = true,
auto_categorize: _auto_categorize = true,
settlement_account,
} = body
if (!transactions || transactions.length === 0) {
return errorResponseFromCode('BANK_FILE_NO_TRANSACTIONS', log, { requestId })
}
const opLog = log.child({ filename, fileHash: file_hash, txCount: transactions.length })
try {
const { data: importRecord, error: importError } = await supabase
.from('bank_file_imports')
.upsert({
user_id: user.id,
company_id: companyId,
filename,
file_hash,
file_format: format,
transaction_count: transactions.length,
status: 'processing',
date_from: transactions.map((t) => t.date).sort()[0] || null,
date_to: transactions.map((t) => t.date).sort().reverse()[0] || null,
}, { onConflict: 'company_id,file_hash' })
.select()
.single()
if (importError) {
opLog.error('failed to create bank_file_imports record', importError)
return errorResponseFromCode('BANK_FILE_IMPORT_RECORD_FAILED', opLog, {
requestId,
details: { reason: getUserErrorMessage(importError) },
})
}
const rawTransactions: RawTransaction[] = transactions.map((tx, index) => ({
date: tx.date,
description: tx.description,
amount: tx.amount,
currency: tx.currency || 'SEK',
external_id: generateExternalId(tx, format, index),
reference: tx.reference || null,
import_source: format === 'camt053' ? 'camt053' : `csv_${format}`,
}))
// Detect SIE overlap, mirroring the enable-banking sync paths: a bank
// file covering a period a completed SIE import already booked must be
// matched against the imported verifikat, not re-booked. CSV is the only
// way a migrator gets deep history (PSD2 windows stop at ~90 days), so
// this path is the primary one for the Fortnox/SIE migrator journey.
const fileDateFrom = transactions.map((t) => t.date).sort()[0] || undefined
const fileDateTo = transactions.map((t) => t.date).sort().reverse()[0] || undefined
let sieOverlap: { id: string } | null = null
if (fileDateFrom) {
const { data } = await supabase
.from('sie_imports')
.select('id')
.eq('company_id', companyId)
.eq('status', 'completed')
.gte('fiscal_year_end', fileDateFrom)
.limit(1)
.maybeSingle()
sieOverlap = data ?? null
}
const ingestOptions: IngestOptions = {
// Stamp every inserted row with this batch so the owner/admin
// "undo this import" action can scope its bulk delete exactly.
bankFileImportId: importRecord.id,
}
if (settlement_account) ingestOptions.settlementAccount = settlement_account
if (role === 'viewer') ingestOptions.rawInsertOnly = true
if (sieOverlap) ingestOptions.skipAutoCategorization = true
const ingestResult = await ingestTransactions(supabase, companyId, user.id, rawTransactions, ingestOptions)
if (ingestResult.errors > 0 && ingestResult.first_error) {
opLog.error('bank file ingest reported insert errors', new Error(ingestResult.first_error.message), {
errorCount: ingestResult.errors,
code: ingestResult.first_error.code,
details: ingestResult.first_error.details,
hint: ingestResult.first_error.hint,
})
}
const errorMessage = ingestResult.errors > 0
? ingestResult.first_error
? `${ingestResult.errors} fel: ${ingestResult.first_error.message}${ingestResult.first_error.details ? ` (${ingestResult.first_error.details})` : ''}`
: `${ingestResult.errors} transactions failed to import`
: null
await supabase
.from('bank_file_imports')
.update({
imported_count: ingestResult.imported,
duplicate_count: ingestResult.duplicates,
matched_count: ingestResult.auto_matched_invoices,
status: ingestResult.errors > 0 && ingestResult.imported === 0 ? 'failed' : 'completed',
error_message: errorMessage,
})
.eq('id', importRecord.id)
// SIE-overlap-gated reconciliation sweep (issue: no sweep fired after a
// bank CSV import, yet CSV is how a migrator gets pre-PSD2 history). One
// scoped run per enabled cash account; >= 0.9 auto-links, the 0.75-0.89
// band persists as reviewable suggestions. Viewers skip it: the sweep
// updates transactions, which viewers cannot do.
if (sieOverlap && ingestResult.imported > 0 && role !== 'viewer') {
try {
const sweepResult = await runUnattendedReconciliationSweep(supabase, companyId, user.id, {
dateFrom: fileDateFrom,
dateTo: fileDateTo,
})
const { error: stampError } = await supabase
.from('bank_file_imports')
.update({
sie_sweep: toSweepSummary(sweepResult, {
dateFrom: fileDateFrom,
dateTo: fileDateTo,
}),
})
.eq('id', importRecord.id)
if (stampError) {
// The links/suggestions are already written; only the UI summary
// is missing. Say so instead of letting the sweep look unrun.
opLog.warn('failed to stamp sie_sweep summary on bank_file_imports', stampError)
}
if (sweepResult.applied > 0 || sweepResult.suggested > 0) {
opLog.info('post-import SIE reconciliation sweep', {
applied: sweepResult.applied,
suggested: sweepResult.suggested,
unmatched: sweepResult.unmatched,
})
}
} catch (err) {
// Non-critical: rows stay in "Att bokföra" for manual matching.
opLog.warn('post-import SIE reconciliation sweep failed', err as Error)
}
}
if (ingestResult.imported > 0 && ingestResult.transaction_ids.length > 0) {
try {
const { data: importedTransactions } = await supabase
.from('transactions')
.select('*')
.in('id', ingestResult.transaction_ids)
if (importedTransactions && importedTransactions.length > 0) {
await eventBus.emit({
type: 'transaction.synced',
payload: {
transactions: importedTransactions as Transaction[],
userId: user.id,
companyId,
},
})
}
} catch (err) {
opLog.warn('transaction.synced event emission failed', err as Error)
}
}
return NextResponse.json({
data: {
import_id: importRecord.id,
...ingestResult,
},
})
} catch (err) {
opLog.error('bank file execute failed', err as Error)
return errorResponseFromCode('BANK_FILE_EXECUTE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
)
@@ -0,0 +1,91 @@
/**
* Tests for POST /api/import/bank-file/parse, focused on the skattekonto
* redirect: a skattekontoutdrag uploaded into the bank flow must be refused
* with a pointer to the dedicated importer (its rows belong on 1630, not on
* a bank account), while an explicit format override still forces a bank
* parse as the escape hatch.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { 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'),
}))
vi.mock('@/lib/auth/require-write', () => ({
getCompanyRole: vi.fn().mockResolvedValue({ ok: true, role: 'owner', companyId: 'company-1' }),
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
import { POST } from '../route'
const emptyParams = { params: Promise.resolve({}) }
const SKATTEKONTO_CSV = [
'"Testbolaget AB";"556677-8899";""',
'"";"Ingående saldo 2026-05-03";"-500"',
'"2026-06-06";"Kostnadsränta";"-10"',
'"";"Utgående saldo 2026-06-06";"-510"',
].join('\r\n')
const SEB_BANK_CSV = [
'Bokföringsdag;Valutadag;Verifikationsnummer;Text;Belopp;Saldo',
'2024-01-15;2024-01-15;12345;SPOTIFY AB;-99,00;12345,67',
].join('\n')
function makeFileRequest(content: string, filename: string, format?: string) {
const formData = new FormData()
formData.append('file', new File([content], filename, { type: 'text/csv' }))
if (format) formData.append('format', format)
return new Request('http://localhost:3000/api/import/bank-file/parse', {
method: 'POST',
body: formData,
})
}
describe('POST /api/import/bank-file/parse (skattekonto redirect)', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
})
it('refuses a skattekontoutdrag with a redirect error code', async () => {
enqueue({ data: null }) // no prior bank_file_imports row
const response = await POST(
makeFileRequest(SKATTEKONTO_CSV, 'Kontoutdrag 556677-8899 2026-05-03--2026-08-01.csv'),
emptyParams,
)
const body = await response.json()
expect(response.status).toBe(400)
expect(body.error.code).toBe('BANK_FILE_SKATTEKONTO_DETECTED')
})
it('honors an explicit format override as the escape hatch', async () => {
enqueue({ data: null }) // no prior bank_file_imports row
const response = await POST(
makeFileRequest(SKATTEKONTO_CSV, 'skattekonto.skv', 'generic_csv'),
emptyParams,
)
// Not the redirect: the override forces a bank parse attempt.
const body = await response.json()
expect(body?.error?.code).not.toBe('BANK_FILE_SKATTEKONTO_DETECTED')
})
it('parses a real bank file normally', async () => {
enqueue({ data: null }) // no prior bank_file_imports row
const response = await POST(makeFileRequest(SEB_BANK_CSV, 'kontoutdrag.csv'), emptyParams)
const body = await response.json()
expect(response.status).toBe(200)
expect(body.data.detected_format).toBe('seb')
expect(body.data.parse_result.transactions).toHaveLength(1)
})
})
+101
View File
@@ -0,0 +1,101 @@
import { NextResponse } from 'next/server'
import { parseBankFile, generateFileHash, detectFileFormat } from '@/lib/import/bank-file/parser'
import { detectSkattekontoFile } from '@/lib/import/skattekonto-file/parser'
import { decodeFileContent } from '@/lib/import/shared/encoding'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { BankFileFormatId } from '@/lib/import/bank-file/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* POST /api/import/bank-file/parse
*
* Accepts a bank file (CSV/XML) via FormData, auto-detects format, and returns
* a parsed transactions preview with duplicate detection.
*/
export const POST = withRouteContext(
'bank_file.parse',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const formData = await request.formData()
const file = formData.get('file') as File | null
const formatOverride = formData.get('format') as BankFileFormatId | null
if (!file) {
return errorResponseFromCode('BANK_FILE_NO_FILE', log, { requestId })
}
if (file.size > 10 * 1024 * 1024) {
return errorResponseFromCode('BANK_FILE_TOO_LARGE', log, {
requestId,
details: { sizeMb: +(file.size / 1024 / 1024).toFixed(1) },
})
}
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
try {
const arrayBuffer = await file.arrayBuffer()
const content = decodeFileContent(arrayBuffer)
const fileHash = generateFileHash(content)
const { data: existingImport } = await supabase
.from('bank_file_imports')
.select('id, status, imported_count, created_at')
.eq('company_id', companyId)
.eq('file_hash', fileHash)
.single()
if (existingImport && existingImport.status === 'completed') {
return errorResponseFromCode('BANK_FILE_DUPLICATE', opLog, {
requestId,
details: {
importId: existingImport.id,
importedCount: existingImport.imported_count,
importedAt: existingImport.created_at,
},
})
}
// A skattekontoutdrag is not a bank statement: its rows belong on the
// skattekonto (1630), not on a bank account. Redirect the user to the
// dedicated importer. An explicit format override still forces a bank
// parse as the escape hatch.
if (!formatOverride && detectSkattekontoFile(content, file.name)) {
return errorResponseFromCode('BANK_FILE_SKATTEKONTO_DETECTED', opLog, { requestId })
}
const detectedFormat = formatOverride
? null
: detectFileFormat(content, file.name)
const parseResult = parseBankFile(content, file.name, formatOverride || undefined)
// Per-row duplicate detection deliberately does NOT live here: the
// wizard calls POST /api/import/bank-file/check-duplicates after every
// (re-)parse, including the client-side generic_csv re-parse that never
// hits this route. The old existing_transaction_count field (a raw count
// of ALL transactions in the date range) was consumed by nothing and has
// been removed.
return NextResponse.json({
data: {
parse_result: parseResult,
detected_format: detectedFormat?.id || formatOverride || null,
detected_format_name: detectedFormat?.name || parseResult.format_name,
file_hash: fileHash,
filename: file.name,
headers: parseResult.format === 'generic_csv'
? content.split('\n')[0]?.split(',').map((h) => h.trim()) || []
: null,
},
})
} catch (err) {
opLog.error('bank file parse failed', err as Error)
return errorResponseFromCode('BANK_FILE_PARSE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
)
+85
View File
@@ -0,0 +1,85 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import type { BankFileImportStatus } from '@/types'
const VALID_STATUSES: readonly BankFileImportStatus[] = [
'pending',
'processing',
'completed',
'failed',
'undone',
]
const DEFAULT_LIMIT = 20
const MAX_LIMIT = 100
/** Strictly-digits nonnegative integer, or null when the value is invalid. */
function parseNonNegativeInt(raw: string | null, fallback: number): number | null {
if (raw === null) return fallback
if (!/^\d+$/.test(raw)) return null
const n = Number(raw)
return Number.isSafeInteger(n) ? n : null
}
/**
* GET /api/import/bank-file
* List the company's bank file imports, newest first. Mirrors
* GET /api/import/sie; feeds the 'Tidigare bankfilsimporter' history table
* on the import tab (BankFileImportHistory), which is where the per-import
* undo lives.
*/
export const GET = withRouteContext(
'bank_file.list',
async (request, { supabase, companyId, log, requestId }) => {
const { searchParams } = new URL(request.url)
// parseInt would accept 'NaN'-producing and partial values ('12abc',
// '1e9', '-1') and build an invalid or unbounded range from them; the
// strict parse rejects them with a mapped 400, and limit is capped so a
// single request cannot page the whole table.
const limit = parseNonNegativeInt(searchParams.get('limit'), DEFAULT_LIMIT)
const offset = parseNonNegativeInt(searchParams.get('offset'), 0)
const rawStatus = searchParams.get('status')
const status =
rawStatus === null
? null
: (VALID_STATUSES as readonly string[]).includes(rawStatus)
? (rawStatus as BankFileImportStatus)
: undefined
if (limit === null || limit < 1 || limit > MAX_LIMIT || offset === null || status === undefined) {
return errorResponseFromCode('BANK_FILE_LIST_INVALID_QUERY', log, {
requestId,
details: {
limit: searchParams.get('limit'),
offset: searchParams.get('offset'),
status: rawStatus,
maxLimit: MAX_LIMIT,
},
})
}
let query = supabase
.from('bank_file_imports')
.select('*', { count: 'exact' })
.eq('company_id', companyId)
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
if (status) {
query = query.eq('status', status)
}
const { data, error, count } = await query
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({
data,
count,
limit,
offset,
})
},
)
+209
View File
@@ -0,0 +1,209 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { eventBus } from '@/lib/events'
import { validateBody } from '@/lib/api/validate'
import { CustomerImportExecuteSchema } from '@/lib/api/schemas'
import { normalizeOrgNumber, normalizeEmail } from '@/lib/import/shared/column-utils'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { Customer } from '@/types'
import type { CustomerImportExecuteResult } from '@/lib/import/customers/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
interface ExistingCustomer {
id: string
name: string
org_number: string | null
email: string | null
phone: string | null
address_line1: string | null
address_line2: string | null
postal_code: string | null
city: string | null
country: string
vat_number: string | null
default_payment_terms: number
notes: string | null
customer_type: string
}
/**
* POST /api/import/customers/execute
*
* Imports validated customer rows. Duplicates (matched by org_number or email)
* are either updated (merge: only non-empty file fields overwrite) or skipped
* based on `update_duplicates`.
*/
export const POST = withRouteContext(
'register_import.customers.execute',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const result = await validateBody(request, CustomerImportExecuteSchema, {
log,
operation: 'register_import.customers.execute',
})
if (!result.success) return result.response
const { rows, update_duplicates } = result.data
const opLog = log.child({ rowCount: rows.length, updateDuplicates: update_duplicates })
if (rows.length === 0) {
return errorResponseFromCode('REG_IMPORT_NO_ROWS', opLog, { requestId })
}
try {
const existingRaw = await fetchAllRows(({ from, to }) =>
supabase
.from('customers')
.select(
'id, name, org_number, email, phone, address_line1, address_line2, ' +
'postal_code, city, country, vat_number, default_payment_terms, notes, ' +
'customer_type',
)
.eq('company_id', companyId)
.range(from, to),
)
const existing = existingRaw as unknown as ExistingCustomer[]
const byOrg = new Map<string, ExistingCustomer>()
const byEmail = new Map<string, ExistingCustomer>()
for (const c of existing) {
const org = normalizeOrgNumber(c.org_number)
if (org) byOrg.set(org, c)
const email = normalizeEmail(c.email)
if (email) byEmail.set(email, c)
}
const created: Customer[] = []
const updated: Customer[] = []
let skipped = 0
const errors: { row_index: number; name: string; reason: string }[] = []
for (const row of rows) {
const orgKey = normalizeOrgNumber(row.org_number)
const emailKey = normalizeEmail(row.email)
const match =
(orgKey && byOrg.get(orgKey)) ||
(emailKey && byEmail.get(emailKey)) ||
null
if (match) {
if (!update_duplicates) {
skipped++
continue
}
// Merge mode: only overwrite fields where the file has a non-empty value.
const merged: Record<string, unknown> = {}
if (row.name) merged.name = row.name
if (row.customer_type) merged.customer_type = row.customer_type
if (row.org_number) merged.org_number = row.org_number
if (row.email) merged.email = row.email
if (row.phone) merged.phone = row.phone
if (row.address_line1) merged.address_line1 = row.address_line1
if (row.address_line2) merged.address_line2 = row.address_line2
if (row.postal_code) merged.postal_code = row.postal_code
if (row.city) merged.city = row.city
if (row.country) merged.country = row.country
if (row.vat_number) merged.vat_number = row.vat_number
if (row.default_payment_terms) merged.default_payment_terms = row.default_payment_terms
if (row.notes) merged.notes = row.notes
if (Object.keys(merged).length === 0) {
skipped++
continue
}
const { data, error } = await supabase
.from('customers')
.update(merged)
.eq('id', match.id)
.eq('company_id', companyId)
.select()
.single()
if (error) {
errors.push({ row_index: row.row_index, name: row.name, reason: getUserErrorMessage(error) })
continue
}
if (data) updated.push(data as Customer)
continue
}
// No match, create.
const { data, error } = await supabase
.from('customers')
.insert({
user_id: user.id,
company_id: companyId,
name: row.name,
customer_type: row.customer_type,
email: row.email,
phone: row.phone,
address_line1: row.address_line1,
address_line2: row.address_line2,
postal_code: row.postal_code,
city: row.city,
country: row.country || 'SE',
org_number: row.org_number,
vat_number: row.vat_number,
default_payment_terms: row.default_payment_terms || 30,
notes: row.notes,
})
.select()
.single()
if (error) {
// Treat unique-violation as a soft skip (race with concurrent import).
if (error.code === '23505') {
skipped++
continue
}
errors.push({ row_index: row.row_index, name: row.name, reason: getUserErrorMessage(error) })
continue
}
if (data) {
created.push(data as Customer)
// Track newly inserted org/email so subsequent rows in the same batch
// dedup against them too.
const newOrg = normalizeOrgNumber(data.org_number)
if (newOrg) byOrg.set(newOrg, data as ExistingCustomer)
const newEmail = normalizeEmail(data.email)
if (newEmail) byEmail.set(newEmail, data as ExistingCustomer)
}
}
// Emit events for downstream listeners (non-blocking).
for (const c of created) {
await eventBus.emit({
type: 'customer.created',
payload: { customer: c, companyId: companyId!, userId: user.id },
})
}
const response: CustomerImportExecuteResult = {
success: errors.length === 0,
created: created.length,
updated: updated.length,
skipped,
failed: errors.length,
errors,
}
opLog.info('customer import complete', response)
return NextResponse.json({ data: response })
} catch (err) {
opLog.error('customer import execute failed', err as Error)
return errorResponseFromCode('REG_IMPORT_EXECUTE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
{ requireWrite: true },
)
+121
View File
@@ -0,0 +1,121 @@
import { NextResponse } from 'next/server'
import { parseCustomersFile } from '@/lib/import/customers/parser'
import { normalizeOrgNumber, normalizeEmail } from '@/lib/import/shared/column-utils'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type {
AnnotatedCustomerRow,
CustomerImportParseResult,
DetectedCustomerColumns,
} from '@/lib/import/customers/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const ALLOWED_EXTENSIONS = ['.xlsx', '.xls', '.csv', '.ods']
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
/**
* POST /api/import/customers/parse
*
* Accepts an Excel/CSV file via FormData, auto-detects columns, parses rows,
* and annotates each row with any duplicate-match against existing customers.
*/
export const POST = withRouteContext(
'register_import.customers.parse',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const formData = await request.formData()
const file = formData.get('file') as File | null
const columnOverridesRaw = formData.get('column_overrides') as string | null
if (!file) {
return errorResponseFromCode('REG_IMPORT_NO_FILE', log, { requestId })
}
if (file.size > MAX_FILE_SIZE) {
return errorResponseFromCode('REG_IMPORT_FILE_TOO_LARGE', log, {
requestId,
details: { sizeMb: +(file.size / 1024 / 1024).toFixed(1) },
})
}
const ext = '.' + file.name.split('.').pop()?.toLowerCase()
if (!ALLOWED_EXTENSIONS.includes(ext)) {
return errorResponseFromCode('REG_IMPORT_INVALID_FORMAT', log, {
requestId,
details: { extension: ext, allowed: ALLOWED_EXTENSIONS },
})
}
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
let columnOverrides: DetectedCustomerColumns | undefined
if (columnOverridesRaw) {
try {
columnOverrides = JSON.parse(columnOverridesRaw)
} catch {
return errorResponseFromCode('REG_IMPORT_INVALID_COLUMN_OVERRIDES', opLog, { requestId })
}
}
try {
const buffer = await file.arrayBuffer()
const parsed = parseCustomersFile(buffer, file.name, columnOverrides)
// Fetch existing customers for duplicate detection.
const existing = await fetchAllRows(({ from, to }) =>
supabase
.from('customers')
.select('id, name, org_number, email')
.eq('company_id', companyId)
.range(from, to),
)
const byOrg = new Map<string, { id: string; name: string }>()
const byEmail = new Map<string, { id: string; name: string }>()
for (const c of existing) {
const org = normalizeOrgNumber(c.org_number)
if (org) byOrg.set(org, { id: c.id, name: c.name })
const email = normalizeEmail(c.email)
if (email) byEmail.set(email, { id: c.id, name: c.name })
}
let duplicateCount = 0
const annotated: AnnotatedCustomerRow[] = parsed.rows.map((r) => {
const orgKey = normalizeOrgNumber(r.org_number)
const emailKey = normalizeEmail(r.email)
let match: AnnotatedCustomerRow['duplicate_match'] = null
if (orgKey && byOrg.has(orgKey)) {
const e = byOrg.get(orgKey)!
match = { customer_id: e.id, matched_by: 'org_number', existing_name: e.name }
} else if (emailKey && byEmail.has(emailKey)) {
const e = byEmail.get(emailKey)!
match = { customer_id: e.id, matched_by: 'email', existing_name: e.name }
}
if (match) duplicateCount++
return { ...r, duplicate_match: match }
})
const result: CustomerImportParseResult = {
filename: parsed.filename,
sheet_name: parsed.sheet_name,
total_rows: annotated.length,
detected_columns: parsed.detected_columns,
headers: parsed.headers,
preview_rows: parsed.preview_rows,
rows: annotated,
duplicate_count: duplicateCount,
warnings: parsed.warnings,
}
return NextResponse.json({ data: result })
} catch (err) {
opLog.error('customer import parse failed', err as Error)
return errorResponseFromCode('REG_IMPORT_PARSE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
)
@@ -0,0 +1,397 @@
/**
* Tests for POST /api/import/documents/attach: archives one underlag file and
* links it to the SIE-migrated verifikat its filename names.
*
* The link is irreversible räkenskapsinformation (BFL 7 kap), so the guards
* matter more than the happy path: the target must belong to the company, and
* the automatic path must land where the preview said it would.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse } from '@/tests/helpers'
const PERIOD_OPEN = '44444444-4444-4444-8444-444444444444'
const PERIOD_OTHER = '55555555-5555-4555-8555-555555555555'
const PERIODS = [
{
id: PERIOD_OPEN,
period_start: '2024-01-01',
period_end: '2024-12-31',
is_closed: false,
locked_at: null,
},
]
const TARGET_ID = '11111111-1111-4111-8111-111111111111'
const OTHER_ID = '22222222-2222-4222-8222-222222222222'
const VOUCHER = {
id: TARGET_ID,
fiscal_period_id: PERIOD_OPEN,
entry_date: '2024-03-14',
description: 'Inköp kontorsmaterial',
voucher_series: 'A',
voucher_number: 47,
source_voucher_series: 'A',
source_voucher_number: 31,
}
/** The row the tenant-ownership lookup finds, or null for "not this company". */
let targetEntry: Record<string, unknown> | null = null
/** What the ledger holds for the filename's ref, as the plan would see it. */
let vouchers: Record<string, unknown>[] = []
const supabase = {
from(table: string) {
let filteredByNumber = false
let single = false
const result = () => {
if (table === 'fiscal_periods') return { data: PERIODS, error: null, count: PERIODS.length }
if (single) return { data: targetEntry, error: null }
return { data: filteredByNumber ? vouchers : [], error: null, count: vouchers.length }
}
const chain: Record<string, unknown> = {}
for (const method of ['select', 'eq', 'not', 'order', 'limit']) {
chain[method] = () => chain
}
chain.maybeSingle = () => {
single = true
return chain
}
chain.in = () => {
filteredByNumber = true
return chain
}
chain.range = () => Promise.resolve(result())
chain.then = (onFulfilled: (value: unknown) => unknown) =>
Promise.resolve(result()).then(onFulfilled)
return chain
},
}
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
// Guideline mock: no real Supabase client may ever be constructed in a route
// test, even though this suite injects its double through requireAuth.
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(supabase),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const getCompanyRoleMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
getCompanyRole: (...args: unknown[]) => getCompanyRoleMock(...args),
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const uploadDocumentMock = vi.fn()
vi.mock('@/lib/core/documents/document-service', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/core/documents/document-service')>()
return {
...actual,
uploadDocument: (...args: unknown[]) => uploadDocumentMock(...args),
}
})
import { POST } from '../route'
const emptyParams = { params: Promise.resolve({}) }
function makeRequest(options: {
fileName?: string
journalEntryId?: string | null
/** The year the plan was built against, as the wizard echoes it back. */
declaredPeriodId?: string | null
override?: boolean
withFile?: boolean
mimeType?: string
}) {
const form = new FormData()
if (options.withFile !== false) {
form.append(
'file',
new File(['%PDF-1.4 underlag'], options.fileName ?? 'A31_8c2db060.pdf', {
type: options.mimeType ?? 'application/pdf',
}),
)
}
if (options.journalEntryId !== null) {
form.append('journal_entry_id', options.journalEntryId ?? TARGET_ID)
}
if (options.declaredPeriodId !== null) {
form.append('fiscal_period_id', options.declaredPeriodId ?? PERIOD_OPEN)
}
if (options.override) form.append('override', 'true')
return new Request('http://localhost:3000/api/import/documents/attach', {
method: 'POST',
body: form,
})
}
describe('POST /api/import/documents/attach', () => {
beforeEach(() => {
vi.clearAllMocks()
targetEntry = { id: TARGET_ID, fiscal_period_id: PERIOD_OPEN, status: 'posted', source_voucher_series: 'A', source_voucher_number: 31 }
vouchers = [VOUCHER]
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
getCompanyRoleMock.mockResolvedValue({ ok: true, role: 'owner', companyId: 'company-1' })
uploadDocumentMock.mockResolvedValue({ id: 'doc-1', file_name: 'A31_8c2db060.pdf' })
})
it('returns 401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeRequest({}), emptyParams)
expect(res.status).toBe(401)
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('returns 400 when no file was sent', async () => {
const res = await POST(makeRequest({ withFile: false }), emptyParams)
expect(res.status).toBe(400)
})
it('returns 400 when journal_entry_id is missing or not a uuid', async () => {
expect((await POST(makeRequest({ journalEntryId: null }), emptyParams)).status).toBe(400)
expect((await POST(makeRequest({ journalEntryId: 'A31' }), emptyParams)).status).toBe(400)
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('returns 404 when the target entry belongs to another company', async () => {
targetEntry = null
const res = await POST(makeRequest({}), emptyParams)
expect(res.status).toBe(404)
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('refuses a target the filename does not resolve to', async () => {
// The entry exists and is ours, but A31 belongs to a different verifikat:
// a stale plan in the browser must not scatter underlag permanently.
vouchers = [{ ...VOUCHER, id: OTHER_ID }]
const res = await POST(makeRequest({}), emptyParams)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('UNDERLAG_REF_MISMATCH')
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('resolves the basename when the browser sends a folder-relative multipart filename', async () => {
// Chrome fills the multipart `filename` with webkitRelativePath for files
// picked through a folder selection, so the server sees the Fortnox export
// tree (<year>/<month>/<type>/<file>) while the preview, built from
// File.name, saw only the basename. The check must run on the name the
// user reviewed, and the archived document must carry that name, not the
// path. Long exporter suffixes after the ref are part of the same shape.
const res = await POST(
makeRequest({
fileName:
'2026/06/Leverantörsfakturor/A31_90493_62864442_Hetzner_2026-05-13_089000921156.pdf',
}),
emptyParams,
)
expect(res.status).toBe(200)
const [, , , file] = uploadDocumentMock.mock.calls[0]
expect(file).toMatchObject({
name: 'A31_90493_62864442_Hetzner_2026-05-13_089000921156.pdf',
})
})
it('still refuses a folder-relative filename whose basename points elsewhere', async () => {
// Normalizing the path must not loosen the guard: the basename is checked
// exactly as a bare filename would be.
vouchers = [{ ...VOUCHER, id: OTHER_ID }]
const res = await POST(
makeRequest({ fileName: '2026/06/Leverantörsfakturor/A31_kvitto.pdf' }),
emptyParams,
)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('UNDERLAG_REF_MISMATCH')
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('attaches several underlag to the same verifikat, one request each', async () => {
// Fortnox exports one file per attachment, so a verifikat with six
// receipts is six files sharing a prefix. Each lands on the same target
// under the same entry-scoped idempotency key; the content hash keeps
// them apart as separate documents.
for (const fileName of ['A31_90470_1_faktura.pdf', 'A31_90470_2_kvitto.pdf']) {
expect((await POST(makeRequest({ fileName }), emptyParams)).status).toBe(200)
}
expect(uploadDocumentMock).toHaveBeenCalledTimes(2)
for (const call of uploadDocumentMock.mock.calls) {
expect(call[4]).toMatchObject({ journal_entry_id: TARGET_ID, idempotency_key: TARGET_ID })
}
})
it('returns 400 when the declared fiscal year is missing or not a uuid', async () => {
expect((await POST(makeRequest({ declaredPeriodId: null }), emptyParams)).status).toBe(400)
expect((await POST(makeRequest({ declaredPeriodId: '2024' }), emptyParams)).status).toBe(400)
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('refuses a target outside the fiscal year the batch declared', async () => {
// The user reviewed a plan for one year; this target lives in another.
// Nothing about the filename can make that acceptable.
const res = await POST(makeRequest({ declaredPeriodId: PERIOD_OTHER }), emptyParams)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('UNDERLAG_PERIOD_MISMATCH')
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('enforces the declared year even on a manual override', async () => {
// An override is a statement about WHICH verifikat, never about which
// year, so it must not widen the batch across fiscal years.
const res = await POST(
makeRequest({ declaredPeriodId: PERIOD_OTHER, override: true, fileName: 'kvitto.pdf' }),
emptyParams,
)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('UNDERLAG_PERIOD_MISMATCH')
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('explains a target that never came from a SIE import', async () => {
targetEntry = { id: TARGET_ID, fiscal_period_id: PERIOD_OPEN, status: 'posted', source_voucher_series: null, source_voucher_number: null }
const res = await POST(makeRequest({}), emptyParams)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(400)
expect(body.error.code).toBe('UNDERLAG_ENTRY_NOT_MIGRATED')
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('refuses a target that is not posted, overrides included', async () => {
// The SIE import posts entries inside its own transaction, so a draft with
// a source ref should be unreachable. This route does not lean on an
// invariant enforced in another file: underlag references a verifikation
// (BFL 5 kap 6-7 §), so the target must BE one.
targetEntry = { ...targetEntry!, status: 'draft' }
const auto = await POST(makeRequest({}), emptyParams)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(auto)
expect(status).toBe(409)
expect(body.error.code).toBe('UNDERLAG_ENTRY_NOT_POSTED')
const overridden = await POST(
makeRequest({ fileName: 'kvitto ica.pdf', override: true }),
emptyParams,
)
expect(overridden.status).toBe(409)
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('accepts a REVERSED target: a storno original keeps its underlag', async () => {
targetEntry = { ...targetEntry!, status: 'reversed' }
const res = await POST(makeRequest({}), emptyParams)
expect(res.status).toBe(200)
expect(uploadDocumentMock).toHaveBeenCalledOnce()
})
it('refuses an override for a filename that resolves to a DIFFERENT target', async () => {
// The server honors override only for filenames it cannot place. A31.pdf
// resolves cleanly to another verifikat, so a lying client cannot use
// override to scatter it.
vouchers = [{ ...VOUCHER, id: OTHER_ID }]
const res = await POST(makeRequest({ override: true }), emptyParams)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('UNDERLAG_REF_MISMATCH')
expect(uploadDocumentMock).not.toHaveBeenCalled()
})
it('allows an explicit manual assignment to skip the filename check', async () => {
targetEntry = { id: TARGET_ID, fiscal_period_id: PERIOD_OPEN, status: 'posted', source_voucher_series: null, source_voucher_number: null }
const res = await POST(
makeRequest({ fileName: 'kvitto ica.pdf', override: true }),
emptyParams,
)
expect(res.status).toBe(200)
expect(uploadDocumentMock).toHaveBeenCalledOnce()
})
it('archives and links the file, scoping idempotency to the verifikat', async () => {
const res = await POST(makeRequest({}), emptyParams)
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(res)
expect(status).toBe(200)
expect(body.data.id).toBe('doc-1')
const [, userId, companyId, file, metadata] = uploadDocumentMock.mock.calls[0]
expect(userId).toBe('user-1')
expect(companyId).toBe('company-1')
expect(file).toMatchObject({ name: 'A31_8c2db060.pdf', type: 'application/pdf' })
expect(metadata).toMatchObject({
journal_entry_id: TARGET_ID,
// Same content on a different verifikat must archive separately, so the
// key is the entry, not the bytes.
idempotency_key: TARGET_ID,
upload_source: 'file_upload',
// The verifikat is already booked: no per-file model pass (#2188).
extractionOwner: 'none',
})
})
it('maps the period-lock trigger to a usable error instead of a 500', async () => {
uploadDocumentMock.mockRejectedValue(
new Error('Cannot attach documents to entries in a locked/closed fiscal period'),
)
const res = await POST(makeRequest({}), emptyParams)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(400)
expect(body.error.code).toBe('DOC_UPLOAD_PERIOD_LOCKED')
})
it('does not leak storage internals when the archive write fails', async () => {
uploadDocumentMock.mockRejectedValue(new Error('bucket s3://internal-prod-bucket exploded'))
const res = await POST(makeRequest({}), emptyParams)
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(
res,
)
expect(status).toBe(500)
expect(body.error.code).toBe('DOC_UPLOAD_STORAGE_FAILED')
expect(body.error.message).not.toContain('internal-prod-bucket')
})
})
+234
View File
@@ -0,0 +1,234 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { uploadDocument, validateDocumentFile } from '@/lib/core/documents/document-service'
import { planPermitsAttach } from '@/lib/documents/underlag-import'
import { uploadedFileBaseName } from '@/lib/documents/upload-file-name'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
ensureInitialized()
const AttachFieldsSchema = z.object({
journal_entry_id: z.string().uuid(),
/**
* The fiscal year the user reviewed this batch against, echoed back from the
* plan. Required, and checked against the target's own year on every request
* including overrides: it is the only thing that makes the year enforceable
* server-side. Deriving it from the target instead would be tautological, an
* entry is by construction inside its own period, and that is precisely the
* hole that let a 2023 receipt land on a 2025 verifikat.
*/
fiscal_period_id: z.string().uuid(),
/**
* Set ONLY when the user resolved this file by hand because its filename
* carries no usable reference. Honored server-side ONLY for filenames the
* resolver cannot place in the declared year: a resolvable filename must
* land where it points, override or not. Company ownership, the year
* assertion and the period lock are always enforced.
*
* Choosing among candidates the server itself proposed is NOT an override:
* those targets pass the check already, and flagging them would switch the
* guard off on exactly the ambiguous rows it exists for.
*/
override: z.boolean(),
})
/**
* POST /api/import/documents/attach: archive one underlag file and link it to a
* migrated verifikat.
*
* multipart/form-data:
* file: the underlag
* journal_entry_id: the target the user approved in the preview
* fiscal_period_id: the year the plan was built against (echoed back)
* override: 'true' when the target was chosen by hand
*
* One file per request on purpose: a folder migration is hundreds of files, the
* browser streams them one at a time with visible progress, and a failure on
* file 200 leaves the first 199 correctly attached instead of rolling back work
* that is legally irreversible anyway.
*
* Idempotent per (verifikat, content): re-running the same import converges on
* the same document row rather than archiving duplicates, via the deterministic
* document id that `idempotency_key` reserves.
*/
export const POST = withRouteContext(
'import.documents.attach',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const formData = await request.formData()
const file = formData.get('file') as File | null
if (!file) {
return errorResponseFromCode('DOC_UPLOAD_NO_FILE', log, { requestId })
}
// The multipart `filename` is not `File.name`. For a folder selection
// Chrome writes the relative path (`2026/06/Leverantörsfakturor/A166_x.pdf`)
// while the preview the user approved was built from `File.name`
// (`A166_x.pdf`). Every use below, the resolver check and the archived
// name alike, must see the name the user reviewed, so it is normalized
// once, here, at the boundary.
const fileName = uploadedFileBaseName(file.name)
const fields = AttachFieldsSchema.safeParse({
journal_entry_id: formData.get('journal_entry_id'),
fiscal_period_id: formData.get('fiscal_period_id'),
override: formData.get('override') === 'true',
})
if (!fields.success) {
return errorResponseFromCode('VALIDATION_ERROR', log, {
requestId,
details: {
issues: fields.error.issues.map((i) => ({
field: i.path.join('.'),
reason: i.message,
})),
},
})
}
const {
journal_entry_id: journalEntryId,
fiscal_period_id: fiscalPeriodId,
override,
} = fields.data
const validationError = validateDocumentFile({ size: file.size, type: file.type })
if (validationError) {
const code = /storlek|stor|MB/i.test(validationError)
? 'DOC_UPLOAD_TOO_LARGE'
: 'DOC_UPLOAD_UNSUPPORTED_TYPE'
return errorResponseFromCode(code, log, {
requestId,
details: { reason: validationError, sizeBytes: file.size, mimeType: file.type },
})
}
const opLog = log.child({
filename: fileName,
journalEntryId,
// Kept only when the browser sent something else, so a refusal can be
// read against exactly what arrived on the wire.
...(file.name !== fileName ? { uploadedAs: file.name } : {}),
})
// Tenant check first and explicitly: RLS covers the cookie session, but the
// link is irreversible, so the route never takes the client's word for which
// company an entry belongs to.
const { data: entry, error: entryError } = await supabase
.from('journal_entries')
.select('id, fiscal_period_id, status, source_voucher_series, source_voucher_number')
.eq('id', journalEntryId)
.eq('company_id', companyId!)
.maybeSingle()
if (entryError) {
opLog.error('underlag attach target lookup failed', entryError)
return errorResponseFromCode('DOC_LINK_FAILED', opLog, { requestId })
}
if (!entry) {
return errorResponseFromCode('DOC_LINK_ENTRY_NOT_FOUND', opLog, { requestId })
}
// Underlag references a verifikation (BFL 5 kap 6-7 §), so the target must
// BE one: posted, or reversed (a storno'd original keeps its underlag). The
// SIE import posts entries inside its own transaction, so a draft here
// should be unreachable, but this route writes irreversible links and does
// not lean on an invariant enforced in another file.
if (entry.status !== 'posted' && entry.status !== 'reversed') {
opLog.warn('underlag attach refused: target entry is not posted', {
entryStatus: entry.status,
})
return errorResponseFromCode('UNDERLAG_ENTRY_NOT_POSTED', opLog, { requestId })
}
// The batch declared a fiscal year and the user reviewed the plan against
// it. The target must actually be in that year. Enforced FIRST and
// unconditionally, overrides included: a hand-resolved filename is a
// statement about which verifikat, never about which year, and this is the
// only check that makes the declared year mean anything on the server.
if (entry.fiscal_period_id !== fiscalPeriodId) {
opLog.warn('underlag attach refused: target sits in a different fiscal year', {
declaredFiscalPeriodId: fiscalPeriodId,
entryFiscalPeriodId: entry.fiscal_period_id,
})
return errorResponseFromCode('UNDERLAG_PERIOD_MISMATCH', opLog, { requestId })
}
// The file must additionally land where the preview said it would. A stale
// plan in the browser (the user re-imported SIE in another tab, say) would
// otherwise scatter underlag across the wrong verifikat. The resolver runs
// on EVERY request: an override only relaxes it for filenames it cannot
// place at all, never for a filename that resolves elsewhere.
if (!override && entry.source_voucher_number == null) {
// Not a SIE-migrated verifikat, so no filename can ever resolve to it.
// Say that plainly instead of reporting a mismatch the user can't fix.
return errorResponseFromCode('UNDERLAG_ENTRY_NOT_MIGRATED', opLog, { requestId })
}
const permitted = await planPermitsAttach(
supabase,
companyId!,
fileName,
journalEntryId,
fiscalPeriodId,
override,
)
if (!permitted) {
opLog.warn('underlag attach refused: filename does not resolve to the target', { override })
return errorResponseFromCode('UNDERLAG_REF_MISMATCH', opLog, { requestId })
}
try {
const buffer = await file.arrayBuffer()
const document = await uploadDocument(
supabase,
user.id,
companyId!,
{ name: fileName, buffer, type: file.type },
{
upload_source: 'file_upload',
journal_entry_id: journalEntryId,
// The file lands on a posted verifikat by construction, so the
// booking is already known and a model pass per file buys nothing.
// Run inline through document.uploaded (the bus awaits its
// handlers), that pass was the bulk of a 10-minute foreground wait
// on a few hundred migrated files (#2188). Same opt-out as the
// provider underlag sweep (#1783), for the same reason.
extractionOwner: 'none',
// Scope the deterministic id to the target verifikat: the same
// receipt may legitimately back several verifikat, so content alone
// must not dedupe across them.
idempotency_key: journalEntryId,
},
)
return NextResponse.json({ data: document })
} catch (err) {
const message = err instanceof Error ? err.message : 'unknown'
// enforce_period_lock_documents: a migrated year is often closed by the
// time the receipts arrive, and the trigger blocks the link outright.
if (/locked\/closed fiscal period|Bokföringen är låst/i.test(message)) {
return errorResponseFromCode('DOC_UPLOAD_PERIOD_LOCKED', opLog, {
requestId,
details: { reason: getErrorMessage(err) },
})
}
if (/kunde inte verifieras|matchar inte den angivna filtypen/i.test(message)) {
opLog.warn('underlag attach rejected by content validation', { reason: message })
return errorResponseFromCode('DOC_UPLOAD_INVALID_CONTENT', opLog, {
requestId,
details: { reason: getErrorMessage(err) },
})
}
opLog.error('underlag attach failed', err as Error)
return errorResponseFromCode('DOC_UPLOAD_STORAGE_FAILED', opLog, { requestId })
}
},
{ requireWrite: true },
)
@@ -0,0 +1,180 @@
/**
* Tests for POST /api/import/documents/preview: the read-only match plan that
* pairs underlag filenames with SIE-migrated verifikat before anything is
* uploaded or linked.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
import type { UnderlagPlan } from '@/lib/documents/underlag-import'
const PERIOD_OPEN = '33333333-3333-4333-8333-333333333333'
const PERIODS = [
{
id: PERIOD_OPEN,
period_start: '2024-01-01',
period_end: '2024-12-31',
is_closed: false,
locked_at: null,
},
]
let vouchers: Record<string, unknown>[] = []
/** The row the fiscal-period ownership lookup finds, or null for "not ours". */
let ownedPeriod: Record<string, unknown> | null = null
/** Shape-keyed double: the plan reads vouchers and periods concurrently. */
const supabase = {
from(table: string) {
let filteredByNumber = false
let single = false
const result = () => {
if (table === 'fiscal_periods') {
return single
? { data: ownedPeriod, error: null }
: { data: PERIODS, error: null, count: PERIODS.length }
}
return {
data: filteredByNumber ? vouchers : [],
error: null,
count: vouchers.length,
}
}
const chain: Record<string, unknown> = {}
for (const method of ['select', 'eq', 'not', 'order', 'limit', 'single']) {
chain[method] = () => chain
}
chain.maybeSingle = () => {
single = true
return chain
}
chain.in = () => {
filteredByNumber = true
return chain
}
chain.range = () => Promise.resolve(result())
chain.then = (onFulfilled: (value: unknown) => unknown) =>
Promise.resolve(result()).then(onFulfilled)
return chain
},
}
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
// Guideline mock: no real Supabase client may ever be constructed in a route
// test, even though this suite injects its double through requireAuth.
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(supabase),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { POST } from '../route'
const emptyParams = { params: Promise.resolve({}) }
function makeRequest(body: Record<string, unknown>) {
return createMockRequest('/api/import/documents/preview', {
method: 'POST',
body: { fiscal_period_id: PERIOD_OPEN, ...body },
})
}
describe('POST /api/import/documents/preview', () => {
beforeEach(() => {
vi.clearAllMocks()
vouchers = [
{
id: 'je-1',
fiscal_period_id: PERIOD_OPEN,
entry_date: '2024-03-14',
description: 'Inköp kontorsmaterial',
voucher_series: 'A',
voucher_number: 47,
source_voucher_series: 'A',
source_voucher_number: 31,
},
]
ownedPeriod = { id: PERIOD_OPEN }
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
})
it('returns 401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeRequest({ file_names: ['A31.pdf'] }), emptyParams)
expect(res.status).toBe(401)
})
it('returns 400 when file_names is missing or empty', async () => {
expect((await POST(makeRequest({}), emptyParams)).status).toBe(400)
expect((await POST(makeRequest({ file_names: [] }), emptyParams)).status).toBe(400)
})
it('returns 400 without a fiscal year: a filename alone cannot identify a verifikat', async () => {
const noYear = createMockRequest('/api/import/documents/preview', {
method: 'POST',
body: { file_names: ['A31.pdf'] },
})
expect((await POST(noYear, emptyParams)).status).toBe(400)
const badYear = await POST(
makeRequest({ file_names: ['A31.pdf'], fiscal_period_id: 'not-a-uuid' }),
emptyParams,
)
expect(badYear.status).toBe(400)
})
it("returns 404 for a fiscal year that is not this company's", async () => {
ownedPeriod = null
const res = await POST(makeRequest({ file_names: ['A31.pdf'] }), emptyParams)
expect(res.status).toBe(404)
})
it('returns 400 when the batch exceeds the 2000-file cap', async () => {
const oversized = Array.from({ length: 2001 }, (_, i) => `A${i + 1}.pdf`)
const res = await POST(makeRequest({ file_names: oversized }), emptyParams)
expect(res.status).toBe(400)
})
it('returns the match plan for the submitted filenames (happy path)', async () => {
const res = await POST(
makeRequest({ file_names: ['A31_8c2db060.pdf', 'kvitto.pdf'] }),
emptyParams,
)
const { status, body } = await parseJsonResponse<{ data: UnderlagPlan }>(res)
expect(status).toBe(200)
expect(body.data.rows).toHaveLength(2)
expect(body.data.rows[0]).toMatchObject({ status: 'matched', journal_entry_id: 'je-1' })
expect(body.data.rows[1]).toMatchObject({ status: 'unparsed', journal_entry_id: null })
expect(body.data.summary).toMatchObject({ total: 2, matched: 1, unparsed: 1 })
})
it('never returns a target the filename does not name', async () => {
const res = await POST(makeRequest({ file_names: ['A99.pdf'] }), emptyParams)
const { body } = await parseJsonResponse<{ data: UnderlagPlan }>(res)
expect(body.data.rows[0].status).toBe('no_match')
expect(body.data.rows[0].journal_entry_id).toBeNull()
})
})
+54
View File
@@ -0,0 +1,54 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { UnderlagImportPreviewSchema } from '@/lib/api/schemas'
import { buildUnderlagPlan } from '@/lib/documents/underlag-import'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
ensureInitialized()
/**
* POST /api/import/documents/preview: plan which verifikat each underlag file
* belongs to, from the voucher reference in its filename.
*
* Read-only by construction. Only the NAMES are sent, so a user can review the
* whole plan (including the misses) before a single byte is uploaded, and
* before a single irreversible link is written.
*
* Scoped to the fiscal year the caller declares: `A31` identifies a verifikat
* only inside a year, because source systems restart numbering annually.
*/
export const POST = withRouteContext('import.documents.preview', async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const validation = await validateBody(request, UnderlagImportPreviewSchema)
if (!validation.success) return validation.response
const { file_names: fileNames, fiscal_period_id: fiscalPeriodId } = validation.data
// The period must belong to this company: buildUnderlagPlan filters entries
// by it, and an unowned id would silently produce an all-misses plan rather
// than an honest error.
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('id')
.eq('id', fiscalPeriodId)
.eq('company_id', companyId!)
.maybeSingle()
if (periodError) {
log.error('underlag import preview period lookup failed', periodError)
return errorResponse(periodError, log, { requestId })
}
if (!period) {
return errorResponseFromCode('FISCAL_PERIOD_NOT_FOUND', log, { requestId })
}
try {
const plan = await buildUnderlagPlan(supabase, companyId!, fileNames, fiscalPeriodId)
return NextResponse.json({ data: plan })
} catch (err) {
log.error('underlag import preview failed', err as Error, { fileCount: fileNames.length })
return errorResponse(err, log, { requestId })
}
})
@@ -0,0 +1,274 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const mockCreateJournalEntry = vi.fn()
const mockReverseEntry = vi.fn()
vi.mock('@/lib/bookkeeping/engine', () => ({
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
reverseEntry: (...args: unknown[]) => mockReverseEntry(...args),
}))
vi.mock('@/lib/bookkeeping/bas-reference', () => ({
getBASReference: vi.fn().mockReturnValue(null),
}))
vi.mock('@/lib/supabase/fetch-all', () => ({
// All referenced accounts already exist → no chart activation insert.
fetchAllRows: vi.fn().mockResolvedValue([
{ account_number: '1930' },
{ account_number: '2099' },
]),
}))
import { POST } from '../correct/route'
const PERIOD_ID = '550e8400-e29b-41d4-a716-446655440000'
const BALANCED_LINES = [
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
]
function makeRequest(body: unknown) {
return createMockRequest('/api/import/opening-balance/correct', {
method: 'POST',
body,
})
}
function openPeriodWithOB(overrides: Record<string, unknown> = {}) {
return {
id: PERIOD_ID,
company_id: 'company-1',
is_closed: false,
locked_at: null,
opening_balances_set: true,
opening_balance_entry_id: 'entry-old',
period_start: '2026-01-01',
...overrides,
}
}
describe('POST /api/import/opening-balance/correct', () => {
const mockUser = { id: 'user-1', email: '[email protected]' }
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
it('returns 401 for unauthenticated requests', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(401)
expect(body.error).toBe('Unauthorized')
})
it('returns 400 for invalid body', async () => {
const res = await POST(makeRequest({ fiscal_period_id: 'not-a-uuid', lines: [] }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 404 for non-existent fiscal period', async () => {
enqueue({ data: null, error: { message: 'not found' } })
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect((body.error as unknown as { code: string }).code).toBe('OB_PERIOD_NOT_FOUND')
})
it('returns 400 when the period is closed', async () => {
enqueue({ data: openPeriodWithOB({ is_closed: true }) })
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(400)
expect((body.error as unknown as { code: string }).code).toBe('OB_PERIOD_CLOSED')
})
it('returns 400 when the period is locked', async () => {
enqueue({ data: openPeriodWithOB({ locked_at: '2026-06-28T00:00:00Z' }) })
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(400)
expect((body.error as unknown as { code: string }).code).toBe('OB_PERIOD_LOCKED')
})
it('returns 409 when the company lock date covers the period start', async () => {
enqueue({ data: openPeriodWithOB() }) // period (period_start 2026-01-01)
enqueue({ data: { bookkeeping_locked_through: '2026-02-28' } }) // company lock-date pre-flight
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(409)
const err = body.error as unknown as { code: string; details?: { lockDate?: string; entryDate?: string } }
expect(err.code).toBe('OB_COMPANY_LOCK_DATE')
expect(err.details?.lockDate).toBe('2026-02-28')
expect(err.details?.entryDate).toBe('2026-01-01')
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
expect(mockReverseEntry).not.toHaveBeenCalled()
})
it('proceeds when the company lock date is before the period start', async () => {
enqueue({ data: openPeriodWithOB() }) // period (period_start 2026-01-01)
enqueue({ data: { bookkeeping_locked_through: '2025-12-31' } }) // company lock-date pre-flight
enqueue({ count: 0 }) // year-end check
enqueue({ error: null }) // replace_period_opening_balance_link RPC
mockCreateJournalEntry.mockResolvedValue({ id: 'entry-new', voucher_series: 'A', voucher_number: 5 })
mockReverseEntry.mockResolvedValue({ id: 'entry-storno' })
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.success).toBe(true)
})
it('maps a raced lock-date trigger rejection to OB_COMPANY_LOCK_DATE instead of a retryable 500', async () => {
enqueue({ data: openPeriodWithOB() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // pre-flight passes (lock set after it)
enqueue({ count: 0 }) // year-end check
// The enforce_company_lock_date trigger fired inside the engine.
mockCreateJournalEntry.mockRejectedValue(
new Error('Database operation "create_draft_entry" failed: Bokföringen är låst t.o.m. 2026-02-28. Kan inte skapa verifikation med datum 2026-01-01.'),
)
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(409)
expect((body.error as unknown as { code: string }).code).toBe('OB_COMPANY_LOCK_DATE')
expect(mockReverseEntry).not.toHaveBeenCalled()
})
it('returns 409 when the period has no opening balances to correct', async () => {
enqueue({ data: openPeriodWithOB({ opening_balances_set: false, opening_balance_entry_id: null }) })
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(409)
expect((body.error as unknown as { code: string }).code).toBe('OB_CORRECT_NO_EXISTING')
})
it('returns 409 when a year-end close exists on the period', async () => {
enqueue({ data: openPeriodWithOB() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
enqueue({ count: 1 }) // year-end entry count
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(409)
expect((body.error as unknown as { code: string }).code).toBe('OB_CORRECT_YEAR_END_EXISTS')
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
expect(mockReverseEntry).not.toHaveBeenCalled()
})
it('returns 400 for unbalanced corrected lines', async () => {
enqueue({ data: openPeriodWithOB() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
enqueue({ count: 0 }) // year-end check
const res = await POST(makeRequest({
fiscal_period_id: PERIOD_ID,
lines: [
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 40000 },
],
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(400)
expect((body.error as unknown as { code: string }).code).toBe('OB_UNBALANCED')
})
it('books a corrected IB, stornoes the old one, and relinks on success', async () => {
enqueue({ data: openPeriodWithOB() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
enqueue({ count: 0 }) // year-end check
enqueue({ error: null }) // replace_period_opening_balance_link RPC
mockCreateJournalEntry.mockResolvedValue({ id: 'entry-new', voucher_series: 'A', voucher_number: 5 })
mockReverseEntry.mockResolvedValue({ id: 'entry-storno' })
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.success).toBe(true)
expect(body.data.journal_entry_id).toBe('entry-new')
expect(body.data.reversed_entry_id).toBe('entry-old')
expect(body.data.lines_created).toBe(2)
// New IB created before the old one is reversed.
expect(mockCreateJournalEntry).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({ source_type: 'opening_balance', voucher_series: 'A' }),
)
expect(mockReverseEntry).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
'entry-old',
)
expect(mockSupabase.rpc).toHaveBeenCalledWith(
'replace_period_opening_balance_link',
expect.objectContaining({ p_period_id: PERIOD_ID, p_new_entry_id: 'entry-new' }),
)
})
it('returns 500 OB_CORRECT_FAILED if the relink RPC fails', async () => {
enqueue({ data: openPeriodWithOB() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
enqueue({ count: 0 }) // year-end check
enqueue({ error: { message: 'relink boom' } }) // RPC failure
mockCreateJournalEntry.mockResolvedValue({ id: 'entry-new', voucher_series: 'A', voucher_number: 5 })
mockReverseEntry.mockResolvedValue({ id: 'entry-storno' })
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(500)
expect((body.error as unknown as { code: string }).code).toBe('OB_CORRECT_FAILED')
})
})
@@ -0,0 +1,251 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const mockCreateJournalEntry = vi.fn()
vi.mock('@/lib/bookkeeping/engine', () => ({
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
}))
vi.mock('@/lib/bookkeeping/bas-reference', () => ({
getBASReference: vi.fn().mockReturnValue(null),
}))
vi.mock('@/lib/supabase/fetch-all', () => ({
fetchAllRows: vi.fn().mockResolvedValue([
{ account_number: '1930' },
{ account_number: '2099' },
{ account_number: '2440' },
{ account_number: '1510' },
{ account_number: '3001' },
]),
}))
import { POST } from '../execute/route'
const PERIOD_ID = '550e8400-e29b-41d4-a716-446655440000'
function makeRequest(body: unknown) {
return createMockRequest('/api/import/opening-balance/execute', {
method: 'POST',
body,
})
}
describe('POST /api/import/opening-balance/execute', () => {
const mockUser = { id: 'user-1', email: '[email protected]' }
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
it('returns 401 for unauthenticated requests', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(makeRequest({
fiscal_period_id: PERIOD_ID,
lines: [
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
],
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(401)
expect(body.error).toBe('Unauthorized')
})
it('returns 400 for invalid body', async () => {
const res = await POST(makeRequest({
fiscal_period_id: 'not-a-uuid',
lines: [],
}))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 404 for non-existent fiscal period', async () => {
enqueue({ data: null, error: { message: 'not found' } })
const res = await POST(makeRequest({
fiscal_period_id: PERIOD_ID,
lines: [
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
],
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect((body.error as unknown as { code: string }).code).toBe('OB_PERIOD_NOT_FOUND')
})
it('returns 409 if period already has opening balances', async () => {
enqueue({
data: {
id: PERIOD_ID,
company_id: 'company-1',
is_closed: false,
locked_at: null,
opening_balances_set: true,
opening_balance_entry_id: 'entry-existing',
period_start: '2026-01-01',
},
})
const res = await POST(makeRequest({
fiscal_period_id: PERIOD_ID,
lines: [
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
],
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(409)
expect((body.error as unknown as { code: string }).code).toBe('OB_PERIOD_ALREADY_HAS_BALANCES')
expect(
(body.error as unknown as { details: { existingEntryId: string } }).details.existingEntryId,
).toBe('entry-existing')
})
it('returns 400 for unbalanced lines', async () => {
enqueue({
data: {
id: PERIOD_ID,
company_id: 'company-1',
is_closed: false,
locked_at: null,
opening_balances_set: false,
period_start: '2026-01-01',
},
})
const res = await POST(makeRequest({
fiscal_period_id: PERIOD_ID,
lines: [
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 40000 },
],
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(400)
expect((body.error as unknown as { code: string }).code).toBe('OB_UNBALANCED')
})
it('returns 400 for P&L accounts', async () => {
enqueue({
data: {
id: PERIOD_ID,
company_id: 'company-1',
is_closed: false,
locked_at: null,
opening_balances_set: false,
period_start: '2026-01-01',
},
})
const res = await POST(makeRequest({
fiscal_period_id: PERIOD_ID,
lines: [
{ account_number: '3001', debit_amount: 0, credit_amount: 50000 },
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
],
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(400)
expect((body.error as unknown as { code: string }).code).toBe('OB_PNL_ACCOUNT')
})
it('creates journal entry on success', async () => {
// Fiscal period query
enqueue({
data: {
id: PERIOD_ID,
company_id: 'company-1',
is_closed: false,
locked_at: null,
opening_balances_set: false,
period_start: '2026-01-01',
},
})
// Fiscal period update
enqueue({ data: null })
mockCreateJournalEntry.mockResolvedValue({
id: 'entry-new',
company_id: 'company-1',
user_id: 'user-1',
fiscal_period_id: PERIOD_ID,
entry_date: '2026-01-01',
description: 'Ingående balanser (Excel-import)',
source_type: 'opening_balance',
voucher_series: 'A',
voucher_number: 1,
source_id: null,
reverses_id: null,
reversed_by_id: null,
correction_of_id: null,
attachment_urls: null,
notes: null,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
})
const res = await POST(makeRequest({
fiscal_period_id: PERIOD_ID,
lines: [
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
],
}))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.success).toBe(true)
expect(body.data.journal_entry_id).toBe('entry-new')
expect(body.data.lines_created).toBe(2)
expect(body.data.total_debit).toBe(50000)
expect(body.data.total_credit).toBe(50000)
expect(mockCreateJournalEntry).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({
fiscal_period_id: PERIOD_ID,
entry_date: '2026-01-01',
source_type: 'opening_balance',
voucher_series: 'A',
}),
)
})
})
@@ -0,0 +1,220 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const mockBackfill = vi.fn().mockResolvedValue([])
vi.mock('@/lib/bookkeeping/account-backfill', () => ({
backfillStandardBASAccounts: (...args: unknown[]) => mockBackfill(...args),
}))
// The cascade has its own unit tests; here we verify the route wires it with
// mode 'inline' and the delta computed from struck vs new lines.
const mockCascade = vi.fn()
vi.mock('@/lib/import/opening-balance/cascade', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return {
...actual,
cascadeOpeningBalanceCorrection: (...args: unknown[]) => mockCascade(...args),
}
})
import { POST } from '../route'
const PERIOD_ID = '550e8400-e29b-41d4-a716-446655440000'
const LINE_1930 = '11111111-1111-4111-8111-111111111111'
const ROUTE_PARAMS = { params: Promise.resolve({}) }
interface InlineResponse {
data: {
success: boolean
journal_entry_id: string
cascade?: { corrected: unknown[]; skipped: unknown[] }
}
error?: { code: string; message?: string }
}
function makeRequest(body: unknown) {
return createMockRequest('/api/import/opening-balance/correct-inline', {
method: 'POST',
body,
})
}
function openPeriod(overrides: Record<string, unknown> = {}) {
return {
id: PERIOD_ID,
period_start: '2024-01-01',
is_closed: false,
locked_at: null,
opening_balances_set: true,
opening_balance_entry_id: 'entry-ib',
...overrides,
}
}
const BODY = {
fiscal_period_id: PERIOD_ID,
strike_line_ids: [LINE_1930],
new_lines: [{ account_number: '1930', debit_amount: 55000, credit_amount: 0 }],
cascade: true,
}
describe('POST /api/import/opening-balance/correct-inline', () => {
const mockUser = { id: 'user-1', email: '[email protected]' }
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
mockCascade.mockResolvedValue({ corrected: [], skipped: [] })
})
it('returns 401 for unauthenticated requests', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const res = await POST(makeRequest(BODY), ROUTE_PARAMS)
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 400 when nothing is struck or added', async () => {
const res = await POST(
makeRequest({ fiscal_period_id: PERIOD_ID, strike_line_ids: [], new_lines: [] }),
ROUTE_PARAMS,
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 404 for an unknown fiscal period', async () => {
enqueue({ data: null, error: { message: 'not found' } })
const res = await POST(makeRequest(BODY), ROUTE_PARAMS)
const { status, body } = await parseJsonResponse<InlineResponse>(res)
expect(status).toBe(404)
expect(body.error?.code).toBe('OB_PERIOD_NOT_FOUND')
})
it('refuses closed periods with the same code as the storno route', async () => {
enqueue({ data: openPeriod({ is_closed: true }) })
const res = await POST(makeRequest(BODY), ROUTE_PARAMS)
const { status, body } = await parseJsonResponse<InlineResponse>(res)
expect(status).toBe(400)
expect(body.error?.code).toBe('OB_PERIOD_CLOSED')
})
it('refuses periods with a posted bokslut', async () => {
enqueue({ data: openPeriod() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // lock date
enqueue({ count: 1 }) // year-end check
const res = await POST(makeRequest(BODY), ROUTE_PARAMS)
const { status, body } = await parseJsonResponse<InlineResponse>(res)
expect(status).toBe(409)
expect(body.error?.code).toBe('OB_CORRECT_YEAR_END_EXISTS')
})
it('edits in place via the RPC and cascades inline with the delta from the rättelse log', async () => {
enqueue({ data: openPeriod() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // lock date
enqueue({ count: 0 }) // year-end check
enqueue({ data: { log_id: 'log-1', struck_count: 1, added_count: 1 } }) // RPC
enqueue({
data: {
struck_lines: [{ account_number: '1930', debit_amount: 50000, credit_amount: 0 }],
added_lines: [{ account_number: '1930', debit_amount: 55000, credit_amount: 0 }],
},
}) // rättelse-log fetch (authoritative delta source)
const res = await POST(makeRequest(BODY), ROUTE_PARAMS)
const { status, body } = await parseJsonResponse<InlineResponse>(res)
expect(status).toBe(200)
expect(body.data.success).toBe(true)
expect(body.data.journal_entry_id).toBe('entry-ib')
expect(body.data.cascade).toEqual({ corrected: [], skipped: [] })
expect(mockSupabase.rpc).toHaveBeenCalledWith(
'correct_entry_lines_inline',
expect.objectContaining({
p_company_id: 'company-1',
p_entry_id: 'entry-ib',
p_strike_line_ids: [LINE_1930],
p_new_lines: [
expect.objectContaining({ account_number: '1930', debit_amount: 55000 }),
],
p_user_id: 'user-1',
}),
)
// Cascade runs in inline mode with delta = added (55000) minus struck
// (50000), sourced from the RPC's own rättelse-log row.
expect(mockCascade).toHaveBeenCalledTimes(1)
const opts = mockCascade.mock.calls[0][3] as {
basePeriodStart: string
mode: string
deltas: Map<string, number>
}
expect(opts.mode).toBe('inline')
expect(opts.basePeriodStart).toBe('2024-01-01')
expect(opts.deltas.get('1930')).toBe(5000)
})
it('does not cascade when the flag is omitted', async () => {
enqueue({ data: openPeriod() })
enqueue({ data: { bookkeeping_locked_through: null } })
enqueue({ count: 0 })
enqueue({ data: { log_id: 'log-1' } }) // RPC; no log fetch without cascade
const res = await POST(
makeRequest({ ...BODY, cascade: undefined }),
ROUTE_PARAMS,
)
const { status, body } = await parseJsonResponse<InlineResponse>(res)
expect(status).toBe(200)
expect(body.data.cascade).toBeUndefined()
expect(mockCascade).not.toHaveBeenCalled()
})
it('surfaces an RPC rule violation verbatim as 409 OB_INLINE_REFUSED', async () => {
enqueue({ data: openPeriod() })
enqueue({ data: { bookkeeping_locked_through: null } })
enqueue({ count: 0 })
enqueue({ data: null, error: { code: 'P0001', message: 'Verifikationen balanserar inte efter rättelsen (debet 55000, kredit 50000).' } })
const res = await POST(makeRequest(BODY), ROUTE_PARAMS)
const { status, body } = await parseJsonResponse<InlineResponse>(res)
expect(status).toBe(409)
expect(body.error?.code).toBe('OB_INLINE_REFUSED')
expect(body.error?.message).toContain('balanserar inte')
expect(mockCascade).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,209 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { OpeningBalanceCorrectInlineSchema } from '@/lib/api/schemas'
import { backfillStandardBASAccounts } from '@/lib/bookkeeping/account-backfill'
import {
cascadeOpeningBalanceCorrection,
computeAccountDeltas,
type CascadeResult,
} from '@/lib/import/opening-balance/cascade'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
/**
* POST /api/import/opening-balance/correct-inline
*
* Fortnox-style IB correction: strike changed lines and add replacements
* inside the SAME IB verifikat (BFL 5 kap 5 § track 2, rättelse in the same
* bokföringspost), via the correct_entry_lines_inline RPC. No storno, no new
* verifikat; the struck originals live on in journal_entry_rattelse_log and
* fiscal_periods.opening_balance_entry_id never changes.
*
* Only for open, unlocked years without a bokslut: the pre-flights below
* return the same OB_* codes as the storno-based /correct route (so the
* dialog's blocked-year guidance applies), and the RPC re-enforces the whole
* envelope transactionally.
*
* With `cascade: true` the per-account delta (added minus struck) is appended
* as labelled adjustment lines inside each subsequent year's own IB verifikat
* (cascade mode 'inline'): a multi-year correction with zero new verifikat.
* Locked/closed/bokslut years are skipped and reported, never forced.
*/
export const POST = withRouteContext(
'opening_balance.correct_inline',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const result = await validateBody(request, OpeningBalanceCorrectInlineSchema, {
log,
operation: 'opening_balance.correct_inline',
})
if (!result.success) return result.response
const { fiscal_period_id, strike_line_ids, new_lines, cascade } = result.data
const opLog = log.child({ fiscalPeriodId: fiscal_period_id })
// Pre-flights mirror the storno-based /correct route (same OB_* codes so
// the client guidance is uniform). The RPC re-checks everything inside
// its transaction: these exist to give structured, actionable errors.
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('id, period_start, is_closed, locked_at, opening_balances_set, opening_balance_entry_id')
.eq('id', fiscal_period_id)
.eq('company_id', companyId)
.single()
if (periodError || !period) {
return errorResponseFromCode('OB_PERIOD_NOT_FOUND', opLog, { requestId })
}
if (period.is_closed) {
return errorResponseFromCode('OB_PERIOD_CLOSED', opLog, { requestId })
}
if (period.locked_at) {
return errorResponseFromCode('OB_PERIOD_LOCKED', opLog, { requestId })
}
const { data: settings } = await supabase
.from('company_settings')
.select('bookkeeping_locked_through')
.eq('company_id', companyId)
.maybeSingle()
const lockDate = settings?.bookkeeping_locked_through as string | null
if (lockDate && period.period_start <= lockDate) {
return errorResponseFromCode('OB_COMPANY_LOCK_DATE', opLog, {
requestId,
details: { lockDate, entryDate: period.period_start },
})
}
if (!period.opening_balances_set || !period.opening_balance_entry_id) {
return errorResponseFromCode('OB_CORRECT_NO_EXISTING', opLog, { requestId })
}
const { count: yearEndCount } = await supabase
.from('journal_entries')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscal_period_id)
.eq('source_type', 'year_end')
.eq('status', 'posted')
if ((yearEndCount ?? 0) > 0) {
return errorResponseFromCode('OB_CORRECT_YEAR_END_EXISTS', opLog, { requestId })
}
const entryId = period.opening_balance_entry_id
// Seed standard BAS accounts the replacement lines reference but the
// chart lacks (same courtesy as the storno flow); unknown numbers fail
// the RPC's chart check with a clear error.
const accountNumbers = [...new Set(new_lines.map((l) => l.account_number))]
if (accountNumbers.length > 0) {
await backfillStandardBASAccounts(supabase, companyId!, user.id, accountNumbers)
}
const { data: rpcData, error: rpcError } = await supabase.rpc('correct_entry_lines_inline', {
p_company_id: companyId,
p_entry_id: entryId,
p_strike_line_ids: strike_line_ids,
p_new_lines: new_lines.map((l) => ({
account_number: l.account_number,
debit_amount: l.debit_amount,
credit_amount: l.credit_amount,
line_description: l.line_description ?? null,
dimensions: l.dimensions ?? {},
})),
p_user_id: user.id,
})
if (rpcError) {
// Rule violations are plain RAISE EXCEPTION (P0001) with user-facing
// Swedish messages: surface verbatim (same approach as the generic
// strike-lines route). Tenant guard raises 42501.
if (rpcError.code === 'P0001') {
return NextResponse.json(
{
error: {
code: 'OB_INLINE_REFUSED',
message: getUserErrorMessage(rpcError, { locale: 'sv' }),
message_en: getUserErrorMessage(rpcError, { locale: 'en' }),
requestId,
},
},
{ status: 409 },
)
}
if (rpcError.code === '42501') {
return NextResponse.json(
{ error: { code: 'FORBIDDEN', message: getUserErrorMessage(rpcError), requestId } },
{ status: 403 },
)
}
opLog.error('correct_entry_lines_inline failed for IB', new Error(rpcError.message), { entryId })
return errorResponseFromCode('OB_CORRECT_FAILED', opLog, {
requestId,
details: { reason: getUserErrorMessage(rpcError) },
})
}
// Base rättelse committed. Cascade is best-effort on top, one inline
// rättelse per later year; a failure there never errors this request.
//
// The delta comes from the RPC's OWN rättelse-log row (struck_lines /
// added_lines snapshotted inside the RPC transaction), never from a
// pre-RPC read: a concurrent edit between a route-side snapshot and the
// RPC could otherwise cascade a delta that no longer matches what was
// actually committed to the base year.
let cascadeResult: CascadeResult | null = null
if (cascade) {
try {
const logId = (rpcData as { log_id?: string } | null)?.log_id
const { data: logRow, error: logError } = await supabase
.from('journal_entry_rattelse_log')
.select('struck_lines, added_lines')
.eq('id', logId)
.eq('company_id', companyId)
.single()
if (logError || !logRow) {
throw new Error(`rättelse log fetch failed: ${logError?.message ?? 'not found'}`)
}
const toLines = (raw: unknown) =>
((raw ?? []) as Array<{ account_number: string; debit_amount: number | string; credit_amount: number | string }>).map(
(l) => ({
account_number: l.account_number,
debit_amount: Number(l.debit_amount) || 0,
credit_amount: Number(l.credit_amount) || 0,
}),
)
const deltas = computeAccountDeltas(toLines(logRow.struck_lines), toLines(logRow.added_lines))
cascadeResult = await cascadeOpeningBalanceCorrection(supabase, companyId!, user.id, {
basePeriodStart: period.period_start,
deltas,
lockDate,
mode: 'inline',
log: opLog,
})
} catch (cascadeErr) {
opLog.error('inline opening balance cascade failed', cascadeErr as Error)
cascadeResult = { corrected: [], skipped: [], failed: true }
}
}
return NextResponse.json({
data: {
success: true,
journal_entry_id: entryId,
rattelse: rpcData,
...(cascadeResult ? { cascade: cascadeResult } : {}),
},
})
},
{ requireWrite: true },
)
@@ -0,0 +1,193 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const mockCreateJournalEntry = vi.fn()
const mockReverseEntry = vi.fn()
vi.mock('@/lib/bookkeeping/engine', () => ({
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
reverseEntry: (...args: unknown[]) => mockReverseEntry(...args),
}))
vi.mock('@/lib/bookkeeping/bas-reference', () => ({
getBASReference: vi.fn().mockReturnValue(null),
}))
vi.mock('@/lib/supabase/fetch-all', () => ({
fetchAllRows: vi.fn().mockResolvedValue([
{ account_number: '1930' },
{ account_number: '2099' },
]),
}))
// The cascade itself has its own unit tests (lib/import/opening-balance/
// __tests__/cascade.test.ts); here we verify the route wires it correctly:
// flag → original-lines fetch → delta computation → cascade call → response.
const mockCascade = vi.fn()
const mockFetchOriginalLines = vi.fn()
vi.mock('@/lib/import/opening-balance/cascade', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return {
...actual,
cascadeOpeningBalanceCorrection: (...args: unknown[]) => mockCascade(...args),
fetchEntryOpeningBalanceLines: (...args: unknown[]) => mockFetchOriginalLines(...args),
}
})
import { POST } from '../route'
const PERIOD_ID = '550e8400-e29b-41d4-a716-446655440000'
const CORRECTED_LINES = [
{ account_number: '1930', debit_amount: 40000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 40000 },
]
function makeRequest(body: unknown) {
return createMockRequest('/api/import/opening-balance/correct', {
method: 'POST',
body,
})
}
const ROUTE_PARAMS = { params: Promise.resolve({}) }
interface CorrectResponse {
data: {
success: boolean
cascade?: {
corrected: Array<Record<string, unknown>>
skipped: Array<Record<string, unknown>>
}
}
}
function enqueueHappyPath() {
enqueue({
data: {
id: PERIOD_ID,
company_id: 'company-1',
is_closed: false,
locked_at: null,
opening_balances_set: true,
opening_balance_entry_id: 'entry-old',
period_start: '2019-01-01',
opening_balance_entry: { voucher_series: 'A', voucher_number: 1 },
},
}) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // lock-date pre-flight
enqueue({ count: 0 }) // year-end check
enqueue({ error: null }) // relink RPC
}
describe('POST /api/import/opening-balance/correct: cascade wiring', () => {
const mockUser = { id: 'user-1', email: '[email protected]' }
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
mockCreateJournalEntry.mockResolvedValue({ id: 'entry-new', voucher_series: 'A', voucher_number: 9 })
mockReverseEntry.mockResolvedValue({ id: 'entry-storno' })
mockFetchOriginalLines.mockResolvedValue([
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
])
mockCascade.mockResolvedValue({
corrected: [
{
fiscal_period_id: 'period-2020',
period_name: '2020',
journal_entry_id: 'ib-2020-new',
reversed_entry_id: 'ib-2020',
},
],
skipped: [{ fiscal_period_id: 'period-2021', period_name: '2021', reason: 'closed' }],
})
})
it('runs the cascade with the correction deltas and returns its result', async () => {
enqueueHappyPath()
const res = await POST(
makeRequest({ fiscal_period_id: PERIOD_ID, lines: CORRECTED_LINES, cascade: true }),
ROUTE_PARAMS,
)
const { status, body } = await parseJsonResponse<CorrectResponse>(res)
expect(status).toBe(200)
expect(body.data.success).toBe(true)
expect(body.data.cascade).toEqual({
corrected: [expect.objectContaining({ fiscal_period_id: 'period-2020' })],
skipped: [expect.objectContaining({ fiscal_period_id: 'period-2021', reason: 'closed' })],
})
// Original lines are fetched from the OLD entry (before it is stornoed).
expect(mockFetchOriginalLines).toHaveBeenCalledWith(expect.anything(), 'company-1', 'entry-old')
// The cascade gets the base period start and the per-account delta
// (1930: 40000 - 50000 = -10000, 2099: -40000 - (-50000) = +10000).
expect(mockCascade).toHaveBeenCalledTimes(1)
const opts = mockCascade.mock.calls[0][3] as {
basePeriodStart: string
deltas: Map<string, number>
lockDate: string | null
}
expect(opts.basePeriodStart).toBe('2019-01-01')
expect(opts.lockDate).toBeNull()
expect(opts.deltas.get('1930')).toBe(-10000)
expect(opts.deltas.get('2099')).toBe(10000)
})
it('does not touch later periods when cascade is omitted', async () => {
enqueueHappyPath()
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: CORRECTED_LINES }), ROUTE_PARAMS)
const { status, body } = await parseJsonResponse<CorrectResponse>(res)
expect(status).toBe(200)
expect(body.data.success).toBe(true)
expect(body.data.cascade).toBeUndefined()
expect(mockFetchOriginalLines).not.toHaveBeenCalled()
expect(mockCascade).not.toHaveBeenCalled()
})
it('still returns success for the base correction when the cascade throws unexpectedly', async () => {
enqueueHappyPath()
mockCascade.mockRejectedValue(new Error('cascade boom'))
const res = await POST(
makeRequest({ fiscal_period_id: PERIOD_ID, lines: CORRECTED_LINES, cascade: true }),
ROUTE_PARAMS,
)
const { status, body } = await parseJsonResponse<CorrectResponse>(res)
// The base correction is already committed; the response must not flip to
// an error the caller would retry (double-correcting the base year), but
// the failure must be visible so the client can tell the user to check.
expect(status).toBe(200)
expect(body.data.success).toBe(true)
expect(body.data.cascade).toEqual({ corrected: [], skipped: [], failed: true })
})
})
@@ -0,0 +1,220 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const mockCreateJournalEntry = vi.fn()
const mockReverseEntry = vi.fn()
vi.mock('@/lib/bookkeeping/engine', () => ({
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
reverseEntry: (...args: unknown[]) => mockReverseEntry(...args),
}))
vi.mock('@/lib/bookkeeping/bas-reference', () => ({
getBASReference: vi.fn().mockReturnValue(null),
}))
vi.mock('@/lib/supabase/fetch-all', () => ({
// All referenced accounts already exist → no chart activation insert (and no
// extra supabase.from() call that would shift the queued-mock cursor).
fetchAllRows: vi.fn().mockResolvedValue([
{ account_number: '1930' },
{ account_number: '2099' },
]),
}))
import { POST } from '../route'
type SpyInstance = ReturnType<typeof vi.spyOn>
const PERIOD_ID = '550e8400-e29b-41d4-a716-446655440000'
const BALANCED_LINES = [
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
]
function makeRequest(body: unknown) {
return createMockRequest('/api/import/opening-balance/correct', {
method: 'POST',
body,
})
}
function openPeriodWithOB(overrides: Record<string, unknown> = {}) {
return {
id: PERIOD_ID,
company_id: 'company-1',
is_closed: false,
locked_at: null,
opening_balances_set: true,
opening_balance_entry_id: 'entry-old',
period_start: '2026-01-01',
// Embedded resource from the period fetch: the original IB verifikat's
// voucher label, used to build the BFL 5 kap 5§ reference.
opening_balance_entry: { voucher_series: 'A', voucher_number: 123 },
...overrides,
}
}
/** Flatten every console.error call into one searchable string. */
function auditLines(spy: SpyInstance): string {
return spy.mock.calls
.map((call) => call.map((a: unknown) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' '))
.filter((line) => line.includes('opening balance correction failed'))
.join('\n')
}
describe('POST /api/import/opening-balance/correct: atomicity, audit, BFL reference', () => {
const mockUser = { id: 'user-1', email: '[email protected]' }
let errorSpy: SpyInstance
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
// The structured logger writes error-level records to console.error even in
// the test env; spy on it so we can assert the durable audit line.
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
errorSpy.mockRestore()
})
// FIX 3 (BFL 5 kap 5§): the corrected entry references the original voucher.
it('references the original verifikationsnummer in the corrected entry description', async () => {
enqueue({ data: openPeriodWithOB({ opening_balance_entry: { voucher_series: 'B', voucher_number: 7 } }) }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
enqueue({ count: 0 }) // year-end check
enqueue({ error: null }) // replace_period_opening_balance_link RPC
mockCreateJournalEntry.mockResolvedValue({ id: 'entry-new', voucher_series: 'A', voucher_number: 9 })
mockReverseEntry.mockResolvedValue({ id: 'entry-storno' })
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(body.data.success).toBe(true)
expect(mockCreateJournalEntry).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({
description: 'Ingående balanser (korrigerade, rättelse av B7)',
source_type: 'opening_balance',
}),
)
// Happy path stornoes ONLY the old entry, no compensating reverse.
expect(mockReverseEntry).toHaveBeenCalledTimes(1)
expect(mockReverseEntry).toHaveBeenCalledWith(expect.anything(), 'company-1', 'user-1', 'entry-old')
})
// FIX 1 (ASVS V2.3): compensation when the storno of the OLD entry throws
// after the new entry was already created.
it('compensates by stornoing the new entry when reverseEntry throws, returning OB_CORRECT_FAILED', async () => {
enqueue({ data: openPeriodWithOB() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
enqueue({ count: 0 }) // year-end check
// No RPC enqueue: step B throws before the relink is reached.
mockCreateJournalEntry.mockResolvedValue({ id: 'entry-new', voucher_series: 'A', voucher_number: 9 })
mockReverseEntry
.mockRejectedValueOnce(new Error('storno of old failed')) // step B (oldEntryId)
.mockResolvedValueOnce({ id: 'entry-storno-new' }) // compensation (newEntry.id)
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(500)
expect((body.error as unknown as { code: string }).code).toBe('OB_CORRECT_FAILED')
// First the failed storno of the old entry, then the compensating storno of
// the new entry.
expect(mockReverseEntry).toHaveBeenCalledTimes(2)
expect(mockReverseEntry).toHaveBeenNthCalledWith(1, expect.anything(), 'company-1', 'user-1', 'entry-old')
expect(mockReverseEntry).toHaveBeenNthCalledWith(2, expect.anything(), 'company-1', 'user-1', 'entry-new')
// Durable audit carries both ids for manual recovery.
const audit = auditLines(errorSpy)
expect(audit).toContain('entry-new')
expect(audit).toContain('entry-old')
})
// FIX 1 + FIX 2: relink RPC error triggers compensation and a durable audit.
it('compensates and emits a durable audit when the relink RPC returns an error', async () => {
enqueue({ data: openPeriodWithOB() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
enqueue({ count: 0 }) // year-end check
enqueue({ error: { message: 'relink boom' } }) // RPC failure
mockCreateJournalEntry.mockResolvedValue({ id: 'entry-new', voucher_series: 'A', voucher_number: 9 })
mockReverseEntry.mockResolvedValue({ id: 'entry-storno' }) // step B + compensation both succeed
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(500)
const err = body.error as unknown as { code: string; details?: { newEntryId?: string; oldEntryId?: string } }
expect(err.code).toBe('OB_CORRECT_FAILED')
expect(err.details?.newEntryId).toBe('entry-new')
expect(err.details?.oldEntryId).toBe('entry-old')
// Compensation: old entry stornoed (step B) then the new entry stornoed.
expect(mockReverseEntry).toHaveBeenCalledTimes(2)
expect(mockReverseEntry).toHaveBeenNthCalledWith(1, expect.anything(), 'company-1', 'user-1', 'entry-old')
expect(mockReverseEntry).toHaveBeenNthCalledWith(2, expect.anything(), 'company-1', 'user-1', 'entry-new')
// Durable audit event payload contains newEntryId + oldEntryId.
const audit = auditLines(errorSpy)
expect(audit).toContain('opening_balance.correction_failed')
expect(audit).toContain('entry-new')
expect(audit).toContain('entry-old')
})
// FIX 2: the compensating storno may itself fail; the handler must still
// return the envelope and audit the compensation failure (never rethrow).
it('audits a compensation failure and still returns OB_CORRECT_FAILED', async () => {
enqueue({ data: openPeriodWithOB() }) // period
enqueue({ data: { bookkeeping_locked_through: null } }) // company lock-date pre-flight
enqueue({ count: 0 }) // year-end check
enqueue({ error: { message: 'relink boom' } }) // RPC failure
mockCreateJournalEntry.mockResolvedValue({ id: 'entry-new', voucher_series: 'A', voucher_number: 9 })
mockReverseEntry
.mockResolvedValueOnce({ id: 'entry-storno' }) // step B ok
.mockRejectedValueOnce(new Error('compensation storno failed')) // compensation throws
const res = await POST(makeRequest({ fiscal_period_id: PERIOD_ID, lines: BALANCED_LINES }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(500)
expect((body.error as unknown as { code: string }).code).toBe('OB_CORRECT_FAILED')
const audit = auditLines(errorSpy)
expect(audit).toContain('compensation_failed')
expect(audit).toContain('entry-new')
expect(audit).toContain('entry-old')
})
})
@@ -0,0 +1,332 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { validateBody } from '@/lib/api/validate'
import { OpeningBalanceCorrectSchema } from '@/lib/api/schemas'
import { createJournalEntry, reverseEntry } from '@/lib/bookkeeping/engine'
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
import {
validateOpeningBalanceLines,
activateMissingAccounts,
buildOpeningBalanceEntryLines,
type OpeningBalanceLine,
} from '@/lib/import/opening-balance/execute-helpers'
import {
cascadeOpeningBalanceCorrection,
computeAccountDeltas,
fetchEntryOpeningBalanceLines,
type CascadeResult,
} from '@/lib/import/opening-balance/cascade'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
/**
* POST /api/import/opening-balance/correct
*
* Correct a period's existing opening balances the BFL-compliant way: the
* current IB verifikat (immutable, posted) is stornoed and a corrected IB is
* booked, then fiscal_periods.opening_balance_entry_id is relinked to the new
* entry via the replace_period_opening_balance_link RPC.
*
* Because getOpeningBalances reads the linked entry directly and the
* trial-balance / general-ledger movement queries include both `posted` and
* `reversed` lines (excluding only the linked OB entry), the stornoed old IB
* and its storno mirror cancel out in period movement, so the Balansrapport
* IB column shows the corrected figures and UB stays correct.
*
* Gated to the safe case only: the period must be open, unlocked, already have
* opening balances, and have no year-end close on top. Locked/closed periods or
* periods with a bokslut must be unwound first (assisted): we refuse here.
*
* With `cascade: true` the same per-account delta is then applied to every
* subsequent year's linked IB verifikat (storno + rebook + relink per year;
* see lib/import/opening-balance/cascade.ts). SIE migrations book one IB per
* imported year, so without the cascade a base-year correction leaves later
* years' IB verifikat carrying the stale figures. Uncorrectable years are
* skipped and reported in the response, never forced.
*/
export const POST = withRouteContext(
'opening_balance.correct',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const result = await validateBody(request, OpeningBalanceCorrectSchema, {
log,
operation: 'opening_balance.correct',
})
if (!result.success) return result.response
const { fiscal_period_id, lines, cascade } = result.data
const opLog = log.child({ fiscalPeriodId: fiscal_period_id })
try {
// 1. Verify the fiscal period belongs to the company and is correctable.
// Write-role (non-viewer) + company membership are already enforced by
// withRouteContext({ requireWrite: true }) before this handler runs
// (requireWritePermission + getActiveCompanyId), and this fetch is scoped
// by that verified companyId: no redundant authz here (ASVS V8.2.1).
// The embedded opening_balance_entry pulls the original IB verifikat's
// voucher label so the corrected entry can reference it (BFL 5 kap 5§).
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select(
'*, opening_balance_entry:journal_entries!opening_balance_entry_id(voucher_series, voucher_number)',
)
.eq('id', fiscal_period_id)
.eq('company_id', companyId)
.single()
if (periodError || !period) {
return errorResponseFromCode('OB_PERIOD_NOT_FOUND', opLog, { requestId })
}
if (period.is_closed) {
return errorResponseFromCode('OB_PERIOD_CLOSED', opLog, { requestId })
}
if (period.locked_at) {
return errorResponseFromCode('OB_PERIOD_LOCKED', opLog, { requestId })
}
// Company-wide lock date pre-flight. The enforce_company_lock_date
// trigger blocks BOTH the corrected IB and the storno of the old one
// (each books at period_start), and a trigger rejection surfaces as a
// retryable-500 BOOKKEEPING_DATABASE_ERROR with a generic message —
// which invites blind retries (prod incident: 3× against a covering
// lock date). Pre-flight it and return an actionable 409 instead.
const { data: settings } = await supabase
.from('company_settings')
.select('bookkeeping_locked_through')
.eq('company_id', companyId)
.maybeSingle()
const lockDate = settings?.bookkeeping_locked_through as string | null
if (lockDate && period.period_start <= lockDate) {
return errorResponseFromCode('OB_COMPANY_LOCK_DATE', opLog, {
requestId,
details: { lockDate, entryDate: period.period_start },
})
}
if (!period.opening_balances_set || !period.opening_balance_entry_id) {
return errorResponseFromCode('OB_CORRECT_NO_EXISTING', opLog, { requestId })
}
// Refuse if a year-end close was built on top: correcting the IB without
// unwinding the bokslut would leave the period (and the next period's
// carried-forward IB) internally inconsistent.
const { count: yearEndCount } = await supabase
.from('journal_entries')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscal_period_id)
.eq('source_type', 'year_end')
.eq('status', 'posted')
if ((yearEndCount ?? 0) > 0) {
return errorResponseFromCode('OB_CORRECT_YEAR_END_EXISTS', opLog, { requestId })
}
const oldEntryId = period.opening_balance_entry_id
// 2. Validate the corrected lines (drop zeros, ≥2 rows, no P&L, must balance).
const validation = validateOpeningBalanceLines(lines)
if (!validation.ok) {
return errorResponseFromCode(validation.code, opLog, {
requestId,
details:
validation.code === 'OB_PNL_ACCOUNT'
? { accounts: validation.accounts }
: validation.code === 'OB_UNBALANCED'
? { totalDebit: validation.totalDebit, totalCredit: validation.totalCredit, diff: validation.diff }
: undefined,
})
}
const { validLines, totalDebit, totalCredit } = validation
// 3. Auto-activate BAS accounts the corrected file references but the chart lacks.
const accountNumbers = [...new Set(validLines.map((l) => l.account_number))]
const activation = await activateMissingAccounts(supabase, companyId!, user.id, accountNumbers)
if (!activation.ok) {
opLog.error('opening balance account activation failed', new Error(activation.reason))
return errorResponseFromCode('OB_ACCOUNT_ACTIVATION_FAILED', opLog, {
requestId,
details: { reason: activation.reason },
})
}
// Cascade needs the ORIGINAL lines to compute the per-account delta,
// so fetch them before the old entry is stornoed below.
let originalLines: OpeningBalanceLine[] | null = null
if (cascade) {
originalLines = await fetchEntryOpeningBalanceLines(supabase, companyId!, oldEntryId)
}
// BFL 5 kap 5§: reference the original verifikat so the correction is
// traceable to the entry it rättar. The embed above gave us the old IB's
// voucher label (e.g. "A123"). CreateJournalEntryInput exposes no dedicated
// correction-linkage field (corrects_entry_id / correction_of / metadata),
// so the description reference IS the linkage; we deliberately leave the
// generic source_id unset rather than overload it for an opening_balance.
const originalRef = (
period as {
opening_balance_entry?: {
voucher_series?: string | null
voucher_number?: number | null
} | null
}
).opening_balance_entry
const originalVoucherLabel =
originalRef?.voucher_series && originalRef?.voucher_number
? `${originalRef.voucher_series}${originalRef.voucher_number}`
: null
const correctedDescription = originalVoucherLabel
? `Ingående balanser (korrigerade, rättelse av ${originalVoucherLabel})`
: 'Ingående balanser (korrigerade)'
// 4. Book the corrected IB, storno the old one, then relink the period.
// Order matters: create the replacement BEFORE reversing the original so a
// mid-failure never leaves the period without an opening balance.
const newEntry = await createJournalEntry(supabase, companyId!, user.id, {
fiscal_period_id,
entry_date: period.period_start,
description: correctedDescription,
source_type: 'opening_balance',
voucher_series: 'A',
lines: buildOpeningBalanceEntryLines(validLines),
})
// ASVS V16: durable audit sink for a failed correction. The core event bus
// has no opening_balance.* correction event type and lib/events/types.ts is
// outside the scope of this change, so the failure is recorded via the
// structured logger: it lands in the JSON log (Vercel logs, plus the
// observability sink, which no-ops until a provider is configured), tagged
// `audit: true` + both entry ids so an operator can reconcile the period by
// hand. (Follow-up: promote to a typed event persisted to event_log.)
const auditCorrectionFailure = (fields: Record<string, unknown>) => {
opLog.error('audit: opening balance correction failed', {
audit: true,
event: 'opening_balance.correction_failed',
companyId,
userId: user.id,
fiscalPeriodId: fiscal_period_id,
newEntryId: newEntry.id,
oldEntryId,
...fields,
})
}
// FIX (ASVS V2.3: atomicity via compensation): steps B (storno old) and
// C (relink) are NOT atomic with A (create new). A already produced a second
// posted opening_balance entry for the period; if B or C fails, that entry is
// orphaned and the Balansrapport would show two OB entries. Wrap B+C so that
// on ANY failure below we compensate by stornoing the NEW entry, restoring the
// period to its original consistent state (original OB still linked, new entry
// cancelled by its own storno).
try {
// B: storno the original IB.
await reverseEntry(supabase, companyId!, user.id, oldEntryId)
// C: point the period at the corrected IB (single atomic RPC).
const { error: relinkError } = await supabase.rpc('replace_period_opening_balance_link', {
p_company_id: companyId,
p_period_id: fiscal_period_id,
p_new_entry_id: newEntry.id,
})
if (relinkError) {
// Funnel the RPC error into the single compensation path below.
throw new Error(`replace_period_opening_balance_link failed: ${relinkError.message}`)
}
} catch (seqErr) {
const reason = seqErr instanceof Error ? seqErr.message : 'unknown'
// Durable audit BEFORE compensation so the ids survive even if the
// compensating storno also throws.
//
// Residual edge (documented): if B succeeded but C failed, the old entry is
// now reversed yet still linked to the period. We still compensate the new
// entry; the audit payload carries newEntryId + oldEntryId so an operator can
// finish recovery (re-link or re-book) manually.
auditCorrectionFailure({ phase: 'sequence_failed', reason })
// Compensating rollback. This may itself throw (e.g. the period was locked
// between A and here): catch + audit and never let it propagate past the
// handler, so the caller always gets the OB_CORRECT_FAILED envelope.
try {
await reverseEntry(supabase, companyId!, user.id, newEntry.id)
auditCorrectionFailure({ phase: 'compensated', reason })
} catch (compErr) {
auditCorrectionFailure({
phase: 'compensation_failed',
reason,
compensationError: compErr instanceof Error ? compErr.message : 'unknown',
})
}
return errorResponseFromCode('OB_CORRECT_FAILED', opLog, {
requestId,
details: {
reason: getUserErrorMessage(seqErr),
newEntryId: newEntry.id,
oldEntryId,
},
})
}
// The base correction is committed at this point. The cascade to later
// years is best-effort on top: each year is corrected independently and
// an unexpected failure must not turn the whole request into an error
// (the base correction cannot be un-done here).
let cascadeResult: CascadeResult | null = null
if (cascade && originalLines) {
try {
const deltas = computeAccountDeltas(originalLines, validLines)
cascadeResult = await cascadeOpeningBalanceCorrection(supabase, companyId!, user.id, {
basePeriodStart: period.period_start,
deltas,
lockDate,
log: opLog,
})
} catch (cascadeErr) {
opLog.error('opening balance cascade failed', cascadeErr as Error)
cascadeResult = { corrected: [], skipped: [], failed: true }
}
}
return NextResponse.json({
data: {
success: true,
journal_entry_id: newEntry.id,
reversed_entry_id: oldEntryId,
fiscal_period_id,
lines_created: validLines.length,
total_debit: totalDebit,
total_credit: totalCredit,
...(cascadeResult ? { cascade: cascadeResult } : {}),
},
})
} catch (err) {
// Belt-and-braces: if the lock-date trigger fired anyway (lock date set
// between the pre-flight and the write), return the same actionable
// envelope instead of the generic retryable BOOKKEEPING_DATABASE_ERROR.
const message = err instanceof Error ? err.message : ''
if (/Bokföringen är låst/i.test(message)) {
return errorResponseFromCode('OB_COMPANY_LOCK_DATE', opLog, {
requestId,
details: { reason: getUserErrorMessage(err) },
})
}
if (isBookkeepingError(err)) {
return errorResponse(err, opLog, { requestId })
}
opLog.error('opening balance correct failed', err as Error)
return errorResponseFromCode('OB_CORRECT_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
{ requireWrite: true },
)
@@ -0,0 +1,138 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { validateBody } from '@/lib/api/validate'
import { OpeningBalanceExecuteSchema } from '@/lib/api/schemas'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
import {
validateOpeningBalanceLines,
activateMissingAccounts,
buildOpeningBalanceEntryLines,
} from '@/lib/import/opening-balance/execute-helpers'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
/**
* POST /api/import/opening-balance/execute
*
* Creates an opening balance journal entry from user-confirmed lines and
* auto-activates BAS accounts not yet in the company's chart.
*/
export const POST = withRouteContext(
'opening_balance.execute',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const result = await validateBody(request, OpeningBalanceExecuteSchema, {
log,
operation: 'opening_balance.execute',
})
if (!result.success) return result.response
const { fiscal_period_id, lines } = result.data
const opLog = log.child({ fiscalPeriodId: fiscal_period_id })
try {
// 1. Verify fiscal period belongs to the company and is open.
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('*')
.eq('id', fiscal_period_id)
.eq('company_id', companyId)
.single()
if (periodError || !period) {
return errorResponseFromCode('OB_PERIOD_NOT_FOUND', opLog, { requestId })
}
if (period.is_closed) {
return errorResponseFromCode('OB_PERIOD_CLOSED', opLog, { requestId })
}
if (period.locked_at) {
return errorResponseFromCode('OB_PERIOD_LOCKED', opLog, { requestId })
}
if (period.opening_balances_set) {
return errorResponseFromCode('OB_PERIOD_ALREADY_HAS_BALANCES', opLog, {
requestId,
details: { existingEntryId: period.opening_balance_entry_id },
})
}
// 2. Validate lines (drop zeros, ≥2 rows, no P&L accounts, must balance).
const validation = validateOpeningBalanceLines(lines)
if (!validation.ok) {
return errorResponseFromCode(validation.code, opLog, {
requestId,
details:
validation.code === 'OB_PNL_ACCOUNT'
? { accounts: validation.accounts }
: validation.code === 'OB_UNBALANCED'
? { totalDebit: validation.totalDebit, totalCredit: validation.totalCredit, diff: validation.diff }
: undefined,
})
}
const { validLines, totalDebit, totalCredit } = validation
// 3. Auto-activate BAS accounts not in the company's chart.
const accountNumbers = [...new Set(validLines.map((l) => l.account_number))]
const activation = await activateMissingAccounts(supabase, companyId!, user.id, accountNumbers)
if (!activation.ok) {
opLog.error('opening balance account activation failed', new Error(activation.reason))
return errorResponseFromCode('OB_ACCOUNT_ACTIVATION_FAILED', opLog, {
requestId,
details: { reason: activation.reason },
})
}
// 4. Create the opening balance journal entry.
const entryLines = buildOpeningBalanceEntryLines(validLines)
const entry = await createJournalEntry(supabase, companyId!, user.id, {
fiscal_period_id,
entry_date: period.period_start,
description: 'Ingående balanser (Excel-import)',
source_type: 'opening_balance',
voucher_series: 'A',
lines: entryLines,
})
// 5. Mark the fiscal period.
await supabase
.from('fiscal_periods')
.update({
opening_balance_entry_id: entry.id,
opening_balances_set: true,
})
.eq('id', fiscal_period_id)
.eq('company_id', companyId)
return NextResponse.json({
data: {
success: true,
journal_entry_id: entry.id,
fiscal_period_id,
lines_created: entryLines.length,
total_debit: totalDebit,
total_credit: totalCredit,
},
})
} catch (err) {
// Bookkeeping errors flow through the standard envelope; everything else
// becomes OB_EXECUTE_FAILED so the user gets a Swedish toast.
if (isBookkeepingError(err)) {
return errorResponse(err, opLog, { requestId })
}
opLog.error('opening balance execute failed', err as Error)
return errorResponseFromCode('OB_EXECUTE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
{ requireWrite: true },
)
@@ -0,0 +1,68 @@
import { NextResponse } from 'next/server'
import { parseOpeningBalanceFile } from '@/lib/import/opening-balance/parser'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { DetectedColumns } from '@/lib/import/opening-balance/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const ALLOWED_EXTENSIONS = ['.xlsx', '.xls', '.csv', '.ods']
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
/**
* POST /api/import/opening-balance/parse
*
* Accepts an Excel/CSV file via FormData, auto-detects columns, and returns
* parsed opening balance rows with BAS matching.
*/
export const POST = withRouteContext(
'opening_balance.parse',
async (request, ctx) => {
const { log, requestId } = ctx
const formData = await request.formData()
const file = formData.get('file') as File | null
const columnOverridesRaw = formData.get('column_overrides') as string | null
if (!file) {
return errorResponseFromCode('OB_NO_FILE', log, { requestId })
}
if (file.size > MAX_FILE_SIZE) {
return errorResponseFromCode('OB_FILE_TOO_LARGE', log, {
requestId,
details: { sizeMb: +(file.size / 1024 / 1024).toFixed(1) },
})
}
const ext = '.' + file.name.split('.').pop()?.toLowerCase()
if (!ALLOWED_EXTENSIONS.includes(ext)) {
return errorResponseFromCode('OB_INVALID_FORMAT', log, {
requestId,
details: { extension: ext, allowed: ALLOWED_EXTENSIONS },
})
}
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
let columnOverrides: DetectedColumns | undefined
if (columnOverridesRaw) {
try {
columnOverrides = JSON.parse(columnOverridesRaw)
} catch {
return errorResponseFromCode('OB_INVALID_COLUMN_OVERRIDES', opLog, { requestId })
}
}
try {
const buffer = await file.arrayBuffer()
const result = parseOpeningBalanceFile(buffer, file.name, columnOverrides)
return NextResponse.json({ data: result })
} catch (err) {
opLog.error('opening balance parse failed', err as Error)
return errorResponseFromCode('OB_PARSE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
)
@@ -0,0 +1,116 @@
/**
* Tests for GET/DELETE /api/import/sie/[id].
*
* Exercises the route through the real withRouteContext wrapper, mocking only
* its auth/company/write dependencies and injecting a queued Supabase mock via
* requireAuth. Covers: 401, 403 viewer, the completed-import guard, and the
* happy-path delete of a failed import.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET, DELETE } from '../route'
const routeParams = () => createMockRouteParams({ id: 'import-1' })
describe('GET/DELETE /api/import/sie/[id]', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('DELETE returns 401 when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await DELETE(
createMockRequest('/api/import/sie/import-1', { method: 'DELETE' }),
routeParams(),
)
expect(response.status).toBe(401)
})
it('DELETE returns 403 for a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const response = await DELETE(
createMockRequest('/api/import/sie/import-1', { method: 'DELETE' }),
routeParams(),
)
expect(response.status).toBe(403)
})
it('DELETE refuses to delete a completed import (BFL retention)', async () => {
enqueue({ data: { status: 'completed' } })
const response = await DELETE(
createMockRequest('/api/import/sie/import-1', { method: 'DELETE' }),
routeParams(),
)
const { status, body } = await parseJsonResponse<{ error: string }>(response)
expect(status).toBe(403)
expect(body.error).toContain('BFL 7 kap')
})
it('DELETE removes a failed import', async () => {
// 1st DB hit: status lookup. 2nd DB hit: the delete itself.
enqueue({ data: { status: 'failed' } })
enqueue({ data: null })
const response = await DELETE(
createMockRequest('/api/import/sie/import-1', { method: 'DELETE' }),
routeParams(),
)
const { status, body } = await parseJsonResponse<{ success: boolean }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
})
it('GET returns the import record', async () => {
enqueue({ data: { id: 'import-1', status: 'pending' } })
const response = await GET(
createMockRequest('/api/import/sie/import-1'),
routeParams(),
)
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(response)
expect(status).toBe(200)
expect(body.data.id).toBe('import-1')
})
})
@@ -0,0 +1,118 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
// The route delegates everything to replaceSIEImport (which itself runs the
// replace_sie_import RPC on the service client). The route's own contract is
// what these tests pin: auth, the 403 mapping of the RPC's authorization
// raise, the 400 fallback, and the success envelope.
const replaceSIEImportMock = vi.fn()
vi.mock('@/lib/import/sie-import', () => ({
replaceSIEImport: (...args: unknown[]) => replaceSIEImportMock(...args),
}))
import { POST } from '../route'
import { NextResponse } from 'next/server'
const mockUser = { id: 'user-1', email: '[email protected]' }
function makeReq() {
return new Request('http://localhost/api/import/sie/import-1/replace', { method: 'POST' })
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
})
describe('POST /api/import/sie/[id]/replace', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeReq(), createMockRouteParams({ id: 'import-1' }))
expect(res.status).toBe(401)
expect(replaceSIEImportMock).not.toHaveBeenCalled()
})
it('maps the RPC authorization raise (42501) to 403 SIE_REPLACE_FORBIDDEN', async () => {
// replaceSIEImport flattens the PostgREST error into a message string, so
// the route matches the raise text pinned by migration 20260727120000.
replaceSIEImportMock.mockResolvedValue({
success: false,
deletedEntries: 0,
error: 'Kunde inte ersätta import: Only company owners and admins can replace SIE imports',
})
const res = await POST(makeReq(), createMockRouteParams({ id: 'import-1' }))
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string }
}>(res)
expect(status).toBe(403)
expect(body.error.code).toBe('SIE_REPLACE_FORBIDDEN')
// Swedish user-facing message, not raw Postgres prose.
expect(body.error.message).toBe(
'Endast ägare eller administratörer kan ersätta en SIE-import.',
)
})
it('returns 400 SIE_REPLACE_FAILED with the reason for other failures', async () => {
replaceSIEImportMock.mockResolvedValue({
success: false,
deletedEntries: 0,
error: 'Kan inte ersätta import i ett låst eller stängt räkenskapsår. Öppna perioden först.',
})
const res = await POST(makeReq(), createMockRouteParams({ id: 'import-1' }))
const { status, body } = await parseJsonResponse<{
error: { code: string; details?: { reason?: string } }
}>(res)
expect(status).toBe(400)
expect(body.error.code).toBe('SIE_REPLACE_FAILED')
expect(body.error.details?.reason).toContain('låst eller stängt')
})
it('passes the authorising user through and returns the deleted count', async () => {
replaceSIEImportMock.mockResolvedValue({ success: true, deletedEntries: 42 })
const res = await POST(makeReq(), createMockRouteParams({ id: 'import-1' }))
const { status, body } = await parseJsonResponse<{
success: boolean
deletedEntries: number
}>(res)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.deletedEntries).toBe(42)
expect(replaceSIEImportMock).toHaveBeenCalledWith(
mockSupabase,
'company-1',
'import-1',
'user-1',
)
})
})

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