Files
accounted/app/api/bookkeeping/no-doc-required/bulk-missing/route.ts
T
MattssonandClaude Fable 5.1 2f787a2b3c fix(bookkeeping): send each missing-underlag lookup chunk once per URL (#2430)
* fix(bookkeeping): send each missing-underlag lookup chunk once per URL

The "verifikat utan underlag" filter (/bookkeeping?missingUnderlag=true)
failed with "Verifikaten kunde inte hamtas" on a self-hosted instance as
soon as the candidate set passed one chunk of 150 ids.

Why it occurred: resolveMissingUnderlagEntries issues four lookups per
chunk. Three carry the id list once; the supplier_invoices lookup
interpolated the same chunk twice into a single .or() over
registration_journal_entry_id and payment_journal_entry_id. That URL
alone crossed the 8 KB header buffer nginx/Kong ship with, so the
gateway answered 414 before PostgREST saw the request. Hosted sits at
roughly half of Cloudflare's 16 KB ceiling on the same query. The
LOOKUP_CHUNK docblock acknowledged the doubling without sizing for it.

What was removed: the runtime-built .or() string, the chunkInList
helper and its uuid guard (the .in() array filter is injection-safe on
its own). The supplier-invoice lookup is now two .in() queries, one per
FK column, merged into the same set, so every request carries the chunk
exactly once and the proxy limit stops being a dependency rather than
moving. LOOKUP_CHUNK stays 150 and its comment is now true. The
literal filter also leaves the phantom-column scanner's unresolvable
budget.

Two secondary defects from the same report: MissingUnderlagQueryError
now carries the raw driver error as `cause` and the journal-entries
route logs it, while the response keeps the Swedish text (the log used
to say only "Nagot gick fel", hiding the 414). The "Visa saknade
underlag" badge renders the total of the last successful filtered fetch
and hides on failure, instead of borrowing the list count (0 on a
failed first load, the whole ledger after a toggle).

Alternatives: halving LOOKUP_CHUNK moves the wall instead of removing
it. Pushing the list filters into the verifikat_without_documents RPC
and deleting the TS mirror leaves one predicate instead of two, but
moves search, series, date and sort into SQL; recorded in DECISIONS.md
as the intended next step for the surface owner.

Fixes #2395

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q4kpVfYooLp8CWeUguRVpQ

* fix(bookkeeping): hide the underlag badge on network failure, log the bulk route's cause

Skeptic findings on aacb17634. The badge contract is "no honest source,
no badge": the non-OK branch cleared missingCount but the network-level
catch (offline, aborted body, JSON parse rejection) did not, so a period
or series change that failed at that level kept the previous filtered
total next to the toggle. The bulk "Inget underlag kravs" route had the
same log gap as the list route: it returned the mapped text without
logging the driver error, so a gateway 414 on that path stayed
invisible.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q4kpVfYooLp8CWeUguRVpQ

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 16:35:41 +02:00

112 lines
4.2 KiB
TypeScript

import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { markEntriesNoDocRequired } from '@/lib/bookkeeping/no-doc-required'
import {
MissingUnderlagQueryError,
resolveMissingUnderlagEntries,
} from '@/lib/bookkeeping/missing-underlag'
// A real calendar date in YYYY-MM-DD form. Rejects shaped-but-invalid values
// (e.g. 9999-99-99 or 2026-02-30) that a bare /^\d{4}-\d{2}-\d{2}$/ regex would
// let through and that would otherwise reach the query layer.
const isoDate = z.string().refine(
(v) => {
if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) return false
const [y, m, d] = v.split('-').map(Number)
const date = new Date(Date.UTC(y, m - 1, d))
return (
date.getUTCFullYear() === y &&
date.getUTCMonth() + 1 === m &&
date.getUTCDate() === d
)
},
{ message: 'Ogiltigt datum (förväntat YYYY-MM-DD)' },
)
const BulkMissingSchema = z.object({
period_id: z.string().uuid().nullable().optional(),
// Single uppercase verifikationsserie (A-Z); the list sends null for "all".
series: z.string().regex(/^[A-Z]$/).nullable().optional(),
date_from: isoDate.nullable().optional(),
date_to: isoDate.nullable().optional(),
search: z.string().max(200).nullable().optional(),
reason: z.string().trim().max(200).nullable().optional(),
// When true, only count the matching verifikat (no writes) so the UI can
// confirm the scope before the user commits.
dry_run: z.boolean().optional(),
})
/**
* Mark every posted, document-requiring verifikat that currently lacks an
* underlag AND matches the active list filters (period / series / date / search)
* as "Inget underlag krävs", across all pages, in one action. This is the
* scalable remedy for the "thousands of saknade underlag after a migration"
* problem; the per-entry batch route handles selective marking.
*
* The missing-doc predicate lives in resolveMissingUnderlagEntries (shared
* with the journal list's missing_underlag filter) and mirrors
* countVerifikatMissingDocument: posted + NEEDS_DOC source type, no
* current-version document_attachment, no anchored supplier-invoice reference,
* not already exempt.
*/
export const POST = withRouteContext(
'journal_entry.bulk_missing_no_document_required',
async (request, { supabase, companyId, user, log }) => {
const validation = await validateBody(request, BulkMissingSchema)
if (!validation.success) return validation.response
// All formats are enforced by the schema above, so these are already valid
// (or null). No re-validation needed before they reach the query layer.
const { period_id, reason, dry_run } = validation.data
let missing
try {
missing = await resolveMissingUnderlagEntries(
supabase,
companyId,
{
periodId: period_id ?? null,
series: validation.data.series ?? null,
dateFrom: validation.data.date_from ?? null,
dateTo: validation.data.date_to ?? null,
search: validation.data.search ?? null,
},
// No sorting here, so skip the per-row total_amount computed column
// on what can be a full post-import candidate scan.
{ idOnly: true },
)
} catch (err) {
if (err instanceof MissingUnderlagQueryError) {
// userMessage is already mapped through getErrorMessage() in the
// resolver: user-facing Swedish, never a raw driver message.
// The driver error goes to the log, same as the list route (#2395).
log.error('failed to resolve missing-underlag entries', err, { cause: err.cause })
return NextResponse.json({ error: err.userMessage }, { status: 400 })
}
throw err
}
const missingIds = missing.map((e) => e.id)
if (dry_run) {
return NextResponse.json({ data: { count: missingIds.length } })
}
if (missingIds.length === 0) {
return NextResponse.json({ data: { exempted: 0 } })
}
const exempted = await markEntriesNoDocRequired(
supabase,
companyId,
user.id,
missingIds,
reason ?? null,
)
return NextResponse.json({ data: { exempted } })
},
{ requireWrite: true },
)