Ручки для ассистентов: очередь кратко, остаток по контракту, поиск чека (список и ответ); раздел интерфейсов в передаче
Some checks failed
ci / deploy (push) Failing after 2m13s
ci / test (push) Successful in 49s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 20:02:09 +03:00
parent 9f5297f765
commit 73eba1d977
6 changed files with 206 additions and 14 deletions

View File

@@ -0,0 +1,86 @@
import type { FastifyInstance, FastifyReply } from "fastify";
import type { Pool } from "khb_common";
import { ChargebackError, contractBalance } from "./chargeback.js";
import { recordSearchAnswer, type AnswerKind } from "./receipts.js";
type Json = Record<string, unknown>;
/**
* Ручки под токеном сервиса для ассистентов в Slack (ассистент бухгалтерии, ассистент менеджера):
* очередь кратко, остаток по контракту, открытые «поиски чека» человека и запись ответа по ним.
* Только данные и расчёты; сообщения в Slack пишут сами ассистенты. Тела - JSON-объекты; ошибки: {error, message}.
*/
export function registerAssistantRoutes(app: FastifyInstance, deps: { pool: Pool }): void {
const body = (req: { body: unknown }): Json => (req.body && typeof req.body === "object" && !Array.isArray(req.body) ? (req.body as Json) : {});
const run = async (reply: FastifyReply, fn: () => Promise<unknown>): Promise<unknown> => {
try {
return await fn();
} catch (e) {
if (e instanceof ChargebackError) return reply.code(e.status).send({ error: e.code, message: e.message });
throw e;
}
};
/** Очередь acc_manual_review кратко: по ролям и видам - сколько всего и сколько с проблемой (отложенные не считаются). */
app.post("/queue/summary", (req, reply) =>
run(reply, async () => {
const b = body(req);
const role = typeof b.role === "string" ? b.role : null;
if (role !== null && role !== "accountant" && role !== "cfo") throw new ChargebackError(400, "bad_request", "role: accountant или cfo");
const { rows } = await deps.pool.query(
`select assignee_role as role, kind, count(*)::int as total,
count(*) filter (where nullif(btrim(problem_highlight), '') is not null)::int as with_problem,
min(created_at) as oldest
from acc_manual_review
where ($1::text is null or assignee_role = $1) and (snoozed_until is null or snoozed_until <= now())
group by 1, 2 order by 1, 2`,
[role],
);
return { queue: rows, total: rows.reduce((n, r) => n + Number(r.total), 0) };
}),
);
/** Остаток по контракту: сумма, удержания, оплачено, остаток (поиск по contract_id или vendor_name, можно с project_customer_id). */
app.post("/contract/balance", (req, reply) => run(reply, () => contractBalance(deps.pool, body(req))));
/** Открытые «поиски чека» человека (person_id или slack_user_id): что у него без чека. */
app.post("/receipt-search/open", (req, reply) =>
run(reply, async () => {
const b = body(req);
let personId = typeof b.person_id === "string" ? b.person_id : null;
if (!personId && typeof b.slack_user_id === "string") {
personId = (await deps.pool.query<{ id: string }>("select id from person where slack_user_id = $1 and is_active limit 1", [b.slack_user_id])).rows[0]?.id ?? null;
}
if (!personId) throw new ChargebackError(400, "bad_request", "нужен person_id или известный slack_user_id");
const { rows } = await deps.pool.query(
`select id, vendor_name, amount, to_char(txn_date, 'YYYY-MM-DD') as txn_date, card_or_account, escalation_level, last_asked_at, answer, asks
from acc_receipt_search where responsible_person_id = $1 and closed_at is null order by created_at`,
[personId],
);
return { person_id: personId, searches: rows };
}),
);
/** Запись ответа человека по поиску чека: kind personal (личный расход) или unknown (не знаю, что это). */
app.post("/receipt-search/answer", (req, reply) =>
run(reply, async () => {
const b = body(req);
const kind = b.kind;
if (kind !== "personal" && kind !== "unknown") throw new ChargebackError(400, "bad_request", "kind: personal или unknown");
if (typeof b.search_id !== "string") throw new ChargebackError(400, "bad_request", "нужен search_id");
const s = (
await deps.pool.query<{ id: string; vendor_name: string | null; amount: string | null; answer: string | null; closed_at: string | null; who: string | null }>(
`select s.id, s.vendor_name, s.amount, s.answer, s.closed_at, p.display_name as who
from acc_receipt_search s left join person p on p.id = s.responsible_person_id where s.id::text = $1`,
[b.search_id],
)
).rows[0];
if (!s) throw new ChargebackError(404, "not_found", "поиск чека не найден");
if (s.closed_at) throw new ChargebackError(409, "closed", "поиск чека уже закрыт");
if (s.answer) return { ok: true, already: true, answer: s.answer };
const op = `${s.vendor_name ?? "вендор неизвестен"}${s.amount != null ? ` $${Number(s.amount).toFixed(2)}` : ""}`;
await recordSearchAnswer(deps.pool, s.id, kind as AnswerKind, typeof b.who === "string" ? b.who : (s.who ?? "сотрудник"), op);
return { ok: true, already: false, answer: kind };
}),
);
}