66 lines
4.0 KiB
JavaScript
66 lines
4.0 KiB
JavaScript
// Сопоставление 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();
|