Compare commits
2 Commits
31e69589d8
...
db333d6750
| Author | SHA1 | Date | |
|---|---|---|---|
| db333d6750 | |||
| dd60da4091 |
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;
|
||||
}
|
||||
@@ -106,6 +106,20 @@ export class DriveClient implements DriveStore {
|
||||
return (await res.json()) as { name: string; mimeType: string };
|
||||
}
|
||||
|
||||
/** Переносит файл в другую папку (и при необходимости переименовывает). */
|
||||
async move(fileId: string, folderId: string, newName?: string): Promise<void> {
|
||||
const id = encodeURIComponent(fileId);
|
||||
const cur = (await (await this.call(`${API}/files/${id}?fields=parents&supportsAllDrives=true`)).json()) as { parents?: string[] };
|
||||
const params = new URLSearchParams({ addParents: folderId, supportsAllDrives: "true", fields: "id" });
|
||||
const remove = (cur.parents ?? []).filter((p) => p !== folderId);
|
||||
if (remove.length) params.set("removeParents", remove.join(","));
|
||||
await this.call(`${API}/files/${id}?${params}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(newName ? { name: newName } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async download(fileId: string): Promise<Buffer> {
|
||||
const res = await this.call(`${API}/files/${encodeURIComponent(fileId)}?alt=media&supportsAllDrives=true`);
|
||||
return Buffer.from(await res.arrayBuffer());
|
||||
|
||||
17
packages/accounting_automation/src/invoice-filing.test.ts
Normal file
17
packages/accounting_automation/src/invoice-filing.test.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { invoiceFileName, invoiceFolderPath, methodFolder, monthLabel } from "./invoice-filing.js";
|
||||
|
||||
describe("раскладка инвойсов на Drive (как «07. Invoices»)", () => {
|
||||
it("месяц и имя файла", () => {
|
||||
expect(monthLabel(new Date("2026-11-30T00:00:00Z"))).toBe("November 2026");
|
||||
expect(invoiceFileName(1500, "ACME Plumbing LLC", "inv.PDF")).toBe("$1,500.00 ACME Plumbing LLC.pdf");
|
||||
expect(invoiceFileName(null, "A/B", "x.pdf")).toBe("A B.pdf");
|
||||
});
|
||||
it("до оплаты - «Без оплаты», после - по счёту оплаты без номера", () => {
|
||||
const d = new Date("2026-03-05T00:00:00Z");
|
||||
expect(invoiceFolderPath(null, d)).toEqual(["Инвойсы", "Без оплаты", "March 2026"]);
|
||||
expect(invoiceFolderPath("Capital One 2381", d)).toEqual(["Инвойсы", "Capital One", "March 2026"]);
|
||||
expect(methodFolder("Bank of America (4455)")).toBe("Bank of America");
|
||||
expect(methodFolder("Amex")).toBe("Amex");
|
||||
});
|
||||
});
|
||||
76
packages/accounting_automation/src/invoice-filing.ts
Normal file
76
packages/accounting_automation/src/invoice-filing.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { extname } from "node:path";
|
||||
import type { Logger, Pool } from "khb_common";
|
||||
|
||||
/**
|
||||
* Раскладка файлов инвойсов на Drive повторяет «7. FINANCE / 07. Invoices» Анастасии (решение Юрия 2026-11-30), но внутри нашей папки:
|
||||
* Инвойсы / <способ оплаты: Amex, Bank of America, Capital One...> / <Месяц ГГГГ> / «$<сумма> <Вендор>.pdf».
|
||||
* Пока инвойс не оплачен, способ оплаты неизвестен: папка «Без оплаты». Когда оплата найдена в QuickBooks (acc_invoices.qbo_txn_id),
|
||||
* файл переносится в папку счёта, которым заплачено (название счёта из qbo_purchase без хвоста с номером).
|
||||
*/
|
||||
export const UNPAID_FOLDER = "Без оплаты";
|
||||
const LOCK_KEY = 7_340_004;
|
||||
const BATCH = 30;
|
||||
|
||||
export const safeName = (s: string): string => s.replace(/[\\/:*?"<>|\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 100) || "_";
|
||||
|
||||
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||
export const monthLabel = (d: Date): string => `${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
|
||||
|
||||
/** Название способа оплаты для папки: имя счёта QuickBooks без номера в конце («Capital One 2381» -> «Capital One»). */
|
||||
export const methodFolder = (accountName: string | null): string => {
|
||||
const n = (accountName ?? "").replace(/[\s(#-]*\d{3,}\)?\s*$/, "").trim();
|
||||
return n ? safeName(n) : UNPAID_FOLDER;
|
||||
};
|
||||
|
||||
export const invoiceFolderPath = (accountName: string | null, date: Date): string[] => ["Инвойсы", accountName ? methodFolder(accountName) : UNPAID_FOLDER, monthLabel(date)];
|
||||
|
||||
/** «$1,500.00 ACME Plumbing LLC.pdf»: как называет файлы Анастасия («$<сумма> <Вендор>.pdf»). */
|
||||
export const invoiceFileName = (amount: number | string | null | undefined, vendor: string | null | undefined, original: string): string => {
|
||||
const ext = extname(original).toLowerCase() || ".pdf";
|
||||
const a = amount == null || amount === "" ? "" : `$${Number(amount).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} `;
|
||||
return safeName(`${a}${vendor ?? "Без вендора"}`) + ext;
|
||||
};
|
||||
|
||||
export interface FilingDrive {
|
||||
ensureFolder(pathParts: string[]): Promise<string>;
|
||||
meta(fileId: string): Promise<{ name: string; mimeType: string }>;
|
||||
move(fileId: string, folderId: string, newName?: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** Переносит файлы оплаченных инвойсов из «Без оплаты» в папку способа оплаты. */
|
||||
export async function runInvoiceFiling(deps: { pool: Pool; drive: FilingDrive; log: Logger }): Promise<{ moved: number; failed: number }> {
|
||||
const { pool, drive, log } = deps;
|
||||
const out = { moved: 0, failed: 0 };
|
||||
const c = await pool.connect();
|
||||
try {
|
||||
if (!(await c.query("select pg_try_advisory_lock($1) as ok", [LOCK_KEY])).rows[0].ok) return out;
|
||||
try {
|
||||
const { rows } = await pool.query<{ id: string; drive_file_id: string; vendor_name: string; amount: string; paid_on: string; account_name: string }>(
|
||||
`select i.id, i.drive_file_id, i.vendor_name, i.amount::text, i.paid_on::text, p.account_name
|
||||
from acc_invoices i join qbo_purchase p on p.id = i.qbo_txn_id
|
||||
where i.paid_on is not null and p.account_name is not null
|
||||
and (i.drive_folder is null or i.drive_folder like 'Инвойсы/${UNPAID_FOLDER}/%')
|
||||
order by i.paid_on limit ${BATCH}`,
|
||||
);
|
||||
for (const r of rows) {
|
||||
try {
|
||||
const path = invoiceFolderPath(r.account_name, new Date(`${r.paid_on}T00:00:00Z`));
|
||||
if (methodFolder(r.account_name) === UNPAID_FOLDER) continue;
|
||||
const folder = await drive.ensureFolder(path);
|
||||
const meta = await drive.meta(r.drive_file_id);
|
||||
await drive.move(r.drive_file_id, folder, invoiceFileName(r.amount, r.vendor_name, meta.name));
|
||||
await pool.query("update acc_invoices set drive_folder = $2 where id = $1", [r.id, path.join("/")]);
|
||||
out.moved++;
|
||||
} catch (e) {
|
||||
out.failed++;
|
||||
log.error({ invoice: r.id, err: String(e) }, "перенос файла инвойса на Drive не удался");
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} finally {
|
||||
await c.query("select pg_advisory_unlock($1)", [LOCK_KEY]);
|
||||
}
|
||||
} finally {
|
||||
c.release();
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,8 @@ d("загрузка инвойсов из почты (временная БД,
|
||||
expect(row).toMatchObject({ source_message_id: "m1", drive_file_id: "drv-1", vendor_qbo_id: "V1", project_customer_id: "C1", invoice_number: "INV-1", problem_highlight: null });
|
||||
expect(row.contract_id).toBe("00000000-0000-0000-0000-0000000000c1");
|
||||
expect(Number(row.amount)).toBe(1500);
|
||||
expect(uploads[0].folder).toEqual(["Инвойсы", "ACME Plumbing LLC", "2026-03"]);
|
||||
expect(uploads[0].folder).toEqual(["Инвойсы", "Без оплаты", "March 2026"]);
|
||||
expect(uploads[0].name).toBe("$1,500.00 ACME Plumbing LLC.pdf");
|
||||
expect((await db.pool.query("select 1 from acc_invoices_review_original where id = $1", [row.id])).rowCount).toBe(1);
|
||||
expect((await db.pool.query("select kind, ref_id from acc_manual_review")).rows).toEqual([{ kind: "invoice", ref_id: row.id }]);
|
||||
expect((await db.pool.query("select result from acc_mail_processed")).rows).toEqual([{ result: "invoice" }]);
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { Logger, Pool } from "khb_common";
|
||||
import type { ClaudeRunner } from "./claude-runner.js";
|
||||
import { UNTRUSTED_DOC_ARGS } from "./claude-runner.js";
|
||||
import type { DriveStore } from "./drive.js";
|
||||
import { invoiceFileName, invoiceFolderPath } from "./invoice-filing.js";
|
||||
import { ingestCertificate } from "./certificates-ingest.js";
|
||||
import { normalizeVendorName } from "./vendor-name.js";
|
||||
import type { MailAttachment, MailMessage, MailSource } from "./gmail.js";
|
||||
@@ -348,8 +349,10 @@ async function processAttachment(deps: InvoiceIngestDeps, msg: MailMessage, att:
|
||||
if (tbd.length) problems.unshift(`tbd: ${tbd.join(", ")}`);
|
||||
|
||||
const refDate = rec.invoice_date ? new Date(`${rec.invoice_date}T00:00:00Z`) : msg.receivedAt;
|
||||
const folder = await deps.drive.ensureFolder(["Инвойсы", safeName(rec.vendor_name ?? "Без вендора"), ym(refDate)]);
|
||||
const file = await deps.drive.upload(att.filename, att.mime || "application/octet-stream", bytes, folder);
|
||||
// раскладка как в папке «07. Invoices» Анастасии: способ оплаты / месяц / «$сумма Вендор.pdf»; способ оплаты неизвестен до оплаты - «Без оплаты»,
|
||||
// после оплаты файл переносится в папку счёта оплаты (invoice-filing.ts)
|
||||
const folder = await deps.drive.ensureFolder(invoiceFolderPath(null, refDate));
|
||||
const file = await deps.drive.upload(invoiceFileName(rec.amount, rec.vendor_name, att.filename), att.mime || "application/octet-stream", bytes, folder);
|
||||
|
||||
await pool.query(
|
||||
`insert into acc_invoices_review (id, source_message_id, drive_file_id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, lines,
|
||||
|
||||
@@ -18,6 +18,7 @@ import { runSpamRescue } from "./spam-rescue.js";
|
||||
import { runCategorizePost } from "./categorize-post.js";
|
||||
import { makeQboClient } from "./qbo-client.js";
|
||||
import { runQboAttach } from "./qbo-attach.js";
|
||||
import { runInvoiceFiling } from "./invoice-filing.js";
|
||||
import { runHistoryWeekly } from "./history-report.js";
|
||||
import { makeClaudeStatementReader, runMonthlyReconcile } from "./reconcile.js";
|
||||
import { buildApi } from "./http-api.js";
|
||||
@@ -164,7 +165,10 @@ const app = buildApi({
|
||||
"categorize-post": async () => runCategorizePost({ pool, claude, log, notify }),
|
||||
"qbo-attach": async () => {
|
||||
if (!qbo || !drive) throw new Error("не настроены qbo_auth (токен) или Drive");
|
||||
return runQboAttach({ pool, qbo, drive, log });
|
||||
const attached = await runQboAttach({ pool, qbo, drive, log });
|
||||
// оплаченные инвойсы: файл из «Без оплаты» в папку способа оплаты (раскладка как в «07. Invoices»)
|
||||
const filed = await runInvoiceFiling({ pool, drive, log });
|
||||
return { ...attached, filed };
|
||||
},
|
||||
"spam-rescue": async () => {
|
||||
if (!auth || !s.google) throw new Error("не настроены google (ключ сервисного аккаунта)");
|
||||
|
||||
34
packages/khb_common/migrations/079_old_invoices.sql
Normal file
34
packages/khb_common/migrations/079_old_invoices.sql
Normal file
@@ -0,0 +1,34 @@
|
||||
-- Архив инвойсов из 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;
|
||||
|
||||
-- Папка файла инвойса на Drive (Инвойсы/<способ оплаты>/<Месяц ГГГГ>); пусто - файл ещё в «Без оплаты» или в старой раскладке
|
||||
alter table acc_invoices add column if not exists drive_folder text;
|
||||
Reference in New Issue
Block a user