import type { Logger, Pool } from "khb_common"; import { addressKey, normalizeAddress } from "./invoices-mail.js"; import { upsertSearchTask } from "./receipts.js"; import type { SlackApi } from "./slack.js"; import { workdaysBetween } from "./workdays.js"; /** * Процесс «Поиск чека» (docs/proposed/modules/quickbooks_bookkeeper/processes.md): * ежедневно (шаги 1-3, 6), еженедельный отчёт (шаг 9), согласие Анастасии на расход без чека (шаг 8). * Приём ответов сотрудника (шаги 4-5, 7) - в receipts.ts (тот же job, что принимает чеки). */ export interface SearchOptions { tz: string; /** Сколько рабочих дней операция ждёт документ до начала поиска. */ graceWorkdays: number; /** Рабочих дней после первого вопроса до: напоминания, руководителя, Юли, Анастасии. */ escalationWorkdays: readonly [number, number, number, number]; /** Постоянные подписки (часть названия вендора): пропускаются. */ subscriptionVendors: readonly string[]; /** * Ссылка на банковские операции QuickBooks. Если содержит {feed_txn_id}, подставляется id операции (ссылка на конкретную операцию); * иначе это общая ссылка, а операция описывается id, суммой и датой. */ qboBankingUrl: string; } export interface SearchDeps { pool: Pool; slack: SlackApi; now(): Date; log: Logger; nonWorkdays(): Promise>; options: SearchOptions; } export interface SearchResult { /** Заведено поисков чека. */ created: number; /** Из них ответственный не найден (задача Юле). */ noResponsible: number; /** Пропущено как постоянные подписки. */ subscriptions: number; /** Задано первых вопросов (включая повторные после сбоя Slack). */ asked: number; /** Подняты по цепочке: напоминание, руководитель, Юля, Анастасия. */ escalated: [number, number, number, number]; /** Закрыто: операция уже закрыта в разборе. */ closed: number; errors: number; } interface Person { id: string; display_name: string; slack_user_id: string | null; role_code: string | null; } interface Ask { channel: string; ts: string; person_id: string; level: number; } interface SearchRow { id: string; feed_txn_id: string; responsible_person_id: string | null; escalation_level: number; created_at: Date; last_asked_at: Date | null; answer: string | null; txn_date: string | null; amount: string | null; vendor_name: string | null; card_or_account: string | null; project_customer_id: string | null; asks: Ask[]; approved_without_receipt_at: Date | null; } const money = (n: number | string): string => `$${Number(n).toFixed(2)}`; const PERSON_COLS = "p.id, p.display_name, p.slack_user_id, p.role_code"; // ----------------------------------------------------------------- кого спросить (шаг 2) async function personById(pool: Pool, id: string | null): Promise { if (!id) return null; const { rows } = await pool.query(`select ${PERSON_COLS} from person p where p.id = $1 and p.is_active`, [id]); return rows[0] ?? null; } async function cardHolder(pool: Pool, card: string | null): Promise { if (!card) return null; const { rows } = await pool.query( `select ${PERSON_COLS} from acc_card_holders h join person p on p.id = h.person_id where p.is_active and (h.card_or_account = $1 or right(h.card_or_account, 4) = right($1, 4)) limit 1`, [card], ); return rows[0] ?? null; } /** Менеджер проекта в JobTread: проект QuickBooks сопоставляется с работой JobTread по адресу. */ async function projectManager(pool: Pool, projectCustomerId: string | null): Promise { if (!projectCustomerId) return null; const c = await pool.query<{ display_name: string; fully_qualified_name: string | null }>("select display_name, fully_qualified_name from qbo_customer where id = $1 limit 1", [projectCustomerId]); if (!c.rows[0]) return null; const names = [c.rows[0].display_name, c.rows[0].fully_qualified_name].filter((x): x is string => !!x); const jobs = await pool.query<{ name: string; manager_person_id: string }>( "select j.name, ap.manager_person_id from jt_job j join assistant_project ap on ap.jt_job_id = j.id where ap.is_enabled", ); const hit = jobs.rows.find((j) => names.some((n) => { const a = addressKey(n); return (a !== null && a === addressKey(j.name)) || normalizeAddress(n) === normalizeAddress(j.name); }), ); return hit ? personById(pool, hit.manager_person_id) : null; } /** * Руководитель по роли: строительные менеджеры и остальные подчиняются Артуру (role_code ceo), отдел финансов (accountant, в том числе Юля) * - Анастасии (cfo); у Артура и Анастасии вышестоящий - владелец Дмитрий (owner); у владельца руководителя нет. */ export async function supervisorOf(pool: Pool, person: Person): Promise { const target: Record = { owner: null, ceo: "owner", cfo: "owner", accountant: "cfo", construction_manager: "ceo", employee: "ceo", it: "ceo" }; const role = person.role_code && person.role_code in target ? target[person.role_code] : "ceo"; if (!role) return null; const { rows } = await pool.query(`select ${PERSON_COLS} from person p where p.role_code = $1 and p.is_active and p.id <> $2 order by p.display_name limit 1`, [role, person.id]); return rows[0] ?? null; } /** Первым спрашивают держателя карты; нет держателя - менеджера проекта. Нужен Slack, иначе спросить нечем. */ async function findResponsible(pool: Pool, card: string | null, projectId: string | null): Promise<{ person: Person | null; reason: string }> { const holder = await cardHolder(pool, card); if (holder?.slack_user_id) return { person: holder, reason: "" }; const pm = await projectManager(pool, projectId); if (pm?.slack_user_id) return { person: pm, reason: "" }; if (holder) return { person: null, reason: `у держателя карты ${holder.display_name} нет Slack` }; if (pm) return { person: null, reason: `у менеджера проекта ${pm.display_name} нет Slack` }; return { person: null, reason: card ? `держатель карты «${card}» не найден (acc_card_holders), менеджер проекта не определён` : "карта операции неизвестна, менеджер проекта не определён" }; } // ----------------------------------------------------------------- вопросы в Slack async function vendorProjectHint(pool: Pool, vendor: string | null): Promise { if (!vendor) return ""; const { rows } = await pool.query<{ customer_name: string; n: string }>( `select l.customer_name, count(*) as n from qbo_purchase p join qbo_purchase_line l on l.realm_id = p.realm_id and l.purchase_id = p.id where lower(p.entity_name) = lower($1) and l.customer_name is not null group by l.customer_name order by n desc limit 2`, [vendor], ); const top = rows[0]; if (!top) return ""; const total = rows.reduce((s, r) => s + Number(r.n), 0); return Number(top.n) >= 3 && Number(top.n) / total >= 0.8 ? `\nПодсказка: этот вендор обычно относится к проекту ${top.customer_name}.` : ""; } /** Строка со ссылкой на операцию в QuickBooks: конкретная ссылка (по шаблону) либо общая ссылка плюс id, сумма и дата операции. */ export function operationLine(url: string, s: { feed_txn_id: string; amount: string | null; txn_date: string | null }): string { if (url.includes("{feed_txn_id}")) return `Операция в QuickBooks: ${url.split("{feed_txn_id}").join(encodeURIComponent(s.feed_txn_id))}`; const parts = [`id операции ${s.feed_txn_id}`, s.amount != null ? money(s.amount) : null, s.txn_date ? String(s.txn_date).slice(0, 10) : null].filter(Boolean); return `Операция в QuickBooks: ${url} (${parts.join(", ")})`; } const describeOp = (s: SearchRow): string => `${s.amount != null ? money(s.amount) : "сумма неизвестна"}, ${s.vendor_name ?? "вендор неизвестен"}${s.txn_date ? `, ${String(s.txn_date).slice(0, 10)}` : ""}${s.card_or_account ? `, карта ••${s.card_or_account.slice(-4)}` : ""}`; async function sendAsk(deps: SearchDeps, s: SearchRow, to: Person, text: string, level: number, inThread?: Ask): Promise { try { const r = await deps.slack.postMessage(inThread?.channel ?? to.slack_user_id!, text, inThread?.ts); if (!inThread) { const ask: Ask = { channel: r.channel, ts: r.ts, person_id: to.id, level }; await deps.pool.query("update acc_receipt_search set asks = asks || $2::jsonb, last_asked_at = $3 where id = $1", [s.id, JSON.stringify([ask]), deps.now()]); s.asks = [...s.asks, ask]; } else { await deps.pool.query("update acc_receipt_search set last_asked_at = $2 where id = $1", [s.id, deps.now()]); } return true; } catch (e) { deps.log.error({ err: String(e), searchId: s.id }, "не удалось написать в Slack по поиску чека"); return false; } } async function firstQuestion(deps: SearchDeps, s: SearchRow, p: Person): Promise { const text = `Списание ${describeOp(s)}: пришлите чек и укажите проект.\n${operationLine(deps.options.qboBankingUrl, s)}` + `\nЕсли это личный расход или вы не знаете, что это, так и напишите.${await vendorProjectHint(deps.pool, s.vendor_name)}`; return sendAsk(deps, s, p, text, 0); } // ----------------------------------------------------------------- шаги 1-3: заведение поиска const isSubscription = (vendor: string | null, list: readonly string[]): boolean => { const v = (vendor ?? "").toLowerCase(); return !!v && list.some((x) => x.trim() && v.includes(x.trim().toLowerCase())); }; async function startSearches(deps: SearchDeps, out: SearchResult): Promise { const { pool, options } = deps; const non = await deps.nonWorkdays(); const { rows } = await pool.query<{ feed_txn_id: string; created_at: Date; txn_date: string | null; amount: string | null; vendor_name: string | null; card_or_account: string | null; project: string | null; }>( `select r.feed_txn_id, r.created_at, to_char(f.txn_date, 'YYYY-MM-DD') as txn_date, f.amount, f.vendor_name, f.card_or_account, r.suggestion->>'project_customer_id' as project from acc_categorization_review r left join acc_feed_txn f on f.feed_txn_id = r.feed_txn_id where not r.done and r.problem_highlight ilike '%ждёт документ%' and not exists (select 1 from acc_receipt_search s where s.feed_txn_id = r.feed_txn_id) and not exists (select 1 from acc_receipts x where x.feed_txn_id = r.feed_txn_id) order by r.created_at`, ); for (const r of rows) { // «старше 2 рабочих дней»: отсчёт от появления проблемы в разборе if (workdaysBetween(r.created_at, deps.now(), options.tz, non) < options.graceWorkdays) continue; if (isSubscription(r.vendor_name, options.subscriptionVendors)) { out.subscriptions++; continue; } try { const { person, reason } = await findResponsible(pool, r.card_or_account, r.project); const level = person ? 0 : 3; const ins = await pool.query( `insert into acc_receipt_search (feed_txn_id, responsible_person_id, escalation_level, txn_date, amount, vendor_name, card_or_account, project_customer_id, created_at) values ($1,$2,$3,$4,$5,$6,$7,$8,$9) on conflict (feed_txn_id) do nothing returning ${SEARCH_COLS}`, [r.feed_txn_id, person?.id ?? null, level, r.txn_date, r.amount, r.vendor_name, r.card_or_account, r.project, deps.now()], ); const s = ins.rows[0]; if (!s) continue; out.created++; if (!person) { out.noResponsible++; await upsertSearchTask(pool, s.id, "accountant", `Ответственный не найден (${reason}): операция ${describeOp(s)} без чека, найдите, кого спросить`); continue; } if (await firstQuestion(deps, s, person)) out.asked++; } catch (e) { out.errors++; deps.log.error({ err: e, feedTxnId: r.feed_txn_id }, "ошибка заведения поиска чека"); } } } // ----------------------------------------------------------------- шаг 6: эскалация const SEARCH_COLS = "id, feed_txn_id, responsible_person_id, escalation_level, created_at, last_asked_at, answer, to_char(txn_date, 'YYYY-MM-DD') as txn_date, amount, vendor_name, card_or_account, project_customer_id, asks, approved_without_receipt_at"; async function escalate(deps: SearchDeps, s: SearchRow, target: number, wd: number, out: SearchResult): Promise { const { pool } = deps; const responsible = await personById(pool, s.responsible_person_id); const first = s.asks[0]; const op = describeOp(s); if (target === 1 && responsible) { const text = `Напоминание: по операции ${op} всё ещё нет чека (${wd} раб. дн.). Пришлите чек и проект или напишите «личный расход» / «не знаю, что это».`; if (!(await sendAsk(deps, s, responsible, text, 1, first))) throw new Error("Slack недоступен"); } else if (target === 2 && responsible) { const pm = await projectManager(pool, s.project_customer_id); const sup = await supervisorOf(pool, responsible); const candidates = [pm && pm.id !== responsible.id ? pm : null, sup].filter((x): x is Person => !!x); const boss = candidates.find((x) => x.slack_user_id); if (!boss) { // уровень поднимается, но молча - нельзя: Юля узнаёт, что руководителю написать некому const why = candidates.length ? `нет Slack у ${candidates.map((x) => x.display_name).join(", ")}` : "руководитель не найден"; await upsertSearchTask(pool, s.id, "accountant", `Чек не найден за ${wd} раб. дн.: ${op}. Вопрос руководителю не отправлен: ${why}. Свяжитесь с ${responsible.display_name} или руководителем другим способом`); } else if (boss.slack_user_id) { const text = `${responsible.display_name} не прислал(а) чек за ${wd} раб. дн.: ${op}. Помогите, пожалуйста: нужен чек и проект (копия вопроса у ${responsible.display_name}).\n${operationLine(deps.options.qboBankingUrl, s)}`; if (!(await sendAsk(deps, s, boss, text, 2))) throw new Error("Slack недоступен"); if (first) await sendAsk(deps, s, responsible, `Вопрос по чеку передан ${boss.display_name} (${op}).`, 2, first); } } else if (target === 3) { await upsertSearchTask(pool, s.id, "accountant", `Чек не найден за ${wd} раб. дн.: ${op}. Попросите копию чека у вендора (в JobTread, если вендор там есть, иначе в Gmail)`); } else if (target === 4) { await upsertSearchTask(pool, s.id, "cfo", `Чек не найден за ${wd} раб. дн.: ${op}. Решите, как закрыть: провести без чека (только до лимита, инструмент acc_receipt_allow_without) или оставить открытой`); } await pool.query("update acc_receipt_search set escalation_level = $2 where id = $1", [s.id, target]); out.escalated[target - 1]!++; } async function escalateAll(deps: SearchDeps, out: SearchResult): Promise { const { pool, options } = deps; const non = await deps.nonWorkdays(); const { rows } = await pool.query(`select ${SEARCH_COLS} from acc_receipt_search where closed_at is null order by created_at`); for (const s of rows) { try { // первый вопрос не дошёл (сбой Slack): повторяем if (s.escalation_level === 0 && s.asks.length === 0 && s.responsible_person_id) { const p = await personById(pool, s.responsible_person_id); if (p?.slack_user_id && (await firstQuestion(deps, s, p))) out.asked++; } // сотрудник уже ответил или Анастасия разрешила провести без чека: дальше решают люди if (s.answer || s.approved_without_receipt_at) continue; const wd = workdaysBetween(s.created_at, deps.now(), options.tz, non); const target = options.escalationWorkdays.filter((d) => wd >= d).length; if (target > s.escalation_level) await escalate(deps, s, target, wd, out); } catch (e) { out.errors++; deps.log.error({ err: e, searchId: s.id }, "ошибка эскалации поиска чека"); } } } /** Операция уже закрыта в разборе (история категоризации): закрываем поиск и его задачу. */ async function closeFinished(deps: SearchDeps, out: SearchResult): Promise { const { pool } = deps; const { rows } = await pool.query<{ id: string; approved_reason: string | null; approved_without_receipt_at: Date | null }>( `select s.id, s.approved_reason, s.approved_without_receipt_at from acc_receipt_search s where s.closed_at is null and not exists (select 1 from acc_categorization_review r where r.feed_txn_id = s.feed_txn_id) and exists (select 1 from acc_categorization_review_history h where h.feed_txn_id = s.feed_txn_id)`, ); for (const s of rows) { const resolution = s.approved_without_receipt_at ? `проведено без чека (${s.approved_reason ?? "причина не указана"})` : "операция закрыта в разборе"; await pool.query("update acc_receipt_search set closed_at = $2, resolution = coalesce(resolution, $3) where id = $1", [s.id, deps.now(), resolution]); await pool.query("delete from acc_manual_review where ref_table = 'acc_receipt_search' and ref_id = $1", [s.id]); out.closed++; } } /** Job 'receipt-search': раз в день утром. */ export async function runReceiptSearch(deps: SearchDeps): Promise { const out: SearchResult = { created: 0, noResponsible: 0, subscriptions: 0, asked: 0, escalated: [0, 0, 0, 0], closed: 0, errors: 0 }; await closeFinished(deps, out); await startSearches(deps, out); await escalateAll(deps, out); return out; } // ----------------------------------------------------------------- шаг 9: недельный отчёт export interface WeeklyReportDeps { pool: Pool; slack: SlackApi; now(): Date; /** Если Анастасии (role_code = cfo со Slack) нет - канал бухгалтерии. */ fallbackChannelId?: string; } export async function buildWeeklyReport(pool: Pool, now: Date): Promise { const { rows } = await pool.query<{ who: string | null; amount: string | null; vendor_name: string | null; created_at: Date; escalation_level: number; answer: string | null }>( `select p.display_name as who, s.amount, s.vendor_name, s.created_at, s.escalation_level, s.answer from acc_receipt_search s left join person p on p.id = s.responsible_person_id where s.closed_at is null order by p.display_name nulls last, s.created_at`, ); if (rows.length === 0) return "Непринесённых чеков нет."; const groups = new Map(); for (const r of rows) groups.set(r.who ?? "ответственный не найден", [...(groups.get(r.who ?? "ответственный не найден") ?? []), r]); const level = ["вопрос задан", "напоминание", "руководитель", "Юля", "Анастасия"]; const lines = [`Непринесённые чеки: ${rows.length} шт., ${money(rows.reduce((s, r) => s + Number(r.amount ?? 0), 0))}.`]; for (const [who, list] of groups) { lines.push(`${who}: ${list.length} шт., ${money(list.reduce((s, r) => s + Number(r.amount ?? 0), 0))}`); for (const r of list) { const days = Math.floor((now.getTime() - r.created_at.getTime()) / 86_400_000); lines.push(`- ${r.amount != null ? money(r.amount) : "сумма неизвестна"}, ${r.vendor_name ?? "вендор неизвестен"}, ${days} дн., уровень ${r.escalation_level} (${level[r.escalation_level] ?? "?"})${r.answer ? `, ответ: ${r.answer}` : ""}`); } } return lines.join("\n"); } /** Job 'receipt-weekly-report'. */ export async function runReceiptWeeklyReport(deps: WeeklyReportDeps): Promise<{ sent: boolean; to: string | null; open: number }> { const open = Number((await deps.pool.query("select count(*)::int as n from acc_receipt_search where closed_at is null")).rows[0]!.n); // отчёт шлётся только если есть непринесённые чеки if (open === 0) return { sent: false, to: null, open: 0 }; const text = await buildWeeklyReport(deps.pool, deps.now()); 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"); const to = rows[0]?.slack_user_id ?? deps.fallbackChannelId; if (!to) throw new Error("некому отправить отчёт: у Анастасии (role_code = cfo) нет slack_user_id и не задан канал бухгалтерии"); await deps.slack.postMessage(to, text); return { sent: true, to, open }; } // ----------------------------------------------------------------- шаг 8: расход без чека type Queryable = Pick; /** Согласие Анастасии провести расход без чека: только до лимита и по каждому расходу отдельно. */ export async function allowWithoutReceipt(pool: Queryable, by: string, feedTxnId: string, reason: string, limitUsd: number, now: Date): Promise<{ amount: number }> { const { rows } = await pool.query<{ id: string; amount: string | null }>("select id, amount from acc_receipt_search where feed_txn_id = $1 for update", [feedTxnId]); const s = rows[0]; if (!s) throw new Error("поиск чека по этой операции не заведён (операция ждёт документ меньше положенного срока)"); const feed = await pool.query<{ amount: string | null }>("select amount from acc_feed_txn where feed_txn_id = $1", [feedTxnId]); const amount = feed.rows[0]?.amount ?? s.amount; if (amount == null) throw new Error("сумма операции неизвестна: проверить лимит нельзя"); if (Number(amount) > limitUsd) throw new Error(`сумма ${money(amount)} больше лимита ${money(limitUsd)}: без чека такой расход не проводится`); if (!reason.trim()) throw new Error("нужна причина: почему чек не найден"); await pool.query( "update acc_receipt_search set approved_without_receipt_by = $2, approved_without_receipt_at = $3, approved_reason = $4, resolution = $5 where id = $1", [s.id, by, now, reason.trim(), `проведено без чека (${reason.trim()})`], ); await pool.query("delete from acc_manual_review where ref_table = 'acc_receipt_search' and ref_id = $1", [s.id]); return { amount: Number(amount) }; } /** * Проверка при закрытии категоризации (finalize): операция ждала документ, а документа нет. * Больше лимита без чека не проводится; до лимита - только с согласием Анастасии. null - можно закрывать. * Если сумма операции неизвестна (acc_feed_txn пуст), проверить лимит нечем - закрытие не блокируется. */ export async function missingDocumentProblem(c: Queryable, row: Record, limitUsd: number): Promise { const id = String(row.feed_txn_id); const sugg = (row.suggestion && typeof row.suggestion === "object" ? row.suggestion : {}) as Record; if ((Array.isArray(sugg.invoice_ids) && sugg.invoice_ids.length > 0) || sugg.receipt_id) return null; if ((await c.query("select 1 from acc_receipts where feed_txn_id = $1 limit 1", [id])).rowCount) return null; const orig = await c.query<{ problem_highlight: string | null }>("select problem_highlight from acc_categorization_review_original where feed_txn_id = $1", [id]); const search = (await c.query<{ amount: string | null; approved_without_receipt_at: Date | null }>("select amount, approved_without_receipt_at from acc_receipt_search where feed_txn_id = $1", [id])).rows[0]; const waiting = /ждёт документ/i.test(String(row.problem_highlight ?? "")) || /ждёт документ/i.test(orig.rows[0]?.problem_highlight ?? "") || !!search; if (!waiting) return null; const feed = (await c.query<{ amount: string | null }>("select amount from acc_feed_txn where feed_txn_id = $1", [id])).rows[0]; const amount = feed?.amount ?? search?.amount ?? null; if (amount == null) return null; if (Number(amount) > limitUsd) return `нет чека, а сумма ${money(amount)} больше ${money(limitUsd)}: без чека такой расход не проводится (привяжите чек или инвойс: receipt_id или invoice_ids в suggestion)`; if (!search?.approved_without_receipt_at) return `нет чека: расход ${money(amount)} без чека проводится только с согласия Анастасии (инструмент acc_receipt_allow_without) или после привязки чека`; return null; }