import type { Logger, Pool } from "khb_common"; import { autoUpdateCertificateReview } from "./certificates-ingest.js"; import { normalizeVendorName } from "./vendor-name.js"; /** * Процесс «Страховые сертификаты подрядчиков», шаги 3, 4 и 6 (задание `certificates`, раз в день): * - сроки действующих вендоров: за 30 и за 5 дней до окончания, при просрочке и при отсутствии сертификата - строка acc_certificates_review * (триггер БД сам создаёт задачу для accountant в acc_manual_review); * - письмо-запрос подрядчику (после подтверждения Юли или сразу, если включена автоотправка), повтор через 5 дней; * - отметка «нет страховки» в acc_invoices. * Письма с сертификатами разбирает задание invoices-mail (certificates-ingest.ts). */ export type AlertKind = "expiring_30" | "expiring_5" | "expired" | "missing"; const RANK: Record = { new_certificate: 0, expiring_30: 1, expiring_5: 2, expired: 3, missing: 3 }; /** Отправка сообщения подрядчику (в боевом режиме - сообщение в JobTread). */ export interface ContractorMessenger { send(m: { vendorName: string; vendorQboId: string | null; subject: string; body: string }): Promise<{ delivered: boolean; channel: string; ref?: string }>; } /** * Пока в проекте нет клиента записи сообщений в JobTread (data_collector только читает), письмо готовится и сохраняется * в журнале запросов строки разбора; Юля отправляет его вручную из JobTread. */ export const manualMessenger: ContractorMessenger = { async send() { return { delivered: false, channel: "manual" }; }, }; export const DEFAULT_TEMPLATE = [ "Hello {{vendor}},", "", "Our records show that your certificate of insurance {{status}}.", "Please send us an updated certificate of insurance (general liability and workers' compensation) as soon as possible,", "so that we can keep processing your invoices without delay.", "", "Thank you,", "KH Build", ].join("\n"); export const CERTIFICATE_SUBJECT = "Certificate of insurance request"; export interface CertificatesDeps { pool: Pool; messenger?: ContractorMessenger; now?: () => Date; log?: Logger; /** Текст шаблона запроса (Google Docs «Шаблон запроса сертификата»); null/ошибка - встроенный текст. */ loadTemplate?: () => Promise; /** Отправлять без подтверждения Юли (решение Анастасии; по умолчанию нет). */ autoSend?: boolean; /** Через сколько дней повторять запрос (по умолчанию 5) и сколько запросов максимум (по умолчанию 2: первый и один повтор). */ repeatDays?: number; maxRequests?: number; } export interface CertificatesResult { vendorsChecked: number; reviewsCreated: number; reviewsEscalated: number; requestsSent: number; requestsPrepared: number; requestErrors: number; flaggedNoInsurance: number; } const DAY = 86_400_000; const dayStr = (d: Date): string => d.toISOString().slice(0, 10); const daysBetween = (fromIso: string, toIso: string): number => Math.round((Date.parse(`${toIso}T00:00:00Z`) - Date.parse(`${fromIso}T00:00:00Z`)) / DAY); interface Vendor { key: string; name: string; qboId: string | null; } /** Действующие вендоры: контракты с остатком и инвойсы в работе (не оплаченные и не отклонённые). */ async function activeVendors(pool: Pool): Promise { const { rows } = await pool.query<{ vendor_name: string; vendor_qbo_id: string | null }>( `select vendor_name, vendor_qbo_id from acc_contracts where total_amount - retained_amount - paid_amount > 0 union all select vendor_name, vendor_qbo_id from acc_invoices where stage in ('checking', 'to_approve', 'approved', 'wait') and paid_on is null`, ); const m = new Map(); for (const r of rows) { const key = normalizeVendorName(r.vendor_name); if (!key) continue; const ex = m.get(key); if (!ex) m.set(key, { key, name: r.vendor_name, qboId: r.vendor_qbo_id }); else if (!ex.qboId && r.vendor_qbo_id) ex.qboId = r.vendor_qbo_id; } return [...m.values()]; } interface Latest { id: string; validUntil: string; } /** Самый поздний срок по вендору: ищем и по QuickBooks id, и по нормализованному имени. */ async function latestCertificates(pool: Pool): Promise<(v: { key: string; qboId: string | null }) => Latest | null> { const { rows } = await pool.query<{ id: string; vendor_name: string; vendor_qbo_id: string | null; valid_until: string }>( "select id, vendor_name, vendor_qbo_id, to_char(valid_until, 'YYYY-MM-DD') as valid_until from acc_insurance_certificates", ); const byKey = new Map(); const byQbo = new Map(); const put = (m: Map, k: string, l: Latest): void => { const ex = m.get(k); if (!ex || ex.validUntil < l.validUntil) m.set(k, l); }; for (const r of rows) { const l = { id: r.id, validUntil: r.valid_until }; put(byKey, normalizeVendorName(r.vendor_name), l); if (r.vendor_qbo_id) put(byQbo, r.vendor_qbo_id, l); } return (v) => { const a = byKey.get(v.key); const b = v.qboId ? byQbo.get(v.qboId) : undefined; if (a && b) return a.validUntil >= b.validUntil ? a : b; return a ?? b ?? null; }; } export function alertFor(latest: Latest | null, today: string): { kind: AlertKind; days: number | null } | null { if (!latest) return { kind: "missing", days: null }; const d = daysBetween(today, latest.validUntil); if (d < 0) return { kind: "expired", days: d }; if (d <= 5) return { kind: "expiring_5", days: d }; if (d <= 30) return { kind: "expiring_30", days: d }; return null; } export function alertText(vendor: string, latest: Latest | null, a: { kind: AlertKind; days: number | null }): string { if (a.kind === "missing") return `У вендора ${vendor} нет страхового сертификата`; if (a.kind === "expired") return `У вендора ${vendor} сертификат просрочен: действовал до ${latest!.validUntil} (${-a.days!} дн. назад)`; return `У вендора ${vendor} сертификат истекает ${latest!.validUntil} (через ${a.days} дн.)`; } async function ensureReviews(deps: CertificatesDeps, today: string, now: Date, res: CertificatesResult): Promise { const { pool } = deps; const vendors = await activeVendors(pool); const latestOf = await latestCertificates(pool); const open = (await pool.query<{ id: string; vendor_name: string; vendor_qbo_id: string | null; alert_kind: string | null }>( "select id, vendor_name, vendor_qbo_id, alert_kind from acc_certificates_review where not done", )).rows; const hist = (await pool.query<{ vendor_name: string; alert_kind: string | null; expires_on: string | null; closed_at: Date }>( "select vendor_name, alert_kind, to_char(expires_on, 'YYYY-MM-DD') as expires_on, closed_at from acc_certificates_review_history", )).rows; res.vendorsChecked = vendors.length; for (const v of vendors) { const latest = latestOf(v); const a = alertFor(latest, today); if (!a) continue; const text = alertText(v.name, latest, a); const mine = open.filter((r) => (v.qboId && r.vendor_qbo_id === v.qboId) || normalizeVendorName(r.vendor_name) === v.key); if (mine.length > 0) { // строка уже ждёт человека: усиливаем срочность, не затирая ничего другого for (const r of mine) { if ((RANK[r.alert_kind ?? ""] ?? 0) < RANK[a.kind]! && r.alert_kind !== "new_certificate") { await autoUpdateCertificateReview(pool, r.id, { alert_kind: a.kind, problem_highlight: text, expires_on: latest?.validUntil ?? null }); res.reviewsEscalated++; } } continue; } // закрытую строку с тем же поводом не создаём заново: для истёкших и «нет сертификата» - 14 дней паузы const sameBefore = hist.filter((h) => normalizeVendorName(h.vendor_name) === v.key && h.alert_kind === a.kind && (h.expires_on ?? null) === (latest?.validUntil ?? null)); const recent = sameBefore.some((h) => now.getTime() - new Date(h.closed_at).getTime() < 14 * DAY); if (a.kind === "expired" || a.kind === "missing" ? recent : sameBefore.length > 0) continue; await pool.query( `insert into acc_certificates_review (vendor_name, vendor_qbo_id, certificate_id, expires_on, problem_highlight, alert_kind) values ($1,$2,$3,$4,$5,$6)`, [v.name, v.qboId, latest?.id ?? null, latest?.validUntil ?? null, text, a.kind], ); res.reviewsCreated++; } } function compose(template: string, vendor: string, latest: Latest | null, today: string): string { const status = !latest ? "is missing from our records" : latest.validUntil < today ? `expired on ${latest.validUntil}` : `expires on ${latest.validUntil}`; return template.replace(/\{\{\s*vendor\s*\}\}/g, vendor).replace(/\{\{\s*valid_until\s*\}\}/g, latest?.validUntil ?? "n/a").replace(/\{\{\s*status\s*\}\}/g, status); } type LogEntry = { at: string; delivered: boolean; channel: string; subject: string; text: string; ref?: string }; async function sendRequests(deps: CertificatesDeps, today: string, now: Date, res: CertificatesResult): Promise { const { pool } = deps; const messenger = deps.messenger ?? manualMessenger; const repeatMs = (deps.repeatDays ?? 5) * DAY; const maxRequests = deps.maxRequests ?? 2; let template: string | null = null; try { template = (await deps.loadTemplate?.()) ?? null; } catch (e) { deps.log?.warn({ err: String(e) }, "шаблон запроса сертификата недоступен, используется встроенный"); } const tpl = template && template.trim() ? template : DEFAULT_TEMPLATE; const latestOf = await latestCertificates(pool); const { rows } = await pool.query<{ id: string; vendor_name: string; vendor_qbo_id: string | null; alert_kind: string | null; request_count: number; request_sent_at: Date | null; request_approved_at: Date | null; request_log: LogEntry[] | null; problem_highlight: string | null; }>( `select id, vendor_name, vendor_qbo_id, alert_kind, request_count, request_sent_at, request_approved_at, request_log, problem_highlight from acc_certificates_review where not done and alert_kind in ('expiring_30', 'expiring_5', 'expired', 'missing') order by created_at`, ); for (const r of rows) { if (!r.request_approved_at && !deps.autoSend) continue; const first = r.request_count === 0; if (!first && (r.request_count >= maxRequests || !r.request_sent_at || now.getTime() - new Date(r.request_sent_at).getTime() < repeatMs)) continue; const latest = latestOf({ key: normalizeVendorName(r.vendor_name), qboId: r.vendor_qbo_id }); if (latest && latest.validUntil >= today && daysBetween(today, latest.validUntil) > 30) continue; // сертификат уже обновили const body = compose(tpl, r.vendor_name, latest, today); try { const out = await messenger.send({ vendorName: r.vendor_name, vendorQboId: r.vendor_qbo_id, subject: CERTIFICATE_SUBJECT, body }); const entry: LogEntry = { at: now.toISOString(), delivered: out.delivered, channel: out.channel, subject: CERTIFICATE_SUBJECT, text: body, ...(out.ref ? { ref: out.ref } : {}) }; const log = [...(r.request_log ?? []), entry]; await pool.query( "update acc_certificates_review set request_sent_at = $2, request_count = request_count + 1, request_log = $3::jsonb where id = $1", [r.id, now, JSON.stringify(log)], ); if (out.delivered) res.requestsSent++; else { res.requestsPrepared++; const note = `Запрос подрядчику подготовлен, отправь вручную из JobTread (текст в request_log строки; запрос № ${r.request_count + 1})`; await pool.query("update acc_certificates_review set problem_highlight = $2 where id = $1", [r.id, r.problem_highlight ? `${r.problem_highlight} | ${note}` : note]); } } catch (e) { res.requestErrors++; deps.log?.error({ err: String(e), id: r.id }, "не удалось отправить запрос сертификата"); } } } /** Шаг 6: отметка «нет страховки» у не оплаченных инвойсов вендоров без действующего сертификата. */ export async function refreshInsuranceFlags(pool: Pool, today: string): Promise { const { rows: certs } = await pool.query<{ vendor_name: string; vendor_qbo_id: string | null }>( "select vendor_name, vendor_qbo_id from acc_insurance_certificates where valid_until >= $1::date", [today], ); const okKeys = new Set(certs.map((c) => normalizeVendorName(c.vendor_name))); const okQbo = new Set(certs.map((c) => c.vendor_qbo_id).filter((x): x is string => !!x)); const { rows: inv } = await pool.query<{ id: string; vendor_name: string; vendor_qbo_id: string | null; no_insurance: boolean }>( "select id, vendor_name, vendor_qbo_id, no_insurance from acc_invoices where stage <> 'paid' and paid_on is null", ); const flip: { id: string; v: boolean }[] = []; for (const i of inv) { const has = (i.vendor_qbo_id && okQbo.has(i.vendor_qbo_id)) || okKeys.has(normalizeVendorName(i.vendor_name)); if (i.no_insurance === !!has) flip.push({ id: i.id, v: !has }); } if (flip.length) { await pool.query("update acc_invoices a set no_insurance = f.v from (select unnest($1::uuid[]) as id, unnest($2::boolean[]) as v) f where a.id = f.id", [ flip.map((f) => f.id), flip.map((f) => f.v), ]); } return flip.filter((f) => f.v).length; } export async function runCertificates(deps: CertificatesDeps): Promise { const now = (deps.now ?? (() => new Date()))(); const today = dayStr(now); const res: CertificatesResult = { vendorsChecked: 0, reviewsCreated: 0, reviewsEscalated: 0, requestsSent: 0, requestsPrepared: 0, requestErrors: 0, flaggedNoInsurance: 0 }; await ensureReviews(deps, today, now, res); await sendRequests(deps, today, now, res); res.flaggedNoInsurance = await refreshInsuranceFlags(deps.pool, today); return res; }