MCP: пакетный acc_review_batch, компактная таблица очереди, интерактивное приложение (ui://) с кнопками Done/Delegate/Snooze, подсказки readOnly/destructive
All checks were successful
ci / test (push) Successful in 38s
ci / deploy (push) Successful in 2m37s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 09:21:34 +03:00
parent 7638242a51
commit aae7472010
3 changed files with 330 additions and 6 deletions

View File

@@ -0,0 +1,161 @@
/** Представление очереди разбора: компактные строки, markdown-таблица для текста и HTML-приложение (MCP Apps) с кнопками. */
type Json = Record<string, unknown>;
export const REVIEW_UI_URI = "ui://accounting_automation/review-table";
export const REVIEW_UI_MIME = "text/html;profile=mcp-app";
export interface ReviewRow {
id: string;
kind: string;
role: string;
date: string | null;
amount: string | null;
who: string | null;
what: string | null;
confidence: number | null;
problem: string | null;
snoozed: boolean;
file_url: string | null;
}
const s = (v: unknown): string | null => (v === null || v === undefined || v === "" ? null : String(v));
const day = (v: unknown): string | null => {
const x = s(v);
return x ? x.slice(0, 10) : null;
};
/** Одна строка таблицы из задачи списка (task + review). */
export function toRow(t: Json): ReviewRow {
const review = (t.review ?? {}) as Json;
const kind = String(t.kind);
let date: string | null = null;
let amount: string | null = null;
let who: string | null = null;
let what: string | null = null;
let confidence: number | null = typeof review.confidence === "number" ? review.confidence : null;
if (kind === "categorization") {
const sg = (review.suggestion ?? {}) as Json;
date = day(sg.date);
amount = s(sg.amount);
who = s(sg.vendor);
what = [s(sg.account), sg.project_customer_id ? `проект ${String(sg.project_customer_id)}` : null].filter(Boolean).join(", ") || s(review.feed_txn_id);
} else if (kind === "invoice") {
date = day(review.invoice_date);
amount = s(review.amount);
who = s(review.vendor_name);
what =
[s(review.invoice_number) ? `№ ${String(review.invoice_number)}` : null, review.project_customer_id ? `проект ${String(review.project_customer_id)}` : null].filter(Boolean).join(", ") || null;
confidence = null;
} else if (kind === "certificate") {
date = day(review.expires_on);
who = s(review.vendor_name);
what = "сертификат страхования";
confidence = null;
}
return {
id: String(t.id),
kind,
role: String(t.assignee_role),
date,
amount,
who,
what,
confidence,
problem: s(t.problem_highlight),
snoozed: t.snoozed_until != null,
file_url: s(t.file_url),
};
}
const cell = (v: string | number | null, max = 60): string => {
const x = v === null ? "" : String(v).replace(/\s+/g, " ").replace(/\|/g, "/");
return x.length > max ? `${x.slice(0, max - 1)}…` : x;
};
/** Текстовая таблица для хостов без поддержки интерактивных приложений и для самой модели. */
export function rowsToMarkdown(rows: ReviewRow[], total: number): string {
if (rows.length === 0) return "Очередь разбора пуста.";
const head = "| id | вид | дата | сумма | кто | что | % | проблема | роль |\n|---|---|---|---|---|---|---|---|---|";
const body = rows.map(
(r) => `| ${r.id.slice(0, 8)} | ${r.kind} | ${cell(r.date)} | ${cell(r.amount)} | ${cell(r.who, 30)} | ${cell(r.what, 40)} | ${cell(r.confidence)} | ${cell(r.problem, 80)} | ${r.role} |`,
);
return `${head}\n${body.join("\n")}\n\nПоказано ${rows.length} из ${total}. Действия по нескольким задачам - одним вызовом acc_review_batch (id - первые 8 символов из таблицы).`;
}
/** HTML-приложение (MCP Apps): таблица очереди с кнопками Done / Delegate / Snooze. Данные приходят в ui/notifications/tool-result. */
export const REVIEW_UI_HTML = String.raw`<!doctype html>
<html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Очередь разбора бухгалтерии</title>
<style>
:root{--bg:#fff;--fg:#1f2328;--mut:#6b7280;--line:#e5e7eb;--acc:#2563eb;--bad:#b42318;--hl:#fff7ed}
@media (prefers-color-scheme:dark){:root{--bg:#1c1c1e;--fg:#e8e8ea;--mut:#9ca3af;--line:#3a3a3e;--acc:#6ea0ff;--bad:#ff8a80;--hl:#3a2a1a}}
html,body{margin:0;background:var(--bg);color:var(--fg);font:13px/1.4 system-ui,sans-serif}
.wrap{padding:8px 10px}
.bar{display:flex;gap:8px;align-items:center;margin:0 0 8px;flex-wrap:wrap}
.bar .st{color:var(--mut);margin-left:auto}
button{font:inherit;border:1px solid var(--line);background:transparent;color:var(--fg);border-radius:6px;padding:3px 9px;cursor:pointer}
button:hover{border-color:var(--acc);color:var(--acc)} button:disabled{opacity:.45;cursor:default}
button.pri{background:var(--acc);border-color:var(--acc);color:#fff}
table{width:100%;border-collapse:collapse}
th,td{text-align:left;padding:5px 6px;border-bottom:1px solid var(--line);vertical-align:top}
th{color:var(--mut);font-weight:500;white-space:nowrap}
td.n,th.n{text-align:right;white-space:nowrap} tr.p td{background:var(--hl)}
.prob{color:var(--bad)} .acts{white-space:nowrap;display:flex;gap:4px}
.empty{color:var(--mut);padding:14px 4px}
</style></head><body><div class="wrap">
<div class="bar"><button id="done" class="pri" disabled>Done выбранные</button><button id="deleg" disabled>Delegate выбранные</button><button id="snz" disabled>Snooze 1д</button><span class="st" id="st"></span></div>
<div id="root"><div class="empty">Загрузка…</div></div></div>
<script>
(function(){
var rows=[],sel={},nextId=1,pending={};
function send(m){parent.postMessage(Object.assign({jsonrpc:"2.0"},m),"*");}
function req(method,params){return new Promise(function(res,rej){var id=nextId++;pending[id]={res:res,rej:rej};send({id:id,method:method,params:params});});}
function esc(x){return String(x==null?"":x).replace(/[&<>"]/g,function(c){return {"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c];});}
function status(t){document.getElementById("st").textContent=t||"";}
function other(r){return r==="accountant"?"cfo":"accountant";}
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 class="n">сумма</th><th>кто</th><th>что</th><th class="n">%</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 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><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();
}
function updBtns(){var n=selIds().length;["done","deleg","snz"].forEach(function(i){document.getElementById(i).disabled=!n;});}
function size(){send({method:"ui/notifications/size-changed",params:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight}});}
function tomorrow(){return new Date(Date.now()+24*3600*1000).toISOString();}
function run(ids,action){
var byId={};rows.forEach(function(r){byId[r.id]=r;});
var actions=ids.map(function(id){var a={id:id,action:action};if(action==="handoff"){a.role=other(byId[id].role);a.comment="из таблицы";}if(action==="snooze")a.until=tomorrow();return a;});
status("Выполняю…");
req("tools/call",{name:"acc_review_batch",arguments:{actions:actions}}).then(function(r){
var sc=(r&&r.structuredContent)||{};var okIds={};(sc.results||[]).forEach(function(x){if(x.ok)okIds[x.id]=1;});
var bad=(sc.results||[]).filter(function(x){return !x.ok;});
rows=rows.filter(function(x){return !okIds[x.id];});ids.forEach(function(i){delete sel[i];});
render();status(Object.keys(okIds).length+" выполнено"+(bad.length?", ошибок: "+bad.length+" ("+bad[0].error+")":""));
}).catch(function(e){status("Ошибка: "+((e&&e.message)||e));});
}
document.addEventListener("click",function(e){
var t=e.target;if(!t||!t.dataset)return;
if(t.dataset.a){run([t.dataset.id],t.dataset.a);return;}
if(t.id==="done")run(selIds(),"done");
if(t.id==="deleg")run(selIds(),"handoff");
if(t.id==="snz")run(selIds(),"snooze");
});
document.addEventListener("change",function(e){var t=e.target;if(t&&t.dataset&&t.dataset.sel){sel[t.dataset.sel]=t.checked;updBtns();}});
window.addEventListener("message",function(e){
var m=e.data;if(!m||m.jsonrpc!=="2.0")return;
if(m.id!=null&&pending[m.id]){var p=pending[m.id];delete pending[m.id];if(m.error)p.rej(new Error(m.error.message||"error"));else p.res(m.result);return;}
if(m.method==="ui/notifications/tool-result"){var sc=(m.params&&m.params.structuredContent)||{};rows=sc.rows||[];sel={};render();status("Всего в очереди: "+(sc.total!=null?sc.total:rows.length));}
if(m.id!=null&&m.method==="ui/resource-teardown"){send({id:m.id,result:{}});}
});
req("ui/initialize",{protocolVersion:"2026-01-26",capabilities:{},clientInfo:{name:"accounting_automation review table",version:"0.1.0"},appCapabilities:{}}).then(function(){send({method:"ui/notifications/initialized"});}).catch(function(){});
})();
</script></body></html>`;