* feat(bookkeeping): dashboard deep link filters verifikat utan underlag server-side The dashboard "Verifikat utan underlag" card (and the push-notification link) pointed at /bookkeeping?missingUnderlag=true, but nothing read the param: the user landed on the plain unfiltered ledger. The existing "Visa saknade underlag" toggle also only filtered the already-fetched page, so it could not represent the badge count across pages. - lib/bookkeeping/missing-underlag.ts: shared resolver of "posted verifikat lacking underlag" (document-requiring source types, no current-version document, no anchored supplier-invoice reference per BFL 5 kap 7 §, no exemption), extracted from the bulk "Inget underlag krävs" route so list, bulk remedy and dashboard badge share one predicate. - GET /api/bookkeeping/journal-entries?missing_underlag=true: resolves the full missing set server-side, applies the active sort stack, pages it, and returns the full-set count, fetching page rows in id chunks so the "Alla" page size cannot blow the PostgREST URL limit. - JournalEntryList: the toggle is now server-backed (refetch on change, honest count in the dialog badge); client-side re-filtering against late-arriving attachment counts removed. Deep-link arrival turns the filter on and scopes the visit to all fiscal years in memory only, matching the all-years badge count without touching the saved preference. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bookkeeping): harden the saknade-underlag filter after skeptic review Three skeptic subagents refuted the first cut; this fixes every confirmed finding in one pass: - FyPicker: new suppressAutoRestore prop. The deep-link visit opens as "Alla räkenskapsår" in memory, and FyPicker's on-load restore of the persisted year (value === null) snapped the scope back right after load, desyncing the list from the all-years badge that launched it. Manual picks still persist as usual. - Voucher-label search: the resolver now carries the same parseVoucher OR-branch as the direct list path, so searching "A209" with the filter on finds verifikat A209 instead of silently returning 0 rows. - Staleness while the filter is on: batch exempt, the single-row "Inget underlag krävs" toggle, and a row gaining its first underlag now refetch in place so fixed rows leave the filtered list and the count stays honest (the pre-server-filter behavior). The attachment-driven refetch is guarded per entry id against predicate-disagreement loops. - Drafts view: the filter switch is disabled there; the predicate is posted-only and the badge would mislabel the draft count. - Perf: the bulk-exempt route resolves ids only, skipping the per-row total_amount computed column on its full post-import candidate scan. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bookkeeping): keep the underlag resolver statically checkable The skeptic-fix commit tripped the phantom-column scanner ceiling (tests/schema/no-phantom-columns.test.ts, 382 > 380): a computed select() string and a runtime-built .or() are expressions the scanner cannot resolve against the schema. Restructured instead of raising the ceiling: the idOnly/full column choice is two literal select() calls behind a lazy branch, and a voucher-label search fans out to two statically-checkable candidate queries (description ilike, series+number eq) unioned by id, same semantics as before. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
110 lines
4.0 KiB
TypeScript
110 lines
4.0 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 }) => {
|
|
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.
|
|
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 },
|
|
)
|