Files
khb_microservices/packages/accounting_automation/src/summary.ts

179 lines
8.4 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 { 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
), 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 h, 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");
}
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;
}