docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,84 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { contentDisposition } from '@/lib/api/content-disposition'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import { getAttachmentRow } from '@/lib/reconciliation/attachments-store'
|
||||
import { downloadUnderlag, ReconciliationAttachmentError, removeUnderlag } from '@/lib/reconciliation/attachments'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
const UUID = z.string().uuid()
|
||||
|
||||
/**
|
||||
* GET /api/reconciliation/accounts/{accountKey}/attachments/{attachmentId}
|
||||
* streams the file inline (same shape as /api/documents/{id}/inline:
|
||||
* the caller's client authorizes the row, the service role reads the
|
||||
* non-public bucket).
|
||||
* DELETE /api/reconciliation/accounts/{accountKey}/attachments/{attachmentId}
|
||||
* stamps the attachment removed; body { reason? }. The file and the
|
||||
* row stay (BFL 7 kap.).
|
||||
*/
|
||||
export const GET = withRouteContext<{ params: Promise<{ accountKey: string; attachmentId: string }> }>(
|
||||
'reconciliation.accounts.attachments.file',
|
||||
async (_request, { supabase, companyId, log }, { params }) => {
|
||||
const { accountKey, attachmentId } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success || !UUID.safeParse(attachmentId).success) {
|
||||
return NextResponse.json({ error: 'Okänt underlag' }, { status: 404 })
|
||||
}
|
||||
const row = await getAttachmentRow(supabase, companyId, accountKey, attachmentId)
|
||||
if (!row) {
|
||||
return NextResponse.json({ error: 'Okänt underlag' }, { status: 404 })
|
||||
}
|
||||
const { blob, error } = await downloadUnderlag(createServiceClient(), row)
|
||||
if (error || !blob) {
|
||||
log.error('underlag download failed', error, { companyId, accountKey, attachmentId })
|
||||
return NextResponse.json({ error: 'Kunde inte hämta underlaget. Försök igen om en stund.' }, { status: 500 })
|
||||
}
|
||||
return new NextResponse(blob, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': row.mime_type,
|
||||
'Content-Disposition': contentDisposition('inline', row.file_name),
|
||||
'Cache-Control': 'private, no-store',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
const RemoveBodySchema = z.object({ reason: z.string().max(500).nullable().optional() })
|
||||
|
||||
export const DELETE = withRouteContext<{ params: Promise<{ accountKey: string; attachmentId: string }> }>(
|
||||
'reconciliation.accounts.attachments.remove',
|
||||
async (request, { supabase, user, companyId }, { params }) => {
|
||||
const { accountKey, attachmentId } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success || !UUID.safeParse(attachmentId).success) {
|
||||
return NextResponse.json({ error: 'Okänt underlag' }, { status: 404 })
|
||||
}
|
||||
let reason: string | null = null
|
||||
const raw = await request.text()
|
||||
if (raw.trim()) {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Ogiltig JSON' }, { status: 400 })
|
||||
}
|
||||
const body = RemoveBodySchema.safeParse(parsed)
|
||||
if (!body.success) return NextResponse.json({ error: 'Ogiltig body' }, { status: 400 })
|
||||
reason = body.data.reason ?? null
|
||||
}
|
||||
try {
|
||||
const attachment = await removeUnderlag(supabase, companyId, user.id, accountKey, attachmentId, { reason })
|
||||
if (!attachment) return NextResponse.json({ error: 'Okänt underlag' }, { status: 404 })
|
||||
return NextResponse.json({ data: { attachment } })
|
||||
} catch (err) {
|
||||
if (err instanceof ReconciliationAttachmentError) {
|
||||
return NextResponse.json({ error: getErrorMessage(err), code: err.code }, { status: err.code === 'ALREADY_REMOVED' ? 409 : 400 })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,82 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import {
|
||||
attachUnderlag,
|
||||
listAttachments,
|
||||
MAX_ATTACHMENT_NOTE_LENGTH,
|
||||
ReconciliationAttachmentError,
|
||||
} from '@/lib/reconciliation/attachments'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { ISO_DATE_RE } from '@/lib/invariants'
|
||||
|
||||
/**
|
||||
* GET /api/reconciliation/accounts/{accountKey}/attachments?through_date=
|
||||
* POST /api/reconciliation/accounts/{accountKey}/attachments (multipart)
|
||||
*
|
||||
* The underlag of one account's balansdag: the files the account was
|
||||
* reconciled against. GET lists them (?include_removed=1 adds the removed
|
||||
* ones with their stamp); POST attaches one file: fields `file`,
|
||||
* `through_date` and optional `note`. Policy in lib/reconciliation/attachments.ts.
|
||||
*/
|
||||
export const GET = withRouteContext<{ params: Promise<{ accountKey: string }> }>(
|
||||
'reconciliation.accounts.attachments.list',
|
||||
async (request, { supabase, companyId }, { params }) => {
|
||||
const { accountKey } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success) {
|
||||
return NextResponse.json({ error: 'Okänt konto' }, { status: 404 })
|
||||
}
|
||||
const { searchParams } = new URL(request.url)
|
||||
const throughDate = searchParams.get('through_date') ?? ''
|
||||
if (!ISO_DATE_RE.test(throughDate)) {
|
||||
return NextResponse.json({ error: 'through_date (ÅÅÅÅ-MM-DD) krävs' }, { status: 400 })
|
||||
}
|
||||
const attachments = await listAttachments(supabase, companyId, accountKey, throughDate, {
|
||||
includeRemoved: searchParams.get('include_removed') === '1',
|
||||
})
|
||||
return NextResponse.json({ data: { attachments } })
|
||||
},
|
||||
)
|
||||
|
||||
export const POST = withRouteContext<{ params: Promise<{ accountKey: string }> }>(
|
||||
'reconciliation.accounts.attachments.create',
|
||||
async (request, { supabase, user, companyId }, { params }) => {
|
||||
const { accountKey } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success) {
|
||||
return NextResponse.json({ error: 'Okänt konto' }, { status: 404 })
|
||||
}
|
||||
let form: FormData
|
||||
try {
|
||||
form = await request.formData()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Ogiltig uppladdning: förväntade multipart/form-data' }, { status: 400 })
|
||||
}
|
||||
const file = form.get('file')
|
||||
const throughDate = String(form.get('through_date') ?? '')
|
||||
const noteRaw = form.get('note')
|
||||
const note = typeof noteRaw === 'string' ? noteRaw : null
|
||||
if (!(file instanceof File)) {
|
||||
return NextResponse.json({ error: 'Ingen fil bifogad' }, { status: 400 })
|
||||
}
|
||||
if (!ISO_DATE_RE.test(throughDate)) {
|
||||
return NextResponse.json({ error: 'through_date (ÅÅÅÅ-MM-DD) krävs' }, { status: 400 })
|
||||
}
|
||||
if (note && note.length > MAX_ATTACHMENT_NOTE_LENGTH) {
|
||||
return NextResponse.json({ error: 'Noteringen är för lång' }, { status: 400 })
|
||||
}
|
||||
try {
|
||||
const attachment = await attachUnderlag(supabase, companyId, user.id, accountKey, {
|
||||
through_date: throughDate,
|
||||
note,
|
||||
file: { name: file.name, type: file.type, size: file.size, buffer: await file.arrayBuffer() },
|
||||
})
|
||||
return NextResponse.json({ data: { attachment } }, { status: 201 })
|
||||
} catch (err) {
|
||||
if (err instanceof ReconciliationAttachmentError) {
|
||||
return NextResponse.json({ error: getErrorMessage(err), code: err.code }, { status: 400 })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,52 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import { setItemIgnored } from '@/lib/reconciliation/actions'
|
||||
import { SkattekontoLinkError } from '@/lib/skatteverket/skattekonto-link'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
const IgnoreBodySchema = z.object({ ignored: z.boolean().optional() })
|
||||
|
||||
/**
|
||||
* POST /api/reconciliation/accounts/{accountKey}/items/{itemId}/ignore
|
||||
*
|
||||
* The page's "Ignorera" / "Återställ" on one outside row. Body
|
||||
* { ignored: boolean } (default true).
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ accountKey: string; itemId: string }> }>(
|
||||
'reconciliation.accounts.items.ignore',
|
||||
async (request, { supabase, companyId }, { params }) => {
|
||||
const { accountKey, itemId } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success || !z.string().uuid().safeParse(itemId).success) {
|
||||
return NextResponse.json({ error: 'Okänd rad' }, { status: 404 })
|
||||
}
|
||||
// Empty body = ignore; `{ ignored: false }` restores.
|
||||
let body: unknown = {}
|
||||
try {
|
||||
const text = await request.text()
|
||||
body = text ? JSON.parse(text) : {}
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Ogiltig JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = IgnoreBodySchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig body' }, { status: 400 })
|
||||
}
|
||||
const ignored = parsed.data.ignored ?? true
|
||||
try {
|
||||
const result = await setItemIgnored(supabase, companyId, accountKey, itemId, ignored)
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
if (err instanceof SkattekontoLinkError) {
|
||||
const status = err.code === 'TRANSACTION_NOT_FOUND' ? 404 : 400
|
||||
return NextResponse.json({ error: getErrorMessage(err), code: err.code }, { status })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,48 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { AccountKeySchema, ReconciliationItemBucketSchema } from '@/lib/reconciliation/schemas'
|
||||
import { listAccountItems, MAX_ITEMS_LIMIT } from '@/lib/reconciliation/items'
|
||||
import { ISO_DATE_RE } from '@/lib/invariants'
|
||||
|
||||
const DATE = ISO_DATE_RE
|
||||
|
||||
/**
|
||||
* GET /api/reconciliation/accounts/{accountKey}/items
|
||||
*
|
||||
* The rows behind one account's bridge, bucketed and paginated
|
||||
* (?bucket, ?date_from, ?date_to, ?limit, ?offset).
|
||||
*/
|
||||
export const GET = withRouteContext<{ params: Promise<{ accountKey: string }> }>(
|
||||
'reconciliation.accounts.items',
|
||||
async (request, { supabase, companyId }, { params }) => {
|
||||
const { accountKey } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success) {
|
||||
return NextResponse.json({ error: 'Okänt konto' }, { status: 404 })
|
||||
}
|
||||
const { searchParams } = new URL(request.url)
|
||||
const bucketRaw = searchParams.get('bucket')
|
||||
const bucket = bucketRaw ? ReconciliationItemBucketSchema.safeParse(bucketRaw) : null
|
||||
if (bucket && !bucket.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig bucket' }, { status: 400 })
|
||||
}
|
||||
const dateFrom = searchParams.get('date_from') || null
|
||||
const dateTo = searchParams.get('date_to') || null
|
||||
if ((dateFrom && !DATE.test(dateFrom)) || (dateTo && !DATE.test(dateTo))) {
|
||||
return NextResponse.json({ error: 'Ogiltigt datum' }, { status: 400 })
|
||||
}
|
||||
const limit = Math.min(Number(searchParams.get('limit') ?? 50) || 50, MAX_ITEMS_LIMIT)
|
||||
const offset = Math.max(0, Number(searchParams.get('offset') ?? 0) || 0)
|
||||
|
||||
const result = await listAccountItems(supabase, companyId, accountKey, {
|
||||
bucket: bucket?.success ? bucket.data : undefined,
|
||||
windowFrom: dateFrom,
|
||||
windowTo: dateTo,
|
||||
limit,
|
||||
offset,
|
||||
})
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ data: result })
|
||||
},
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import { unmatchLink } from '@/lib/reconciliation/actions'
|
||||
import { SkattekontoLinkError } from '@/lib/skatteverket/skattekonto-link'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
/**
|
||||
* DELETE /api/reconciliation/accounts/{accountKey}/links/{linkId}
|
||||
*
|
||||
* The page's "Koppla bort": clears the link on one outside row (linkId = the
|
||||
* row id). The verifikat is untouched.
|
||||
*/
|
||||
export const DELETE = withRouteContext<{ params: Promise<{ accountKey: string; linkId: string }> }>(
|
||||
'reconciliation.accounts.links.delete',
|
||||
async (_request, { supabase, user, companyId }, { params }) => {
|
||||
const { accountKey, linkId } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success || !z.string().uuid().safeParse(linkId).success) {
|
||||
return NextResponse.json({ error: 'Okänd koppling' }, { status: 404 })
|
||||
}
|
||||
try {
|
||||
const result = await unmatchLink(supabase, companyId, user.id, accountKey, linkId)
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
if (err instanceof SkattekontoLinkError) {
|
||||
const status = err.code === 'TRANSACTION_NOT_FOUND' ? 404 : 400
|
||||
return NextResponse.json({ error: getErrorMessage(err), code: err.code }, { status })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,48 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import {
|
||||
AccountKeySchema,
|
||||
reconciliationLinksBodyFields,
|
||||
reconciliationLinksBodyRefinement,
|
||||
} from '@/lib/reconciliation/schemas'
|
||||
import { matchPairs } from '@/lib/reconciliation/actions'
|
||||
|
||||
const ReconciliationLinksBodySchema = z
|
||||
.object({
|
||||
...reconciliationLinksBodyFields,
|
||||
dry_run: z.boolean().optional(),
|
||||
})
|
||||
.refine(...reconciliationLinksBodyRefinement)
|
||||
|
||||
/**
|
||||
* POST /api/reconciliation/accounts/{accountKey}/links
|
||||
*
|
||||
* The page's "Koppla" and "Koppla N föreslagna": link outside rows to existing
|
||||
* verifikat (N:1), or one bank transaction to several verifikat (1:N, with
|
||||
* optional allocations). A human clicked, so this applies directly (dry_run:
|
||||
* true for the preview). Same service function as v1 and the MCP commit
|
||||
* executor.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ accountKey: string }> }>(
|
||||
'reconciliation.accounts.links.create',
|
||||
async (request, { supabase, user, companyId }, { params }) => {
|
||||
const { accountKey } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success) {
|
||||
return NextResponse.json({ error: 'Okänt konto' }, { status: 404 })
|
||||
}
|
||||
const validation = await validateBody(request, ReconciliationLinksBodySchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { dry_run, ...input } = validation.data
|
||||
|
||||
const result = await matchPairs(supabase, companyId, user.id, accountKey, input, {
|
||||
dryRun: dry_run === true,
|
||||
})
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ data: result })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,76 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import { bookResidualAndLink, ReconciliationResidualError } from '@/lib/reconciliation/residual'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { ISO_DATE_RE } from '@/lib/invariants'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
|
||||
// Booking a residual commits a verifikat; the engine emits journal_entry
|
||||
// events that extension handlers subscribe to.
|
||||
ensureInitialized()
|
||||
|
||||
const ResidualBodySchema = z.object({
|
||||
external_ids: z.array(z.string().uuid()).min(1).max(50),
|
||||
journal_entry_id: z.string().uuid(),
|
||||
kind: z.enum(['bank_fee', 'rounding', 'interest_income', 'interest_expense']),
|
||||
entry_date: z.string().regex(ISO_DATE_RE).optional(),
|
||||
description: z.string().max(200).optional(),
|
||||
dry_run: z.boolean().optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/reconciliation/accounts/{accountKey}/residual
|
||||
*
|
||||
* The worksheet's "bokför mellanskillnaden och koppla": books the remainder
|
||||
* of a selection (bank rows vs one verifikat) as a bank fee / interest /
|
||||
* rounding verifikat and links the selection. Bank accounts only.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ accountKey: string }> }>(
|
||||
'reconciliation.accounts.residual',
|
||||
async (request, { supabase, user, companyId }, { params }) => {
|
||||
const { accountKey } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success) {
|
||||
return NextResponse.json({ error: 'Okänt konto' }, { status: 404 })
|
||||
}
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Ogiltig JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = ResidualBodySchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig body: external_ids, journal_entry_id och kind krävs' }, { status: 400 })
|
||||
}
|
||||
try {
|
||||
const result = await bookResidualAndLink(
|
||||
supabase,
|
||||
companyId,
|
||||
user.id,
|
||||
accountKey,
|
||||
{
|
||||
external_ids: parsed.data.external_ids,
|
||||
journal_entry_id: parsed.data.journal_entry_id,
|
||||
kind: parsed.data.kind,
|
||||
entry_date: parsed.data.entry_date,
|
||||
description: parsed.data.description,
|
||||
},
|
||||
{ dryRun: parsed.data.dry_run === true },
|
||||
)
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
if (err instanceof ReconciliationResidualError) {
|
||||
const status =
|
||||
err.code === 'RESIDUAL_ROWS_NOT_FOUND' || err.code === 'RESIDUAL_ENTRY_NOT_FOUND' ? 404 : 400
|
||||
return NextResponse.json({ error: getErrorMessage(err), code: err.code }, { status })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import { getAccountStatus } from '@/lib/reconciliation/service'
|
||||
import { ISO_DATE_RE } from '@/lib/invariants'
|
||||
|
||||
const DATE = ISO_DATE_RE
|
||||
|
||||
/**
|
||||
* GET /api/reconciliation/accounts/{accountKey}
|
||||
*
|
||||
* The bridge for one account (plus, for the skattekonto, the item buckets the
|
||||
* page renders under it). Same service function as v1 and MCP.
|
||||
*/
|
||||
export const GET = withRouteContext<{ params: Promise<{ accountKey: string }> }>(
|
||||
'reconciliation.accounts.status',
|
||||
async (request, { supabase, companyId }, { params }) => {
|
||||
const { accountKey } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success) {
|
||||
return NextResponse.json({ error: 'Okänt konto' }, { status: 404 })
|
||||
}
|
||||
const { searchParams } = new URL(request.url)
|
||||
const dateFrom = searchParams.get('date_from') || null
|
||||
const dateTo = searchParams.get('date_to') || null
|
||||
if ((dateFrom && !DATE.test(dateFrom)) || (dateTo && !DATE.test(dateTo))) {
|
||||
return NextResponse.json({ error: 'Ogiltigt datum' }, { status: 400 })
|
||||
}
|
||||
const status = await getAccountStatus(supabase, companyId, accountKey, {
|
||||
windowFrom: dateFrom,
|
||||
windowTo: dateTo,
|
||||
})
|
||||
if (!status) {
|
||||
return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ data: status })
|
||||
},
|
||||
)
|
||||
@@ -1,51 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import { ReconciliationSignoffError, reopenSignoff } from '@/lib/reconciliation/signoff'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
const ReopenBodySchema = z.object({ reason: z.string().max(2000).nullable().optional() })
|
||||
|
||||
/**
|
||||
* POST /api/reconciliation/accounts/{accountKey}/signoff/{signoffId}/reopen
|
||||
*
|
||||
* The undo of a sign-off: stamps it reopened (the row stays as history).
|
||||
* Body { reason? }; an empty body is fine.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ accountKey: string; signoffId: string }> }>(
|
||||
'reconciliation.accounts.signoff.reopen',
|
||||
async (request, { supabase, user, companyId }, { params }) => {
|
||||
const { accountKey, signoffId } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success || !z.string().uuid().safeParse(signoffId).success) {
|
||||
return NextResponse.json({ error: 'Okänd signering' }, { status: 404 })
|
||||
}
|
||||
let body: unknown = {}
|
||||
try {
|
||||
const text = await request.text()
|
||||
body = text ? JSON.parse(text) : {}
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Ogiltig JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = ReopenBodySchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig body' }, { status: 400 })
|
||||
}
|
||||
try {
|
||||
const result = await reopenSignoff(supabase, companyId, user.id, accountKey, signoffId, {
|
||||
reason: parsed.data.reason ?? null,
|
||||
})
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ data: { signoff: result } })
|
||||
} catch (err) {
|
||||
if (err instanceof ReconciliationSignoffError) {
|
||||
const status = err.code === 'SIGNOFF_NOT_FOUND' ? 404 : err.code === 'SIGNOFF_RACE' ? 409 : 400
|
||||
return NextResponse.json({ error: getErrorMessage(err), code: err.code }, { status })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,101 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import { listSignoffs } from '@/lib/reconciliation/signoff-store'
|
||||
import { ReconciliationSignoffError, signOffAccount } from '@/lib/reconciliation/signoff'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { ISO_DATE_RE } from '@/lib/invariants'
|
||||
|
||||
const SignoffBodySchema = z.object({
|
||||
through_date: z.string().regex(ISO_DATE_RE),
|
||||
note: z.string().max(2000).nullable().optional(),
|
||||
force: z.boolean().optional(),
|
||||
/** Manual accounts without a system specification: the balance per the signer's underlag, ledger sign. */
|
||||
external_balance: z.number().finite().nullable().optional(),
|
||||
dry_run: z.boolean().optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* GET /api/reconciliation/accounts/{accountKey}/signoff
|
||||
*
|
||||
* Sign-off history for one account, newest first (?include_reopened=1 to
|
||||
* see reopened ones too, ?limit).
|
||||
*/
|
||||
export const GET = withRouteContext<{ params: Promise<{ accountKey: string }> }>(
|
||||
'reconciliation.accounts.signoff.list',
|
||||
async (request, { supabase, companyId }, { params }) => {
|
||||
const { accountKey } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success) {
|
||||
return NextResponse.json({ error: 'Okänt konto' }, { status: 404 })
|
||||
}
|
||||
const { searchParams } = new URL(request.url)
|
||||
const limit = Math.min(Number(searchParams.get('limit') ?? 50) || 50, 200)
|
||||
const includeReopened = searchParams.get('include_reopened') === '1'
|
||||
const signoffs = await listSignoffs(supabase, companyId, accountKey, { limit, includeReopened })
|
||||
return NextResponse.json({ data: { signoffs } })
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* POST /api/reconciliation/accounts/{accountKey}/signoff
|
||||
*
|
||||
* "Markera som avstämd t.o.m. <datum>". Body { through_date, note?, force?,
|
||||
* dry_run? }. Refused (400 + code, plus details.unexplained_difference on
|
||||
* NOT_RECONCILED) unless the account is reconciled through the date, or
|
||||
* force + note is given. The dialog sends dry_run first so what it shows is
|
||||
* exactly what the real call will judge.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ accountKey: string }> }>(
|
||||
'reconciliation.accounts.signoff.create',
|
||||
async (request, { supabase, user, companyId }, { params }) => {
|
||||
const { accountKey } = await params
|
||||
if (!AccountKeySchema.safeParse(accountKey).success) {
|
||||
return NextResponse.json({ error: 'Okänt konto' }, { status: 404 })
|
||||
}
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Ogiltig JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = SignoffBodySchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig body: through_date (ÅÅÅÅ-MM-DD) krävs' }, { status: 400 })
|
||||
}
|
||||
try {
|
||||
const result = await signOffAccount(
|
||||
supabase,
|
||||
companyId,
|
||||
user.id,
|
||||
accountKey,
|
||||
{
|
||||
through_date: parsed.data.through_date,
|
||||
note: parsed.data.note ?? null,
|
||||
force: parsed.data.force,
|
||||
external_balance: parsed.data.external_balance ?? null,
|
||||
},
|
||||
{ dryRun: parsed.data.dry_run === true },
|
||||
)
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Okänt konto för det här företaget' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
if (err instanceof ReconciliationSignoffError) {
|
||||
const status = err.code === 'SIGNOFF_NOT_FOUND' ? 404 : err.code === 'SIGNOFF_RACE' ? 409 : 400
|
||||
// The refusal text reaches the user as written (the codes are
|
||||
// registered with thrown_message_sv; before that the mapper fell
|
||||
// through to "Något gick fel. Försök igen."). details (the unexplained
|
||||
// amount on NOT_RECONCILED) lets the dialog name the difference when
|
||||
// it previews the sign-off with dry_run.
|
||||
return NextResponse.json(
|
||||
{ error: getErrorMessage(err), code: err.code, ...(err.details ? { details: err.details } : {}) },
|
||||
{ status },
|
||||
)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,188 +0,0 @@
|
||||
/**
|
||||
* Tests for the dashboard underlag routes (cookie session, withRouteContext):
|
||||
* GET/POST /api/reconciliation/accounts/{accountKey}/attachments and
|
||||
* GET/DELETE .../attachments/{attachmentId}. The policy layer is mocked; the wrapper is real.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, 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),
|
||||
}))
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const listMock = vi.fn()
|
||||
const attachMock = vi.fn()
|
||||
const removeMock = vi.fn()
|
||||
const downloadMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/attachments', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/reconciliation/attachments')>('@/lib/reconciliation/attachments')
|
||||
return {
|
||||
...actual,
|
||||
listAttachments: (...args: unknown[]) => listMock(...args),
|
||||
attachUnderlag: (...args: unknown[]) => attachMock(...args),
|
||||
removeUnderlag: (...args: unknown[]) => removeMock(...args),
|
||||
downloadUnderlag: (...args: unknown[]) => downloadMock(...args),
|
||||
}
|
||||
})
|
||||
const getRowMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/attachments-store', () => ({
|
||||
getAttachmentRow: (...args: unknown[]) => getRowMock(...args),
|
||||
}))
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: () => ({ storage: { from: () => ({}) } }),
|
||||
}))
|
||||
|
||||
import { ReconciliationAttachmentError } from '@/lib/reconciliation/attachments'
|
||||
import { GET as listGET, POST as attachPOST } from '../[accountKey]/attachments/route'
|
||||
import { GET as fileGET, DELETE as removeDELETE } from '../[accountKey]/attachments/[attachmentId]/route'
|
||||
|
||||
const ATTACHMENT_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const p = (obj: Record<string, string>) => ({ params: Promise.resolve(obj) }) as never
|
||||
const attachment = {
|
||||
id: ATTACHMENT_ID,
|
||||
account_key: 'manual:2350',
|
||||
through_date: '2026-12-31',
|
||||
file_name: 'kontoutdrag.pdf',
|
||||
mime_type: 'application/pdf',
|
||||
size_bytes: 10,
|
||||
sha256: 'ab'.repeat(32),
|
||||
note: null,
|
||||
uploaded_by: 'user-1',
|
||||
uploaded_at: '2027-01-10T08:00:00Z',
|
||||
removed_at: null,
|
||||
removed_by: null,
|
||||
removed_reason: null,
|
||||
}
|
||||
|
||||
describe('dashboard underlag routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
listMock.mockResolvedValue([attachment])
|
||||
attachMock.mockResolvedValue(attachment)
|
||||
removeMock.mockResolvedValue({ ...attachment, removed_at: '2027-01-11T08:00:00Z', removed_by: 'user-1' })
|
||||
})
|
||||
|
||||
it('401 without a session', async () => {
|
||||
requireAuthMock.mockResolvedValue({ error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) })
|
||||
const res = await listGET(createMockRequest('http://localhost/x?through_date=2026-12-31'), p({ accountKey: 'manual:2350' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('GET lists the files for the date, 400s without a date, 404s a bad key', async () => {
|
||||
const ok = await listGET(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/manual:2350/attachments?through_date=2026-12-31&include_removed=1'),
|
||||
p({ accountKey: 'manual:2350' }),
|
||||
)
|
||||
expect(ok.status).toBe(200)
|
||||
const { body } = await parseJsonResponse<{ data: { attachments: unknown[] } }>(ok)
|
||||
expect(body.data.attachments).toHaveLength(1)
|
||||
expect(listMock).toHaveBeenCalledWith(supabase, 'company-1', 'manual:2350', '2026-12-31', { includeRemoved: true })
|
||||
|
||||
const noDate = await listGET(createMockRequest('http://localhost/x'), p({ accountKey: 'manual:2350' }))
|
||||
expect(noDate.status).toBe(400)
|
||||
const badKey = await listGET(createMockRequest('http://localhost/x?through_date=2026-12-31'), p({ accountKey: '2350' }))
|
||||
expect(badKey.status).toBe(404)
|
||||
})
|
||||
|
||||
it('POST attaches the multipart file with its date and note, and maps policy refusals to 400 + code', async () => {
|
||||
const form = new FormData()
|
||||
form.set('file', new File([new Uint8Array([0x25, 0x50, 0x44, 0x46])], 'kontoutdrag.pdf', { type: 'application/pdf' }))
|
||||
form.set('through_date', '2026-12-31')
|
||||
form.set('note', 'Kontoutdrag december')
|
||||
const req = new Request('http://localhost/api/reconciliation/accounts/manual:2350/attachments', { method: 'POST', body: form })
|
||||
const res = await attachPOST(req as never, p({ accountKey: 'manual:2350' }))
|
||||
expect(res.status).toBe(201)
|
||||
expect(attachMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
'manual:2350',
|
||||
expect.objectContaining({
|
||||
through_date: '2026-12-31',
|
||||
note: 'Kontoutdrag december',
|
||||
file: expect.objectContaining({ name: 'kontoutdrag.pdf', type: 'application/pdf', size: 4 }),
|
||||
}),
|
||||
)
|
||||
|
||||
attachMock.mockRejectedValue(new ReconciliationAttachmentError('Filtypen stöds inte.', 'INVALID_FILE'))
|
||||
const form2 = new FormData()
|
||||
form2.set('file', new File(['x'], 'x.csv', { type: 'text/csv' }))
|
||||
form2.set('through_date', '2026-12-31')
|
||||
const refused = await attachPOST(new Request('http://localhost/x', { method: 'POST', body: form2 }) as never, p({ accountKey: 'manual:2350' }))
|
||||
expect(refused.status).toBe(400)
|
||||
expect((await parseJsonResponse<{ code: string }>(refused)).body.code).toBe('INVALID_FILE')
|
||||
})
|
||||
|
||||
it('POST 400s without a file or a date, and requires write permission', async () => {
|
||||
const noFile = new FormData()
|
||||
noFile.set('through_date', '2026-12-31')
|
||||
const res = await attachPOST(new Request('http://localhost/x', { method: 'POST', body: noFile }) as never, p({ accountKey: 'manual:2350' }))
|
||||
expect(res.status).toBe(400)
|
||||
|
||||
const noDate = new FormData()
|
||||
noDate.set('file', new File(['x'], 'x.pdf', { type: 'application/pdf' }))
|
||||
const res2 = await attachPOST(new Request('http://localhost/x', { method: 'POST', body: noDate }) as never, p({ accountKey: 'manual:2350' }))
|
||||
expect(res2.status).toBe(400)
|
||||
|
||||
requireWriteMock.mockResolvedValue({ ok: false, response: NextResponse.json({ error: 'Läsbehörighet' }, { status: 403 }) })
|
||||
const form = new FormData()
|
||||
form.set('file', new File(['x'], 'x.pdf', { type: 'application/pdf' }))
|
||||
form.set('through_date', '2026-12-31')
|
||||
const forbidden = await attachPOST(new Request('http://localhost/x', { method: 'POST', body: form }) as never, p({ accountKey: 'manual:2350' }))
|
||||
expect(forbidden.status).toBe(403)
|
||||
expect(attachMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('GET file streams the bytes inline after the row authorizes, 404s otherwise', async () => {
|
||||
getRowMock.mockResolvedValue({ ...attachment, storage_bucket: 'documents', storage_path: 'documents/company-1/reconciliation/x' })
|
||||
downloadMock.mockResolvedValue({ blob: new Blob(['%PDF'], { type: 'application/pdf' }), error: null })
|
||||
const res = await fileGET(createMockRequest('http://localhost/x'), p({ accountKey: 'manual:2350', attachmentId: ATTACHMENT_ID }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe('application/pdf')
|
||||
expect(res.headers.get('Content-Disposition')).toMatch(/^inline/)
|
||||
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
|
||||
|
||||
getRowMock.mockResolvedValue(null)
|
||||
const missing = await fileGET(createMockRequest('http://localhost/x'), p({ accountKey: 'manual:2350', attachmentId: ATTACHMENT_ID }))
|
||||
expect(missing.status).toBe(404)
|
||||
const badId = await fileGET(createMockRequest('http://localhost/x'), p({ accountKey: 'manual:2350', attachmentId: 'nope' }))
|
||||
expect(badId.status).toBe(404)
|
||||
})
|
||||
|
||||
it('DELETE stamps removal with an optional reason, 409s an already removed file, 404s unknown', async () => {
|
||||
const res = await removeDELETE(
|
||||
createMockRequest('http://localhost/x', { method: 'DELETE', body: { reason: 'fel fil' } }),
|
||||
p({ accountKey: 'manual:2350', attachmentId: ATTACHMENT_ID }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(removeMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', 'manual:2350', ATTACHMENT_ID, { reason: 'fel fil' })
|
||||
|
||||
const empty = await removeDELETE(new Request('http://localhost/x', { method: 'DELETE' }) as never, p({ accountKey: 'manual:2350', attachmentId: ATTACHMENT_ID }))
|
||||
expect(empty.status).toBe(200)
|
||||
expect(removeMock).toHaveBeenLastCalledWith(supabase, 'company-1', 'user-1', 'manual:2350', ATTACHMENT_ID, { reason: null })
|
||||
|
||||
removeMock.mockRejectedValue(new ReconciliationAttachmentError('Underlaget är redan borttaget.', 'ALREADY_REMOVED'))
|
||||
const gone = await removeDELETE(new Request('http://localhost/x', { method: 'DELETE' }) as never, p({ accountKey: 'manual:2350', attachmentId: ATTACHMENT_ID }))
|
||||
expect(gone.status).toBe(409)
|
||||
|
||||
removeMock.mockResolvedValue(null)
|
||||
const unknown = await removeDELETE(new Request('http://localhost/x', { method: 'DELETE' }) as never, p({ accountKey: 'manual:2350', attachmentId: ATTACHMENT_ID }))
|
||||
expect(unknown.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -1,98 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/reconciliation/accounts/{accountKey}/residual (cookie
|
||||
* session, withRouteContext). The residual engine is mocked; the wrapper is real.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, 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),
|
||||
}))
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const residualMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/residual', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/reconciliation/residual')>('@/lib/reconciliation/residual')
|
||||
return { ...actual, bookResidualAndLink: (...args: unknown[]) => residualMock(...args) }
|
||||
})
|
||||
|
||||
import { ReconciliationResidualError } from '@/lib/reconciliation/residual'
|
||||
import { POST } from '../[accountKey]/residual/route'
|
||||
|
||||
const CASH = '11111111-1111-4111-8111-111111111111'
|
||||
const KEY = `bank:${CASH}`
|
||||
const T1 = '22222222-2222-4222-8222-222222222222'
|
||||
const E1 = '44444444-4444-4444-8444-444444444444'
|
||||
const URL = `http://localhost/api/reconciliation/accounts/${KEY}/residual`
|
||||
const p = (obj: Record<string, string>) => ({ params: Promise.resolve(obj) }) as never
|
||||
const body = { external_ids: [T1], journal_entry_id: E1, kind: 'bank_fee' }
|
||||
|
||||
describe('POST /api/reconciliation/accounts/{accountKey}/residual', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
residualMock.mockResolvedValue({ dry_run: false, residual_journal_entry_id: 'res-1', residual_amount: -10, applied: [], skipped: [] })
|
||||
})
|
||||
|
||||
it('401 without a session', async () => {
|
||||
requireAuthMock.mockResolvedValue({ error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) })
|
||||
const res = await POST(createMockRequest(URL, { method: 'POST', body }), p({ accountKey: KEY }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('400 on a body without kind, 404 on a malformed key', async () => {
|
||||
const bad = await POST(createMockRequest(URL, { method: 'POST', body: { external_ids: [T1], journal_entry_id: E1 } }), p({ accountKey: KEY }))
|
||||
expect(bad.status).toBe(400)
|
||||
const badKey = await POST(createMockRequest(URL, { method: 'POST', body }), p({ accountKey: '1930' }))
|
||||
expect(badKey.status).toBe(404)
|
||||
expect(residualMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('books and links, forwarding dry_run', async () => {
|
||||
const res = await POST(createMockRequest(URL, { method: 'POST', body: { ...body, dry_run: true } }), p({ accountKey: KEY }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(residualMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
KEY,
|
||||
{ external_ids: [T1], journal_entry_id: E1, kind: 'bank_fee', entry_date: undefined, description: undefined },
|
||||
{ dryRun: true },
|
||||
)
|
||||
const { body: out } = await parseJsonResponse<{ data: { residual_journal_entry_id: string } }>(res)
|
||||
expect(out.data.residual_journal_entry_id).toBe('res-1')
|
||||
})
|
||||
|
||||
it('maps refusals to 400 + code, missing rows to 404, unknown account to 404, and requires write', async () => {
|
||||
residualMock.mockRejectedValueOnce(new ReconciliationResidualError('för stort', 'RESIDUAL_TOO_LARGE'))
|
||||
const refused = await POST(createMockRequest(URL, { method: 'POST', body }), p({ accountKey: KEY }))
|
||||
expect(refused.status).toBe(400)
|
||||
expect((await parseJsonResponse<{ code: string }>(refused)).body.code).toBe('RESIDUAL_TOO_LARGE')
|
||||
|
||||
residualMock.mockRejectedValueOnce(new ReconciliationResidualError('saknas', 'RESIDUAL_ROWS_NOT_FOUND'))
|
||||
const missingRows = await POST(createMockRequest(URL, { method: 'POST', body }), p({ accountKey: KEY }))
|
||||
expect(missingRows.status).toBe(404)
|
||||
|
||||
residualMock.mockResolvedValueOnce(null)
|
||||
const unknown = await POST(createMockRequest(URL, { method: 'POST', body }), p({ accountKey: KEY }))
|
||||
expect(unknown.status).toBe(404)
|
||||
|
||||
requireWriteMock.mockResolvedValue({ ok: false, response: NextResponse.json({ error: 'Läsbehörighet' }, { status: 403 }) })
|
||||
const forbidden = await POST(createMockRequest(URL, { method: 'POST', body }), p({ accountKey: KEY }))
|
||||
expect(forbidden.status).toBe(403)
|
||||
})
|
||||
})
|
||||
@@ -1,185 +0,0 @@
|
||||
/**
|
||||
* Tests for the dashboard reconciliation routes (cookie session, withRouteContext):
|
||||
* GET /api/reconciliation/accounts, GET .../accounts/{accountKey},
|
||||
* GET .../accounts/{accountKey}/items, POST .../links, DELETE .../links/{linkId},
|
||||
* POST .../items/{itemId}/ignore. The service layer is mocked; the wrapper is real.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, 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),
|
||||
}))
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const listAccountsMock = vi.fn()
|
||||
const statusMock = vi.fn()
|
||||
const itemsMock = vi.fn()
|
||||
const matchMock = vi.fn()
|
||||
const unmatchMock = vi.fn()
|
||||
const ignoreMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/service', () => ({
|
||||
listReconciliationAccounts: (...args: unknown[]) => listAccountsMock(...args),
|
||||
getAccountStatus: (...args: unknown[]) => statusMock(...args),
|
||||
}))
|
||||
vi.mock('@/lib/reconciliation/items', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/reconciliation/items')>('@/lib/reconciliation/items')
|
||||
return { ...actual, listAccountItems: (...args: unknown[]) => itemsMock(...args) }
|
||||
})
|
||||
vi.mock('@/lib/reconciliation/actions', () => ({
|
||||
matchPairs: (...args: unknown[]) => matchMock(...args),
|
||||
unmatchLink: (...args: unknown[]) => unmatchMock(...args),
|
||||
setItemIgnored: (...args: unknown[]) => ignoreMock(...args),
|
||||
}))
|
||||
|
||||
import { GET as listGET } from '../route'
|
||||
import { GET as statusGET } from '../[accountKey]/route'
|
||||
import { GET as itemsGET } from '../[accountKey]/items/route'
|
||||
import { POST as linksPOST } from '../[accountKey]/links/route'
|
||||
import { DELETE as linkDELETE } from '../[accountKey]/links/[linkId]/route'
|
||||
import { POST as ignorePOST } from '../[accountKey]/items/[itemId]/ignore/route'
|
||||
|
||||
const ROW = '22222222-2222-4222-8222-222222222222'
|
||||
const ENTRY = '33333333-3333-4333-8333-333333333333'
|
||||
const ENTRY_2 = '44444444-4444-4444-8444-444444444444'
|
||||
const CASH = '55555555-5555-4555-8555-555555555555'
|
||||
// Dynamic-route params for the handlers under test; `never` keeps each
|
||||
// handler's own params type while letting one helper serve all of them.
|
||||
const p = (obj: Record<string, string>) => ({ params: Promise.resolve(obj) }) as never
|
||||
|
||||
describe('dashboard reconciliation routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
listAccountsMock.mockResolvedValue([{ account_key: 'skattekonto' }])
|
||||
statusMock.mockResolvedValue({ account_key: 'skattekonto', bridge: [] })
|
||||
itemsMock.mockResolvedValue({ items: [], count: 0, total_count: 0, has_more: false, older_unmatched_count: 0 })
|
||||
matchMock.mockResolvedValue({ dry_run: false, considered: 1, applied: [], skipped: [] })
|
||||
unmatchMock.mockResolvedValue({ external_id: ROW, previous_journal_entry_id: ENTRY })
|
||||
ignoreMock.mockResolvedValue({ external_id: ROW, is_ignored: true })
|
||||
})
|
||||
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await listGET(createMockRequest('/api/reconciliation/accounts'), { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('lists accounts, forwarding the window and with_status', async () => {
|
||||
const res = await listGET(
|
||||
createMockRequest('/api/reconciliation/accounts?date_from=2026-01-01&date_to=2026-08-20&with_status=false'),
|
||||
{ params: Promise.resolve({}) },
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const { body } = await parseJsonResponse<{ data: { accounts: unknown[] } }>(res)
|
||||
expect(body.data.accounts).toHaveLength(1)
|
||||
expect(listAccountsMock).toHaveBeenCalledWith(supabase, 'company-1', {
|
||||
windowFrom: '2026-01-01',
|
||||
windowTo: '2026-08-20',
|
||||
withStatus: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('status: 404 on an invalid key, 404 when the service finds nothing, 200 otherwise', async () => {
|
||||
expect((await statusGET(createMockRequest('/api/reconciliation/accounts/1930'), p({ accountKey: '1930' }))).status).toBe(404)
|
||||
statusMock.mockResolvedValueOnce(null)
|
||||
expect((await statusGET(createMockRequest('/api/reconciliation/accounts/skattekonto'), p({ accountKey: 'skattekonto' }))).status).toBe(404)
|
||||
const res = await statusGET(createMockRequest('/api/reconciliation/accounts/skattekonto?date_from=2026-07-01'), p({ accountKey: 'skattekonto' }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(statusMock).toHaveBeenLastCalledWith(supabase, 'company-1', 'skattekonto', { windowFrom: '2026-07-01', windowTo: null })
|
||||
})
|
||||
|
||||
it('items: validates the bucket and forwards paging', async () => {
|
||||
expect((await itemsGET(createMockRequest('/api/reconciliation/accounts/skattekonto/items?bucket=x'), p({ accountKey: 'skattekonto' }))).status).toBe(400)
|
||||
const res = await itemsGET(createMockRequest('/api/reconciliation/accounts/skattekonto/items?bucket=proposed&limit=10&offset=20'), p({ accountKey: 'skattekonto' }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(itemsMock).toHaveBeenCalledWith(supabase, 'company-1', 'skattekonto', expect.objectContaining({ bucket: 'proposed', limit: 10, offset: 20 }))
|
||||
})
|
||||
|
||||
it('links: requires write, validates the body, forwards dry_run', async () => {
|
||||
requireWriteMock.mockResolvedValueOnce({ ok: false, response: NextResponse.json({ error: 'Read only' }, { status: 403 }) })
|
||||
const forbidden = await linksPOST(
|
||||
createMockRequest('/api/reconciliation/accounts/skattekonto/links', { method: 'POST', body: { use_proposals: true } }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(forbidden.status).toBe(403)
|
||||
|
||||
const invalid = await linksPOST(
|
||||
createMockRequest('/api/reconciliation/accounts/skattekonto/links', { method: 'POST', body: { pairs: [] } }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(invalid.status).toBe(400)
|
||||
|
||||
const res = await linksPOST(
|
||||
createMockRequest('/api/reconciliation/accounts/skattekonto/links', {
|
||||
method: 'POST',
|
||||
body: { pairs: [{ external_ids: [ROW], journal_entry_ids: [ENTRY] }], dry_run: true },
|
||||
}),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(matchMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
'skattekonto',
|
||||
{ pairs: [{ external_ids: [ROW], journal_entry_ids: [ENTRY] }] },
|
||||
{ dryRun: true },
|
||||
)
|
||||
})
|
||||
|
||||
it('links: forwards a bank 1:N pair with allocations, and rejects a one-element allocations array (#1553)', async () => {
|
||||
matchMock.mockResolvedValue({ dry_run: false, considered: 1, applied: [], skipped: [] })
|
||||
const pair = {
|
||||
external_ids: [ROW],
|
||||
journal_entry_ids: [ENTRY, ENTRY_2],
|
||||
allocations: [
|
||||
{ journal_entry_id: ENTRY, amount: -500 },
|
||||
{ journal_entry_id: ENTRY_2, amount: -300 },
|
||||
],
|
||||
}
|
||||
const res = await linksPOST(
|
||||
createMockRequest(`/api/reconciliation/accounts/bank:${CASH}/links`, { method: 'POST', body: { pairs: [pair] } }),
|
||||
p({ accountKey: `bank:${CASH}` }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(matchMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', `bank:${CASH}`, { pairs: [pair] }, { dryRun: false })
|
||||
|
||||
const invalid = await linksPOST(
|
||||
createMockRequest(`/api/reconciliation/accounts/bank:${CASH}/links`, {
|
||||
method: 'POST',
|
||||
body: { pairs: [{ ...pair, allocations: [{ journal_entry_id: ENTRY, amount: -800 }] }] },
|
||||
}),
|
||||
p({ accountKey: `bank:${CASH}` }),
|
||||
)
|
||||
expect(invalid.status).toBe(400)
|
||||
})
|
||||
|
||||
it('unlink and ignore call the service with the ids', async () => {
|
||||
const del = await linkDELETE(createMockRequest(`/api/reconciliation/accounts/skattekonto/links/${ROW}`, { method: 'DELETE' }), p({ accountKey: 'skattekonto', linkId: ROW }))
|
||||
expect(del.status).toBe(200)
|
||||
expect(unmatchMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', 'skattekonto', ROW)
|
||||
|
||||
const ign = await ignorePOST(createMockRequest(`/api/reconciliation/accounts/skattekonto/items/${ROW}/ignore`, { method: 'POST', body: { ignored: false } }), p({ accountKey: 'skattekonto', itemId: ROW }))
|
||||
expect(ign.status).toBe(200)
|
||||
expect(ignoreMock).toHaveBeenCalledWith(supabase, 'company-1', 'skattekonto', ROW, false)
|
||||
})
|
||||
})
|
||||
@@ -1,206 +0,0 @@
|
||||
/**
|
||||
* Tests for the dashboard sign-off routes (cookie session, withRouteContext):
|
||||
* GET/POST /api/reconciliation/accounts/{accountKey}/signoff and
|
||||
* POST .../signoff/{signoffId}/reopen. The policy layer is mocked; the wrapper is real.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, 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),
|
||||
}))
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const signMock = vi.fn()
|
||||
const reopenMock = vi.fn()
|
||||
const listMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/signoff', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/reconciliation/signoff')>('@/lib/reconciliation/signoff')
|
||||
return {
|
||||
...actual,
|
||||
signOffAccount: (...args: unknown[]) => signMock(...args),
|
||||
reopenSignoff: (...args: unknown[]) => reopenMock(...args),
|
||||
}
|
||||
})
|
||||
vi.mock('@/lib/reconciliation/signoff-store', () => ({
|
||||
listSignoffs: (...args: unknown[]) => listMock(...args),
|
||||
}))
|
||||
|
||||
import { ReconciliationSignoffError } from '@/lib/reconciliation/signoff'
|
||||
import { GET as listGET, POST as signPOST } from '../[accountKey]/signoff/route'
|
||||
import { POST as reopenPOST } from '../[accountKey]/signoff/[signoffId]/reopen/route'
|
||||
|
||||
const SIGNOFF_ID = '77777777-7777-4777-8777-777777777777'
|
||||
const p = (obj: Record<string, string>) => ({ params: Promise.resolve(obj) }) as never
|
||||
|
||||
describe('dashboard sign-off routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
listMock.mockResolvedValue([{ id: SIGNOFF_ID, through_date: '2026-07-31' }])
|
||||
signMock.mockResolvedValue({ dry_run: false, signoff: { id: SIGNOFF_ID, through_date: '2026-07-31' } })
|
||||
reopenMock.mockResolvedValue({ id: SIGNOFF_ID, reopened_at: '2026-08-24T08:00:00Z' })
|
||||
})
|
||||
|
||||
it('401 without a session', async () => {
|
||||
requireAuthMock.mockResolvedValue({ error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) })
|
||||
const res = await listGET(createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff'), p({ accountKey: 'skattekonto' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('GET lists the history and passes include_reopened / limit through', async () => {
|
||||
const res = await listGET(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff?include_reopened=1&limit=5'),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const { body } = await parseJsonResponse<{ data: { signoffs: Array<{ id: string }> } }>(res)
|
||||
expect(body.data.signoffs[0].id).toBe(SIGNOFF_ID)
|
||||
expect(listMock).toHaveBeenCalledWith(supabase, 'company-1', 'skattekonto', { limit: 5, includeReopened: true })
|
||||
})
|
||||
|
||||
it('GET 404s a malformed account key', async () => {
|
||||
const res = await listGET(createMockRequest('http://localhost/api/reconciliation/accounts/1630/signoff'), p({ accountKey: '1630' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('POST signs off with the validated body and forwards dry_run', async () => {
|
||||
const res = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff', { method: 'POST', body: {
|
||||
through_date: '2026-07-31',
|
||||
note: 'ok',
|
||||
dry_run: true,
|
||||
} }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(signMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
'skattekonto',
|
||||
{ through_date: '2026-07-31', note: 'ok', force: undefined, external_balance: null },
|
||||
{ dryRun: true },
|
||||
)
|
||||
})
|
||||
|
||||
it('POST forwards a stated external_balance for a manual account and 400s a non-numeric one', async () => {
|
||||
const res = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/manual:2350/signoff', { method: 'POST', body: {
|
||||
through_date: '2026-07-31',
|
||||
external_balance: -250000,
|
||||
note: 'Enligt engagemangsbesked',
|
||||
} }),
|
||||
p({ accountKey: 'manual:2350' }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(signMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
'manual:2350',
|
||||
{ through_date: '2026-07-31', note: 'Enligt engagemangsbesked', force: undefined, external_balance: -250000 },
|
||||
{ dryRun: false },
|
||||
)
|
||||
const bad = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/manual:2350/signoff', { method: 'POST', body: {
|
||||
through_date: '2026-07-31',
|
||||
external_balance: '250 000',
|
||||
} }),
|
||||
p({ accountKey: 'manual:2350' }),
|
||||
)
|
||||
expect(bad.status).toBe(400)
|
||||
})
|
||||
|
||||
it('POST 400s a missing or malformed through_date', async () => {
|
||||
const res = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff', { method: 'POST', body: { through_date: '31/07/2026' } }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
expect(signMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST maps policy refusals to 400 + code, races to 409, and a null result to 404', async () => {
|
||||
signMock.mockRejectedValueOnce(
|
||||
new ReconciliationSignoffError('oförklarat', 'NOT_RECONCILED', { unexplained_difference: 53717 }),
|
||||
)
|
||||
const refused = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff', { method: 'POST', body: { through_date: '2026-07-31' } }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(refused.status).toBe(400)
|
||||
const refusedBody = (await parseJsonResponse<{ code: string; error: string; details?: unknown }>(refused)).body
|
||||
expect(refusedBody.code).toBe('NOT_RECONCILED')
|
||||
expect(refusedBody.error).toBe('oförklarat')
|
||||
// The dialog previews with dry_run and reads the amount from here.
|
||||
expect(refusedBody.details).toEqual({ unexplained_difference: 53717 })
|
||||
|
||||
signMock.mockRejectedValueOnce(new ReconciliationSignoffError('okänt', 'OUTSIDE_UNKNOWN'))
|
||||
const unknown = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff', { method: 'POST', body: { through_date: '2026-07-31' } }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect((await parseJsonResponse<{ details?: unknown }>(unknown)).body.details).toBeUndefined()
|
||||
|
||||
signMock.mockRejectedValueOnce(new ReconciliationSignoffError('race', 'SIGNOFF_RACE'))
|
||||
const raced = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff', { method: 'POST', body: { through_date: '2026-07-31' } }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(raced.status).toBe(409)
|
||||
|
||||
signMock.mockResolvedValueOnce(null)
|
||||
const missing = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff', { method: 'POST', body: { through_date: '2026-07-31' } }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(missing.status).toBe(404)
|
||||
})
|
||||
|
||||
it('POST requires write permission', async () => {
|
||||
requireWriteMock.mockResolvedValue({ ok: false, response: NextResponse.json({ error: 'Läsbehörighet' }, { status: 403 }) })
|
||||
const res = await signPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff', { method: 'POST', body: { through_date: '2026-07-31' } }),
|
||||
p({ accountKey: 'skattekonto' }),
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
expect(signMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reopen stamps the sign-off, accepts an empty body, and 404s a malformed id', async () => {
|
||||
const res = await reopenPOST(
|
||||
createMockRequest(`http://localhost/api/reconciliation/accounts/skattekonto/signoff/${SIGNOFF_ID}/reopen`, { method: 'POST' }),
|
||||
p({ accountKey: 'skattekonto', signoffId: SIGNOFF_ID }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(reopenMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', 'skattekonto', SIGNOFF_ID, { reason: null })
|
||||
|
||||
const bad = await reopenPOST(
|
||||
createMockRequest('http://localhost/api/reconciliation/accounts/skattekonto/signoff/not-a-uuid/reopen', { method: 'POST' }),
|
||||
p({ accountKey: 'skattekonto', signoffId: 'not-a-uuid' }),
|
||||
)
|
||||
expect(bad.status).toBe(404)
|
||||
|
||||
reopenMock.mockRejectedValueOnce(new ReconciliationSignoffError('redan', 'ALREADY_REOPENED'))
|
||||
const already = await reopenPOST(
|
||||
createMockRequest(`http://localhost/api/reconciliation/accounts/skattekonto/signoff/${SIGNOFF_ID}/reopen`, { method: 'POST', body: { reason: 'x' } }),
|
||||
p({ accountKey: 'skattekonto', signoffId: SIGNOFF_ID }),
|
||||
)
|
||||
expect(already.status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -1,32 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { listReconciliationAccounts } from '@/lib/reconciliation/service'
|
||||
import { ISO_DATE_RE } from '@/lib/invariants'
|
||||
|
||||
const DATE = ISO_DATE_RE
|
||||
|
||||
/**
|
||||
* GET /api/reconciliation/accounts
|
||||
*
|
||||
* The side list of the Avstämning page: every account with an outside truth
|
||||
* and its status. Same service function the v1 API and the MCP resource use.
|
||||
* ?date_from / ?date_to scope the bank bridge; ?with_status=false skips the
|
||||
* per-account status reads when only the list is needed.
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'reconciliation.accounts.list',
|
||||
async (request, { supabase, companyId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const dateFrom = searchParams.get('date_from') || undefined
|
||||
const dateTo = searchParams.get('date_to') || undefined
|
||||
if ((dateFrom && !DATE.test(dateFrom)) || (dateTo && !DATE.test(dateTo))) {
|
||||
return NextResponse.json({ error: 'Ogiltigt datum' }, { status: 400 })
|
||||
}
|
||||
const accounts = await listReconciliationAccounts(supabase, companyId, {
|
||||
windowFrom: dateFrom,
|
||||
windowTo: dateTo,
|
||||
withStatus: searchParams.get('with_status') !== 'false',
|
||||
})
|
||||
return NextResponse.json({ data: { accounts } })
|
||||
},
|
||||
)
|
||||
@@ -1,151 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/reconciliation/bank/confirm-suggestions.
|
||||
*
|
||||
* Exercises the route through the real withRouteContext wrapper, mocking only
|
||||
* its auth/company/write dependencies plus the suggestions service. Covers:
|
||||
* 401, 403 viewer, validation (400), and both actions' happy paths.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, 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),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const confirmMock = vi.fn()
|
||||
const rejectMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/suggestions', () => ({
|
||||
confirmJournalEntrySuggestions: (...args: unknown[]) => confirmMock(...args),
|
||||
rejectJournalEntrySuggestions: (...args: unknown[]) => rejectMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const emptyParams = { params: Promise.resolve({}) }
|
||||
const TX_1 = '11111111-1111-4111-8111-111111111111'
|
||||
const TX_2 = '22222222-2222-4222-8222-222222222222'
|
||||
|
||||
describe('POST /api/reconciliation/bank/confirm-suggestions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
confirmMock.mockResolvedValue({ confirmed: [TX_1], rejected: [], skipped: [] })
|
||||
rejectMock.mockResolvedValue({ confirmed: [], rejected: [TX_1], skipped: [] })
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1], action: 'confirm' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(401)
|
||||
expect(confirmMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1], action: 'confirm' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(403)
|
||||
expect(confirmMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an empty transaction_ids array with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [], action: 'confirm' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(confirmMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an unknown action with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1], action: 'maybe' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('confirms suggestions and reports skipped pairs in snake_case', async () => {
|
||||
confirmMock.mockResolvedValue({
|
||||
confirmed: [TX_1],
|
||||
rejected: [],
|
||||
skipped: [{ transactionId: TX_2, reason: 'voucher_consumed' }],
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1, TX_2], action: 'confirm' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: {
|
||||
confirmed: string[]
|
||||
skipped: Array<{ transaction_id: string; reason: string }>
|
||||
}
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.confirmed).toEqual([TX_1])
|
||||
expect(body.data.skipped).toEqual([
|
||||
{ transaction_id: TX_2, reason: 'voucher_consumed', message: undefined },
|
||||
])
|
||||
expect(confirmMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', [TX_1, TX_2])
|
||||
expect(rejectMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('routes action=reject to the reject service', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/confirm-suggestions', {
|
||||
method: 'POST',
|
||||
body: { transaction_ids: [TX_1], action: 'reject' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ data: { rejected: string[] } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.rejected).toEqual([TX_1])
|
||||
expect(rejectMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', [TX_1])
|
||||
expect(confirmMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,53 +0,0 @@
|
||||
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 { ConfirmJeSuggestionsSchema } from '@/lib/api/schemas'
|
||||
import {
|
||||
confirmJournalEntrySuggestions,
|
||||
rejectJournalEntrySuggestions,
|
||||
} from '@/lib/reconciliation/suggestions'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
// A full 500-item batch runs sequentially with several queries per pair
|
||||
// (revalidation is the point), which can exceed the platform's default
|
||||
// function budget. Same 5-minute allowance as the bank-file and SIE imports.
|
||||
export const maxDuration = 300
|
||||
|
||||
/**
|
||||
* POST /api/reconciliation/bank/confirm-suggestions
|
||||
*
|
||||
* Bulk confirm (or reject) journal-entry match suggestions written by the
|
||||
* SIE reconciliation sweep. Confirming links each transaction to its suggested
|
||||
* verifikat via the ordinary manual-link path with full server-side
|
||||
* revalidation per pair; pairs that went stale between suggestion and click
|
||||
* (entry reversed, verifikat consumed by another row, row booked elsewhere)
|
||||
* are skipped and reported rather than failing the batch.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'reconciliation.bank.confirm_suggestions',
|
||||
async (request, { supabase, user, companyId }) => {
|
||||
const validation = await validateBody(request, ConfirmJeSuggestionsSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { transaction_ids, action } = validation.data
|
||||
|
||||
const result =
|
||||
action === 'confirm'
|
||||
? await confirmJournalEntrySuggestions(supabase, companyId, user.id, transaction_ids)
|
||||
: await rejectJournalEntrySuggestions(supabase, companyId, user.id, transaction_ids)
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
confirmed: result.confirmed,
|
||||
rejected: result.rejected,
|
||||
skipped: result.skipped.map((s) => ({
|
||||
transaction_id: s.transactionId,
|
||||
reason: s.reason,
|
||||
message: s.message,
|
||||
})),
|
||||
},
|
||||
})
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,233 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/reconciliation/bank/link.
|
||||
*
|
||||
* Exercises the route through the real withRouteContext wrapper, mocking only
|
||||
* its auth/company/write dependencies plus the manualLink service. Covers:
|
||||
* 401, 403 viewer, validation (400), service failure (400), and happy path.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, 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),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const manualLinkMock = vi.fn()
|
||||
const linkToVouchersMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/bank-reconciliation', () => ({
|
||||
manualLink: (...args: unknown[]) => manualLinkMock(...args),
|
||||
linkTransactionToVouchers: (...args: unknown[]) => linkToVouchersMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const emptyParams = { params: Promise.resolve({}) }
|
||||
const TX_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const JE_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const JE_ID_2 = '33333333-3333-4333-8333-333333333333'
|
||||
|
||||
describe('POST /api/reconciliation/bank/link', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
manualLinkMock.mockResolvedValue({ success: true })
|
||||
linkToVouchersMock.mockResolvedValue({ success: true, allocations: [] })
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID, journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID, journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('rejects a non-uuid transaction_id with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: 'not-a-uuid', journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(manualLinkMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces a manualLink failure as 400 with the service error', async () => {
|
||||
manualLinkMock.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Transaktionen är redan kopplad till en verifikation.',
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID, journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Transaktionen är redan kopplad till en verifikation.')
|
||||
})
|
||||
|
||||
it('links the transaction, defaulting the account to 1930', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID, journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ data: { success: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.success).toBe(true)
|
||||
expect(manualLinkMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
TX_ID,
|
||||
JE_ID,
|
||||
'user-1',
|
||||
'1930',
|
||||
)
|
||||
})
|
||||
|
||||
it('splits the transaction over several verifikat when allocations are given instead of journal_entry_id (1:N, #1553)', async () => {
|
||||
linkToVouchersMock.mockResolvedValue({
|
||||
success: true,
|
||||
allocations: [
|
||||
{ journal_entry_id: JE_ID, amount: -500 },
|
||||
{ journal_entry_id: JE_ID_2, amount: -300 },
|
||||
],
|
||||
})
|
||||
const request = createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
transaction_id: TX_ID,
|
||||
account_number: '1940',
|
||||
allocations: [
|
||||
{ journal_entry_id: JE_ID, amount: -500 },
|
||||
{ journal_entry_id: JE_ID_2, amount: -300 },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ data: { success: boolean; allocations: unknown[] } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.success).toBe(true)
|
||||
expect(body.data.allocations).toHaveLength(2)
|
||||
expect(linkToVouchersMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
TX_ID,
|
||||
[
|
||||
{ journal_entry_id: JE_ID, amount: -500 },
|
||||
{ journal_entry_id: JE_ID_2, amount: -300 },
|
||||
],
|
||||
'user-1',
|
||||
'1940',
|
||||
)
|
||||
expect(manualLinkMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a body with both journal_entry_id and allocations, with neither, or with a single allocation (400)', async () => {
|
||||
const both = await POST(
|
||||
createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
transaction_id: TX_ID,
|
||||
journal_entry_id: JE_ID,
|
||||
allocations: [
|
||||
{ journal_entry_id: JE_ID, amount: -500 },
|
||||
{ journal_entry_id: JE_ID_2, amount: -300 },
|
||||
],
|
||||
},
|
||||
}),
|
||||
emptyParams,
|
||||
)
|
||||
expect(both.status).toBe(400)
|
||||
|
||||
const neither = await POST(
|
||||
createMockRequest('/api/reconciliation/bank/link', { method: 'POST', body: { transaction_id: TX_ID } }),
|
||||
emptyParams,
|
||||
)
|
||||
expect(neither.status).toBe(400)
|
||||
|
||||
const single = await POST(
|
||||
createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID, allocations: [{ journal_entry_id: JE_ID, amount: -800 }] },
|
||||
}),
|
||||
emptyParams,
|
||||
)
|
||||
expect(single.status).toBe(400)
|
||||
expect(manualLinkMock).not.toHaveBeenCalled()
|
||||
expect(linkToVouchersMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces a refused split as 400 with the service error', async () => {
|
||||
linkToVouchersMock.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Fördelningen (-700) stämmer inte med transaktionens belopp (-800).',
|
||||
})
|
||||
const response = await POST(
|
||||
createMockRequest('/api/reconciliation/bank/link', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
transaction_id: TX_ID,
|
||||
allocations: [
|
||||
{ journal_entry_id: JE_ID, amount: -400 },
|
||||
{ journal_entry_id: JE_ID_2, amount: -300 },
|
||||
],
|
||||
},
|
||||
}),
|
||||
emptyParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Fördelningen (-700) stämmer inte med transaktionens belopp (-800).')
|
||||
})
|
||||
})
|
||||
@@ -1,42 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { linkTransactionToVouchers, manualLink } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { BankLinkSchema } from '@/lib/api/schemas'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'reconciliation.bank.link',
|
||||
async (request, { supabase, user, companyId }) => {
|
||||
const validation = await validateBody(request, BankLinkSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { transaction_id, journal_entry_id, allocations, account_number } = validation.data
|
||||
|
||||
// One verifikat: the plain link. Several: the 1:N split (#1553), all or
|
||||
// nothing, slices summing to the transaction.
|
||||
const result = journal_entry_id
|
||||
? await manualLink(supabase, companyId, transaction_id, journal_entry_id, user.id, account_number ?? '1930')
|
||||
: await linkTransactionToVouchers(
|
||||
supabase,
|
||||
companyId,
|
||||
transaction_id,
|
||||
allocations ?? [],
|
||||
user.id,
|
||||
account_number ?? '1930',
|
||||
)
|
||||
|
||||
if (!result.success) {
|
||||
return NextResponse.json({ error: result.error }, { status: 400 })
|
||||
}
|
||||
|
||||
// A split echoes the slices as validated (defaults resolved); the plain
|
||||
// link has nothing to add.
|
||||
const resolvedAllocations = 'allocations' in result ? result.allocations : undefined
|
||||
return NextResponse.json({
|
||||
data: { success: true, ...(resolvedAllocations ? { allocations: resolvedAllocations } : {}) },
|
||||
})
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,119 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/reconciliation/bank/mark-opening-balance.
|
||||
*
|
||||
* 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, validation (400), the RPC error
|
||||
* translation to Swedish, and the happy path.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const emptyParams = { params: Promise.resolve({}) }
|
||||
const JE_ID = '33333333-3333-4333-8333-333333333333'
|
||||
|
||||
describe('POST /api/reconciliation/bank/mark-opening-balance', () => {
|
||||
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 request = createMockRequest('/api/reconciliation/bank/mark-opening-balance', {
|
||||
method: 'POST',
|
||||
body: { journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/mark-opening-balance', {
|
||||
method: 'POST',
|
||||
body: { journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('rejects a non-uuid journal_entry_id with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/mark-opening-balance', {
|
||||
method: 'POST',
|
||||
body: { journal_entry_id: 'nope' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('translates a locked-period RPC error to Swedish', async () => {
|
||||
enqueue({ error: { message: 'Cannot modify entries in a locked fiscal period' } })
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/mark-opening-balance', {
|
||||
method: 'POST',
|
||||
body: { journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Perioden är låst. Lås upp perioden innan du ändrar verifikationen.')
|
||||
})
|
||||
|
||||
it('marks the entry as opening balance via the RPC', async () => {
|
||||
enqueue({ data: { updated: true } })
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/mark-opening-balance', {
|
||||
method: 'POST',
|
||||
body: { journal_entry_id: JE_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ data: { updated: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.updated).toBe(true)
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('mark_entry_as_opening_balance', {
|
||||
p_company_id: 'company-1',
|
||||
p_entry_id: JE_ID,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,52 +0,0 @@
|
||||
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 { MarkOpeningBalanceSchema } from '@/lib/api/schemas'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
/**
|
||||
* Re-tag a posted manual/import voucher on a bank account as an opening balance
|
||||
* (source_type='opening_balance') so bank reconciliation stops counting it as a
|
||||
* phantom difference. Delegates to the mark_entry_as_opening_balance RPC, which
|
||||
* enforces owner/admin role, the manual/import precondition, a bank-line check,
|
||||
* and the period lock. We only translate its errors to Swedish here.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'reconciliation.bank.mark_opening_balance',
|
||||
async (request, { supabase, companyId }) => {
|
||||
const validation = await validateBody(request, MarkOpeningBalanceSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { journal_entry_id } = validation.data
|
||||
|
||||
const { data, error } = await supabase.rpc('mark_entry_as_opening_balance', {
|
||||
p_company_id: companyId,
|
||||
p_entry_id: journal_entry_id,
|
||||
})
|
||||
|
||||
if (error) {
|
||||
const raw = error.message || ''
|
||||
let message = 'Kunde inte markera verifikationen som ingående balans.'
|
||||
if (/owners and admins/i.test(raw)) {
|
||||
message = 'Endast ägare och administratörer kan markera en ingående balans.'
|
||||
} else if (/not found/i.test(raw)) {
|
||||
message = 'Verifikationen kunde inte hittas.'
|
||||
} else if (/manual\/import/i.test(raw)) {
|
||||
message = 'Bara manuellt eller importerat bokförda verifikationer kan markeras som ingående balans.'
|
||||
} else if (/posted entries/i.test(raw)) {
|
||||
message = 'Bara bokförda verifikationer kan markeras som ingående balans.'
|
||||
} else if (/bank\/cash account/i.test(raw)) {
|
||||
message = 'Verifikationen saknar rad på ett bankkonto (19xx) och kan inte vara en ingående balans.'
|
||||
} else if (/closed fiscal period/i.test(raw)) {
|
||||
message = 'Perioden är stängd. Öppna perioden innan du ändrar verifikationen.'
|
||||
} else if (/locked fiscal period/i.test(raw)) {
|
||||
message = 'Perioden är låst. Lås upp perioden innan du ändrar verifikationen.'
|
||||
}
|
||||
return NextResponse.json({ error: message }, { status: 400 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,337 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/reconciliation/bank/run.
|
||||
*
|
||||
* Exercises the route through the real withRouteContext wrapper, mocking only
|
||||
* its auth/company/write dependencies plus the runReconciliation service.
|
||||
* Covers: 401, 403 viewer, unknown cash account (400), and the happy path.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const runReconciliationMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/bank-reconciliation', () => ({
|
||||
runReconciliation: (...args: unknown[]) => runReconciliationMock(...args),
|
||||
DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD: 0.9,
|
||||
}))
|
||||
|
||||
const sweepMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/unattended-sweep', () => ({
|
||||
runUnattendedReconciliationSweep: (...args: unknown[]) => sweepMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const emptyParams = { params: Promise.resolve({}) }
|
||||
|
||||
describe('POST /api/reconciliation/bank/run', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
runReconciliationMock.mockResolvedValue({ matches: [], applied: 0, errors: [] })
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { dry_run: true },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { dry_run: true },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('rejects an out-of-range confidence_threshold with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { dry_run: false, confidence_threshold: 1.5 },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(runReconciliationMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a negative confidence_threshold with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { dry_run: false, confidence_threshold: -0.1 },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(runReconciliationMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes confidence_threshold and selected_matches through to runReconciliation', async () => {
|
||||
// cash_accounts lookup: no row, '1930' default is exempt.
|
||||
enqueue({ data: null })
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
dry_run: false,
|
||||
confidence_threshold: 0.85,
|
||||
selected_matches: [
|
||||
{
|
||||
transaction_id: '11111111-1111-4111-8111-111111111111',
|
||||
journal_entry_id: '22222222-2222-4222-8222-222222222222',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(200)
|
||||
expect(runReconciliationMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({
|
||||
confidenceThreshold: 0.85,
|
||||
applyOnly: [
|
||||
{
|
||||
transactionId: '11111111-1111-4111-8111-111111111111',
|
||||
journalEntryId: '22222222-2222-4222-8222-222222222222',
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('defaults a no-selection apply to the 0.9 unattended floor when the client sends no threshold', async () => {
|
||||
// Merged semantics (#1571 x bank-and-sie-match): an explicit
|
||||
// confidence_threshold always wins; WITHOUT one, an apply with no
|
||||
// selected_matches is effectively unattended, so it floors at 0.9 and
|
||||
// persists the review band instead of auto-committing fuzzy matches.
|
||||
// cash_accounts lookup: no row, '1930' default is exempt.
|
||||
enqueue({ data: null })
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { dry_run: false },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(200)
|
||||
expect(runReconciliationMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({ confidenceThreshold: 0.9, persistSuggestions: true }),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a non-default account with no cash_accounts row', async () => {
|
||||
// cash_accounts lookup finds nothing for 1932.
|
||||
enqueue({ data: null })
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { account_number: '1932', dry_run: true },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Okänt kassakonto för det här företaget')
|
||||
expect(runReconciliationMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs reconciliation on the default 1930 account even without a cash_accounts row', async () => {
|
||||
// cash_accounts lookup: no row, but '1930' is exempt.
|
||||
enqueue({ data: null })
|
||||
runReconciliationMock.mockResolvedValue({
|
||||
matches: [
|
||||
{
|
||||
transaction: { id: 't-1', date: '2024-06-15', description: 'Betalning', amount: 1250 },
|
||||
glLine: {
|
||||
journal_entry_id: 'je-1',
|
||||
voucher_number: 12,
|
||||
voucher_series: 'A',
|
||||
entry_date: '2024-06-15',
|
||||
entry_description: 'Kundfaktura',
|
||||
},
|
||||
method: 'exact',
|
||||
confidence: 1,
|
||||
},
|
||||
],
|
||||
applied: 1,
|
||||
errors: [],
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { date_from: '2024-06-01', date_to: '2024-06-30' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { matches: { transaction_id: string }[]; applied: number; dry_run: boolean }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.applied).toBe(1)
|
||||
expect(body.data.dry_run).toBe(false)
|
||||
expect(body.data.matches[0].transaction_id).toBe('t-1')
|
||||
expect(runReconciliationMock).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
// A no-selection apply run persists the review band as suggestions
|
||||
// behind the unattended confidence floor ("Kör matchning igen").
|
||||
expect.objectContaining({
|
||||
accountNumber: '1930',
|
||||
currency: 'SEK',
|
||||
dryRun: false,
|
||||
confidenceThreshold: 0.9,
|
||||
persistSuggestions: true,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the legacy no-threshold behavior for a reviewed selected_matches apply', async () => {
|
||||
// cash_accounts lookup: no row, '1930' exempt.
|
||||
enqueue({ data: null })
|
||||
runReconciliationMock.mockResolvedValue({
|
||||
matches: [],
|
||||
applied: 0,
|
||||
errors: 0,
|
||||
skippedBelowThreshold: 0,
|
||||
suggested: 0,
|
||||
candidates: 0,
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
selected_matches: [
|
||||
{
|
||||
transaction_id: '11111111-1111-4111-8111-111111111111',
|
||||
journal_entry_id: '22222222-2222-4222-8222-222222222222',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(200)
|
||||
|
||||
const options = runReconciliationMock.mock.calls[0][3] as Record<string, unknown>
|
||||
expect(options.applyOnly).toHaveLength(1)
|
||||
// The user already reviewed these pairs in the dry-run preview: no floor,
|
||||
// no suggestion persistence.
|
||||
expect(options.confidenceThreshold).toBeUndefined()
|
||||
expect(options.persistSuggestions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('routes all_accounts to the per-account sweep ("Kör matchning igen")', async () => {
|
||||
sweepMock.mockResolvedValue({
|
||||
accounts: [
|
||||
{ accountNumber: '1930', applied: 3, suggested: 1 },
|
||||
{ accountNumber: '1931', applied: 1, suggested: 0 },
|
||||
],
|
||||
applied: 4,
|
||||
errors: 0,
|
||||
skippedBelowThreshold: 1,
|
||||
suggested: 1,
|
||||
unmatched: 2,
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { all_accounts: true },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { applied: number; suggested: number; unmatched: number }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.applied).toBe(4)
|
||||
expect(body.data.suggested).toBe(1)
|
||||
expect(body.data.unmatched).toBe(2)
|
||||
expect(sweepMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', {
|
||||
dateFrom: undefined,
|
||||
dateTo: undefined,
|
||||
})
|
||||
expect(runReconciliationMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects all_accounts combined with dry_run: the sweep has no preview form and must never apply on a requested preview', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', {
|
||||
method: 'POST',
|
||||
body: { all_accounts: true, dry_run: true },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(sweepMock).not.toHaveBeenCalled()
|
||||
expect(runReconciliationMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects all_accounts combined with account_number or selected_matches', async () => {
|
||||
for (const body of [
|
||||
{ all_accounts: true, account_number: '1930' },
|
||||
{ all_accounts: true, confidence_threshold: 0.85 },
|
||||
{
|
||||
all_accounts: true,
|
||||
selected_matches: [
|
||||
{
|
||||
transaction_id: '11111111-1111-4111-8111-111111111111',
|
||||
journal_entry_id: '22222222-2222-4222-8222-222222222222',
|
||||
},
|
||||
],
|
||||
},
|
||||
]) {
|
||||
const request = createMockRequest('/api/reconciliation/bank/run', { method: 'POST', body })
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
}
|
||||
expect(sweepMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,148 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import {
|
||||
runReconciliation,
|
||||
DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD,
|
||||
} from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { runUnattendedReconciliationSweep } from '@/lib/reconciliation/unattended-sweep'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { RunReconciliationSchema } from '@/lib/api/schemas'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'reconciliation.bank.run',
|
||||
async (request, { supabase, user, companyId }) => {
|
||||
const validation = await validateBody(request, RunReconciliationSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const {
|
||||
date_from,
|
||||
date_to,
|
||||
account_number,
|
||||
dry_run,
|
||||
selected_matches,
|
||||
confidence_threshold,
|
||||
all_accounts,
|
||||
} = validation.data
|
||||
|
||||
// "Kör matchning igen": the per-account sweep across every enabled cash
|
||||
// account, exactly what the unattended post-sync path runs. New >= 0.9
|
||||
// matches auto-link; the 0.75-0.89 band persists as suggestions.
|
||||
//
|
||||
// The sweep ALWAYS writes at its own fixed floor: there is no dry-run form
|
||||
// of it, and silently ignoring dry_run (or a client-sent floor) here would
|
||||
// turn a requested preview into applied links (the documented
|
||||
// dry-run-gotcha P0 class). Enforce the mutual exclusion instead of just
|
||||
// documenting it.
|
||||
if (
|
||||
all_accounts &&
|
||||
(dry_run !== undefined ||
|
||||
account_number ||
|
||||
selected_matches ||
|
||||
confidence_threshold !== undefined)
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
'all_accounts kan inte kombineras med dry_run, account_number, selected_matches eller confidence_threshold',
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
if (all_accounts) {
|
||||
const sweep = await runUnattendedReconciliationSweep(supabase, companyId, user.id, {
|
||||
dateFrom: date_from,
|
||||
dateTo: date_to,
|
||||
})
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
applied: sweep.applied,
|
||||
errors: sweep.errors,
|
||||
suggested: sweep.suggested,
|
||||
unmatched: sweep.unmatched,
|
||||
skipped_below_threshold: sweep.skippedBelowThreshold,
|
||||
accounts: sweep.accounts.map((a) => ({
|
||||
account_number: a.accountNumber,
|
||||
applied: a.applied,
|
||||
suggested: a.suggested,
|
||||
})),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const accountNumber = account_number ?? '1930'
|
||||
|
||||
// Defense-in-depth: reject a non-default account the company hasn't
|
||||
// registered as a cash account. The default '1930' is exempt: when no
|
||||
// cash_accounts row exists it falls back to currency-only scoping
|
||||
// (cashAccountId undefined), so a company reconciling its primary SEK account
|
||||
// without a row behaves exactly as before this feature. Matches the status
|
||||
// endpoint, which is likewise lenient for '1930'.
|
||||
const { data: cashAccount } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('id, currency, is_primary')
|
||||
.eq('company_id', companyId)
|
||||
.eq('ledger_account', accountNumber)
|
||||
.maybeSingle()
|
||||
|
||||
if (!cashAccount && accountNumber !== '1930') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Okänt kassakonto för det här företaget' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
const currency = (cashAccount?.currency as string | undefined) ?? 'SEK'
|
||||
|
||||
const result = await runReconciliation(supabase, companyId, user.id, {
|
||||
dateFrom: date_from,
|
||||
dateTo: date_to,
|
||||
accountNumber,
|
||||
currency,
|
||||
cashAccountId: cashAccount?.id as string | undefined,
|
||||
// Only the primary account claims unassigned (NULL cash_account_id) rows:
|
||||
// a secondary same-currency account must scope strictly to its own id.
|
||||
includeUnassigned: Boolean(cashAccount?.is_primary),
|
||||
dryRun: dry_run ?? false,
|
||||
applyOnly: selected_matches?.map((m) => ({
|
||||
transactionId: m.transaction_id,
|
||||
journalEntryId: m.journal_entry_id,
|
||||
})),
|
||||
// Server-side floor on the apply path. A client-sent confidence_threshold
|
||||
// always wins (mirrors the v1 route: pairs the fresh re-run scores below
|
||||
// it are skipped, not applied). Without one: a no-selection apply run is
|
||||
// effectively unattended, so it floors at 0.9 and persists the 0.75-0.89
|
||||
// band as reviewable suggestions instead of auto-committing fuzzy
|
||||
// matches; applyOnly runs keep the legacy no-floor behavior (the user
|
||||
// already reviewed the pairs in the dry-run preview). Ignored on dry runs.
|
||||
confidenceThreshold:
|
||||
confidence_threshold ??
|
||||
(selected_matches ? undefined : DEFAULT_UNATTENDED_CONFIDENCE_THRESHOLD),
|
||||
...(selected_matches ? {} : { persistSuggestions: true }),
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
matches: result.matches.map((m) => ({
|
||||
transaction_id: m.transaction.id,
|
||||
transaction_date: m.transaction.date,
|
||||
transaction_description: m.transaction.description,
|
||||
transaction_amount: m.transaction.amount,
|
||||
journal_entry_id: m.glLine.journal_entry_id,
|
||||
voucher_number: m.glLine.voucher_number,
|
||||
voucher_series: m.glLine.voucher_series,
|
||||
entry_date: m.glLine.entry_date,
|
||||
entry_description: m.glLine.entry_description,
|
||||
method: m.method,
|
||||
confidence: m.confidence,
|
||||
})),
|
||||
applied: result.applied,
|
||||
errors: result.errors,
|
||||
suggested: result.suggested,
|
||||
skipped_below_threshold: result.skippedBelowThreshold,
|
||||
dry_run: dry_run ?? false,
|
||||
},
|
||||
})
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,50 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { getReconciliationStatus } from '@/lib/reconciliation/bank-reconciliation'
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'reconciliation.bank.status',
|
||||
async (request, { supabase, companyId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const dateFrom = searchParams.get('date_from') || undefined
|
||||
const dateTo = searchParams.get('date_to') || undefined
|
||||
const accountNumber = searchParams.get('account_number') || '1930'
|
||||
|
||||
// Look up the cash account so we can pair the bank account with the right
|
||||
// currency. Comparing EUR GL movements against SEK transactions silently
|
||||
// produces nonsense.
|
||||
const { data: cashAccount } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('id, currency, is_primary')
|
||||
.eq('company_id', companyId)
|
||||
.eq('ledger_account', accountNumber)
|
||||
.maybeSingle()
|
||||
|
||||
if (!cashAccount && accountNumber !== '1930') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Okänt kassakonto för det här företaget' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const currency = (cashAccount?.currency as string | undefined) ?? 'SEK'
|
||||
const cashAccountId = cashAccount?.id as string | undefined
|
||||
// Only the primary account claims unassigned (NULL cash_account_id) rows.
|
||||
// A secondary same-currency account (e.g. a 1931 savings account) must not, or
|
||||
// 1930's unassigned rows inflate its bank total and show a bogus difference.
|
||||
const includeUnassigned = Boolean(cashAccount?.is_primary)
|
||||
|
||||
const status = await getReconciliationStatus(
|
||||
supabase,
|
||||
companyId,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
accountNumber,
|
||||
currency,
|
||||
cashAccountId,
|
||||
includeUnassigned,
|
||||
)
|
||||
|
||||
return NextResponse.json({ data: status })
|
||||
},
|
||||
)
|
||||
@@ -1,122 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/reconciliation/bank/unlink.
|
||||
*
|
||||
* Exercises the route through the real withRouteContext wrapper, mocking only
|
||||
* its auth/company/write dependencies plus the unlinkReconciliation service.
|
||||
* Covers: 401, 403 viewer, validation (400), service failure (400), and the
|
||||
* happy path.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, 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 unlinkMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/bank-reconciliation', () => ({
|
||||
unlinkReconciliation: (...args: unknown[]) => unlinkMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const emptyParams = { params: Promise.resolve({}) }
|
||||
const TX_ID = '44444444-4444-4444-8444-444444444444'
|
||||
|
||||
describe('POST /api/reconciliation/bank/unlink', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
unlinkMock.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/unlink', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/unlink', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('rejects a non-uuid transaction_id with 400', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/unlink', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: 'not-a-uuid' },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
expect(response.status).toBe(400)
|
||||
expect(unlinkMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces an unlink failure as 400 with the service error', async () => {
|
||||
unlinkMock.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Cannot unlink a categorization-created entry. Use storno to reverse it instead.',
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/reconciliation/bank/unlink', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('storno')
|
||||
})
|
||||
|
||||
it('unlinks the transaction', async () => {
|
||||
const request = createMockRequest('/api/reconciliation/bank/unlink', {
|
||||
method: 'POST',
|
||||
body: { transaction_id: TX_ID },
|
||||
})
|
||||
|
||||
const response = await POST(request, emptyParams)
|
||||
const { status, body } = await parseJsonResponse<{ data: { success: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.success).toBe(true)
|
||||
expect(unlinkMock).toHaveBeenCalledWith(supabase, 'company-1', TX_ID, 'user-1')
|
||||
})
|
||||
})
|
||||
@@ -1,23 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { unlinkReconciliation } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { BankUnlinkSchema } from '@/lib/api/schemas'
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'reconciliation.bank.unlink',
|
||||
async (request, { supabase, user, companyId }) => {
|
||||
const validation = await validateBody(request, BankUnlinkSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { transaction_id } = validation.data
|
||||
|
||||
const result = await unlinkReconciliation(supabase, companyId, transaction_id, user.id)
|
||||
|
||||
if (!result.success) {
|
||||
return NextResponse.json({ error: result.error }, { status: 400 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { success: true } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,371 +0,0 @@
|
||||
/**
|
||||
* Tests for GET /api/reconciliation/bank/unmatched-entries.
|
||||
*
|
||||
* Exercises the route through the real withRouteContext wrapper and the REAL
|
||||
* matcher (tryReconcileTransaction / ledgerLineAmountIn); only the RPC-backed
|
||||
* candidate fetch is mocked, so the currency guard is tested end to end rather
|
||||
* than against a stubbed scorer.
|
||||
*
|
||||
* The focus is the ranking currency: it is the CASH ACCOUNT's, never the
|
||||
* transaction's own. Sourcing it from the transaction made
|
||||
* tryReconcileTransaction's `transaction.currency !== expectedCurrency` guard
|
||||
* compare the transaction against itself, so it never rejected anything and a
|
||||
* foreign bank line was ranked against this account's SEK vouchers.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import type { GLLineForMatching } from '@/lib/reconciliation/bank-reconciliation'
|
||||
|
||||
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'),
|
||||
}))
|
||||
|
||||
// Only the candidate fetch is stubbed: the scorer and ledgerLineAmountIn stay
|
||||
// real so a regression in the currency handling actually fails here.
|
||||
const fetchGLLinesForMatchingMock = vi.fn()
|
||||
vi.mock('@/lib/reconciliation/bank-reconciliation', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/reconciliation/bank-reconciliation')>()
|
||||
return {
|
||||
...actual,
|
||||
fetchGLLinesForMatching: (...args: unknown[]) => fetchGLLinesForMatchingMock(...args),
|
||||
}
|
||||
})
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
const emptyParams = { params: Promise.resolve({}) }
|
||||
const TX_ID = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
type RankedLine = GLLineForMatching & { confidence: number }
|
||||
type Body = { data: RankedLine[]; not_rankable_reason?: string }
|
||||
|
||||
function makeGLLine(overrides: Partial<GLLineForMatching> = {}): GLLineForMatching {
|
||||
return {
|
||||
line_id: 'line-1',
|
||||
journal_entry_id: 'je-1',
|
||||
// The RPC projects the SEK debit/credit columns only: see the currency /
|
||||
// amount_in_currency note on UnlinkedGLLine.
|
||||
debit_amount: 0,
|
||||
credit_amount: 1150,
|
||||
line_description: null,
|
||||
entry_date: '2026-03-10',
|
||||
voucher_number: 42,
|
||||
voucher_series: 'A',
|
||||
entry_description: 'Leverantörsbetalning',
|
||||
source_type: 'manual',
|
||||
linked_transaction_count: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** Queue the cash_accounts lookup the route always performs first. */
|
||||
function enqueueCashAccount(currency: string | null = 'SEK') {
|
||||
enqueue({ data: { id: 'cash-1', currency } })
|
||||
}
|
||||
|
||||
/** Queue the transaction lookup the ranked path performs second. */
|
||||
function enqueueTransaction(overrides: Record<string, unknown> = {}) {
|
||||
enqueue({
|
||||
data: {
|
||||
id: TX_ID,
|
||||
amount: -1150,
|
||||
date: '2026-03-10',
|
||||
currency: 'SEK',
|
||||
reference: null,
|
||||
...overrides,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function request(searchParams: Record<string, string>) {
|
||||
return createMockRequest('/api/reconciliation/bank/unmatched-entries', { searchParams })
|
||||
}
|
||||
|
||||
describe('GET /api/reconciliation/bank/unmatched-entries', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([])
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await GET(request({ account_number: '1930' }), emptyParams)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(fetchGLLinesForMatchingMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an account the company has not registered as a cash account', async () => {
|
||||
// The route's "not found": an unregistered ledger account is refused rather
|
||||
// than probed, so this endpoint cannot be used to read arbitrary GL accounts.
|
||||
enqueue({ data: null })
|
||||
|
||||
const response = await GET(request({ account_number: '1510' }), emptyParams)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(fetchGLLinesForMatchingMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns no candidates when transaction_id does not resolve in this company', async () => {
|
||||
enqueueCashAccount('SEK')
|
||||
enqueue({ data: null })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([makeGLLine()])
|
||||
|
||||
const response = await GET(
|
||||
request({ account_number: '1930', transaction_id: TX_ID }),
|
||||
emptyParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<Body>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual([])
|
||||
})
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// SEK: the 95% path, byte-for-byte unchanged
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
it('ranks a SEK bank line against SEK vouchers exactly as before', async () => {
|
||||
enqueueCashAccount('SEK')
|
||||
enqueueTransaction({ currency: 'SEK', amount: -1150, date: '2026-03-10' })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([
|
||||
makeGLLine({ line_id: 'line-far', journal_entry_id: 'je-far', entry_date: '2026-02-01' }),
|
||||
makeGLLine({ line_id: 'line-hit', journal_entry_id: 'je-hit', entry_date: '2026-03-10' }),
|
||||
])
|
||||
|
||||
const response = await GET(
|
||||
request({ account_number: '1930', transaction_id: TX_ID }),
|
||||
emptyParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<Body>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
// Nothing withheld on a SEK account: ledgerLineAmountIn never returns null there.
|
||||
expect(body.data).toHaveLength(2)
|
||||
expect(body.not_rankable_reason).toBeUndefined()
|
||||
// Exact amount + exact date = auto_exact, sorted to the top.
|
||||
expect(body.data[0].journal_entry_id).toBe('je-hit')
|
||||
expect(body.data[0].confidence).toBe(0.95)
|
||||
expect(body.data[1].confidence).toBe(0)
|
||||
})
|
||||
|
||||
it('leaves the unranked list untouched when no transaction_id is passed', async () => {
|
||||
enqueueCashAccount('SEK')
|
||||
const lines = [makeGLLine()]
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue(lines)
|
||||
|
||||
const response = await GET(request({ account_number: '1930' }), emptyParams)
|
||||
const { status, body } = await parseJsonResponse<Body>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
expect(body.data[0]).not.toHaveProperty('confidence')
|
||||
})
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Orphaned reconnect rows (#1643 problem 1): the ranked (dialog) path also
|
||||
// offers vouchers booked on sibling ledgers of the same physical account
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
it('widens ranked candidates to sibling ledgers sharing the account IBAN', async () => {
|
||||
const iban = 'SE4550000000058398257466'
|
||||
// The transaction's own (orphaned) row: ledger 1931, carries the IBAN.
|
||||
enqueue({ data: { id: 'cash-orphan', currency: 'SEK', iban } })
|
||||
// Sibling scan (describeCashAccountSiblings): the live row for the same
|
||||
// physical account sits on 1940 (spaced IBAN variant to prove
|
||||
// normalization), plus an unrelated account.
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'cash-orphan', ledger_account: '1931', iban, currency: 'SEK', enabled: true, bank_connection_id: null },
|
||||
{ id: 'cash-live', ledger_account: '1940', iban: 'SE45 5000 0000 0583 9825 7466', currency: 'SEK', enabled: true, bank_connection_id: 'conn-live' },
|
||||
// Same IBAN, EUR pocket of a multi-currency account: not a sibling.
|
||||
{ id: 'cash-eur', ledger_account: '1932', iban, currency: 'EUR', enabled: true, bank_connection_id: 'conn-live' },
|
||||
{ id: 'cash-other', ledger_account: '1935', iban: 'SE1112223334445556667778', currency: 'SEK', enabled: true, bank_connection_id: 'conn-live' },
|
||||
],
|
||||
})
|
||||
enqueue({ data: [{ id: 'conn-live', status: 'active' }] }) // bank_connections statuses
|
||||
enqueueTransaction({ currency: 'SEK', amount: 217.04, date: '2026-03-10' })
|
||||
|
||||
fetchGLLinesForMatchingMock.mockImplementation((_supabase, _companyId, account) =>
|
||||
account === '1940'
|
||||
? Promise.resolve([
|
||||
makeGLLine({
|
||||
line_id: 'line-live',
|
||||
journal_entry_id: 'je-live',
|
||||
debit_amount: 217.04,
|
||||
credit_amount: 0,
|
||||
entry_date: '2026-03-10',
|
||||
}),
|
||||
])
|
||||
: Promise.resolve([]),
|
||||
)
|
||||
|
||||
const response = await GET(
|
||||
request({ account_number: '1931', transaction_id: TX_ID }),
|
||||
emptyParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<Body>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
// The voucher booked on the LIVE ledger is offered (and ranks as an exact
|
||||
// hit) even though the row itself is stamped on the orphaned 1931.
|
||||
expect(body.data).toHaveLength(1)
|
||||
expect(body.data[0].journal_entry_id).toBe('je-live')
|
||||
expect(body.data[0].confidence).toBe(0.95)
|
||||
|
||||
const fetchedAccounts = fetchGLLinesForMatchingMock.mock.calls.map((c) => c[2])
|
||||
expect(fetchedAccounts).toEqual(['1931', '1940'])
|
||||
})
|
||||
|
||||
it('does not offer vouchers on a DEAD sibling to a transaction on the live row (#1643 round 2)', async () => {
|
||||
const iban = 'SE4550000000058398257466'
|
||||
// manualLink would not move a live row onto the dead sibling, so the
|
||||
// dead sibling's vouchers are not candidates for it.
|
||||
enqueue({ data: { id: 'cash-live', currency: 'SEK', iban } })
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'cash-live', ledger_account: '1940', iban, currency: 'SEK', enabled: true, bank_connection_id: 'conn-live' },
|
||||
{ id: 'cash-orphan', ledger_account: '1931', iban, currency: 'SEK', enabled: true, bank_connection_id: 'conn-old' },
|
||||
],
|
||||
})
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'conn-live', status: 'active' },
|
||||
{ id: 'conn-old', status: 'revoked' },
|
||||
],
|
||||
})
|
||||
enqueueTransaction({ currency: 'SEK', amount: 217.04, date: '2026-03-10' })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([])
|
||||
|
||||
const response = await GET(
|
||||
request({ account_number: '1940', transaction_id: TX_ID }),
|
||||
emptyParams,
|
||||
)
|
||||
expect(response.status).toBe(200)
|
||||
const fetchedAccounts = fetchGLLinesForMatchingMock.mock.calls.map((c) => c[2])
|
||||
expect(fetchedAccounts).toEqual(['1940'])
|
||||
})
|
||||
|
||||
it('does not offer a demoted twin\'s vouchers to a row on an EXPIRED connection (#1643 round 3)', async () => {
|
||||
const iban = 'SE4550000000058398257466'
|
||||
// manualLink would not move a renewable row onto the dead twin either.
|
||||
enqueue({ data: { id: 'cash-expired', currency: 'SEK', iban } })
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'cash-expired', ledger_account: '1930', iban, currency: 'SEK', enabled: true, bank_connection_id: 'conn-expired' },
|
||||
{ id: 'cash-demoted', ledger_account: '1931', iban, currency: 'SEK', enabled: true, bank_connection_id: null },
|
||||
],
|
||||
})
|
||||
enqueue({ data: [{ id: 'conn-expired', status: 'expired' }] })
|
||||
enqueueTransaction({ currency: 'SEK', amount: 217.04, date: '2026-03-10' })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([])
|
||||
|
||||
const response = await GET(
|
||||
request({ account_number: '1930', transaction_id: TX_ID }),
|
||||
emptyParams,
|
||||
)
|
||||
expect(response.status).toBe(200)
|
||||
const fetchedAccounts = fetchGLLinesForMatchingMock.mock.calls.map((c) => c[2])
|
||||
expect(fetchedAccounts).toEqual(['1930'])
|
||||
})
|
||||
|
||||
it('does not widen the unranked (reconciliation view) path', async () => {
|
||||
const iban = 'SE4550000000058398257466'
|
||||
enqueue({ data: { id: 'cash-orphan', currency: 'SEK', iban } })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([makeGLLine()])
|
||||
|
||||
const response = await GET(request({ account_number: '1931' }), emptyParams)
|
||||
const { status } = await parseJsonResponse<Body>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(fetchGLLinesForMatchingMock).toHaveBeenCalledTimes(1)
|
||||
expect(fetchGLLinesForMatchingMock.mock.calls[0][2]).toBe('1931')
|
||||
})
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Foreign currency: never ranked against an unconverted SEK ledger leg
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
it('does not rank a foreign bank line against a same-magnitude SEK voucher', async () => {
|
||||
// A 1 150 EUR payment out of the EUR account. The voucher's 1932 leg holds
|
||||
// 1 150 in the SEK columns for an unrelated amount of money; the RPC
|
||||
// projects no currency / amount_in_currency, so there is no rate to convert
|
||||
// with. Offering it as the settlement would be a coincidence of magnitude.
|
||||
enqueueCashAccount('EUR')
|
||||
enqueueTransaction({ currency: 'EUR', amount: -1150, date: '2026-03-10' })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([makeGLLine({ credit_amount: 1150 })])
|
||||
|
||||
const response = await GET(
|
||||
request({ account_number: '1932', transaction_id: TX_ID }),
|
||||
emptyParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<Body>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual([])
|
||||
// Honest about WHY the list is empty: candidates exist, they just cannot be
|
||||
// expressed in the account's currency. Not "no unmatched verifikationer".
|
||||
expect(body.not_rankable_reason).toBe('gl_lines_missing_currency_amount')
|
||||
})
|
||||
|
||||
it('refuses to rank a bank line denominated in another currency than the account', async () => {
|
||||
// The tautology this fixes: with the reconciliation currency read off the
|
||||
// transaction, this EUR row was ranked against the SEK account's vouchers.
|
||||
enqueueCashAccount('SEK')
|
||||
enqueueTransaction({ currency: 'EUR', amount: -1150, date: '2026-03-10' })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([makeGLLine({ credit_amount: 1150 })])
|
||||
|
||||
const response = await GET(
|
||||
request({ account_number: '1930', transaction_id: TX_ID }),
|
||||
emptyParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<Body>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual([])
|
||||
expect(body.not_rankable_reason).toBe('transaction_currency_mismatch')
|
||||
})
|
||||
|
||||
it('ranks a foreign bank line when the ledger line carries a foreign amount', async () => {
|
||||
// Proves the filter is per-line, not a blanket "non-SEK account cannot
|
||||
// rank": the day the RPC projects currency + amount_in_currency, ranking
|
||||
// resumes with no further change here.
|
||||
enqueueCashAccount('EUR')
|
||||
enqueueTransaction({ currency: 'EUR', amount: -100, date: '2026-03-10' })
|
||||
fetchGLLinesForMatchingMock.mockResolvedValue([
|
||||
makeGLLine({
|
||||
// Debit/credit are SEK; the EUR figure lives in amount_in_currency.
|
||||
credit_amount: 1150,
|
||||
currency: 'EUR',
|
||||
amount_in_currency: 100,
|
||||
}),
|
||||
])
|
||||
|
||||
const response = await GET(
|
||||
request({ account_number: '1932', transaction_id: TX_ID }),
|
||||
emptyParams,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<Body>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
expect(body.data[0].confidence).toBe(0.95)
|
||||
expect(body.not_rankable_reason).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,184 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import {
|
||||
fetchGLLinesForMatching,
|
||||
ledgerLineAmountIn,
|
||||
tryReconcileTransaction,
|
||||
} from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { describeCashAccountSiblings, normalizeIban, shouldRepointToSibling } from '@/lib/cash-accounts/service'
|
||||
import type { Transaction } from '@/types'
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'reconciliation.bank.unmatched_entries',
|
||||
async (request, { supabase, companyId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const dateFrom = searchParams.get('date_from') || undefined
|
||||
const dateTo = searchParams.get('date_to') || undefined
|
||||
const accountNumber = searchParams.get('account_number') || '1930'
|
||||
// Optional: when set, rank the returned candidates for this specific bank
|
||||
// transaction (used by the Transactions-page "Matcha mot befintlig
|
||||
// verifikation" dialog). Ranking happens server-side on purpose:
|
||||
// lib/reconciliation/bank-reconciliation pulls in server-only deps (event
|
||||
// bus, match-log) and must never reach the client bundle.
|
||||
const transactionId = searchParams.get('transaction_id') || undefined
|
||||
// When true, also return vouchers already matched to a bank transaction (each
|
||||
// carries linked_transaction_count) so the user can attach a second/third
|
||||
// transaction to the same verifikat, the N:1 "lägga på flera" case. Default
|
||||
// false keeps the list to unmatched candidates only.
|
||||
const includeMatched = searchParams.get('include_matched') === 'true'
|
||||
|
||||
// Defense-in-depth: only allow account numbers that the company has actually
|
||||
// registered as a cash account. Without this, a curious caller could probe
|
||||
// arbitrary GL accounts for posted-but-unmatched amounts. Applies uniformly
|
||||
// including '1930': the cash_accounts backfill seeds 1930 for every company
|
||||
// that had a SEK PSD2 account, and the AccountPickerDialog seeds it for new
|
||||
// companies on first connection.
|
||||
// `currency` comes along because it, not the transaction's own currency, is
|
||||
// the unit this account is reconciled in: see the ranking block below.
|
||||
// `iban` identifies the physical bank account so the ranked (dialog) path
|
||||
// can widen the candidate set to sibling ledgers of the same account.
|
||||
const { data: cashAccount } = await supabase
|
||||
.from('cash_accounts')
|
||||
.select('id, currency, iban')
|
||||
.eq('company_id', companyId)
|
||||
.eq('ledger_account', accountNumber)
|
||||
.maybeSingle()
|
||||
|
||||
if (!cashAccount) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Okänt kassakonto för det här företaget' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// cash_accounts.currency is NOT NULL in the schema; the fallback only guards
|
||||
// against a legacy/hand-built row so a missing value can never silently turn
|
||||
// into "no currency" and disable ranking for a SEK company.
|
||||
const accountCurrency = (cashAccount.currency as string | null) ?? 'SEK'
|
||||
|
||||
let lines = await fetchGLLinesForMatching(supabase, companyId, accountNumber, dateFrom, dateTo, includeMatched)
|
||||
|
||||
if (transactionId) {
|
||||
// The "Matcha mot befintlig verifikation" dialog resolves the account
|
||||
// from the TRANSACTION's own cash_accounts row. When that row is an
|
||||
// orphan of a broken reconnect (issue #1643 problem 1), the verifikat
|
||||
// the row settles is booked on the LIVE ledger of the same physical
|
||||
// account (e.g. row stamped 1931, voucher on 1940) and could never be
|
||||
// offered. Sibling rows share the account's IBAN, so the candidate set
|
||||
// widens to every ledger carrying it in the SAME currency (the other
|
||||
// currency pockets of a multi-currency account share the IBAN but are
|
||||
// different accounts). Accounts without an IBAN (manual, CSV) have no
|
||||
// siblings and keep the exact single-ledger behavior.
|
||||
// A sibling that is NOT live (demoted or held by a revoked/expired
|
||||
// connection) is only offered when manualLink would re-point the row
|
||||
// onto it (shouldRepointToSibling: the own row's holder is gone and no
|
||||
// sibling is live): a live row, or one on a merely expired connection
|
||||
// that re-auth renews, must never be parked on a row no connection can
|
||||
// sync again.
|
||||
const ownIban = normalizeIban((cashAccount as { iban?: string | null }).iban ?? null)
|
||||
const siblingInfo = ownIban
|
||||
? await describeCashAccountSiblings(supabase, companyId, cashAccount.id as string)
|
||||
: null
|
||||
if (siblingInfo && siblingInfo.siblings.length > 0) {
|
||||
const siblingLedgers = [
|
||||
...new Set(
|
||||
siblingInfo.siblings
|
||||
.filter((row) => shouldRepointToSibling(siblingInfo, row))
|
||||
.map((row) => row.ledger_account),
|
||||
),
|
||||
]
|
||||
if (siblingLedgers.length > 0) {
|
||||
const merged = [...lines]
|
||||
const seen = new Set(lines.map((l) => l.line_id))
|
||||
for (const ledger of siblingLedgers) {
|
||||
const siblingLines = await fetchGLLinesForMatching(
|
||||
supabase, companyId, ledger, dateFrom, dateTo, includeMatched,
|
||||
)
|
||||
for (const line of siblingLines) {
|
||||
if (seen.has(line.line_id)) continue
|
||||
seen.add(line.line_id)
|
||||
merged.push(line)
|
||||
}
|
||||
}
|
||||
lines = merged
|
||||
}
|
||||
}
|
||||
// company-scoped fetch (defense-in-depth). A malformed/foreign id yields no
|
||||
// row → we fall through to the unranked list rather than erroring.
|
||||
const { data: tx } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, amount, date, currency, reference')
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!tx) {
|
||||
// transaction_id was supplied but doesn't resolve to a row in the
|
||||
// caller's company: the ranking context is invalid. Return no candidates
|
||||
// rather than silently falling back to the full unranked list, so a
|
||||
// fabricated or foreign id can never yield a broader result set.
|
||||
return NextResponse.json({ data: [] })
|
||||
}
|
||||
|
||||
// The reconciliation currency is the CASH ACCOUNT's, never the
|
||||
// transaction's. Reading it off `tx` made tryReconcileTransaction's
|
||||
// `transaction.currency !== expectedCurrency` guard compare the
|
||||
// transaction against itself: a tautology that passed for every row, so
|
||||
// the guard never rejected anything and a foreign bank line was ranked
|
||||
// against this account's (SEK) vouchers.
|
||||
const txCurrency = (tx.currency as string | null) ?? 'SEK'
|
||||
if (txCurrency !== accountCurrency) {
|
||||
// A bank line in another currency cannot be settled on this account, so
|
||||
// there is no honest ranking to produce. Same posture as the unresolved
|
||||
// transaction above: no candidates beats plausible-looking wrong ones.
|
||||
return NextResponse.json({
|
||||
data: [],
|
||||
not_rankable_reason: 'transaction_currency_mismatch',
|
||||
})
|
||||
}
|
||||
|
||||
// Withhold any candidate that cannot be expressed in the account's
|
||||
// currency. journal_entry_lines.debit_amount / credit_amount are ALWAYS
|
||||
// SEK; `currency` on the line labels the underlying DOCUMENT and
|
||||
// amount_in_currency carries the foreign figure (see ledgerLineAmountIn).
|
||||
// On a SEK account this filter is a no-op: ledgerLineAmountIn never
|
||||
// returns null there, so SEK-only companies see exactly the list they
|
||||
// always did. On a foreign account it currently drops EVERY candidate,
|
||||
// because get_account_gl_lines_for_matching projects neither currency nor
|
||||
// amount_in_currency (verified against prod), so no row carries a rate to
|
||||
// convert with. Ranking them anyway would offer a 1 150 SEK ledger leg as
|
||||
// the settlement for a 1 150 EUR bank line. Written per-line rather than
|
||||
// as an `accountCurrency !== 'SEK'` short-circuit so that ranking resumes
|
||||
// by itself the day the RPC projects those two columns.
|
||||
const rankable = lines.filter((line) => ledgerLineAmountIn(line, accountCurrency) !== null)
|
||||
|
||||
const txDate = tx.date as string
|
||||
const ranked = rankable
|
||||
.map((line) => {
|
||||
// Score each line in isolation; confidence 0 means "no auto-match
|
||||
// rule fired": the line still appears so the user can pick it
|
||||
// manually (e.g. a salary or Fortnox voucher with a tweaked date).
|
||||
const match = tryReconcileTransaction(tx as unknown as Transaction, [line], accountCurrency)
|
||||
return { ...line, confidence: match?.confidence ?? 0 }
|
||||
})
|
||||
.sort((a, b) => {
|
||||
if (b.confidence !== a.confidence) return b.confidence - a.confidence
|
||||
const da = Math.abs(new Date(a.entry_date).getTime() - new Date(txDate).getTime())
|
||||
const db = Math.abs(new Date(b.entry_date).getTime() - new Date(txDate).getTime())
|
||||
return da - db
|
||||
})
|
||||
|
||||
// Say so when candidates were withheld, instead of letting an empty list
|
||||
// read as "this account has no unmatched verifikationer in the period".
|
||||
if (rankable.length !== lines.length) {
|
||||
return NextResponse.json({
|
||||
data: ranked,
|
||||
not_rankable_reason: 'gl_lines_missing_currency_amount',
|
||||
})
|
||||
}
|
||||
return NextResponse.json({ data: ranked })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: lines })
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user