@@ -3,7 +3,7 @@ import { extname, join, normalize } from "node:path";
import Fastify , { type FastifyInstance , type FastifyReply , type FastifyRequest } from "fastify" ;
import { withTx , type Logger , type Pool } from "khb_common" ;
import { z } from "zod" ;
import { AuthError , createAuth , type Actor , type JwtVerifier } from "./auth.js" ;
import { AuthError , actorOf , createAuth , safeEqual , type Actor , type JwtVerifier } from "./auth.js" ;
import { LOOKUP , getApproves , getContractPanel , getDetails , getInvoice , listInvoices , recomputeApproved , type ListItem } from "./repo.js" ;
import {
QUICK_FILTERS , STATUS_LABELS , canCancel , canMarkPaid , canReturnToDraft , canSendToBank , canView , dayInTz , editableFields , errorsOf , isStaff , matchesFilter , normResult , statusOf , submitProblems ,
@@ -100,9 +100,19 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
// контекст автора для журнала: в каждом запросе свой, заполняется после входа
app . addHook ( "onRequest" , ( _req , _reply , done ) = > { auditStore . run ( { } , done ) ; } ) ;
const need = async ( req : FastifyRequest ) : Promise < Actor > = > {
const a = await authenticate ( req . headers . authorization , typeof req . headers [ "x-acting-role" ] === "string" ? req . headers [ "x-acting-role" ] : undefined ) ;
const acting = typeof req . headers [ "x-acting-role" ] === "string" ? req . headers [ "x-acting-role" ] : undefined ;
const internal = req . headers [ "x-internal-token" ] ;
let a : Actor ;
let via = "" ;
if ( typeof internal === "string" && settings . auth . internalToken ) {
// MCP (accounting_automation): уже аутентифицированный человек, е г о id передаётся заголовком
const pid = req . headers [ "x-person-id" ] ;
if ( ! safeEqual ( internal , settings . auth . internalToken ) || typeof pid !== "string" || ! uuid . safeParse ( pid ) . success ) throw new AuthError ( "внутренний токен не принят" , 401 ) ;
a = await actorOf ( rawPool , pid , acting ) ;
via = ` via ${ String ( req . headers [ "x-via" ] ? ? "mcp" ) . slice ( 0 , 60 ) } ` ;
} else a = await authenticate ( req . headers . authorization , acting ) ;
const st = auditStore . getStore ( ) ;
if ( st ) Object . assign ( st , { actorId : a.personId , actorName : a.displayName , actingRole : a.acting , action : ` ${ req . method } ${ req . routeOptions ? . url ? ? req . url } ` } ) ;
if ( st ) Object . assign ( st , { actorId : a.personId , actorName : a.displayName , actingRole : a.acting , action : ` ${ req . method } ${ req . routeOptions ? . url ? ? req . url } ${ via } ` } ) ;
return a ;
} ;
const fail = ( reply : FastifyReply , status : number , error : string ) = > reply . code ( status ) . send ( { error } ) ;
@@ -171,6 +181,39 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
return { items : rows } ;
} ) ;
/** Общий журнал и е г о разбор (бухгалтерия): фильтры по инвойсу, автору, действию, таблице, полю, периоду; group - счётчики вместо строк. */
app . get ( "/api/log" , async ( req , reply ) = > {
const a = await need ( req ) ;
if ( ! isStaff ( a ) ) return fail ( reply , 403 , "журнал доступен бухгалтерии" ) ;
const q = z . object ( {
invoice_id : uuid.optional ( ) , actor : z.string ( ) . max ( 100 ) . optional ( ) , action : z.string ( ) . max ( 100 ) . optional ( ) ,
tbl : z.enum ( [ "acc_invoices" , "acc_invoices_details" , "acc_invoices_approves" ] ) . optional ( ) , field : z.string ( ) . max ( 60 ) . optional ( ) ,
since : z.string ( ) . max ( 40 ) . optional ( ) , until : z.string ( ) . max ( 40 ) . optional ( ) , system_only : z.enum ( [ "true" , "false" ] ) . optional ( ) ,
group : z.enum ( [ "actor" , "action" , "invoice" , "day" ] ) . optional ( ) , limit : z.coerce.number ( ) . int ( ) . min ( 1 ) . max ( 500 ) . default ( 100 ) ,
} ) . parse ( req . query ) ;
const w : string [ ] = [ ] ;
const v : unknown [ ] = [ ] ;
const add = ( sql : string , val : unknown ) = > { v . push ( val ) ; w . push ( sql . replace ( "?" , "$" + v . length ) ) ; } ;
if ( q . invoice_id ) add ( "l.invoice_id = ?" , q . invoice_id ) ;
if ( q . actor ) add ( "l.actor_name ilike ?" , "%" + q . actor + "%" ) ;
if ( q . action ) add ( "l.action ilike ?" , "%" + q . action + "%" ) ;
if ( q . tbl ) add ( "l.tbl = ?" , q . tbl ) ;
if ( q . field ) add ( "jsonb_exists(l.changes, ?)" , q . field ) ;
if ( q . since ) add ( "l.at >= ?::timestamptz" , q . since ) ;
if ( q . until ) add ( "l.at < ?::timestamptz" , q . until ) ;
if ( q . system_only === "true" ) w . push ( "l.actor_id is null" ) ;
const where = w . length ? "where " + w . join ( " and " ) : "" ;
if ( q . group ) {
const key = { actor : "coalesce(l.actor_name, 'система (' || l.db_user || ')')" , action : "coalesce(l.action, 'вне WebUI')" , invoice : "l.invoice_id::text" , day : "(l.at at time zone 'America/New_York')::date::text" } [ q . group ] ;
const rows = ( await pool . query ( ` select ${ key } as key, count(*)::int as events, min(l.at) as first_at, max(l.at) as last_at from acc_invoices_log l ${ where } group by 1 order by events desc limit ${ q . limit } ` , v ) ) . rows ;
return { items : rows } ;
}
const rows = ( await pool . query (
` select l.id, l.at, l.invoice_id, i.vendor_name, i.invoice_number, l.tbl, l.op, l.actor_name, l.acting_role, l.action, l.db_user, l.changes
from acc_invoices_log l left join acc_invoices i on i.id = l.invoice_id ${ where } order by l.id desc limit ${ q . limit } ` , v ) ) . rows ;
return { items : rows } ;
} ) ;
/* ------------------------------------------------------------- создание */
app . post ( "/api/invoices" , async ( req , reply ) = > {
const a = await need ( req ) ;