import type { Pool } from "khb_common"; import type { SlackPoster } from "./slack.js"; /** * «Разбор истории правок» (раздел «Завершение ручного разбора», задание `history-weekly`, раз в неделю): * анализ *_history за неделю - какие поля люди правят чаще всего, у каких вендоров и проектов, доля записей без правок, * повторяющиеся правки как кандидаты в правила. Текст отчёта детерминированный (SQL + шаблон), Claude не нужен. */ interface Source { table: string; label: string; /** SQL-выражение вендора и проекта строки history. */ vendor: string; project: string | null; } const SOURCES: Source[] = [ { table: "acc_invoices_review_history", label: "Инвойсы", vendor: "coalesce(vendor_name, '(не указан)')", project: "project_customer_id" }, { table: "acc_categorization_review_history", label: "Категоризация банка", vendor: "coalesce(suggestion ->> 'vendor_name', '(не указан)')", project: "suggestion ->> 'project_customer_id'" }, { table: "acc_certificates_review_history", label: "Сертификаты", vendor: "coalesce(vendor_name, '(не указан)')", project: null }, ]; export interface HistoryStats { label: string; total: number; unchanged: number; fields: { field: string; n: number }[]; vendors: { vendor: string; changed: number; total: number }[]; projects: { project: string; changed: number }[]; candidates: { text: string; n: number }[]; } export interface HistoryReport { from: string; to: string; text: string; stats: HistoryStats[]; } const CHANGED = "(changed_fields is not null and changed_fields <> '{}'::jsonb)"; const pct = (a: number, b: number): string => (b === 0 ? "0" : String(Math.round((100 * a) / b))); const ru = (iso: string): string => `${iso.slice(8, 10)}.${iso.slice(5, 7)}.${iso.slice(0, 4)}`; const quote = (v: unknown): string => (v === null || v === undefined || v === "" ? "(пусто)" : `«${String(v).slice(0, 60)}»`); async function analyze(pool: Pool, s: Source, from: Date, minRepeat: number): Promise { const t = await pool.query<{ total: number; unchanged: number }>( `select count(*)::int as total, count(*) filter (where not ${CHANGED})::int as unchanged from ${s.table} where closed_at >= $1`, [from], ); const fields = await pool.query<{ field: string; n: number }>( `select k as field, count(*)::int as n from ${s.table}, jsonb_object_keys(coalesce(changed_fields, '{}'::jsonb)) k where closed_at >= $1 group by k order by n desc, k limit 8`, [from], ); const vendors = await pool.query<{ vendor: string; changed: number; total: number }>( `select ${s.vendor} as vendor, (count(*) filter (where ${CHANGED}))::int as changed, count(*)::int as total from ${s.table} where closed_at >= $1 group by 1 having count(*) filter (where ${CHANGED}) > 0 order by changed desc, vendor limit 5`, [from], ); const projects = s.project ? await pool.query<{ project: string; changed: number }>( `select coalesce((select q.display_name from qbo_customer q where q.id = p.pid limit 1), p.pid, '(не указан)') as project, count(*)::int as changed from (select ${s.project} as pid from ${s.table} where closed_at >= $1 and ${CHANGED}) p group by p.pid order by changed desc, project limit 5`, [from], ) : { rows: [] as { project: string; changed: number }[] }; const candidates: { text: string; n: number }[] = []; if (s.table === "acc_categorization_review_history") { const c = await pool.query<{ vendor: string; sub: string; old_v: string | null; new_v: string | null; n: number }>( `select ${s.vendor} as vendor, sub, changed_fields -> 'suggestion' -> 'old' ->> sub as old_v, changed_fields -> 'suggestion' -> 'new' ->> sub as new_v, count(*)::int as n from ${s.table} cross join unnest(array['account', 'project_customer_id']) sub where closed_at >= $1 and changed_fields ? 'suggestion' and changed_fields -> 'suggestion' -> 'old' ->> sub is distinct from changed_fields -> 'suggestion' -> 'new' ->> sub group by 1, 2, 3, 4 having count(*) >= $2 order by n desc limit 10`, [from, minRepeat], ); for (const r of c.rows) { const what = r.sub === "account" ? "счёт" : "проект"; candidates.push({ n: r.n, text: `у «${r.vendor}» автомат ставит ${what} ${quote(r.old_v)}, люди исправляют на ${quote(r.new_v)} (${r.n} раз): правило для промпта категоризации` }); } } else { const c = await pool.query<{ vendor: string; field: string; new_v: string | null; n: number }>( `select ${s.vendor} as vendor, k as field, changed_fields -> k ->> 'new' as new_v, count(*)::int as n from ${s.table}, jsonb_object_keys(coalesce(changed_fields, '{}'::jsonb)) k where closed_at >= $1 group by 1, 2, 3 having count(*) >= $2 order by n desc limit 10`, [from, minRepeat], ); for (const r of c.rows) candidates.push({ n: r.n, text: `у «${r.vendor}» поле ${r.field} исправляют на ${quote(r.new_v)} (${r.n} раз): правило распознавания` }); } return { label: s.label, total: t.rows[0]!.total, unchanged: t.rows[0]!.unchanged, fields: fields.rows, vendors: vendors.rows, projects: projects.rows, candidates }; } export async function buildHistoryReport(pool: Pool, now: Date, opts: { days?: number; minRepeat?: number } = {}): Promise { const days = opts.days ?? 7; const from = new Date(now.getTime() - days * 86_400_000); const stats: HistoryStats[] = []; for (const s of SOURCES) stats.push(await analyze(pool, s, from, opts.minRepeat ?? 3)); const fromIso = from.toISOString().slice(0, 10); const toIso = now.toISOString().slice(0, 10); const total = stats.reduce((a, x) => a + x.total, 0); const unchanged = stats.reduce((a, x) => a + x.unchanged, 0); const lines: string[] = [`Разбор истории правок за неделю ${ru(fromIso)} - ${ru(toIso)}.`]; if (total === 0) { lines.push("За неделю не закрыто ни одной записи ручного разбора: анализировать нечего."); } else { lines.push(`Закрыто записей: ${total}, принято без изменений: ${unchanged} (${pct(unchanged, total)}%).`); for (const x of stats) { if (x.total === 0) continue; lines.push("", `${x.label}: закрыто ${x.total}, без изменений ${x.unchanged} (${pct(x.unchanged, x.total)}%).`); if (x.fields.length) lines.push(` Чаще всего правят поля: ${x.fields.map((f) => `${f.field} (${f.n})`).join(", ")}.`); if (x.vendors.length) lines.push(` Вендоры с правками: ${x.vendors.map((v) => `${v.vendor} (${v.changed} из ${v.total})`).join(", ")}.`); if (x.projects.length) lines.push(` Проекты с правками: ${x.projects.map((p) => `${p.project} (${p.changed})`).join(", ")}.`); } const all = stats.flatMap((x) => x.candidates.map((c) => ({ label: x.label, ...c }))).sort((a, b) => b.n - a.n); lines.push(""); if (all.length === 0) lines.push("Кандидатов в правила нет: повторяющихся правок не найдено."); else { lines.push("Кандидаты в правила (повторяющиеся правки):"); for (const c of all) lines.push(`- ${c.label}: ${c.text}`); lines.push("Решить, что принять: править промпт категоризации в Google Drive или правила распознавания."); } } return { from: fromIso, to: toIso, text: lines.join("\n"), stats }; } export interface HistoryWeeklyDeps { pool: Pool; slack: SlackPoster; channelId: string; now?: () => Date; } export async function runHistoryWeekly(deps: HistoryWeeklyDeps): Promise<{ sent: true; total: number; candidates: number }> { const rep = await buildHistoryReport(deps.pool, (deps.now ?? (() => new Date()))()); await deps.slack.post(deps.channelId, rep.text); return { sent: true, total: rep.stats.reduce((a, x) => a + x.total, 0), candidates: rep.stats.reduce((a, x) => a + x.candidates.length, 0) }; }