@fayz-ai/financial 0.3.0 → 0.3.2

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-CTJ6LVDH.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-IVIMTPAV.js';
12
+ import { transferForStatementLine, statementLegOf, candidateTolerance, candidateScore, statementLinesPage, pageTotals } from './chunk-NAEXIF3W.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';
@@ -155,14 +155,15 @@ function invoiceLineOrFilter(groups) {
155
155
  return `and(${active.map((g) => `or(${g.join(",")})`).join(",")})`;
156
156
  }
157
157
  async function findInvoiceIdsByLineAccounting(core, pub, filters) {
158
- if (!filters.accountId && !filters.costCenterId) return void 0;
158
+ const accountIds = filters.accountIds?.length ? filters.accountIds : filters.accountId ? [filters.accountId] : [];
159
+ if (accountIds.length === 0 && !filters.costCenterId) return void 0;
159
160
  let sideQ = pub.from(T.invoiceItems).select("item_id");
160
- if (filters.accountId) sideQ = sideQ.eq("chart_account_id", filters.accountId);
161
+ if (accountIds.length > 0) sideQ = sideQ.in("chart_account_id", accountIds);
161
162
  if (filters.costCenterId) sideQ = sideQ.eq("cost_center_id", filters.costCenterId);
162
163
  const { data: sideRows } = await sideQ;
163
164
  const itemIds = (sideRows ?? []).map((r) => r.item_id).filter(Boolean);
164
165
  let legacyQ = core.from("items").select("id");
165
- if (filters.accountId) legacyQ = legacyQ.filter("metadata->>accountId", "eq", filters.accountId);
166
+ if (accountIds.length > 0) legacyQ = legacyQ.filter("metadata->>accountId", "in", `(${accountIds.join(",")})`);
166
167
  if (filters.costCenterId) legacyQ = legacyQ.filter("metadata->>costCenterId", "eq", filters.costCenterId);
167
168
  const { data: legacyRows } = await legacyQ;
168
169
  for (const r of legacyRows ?? []) if (r.id) itemIds.push(r.id);
@@ -230,6 +231,22 @@ async function attachCurrency(pub, invoices) {
230
231
  } catch {
231
232
  }
232
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
+ }
233
250
  async function sumInvoiceLines(build) {
234
251
  const CHUNK = 1e3;
235
252
  const byCurrency = /* @__PURE__ */ new Map();
@@ -471,6 +488,7 @@ function createSupabaseFinancialProvider() {
471
488
  ].join(",");
472
489
  const scoped = await findInvoiceIdsByLineAccounting(core, pub, {
473
490
  accountId: query.accountId,
491
+ accountIds: query.accountIds,
474
492
  costCenterId: query.costCenterId
475
493
  });
476
494
  if (scoped && scoped.length === 0) return { data: [], total: 0, totals: [], nextDueDate: null };
@@ -502,7 +520,7 @@ function createSupabaseFinancialProvider() {
502
520
  const page = query.page ?? 1;
503
521
  const pageSize = query.pageSize ?? 50;
504
522
  qb = qb.range((page - 1) * pageSize, page * pageSize);
505
- 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 });
506
524
  const { data, count, error } = await qb;
507
525
  if (error) throw error;
508
526
  const rows = data ?? [];
@@ -2331,32 +2349,38 @@ function createSupabaseFinancialProvider() {
2331
2349
  const { pub } = getClients();
2332
2350
  const { page, pageSize } = statementLinesPage(query);
2333
2351
  const from = (page - 1) * pageSize;
2334
- let qb = pub.from(T.statementLines).select("*", { count: "exact" }).eq("provider_deleted", false);
2335
- if (query?.bankAccountId) qb = qb.eq("bank_account_id", query.bankAccountId);
2336
- if (query?.dateRange) qb = qb.gte("posted_on", query.dateRange.from).lte("posted_on", query.dateRange.to);
2337
- if (query?.direction) qb = qb.eq("direction", query.direction);
2338
- if (query?.status === "reconciled") qb = qb.not("reconciled_at", "is", null);
2339
- else if (query?.status === "pending") qb = qb.is("reconciled_at", null);
2340
- const term = (query?.search ?? "").trim();
2341
- if (term) {
2342
- const safe = term.replace(/[,()*%]/g, " ");
2343
- qb = qb.or([
2344
- `description.ilike.%${safe}%`,
2345
- `counterparty_name.ilike.%${safe}%`,
2346
- `counterparty_document.ilike.%${safe}%`,
2347
- `document.ilike.%${safe}%`,
2348
- `code.ilike.%${safe}%`,
2349
- `category.ilike.%${safe}%`,
2350
- `transaction_type.ilike.%${safe}%`,
2351
- `external_id.ilike.%${safe}%`
2352
- ].join(","));
2353
- }
2354
- if (query?.hideInvestments) qb = qb.or(`code.is.null,code.not.in.(${INVESTMENT_CODES.join(",")})`);
2355
- 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
+ ]);
2356
2380
  if (error) throw error;
2357
2381
  const rows = (data ?? []).map(toStatementLine);
2358
2382
  await anexaContraparte(rows);
2359
- return { rows, total: count ?? 0, page, pageSize, ...pageTotals(rows) };
2383
+ return { rows, total: count ?? 0, page, pageSize, ...pageTotals(rows), totals };
2360
2384
  },
2361
2385
  async getUnreconciled(query) {
2362
2386
  const { pub } = getClients();
@@ -2851,5 +2875,5 @@ function createSupabaseFinancialProvider() {
2851
2875
  }
2852
2876
 
2853
2877
  export { createSupabaseFinancialProvider, invoiceLineOrFilter };
2854
- //# sourceMappingURL=chunk-AYMB572M.js.map
2855
- //# sourceMappingURL=chunk-AYMB572M.js.map
2878
+ //# sourceMappingURL=chunk-5FESQBPQ.js.map
2879
+ //# sourceMappingURL=chunk-5FESQBPQ.js.map