old_invoices: сопоставление проектов и вендоров, md-отчёт; pay_method (080); spam-rescue: сравнение без регистра и диакритики, исправлен json в белом списке
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
148
docs/proposed/data_objects/accounting_automation/old_invoices.md
Normal file
148
docs/proposed/data_objects/accounting_automation/old_invoices.md
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
# old_invoices: архив инвойсов из Excel Анастасии (попытка загрузки, 2026-11-30/12-01)
|
||||||
|
|
||||||
|
Статус: загружено, доводить не срочно. Таблица old_invoices (миграция 079) - история, в рабочий реестр acc_invoices не входит.
|
||||||
|
Источник: «Payments_Constr List 27 Oct.xlsx» (Drive id 1gPOutfuVrdEJK3j1YoaOd3e_7gHBv4GM), скрипты packages/accounting_automation/scripts/old-invoices-*.mjs (разбор, загрузка, сопоставление; повторяемо).
|
||||||
|
|
||||||
|
## Что загружено
|
||||||
|
- Лист «KH BUILD» (1294 строки, 2025-02..2026-11) - текущий реестр.
|
||||||
|
- Лист «KH Open Invoices» (1477 строк, 2024-02..2026-09) - прежний реестр.
|
||||||
|
- Лист «GK Open Invoices» НЕ переносится (решение Юрия): GK - компания-предшественник KH Build, по ней идут завершающие платежи, ведётся Анастасией вручную до закрытия. Поле «Компания» не добавляем. Если письма по GK попадут в разбор, они получат проблему «не та компания», Анастасия обработает их сама. Лист остаётся в Excel.
|
||||||
|
- Остальные листы (Total, Projects, Credit Lines, Loan Interest Payout, ASAP Shell и др.) - бюджеты и займы, не инвойсы.
|
||||||
|
|
||||||
|
## Автоматическое сопоставление (результат)
|
||||||
|
- Проект (адрес -> qbo_customer, ключ «номер + первое слово улицы»): 1857 из 2771 строк; на листе KH BUILD 1151 из 1294 (89%).
|
||||||
|
- Вендор (имя -> qbo_vendor без формы собственности и слов «final payment», «Draw N» и т. п.): 1899 из 2771; на листе KH BUILD 1126 из 1294 (87%).
|
||||||
|
- Первая попытка (грубое «like») давала почти ноль, потому что адреса в QuickBooks и в Excel пишутся по-разному. Замечание Анастасии про X или XX в начале относится к СЧЕТАМ (accounts) QuickBooks («XX6 161st Ave Curtis Craft», «X840 3rd Ave Craig Dean»); клиенты и проекты (qbo_customer, jt_job) в зеркале написаны нормально. Ключ адреса на всякий случай срезает ведущие X.
|
||||||
|
- Не сопоставились: 137 написаний проектов и 181 вендоров. В основном дома прежнего реестра (4540 11th Ave Lot 19, 5210 18th Ave S, Huron и т. п. - клиента в QuickBooks нет), записи без адреса («Total», «funding to KelnerHomes») и вендоры, которых нет в qbo_vendor.
|
||||||
|
|
||||||
|
Сопоставленные проекты (Excel -> клиент QuickBooks):
|
||||||
|
- 1935 Shore Acres -> 1935 Shore Acres Blvd
|
||||||
|
- 4000 43rd St S -> 4000 43rd
|
||||||
|
- 1943 Shore Acres -> 1943 Shore Acres Blvd
|
||||||
|
- 5223 29th Ave (2838 53rd St Lot 11) -> 5223 29th Ave Lot 11
|
||||||
|
- 5221 29th Ave (2838 53rd Lot 9) -> 5221 29th Ave S lot 9
|
||||||
|
- 5223 29th Ave (2838 53rd Lot 11) -> 5223 29th Ave Lot 11
|
||||||
|
- 5221 29th Ave (2838 53rd Lot 9) (Roof+Soffit+Fascia) -> 5221 29th Ave S lot 9
|
||||||
|
- 408 161st Ave -> 408 161st Ave, Redington Beach, FL 33708
|
||||||
|
- 5118 31st Ave S -> 5118 31st Ave S.
|
||||||
|
- 408 161st Avenue -> 408 161st Ave, Redington Beach, FL 33708
|
||||||
|
- 428 Bath Club Blvd -> 428 Bath Club Blvd N North Redington Beach Florida 33708
|
||||||
|
- 4203 S Trask St -> 4203 S Trask St, Tampa, FL 33611
|
||||||
|
- 1919 Arrowhead Dr NE -> 1919 Arrowhead Drive NE
|
||||||
|
- 7841 3rd Ave S -> 7841 3rd Ave S
|
||||||
|
- 734 Placido Way, St Pet -> 734 Placido Way NE, Saint Petersburg, Florida 33704
|
||||||
|
- 586 182nd Ave E, Reddington Shores -> 586 182nd Ave E, Reddington Shores 33708
|
||||||
|
- 256 Bayside Dr -> 256 Bayside Dr, Clearwater
|
||||||
|
- 646 Mehlenbacher Rd -> 646 Mehlenbacher Rd, Belleair, FL 33756
|
||||||
|
- 340 Boca Ciega Dr -> 340 Boca Ciega Drive, Madeira Beach, Florida 33708
|
||||||
|
- 6183 1st (расходы КН Вuild) -> 6183 1st Avenue North St. Petersburg
|
||||||
|
- 301 161st Ave -> 301 161st Ave, Redington Beach
|
||||||
|
- 16112 Redington Dr -> 16112 Redington Dr, Redington Beach, FL 33708
|
||||||
|
- 1919 Arrowhead Dr NE (375 13th St N) -> 1919 Arrowhead Drive NE
|
||||||
|
- 1807 Pass-a-Grille Way -> 1807 Pass A Grill
|
||||||
|
- 406 161st Ave -> 406 161st Ave, Redington Beach
|
||||||
|
- 1807 Pass a Grille Way, St Pete Beach -> 1807 Pass A Grill
|
||||||
|
- 586 182nd Ave E, Raddington Shores -> 586 182nd Ave E, Reddington Shores 33708
|
||||||
|
- 1807 Pass A Grill -> 1807 Pass A Grill
|
||||||
|
- 424 Monte Cristo -> 424 Monte Cristo Blvd, Tierra Verde, FL 33715
|
||||||
|
- 1145 Boca Ciega -> 1145 Boca Ciega
|
||||||
|
- 424 Monte Cristo Blvd -> 424 Monte Cristo Blvd, Tierra Verde, FL 33715
|
||||||
|
- 11410 1st St E, Treasure Island -> 11410 1st St E, Treasure Island
|
||||||
|
- 15500 2nd St E -> 15500 2ND ST E, Redington Beach, FL 33708
|
||||||
|
- 340 Boca Ciega Dr. Madeira Beach (Marsha Buckley) -> 340 Boca Ciega Drive, Madeira Beach, Florida 33708
|
||||||
|
- 6183 1st Ave -> 6183 1st Avenue North St. Petersburg
|
||||||
|
|
||||||
|
Крупнейшие несопоставленные проекты (по сумме):
|
||||||
|
- Huron: $805,523
|
||||||
|
- 4540 11th Ave Lot 19: $383,203
|
||||||
|
- Penta / Lumsden: $304,146
|
||||||
|
- 4550 11th Ave Lot 20: $289,658
|
||||||
|
- 5210 18th Ave S: $287,650
|
||||||
|
- 4560 11th Ave Lot 21: $276,738
|
||||||
|
- KELNER HOLDINGS money: $185,000
|
||||||
|
- 301 79 th St: $108,994
|
||||||
|
- (total +750k): $100,000
|
||||||
|
- 6014 Kipps Colony: $95,266
|
||||||
|
- 4550 11th Ave: $73,980
|
||||||
|
- 4560 11th Ave: $69,125
|
||||||
|
- Snug Lot 3-7 (5 Lots): $66,250
|
||||||
|
- KH Build LLC: $61,663
|
||||||
|
- Invoice 21525: $49,485
|
||||||
|
- 1783 Tanglewood Dr NE: $43,347
|
||||||
|
- 1935 / 1943 Shore Acres: $42,822
|
||||||
|
- 1934 Shore Acres: $39,800
|
||||||
|
- 2838 53RD ST Lot 9: $39,172
|
||||||
|
- 3715 15th: $36,877
|
||||||
|
- Pasadena 2: $34,839
|
||||||
|
- Kelner Randesi - Lot Specific: $29,950
|
||||||
|
- 3036 Fairfield Ave. S: $28,342
|
||||||
|
- Kelner Nelson-Vac - Lot Specific: $25,823
|
||||||
|
- Kelner Stewart - Lot 1: $25,000
|
||||||
|
- 2045 Michigan Ave: $24,850
|
||||||
|
- balance from Khomes: $23,418
|
||||||
|
- 5718 Tangerine Ave S: $23,167
|
||||||
|
- 3715 15th St: $20,501
|
||||||
|
- Snug Harbor: $20,377
|
||||||
|
- 6014 Kipps Colony Driv: $19,553
|
||||||
|
- Kelner Caldwell - Lot Specific: $17,157
|
||||||
|
- Hope Res. - 2 Sea Ln., St. Pete: $17,040
|
||||||
|
- 10455 14th Street NE: $15,875
|
||||||
|
- 2867 Fairfield Ave: $15,217
|
||||||
|
- 3036 Fairfield ave: $15,120
|
||||||
|
- Kelner Cavanaugh - Lot Specific: $14,095
|
||||||
|
- Tangerine Lot 1: $13,503
|
||||||
|
- Kelner - Alejo Lot 1: $13,000
|
||||||
|
- Kelner Stewart - Lot 2: $13,000
|
||||||
|
|
||||||
|
Крупнейшие несопоставленные вендоры (по сумме):
|
||||||
|
- Total: $1,772,742
|
||||||
|
- DE LA CRUZ REMODELING: $328,745
|
||||||
|
- Tampa Shell Contractors: $304,022
|
||||||
|
- DSA / MANCINI: $280,777
|
||||||
|
- Craigco Stucco LLC: $211,800
|
||||||
|
- funding to KelnerHomes: $200,000
|
||||||
|
- KKC TOTAL SERVICES: $199,578
|
||||||
|
- NESTER ALFONSO PLUMBING: $182,550
|
||||||
|
- FIRMA DRYWALL: $176,798
|
||||||
|
- Flamingo Homes: $159,836
|
||||||
|
- SPEELER & ASSOC. INC: $147,740
|
||||||
|
- DSA: $141,410
|
||||||
|
- Master Godoy Llc (ASAP Shell): $126,000
|
||||||
|
- PF&L: $113,040
|
||||||
|
- JI Electric Choice Corp: $109,980
|
||||||
|
- funding to GK LLC: $85,000
|
||||||
|
- Johan Construction Inc.: $79,672
|
||||||
|
- Rocu Solution LLC (Steps & Glass): $78,688
|
||||||
|
- TILNEY POOLS: $77,406
|
||||||
|
- Carrolls: $74,408
|
||||||
|
- Santos A/C & Plumbing: $74,000
|
||||||
|
- Cardon A/C and Heating Services, LLC: $72,400
|
||||||
|
- Floor and Décor: $61,177
|
||||||
|
- King Stone Surfaces, LLC: $55,988
|
||||||
|
- The Sower Design LLC: $53,980
|
||||||
|
- FAMOUS TATE: $53,528
|
||||||
|
- 11 June: $50,000
|
||||||
|
- Quality Garage Doors Services LLC: $49,840
|
||||||
|
- One Aluminum: $48,235
|
||||||
|
- 16x9 Agency (MTM Creative): $48,000
|
||||||
|
- JOSS Contracting, LLC: $47,155
|
||||||
|
- All-Pro Roofing Services Inc.: $47,080
|
||||||
|
- ALANS CONSTRUCTION USA INC.: $46,500
|
||||||
|
- Rocu Solution LLC (Steps & Glass) / Steps LLC USA: $44,506
|
||||||
|
- J&J Quality Air INC: $41,200
|
||||||
|
- Martin Air Conditioning & Refrigeration Corp.: $38,864
|
||||||
|
- A. Metelskiy: $33,823
|
||||||
|
- CALI: $33,273
|
||||||
|
- evans Roofing: $30,826
|
||||||
|
- Tampa Bay Roofing Services: $30,000
|
||||||
|
|
||||||
|
## Оставшиеся расхождения формата с acc_invoices
|
||||||
|
- Нет PDF: ссылка на Drive только в 17 строках. Обратная связь с папкой «7. FINANCE / 07. Invoices» (файлы «$сумма Вендор.pdf» по способу оплаты и месяцу): сервисный аккаунт эту папку не видит (список пуст). Нужно открыть папку сервисному аккаунту на чтение, тогда сопоставление по сумме и вендору делается автоматически.
|
||||||
|
- Способ оплаты: столбец pay_method добавлен в acc_invoices и таблицы разбора (миграция 080); в old_invoices он есть (pay_method, pay_method_raw).
|
||||||
|
- Нет строк-категорий (lines), структуры согласования (в тексте «approved», «not approved yet (Artur)»), у части оплаченных строк не разобрана дата оплаты.
|
||||||
|
|
||||||
|
## Договоры: предложение
|
||||||
|
- В Excel договор виден только как «total $X» в примечании у платежей (1367 строк, 299 пар «вендор + проект» с суммой договора).
|
||||||
|
- Предложение: из old_invoices строить кандидатов в договоры (вендор + проект): total_amount = максимум «total $X» по паре, paid_amount = сумма платежей с признаком «оплачено», остаток = разница. Кандидатов складывать в отдельный просмотр (не в acc_contracts) и показывать Анастасии пачкой; одобренные переносятся в acc_contracts одним действием.
|
||||||
|
- Платежи без «total» (депозит, «Contract», «DrReq N») договором не считать: они остаются историей.
|
||||||
|
- Ждёт решения Юрия: делать ли этот просмотр сейчас или после согласования раскладки с Анастасией.
|
||||||
@@ -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 символов. */
|
/** Слово для сравнения: имя без формы собственности, не короче 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 {
|
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;
|
return t.length >= 4 ? t : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +58,7 @@ export function decide(mail: SpamMail, rules: RescueRules): RescueDecision {
|
|||||||
const sender = senderEmail(mail.from);
|
const sender = senderEmail(mail.from);
|
||||||
if (rules.whitelist.has(sender)) return { rescue: true, reason: `белый список: ${sender}` };
|
if (rules.whitelist.has(sender)) return { rescue: true, reason: `белый список: ${sender}` };
|
||||||
if (!/\binvoices?@khbuild\.pro\b/i.test(mail.recipients)) return { rescue: false, reason: "не на invoice@" };
|
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 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}»` };
|
for (const t of rules.terms) if (hay.includes(t)) return { rescue: true, reason: `слово «${t}»` };
|
||||||
return { rescue: false, reason: "нет слов из списка" };
|
return { rescue: false, reason: "нет слов из списка" };
|
||||||
@@ -163,7 +166,7 @@ class Mailbox {
|
|||||||
async function learnWhitelist(o: RescueOptions, src: Mailbox, res: RescueResult): Promise<void> {
|
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 }>(
|
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
|
`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) {
|
for (const r of rows) {
|
||||||
let from: string;
|
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