Очередь: столбец «списано с» и ссылка на QuickBooks, ответ на проблему и contract_basis (миграция 077), инструкции и процессы; review-done-action.md
All checks were successful
ci / test (push) Successful in 1m7s
ci / deploy (push) Successful in 3m16s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 17:47:01 +03:00
parent 09f6f81038
commit 1a7515dfbc
9 changed files with 163 additions and 16 deletions

View File

@@ -87,16 +87,16 @@ async function forwardInvoice(c: PoolClient, r: Row): Promise<void> {
// Тот же id; если инвойс уже есть в реестре (вернулся в разбор), обновляем данные, статус не трогаем.
await c.query(
`insert into acc_invoices (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_number, invoice_date,
amount, lines, project_customer_id, jt_job_id, contract_id, stage)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12, 'checking')
amount, lines, project_customer_id, jt_job_id, contract_id, contract_basis, stage)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11, $12, $13, 'checking')
on conflict (id) do update set
source_message_id = excluded.source_message_id, drive_file_id = excluded.drive_file_id, vendor_name = excluded.vendor_name,
vendor_qbo_id = excluded.vendor_qbo_id, invoice_number = excluded.invoice_number, invoice_date = excluded.invoice_date,
amount = excluded.amount, lines = excluded.lines, project_customer_id = excluded.project_customer_id,
jt_job_id = excluded.jt_job_id, contract_id = excluded.contract_id`,
jt_job_id = excluded.jt_job_id, contract_id = excluded.contract_id, contract_basis = excluded.contract_basis`,
[
r.id, r.source_message_id, r.drive_file_id, r.vendor_name, r.vendor_qbo_id ?? null, r.invoice_number ?? null, r.invoice_date,
r.amount, r.lines == null ? null : JSON.stringify(r.lines), r.project_customer_id, r.jt_job_id ?? null, r.contract_id ?? null,
r.amount, r.lines == null ? null : JSON.stringify(r.lines), r.project_customer_id, r.jt_job_id ?? null, r.contract_id ?? null, r.contract_basis ?? null,
],
);
}

View File

@@ -35,6 +35,8 @@ export function buildConclusion(i: {
ambiguousContractIds?: string[];
duplicateIds: string[];
insuranceValidUntil: string | null;
/** Основание вместо договора: invoice - сам инвойс служит основанием (доп. заказ), проблема «нет контракта» не ставится. */
contractBasis?: string | null;
today: string;
now: Date;
}): Conclusion {
@@ -43,7 +45,7 @@ export function buildConclusion(i: {
const remaining = c ? Math.round((c.total_amount - c.retained_amount - c.paid_amount) * 100) / 100 : null;
const ambiguous = i.ambiguousContractIds ?? [];
if (ambiguous.length > 1) problems.push(`контракт неоднозначен: у вендора на этом проекте контрактов ${ambiguous.length}, выберите нужный (сверка стадии работ тоже вручную)`);
else if (!c) problems.push("нет контракта с этим вендором на этом проекте");
else if (!c && i.contractBasis !== "invoice") problems.push("нет контракта с этим вендором на этом проекте");
const exceeds = remaining !== null && i.amount > remaining;
if (exceeds) problems.push(`сумма инвойса ${i.amount.toFixed(2)} больше остатка по контракту ${remaining!.toFixed(2)}`);
if (i.duplicateIds.length > 0) problems.push(`возможный дубль инвойса (${i.duplicateIds.length} шт.: тот же номер или та же сумма и дата)`);
@@ -113,7 +115,7 @@ export async function runInvoiceCheck(deps: { pool: Pool; now?: () => Date }): P
);
const concl = buildConclusion({
amount: Number(inv.amount), contract, ambiguousContractIds: ambiguousIds, duplicateIds: (dup.rows as { id: string }[]).map((r) => r.id),
insuranceValidUntil: cert.rows[0]?.v ?? null, today, now,
insuranceValidUntil: cert.rows[0]?.v ?? null, contractBasis: inv.contract_basis ?? null, today, now,
});
await c.query(
"update acc_invoices set conclusion = $2::jsonb, contract_id = coalesce(contract_id, $3::uuid) where id = $1",

View File

@@ -16,11 +16,17 @@ export interface ReviewRow {
age_days: number | null;
amount: string | null;
who: string | null;
/** Счёт или карта списания (название из QuickBooks, с адресом проекта и последними цифрами). */
paid_from: string | null;
what: string | null;
confidence: number | null;
problem: string | null;
snoozed: boolean;
file_url: string | null;
/** Ссылка на банковские операции QuickBooks (для категоризации). */
qbo_url: string | null;
/** Ответ человека на проблему (инвойсы). */
answer: string | null;
}
const s = (v: unknown): string | null => (v === null || v === undefined || v === "" ? null : String(v));
@@ -31,9 +37,12 @@ const day = (v: unknown): string | null => {
/** Справочные данные для читаемой таблицы (добавляет ReviewTools.list): операция ленты, названия проекта и счёта. */
export interface RowLookup {
feed?: { txn_date?: unknown; amount?: unknown; vendor_name?: unknown; description?: unknown } | null;
feed?: { txn_date?: unknown; amount?: unknown; vendor_name?: unknown; description?: unknown; card_or_account?: unknown } | null;
project?: string | null;
account?: string | null;
/** Название счёта или карты, с которой списаны деньги. */
bank_account?: string | null;
qbo_url?: string | null;
}
/** Одна строка таблицы из задачи списка (task + review). */
@@ -85,11 +94,14 @@ export function toRow(t: Json, nowMs: number = Date.now()): ReviewRow {
age_days: t.created_at ? Math.max(0, Math.floor((nowMs - new Date(String(t.created_at)).getTime()) / 86_400_000)) : null,
amount,
who,
paid_from: kind === "categorization" ? (lk.bank_account ?? s((review.suggestion as Json | null)?.bank_account_id) ?? s(lk.feed?.card_or_account)) : null,
what,
confidence,
problem: s(t.problem_highlight),
snoozed: t.snoozed_until != null,
file_url: s(t.file_url),
qbo_url: kind === "categorization" ? s(lk.qbo_url) : null,
answer: kind === "invoice" ? s(review.answer) : null,
};
}
@@ -101,9 +113,9 @@ const cell = (v: string | number | null, max = 60): string => {
/** Текстовая таблица для хостов без поддержки интерактивных приложений и для самой модели. */
export function rowsToMarkdown(rows: ReviewRow[], total: number): string {
if (rows.length === 0) return "Очередь разбора пуста.";
const head = "| id | вид | дата | получено | дней | сумма | кто | что | % | проблема | роль |\n|---|---|---|---|---|---|---|---|---|---|---|";
const head = "| id | вид | дата | получено | дней | сумма | кто | списано с | что | % | проблема | ответ | роль |\n|---|---|---|---|---|---|---|---|---|---|---|---|---|";
const body = rows.map(
(r) => `| ${r.id.slice(0, 8)} | ${r.kind} | ${cell(r.date)} | ${cell(r.received)} | ${cell(r.age_days)} | ${cell(r.amount)} | ${cell(r.who, 30)} | ${cell(r.what, 40)} | ${cell(r.confidence)} | ${cell(r.problem, 80)} | ${r.role} |`,
(r) => `| ${r.id.slice(0, 8)} | ${r.kind} | ${cell(r.date)} | ${cell(r.received)} | ${cell(r.age_days)} | ${cell(r.amount)} | ${cell(r.who, 30)} | ${cell(r.paid_from, 30)} | ${cell(r.what, 40)} | ${cell(r.confidence)} | ${cell(r.problem, 80)} | ${cell(r.answer, 40)} | ${r.role} |`,
);
return `${head}\n${body.join("\n")}\n\nПоказано ${rows.length} из ${total}. Действия по нескольким задачам - одним вызовом acc_review_batch (id - первые 8 символов из таблицы).`;
}
@@ -143,12 +155,12 @@ function selIds(){return Object.keys(sel).filter(function(k){return sel[k];});}
function render(){
var root=document.getElementById("root");
if(!rows.length){root.innerHTML='<div class="empty">Очередь разбора пуста.</div>';updBtns();size();return;}
var h='<table><thead><tr><th></th><th>вид</th><th>дата</th><th>получено</th><th class="n">дней</th><th class="n">сумма</th><th>кто</th><th>что</th><th class="n">%</th><th>проблема</th><th>роль</th><th></th></tr></thead><tbody>';
var h='<table><thead><tr><th></th><th>вид</th><th>дата</th><th>получено</th><th class="n">дней</th><th class="n">сумма</th><th>кто</th><th>списано с</th><th>что</th><th class="n">%</th><th>проблема</th><th>ответ</th><th>роль</th><th></th></tr></thead><tbody>';
rows.forEach(function(r){
h+='<tr'+(r.problem?' class="p"':'')+'><td><input type="checkbox" data-sel="'+esc(r.id)+'"'+(sel[r.id]?' checked':'')+'></td>'
+'<td>'+esc(r.kind)+'</td><td>'+esc(r.date)+'</td><td>'+esc(r.received)+'</td><td class="n">'+esc(r.age_days)+'</td><td class="n">'+esc(r.amount)+'</td><td>'+esc(r.who)+'</td>'
+'<td>'+(r.file_url?'<a href="'+esc(r.file_url)+'" target="_blank" rel="noopener">':'')+esc(r.what)+(r.file_url?'</a>':'')+'</td>'
+'<td class="n">'+esc(r.confidence)+'</td><td class="prob">'+esc(r.problem)+'</td><td>'+esc(r.role)+'</td>'
+'<td>'+esc(r.kind)+'</td><td>'+esc(r.date)+'</td><td>'+esc(r.received)+'</td><td class="n">'+esc(r.age_days)+'</td><td class="n">'+esc(r.amount)+'</td><td>'+esc(r.who)+'</td><td>'+esc(r.paid_from)+'</td>'
+'<td>'+((r.file_url||r.qbo_url)?'<a href="'+esc(r.file_url||r.qbo_url)+'" target="_blank" rel="noopener">':'')+esc(r.what)+((r.file_url||r.qbo_url)?'</a>':'')+'</td>'
+'<td class="n">'+esc(r.confidence)+'</td><td class="prob">'+esc(r.problem)+'</td><td>'+esc(r.answer)+'</td><td>'+esc(r.role)+'</td>'
+'<td><div class="acts"><button data-a="done" data-id="'+esc(r.id)+'">Done</button><button data-a="handoff" data-id="'+esc(r.id)+'">→ '+esc(other(r.role))+'</button><button data-a="snooze" data-id="'+esc(r.id)+'">1д</button></div></td></tr>';
});
root.innerHTML=h+'</tbody></table>';updBtns();size();

View File

@@ -22,7 +22,7 @@ export class McpToolError extends Error {}
export interface ReviewDeps {
pool: Pool;
settings: Pick<AccountingSettings, "reviewers">;
settings: Pick<AccountingSettings, "reviewers"> & { receipts?: { qboBankingUrl?: string } };
/** Лимит расхода без чека (USD), по умолчанию 500. */
noReceiptLimitUsd?: number;
now?: () => Date;
@@ -71,6 +71,11 @@ const confidenceF = (v: unknown): unknown => {
if (typeof v !== "number" || !Number.isInteger(v) || v < 0 || v > 100) throw new McpToolError("ожидалось целое 0..100");
return v;
};
const contractBasisF = (v: unknown): unknown => {
if (isNull(v)) return null;
if (v !== "contract" && v !== "invoice" && v !== "none") throw new McpToolError("contract_basis: contract, invoice или none");
return v;
};
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const problem: FieldSpec = { cast: "text", check: text(true) };
@@ -90,6 +95,10 @@ export const KINDS: Record<string, KindMeta> = {
jt_job_id: { cast: "text", check: text(true) },
contract_id: { cast: "uuid", check: uuidF },
problem_highlight: problem,
/** Ответ человека на проблему: по нему агент решает, что делать дальше. */
answer: { cast: "text", check: text(true) },
/** Основание вместо договора: contract - договор, invoice - сам инвойс (доп. заказ, change order), none - без основания. */
contract_basis: { cast: "text", check: contractBasisF },
},
},
categorization: {
@@ -232,7 +241,7 @@ export class ReviewTools {
const feedIds = rows.filter((r) => r.kind === "categorization").map((r) => String(r.ref_id));
const feed = new Map<string, Json>();
if (feedIds.length) {
const f = await this.d.pool.query("select feed_txn_id, txn_date, amount, vendor_name, description from acc_feed_txn where feed_txn_id = any($1)", [feedIds]);
const f = await this.d.pool.query("select feed_txn_id, txn_date, amount, vendor_name, description, card_or_account from acc_feed_txn where feed_txn_id = any($1)", [feedIds]);
for (const x of f.rows) feed.set(String(x.feed_txn_id), x as Json);
}
const sugg = (r: { row: unknown }): Json => ((r.row as Json | null)?.suggestion ?? {}) as Json;
@@ -242,6 +251,7 @@ export class ReviewTools {
};
const projectIds = [...new Set(rows.map(projectOf).filter((x): x is string => !!x))];
const accountIds = [...new Set(rows.filter((r) => r.kind === "categorization").map((r) => sugg(r).account).filter((x) => x !== null && x !== undefined && x !== "").map(String))];
const bankIds = [...new Set(rows.filter((r) => r.kind === "categorization").map((r) => sugg(r).bank_account_id).filter((x) => x !== null && x !== undefined && x !== "").map(String))];
const projects = new Map<string, string>();
if (projectIds.length) {
const p = await this.d.pool.query(
@@ -259,13 +269,32 @@ export class ReviewTools {
const a = await this.d.pool.query("select id, coalesce(fully_qualified_name, name) as n from qbo_account where id = any($1)", [accountIds]);
for (const x of a.rows) accounts.set(String(x.id), String(x.n));
}
// счёт или карта списания: по id из предложения, иначе по последним 4 цифрам из ленты (в названии счёта QuickBooks они есть)
const banks = new Map<string, string>();
if (bankIds.length) {
const b = await this.d.pool.query("select id, coalesce(fully_qualified_name, name) as n from qbo_account where id = any($1)", [bankIds]);
for (const x of b.rows) banks.set(String(x.id), String(x.n));
}
const last4 = new Map<string, string>();
for (const f of feed.values()) {
const d = String(f.card_or_account ?? "").replace(/D/g, "").slice(-4);
if (d.length === 4 && !last4.has(d)) {
const m = await this.d.pool.query("select coalesce(fully_qualified_name, name) as n from qbo_account where account_type in ('Credit Card','Bank') and active and name like $1 limit 2", [`%${d}%`]);
if (m.rows.length === 1) last4.set(d, String(m.rows[0].n));
}
}
const bankingUrl = this.d.settings.receipts?.qboBankingUrl ?? "https://app.qbo.intuit.com/app/banking";
for (const r of rows) {
const pid = projectOf(r);
const acc = r.kind === "categorization" ? sugg(r).account : null;
const bid = r.kind === "categorization" && sugg(r).bank_account_id ? String(sugg(r).bank_account_id) : null;
const f4 = r.kind === "categorization" ? String(feed.get(String(r.ref_id))?.card_or_account ?? "").replace(/D/g, "").slice(-4) : "";
out.set(String(r.id), {
feed: r.kind === "categorization" ? (feed.get(String(r.ref_id)) ?? null) : null,
project: pid ? (projects.get(pid) ?? null) : null,
account: acc ? (accounts.get(String(acc)) ?? null) : null,
bank_account: bid ? (banks.get(bid) ?? null) : (last4.get(f4) ?? null),
qbo_url: r.kind === "categorization" ? bankingUrl.split("{feed_txn_id}").join(encodeURIComponent(String(r.ref_id))) : null,
});
}
return out;

View File

@@ -0,0 +1,17 @@
-- Встреча 2026-11-30: ответ человека на проблему инвойса и основание вместо договора (доп. заказ / change order без отдельного контракта).
-- Колонки нужны во всех трёх таблицах разбора (review, _original, _history), чтобы копирование строк шло без потерь.
alter table acc_invoices_review add column if not exists answer text;
alter table acc_invoices_review add column if not exists contract_basis text;
alter table acc_invoices_review_original add column if not exists answer text;
alter table acc_invoices_review_original add column if not exists contract_basis text;
alter table acc_invoices_review_history add column if not exists answer text;
alter table acc_invoices_review_history add column if not exists contract_basis text;
-- в реестре остаётся только основание (ответ - рабочая заметка разбора)
alter table acc_invoices add column if not exists contract_basis text;
-- contract = договор, invoice = сам инвойс/пропоузел служит основанием (контракт не создаётся), none = без основания
do $$ begin
alter table acc_invoices_review add constraint acc_invoices_review_contract_basis_chk check (contract_basis is null or contract_basis in ('contract','invoice','none'));
exception when duplicate_object then null; end $$;
do $$ begin
alter table acc_invoices add constraint acc_invoices_contract_basis_chk check (contract_basis is null or contract_basis in ('contract','invoice','none'));
exception when duplicate_object then null; end $$;