Files
accounted/lib/api/validate.ts
T
Mattsson 5725c25bf1 Logs/improved logging (#398)
* feat(mcp): add create_transactions tool with /pending approval gate

New MCP tool gnubok_create_transactions stages 1–10 transactions per call
as pending_operations of type create_transaction (risk: medium). Each item
becomes its own card on /pending; on confirm, the executor inserts the row
into transactions with import_source='mcp' so MCP-staged ingestion is
distinguishable from PSD2 sync. Designed for skill workflows that pull
external data (e.g., Airtable) and want the user to gate the writes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(bas): strip concatenated group headers from corrupted account names

A chart-data import bug had glued the next group's header onto the last
account in each preceding group across all eight bas-data class files
(e.g. account 2670 read "Utgående moms på försäljning inom EU, OSS 27
PERSONALENS SKATTER, AVGIFTER OCH LÖNEAVDRAG"). The corrupted names
surface in transaction dropdowns, ledgers, SIE exports and årsredovisning,
and risk VAT miscategorization on the OSS (2670) and blandad-verksamhet
(6999) accounts specifically.

- Cleans 69 account_name and 64 description fields across class-1..8 files
- Adds a regression test asserting no name contains a concatenated header
- Ships an idempotent safety-net migration that updates already-seeded
  chart_of_accounts rows, gated on the corrupted string so user
  customizations are preserved

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(errors): add structured error codes and handling for various operations

- Introduced a new structured error registry in `structured-errors.ts` to standardize error handling across the application.
- Added Swedish and English messages for various error scenarios, including validation, authorization, and bookkeeping errors.
- Implemented a client-side error toast in `use-error-toast.ts` to display user-friendly error messages with remediation hints.
- Created a wrapper for recording operation outcomes in `record-operation.ts`, enhancing audit capabilities for operations.
- Developed a provider call wrapper in `with-provider-call.ts` to handle external HTTP calls with structured logging and error mapping.
- Added a new SQL migration to extend the processing history with new event types and aggregate types for better operational telemetry.

* Refactor supplier API routes to use context-based logging and error handling

- Replaced direct Supabase client usage in GET and POST routes with context-based approach using `withRouteContext`.
- Enhanced error handling to provide structured error responses for supplier creation and listing.
- Updated logging to include request IDs for better traceability.
- Introduced new error codes for supplier-related operations.
- Refactored tax deadlines cron job to utilize context and improved error handling.
- Updated ESLint configuration to enforce logging practices across API and lib directories.
- Enhanced arcim migration extension with structured error handling and logging.
- Added classification for provider errors to improve user-facing error messages.
- Introduced request ID in extension context for better log correlation.

* fix(route-context): update DynamicParams type for improved type safety in route handlers

* feat(transactions): add 'create_transaction' operation to PendingOperationType

* fix(route): ensure companyId is non-nullable in loadAndDeriveAbsence function

* fix(route-context): ensure companyId is always non-null by short-circuiting with COMPANY_CONTEXT_MISSING

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 11:12:02 +02:00

145 lines
3.4 KiB
TypeScript

import { z } from 'zod'
import { NextResponse } from 'next/server'
import type { Logger } from '@/lib/logger'
export interface ValidationSuccess<T> {
success: true
data: T
}
export interface ValidationFailure {
success: false
response: NextResponse
}
export type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure
interface ValidationOptions {
/** Optional logger; when present, validation failures are logged at warn level. */
log?: Logger
/** Identifier for the operation/route being validated, included in the log line. */
operation?: string
}
function logIssues(
options: ValidationOptions | undefined,
kind: 'body' | 'query' | 'json',
issues: Array<{ field: string; message: string; code: string }> | string,
) {
if (!options?.log) return
options.log.warn('validation failed', {
operation: options.operation,
kind,
...(typeof issues === 'string'
? { reason: issues }
: { issueCount: issues.length, issues }),
})
}
/**
* Validate a request body against a Zod schema.
*
* Returns `{ success: true, data }` on valid input, or
* `{ success: false, response }` with a 400 NextResponse on failure.
*
* Usage in an API route:
* ```ts
* const result = await validateBody(request, CreateInvoiceSchema)
* if (!result.success) return result.response
* const { data } = result
* ```
*/
export async function validateBody<T>(
request: Request,
schema: z.ZodType<T>,
options?: ValidationOptions,
): Promise<ValidationResult<T>> {
let body: unknown
try {
body = await request.json()
} catch {
logIssues(options, 'json', 'Invalid JSON in request body')
return {
success: false,
response: NextResponse.json(
{
error: 'Invalid JSON in request body',
type: 'validation_error',
},
{ status: 400 },
),
}
}
const result = schema.safeParse(body)
if (!result.success) {
const errors = result.error.issues.map((issue) => ({
field: issue.path.join('.'),
message: issue.message,
code: issue.code,
}))
logIssues(options, 'body', errors)
return {
success: false,
response: NextResponse.json(
{
error: 'Validation failed',
type: 'validation_error',
errors,
},
{ status: 400 },
),
}
}
return { success: true, data: result.data }
}
/**
* Validate query parameters (from URL searchParams) against a Zod schema.
*
* Usage:
* ```ts
* const params = validateQuery(request, VatDeclarationQuerySchema)
* if (!params.success) return params.response
* const { data } = params
* ```
*/
export function validateQuery<T>(
request: Request,
schema: z.ZodType<T>,
options?: ValidationOptions,
): ValidationResult<T> {
const url = new URL(request.url)
const raw = Object.fromEntries(url.searchParams.entries())
const result = schema.safeParse(raw)
if (!result.success) {
const errors = result.error.issues.map((issue) => ({
field: issue.path.join('.'),
message: issue.message,
code: issue.code,
}))
logIssues(options, 'query', errors)
return {
success: false,
response: NextResponse.json(
{
error: 'Invalid query parameters',
type: 'validation_error',
errors,
},
{ status: 400 },
),
}
}
return { success: true, data: result.data }
}