Done: нельзя при нерешённой проблеме (Can't done - not solved yet. SS, исходная проблема сохраняется), точечная проверка операции в QuickBooks; вложения документов в QuickBooks (qbo-attach, миграция 078, ссылка на Drive в Memo); review-done-action.md по замечаниям
Some checks failed
ci / test (push) Failing after 1m0s
ci / deploy (push) Has been skipped

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 19:32:51 +03:00
parent 2419bd26d3
commit 1112dac733
12 changed files with 523 additions and 55 deletions

View File

@@ -1,6 +1,7 @@
import { isDeepStrictEqual } from "node:util";
import { withTx, type Pool } from "khb_common";
import { missingDocumentProblem } from "./receipt-search.js";
import type { QboClient } from "./qbo-client.js";
type PoolClient = Parameters<Parameters<typeof withTx>[1]>[0];
@@ -25,6 +26,8 @@ export interface FinalizeDeps {
notify: (text: string) => Promise<void> | void;
/** Личное сообщение исполнителю (Slack user id): причина отказа уходит тому, кто отметил запись выполненной (done_by -> person). */
notifyPerson?: (slackUserId: string, text: string) => Promise<void> | void;
/** Прямой клиент QuickBooks: при Done по категоризации сервис сам проверяет, есть ли операция в QuickBooks. Без клиента проверка пропускается. */
qbo?: QboClient | null;
}
export interface RejectedItem {
@@ -51,8 +54,54 @@ interface KindConfig {
validate: (row: Row, c: PoolClient, limitUsd: number) => string | null | Promise<string | null>;
/** Передача результата дальше (в той же транзакции). */
forward: (c: PoolClient, row: Row) => Promise<void>;
/** Проблема строки, оставшаяся нерешённой (текст отказа Done не добавляется: исходная проблема важнее). null - решена. */
unsolved?: (row: Row, originalProblem: string) => string | null;
/** Операция уже есть в QuickBooks (проверка по месту, в самом QuickBooks): id записи или null. Если есть, строка закрывается без остальных проверок. */
inQbo?: (row: Row, c: PoolClient, qbo: QboClient) => Promise<string | null>;
}
const CANT_DONE = "Can't done - not solved yet.";
const CANT_DONE_RE = /(?:\s*\|\s*)?Can't done - not solved yet\. \d{2}(?: \([^]*\))?\s*$/;
/** Исходный текст проблемы без отметки отказа Done и без старого текста «Завершение отклонено: ...». */
export function originalProblem(text: unknown): string {
const t = typeof text === "string" ? text : "";
if (t.startsWith("Завершение отклонено:")) return "";
return t.replace(CANT_DONE_RE, "").trim();
}
/** Новая отметка отказа: старая убирается, исходная проблема сохраняется; секунды делают текст «живым» (видно, что Done сработал, но не пустил). */
export function cantDoneText(current: unknown, now: Date, extra?: string): string {
const base = originalProblem(current);
const ss = String(now.getSeconds()).padStart(2, "0");
const mark = `${CANT_DONE} ${ss}${extra ? ` (${extra})` : ""}`;
return base ? `${base} | ${mark}` : mark;
}
const addDays = (d: string, n: number): string => new Date(Date.parse(`${d}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10);
/** Расход в QuickBooks по операции ленты: та же сумма, близкая дата, тот же получатель; одна запись закрывает одну операцию. */
async function purchaseInQbo(row: Row, c: PoolClient, qbo: QboClient): Promise<string | null> {
const f = (await c.query("select amount::text as amount, txn_date::text as d, vendor_name from acc_feed_txn where feed_txn_id = $1", [String(row.feed_txn_id)])).rows[0];
if (!f || f.amount == null || !f.d) return null;
const w = String(f.vendor_name ?? "").trim().split(" ")[0]?.toLowerCase() ?? "";
if (w.length < 3) return null;
const q = await qbo.query(`select Id, TotalAmt, TxnDate, EntityRef from Purchase where TotalAmt = '${Number(f.amount).toFixed(2)}' and TxnDate >= '${addDays(f.d, -3)}' and TxnDate <= '${addDays(f.d, 30)}'`);
const list = (q.Purchase as { Id: string; EntityRef?: { name?: string } }[] | undefined) ?? [];
for (const p of list) {
if (!String(p.EntityRef?.name ?? "").toLowerCase().includes(w)) continue;
const used = await c.query(
"select 1 from acc_categorization_review_history where qbo_txn_id = $1 or done_by like '%(purchase ' || $1 || ')' limit 1",
[p.Id],
);
if (used.rowCount === 0) return p.Id;
}
return null;
}
const unsolvedByProblem = (_row: Row, original: string): string | null => (original.trim() ? "проблема не решена" : null);
const unsolvedInvoice = (row: Row, original: string): string | null => (original.trim() && blank(row.answer) ? "проблема не решена" : null);
/** Поля, изменения которых не считаются правкой человека (служебные и отметки процесса). */
const SERVICE_FIELDS = new Set(["updated_at", "created_at", "done", "done_by", "problem_highlight", "request_sent_at", "fraud_checked_at", "request_count", "request_approved_by", "request_approved_at", "request_log", "alert_kind"]);
@@ -136,10 +185,10 @@ async function forwardCertificate(c: PoolClient, r: Row): Promise<void> {
}
const KINDS: KindConfig[] = [
{ kind: "invoices", table: "acc_invoices_review", key: "id", label: "инвойс", validate: validateInvoice, forward: forwardInvoice },
{ kind: "invoices", table: "acc_invoices_review", key: "id", label: "инвойс", validate: validateInvoice, forward: forwardInvoice, unsolved: unsolvedInvoice },
// Категоризация: проводка в QuickBooks уже сделана Claude, обязательных полей нет; фиксируется только результат.
// Проверка: расход без документа (чека) больше лимита ($500) не закрывается, до лимита - только с согласия Анастасии.
{ kind: "categorization", table: "acc_categorization_review", key: "feed_txn_id", label: "операция банка", validate: (row, c, limit) => (String(row.done_by ?? "").startsWith("auto:") ? null : missingDocumentProblem(c, row, limit)), forward: async () => {} },
{ kind: "categorization", table: "acc_categorization_review", key: "feed_txn_id", label: "операция банка", validate: (row, c, limit) => (String(row.done_by ?? "").startsWith("auto:") ? null : missingDocumentProblem(c, row, limit)), forward: async () => {}, unsolved: unsolvedByProblem, inQbo: purchaseInQbo },
{ kind: "certificates", table: "acc_certificates_review", key: "id", label: "сертификат", validate: validateCertificate, forward: forwardCertificate },
];
@@ -158,7 +207,7 @@ export function diffWithOriginal(current: Row, original: Row | null): Record<str
type Outcome = { status: "skipped" } | { status: "finalized" } | { status: "rejected"; reason: string; doneBy: string | null };
async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date, now: Date, limitUsd: number): Promise<Outcome> {
async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date, now: Date, limitUsd: number, qbo: QboClient | null): Promise<Outcome> {
return withTx(pool, async (c) => {
// Блокировка строки; занятую другим запуском пропускаем. Условия проверяются заново уже под блокировкой.
const locked = await c.query(
@@ -169,10 +218,25 @@ async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date
const row = locked.rows[0].j as Row;
const doneBy = (row.done_by as string | null) ?? null;
const reason = await cfg.validate(row, c, limitUsd);
if (reason) {
await c.query(`update ${cfg.table} set done = false, problem_highlight = $2 where ${cfg.key}::text = $1`, [id, `Завершение отклонено: ${reason}`]);
return { status: "rejected", reason, doneBy } as Outcome;
const auto = String(row.done_by ?? "").startsWith("auto:");
let qboId: string | null = null;
if (cfg.inQbo && qbo && !auto) {
try {
qboId = await cfg.inQbo(row, c, qbo);
} catch {
// QuickBooks недоступен: не можем обоснованно сказать «не решено», запись остаётся и будет проверена в следующий запуск
return { status: "skipped" } as Outcome;
}
}
if (!qboId) {
const reason = await cfg.validate(row, c, limitUsd);
const orig = originalProblem(row.problem_highlight);
const unsolved = auto ? null : (cfg.unsolved?.(row, orig) ?? null);
if (reason || unsolved) {
// исходная проблема остаётся; Done просто сбрасывается с живой отметкой «Can't done»
await c.query(`update ${cfg.table} set done = false, problem_highlight = $2 where ${cfg.key}::text = $1`, [id, cantDoneText(row.problem_highlight, now, reason ?? undefined)]);
return { status: "rejected", reason: (reason ?? unsolved) as string, doneBy } as Outcome;
}
}
const orig = await c.query(`select to_jsonb(o) as j from ${cfg.table}_original o where o.${cfg.key}::text = $1`, [id]);
@@ -181,6 +245,12 @@ async function finalizeOne(pool: Pool, cfg: KindConfig, id: string, cutoff: Date
const hist = { ...row, closed_by: doneBy, closed_at: now.toISOString(), changed_fields: changed };
await c.query(`insert into ${cfg.table}_history select (jsonb_populate_record(null::${cfg.table}_history, $1::jsonb)).*`, [JSON.stringify(hist)]);
if (qboId) {
await c.query(
`update ${cfg.table}_history set qbo_posted_at = now(), qbo_txn_id = $2, qbo_post_error = 'уже проведено в QuickBooks (проверено при Done)' where ${cfg.key}::text = $1`,
[id, qboId],
);
}
await cfg.forward(c, row);
await c.query(`delete from ${cfg.table} where ${cfg.key}::text = $1`, [id]);
return { status: "finalized" } as Outcome;
@@ -204,13 +274,13 @@ export async function runFinalize(deps: FinalizeDeps): Promise<FinalizeResult> {
const cand = await deps.pool.query(`select ${cfg.key}::text as id from ${cfg.table} where done and updated_at <= $1 order by created_at`, [cutoff]);
for (const { id } of cand.rows as { id: string }[]) {
try {
const out = await finalizeOne(deps.pool, cfg, id, cutoff, now, deps.noReceiptLimitUsd ?? 500);
const out = await finalizeOne(deps.pool, cfg, id, cutoff, now, deps.noReceiptLimitUsd ?? 500, deps.qbo ?? null);
if (out.status === "finalized") result.finalized[cfg.kind]++;
else if (out.status === "rejected") {
result.rejected.push({ kind: cfg.kind, id, reason: out.reason });
try {
const executor = await executorOf(deps.pool, out.doneBy);
const text = `Завершение разбора отклонено (${cfg.label}, ${id}${executor.name ? `, отметил ${executor.name}` : ""}): ${out.reason}. Отметка «выполнено» снята, исправьте запись и отметьте заново.`;
const text = `Завершение разбора отклонено (${cfg.label}, ${id}${executor.name ? `, отметил ${executor.name}` : ""}): ${out.reason}. Отметка «выполнено» снята (исходная проблема сохранена): решите её и отметьте заново.`;
let sent = false;
if (executor.slackUserId && deps.notifyPerson) {
try {