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

@@ -100,6 +100,12 @@ export class DriveClient implements DriveStore {
return out;
}
/** Имя и тип файла. */
async meta(fileId: string): Promise<{ name: string; mimeType: string }> {
const res = await this.call(`${API}/files/${encodeURIComponent(fileId)}?fields=name,mimeType&supportsAllDrives=true`);
return (await res.json()) as { name: string; mimeType: string };
}
async download(fileId: string): Promise<Buffer> {
const res = await this.call(`${API}/files/${encodeURIComponent(fileId)}?alt=media&supportsAllDrives=true`);
return Buffer.from(await res.arrayBuffer());

View File

@@ -1,6 +1,7 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
import { diffWithOriginal, runFinalize } from "./finalize.js";
import { cantDoneText, diffWithOriginal, originalProblem, runFinalize } from "./finalize.js";
import type { QboClient } from "./qbo-client.js";
import { buildDailySummary, postDailySummary, twoWorkdaysAgo } from "./summary.js";
import { createSlackPoster } from "./slack.js";
@@ -11,7 +12,7 @@ const TABLES = [
"acc_manual_review", "acc_invoices_review", "acc_categorization_review", "acc_certificates_review",
"acc_invoices_review_original", "acc_categorization_review_original", "acc_certificates_review_original",
"acc_invoices_review_history", "acc_categorization_review_history", "acc_certificates_review_history",
"acc_invoices", "acc_insurance_certificates", "acc_receipt_search",
"acc_invoices", "acc_insurance_certificates", "acc_receipt_search", "acc_feed_txn",
];
d("завершение ручного разбора и сводка (временная БД)", () => {
@@ -126,7 +127,8 @@ d("завершение ручного разбора и сводка (врем
values ('tx-1', 'run-1', now(), '{"account":"Materials"}', 80, 'ждёт документ')`,
);
expect(await q("select kind from acc_manual_review")).toEqual([{ kind: "categorization" }]);
await q("update acc_categorization_review set done = true, done_by = 'Anastasia' where feed_txn_id = 'tx-1'");
// проблема решена (документ найден): человек очищает её, оригинал сохраняется в _original
await q("update acc_categorization_review set problem_highlight = null, done = true, done_by = 'Anastasia' where feed_txn_id = 'tx-1'");
const res = await fin();
expect(res.finalized).toEqual({ invoices: 0, categorization: 1, certificates: 0 });
const h = await q("select closed_by, changed_fields, suggestion from acc_categorization_review_history where feed_txn_id = 'tx-1'");
@@ -138,6 +140,63 @@ d("завершение ручного разбора и сводка (врем
expect(await q("select 1 from acc_manual_review")).toHaveLength(0);
});
it("Done при нерешённой проблеме сбрасывается: исходная проблема остаётся, добавляется «Can't done» с секундами, старая отметка убирается", async () => {
await q(`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, problem_highlight) values ('tx-9', 'r', now(), '{"account":"Materials"}', 'проект неясен')`);
await q("update acc_categorization_review set done = true, done_by = 'Yulia' where feed_txn_id = 'tx-9'");
const r1 = await fin({ now: () => new Date(Date.now() + 7200_000) });
expect(r1.rejected).toHaveLength(1);
const p1 = (await q("select done, problem_highlight from acc_categorization_review where feed_txn_id = 'tx-9'"))[0];
expect(p1.done).toBe(false);
expect(p1.problem_highlight).toMatch(/^проект неясен \| Can't done - not solved yet\. \d{2}$/);
await q("update acc_categorization_review set done = true where feed_txn_id = 'tx-9'");
await fin({ now: () => new Date(Date.now() + 7200_000) });
const p2 = (await q("select problem_highlight from acc_categorization_review where feed_txn_id = 'tx-9'"))[0].problem_highlight as string;
expect(p2.match(/Can't done/g)).toHaveLength(1); // старая отметка убрана
expect(originalProblem(p2)).toBe("проект неясен");
});
it("Done: операция уже есть в QuickBooks - строка уходит, проводка не повторяется; нет в QuickBooks - «not solved»", async () => {
await q(`insert into acc_feed_txn (feed_txn_id, txn_date, amount, vendor_name) values ('tx-q', '2026-11-27', 16.99, 'Zoom Communications'), ('tx-n', '2026-11-27', 99.00, 'Nobody Inc')`);
await q(`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, problem_highlight) values ('tx-q', 'r', now(), '{"account":"Software"}', 'нужен человек'), ('tx-n', 'r', now(), '{"account":"Other"}', 'нужен человек')`);
await q("update acc_categorization_review set done = true, done_by = 'Yulia'");
const qbo = {
async query(sql: string) {
return sql.includes("16.99") ? { Purchase: [{ Id: "4174", EntityRef: { name: "Zoom Video Communications" } }] } : {};
},
} as unknown as QboClient;
const res = await fin({ qbo });
expect(res.finalized.categorization).toBe(1);
expect(res.rejected).toHaveLength(1);
const h = (await q("select qbo_txn_id, qbo_posted_at from acc_categorization_review_history where feed_txn_id = 'tx-q'"))[0];
expect(h.qbo_txn_id).toBe("4174");
expect(h.qbo_posted_at).not.toBeNull();
expect((await q("select problem_highlight from acc_categorization_review where feed_txn_id = 'tx-n'"))[0].problem_highlight).toContain("Can't done - not solved yet.");
});
it("Done: если QuickBooks недоступен, «not solved» не пишется - запись ждёт следующей проверки", async () => {
await q(`insert into acc_feed_txn (feed_txn_id, txn_date, amount, vendor_name) values ('tx-e', '2026-11-27', 5.00, 'Vendor X')`);
await q(`insert into acc_categorization_review (feed_txn_id, run_id, run_started_at, suggestion, problem_highlight) values ('tx-e', 'r', now(), '{"account":"A"}', 'проблема')`);
await q("update acc_categorization_review set done = true");
const qbo = { async query() { throw new Error("down"); } } as unknown as QboClient;
const res = await fin({ qbo });
expect(res.rejected).toEqual([]);
expect((await q("select done, problem_highlight from acc_categorization_review"))[0]).toMatchObject({ done: true, problem_highlight: "проблема" });
});
it("инвойс: проблема с заполненным «ответом» считается решённой", async () => {
const id = await newInvoice();
await q("update acc_invoices_review set problem_highlight = 'контракт не найден', done = true where id = $1", [id]);
expect((await fin()).rejected).toHaveLength(1);
await q("update acc_invoices_review set answer = 'проведи без договора', done = true where id = $1", [id]);
expect((await fin()).finalized.invoices).toBe(1);
});
it("cantDoneText: пустая исходная проблема - только отметка; причина валидации в скобках", () => {
expect(cantDoneText(null, new Date(2026, 10, 30, 12, 0, 7))).toBe("Can't done - not solved yet. 07");
expect(cantDoneText("нет чека | Can't done - not solved yet. 41", new Date(2026, 10, 30, 12, 0, 9), "нет чека")).toBe("нет чека | Can't done - not solved yet. 09 (нет чека)");
expect(originalProblem("Завершение отклонено: что-то")).toBe("");
});
it("сертификат: обновляет существующий, создаёт новый, отклоняет пустой", async () => {
const [{ id: certId }] = await q(
"insert into acc_insurance_certificates (vendor_name, valid_until, drive_file_id) values ('Roofers Inc', '2026-11-20', 'f-1') returning id",

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 {

View File

@@ -35,8 +35,10 @@ export interface JobHandlers {
"spam-rescue"?: () => Promise<unknown>;
/** Проводка в QuickBooks операций, отмеченных Done (после finalize). */
"categorize-post"?: () => Promise<unknown>;
/** Вложения документов (чек, инвойс) к записям QuickBooks; при невозможности загрузки - ссылка на Drive в Memo. */
"qbo-attach"?: () => Promise<unknown>;
}
export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary", "fraud-flags", "invoice-check", "invoice-paid", "invoice-reconcile", "receipts-slack", "receipt-search", "receipt-weekly-report", "certificates", "reconcile-monthly", "history-weekly", "fraud-weekly", "spam-rescue", "categorize-post"] as const;
export const JOB_NAMES = ["invoices-mail", "finalize", "categorize", "summary", "fraud-flags", "invoice-check", "invoice-paid", "invoice-reconcile", "receipts-slack", "receipt-search", "receipt-weekly-report", "certificates", "reconcile-monthly", "history-weekly", "fraud-weekly", "spam-rescue", "categorize-post", "qbo-attach"] as const;
export interface ApiDeps {
pool: Pool;

View File

@@ -16,6 +16,8 @@ import { GmailClient } from "./gmail.js";
import { GoogleAuth } from "./google.js";
import { runSpamRescue } from "./spam-rescue.js";
import { runCategorizePost } from "./categorize-post.js";
import { makeQboClient } from "./qbo-client.js";
import { runQboAttach } from "./qbo-attach.js";
import { runHistoryWeekly } from "./history-report.js";
import { makeClaudeStatementReader, runMonthlyReconcile } from "./reconcile.js";
import { buildApi } from "./http-api.js";
@@ -29,7 +31,7 @@ import { runReceiptSearch, runReceiptWeeklyReport } from "./receipt-search.js";
import { runReceiptsSlack } from "./receipts.js";
import { loadNonWorkdays } from "./workdays.js";
const { common, service: s } = loadServiceSettings("accounting_automation", accountingSchema);
const { common, service: s, raw: rawSettings } = loadServiceSettings("accounting_automation", accountingSchema);
const log = createLogger("accounting_automation", common.logLevel);
const pool = createPool(common.database.url, 6);
@@ -42,6 +44,9 @@ const claude = makeClaudeRunner({
});
const auth = s.google ? new GoogleAuth({ client_email: s.google.client_email, private_key: s.google.private_key }) : null;
const drive = auth && s.google?.rootFolderId ? new DriveClient({ auth, rootFolderId: s.google.rootFolderId }) : null;
// Прямой клиент QuickBooks (токен у qbo_auth): проверка операции при Done и вложения документов
const qboAuthToken = (rawSettings.qbo_auth as { http?: { token?: string } } | undefined)?.http?.token;
const qbo = qboAuthToken ? makeQboClient({ authUrl: process.env.KHB_QBO_AUTH_URL ?? "http://khb-qbo-auth:8095", authToken: qboAuthToken }) : null;
const slack = s.slack ? createSlackClient({ botToken: s.slack.botToken }) : null;
const notify = async (text: string): Promise<void> => {
@@ -100,6 +105,7 @@ const app = buildApi({
delaySeconds: s.finalizeDelaySeconds,
noReceiptLimitUsd: s.receipts.noReceiptLimitUsd,
notify,
qbo,
notifyPerson: slack ? async (slackUserId, text) => void (await slack.postMessage(slackUserId, text)) : undefined,
});
return booked.closed ? { ...done, booked } : done;
@@ -156,6 +162,10 @@ const app = buildApi({
"history-weekly": () => runHistoryWeekly({ pool, ...reportSlack() }),
"fraud-weekly": () => runFraudWeekly({ pool, ...reportSlack() }),
"categorize-post": async () => runCategorizePost({ pool, claude, log, notify }),
"qbo-attach": async () => {
if (!qbo || !drive) throw new Error("не настроены qbo_auth (токен) или Drive");
return runQboAttach({ pool, qbo, drive, log });
},
"spam-rescue": async () => {
if (!auth || !s.google) throw new Error("не настроены google (ключ сервисного аккаунта)");
return runSpamRescue({ pool, auth, log, mailboxes: s.google.spamRescue.mailboxes, sourceMailbox: s.google.gmailUser, dryRun: s.google.spamRescue.dryRun });

View File

@@ -0,0 +1,130 @@
import type { Logger, Pool } from "khb_common";
import { QboFileTooLarge, type QboClient } from "./qbo-client.js";
/**
* Вложения к записям QuickBooks (решение Юрия 2026-11-30): чек или инвойс, по которому проведена операция, прикладывается к записи
* (Purchase) прямо в QuickBooks. Файл скачивается с Drive и грузится через API (Attachable). Если файл не проходит по размеру или типу,
* вместо вложения в Memo (PrivateNote) записи дописывается ссылка на файл на Drive. Результат фиксируется в acc_qbo_attachments
* (одна запись на пару «запись QuickBooks + файл»), повторный запуск ничего не дублирует.
* Источники: проведённые категоризации (чек/инвойс из предложения или привязанный к операции, в том числе закрытые автоматически
* «уже проведено в QuickBooks (purchase N)») и оплаченные инвойсы (acc_invoices.qbo_txn_id).
*/
const MAX_ATTEMPTS = 3;
const BATCH = 20;
const LOCK_KEY = 7_340_003;
export interface AttachDrive {
meta(fileId: string): Promise<{ name: string; mimeType: string }>;
download(fileId: string): Promise<Buffer>;
}
export interface AttachDeps {
pool: Pool;
qbo: QboClient;
drive: AttachDrive;
log: Logger;
}
export interface AttachResult {
queued: number;
attached: number;
memoLinks: number;
failed: number;
skipped: number;
}
export const driveUrl = (fileId: string): string => `https://drive.google.com/file/d/${fileId}/view`;
/** Ставит в очередь пары «запись QuickBooks + файл» из проведённых категоризаций и оплаченных инвойсов. */
export async function queueAttachments(pool: Pool): Promise<number> {
const a = await pool.query(
`insert into acc_qbo_attachments (qbo_entity_type, qbo_entity_id, drive_file_id, source)
select 'Purchase', x.eid, d.drive_file_id, 'categorization'
from (select h.feed_txn_id::text as feed, h.suggestion,
coalesce(h.qbo_txn_id, substring(h.done_by from '\\(purchase (\\d+)\\)')) as eid
from acc_categorization_review_history h) x
cross join lateral (
select r.drive_file_id from acc_receipts r
where r.feed_txn_id = x.feed or (x.suggestion ? 'receipt_id' and r.id::text = x.suggestion->>'receipt_id')
union
select i.drive_file_id from acc_invoices i
where jsonb_typeof(x.suggestion->'invoice_ids') = 'array' and i.id::text in (select jsonb_array_elements_text(x.suggestion->'invoice_ids'))
) d
where x.eid is not null
on conflict do nothing`,
);
const b = await pool.query(
`insert into acc_qbo_attachments (qbo_entity_type, qbo_entity_id, drive_file_id, source)
select 'Purchase', i.qbo_txn_id, i.drive_file_id, 'invoice' from acc_invoices i
where i.qbo_txn_id is not null and i.drive_file_id is not null
on conflict do nothing`,
);
return (a.rowCount ?? 0) + (b.rowCount ?? 0);
}
const TOO_BIG = /size|large|too big|unsupported|content.?type|file type|extension/i;
export async function runQboAttach(deps: AttachDeps): Promise<AttachResult> {
const { pool, qbo, drive, log } = deps;
const out: AttachResult = { queued: 0, attached: 0, memoLinks: 0, failed: 0, skipped: 0 };
const client = await pool.connect();
try {
const lock = await client.query("select pg_try_advisory_lock($1) as ok", [LOCK_KEY]);
if (!lock.rows[0].ok) return out;
try {
out.queued = await queueAttachments(pool);
const { rows } = await pool.query<{ id: string; qbo_entity_type: string; qbo_entity_id: string; drive_file_id: string; attempts: number }>(
"select id, qbo_entity_type, qbo_entity_id, drive_file_id, attempts from acc_qbo_attachments where status = 'pending' and attempts < $1 order by created_at limit $2",
[MAX_ATTEMPTS, BATCH],
);
for (const r of rows) {
const setDone = (status: string, attachable: string | null, err: string | null): Promise<unknown> =>
pool.query("update acc_qbo_attachments set status = $2, attachable_id = $3, error = $4, done_at = now(), attempts = attempts + 1 where id = $1", [r.id, status, attachable, err]);
try {
const meta = await drive.meta(r.drive_file_id);
const exist = await qbo.query(`select Id, FileName from Attachable where AttachableRef.EntityRef.Type = '${r.qbo_entity_type}' and AttachableRef.EntityRef.value = '${r.qbo_entity_id}'`);
const list = (exist.Attachable as { Id: string; FileName?: string }[] | undefined) ?? [];
const dup = list.find((x) => x.FileName === meta.name);
if (dup) {
await setDone("attached", dup.Id, null);
out.skipped++;
continue;
}
let memo = false;
try {
const bytes = await drive.download(r.drive_file_id);
const up = await qbo.uploadAttachment({
fileName: meta.name,
mime: meta.mimeType,
bytes,
attachTo: { type: r.qbo_entity_type, id: r.qbo_entity_id },
note: `Документ с Drive: ${driveUrl(r.drive_file_id)}`,
});
await setDone("attached", up.id, null);
out.attached++;
log.info({ entity: r.qbo_entity_id, file: r.drive_file_id }, "документ приложен в QuickBooks");
} catch (e) {
if (e instanceof QboFileTooLarge || TOO_BIG.test(String(e)) || r.attempts + 1 >= MAX_ATTEMPTS) memo = true;
else throw e;
}
if (memo) {
await qbo.appendNote(r.qbo_entity_type.toLowerCase(), r.qbo_entity_id, `Документ: ${driveUrl(r.drive_file_id)}`);
await setDone("memo_link", null, "файл не загружен в QuickBooks: ссылка на Drive в Memo");
out.memoLinks++;
log.info({ entity: r.qbo_entity_id, file: r.drive_file_id }, "ссылка на документ записана в Memo QuickBooks");
}
} catch (e) {
out.failed++;
const left = r.attempts + 1;
await pool.query("update acc_qbo_attachments set attempts = $2, error = $3, status = case when $2 >= $4 then 'failed' else 'pending' end where id = $1", [r.id, left, String(e).slice(0, 500), MAX_ATTEMPTS]);
log.error({ entity: r.qbo_entity_id, file: r.drive_file_id, err: String(e) }, "приложить документ к записи QuickBooks не удалось");
}
}
return out;
} finally {
await client.query("select pg_advisory_unlock($1)", [LOCK_KEY]);
}
} finally {
client.release();
}
}

View File

@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";
import { makeQboClient, QboFileTooLarge, MAX_ATTACH_BYTES } from "./qbo-client.js";
function fakeFetch(calls: { url: string; init?: RequestInit }[], respond: (url: string, init?: RequestInit) => Response): typeof fetch {
return (async (url: string | URL, init?: RequestInit) => {
calls.push({ url: String(url), init });
if (String(url).endsWith("/token") || String(url).includes("/token?")) {
return new Response(JSON.stringify({ accessToken: "AT", realmId: "R1", apiBase: "https://qbo.test", expiresAt: new Date(Date.now() + 3600_000).toISOString() }), { status: 200 });
}
return respond(String(url), init);
}) as unknown as typeof fetch;
}
describe("qbo-client", () => {
it("query: токен берётся у qbo_auth, запрос уходит с Bearer", async () => {
const calls: { url: string; init?: RequestInit }[] = [];
const c = makeQboClient({ authUrl: "http://auth", authToken: "T", fetchFn: fakeFetch(calls, () => new Response(JSON.stringify({ QueryResponse: { Purchase: [{ Id: "1" }] } }), { status: 200 })) });
const r = await c.query("select * from Purchase");
expect(r.Purchase).toEqual([{ Id: "1" }]);
expect(calls[0]!.url).toBe("http://auth/token");
expect((calls[0]!.init!.headers as Record<string, string>).authorization).toBe("Bearer T");
expect(calls[1]!.url).toContain("https://qbo.test/v3/company/R1/query?query=select%20*%20from%20Purchase");
});
it("401: токен обновляется принудительно и запрос повторяется один раз", async () => {
const calls: { url: string; init?: RequestInit }[] = [];
let n = 0;
const c = makeQboClient({ authUrl: "http://auth", authToken: "T", fetchFn: fakeFetch(calls, () => (n++ === 0 ? new Response("expired", { status: 401 }) : new Response(JSON.stringify({ QueryResponse: {} }), { status: 200 }))) });
await c.query("select 1");
expect(calls.some((x) => x.url.includes("/token?force=true"))).toBe(true);
});
it("uploadAttachment: multipart с привязкой к записи; слишком большой файл - QboFileTooLarge", async () => {
const calls: { url: string; init?: RequestInit }[] = [];
const c = makeQboClient({ authUrl: "http://auth", authToken: "T", fetchFn: fakeFetch(calls, () => new Response(JSON.stringify({ AttachableResponse: [{ Attachable: { Id: "77" } }] }), { status: 200 })) });
const r = await c.uploadAttachment({ fileName: "a.pdf", mime: "application/pdf", bytes: Buffer.from("PDF"), attachTo: { type: "Purchase", id: "4174" } });
expect(r.id).toBe("77");
const up = calls.find((x) => x.url.includes("/upload"))!;
const body = Buffer.from(up.init!.body as Buffer).toString("latin1");
expect(body).toContain('"value":"4174"');
expect(body).toContain('"type":"Purchase"');
expect(body).toContain("PDF");
await expect(c.uploadAttachment({ fileName: "b.pdf", mime: "application/pdf", bytes: Buffer.alloc(MAX_ATTACH_BYTES + 1), attachTo: { type: "Purchase", id: "1" } })).rejects.toBeInstanceOf(QboFileTooLarge);
});
it("appendNote: дописывает Memo (sparse update) и не дублирует", async () => {
const calls: { url: string; init?: RequestInit }[] = [];
const c = makeQboClient({
authUrl: "http://auth",
authToken: "T",
fetchFn: fakeFetch(calls, (url, init) => (init?.method === "POST" ? new Response("{}", { status: 200 }) : new Response(JSON.stringify({ Purchase: { Id: "5", SyncToken: "2", PrivateNote: "старое" } }), { status: 200 }))),
});
await c.appendNote("purchase", "5", "Документ: https://x");
const post = calls.find((x) => x.init?.method === "POST" && !x.url.includes("/token"))!;
expect(JSON.parse(post.init!.body as string)).toMatchObject({ Id: "5", SyncToken: "2", sparse: true, PrivateNote: "старое\nДокумент: https://x" });
});
});

View File

@@ -0,0 +1,108 @@
/**
* Прямой клиент QuickBooks Online API: токен берётся у qbo_auth (POST /token, служебный Bearer-токен, docker-сеть).
* Нужен для действий, которые не должен делать агент: точечная проверка операции (query) и загрузка вложений (Attachable).
* Деньги клиент не двигает: только чтение, вложения и дописывание PrivateNote.
*/
export type FetchFn = typeof fetch;
export interface QboClient {
/** Запрос на языке QuickBooks («select * from Purchase where ...»): возвращает QueryResponse. */
query(sql: string): Promise<Record<string, unknown>>;
/** Читает запись (entity: purchase, bill ...). */
read(entity: string, id: string): Promise<Record<string, unknown> | null>;
/** Дописывает текст в PrivateNote записи (sparse update). */
appendNote(entity: string, id: string, text: string): Promise<void>;
/** Загружает файл и привязывает к записи. Бросает QboFileTooLarge, если файл не пролезает. */
uploadAttachment(a: { fileName: string; mime: string; bytes: Buffer; attachTo: { type: string; id: string }; note?: string }): Promise<{ id: string }>;
}
export class QboFileTooLarge extends Error {}
/** Предел размера вложения через наш клиент (QuickBooks принимает до 100 МБ, но держим разумный запас). */
export const MAX_ATTACH_BYTES = 20 * 1024 * 1024;
const MINOR = 75;
interface Tok {
accessToken: string;
realmId: string;
apiBase: string;
expiresAt: number;
}
export function makeQboClient(o: { authUrl: string; authToken: string; fetchFn?: FetchFn }): QboClient {
const f = o.fetchFn ?? fetch;
let tok: Tok | null = null;
async function token(force = false): Promise<Tok> {
if (!force && tok && tok.expiresAt - Date.now() > 60_000) return tok;
const res = await f(`${o.authUrl}/token${force ? "?force=true" : ""}`, { method: "POST", headers: { authorization: `Bearer ${o.authToken}` } });
if (!res.ok) throw new Error(`qbo_auth /token: ${res.status}`);
const j = (await res.json()) as { accessToken: string; realmId: string; apiBase: string; expiresAt: string };
tok = { accessToken: j.accessToken, realmId: j.realmId, apiBase: j.apiBase, expiresAt: Date.parse(j.expiresAt) };
return tok;
}
/** Запрос с одним повтором при 401 (токен принудительно обновляется). */
async function call(path: string, init: (t: Tok) => RequestInit): Promise<Response> {
for (let attempt = 0; ; attempt++) {
const t = await token(attempt > 0);
const sep = path.includes("?") ? "&" : "?";
const res = await f(`${t.apiBase}/v3/company/${t.realmId}/${path}${sep}minorversion=${MINOR}`, init(t));
if (res.status === 401 && attempt === 0) continue;
if (!res.ok) throw new Error(`QuickBooks ${res.status}: ${(await res.text()).slice(0, 300)}`);
return res;
}
}
const json = (t: Tok): Record<string, string> => ({ authorization: `Bearer ${t.accessToken}`, accept: "application/json" });
return {
async query(sql) {
const res = await call(`query?query=${encodeURIComponent(sql)}`, (t) => ({ headers: json(t) }));
return ((await res.json()) as { QueryResponse?: Record<string, unknown> }).QueryResponse ?? {};
},
async read(entity, id) {
try {
const res = await call(`${entity}/${encodeURIComponent(id)}`, (t) => ({ headers: json(t) }));
const j = (await res.json()) as Record<string, Record<string, unknown>>;
return j[Object.keys(j).find((k) => k !== "time") ?? ""] ?? null;
} catch (e) {
if (String(e).includes("QuickBooks 400") || String(e).includes("QuickBooks 404")) return null;
throw e;
}
},
async appendNote(entity, id, text) {
const cur = await this.read(entity, id);
if (!cur) throw new Error(`${entity} ${id} не найдена`);
const prev = typeof cur.PrivateNote === "string" ? cur.PrivateNote : "";
if (prev.includes(text)) return;
const next = (prev ? `${prev}\n` : "") + text;
await call(entity, (t) => ({
method: "POST",
headers: { ...json(t), "content-type": "application/json" },
body: JSON.stringify({ Id: id, SyncToken: cur.SyncToken, sparse: true, PrivateNote: next.slice(0, 4000) }),
}));
},
async uploadAttachment(a) {
if (a.bytes.length > MAX_ATTACH_BYTES) throw new QboFileTooLarge(`файл ${a.bytes.length} байт больше ${MAX_ATTACH_BYTES}`);
const boundary = "khb" + Math.random().toString(36).slice(2);
const meta = JSON.stringify({
FileName: a.fileName,
ContentType: a.mime,
Note: a.note,
AttachableRef: [{ EntityRef: { type: a.attachTo.type, value: a.attachTo.id } }],
});
const body = Buffer.concat([
Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file_metadata_01"\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n`),
Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file_content_01"; filename="${a.fileName.replace(/"/g, "")}"\r\nContent-Type: ${a.mime}\r\n\r\n`),
a.bytes,
Buffer.from(`\r\n--${boundary}--\r\n`),
]);
const res = await call("upload", (t) => ({ method: "POST", headers: { ...json(t), "content-type": `multipart/form-data; boundary=${boundary}` }, body }));
const j = (await res.json()) as { AttachableResponse?: { Attachable?: { Id?: string }; Fault?: unknown }[] };
const r = j.AttachableResponse?.[0];
const id = r?.Attachable?.Id;
if (!id) throw new Error(`QuickBooks не принял файл: ${JSON.stringify(r?.Fault ?? j).slice(0, 300)}`);
return { id };
},
};
}

View File

@@ -0,0 +1,16 @@
-- Вложения документов (чек, инвойс) к записям QuickBooks: что уже приложено или заменено ссылкой на Drive в Memo.
create table if not exists acc_qbo_attachments (
id uuid primary key default gen_random_uuid(),
qbo_entity_type text not null,
qbo_entity_id text not null,
drive_file_id text not null,
source text,
status text not null default 'pending' check (status in ('pending', 'attached', 'memo_link', 'failed')),
attachable_id text,
attempts int not null default 0,
error text,
created_at timestamptz not null default now(),
done_at timestamptz,
unique (qbo_entity_type, qbo_entity_id, drive_file_id)
);
alter table acc_qbo_attachments enable row level security;