old_invoices: сопоставление проектов и вендоров, md-отчёт; pay_method (080); spam-rescue: сравнение без регистра и диакритики, исправлен json в белом списке
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
// Сопоставление old_invoices с QuickBooks: проекты (адрес -> qbo_customer) и вендоры (имя -> qbo_vendor).
|
||||
// Запуск в контейнере: node old-invoices-match.mjs [--write]; без --write только отчёт. Результат (JSON) - в stdout.
|
||||
import { createPool, loadServiceSettings } from "khb_common";
|
||||
import { accountingSchema } from "./dist/settings.js";
|
||||
|
||||
const write = process.argv.includes("--write");
|
||||
const { common } = loadServiceSettings("accounting_automation", accountingSchema);
|
||||
const pool = createPool(common.database.url, 2);
|
||||
|
||||
const SUFFIX = /\b(llc|l l c|inc|incorporated|corp|corporation|co|company|ltd|lp|pllc|pa|pc)\b/g;
|
||||
const NOISE = /\b(final payment|final|draw ?\d*|deposit|depo|house layout|payment|balance|retainage)\b/g;
|
||||
const base = (s) => (s ?? "").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9а-я ]+/g, " ");
|
||||
const vkey = (s) => base(s).replace(NOISE, " ").replace(SUFFIX, " ").replace(/\s+/g, "");
|
||||
// ключ адреса: «номер + первое слово улицы»: «734 Placido Way, St Pet» -> «734 placido»; ведущие X (порча QuickBooks) срезаются
|
||||
const akey = (s) => {
|
||||
const t = base(s).replace(/^\s*x+(?=\d)/, "").replace(/\blot\s*\d+\b/g, " ").trim();
|
||||
const m = /^(\d{2,6})\s+(?:(?:n|s|e|w|ne|nw|se|sw)\s+)?([a-z0-9]+)/.exec(t);
|
||||
return m ? `${m[1]} ${m[2]}` : null;
|
||||
};
|
||||
|
||||
const customers = (await pool.query("select id, display_name from qbo_customer where active")).rows;
|
||||
const jobs = (await pool.query("select id, name from jt_job")).rows;
|
||||
const vendors = (await pool.query("select id, display_name, company_name from qbo_vendor")).rows;
|
||||
|
||||
const cmap = new Map();
|
||||
for (const c of customers) {
|
||||
const k = akey(c.display_name);
|
||||
if (k) cmap.set(k, [...(cmap.get(k) ?? []), c]);
|
||||
}
|
||||
const vmap = new Map();
|
||||
for (const v of vendors) for (const n of [v.display_name, v.company_name]) { const k = vkey(n); if (k.length >= 3) vmap.set(k, [...(vmap.get(k) ?? []), v]); }
|
||||
|
||||
const rows = (await pool.query("select id, source_sheet, project_text, vendor_name, amount from old_invoices")).rows;
|
||||
const projRes = new Map();
|
||||
const vendRes = new Map();
|
||||
const stat = { rows: rows.length, proj_matched: 0, proj_no_key: 0, proj_ambiguous: 0, vend_matched: 0, vend_ambiguous: 0 };
|
||||
const unmatchedProj = new Map();
|
||||
const unmatchedVend = new Map();
|
||||
for (const r of rows) {
|
||||
if (r.project_text) {
|
||||
const k = akey(r.project_text);
|
||||
const cs = k ? cmap.get(k) : null;
|
||||
const ids = cs ? [...new Set(cs.map((c) => c.display_name))] : [];
|
||||
if (!k) stat.proj_no_key++;
|
||||
if (ids.length === 1) { projRes.set(r.id, cs[0].id); stat.proj_matched++; projRes.set(`n${r.project_text}`, cs[0].display_name); }
|
||||
else if (ids.length > 1) stat.proj_ambiguous++;
|
||||
else unmatchedProj.set(r.project_text, (unmatchedProj.get(r.project_text) ?? 0) + Number(r.amount));
|
||||
}
|
||||
if (r.vendor_name) {
|
||||
const vs = vmap.get(vkey(r.vendor_name));
|
||||
const ids = vs ? [...new Set(vs.map((v) => v.id))] : [];
|
||||
if (ids.length === 1) { vendRes.set(r.id, ids[0]); stat.vend_matched++; }
|
||||
else if (ids.length > 1) stat.vend_ambiguous++;
|
||||
else unmatchedVend.set(r.vendor_name, (unmatchedVend.get(r.vendor_name) ?? 0) + Number(r.amount));
|
||||
}
|
||||
}
|
||||
if (write) {
|
||||
for (const [id, cid] of projRes) if (typeof id === "number" || /^\d+$/.test(String(id))) await pool.query("update old_invoices set project_customer_id = $2 where id = $1", [id, cid]);
|
||||
for (const [id, vid] of vendRes) await pool.query("update old_invoices set vendor_qbo_id = $2 where id = $1", [id, vid]);
|
||||
}
|
||||
const top = (m, n) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, n).map(([k, v]) => [k, Math.round(v)]);
|
||||
const byName = {};
|
||||
for (const [k, v] of projRes) if (String(k).startsWith("n")) byName[String(k).slice(1)] = v;
|
||||
console.log(JSON.stringify({ stat, customers: customers.length, jobs: jobs.length, matchedProjects: byName, unmatchedProj: top(unmatchedProj, 60), unmatchedVend: top(unmatchedVend, 60), distinctUnmatchedProj: unmatchedProj.size, distinctUnmatchedVend: unmatchedVend.size }));
|
||||
await pool.end();
|
||||
@@ -37,8 +37,11 @@ export function senderEmail(from: string): string {
|
||||
}
|
||||
|
||||
/** Слово для сравнения: имя без формы собственности, не короче 4 символов. */
|
||||
/** Приведение к сравнимому виду: без регистра и диакритики, «&» = «and» («Floor & Decor» = «Floor and Décor»). */
|
||||
export const fold = (s: string): string => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/&/g, " and ");
|
||||
|
||||
export function normalizeTerm(name: string): string | null {
|
||||
const t = name.toLowerCase().replace(COMPANY_SUFFIX, " ").replace(/[^a-z0-9а-яё&.\- ]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
const t = fold(name).replace(COMPANY_SUFFIX, " ").replace(/[^a-z0-9а-яё&.\- ]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
return t.length >= 4 ? t : null;
|
||||
}
|
||||
|
||||
@@ -55,7 +58,7 @@ export function decide(mail: SpamMail, rules: RescueRules): RescueDecision {
|
||||
const sender = senderEmail(mail.from);
|
||||
if (rules.whitelist.has(sender)) return { rescue: true, reason: `белый список: ${sender}` };
|
||||
if (!/\binvoices?@khbuild\.pro\b/i.test(mail.recipients)) return { rescue: false, reason: "не на invoice@" };
|
||||
const hay = `${mail.from} ${mail.subject} ${mail.snippet}`.toLowerCase();
|
||||
const hay = fold(`${mail.from} ${mail.subject} ${mail.snippet}`).replace(/\s+/g, " ");
|
||||
for (const n of rules.projectNumbers) if (new RegExp(`(^|[^0-9])${n}([^0-9]|$)`).test(hay)) return { rescue: true, reason: `проект ${n}` };
|
||||
for (const t of rules.terms) if (hay.includes(t)) return { rescue: true, reason: `слово «${t}»` };
|
||||
return { rescue: false, reason: "нет слов из списка" };
|
||||
@@ -163,7 +166,7 @@ class Mailbox {
|
||||
async function learnWhitelist(o: RescueOptions, src: Mailbox, res: RescueResult): Promise<void> {
|
||||
const { rows } = await o.pool.query<{ source_message_id: string; decided_by: string | null }>(
|
||||
`select distinct on (source_message_id) source_message_id, decided_by from acc_invoices
|
||||
where source_message_id is not null and coalesce(conclusion,'') !~* '(reject|отклон)' order by source_message_id, created_at`,
|
||||
where source_message_id is not null and coalesce(conclusion::text,'') !~* '(reject|отклон)' order by source_message_id, created_at`,
|
||||
);
|
||||
for (const r of rows) {
|
||||
let from: string;
|
||||
|
||||
5
packages/khb_common/migrations/080_pay_method.sql
Normal file
5
packages/khb_common/migrations/080_pay_method.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- Способ оплаты инвойса (в Excel Анастасии отдельный столбец): ach, zelle, wire, bill_pay, bank_transfer, portal_link, qb_link, check, card, cash, paypal, other
|
||||
alter table acc_invoices_review add column if not exists pay_method text;
|
||||
alter table acc_invoices_review_original add column if not exists pay_method text;
|
||||
alter table acc_invoices_review_history add column if not exists pay_method text;
|
||||
alter table acc_invoices add column if not exists pay_method text;
|
||||
Reference in New Issue
Block a user