old_invoices: таблица (миграция 079), разбор Excel Анастасии и загрузка; архив инвойсов вне рабочего реестра
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
32
packages/accounting_automation/scripts/old-invoices-load.mjs
Normal file
32
packages/accounting_automation/scripts/old-invoices-load.mjs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
// Загрузка разобранных строк (результат old-invoices-parse.mjs) в old_invoices; повторный запуск обновляет те же строки.
|
||||||
|
// Запуск в контейнере: node old-invoices-load.mjs <rows.json> <file_id>; соединение с БД - как у сервиса (khb_common).
|
||||||
|
import fs from "node:fs";
|
||||||
|
import { createPool, loadServiceSettings } from "khb_common";
|
||||||
|
import { accountingSchema } from "../dist/settings.js";
|
||||||
|
|
||||||
|
const rows = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
|
||||||
|
const fileId = process.argv[3];
|
||||||
|
const { common } = loadServiceSettings("accounting_automation", accountingSchema);
|
||||||
|
const pool = createPool(common.database.url, 2);
|
||||||
|
let n = 0;
|
||||||
|
for (const r of rows) {
|
||||||
|
await pool.query(
|
||||||
|
`insert into old_invoices (source_file_id, source_sheet, source_row, invoice_date, pay_method_raw, pay_method, project_text, invoice_number_raw, purpose,
|
||||||
|
vendor_name, amount, paid_raw, paid_on, paid_status, note, contract_total, drive_file_id, section, raw)
|
||||||
|
values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19::jsonb)
|
||||||
|
on conflict (source_file_id, source_sheet, source_row) do update set invoice_date = excluded.invoice_date, pay_method_raw = excluded.pay_method_raw,
|
||||||
|
pay_method = excluded.pay_method, project_text = excluded.project_text, invoice_number_raw = excluded.invoice_number_raw, purpose = excluded.purpose,
|
||||||
|
vendor_name = excluded.vendor_name, amount = excluded.amount, paid_raw = excluded.paid_raw, paid_on = excluded.paid_on, paid_status = excluded.paid_status,
|
||||||
|
note = excluded.note, contract_total = excluded.contract_total, drive_file_id = excluded.drive_file_id, section = excluded.section, raw = excluded.raw, loaded_at = now()`,
|
||||||
|
[fileId, r.source_sheet, r.source_row, r.invoice_date, r.pay_method_raw, r.pay_method, r.project_text, r.invoice_number_raw, r.purpose,
|
||||||
|
r.vendor_name, r.amount, r.paid_raw, r.paid_on, r.paid_status, r.note, r.contract_total, r.drive_file_id, r.section, JSON.stringify(r.raw)],
|
||||||
|
);
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
// сопоставление поставщика с QuickBooks по имени без регистра и пунктуации (только однозначное совпадение)
|
||||||
|
await pool.query(`
|
||||||
|
update old_invoices o set vendor_qbo_id = v.id
|
||||||
|
from (select lower(regexp_replace(display_name, '[^a-zA-Z0-9]+', '', 'g')) k, min(id) id, count(*) c from qbo_vendor group by 1) v
|
||||||
|
where o.vendor_qbo_id is null and v.c = 1 and v.k = lower(regexp_replace(o.vendor_name, '[^a-zA-Z0-9]+', '', 'g')) and v.k <> ''`);
|
||||||
|
console.log("loaded", n);
|
||||||
|
await pool.end();
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
// Разбор Excel Анастасии «Payments_Constr List» в строки для таблицы old_invoices.
|
||||||
|
// Запуск: node old-invoices-parse.mjs <файл.xlsx> <выход.json> (на Drive: id 1gPOutfuVrdEJK3j1YoaOd3e_7gHBv4GM)
|
||||||
|
import fs from "node:fs";
|
||||||
|
import { readXlsx } from "./xlsx-read.mjs";
|
||||||
|
|
||||||
|
// три реестра с разной раскладкой столбцов: inv - номер инвойса, proj - проект (адрес)
|
||||||
|
const SHEETS = {
|
||||||
|
"KH Open Invoices": { inv: "G", proj: "F" },
|
||||||
|
"GK Open Invoices": { inv: "F", proj: "G" },
|
||||||
|
"KH BUILD": { inv: "G", proj: "F" },
|
||||||
|
};
|
||||||
|
const MON = { jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5, jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11 };
|
||||||
|
const iso = (d) => d.toISOString().slice(0, 10);
|
||||||
|
const serial = (n) => new Date(Date.UTC(1899, 11, 30) + Math.round(n) * 86400000);
|
||||||
|
const s = (v) => (v === undefined || v === null ? null : String(v).replace(/\s+/g, " ").trim() || null);
|
||||||
|
|
||||||
|
function payNorm(t) {
|
||||||
|
const x = (t ?? "").toLowerCase().trim();
|
||||||
|
if (!x) return null;
|
||||||
|
if (/zelle/.test(x)) return "zelle";
|
||||||
|
if (/bill ?pay/.test(x)) return "bill_pay";
|
||||||
|
if (/wire/.test(x)) return "wire";
|
||||||
|
if (/bofa|transfer/.test(x)) return "bank_transfer";
|
||||||
|
if (/^(ach)/.test(x)) return "ach";
|
||||||
|
if (/paypal|paypall/.test(x)) return "paypal";
|
||||||
|
if (/^(cc|сс|card|cr card|credit card)|cc /.test(x)) return "card";
|
||||||
|
if (/check/.test(x)) return "check";
|
||||||
|
if (/cash/.test(x)) return "cash";
|
||||||
|
if (/qb/.test(x)) return "qb_link";
|
||||||
|
if (/link|portal|porta|site|website/.test(x)) return "portal_link";
|
||||||
|
return "other";
|
||||||
|
}
|
||||||
|
|
||||||
|
function parsePaid(k, invDate) {
|
||||||
|
if (k === undefined || k === null || k === "") return { raw: null, on: null, status: "unknown" };
|
||||||
|
if (typeof k === "number") return { raw: iso(serial(k)), on: iso(serial(k)), status: "paid" };
|
||||||
|
const raw = s(k);
|
||||||
|
let on = null;
|
||||||
|
let m = /\b(\d{1,2})\s+([A-Za-z]{3})[a-z]*\b/.exec(raw);
|
||||||
|
if (m && MON[m[2].toLowerCase()] !== undefined) {
|
||||||
|
const base = invDate ? new Date(`${invDate}T00:00:00Z`) : null;
|
||||||
|
if (base) {
|
||||||
|
let d = new Date(Date.UTC(base.getUTCFullYear(), MON[m[2].toLowerCase()], +m[1]));
|
||||||
|
if (d.getTime() < base.getTime() - 10 * 86400000) d = new Date(Date.UTC(d.getUTCFullYear() + 1, d.getUTCMonth(), d.getUTCDate()));
|
||||||
|
on = iso(d);
|
||||||
|
}
|
||||||
|
} else if ((m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(raw))) on = iso(new Date(Date.UTC(+m[3], +m[1] - 1, +m[2])));
|
||||||
|
if (on && !/not |waiting|approval|don't/i.test(raw)) return { raw, on, status: "paid" };
|
||||||
|
if (/^(paid|check|paper check|cash|reimburs|оплачено)/i.test(raw) || /paid/i.test(raw)) return { raw, on, status: "paid" };
|
||||||
|
if (/not approved|not yet|not finished|waiting|need to|не /i.test(raw)) return { raw, on: null, status: /waiting/i.test(raw) ? "waiting" : "not_approved" };
|
||||||
|
if (/approved/i.test(raw)) return { raw, on: null, status: "approved" };
|
||||||
|
return { raw, on: null, status: "other" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const sheets = readXlsx(process.argv[2]);
|
||||||
|
const out = [];
|
||||||
|
const skipped = { no_vendor_or_amount: 0, empty: 0 };
|
||||||
|
const skippedSamples = [];
|
||||||
|
for (const [name, cfg] of Object.entries(SHEETS)) {
|
||||||
|
const sh = sheets.find((x) => x.name === name);
|
||||||
|
for (const r of sh.rows) {
|
||||||
|
const c = r.cells;
|
||||||
|
if (!Object.keys(c).length) { skipped.empty++; continue; }
|
||||||
|
const header = typeof c.B === "string" && c.B === "#";
|
||||||
|
if (header) continue;
|
||||||
|
if (!(typeof c.J === "number" && c.I)) {
|
||||||
|
if (typeof c.J === "number" || c.I) { skipped.no_vendor_or_amount++; if (skippedSamples.length < 12) skippedSamples.push({ sheet: name, row: r.n, cells: c }); }
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const invDate = typeof c.C === "number" ? iso(serial(c.C)) : null;
|
||||||
|
const paid = parsePaid(c.K, invDate);
|
||||||
|
const note = s(c.L);
|
||||||
|
const total = note ? /total(?:\s*price)?\s*:?\s*\$?\s*\$?\s*([\d][\d,]*(?:\.\d+)?)/i.exec(note) : null;
|
||||||
|
const drive = note ? /drive\.google\.com\/(?:file\/d\/|open\?id=|drive\/folders\/)([\w-]+)/.exec(note) : null;
|
||||||
|
out.push({
|
||||||
|
source_sheet: name, source_row: r.n, invoice_date: invDate, pay_method_raw: s(c.E), pay_method: payNorm(c.E),
|
||||||
|
project_text: s(c[cfg.proj]), invoice_number_raw: s(c[cfg.inv]), purpose: s(c.H), vendor_name: s(c.I), amount: Math.round(c.J * 100) / 100,
|
||||||
|
paid_raw: paid.raw, paid_on: paid.on, paid_status: paid.status, note, contract_total: total ? +total[1].replace(/,/g, "") : null,
|
||||||
|
drive_file_id: drive ? drive[1] : null, section: s(c.A), raw: c,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs.writeFileSync(process.argv[3], JSON.stringify(out));
|
||||||
|
const cnt = (a) => Object.entries(a.reduce((m, x) => ((m[x] = (m[x] || 0) + 1), m), {})).sort((a, b) => b[1] - a[1]);
|
||||||
|
console.log("rows", out.length, "skipped", skipped);
|
||||||
|
console.log("by sheet", cnt(out.map((x) => x.source_sheet)));
|
||||||
|
console.log("pay_method", cnt(out.map((x) => x.pay_method)));
|
||||||
|
console.log("paid_status", cnt(out.map((x) => x.paid_status)));
|
||||||
|
console.log("no date", out.filter((x) => !x.invoice_date).length, "no inv#", out.filter((x) => !x.invoice_number_raw).length, "no project", out.filter((x) => !x.project_text).length);
|
||||||
|
console.log("contract_total", out.filter((x) => x.contract_total).length, "drive link", out.filter((x) => x.drive_file_id).length, "neg", out.filter((x) => x.amount < 0).length);
|
||||||
|
console.log("paid_on null while status paid", out.filter((x) => x.paid_status === "paid" && !x.paid_on).length);
|
||||||
|
console.log("skipped samples", JSON.stringify(skippedSamples));
|
||||||
52
packages/accounting_automation/scripts/xlsx-read.mjs
Normal file
52
packages/accounting_automation/scripts/xlsx-read.mjs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import fs from "fs";
|
||||||
|
import zlib from "zlib";
|
||||||
|
export function unzip(buf) {
|
||||||
|
let e = buf.length - 22;
|
||||||
|
while (e >= 0 && buf.readUInt32LE(e) !== 0x06054b50) e--;
|
||||||
|
const n = buf.readUInt16LE(e + 10), cdOff = buf.readUInt32LE(e + 16);
|
||||||
|
const files = {};
|
||||||
|
let p = cdOff;
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const method = buf.readUInt16LE(p + 10), csize = buf.readUInt32LE(p + 20), nlen = buf.readUInt16LE(p + 28), xlen = buf.readUInt16LE(p + 30), clen = buf.readUInt16LE(p + 32), lh = buf.readUInt32LE(p + 42);
|
||||||
|
const name = buf.toString("utf8", p + 46, p + 46 + nlen);
|
||||||
|
const ln = buf.readUInt16LE(lh + 26), lx = buf.readUInt16LE(lh + 28);
|
||||||
|
const data = buf.subarray(lh + 30 + ln + lx, lh + 30 + ln + lx + csize);
|
||||||
|
files[name] = method === 0 ? data : zlib.inflateRawSync(data);
|
||||||
|
p += 46 + nlen + xlen + clen;
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
const dec = (s) => s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&#(\d+);/g, (_, c) => String.fromCharCode(+c)).replace(/&/g, "&");
|
||||||
|
export function readXlsx(path) {
|
||||||
|
const f = unzip(fs.readFileSync(path));
|
||||||
|
const wb = f["xl/workbook.xml"].toString("utf8");
|
||||||
|
const rels = f["xl/_rels/workbook.xml.rels"].toString("utf8");
|
||||||
|
const ss = [];
|
||||||
|
if (f["xl/sharedStrings.xml"]) {
|
||||||
|
for (const m of f["xl/sharedStrings.xml"].toString("utf8").matchAll(/<si>([\s\S]*?)<\/si>/g)) {
|
||||||
|
ss.push(dec([...m[1].matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)].map((x) => x[1]).join("")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const sheets = [];
|
||||||
|
for (const m of wb.matchAll(/<sheet [^>]*name="([^"]*)"[^>]*r:id="([^"]*)"/g)) {
|
||||||
|
const rid = m[2];
|
||||||
|
const rel = new RegExp(`<Relationship [^>]*Id="${rid}"[^>]*>`).exec(rels)[0];
|
||||||
|
const target = /Target="([^"]*)"/.exec(rel)[1].replace(/^\/?(xl\/)?/, "xl/");
|
||||||
|
const xml = f[target].toString("utf8");
|
||||||
|
const rows = [];
|
||||||
|
for (const r of xml.matchAll(/<row [^>]*?r="(\d+)"[^>]*?(?:\/>|>([\s\S]*?)<\/row>)/g)) {
|
||||||
|
const cells = {};
|
||||||
|
for (const c of (r[2] ?? "").matchAll(/<c ([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
|
||||||
|
const ref = /r="([A-Z]+)\d+"/.exec(c[1])[1];
|
||||||
|
const t = /t="(\w+)"/.exec(c[1])?.[1];
|
||||||
|
const v = /<v>([\s\S]*?)<\/v>/.exec(c[2] ?? "")?.[1];
|
||||||
|
const is = /<is>[\s\S]*?<t[^>]*>([\s\S]*?)<\/t>/.exec(c[2] ?? "")?.[1];
|
||||||
|
let val = v === undefined ? (is === undefined ? null : dec(is)) : t === "s" ? ss[+v] : t === "str" || t === "inlineStr" ? dec(v) : t === "b" ? v === "1" : +v;
|
||||||
|
if (val !== null) cells[ref] = val;
|
||||||
|
}
|
||||||
|
rows.push({ n: +r[1], cells });
|
||||||
|
}
|
||||||
|
sheets.push({ name: dec(m[1]), rows });
|
||||||
|
}
|
||||||
|
return sheets;
|
||||||
|
}
|
||||||
31
packages/khb_common/migrations/079_old_invoices.sql
Normal file
31
packages/khb_common/migrations/079_old_invoices.sql
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
-- Архив инвойсов из Excel Анастасии («Payments_Constr List», Drive id 1gPOutfuVrdEJK3j1YoaOd3e_7gHBv4GM): только история, в рабочий реестр acc_invoices не входит.
|
||||||
|
-- Загрузка повторяемая (уникальность: файл + лист + строка), скрипт packages/accounting_automation/scripts/old-invoices-load.mjs.
|
||||||
|
create table if not exists old_invoices (
|
||||||
|
id bigserial primary key,
|
||||||
|
source_file_id text not null,
|
||||||
|
source_sheet text not null, -- KH Open Invoices / GK Open Invoices / KH BUILD (три реестра = три компании/периода)
|
||||||
|
source_row int not null,
|
||||||
|
invoice_date date,
|
||||||
|
pay_method_raw text, -- как в Excel: portal, ACH, zelle, BofA transfer, QB link ...
|
||||||
|
pay_method text, -- нормализованный: ach, zelle, wire, bill_pay, bank_transfer, portal_link, qb_link, check, card, cash, paypal, other
|
||||||
|
project_text text, -- адрес как в Excel (в acc_invoices - project_customer_id)
|
||||||
|
project_customer_id text, -- заполняется сопоставлением с QuickBooks, если адрес совпал однозначно
|
||||||
|
invoice_number_raw text, -- номер вместе с мусором: «Inv 9846», «INVOICE # 5013», «Contract», «DrReq 4»
|
||||||
|
purpose text,
|
||||||
|
vendor_name text,
|
||||||
|
vendor_qbo_id text, -- заполняется сопоставлением с qbo_vendor по имени
|
||||||
|
amount numeric(14,2) not null, -- сумма платежа по строке (частичные оплаты - отдельными строками)
|
||||||
|
paid_raw text, -- столбец «дата оплаты / статус» как в Excel
|
||||||
|
paid_on date,
|
||||||
|
paid_status text, -- paid / approved / not_approved / waiting / other / unknown
|
||||||
|
note text, -- последний столбец: «total $…», ссылки, комментарии
|
||||||
|
contract_total numeric(14,2), -- «total $X» из примечания: полная сумма договора/инвойса, если платёж частичный
|
||||||
|
drive_file_id text, -- если в примечании была ссылка на Drive
|
||||||
|
section text,
|
||||||
|
raw jsonb not null, -- все ячейки строки по буквам столбцов
|
||||||
|
loaded_at timestamptz not null default now(),
|
||||||
|
unique (source_file_id, source_sheet, source_row)
|
||||||
|
);
|
||||||
|
create index if not exists old_invoices_vendor_idx on old_invoices (vendor_qbo_id, amount);
|
||||||
|
create index if not exists old_invoices_date_idx on old_invoices (invoice_date);
|
||||||
|
alter table old_invoices enable row level security;
|
||||||
Reference in New Issue
Block a user