Files
khb_microservices/packages/accounting_automation/src/summary.ts
Yuri Yaryshev 74ffe8613b accounting_automation: сверка инвойсов с QuickBooks (invoice-reconcile), оплата независима от согласования, сумма и вендор из ленты, сводка Анастасии, правки finalize, поиска чека, проверки инвойса, chargeback; документы
Миграция 071: acc_discrepancies.reason и уникальный индекс открытых расхождений, уникальный открытый card_fraud по операции, insurer в разборе сертификатов.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 19:43:58 +03:00

247 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { Pool } from "khb_common";
import type { SlackApi, SlackPoster } from "./slack.js";
/** Ежедневная сводка ассистента (процесс «Ежедневная сводка ассистента»). */
export interface SummaryOptions {
/** Ссылка на Mathesar (очередь ручного разбора). */
mathesarUrl?: string;
/** Ссылка на ленту банка QuickBooks (для строки по категоризации). */
bankFeedUrl?: string;
/** Нерабочие дни (YYYY-MM-DD) помимо суббот и воскресений. */
nonWorkdays?: ReadonlySet<string>;
}
function plural(n: number, one: string, few: string, many: string): string {
const a = Math.abs(n) % 100;
const b = a % 10;
if (a > 10 && a < 20) return many;
if (b === 1) return one;
if (b >= 2 && b <= 4) return few;
return many;
}
const tasks = (n: number) => `${n} ${plural(n, "задача", "задачи", "задач")}`;
/** Локальная дата YYYY-MM-DD в часовом поясе tz. */
function localDate(d: Date, tz: string): string {
const parts = new Intl.DateTimeFormat("en-US", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(d);
const get = (t: string) => parts.find((p) => p.type === t)!.value;
return `${get("year")}-${get("month")}-${get("day")}`;
}
function ruDate(iso: string): string {
const [y, m, d] = iso.split("-");
return `${d}.${m}.${y}`;
}
function isWorkday(d: Date, tz: string, non: ReadonlySet<string>): boolean {
const wd = new Intl.DateTimeFormat("en-US", { timeZone: tz, weekday: "short" }).format(d);
return wd !== "Sat" && wd !== "Sun" && !non.has(localDate(d, tz));
}
/** Момент, на 2 рабочих дня раньше now: задачи, созданные раньше, ждут больше 2 рабочих дней. */
export function twoWorkdaysAgo(now: Date, tz: string, non: ReadonlySet<string> = new Set()): Date {
let d = new Date(now.getTime());
let n = 0;
while (n < 2) {
d = new Date(d.getTime() - 24 * 3600_000);
if (isWorkday(d, tz, non)) n++;
}
return d;
}
function duration(seconds: number): string {
const min = Math.round(seconds / 60);
if (min < 60) return `${min} мин`;
const h = Math.floor(min / 60);
const m = min % 60;
if (h < 48) return m === 0 ? `${h} ч` : `${h} ч ${m} мин`;
const days = Math.floor(h / 24);
return `${days} дн ${h % 24} ч`;
}
const KIND_LABEL: Record<string, string> = { invoice: "инвойсы", categorization: "категоризация", certificate: "сертификаты" };
const ROLE_LABEL: Record<string, string> = { accountant: "бухгалтер (accountant)", cfo: "Анастасия (cfo)" };
export async function buildDailySummary(pool: Pool, now: Date, tz: string, opts: SummaryOptions = {}): Promise<string> {
const today = localDate(now, tz);
const yesterdayInstant = new Date(now.getTime() - 24 * 3600_000);
const yesterday = localDate(yesterdayInstant, tz);
const old = twoWorkdaysAgo(now, tz, opts.nonWorkdays);
const hasProblem = "(problem_highlight is not null and btrim(problem_highlight) <> '')";
const queue = await pool.query(
`select kind, assignee_role,
count(*)::int as n,
count(*) filter (where ${hasProblem})::int as problems,
count(*) filter (where created_at < $2)::int as old,
count(*) filter (where problem_highlight ~* 'жд[её]т документ')::int as wait_doc,
count(*) filter (where problem_highlight ~* 'дубл')::int as dup,
count(*) filter (where problem_highlight ~* 'нужен человек')::int as human
from acc_manual_review
where snoozed_until is null or snoozed_until <= $1
group by kind, assignee_role`,
[now, old],
);
const snoozed = (await pool.query("select count(*)::int n from acc_manual_review where snoozed_until > $1", [now])).rows[0].n as number;
const byKind = new Map<string, { n: number; problems: number }>();
const byRole = new Map<string, number>();
let total = 0;
let oldCount = 0;
let waitDoc = 0;
let dup = 0;
let human = 0;
for (const r of queue.rows) {
const k = KIND_LABEL[r.kind] ? r.kind : "other";
const cur = byKind.get(k) ?? { n: 0, problems: 0 };
cur.n += r.n;
cur.problems += r.problems;
byKind.set(k, cur);
byRole.set(r.assignee_role, (byRole.get(r.assignee_role) ?? 0) + r.n);
total += r.n;
oldCount += r.old;
if (r.kind === "categorization") {
waitDoc += r.wait_doc;
dup += r.dup;
human += r.human;
}
}
const lines: string[] = [];
lines.push(`Сводка бухгалтерского помощника на ${ruDate(today)}`);
lines.push("");
lines.push(`В очереди ручного разбора: ${tasks(total)}`);
for (const k of ["invoice", "categorization", "certificate", "other"]) {
const v = byKind.get(k);
if (k === "other" && !v) continue;
const label = k === "other" ? "прочие" : KIND_LABEL[k]!;
lines.push(`- ${label}: ${v?.n ?? 0}, из них с проблемой: ${v?.problems ?? 0}`);
}
const roles = [...byRole.keys()].sort();
for (const role of ["accountant", "cfo"]) if (!roles.includes(role)) roles.push(role);
lines.push(`Ждут по ролям: ${roles.map((r) => `${ROLE_LABEL[r] ?? r} - ${byRole.get(r) ?? 0}`).join("; ")}`);
if (snoozed > 0) lines.push(`Отложено до даты повторного показа: ${snoozed}`);
lines.push(`Категоризация: ждёт документ - ${waitDoc}; подозрение на дубль - ${dup}; нужен человек - ${human}${opts.bankFeedUrl ? ` (лента банка: ${opts.bankFeedUrl})` : ""}`);
if (opts.mathesarUrl) lines.push(`Очередь в Mathesar: ${opts.mathesarUrl}`);
// Сводка за вчера: границы суток в tz.
const hist = await pool.query(
`with h as (
select closed_by, closed_at, created_at, changed_fields from acc_invoices_review_history
union all select closed_by, closed_at, created_at, changed_fields from acc_categorization_review_history
union all select closed_by, closed_at, created_at, changed_fields from acc_certificates_review_history
), named as (
-- closed_by хранит id человека (person.id); в сводке выводится его имя, неизвестное значение остаётся как есть
select coalesce(p.display_name, h.closed_by) as closed_by, h.closed_at, h.created_at, h.changed_fields
from h left join person p on p.id::text = h.closed_by
), bounds as (
select (date_trunc('day', $1::timestamptz at time zone $2) - interval '1 day') at time zone $2 as s,
date_trunc('day', $1::timestamptz at time zone $2) at time zone $2 as e
)
select coalesce(closed_by, '') as closed_by,
count(*)::int as n,
count(*) filter (where coalesce(changed_fields, '{}'::jsonb) = '{}'::jsonb)::int as clean,
coalesce(sum(extract(epoch from (closed_at - created_at))), 0)::float8 as secs
from named, bounds where closed_at >= s and closed_at < e
group by 1 order by n desc, 1`,
[now, tz],
);
const closed = hist.rows.reduce((a, r) => a + r.n, 0);
const clean = hist.rows.reduce((a, r) => a + r.clean, 0);
const secs = hist.rows.reduce((a, r) => a + r.secs, 0);
lines.push("");
lines.push(`За вчера (${ruDate(yesterday)}):`);
if (closed === 0) {
lines.push("- закрытых задач не было");
} else {
const who = hist.rows.map((r) => `${r.closed_by === "" ? "кто не указан" : r.closed_by} - ${r.n}`).join(", ");
lines.push(`- закрыто: ${tasks(closed)} (${who})`);
lines.push(`- закрыто без правок автомата: ${clean} из ${closed} (${Math.round((clean / closed) * 100)}%)`);
lines.push(`- среднее время от создания задачи до закрытия: ${duration(secs / closed)}`);
}
lines.push(`- ждут больше 2 рабочих дней: ${oldCount}`);
return lines.join("\n");
}
/**
* Сводка Анастасии отдельным сообщением (процесс «Ежедневная сводка ассистента», шаг 4): проведено вчера, ждёт подтверждения
* (по ролям), без документа, подозрение на дубль; ссылки на Mathesar и ленту банка QuickBooks, если заданы.
*/
export async function buildCfoSummary(pool: Pool, now: Date, tz: string, opts: SummaryOptions = {}): Promise<string> {
const today = localDate(now, tz);
const yesterday = localDate(new Date(now.getTime() - 24 * 3600_000), tz);
const roleRows = await pool.query<{ assignee_role: string; n: number }>(
"select assignee_role, count(*)::int as n from acc_manual_review where snoozed_until is null or snoozed_until <= $1 group by assignee_role",
[now],
);
const byRole = new Map(roleRows.rows.map((r) => [r.assignee_role, r.n]));
const cat = (
await pool.query<{ wait_doc: number; dup: number }>(
`select count(*) filter (where problem_highlight ~* 'жд[её]т документ')::int as wait_doc,
count(*) filter (where problem_highlight ~* 'дубл')::int as dup
from acc_manual_review where kind = 'categorization' and (snoozed_until is null or snoozed_until <= $1)`,
[now],
)
).rows[0]!;
const posted = (
await pool.query<{ n: number; total: number }>(
`with bounds as (
select (date_trunc('day', $1::timestamptz at time zone $2) - interval '1 day') at time zone $2 as s,
date_trunc('day', $1::timestamptz at time zone $2) at time zone $2 as e)
select count(*)::int as n, coalesce(sum(f.amount), 0)::float8 as total
from acc_categorization_review_history h left join acc_feed_txn f on f.feed_txn_id = h.feed_txn_id, bounds
where h.closed_at >= s and h.closed_at < e`,
[now, tz],
)
).rows[0]!;
const roles = [...byRole.keys()].sort();
for (const role of ["accountant", "cfo"]) if (!roles.includes(role)) roles.push(role);
const lines = [
`Анастасия, сводка бухгалтерского помощника на ${ruDate(today)}`,
"",
`Проведено вчера (${ruDate(yesterday)}): ${posted.n} ${plural(posted.n, "операция", "операции", "операций")}${posted.n > 0 && posted.total > 0 ? ` на $${posted.total.toFixed(2)}` : ""}`,
`Ждёт подтверждения по ролям: ${roles.map((r) => `${ROLE_LABEL[r] ?? r} - ${byRole.get(r) ?? 0}`).join("; ")}`,
`Без документа: ${cat.wait_doc}`,
`Подозрение на дубль: ${cat.dup}`,
];
if (opts.mathesarUrl) lines.push(`Очередь в Mathesar: ${opts.mathesarUrl}`);
if (opts.bankFeedUrl) lines.push(`Лента банка QuickBooks: ${opts.bankFeedUrl}`);
return lines.join("\n");
}
export interface PostSummaryDeps {
pool: Pool;
slack: SlackPoster;
/** Канал бухгалтерии (settings.slack.accountingChannelId). */
channelId: string;
now?: () => Date;
/** Часовой пояс сводки, например "Asia/Nicosia" (10:00 по Кипру). */
tz: string;
options?: SummaryOptions;
}
/** Строит сводку и отправляет в канал бухгалтерии; возвращает отправленный текст. */
export async function postDailySummary(deps: PostSummaryDeps): Promise<string> {
const text = await buildDailySummary(deps.pool, (deps.now ?? (() => new Date()))(), deps.tz, deps.options);
await deps.slack.post(deps.channelId, text);
return text;
}
/**
* Отдельное личное сообщение Slack Анастасии (person с role_code cfo и slack_user_id), как недельный отчёт «Поиска чека».
* Нет такого человека или сбой отправки - причина в результате, канальная сводка от этого не страдает.
*/
export async function postCfoSummary(deps: Omit<PostSummaryDeps, "slack" | "channelId"> & { slack: Pick<SlackApi, "postMessage"> }): Promise<{ sent: boolean; reason?: string }> {
const { rows } = await deps.pool.query<{ slack_user_id: string }>(
"select slack_user_id from person where role_code = 'cfo' and is_active and slack_user_id is not null order by display_name limit 1",
);
if (!rows[0]) return { sent: false, reason: "у Анастасии (person.role_code = cfo) нет slack_user_id" };
try {
const text = await buildCfoSummary(deps.pool, (deps.now ?? (() => new Date()))(), deps.tz, deps.options);
await deps.slack.postMessage(rows[0].slack_user_id, text);
return { sent: true };
} catch (e) {
return { sent: false, reason: e instanceof Error ? e.message : String(e) };
}
}