import UAParser from 'ua-parser-js'; import { prisma, effectiveKind } from '../db.js'; import { timeParts } from './time.js'; function parseUA(ua) { if (!ua) return {}; const r = new UAParser(ua).getResult(); const type = r.device.type; // mobile | tablet | undefined (desktop) return { browser: r.browser.name || 'Другое', os: r.os.name ? `${r.os.name}${r.os.version ? ' ' + r.os.version.split('.')[0] : ''}` : 'Другое', device: type === 'mobile' ? 'Телефон' : type === 'tablet' ? 'Планшет' : 'Компьютер', }; } export function clientIp(req) { return (req.ip || '').replace(/^::ffff:/, '') || null; } /** Записать событие в журнал. Никогда не бросает исключения. */ export async function logEvent(req, type, { userId, userKind, bookId, query, resultCount, meta, organizationId } = {}) { try { const ua = req?.headers?.['user-agent']?.slice(0, 400) || null; await prisma.event.create({ data: { type, // организация: явно (вход, регистрация) или из сессии; владелец платформы — null organizationId: organizationId !== undefined ? organizationId : req?.user?.organizationId ?? null, userId: userId ?? req?.user?.id ?? null, userKind: userKind ?? (req?.user && (userId == null || userId === req.user.id) ? effectiveKind(req.user) : null), bookId: bookId ?? null, query: query ?? null, resultCount: resultCount ?? null, ip: req ? clientIp(req) : null, userAgent: ua, ...parseUA(ua), meta: meta ? JSON.stringify(meta) : null, ...timeParts(), }, }); } catch (e) { console.error('logEvent failed:', e.message); } }