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,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 })
}
})