accounting_automation: сверка инвойсов с QuickBooks (invoice-reconcile), оплата независима от согласования, сумма и вендор из ленты, сводка Анастасии, правки finalize, поиска чека, проверки инвойса, chargeback; документы
Миграция 071: acc_discrepancies.reason и уникальный индекс открытых расхождений, уникальный открытый card_fraud по операции, insurer в разборе сертификатов. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,7 +6,8 @@ import type { Pool } from "khb_common";
|
||||
* - резкое изменение суммы регулярного платежа (сумма >= множитель x медиана прошлых платежей, не меньше minHistory платежей в истории).
|
||||
* Причина дописывается в problem_highlight (существующий текст не затирается, повторно не дублируется).
|
||||
* Данные операции берутся из suggestion в acc_categorization_review: amount, vendor_qbo_id, vendor_name,
|
||||
* bank_account_id (счёт или карта QuickBooks), is_card / payment_type.
|
||||
* bank_account_id (счёт или карта QuickBooks), is_card / payment_type. Если suggestion пусто или в нём нет суммы или вендора,
|
||||
* недостающее берётся из acc_feed_txn (amount, vendor_name, card_or_account), см. loadOperation.
|
||||
*/
|
||||
|
||||
export interface FraudSettings {
|
||||
@@ -84,6 +85,24 @@ export function suggestionAmount(s: Suggestion | null): number | null {
|
||||
}
|
||||
export const vendorOf = (s: Suggestion | null): { qboId: string | null; name: string | null } => ({ qboId: str(s?.vendor_qbo_id), name: str(s?.vendor_name) });
|
||||
|
||||
/**
|
||||
* Данные операции: suggestion, дополненный строкой acc_feed_txn (сумма, вендор), если в suggestion их нет (в том числе suggestion = null).
|
||||
* feedCard - карта или счёт из ленты (последние 4 цифры или название): по нему определяется «карта» через acc_card_holders.
|
||||
*/
|
||||
export async function loadOperation(pool: Pool, feedTxnId: string, suggestion: Suggestion | null): Promise<{ suggestion: Suggestion | null; feedCard: string | null }> {
|
||||
const f = (
|
||||
await pool.query<{ amount: number | null; vendor_name: string | null; card_or_account: string | null }>(
|
||||
"select amount::float8 as amount, vendor_name, card_or_account from acc_feed_txn where feed_txn_id = $1",
|
||||
[feedTxnId],
|
||||
)
|
||||
).rows[0];
|
||||
if (!f) return { suggestion, feedCard: null };
|
||||
const merged: Suggestion = { ...(suggestion ?? {}) };
|
||||
if (suggestionAmount(merged) === null && f.amount !== null) merged.amount = f.amount;
|
||||
if (!str(merged.vendor_name) && !str(merged.vendor_qbo_id) && str(f.vendor_name)) merged.vendor_name = f.vendor_name;
|
||||
return { suggestion: Object.keys(merged).length > 0 ? merged : null, feedCard: str(f.card_or_account) };
|
||||
}
|
||||
|
||||
/** История платежей вендору: покупки qbo_purchase (кроме самой операции, если она уже проведена) и ранее закрытые разборы. */
|
||||
export async function queryVendorHistory(
|
||||
pool: Pool,
|
||||
@@ -111,10 +130,15 @@ export async function queryVendorHistory(
|
||||
}
|
||||
|
||||
/** Операция по карте: явный признак в suggestion либо счёт - кредитная карта (qbo_account) или карта из acc_card_holders. */
|
||||
export async function isCardOperation(pool: Pool, s: Suggestion | null, realmId?: string | null): Promise<boolean> {
|
||||
export async function isCardOperation(pool: Pool, s: Suggestion | null, realmId?: string | null, feedCard?: string | null): Promise<boolean> {
|
||||
if (s?.is_card === true || s?.payment_type === "CreditCard") return true;
|
||||
const acct = str(s?.bank_account_id);
|
||||
if (!acct) return false;
|
||||
if (!acct) {
|
||||
// карта из ленты (acc_feed_txn.card_or_account): совпадает с картой держателя целиком или по последним 4 цифрам
|
||||
if (!feedCard) return false;
|
||||
const h = await pool.query("select 1 from acc_card_holders where card_or_account = $1::text or (length($1::text) >= 4 and right(card_or_account, 4) = right($1::text, 4)) limit 1", [feedCard]);
|
||||
return (h.rowCount ?? 0) > 0;
|
||||
}
|
||||
const r = await pool.query(
|
||||
`select (exists (select 1 from qbo_account where id = $1::text and account_type = 'Credit Card' and ($2::text is null or realm_id = $2::text))
|
||||
or exists (select 1 from acc_card_holders where card_or_account = $1::text)) as card`,
|
||||
@@ -143,8 +167,8 @@ export async function flagOne(
|
||||
| { suggestion: Suggestion | null; problem_highlight: string | null }
|
||||
| undefined;
|
||||
if (!row) return "no_data";
|
||||
const s = row.suggestion;
|
||||
const card = await isCardOperation(pool, s, opts.realmId);
|
||||
const { suggestion: s, feedCard } = await loadOperation(pool, feedTxnId, row.suggestion);
|
||||
const card = await isCardOperation(pool, s, opts.realmId, feedCard);
|
||||
if (!card) {
|
||||
// Не карта: флажки не нужны. Отметку ставим только если есть suggestion (иначе признак «карта» могут ещё дописать).
|
||||
if (!s) return "no_data";
|
||||
|
||||
Reference in New Issue
Block a user