@fayz-ai/financial 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,11 +5,11 @@ import { createIdempotencyKey } from './chunk-IP5YH4S5.js';
5
5
  import { NAME_AMOUNT_TOLERANCE, matchStatementLines, scorePair } from './chunk-ZFUQBYBG.js';
6
6
  import { emptyStatement, ledgerBalance, buildStatement } from './chunk-HJPUHTI2.js';
7
7
  import { transferLegs } from './chunk-YUNLQYOZ.js';
8
- import { cancellationReason, invoiceTotal, itemsDescription, summarizeInvoiceLines, lineTotal } from './chunk-5F6ULA56.js';
8
+ import { cancellationReason, invoiceTotal, itemsDescription, summarizeInvoiceLines, lineTotal } from './chunk-HPJDTBVB.js';
9
9
  import { paymentFee, ledgerMethod, toLedgerDirection, fromLedgerDirection } from './chunk-4GXBOEI3.js';
10
10
  import { sessionCashFlow } from './chunk-56NQHYL7.js';
11
- import { runReconcileAsBill, runReconcileLink } from './chunk-FNXIAIUZ.js';
12
- import { transferForStatementLine, statementLegOf, candidateTolerance, candidateScore, statementLinesPage, pageTotals } from './chunk-MCSPCXQK.js';
11
+ import { runReconcileAsBill, runReconcileLink } from './chunk-NONT5MVW.js';
12
+ import { transferForStatementLine, statementLegOf, statementLineKey, rememberClassifications, candidateTolerance, candidateScore, statementLinesPage, pageTotals } from './chunk-MCRRCRQZ.js';
13
13
  import { round2 } from './chunk-XVELDCSL.js';
14
14
  import { summarizeSyncStatus } from './chunk-3QNU7XUB.js';
15
15
  import { getActiveTenantId, getSupabaseClientOptional } from '@fayz-ai/core';
@@ -231,6 +231,22 @@ async function attachCurrency(pub, invoices) {
231
231
  } catch {
232
232
  }
233
233
  }
234
+ async function sumStatementLines(build) {
235
+ const CHUNK = 1e3;
236
+ const rows = [];
237
+ try {
238
+ for (let from = 0; from < 5e4; from += CHUNK) {
239
+ const { data, error } = await build().order("id", { ascending: true }).range(from, from + CHUNK - 1);
240
+ if (error) return void 0;
241
+ for (const row of data ?? []) rows.push({ direction: row.direction, amount: Number(row.amount) || 0 });
242
+ if (!data || data.length < CHUNK) break;
243
+ }
244
+ } catch {
245
+ return void 0;
246
+ }
247
+ const { pageCredits, pageDebits, pageBalance } = pageTotals(rows);
248
+ return { credits: pageCredits, debits: pageDebits, balance: pageBalance };
249
+ }
234
250
  async function sumInvoiceLines(build) {
235
251
  const CHUNK = 1e3;
236
252
  const byCurrency = /* @__PURE__ */ new Map();
@@ -504,7 +520,7 @@ function createSupabaseFinancialProvider() {
504
520
  const page = query.page ?? 1;
505
521
  const pageSize = query.pageSize ?? 50;
506
522
  qb = qb.range((page - 1) * pageSize, page * pageSize);
507
- qb = query.sort === "recent" ? qb.order("created_at", { ascending: false }).order("due_date", { ascending: true }) : qb.order("due_date", { ascending: true });
523
+ qb = query.sort === "recent" ? qb.order("created_at", { ascending: false }).order("due_date", { ascending: true }) : qb.order("due_date", { ascending: false }).order("created_at", { ascending: false });
508
524
  const { data, count, error } = await qb;
509
525
  if (error) throw error;
510
526
  const rows = data ?? [];
@@ -2333,32 +2349,38 @@ function createSupabaseFinancialProvider() {
2333
2349
  const { pub } = getClients();
2334
2350
  const { page, pageSize } = statementLinesPage(query);
2335
2351
  const from = (page - 1) * pageSize;
2336
- let qb = pub.from(T.statementLines).select("*", { count: "exact" }).eq("provider_deleted", false);
2337
- if (query?.bankAccountId) qb = qb.eq("bank_account_id", query.bankAccountId);
2338
- if (query?.dateRange) qb = qb.gte("posted_on", query.dateRange.from).lte("posted_on", query.dateRange.to);
2339
- if (query?.direction) qb = qb.eq("direction", query.direction);
2340
- if (query?.status === "reconciled") qb = qb.not("reconciled_at", "is", null);
2341
- else if (query?.status === "pending") qb = qb.is("reconciled_at", null);
2342
- const term = (query?.search ?? "").trim();
2343
- if (term) {
2344
- const safe = term.replace(/[,()*%]/g, " ");
2345
- qb = qb.or([
2346
- `description.ilike.%${safe}%`,
2347
- `counterparty_name.ilike.%${safe}%`,
2348
- `counterparty_document.ilike.%${safe}%`,
2349
- `document.ilike.%${safe}%`,
2350
- `code.ilike.%${safe}%`,
2351
- `category.ilike.%${safe}%`,
2352
- `transaction_type.ilike.%${safe}%`,
2353
- `external_id.ilike.%${safe}%`
2354
- ].join(","));
2355
- }
2356
- if (query?.hideInvestments) qb = qb.or(`code.is.null,code.not.in.(${INVESTMENT_CODES.join(",")})`);
2357
- const { data, error, count } = await qb.order("posted_on", { ascending: false }).order("id", { ascending: false }).range(from, from + pageSize - 1);
2352
+ const filtrar = (base) => {
2353
+ let qb = base.eq("provider_deleted", false);
2354
+ if (query?.bankAccountId) qb = qb.eq("bank_account_id", query.bankAccountId);
2355
+ if (query?.dateRange) qb = qb.gte("posted_on", query.dateRange.from).lte("posted_on", query.dateRange.to);
2356
+ if (query?.direction) qb = qb.eq("direction", query.direction);
2357
+ if (query?.status === "reconciled") qb = qb.not("reconciled_at", "is", null);
2358
+ else if (query?.status === "pending") qb = qb.is("reconciled_at", null);
2359
+ const term = (query?.search ?? "").trim();
2360
+ if (term) {
2361
+ const safe = term.replace(/[,()*%]/g, " ");
2362
+ qb = qb.or([
2363
+ `description.ilike.%${safe}%`,
2364
+ `counterparty_name.ilike.%${safe}%`,
2365
+ `counterparty_document.ilike.%${safe}%`,
2366
+ `document.ilike.%${safe}%`,
2367
+ `code.ilike.%${safe}%`,
2368
+ `category.ilike.%${safe}%`,
2369
+ `transaction_type.ilike.%${safe}%`,
2370
+ `external_id.ilike.%${safe}%`
2371
+ ].join(","));
2372
+ }
2373
+ if (query?.hideInvestments) qb = qb.or(`code.is.null,code.not.in.(${INVESTMENT_CODES.join(",")})`);
2374
+ return qb;
2375
+ };
2376
+ const [{ data, error, count }, totals] = await Promise.all([
2377
+ filtrar(pub.from(T.statementLines).select("*", { count: "exact" })).order("posted_on", { ascending: false }).order("id", { ascending: false }).range(from, from + pageSize - 1),
2378
+ sumStatementLines(() => filtrar(pub.from(T.statementLines).select("id,direction,amount")))
2379
+ ]);
2358
2380
  if (error) throw error;
2359
2381
  const rows = (data ?? []).map(toStatementLine);
2360
2382
  await anexaContraparte(rows);
2361
- return { rows, total: count ?? 0, page, pageSize, ...pageTotals(rows) };
2383
+ return { rows, total: count ?? 0, page, pageSize, ...pageTotals(rows), totals };
2362
2384
  },
2363
2385
  async getUnreconciled(query) {
2364
2386
  const { pub } = getClients();
@@ -2448,6 +2470,54 @@ function createSupabaseFinancialProvider() {
2448
2470
  lastSyncError: r.last_sync_error
2449
2471
  })));
2450
2472
  },
2473
+ // The memory of the statement: lines already reconciled to a bill say which
2474
+ // chart account their counterparty goes to. Read newest first and capped;
2475
+ // a counterparty that matters shows up in the recent history.
2476
+ async suggestClassifications(lines) {
2477
+ const { pub } = getClients();
2478
+ const abertas = lines.filter((line) => !line.reconciledAt);
2479
+ if (abertas.length === 0) return {};
2480
+ const wanted = new Set(abertas.map(statementLineKey));
2481
+ const { data: hist, error } = await pub.from(T.statementLines).select("direction,description,counterparty_name,counterparty_document,matched_movement_id,posted_on").eq("provider_deleted", false).not("reconciled_at", "is", null).not("matched_movement_id", "is", null).in("direction", [...new Set(abertas.map((line) => line.direction))]).order("posted_on", { ascending: false }).limit(2e3);
2482
+ if (error) throw error;
2483
+ const relevant = (hist ?? []).map((r) => ({ row: r, key: statementLineKey(toStatementLine(r)) })).filter((h) => wanted.has(h.key));
2484
+ if (relevant.length === 0) return {};
2485
+ const inChunks = async (ids, read) => {
2486
+ const out2 = [];
2487
+ for (let i = 0; i < ids.length; i += 150) out2.push(...(await read(ids.slice(i, i + 150))).data ?? []);
2488
+ return out2;
2489
+ };
2490
+ const movementIds = [...new Set(relevant.map((h) => h.row.matched_movement_id))];
2491
+ const movements = await inChunks(movementIds, (chunk) => pub.from(T.movements).select("id,financial_invoice_id").in("id", chunk));
2492
+ const invoiceOf = new Map(movements.filter((m) => m.financial_invoice_id).map((m) => [m.id, m.financial_invoice_id]));
2493
+ const invoiceIds = [...new Set(invoiceOf.values())];
2494
+ const items = await inChunks(invoiceIds, (chunk) => pub.from("v_financial_invoice_lines").select("invoice_id,chart_account_id,total").in("invoice_id", chunk).not("chart_account_id", "is", null).is("item_cancelled_at", null));
2495
+ const accountOf = /* @__PURE__ */ new Map();
2496
+ for (const item of items) {
2497
+ const total = Math.abs(Number(item.total) || 0);
2498
+ const best = accountOf.get(item.invoice_id);
2499
+ if (!best || total > best.total) accountOf.set(item.invoice_id, { accountId: item.chart_account_id, total });
2500
+ }
2501
+ const history = [];
2502
+ for (const h of relevant) {
2503
+ const invoiceId = invoiceOf.get(h.row.matched_movement_id);
2504
+ const account = invoiceId ? accountOf.get(invoiceId) : void 0;
2505
+ if (!account) continue;
2506
+ history.push({ key: h.key, accountId: account.accountId, contactName: h.row.counterparty_name ?? void 0, date: h.row.posted_on ?? "" });
2507
+ }
2508
+ const memory = rememberClassifications(history);
2509
+ if (memory.size === 0) return {};
2510
+ const accountIds = [...new Set([...memory.values()].map((m) => m.accountId))];
2511
+ const accounts = await inChunks(accountIds, (chunk) => pub.from(T.chartOfAccounts).select("id,code,name,is_active").in("id", chunk));
2512
+ const nameOf = new Map(accounts.filter((a) => a.is_active !== false).map((a) => [a.id, [a.code, a.name].filter(Boolean).join(" ")]));
2513
+ const out = {};
2514
+ for (const line of abertas) {
2515
+ const m = memory.get(statementLineKey(line));
2516
+ if (!m || !nameOf.has(m.accountId)) continue;
2517
+ out[line.id] = { ...m, accountName: nameOf.get(m.accountId) };
2518
+ }
2519
+ return out;
2520
+ },
2451
2521
  async suggestReconciliationBatch(lines) {
2452
2522
  const { core, pub } = getClients();
2453
2523
  const abertas = lines.filter((line) => !line.reconciledAt && (Number(line.amount) || 0) > 0);
@@ -2853,5 +2923,5 @@ function createSupabaseFinancialProvider() {
2853
2923
  }
2854
2924
 
2855
2925
  export { createSupabaseFinancialProvider, invoiceLineOrFilter };
2856
- //# sourceMappingURL=chunk-TU2JMMVO.js.map
2857
- //# sourceMappingURL=chunk-TU2JMMVO.js.map
2926
+ //# sourceMappingURL=chunk-Y6XGQLEV.js.map
2927
+ //# sourceMappingURL=chunk-Y6XGQLEV.js.map