import { withTx, type Pool } from "khb_common"; import { normalizeVendorName } from "./vendor-name.js"; /** * Серверная часть процессов «Chargeback к контракту подрядчика» и «Подозрительные операции по карте (fraud)»: * строки acc_chargeback (kind contract | card_fraud) и их задачи в acc_manual_review (kind chargeback). * Пересчёт acc_contracts.retained_amount и закрытие по остатку делают триггеры БД (миграция 062). * Слой чистый: им пользуются HTTP-ручки ассистента менеджера и MCP-инструменты Юли и Анастасии. */ type PoolClient = Parameters[1]>[0]; type Row = Record; /** Ошибка запроса: status - HTTP-код ручки, message - по-русски (MCP показывает её пользователю). */ export class ChargebackError extends Error { constructor( public readonly status: number, public readonly code: string, message: string, ) { super(message); } } const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const bad = (message: string): ChargebackError => new ChargebackError(400, "bad_request", message); function reqStr(v: unknown, name: string): string { if (typeof v !== "string" || !v.trim()) throw bad(`${name}: нужна непустая строка`); return v.trim(); } function optStr(v: unknown, name: string): string | null { if (v === undefined || v === null || v === "") return null; if (typeof v !== "string") throw bad(`${name}: ожидалась строка`); return v.trim() || null; } function optUuid(v: unknown, name: string): string | null { const s = optStr(v, name); if (s !== null && !UUID.test(s)) throw bad(`${name}: ожидался uuid`); return s; } function amountOf(v: unknown, name: string): number { const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v; if (typeof n !== "number" || !Number.isFinite(n) || n <= 0 || n >= 1e12) throw bad(`${name}: ожидалось положительное число`); return Math.round(n * 100) / 100; } function optDate(v: unknown, name: string): string | null { const s = optStr(v, name); if (s === null) return null; if (!/^\d{4}-\d{2}-\d{2}$/.test(s) || new Date(`${s}T00:00:00Z`).toISOString().slice(0, 10) !== s) throw bad(`${name}: ожидалась дата YYYY-MM-DD`); return s; } const COLS = `c.id, c.kind, c.status, c.created_at, c.contract_id, c.defect_daily_log_id, c.defect_daily_log_url, c.defect_description, c.extra_daily_logs, c.reported_by, c.decided_by, c.decided_at, c.fix_vendor_name, c.fix_invoice_id, c.retained_amount::float8 as retained_amount, c.close_reason, c.confirmed_by, c.confirmed_at, c.feed_txn_id, c.reason, c.bank, to_char(c.file_by, 'YYYY-MM-DD') as file_by, c.bank_decision, c.kit, k.vendor_name as contract_vendor_name, k.project_customer_id as contract_project_customer_id, k.jt_job_id as contract_jt_job_id, k.total_amount::float8 as contract_total, k.retained_amount::float8 as contract_retained, k.paid_amount::float8 as contract_paid, (k.total_amount - k.retained_amount - k.paid_amount)::float8 as contract_remaining`; const FROM = "from acc_chargeback c left join acc_contracts k on k.id = c.contract_id"; async function load(c: Pick, id: string, lock = false): Promise { const r = await c.query(`select ${COLS} ${FROM} where c.id = $1 ${lock ? "for update of c" : ""}`.trim(), [id]); if (!r.rows[0]) throw new ChargebackError(404, "not_found", "Строка chargeback не найдена."); return r.rows[0] as Row; } /** id строки: полный uuid, 8+ символов id строки или id задачи из acc_review_list. */ export async function resolveChargebackId(pool: Pick, v: unknown): Promise { if (typeof v !== "string" || !v.trim()) throw bad("id: нужен id строки chargeback или задачи"); const s = v.trim().toLowerCase(); if (UUID.test(s)) { const t = await pool.query("select ref_id from acc_manual_review where id = $1 and ref_table = 'acc_chargeback'", [s]); return (t.rows[0]?.ref_id as string | undefined) ?? s; } if (!/^[0-9a-f]{8,}$/.test(s)) throw bad("id: первые 8 символов (или полный uuid) строки chargeback либо задачи"); const rows = (await pool.query("select id::text as id from acc_chargeback where id::text like $1 limit 2", [`${s}%`])).rows; const tasks = (await pool.query("select ref_id from acc_manual_review where ref_table = 'acc_chargeback' and id::text like $1 limit 2", [`${s}%`])).rows; const all = new Set([...rows.map((r) => r.id as string), ...tasks.map((r) => r.ref_id as string)]); if (all.size === 0) throw new ChargebackError(404, "not_found", "Строка chargeback не найдена."); if (all.size > 1) throw bad("Префикс id неоднозначен: укажите больше символов."); return [...all][0]!; } // ----------------------------------------------------------------- задачи в очереди function taskSpec(r: Row): { role: "accountant" | "cfo"; problem: string } | null { const vendor = String(r.contract_vendor_name ?? "?"); const money = (n: unknown): string => (typeof n === "number" ? n.toFixed(2) : "?"); if (r.kind === "contract") { switch (r.status) { case "claimed": return { role: "cfo", problem: `Chargeback: решить, удерживать ли с подрядчика ${vendor} стоимость исправления дефекта (${String(r.defect_description ?? "без описания")}). Daily Log ${String(r.defect_daily_log_url ?? "?")}. Остаток по контракту ${money(r.contract_remaining)}` }; case "approved": return { role: "accountant", problem: `Chargeback одобрен (дефект исправляет ${String(r.fix_vendor_name ?? "другой подрядчик")}): дождаться его инвойса и привязать (acc_chargeback_link_invoice) с суммой удержания с ${vendor}` }; case "fix_invoiced": return { role: "cfo", problem: `Chargeback: подтвердить сумму удержания ${money(r.retained_amount)} с подрядчика ${vendor} (acc_chargeback_confirm)` }; case "applied": return { role: "accountant", problem: `Удержание ${money(r.retained_amount)} с подрядчика ${vendor} применено: сообщить ему в JobTread (сумма, основание, новый остаток ${money(r.contract_remaining)})` }; default: return null; } } const deadline = r.file_by ? `, срок подачи ${String(r.file_by)}` : ""; switch (r.status) { case "collecting": return { role: "accountant", problem: `Fraud по операции ${String(r.feed_txn_id)}: собрать комплект и подать заявку в банк${deadline}` }; case "filed": return { role: "accountant", problem: `Fraud по операции ${String(r.feed_txn_id)}: ждём решения банка` }; case "refunded": return { role: "accountant", problem: `Fraud по операции ${String(r.feed_txn_id)}: банк вернул деньги, проверить возврат в ленте QuickBooks и закрыть` }; case "rejected": return { role: "accountant", problem: `Fraud по операции ${String(r.feed_txn_id)}: банк отказал (${String(r.bank_decision ?? "причина не записана")}); закрыть или подать повторно` }; default: return null; } } /** Приводит задачу acc_manual_review к статусу строки; для закрытых задачу убирает. */ export async function syncTask(c: Pick, id: string): Promise { const r = await load(c, id); const spec = taskSpec(r); if (!spec) { await c.query("delete from acc_manual_review where ref_table = 'acc_chargeback' and ref_id = $1", [id]); return; } await c.query( `insert into acc_manual_review (kind, ref_table, ref_id, assignee_role, problem_highlight) values ('chargeback', 'acc_chargeback', $1, $2, $3) on conflict (ref_table, ref_id) do update set assignee_role = excluded.assignee_role, problem_highlight = excluded.problem_highlight, snoozed_until = null`, [id, spec.role, spec.problem], ); } // ----------------------------------------------------------------- контракт chargeback (ручки ассистента менеджера) export interface ContractCandidate { id: string; vendor_name: string; project_customer_id: string; jt_job_id: string | null; stage: string | null; total_amount: number; paid_amount: number; retained_amount: number; remaining: number; } const CONTRACT_COLS = `id, vendor_name, project_customer_id, jt_job_id, stage, total_amount::float8 as total_amount, paid_amount::float8 as paid_amount, retained_amount::float8 as retained_amount, (total_amount - retained_amount - paid_amount)::float8 as remaining`; async function findContracts(pool: Pick, jobId: string, vendorName: string): Promise<{ matched: ContractCandidate[]; all: ContractCandidate[] }> { const { rows } = await pool.query(`select ${CONTRACT_COLS} from acc_contracts where jt_job_id = $1 order by vendor_name, stage`, [jobId]); const want = normalizeVendorName(vendorName); return { matched: rows.filter((k) => normalizeVendorName(k.vendor_name) === want), all: rows }; } /** Строки chargeback вида contract по проекту JobTread и подрядчику, в том числе закрытые. */ export async function findChargebacks(pool: Pool, a: Row): Promise<{ rows: Row[] }> { const jobId = reqStr(a.job_id, "job_id"); const vendor = optStr(a.vendor_name, "vendor_name"); const dl = optStr(a.daily_log_id, "daily_log_id"); const { rows } = await pool.query(`select ${COLS} ${FROM} where c.kind = 'contract' and k.jt_job_id = $1 order by c.created_at`, [jobId]); const want = vendor ? normalizeVendorName(vendor) : null; return { rows: (rows as Row[]).filter((r) => (!want || normalizeVendorName(String(r.contract_vendor_name)) === want) && (!dl || r.defect_daily_log_id === dl)) }; } export type StartResult = | { result: "created" | "existing"; chargeback: Row } | { result: "candidates"; message: string; candidates: ContractCandidate[] }; async function createContractRow(pool: Pool, a: Row, closed: boolean): Promise { const dailyLogId = reqStr(a.daily_log_id, "daily_log_id"); const dailyLogUrl = optStr(a.daily_log_url, "daily_log_url"); const description = optStr(a.description, "description"); const reportedBy = optUuid(a.reported_by, "reported_by"); let contractId = optUuid(a.contract_id, "contract_id"); const exist = await pool.query("select id from acc_chargeback where defect_daily_log_id = $1", [dailyLogId]); if (exist.rows[0]) return { result: "existing", chargeback: await load(pool, exist.rows[0].id as string) }; if (contractId) { const k = await pool.query("select id from acc_contracts where id = $1", [contractId]); if (!k.rows[0]) throw new ChargebackError(404, "contract_not_found", "Контракт не найден."); } else { const jobId = reqStr(a.job_id, "job_id"); const vendor = reqStr(a.vendor_name, "vendor_name"); const { matched, all } = await findContracts(pool, jobId, vendor); if (matched.length !== 1) { return { result: "candidates", message: matched.length === 0 ? "Контракт подрядчика на этом проекте не найден: уточните у менеджера и вызовите снова с contract_id." : "Подходящих контрактов несколько: уточните у менеджера и вызовите снова с contract_id.", candidates: matched.length ? matched : all, }; } contractId = matched[0]!.id; } if (reportedBy) { const p = await pool.query("select 1 from person where id = $1", [reportedBy]); if (!p.rows[0]) throw bad("reported_by: такого person нет"); } const id = await withTx(pool, async (c) => { const ins = await c.query( `insert into acc_chargeback (kind, status, contract_id, defect_daily_log_id, defect_daily_log_url, defect_description, reported_by, close_reason) values ('contract', $1, $2, $3, $4, $5, $6, $7) on conflict (defect_daily_log_id) where defect_daily_log_id is not null do nothing returning id`, [closed ? "closed" : "claimed", contractId, dailyLogId, dailyLogUrl, description, reportedBy, closed ? "менеджер закрыл вопрос" : null], ); if (!ins.rows[0]) return null; const newId = ins.rows[0].id as string; await syncTask(c, newId); return newId; }); if (!id) { // параллельный вызов успел раньше const again = await pool.query("select id from acc_chargeback where defect_daily_log_id = $1", [dailyLogId]); return { result: "existing", chargeback: await load(pool, again.rows[0]!.id as string) }; } return { result: "created", chargeback: await load(pool, id) }; } /** chargeback_start: строка claimed и задача cfo. */ export const startChargeback = (pool: Pool, a: Row): Promise => createContractRow(pool, a, false); /** chargeback_close: менеджер закрыл вопрос; строка closed, задачи нет. */ export const closeChargebackByManager = (pool: Pool, a: Row): Promise => createContractRow(pool, a, true); /** chargeback_add_log: ссылка на повторный Daily Log (без дублей). */ export async function addDailyLog(pool: Pool, a: Row): Promise<{ chargeback: Row; added: boolean }> { const id = await resolveChargebackId(pool, a.chargeback_id); const url = reqStr(a.daily_log_url, "daily_log_url"); return withTx(pool, async (c) => { const r = await load(c, id, true); if (r.kind !== "contract") throw bad("Это не chargeback к контракту."); const known = [r.defect_daily_log_url, ...((r.extra_daily_logs as string[] | null) ?? [])]; if (known.includes(url)) return { chargeback: r, added: false }; await c.query("update acc_chargeback set extra_daily_logs = array_append(extra_daily_logs, $2) where id = $1", [id, url]); return { chargeback: await load(c, id), added: true }; }); } // ----------------------------------------------------------------- решения людей (MCP) /** Шаг 4: Анастасия решает удерживать (approve) или отклоняет (reject; строка сразу closed). */ export async function decideChargeback(pool: Pool, actor: string, a: Row): Promise { const id = await resolveChargebackId(pool, a.id); const decision = a.decision; if (decision !== "approve" && decision !== "reject") throw bad("decision: approve или reject"); const fixVendor = optStr(a.fix_vendor_name, "fix_vendor_name"); const comment = optStr(a.comment, "comment"); return withTx(pool, async (c) => { const r = await load(c, id, true); if (r.kind !== "contract") throw bad("Это не chargeback к контракту."); if (r.status !== "claimed") throw bad(`Решение уже принято (статус ${String(r.status)}).`); // approve без исполнителя оставил бы задачу Юле «дефект исправляет другой подрядчик»: подрядчика Б называет Анастасия при решении if (decision === "approve" && !fixVendor) throw bad("fix_vendor_name: для approve укажите подрядчика, который исправит дефект (подрядчик Б)"); if (decision === "approve") await c.query("update acc_chargeback set status = 'approved', decided_by = $2, decided_at = now(), fix_vendor_name = $3 where id = $1", [id, actor, fixVendor]); else await c.query("update acc_chargeback set status = 'closed', decided_by = $2, decided_at = now(), close_reason = $3 where id = $1", [id, actor, `отклонено${comment ? `: ${comment}` : ""}`]); await syncTask(c, id); return load(c, id); }); } /** * Шаг 6: Юля привязывает инвойс подрядчика Б и сумму удержания (по умолчанию - весь инвойс). * Вендор инвойса не совпал с fix_vendor_name - привязка выполняется, а в результат добавляется warnings (не блокирует). */ export async function linkFixInvoice(pool: Pool, actor: string, a: Row): Promise { const id = await resolveChargebackId(pool, a.id); const invoiceId = optUuid(a.invoice_id, "invoice_id"); if (!invoiceId) throw bad("invoice_id: нужен id инвойса из acc_invoices"); void actor; return withTx(pool, async (c) => { const r = await load(c, id, true); if (r.kind !== "contract") throw bad("Это не chargeback к контракту."); if (r.status !== "approved") throw bad(`Привязать инвойс можно только к одобренному chargeback (сейчас ${String(r.status)}).`); const inv = (await c.query("select amount::float8 as amount, project_customer_id, vendor_name from acc_invoices where id = $1", [invoiceId])).rows[0] as { amount: number; project_customer_id: string; vendor_name: string } | undefined; if (!inv) throw new ChargebackError(404, "invoice_not_found", "Инвойс не найден в acc_invoices (возможно, ещё не завершён разбор)."); if (inv.project_customer_id !== r.contract_project_customer_id) throw bad("Инвойс относится к другому проекту, чем контракт подрядчика А."); const retained = a.retained_amount === undefined || a.retained_amount === null ? inv.amount : amountOf(a.retained_amount, "retained_amount"); if (retained > inv.amount + 0.001) throw bad(`Сумма удержания ${retained.toFixed(2)} больше суммы инвойса ${inv.amount.toFixed(2)}.`); await c.query("update acc_chargeback set fix_invoice_id = $2, retained_amount = $3, status = 'fix_invoiced' where id = $1", [id, invoiceId, retained]); await syncTask(c, id); const warnings: string[] = []; const expected = typeof r.fix_vendor_name === "string" ? r.fix_vendor_name : null; if (expected && normalizeVendorName(expected) !== normalizeVendorName(inv.vendor_name)) warnings.push(`Вендор инвойса «${inv.vendor_name}» не совпадает с подрядчиком, которого назвала Анастасия (fix_vendor_name «${expected}»): проверьте, тот ли инвойс привязан.`); const out = await load(c, id); return warnings.length > 0 ? { ...out, warnings } : out; }); } /** Шаг 7: Анастасия подтверждает (или правит) сумму удержания; дальше триггер БД пересчитывает контракт (шаг 8). */ export async function confirmChargeback(pool: Pool, actor: string, a: Row): Promise { const id = await resolveChargebackId(pool, a.id); const override = a.retained_amount === undefined || a.retained_amount === null ? null : amountOf(a.retained_amount, "retained_amount"); return withTx(pool, async (c) => { const r = await load(c, id, true); if (r.kind !== "contract") throw bad("Это не chargeback к контракту."); if (r.status !== "fix_invoiced") throw bad(`Подтвердить можно строку со статусом fix_invoiced (сейчас ${String(r.status)}).`); await c.query("update acc_chargeback set retained_amount = coalesce($2, retained_amount), confirmed_by = $3, confirmed_at = now(), status = 'applied' where id = $1", [id, override, actor]); await syncTask(c, id); return load(c, id); }); } /** Закрытие вручную (Анастасия может раньше шага 12). Для fraud тоже подходит. */ export async function closeChargebackManually(pool: Pool, a: Row): Promise { const id = await resolveChargebackId(pool, a.id); const reason = reqStr(a.reason, "reason"); return withTx(pool, async (c) => { const r = await load(c, id, true); if (r.status === "closed") throw bad("Строка уже закрыта."); await c.query("update acc_chargeback set status = 'closed', close_reason = $2 where id = $1", [id, reason]); return load(c, id); }); } /** Список для Юли и Анастасии: открытые (по умолчанию) или с фильтром; по проекту QuickBooks - чтобы увидеть chargeback при разборе инвойса. */ export async function listChargebacks(pool: Pool, a: Row): Promise<{ rows: Row[] }> { const kind = a.kind === undefined ? null : a.kind; if (kind !== null && kind !== "contract" && kind !== "card_fraud") throw bad("kind: contract или card_fraud"); const status = optStr(a.status, "status"); const project = optStr(a.project_customer_id, "project_customer_id"); const includeClosed = a.include_closed === true; const { rows } = await pool.query( `select ${COLS} ${FROM} where ($1::text is null or c.kind = $1) and ($2::text is null or c.status = $2) and ($3::text is null or k.project_customer_id = $3) and ($4::boolean or c.status <> 'closed') order by c.created_at desc limit 100`, [kind, status, project, includeClosed || status === "closed"], ); return { rows: rows as Row[] }; } /** «Сколько я должна заплатить по контракту»: сумма, удержания, оплачено и остаток к оплате. */ export async function contractBalance(pool: Pool, a: Row): Promise<{ contracts: ContractCandidate[] }> { const id = optUuid(a.contract_id, "contract_id"); const vendor = optStr(a.vendor_name, "vendor_name"); const project = optStr(a.project_customer_id, "project_customer_id"); if (!id && !vendor) throw bad("нужен contract_id или vendor_name"); const { rows } = await pool.query( `select ${CONTRACT_COLS} from acc_contracts where ($1::uuid is null or id = $1) and ($2::text is null or project_customer_id = $2) order by vendor_name`, [id, project], ); const want = vendor ? normalizeVendorName(vendor) : null; return { contracts: rows.filter((k) => !want || normalizeVendorName(k.vendor_name).includes(want) || want.includes(normalizeVendorName(k.vendor_name))) }; } // ----------------------------------------------------------------- fraud по карте const FRAUD_NEXT: Record = { collecting: ["filed", "closed"], filed: ["refunded", "rejected", "closed"], refunded: ["closed"], rejected: ["filed", "closed"], closed: [], }; /** Процесс fraud, шаги 4-5: запись card_fraud по операции с комплектом (операция, чек или отметка «чека нет»). */ export async function createFraud(pool: Pool, actor: string, a: Row): Promise<{ created: boolean; chargeback: Row }> { try { return await createFraudOnce(pool, actor, a); } catch (e) { // параллельный запрос успел раньше: частичный уникальный индекс acc_chargeback_fraud_open_uq (миграция 071) - дело уже есть if ((e as { code?: string }).code !== "23505") throw e; const feed = reqStr(a.feed_txn_id, "feed_txn_id"); const ex = await pool.query("select id from acc_chargeback where kind = 'card_fraud' and feed_txn_id = $1 and status <> 'closed'", [feed]); if (!ex.rows[0]) throw e; return { created: false, chargeback: await load(pool, ex.rows[0].id as string) }; } } async function createFraudOnce(pool: Pool, actor: string, a: Row): Promise<{ created: boolean; chargeback: Row }> { const feed = reqStr(a.feed_txn_id, "feed_txn_id"); const reason = optStr(a.reason, "reason"); const bank = optStr(a.bank, "bank"); const fileBy = optDate(a.file_by, "file_by"); if (!UUID.test(actor) || !(await pool.query("select 1 from person where id = $1", [actor])).rows[0]) throw bad("created_by: такого person нет"); return withTx(pool, async (c) => { const ex = await c.query("select id from acc_chargeback where kind = 'card_fraud' and feed_txn_id = $1 and status <> 'closed' for update", [feed]); if (ex.rows[0]) return { created: false, chargeback: await load(c, ex.rows[0].id as string) }; const op = ( await c.query( `select 'review' as source, suggestion, confidence, problem_highlight from acc_categorization_review where feed_txn_id = $1 union all select 'history', suggestion, confidence, problem_highlight from acc_categorization_review_history where feed_txn_id = $1 limit 1`, [feed], ) ).rows[0] as Row | undefined; const receipt = ( await c.query("select id, drive_file_id, vendor_name, amount::float8 as amount, to_char(receipt_date, 'YYYY-MM-DD') as receipt_date from acc_receipts where feed_txn_id = $1 limit 1", [feed]) ).rows[0] as Row | undefined; const kit = { operation: op ?? null, receipt: receipt ? { ...receipt, url: `https://drive.google.com/file/d/${String(receipt.drive_file_id)}/view` } : null, receipt_note: receipt ? null : "чека нет", vendor_correspondence: "приложить вручную: переписка с вендором из JobTread или Gmail", collected_at: new Date().toISOString(), }; const ins = await c.query( "insert into acc_chargeback (kind, status, feed_txn_id, reason, bank, file_by, kit, created_by) values ('card_fraud', 'collecting', $1, $2, $3, $4, $5::jsonb, $6) returning id", [feed, reason, bank, fileBy, JSON.stringify(kit), actor], ); const id = ins.rows[0]!.id as string; await syncTask(c, id); return { created: true, chargeback: await load(c, id) }; }); } export async function setFraudStatus(pool: Pool, a: Row): Promise { const id = await resolveChargebackId(pool, a.id); const status = reqStr(a.status, "status"); const decision = optStr(a.bank_decision, "bank_decision"); const bank = optStr(a.bank, "bank"); const fileBy = optDate(a.file_by, "file_by"); return withTx(pool, async (c) => { const r = await load(c, id, true); if (r.kind !== "card_fraud") throw bad("Это не fraud по карте."); const allowed = FRAUD_NEXT[String(r.status)] ?? []; if (!allowed.includes(status)) throw bad(`Из статуса ${String(r.status)} можно перейти в: ${allowed.join(", ") || "(ничего, строка закрыта)"}.`); await c.query( "update acc_chargeback set status = $2, bank_decision = coalesce($3, bank_decision), bank = coalesce($4, bank), file_by = coalesce($5::date, file_by) where id = $1", [id, status, decision, bank, fileBy], ); await syncTask(c, id); return load(c, id); }); } /** Недельное напоминание о незакрытых fraud (задание fraud-weekly). Текст детерминированный. */ export async function buildFraudReminder(pool: Pool, now: Date): Promise<{ text: string; count: number } | null> { const { rows } = await pool.query( `select feed_txn_id, status, bank, to_char(file_by, 'YYYY-MM-DD') as file_by, created_at from acc_chargeback where kind = 'card_fraud' and status <> 'closed' order by file_by nulls last, created_at`, ); if (rows.length === 0) return null; const today = now.toISOString().slice(0, 10); const days = (iso: string): number => Math.round((Date.parse(`${iso}T00:00:00Z`) - Date.parse(`${today}T00:00:00Z`)) / 86_400_000); const label: Record = { collecting: "собираем комплект", filed: "подано, ждём банк", refunded: "возврат получен, нужно закрыть", rejected: "банк отказал" }; const lines = rows.map((r) => { let due = ""; if (r.status === "collecting" && r.file_by) { const d = days(r.file_by as string); due = d < 0 ? `, срок подачи ${r.file_by} ПРОСРОЧЕН на ${-d} дн.` : d <= 7 ? `, срок подачи ${r.file_by} (осталось ${d} дн.)` : `, срок подачи ${r.file_by}`; } return `- операция ${String(r.feed_txn_id)}${r.bank ? ` (${String(r.bank)})` : ""}: ${label[String(r.status)] ?? String(r.status)}${due}`; }); return { count: rows.length, text: `Fraud по картам: незакрытых случаев ${rows.length}.\n${lines.join("\n")}\nСтатус и решение банка записываются в acc_chargeback (Claude: acc_fraud_update).` }; } export interface FraudWeeklyDeps { pool: Pool; slack: { post(channelId: string, text: string): Promise }; channelId: string; now?: () => Date; } /** Задание fraud-weekly: напоминание в Slack о незакрытых fraud и сроках подачи; если незакрытых нет, ничего не шлёт. */ export async function runFraudWeekly(deps: FraudWeeklyDeps): Promise<{ sent: boolean; count: number }> { const rem = await buildFraudReminder(deps.pool, (deps.now ?? (() => new Date()))()); if (!rem) return { sent: false, count: 0 }; await deps.slack.post(deps.channelId, rem.text); return { sent: true, count: rem.count }; }