@fayz-ai/financial 0.2.2 → 0.3.0

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,7 +5,7 @@ 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-ZWPYYIZW.js';
8
+ import { cancellationReason, invoiceTotal, itemsDescription, summarizeInvoiceLines, lineTotal } from './chunk-CTJ6LVDH.js';
9
9
  import { paymentFee, ledgerMethod, toLedgerDirection, fromLedgerDirection } from './chunk-4GXBOEI3.js';
10
10
  import { sessionCashFlow } from './chunk-56NQHYL7.js';
11
11
  import { runReconcileAsBill, runReconcileLink } from './chunk-FNXIAIUZ.js';
@@ -230,6 +230,28 @@ async function attachCurrency(pub, invoices) {
230
230
  } catch {
231
231
  }
232
232
  }
233
+ async function sumInvoiceLines(build) {
234
+ const CHUNK = 1e3;
235
+ const byCurrency = /* @__PURE__ */ new Map();
236
+ try {
237
+ for (let from = 0; from < 5e4; from += CHUNK) {
238
+ const { data, error } = await build().order("installment_id", { ascending: true }).range(from, from + CHUNK - 1);
239
+ if (error) return void 0;
240
+ for (const row of data ?? []) {
241
+ if (row.status === "cancelled") continue;
242
+ const code = row.invoice?.currency ?? "";
243
+ const sum = byCurrency.get(code) ?? { currency: code || void 0, total: 0, paid: 0 };
244
+ sum.total += Number(row.amount) || 0;
245
+ sum.paid += Number(row.paid) || 0;
246
+ byCurrency.set(code, sum);
247
+ }
248
+ if (!data || data.length < CHUNK) break;
249
+ }
250
+ } catch {
251
+ return void 0;
252
+ }
253
+ return [...byCurrency.values()];
254
+ }
233
255
  async function attachTags(pub, invoice) {
234
256
  try {
235
257
  const { data, error } = await pub.from("plg_financial_invoices").select("tags").eq("id", invoice.id).maybeSingle();
@@ -447,42 +469,48 @@ function createSupabaseFinancialProvider() {
447
469
  "created_at",
448
470
  "updated_at"
449
471
  ].join(",");
450
- let qb = pub.from("v_financial_invoice_lines_due").select(COLUNAS, { count: "exact" });
451
- if (query.direction) qb = qb.eq("direction", toLedgerDirection(query.direction));
452
- if (query.status) {
453
- const statuses = Array.isArray(query.status) ? query.status : [query.status];
454
- qb = qb.in("status", statuses.map((st) => st === "open" ? "pending" : st));
455
- } else {
456
- qb = qb.neq("status", "cancelled");
457
- }
458
472
  const scoped = await findInvoiceIdsByLineAccounting(core, pub, {
459
473
  accountId: query.accountId,
460
474
  costCenterId: query.costCenterId
461
475
  });
462
- if (scoped) {
463
- if (scoped.length === 0) return { data: [], total: 0 };
464
- qb = qb.in("invoice_id", scoped);
465
- }
466
- if (query.contactId) qb = qb.eq("counterparty_person_id", query.contactId);
467
- if (query.fiscalNumber) qb = qb.ilike("number", `%${query.fiscalNumber}%`);
468
- if (query.bankAccountId) qb = qb.contains("payment_account_ids", [query.bankAccountId]);
469
- const unidades = query.unitId ? ["unit_id.is.null", `unit_id.eq.${query.unitId}`] : [];
470
- const buscas = query.search ? ["description", "notes", "number", "counterparty_name"].map((col) => `${col}.ilike.%${query.search}%`) : [];
471
- const desde = query.dateRange?.from.slice(0, 10);
472
- const vencidas = desde && query.includeOverdue ? [`due_date.gte.${desde}`, `and(due_date.lt.${desde},status.in.(overdue,partial))`] : [];
473
- const grupoOr = invoiceLineOrFilter([unidades, buscas, vencidas]);
474
- if (grupoOr) qb = qb.or(grupoOr);
475
- if (query.dateRange) {
476
- if (!vencidas.length) qb = qb.gte("due_date", desde);
477
- qb = qb.lte("due_date", query.dateRange.to.slice(0, 10));
478
- }
476
+ if (scoped && scoped.length === 0) return { data: [], total: 0, totals: [], nextDueDate: null };
477
+ const filtrar = (qb2) => {
478
+ if (query.direction) qb2 = qb2.eq("direction", toLedgerDirection(query.direction));
479
+ if (query.status) {
480
+ const statuses = Array.isArray(query.status) ? query.status : [query.status];
481
+ qb2 = qb2.in("status", statuses.map((st) => st === "open" ? "pending" : st));
482
+ } else {
483
+ qb2 = qb2.neq("status", "cancelled");
484
+ }
485
+ if (scoped) qb2 = qb2.in("invoice_id", scoped);
486
+ if (query.contactId) qb2 = qb2.eq("counterparty_person_id", query.contactId);
487
+ if (query.fiscalNumber) qb2 = qb2.ilike("number", `%${query.fiscalNumber}%`);
488
+ if (query.bankAccountId) qb2 = qb2.contains("payment_account_ids", [query.bankAccountId]);
489
+ const unidades = query.unitId ? ["unit_id.is.null", `unit_id.eq.${query.unitId}`] : [];
490
+ const buscas = query.search ? ["description", "notes", "number", "counterparty_name"].map((col) => `${col}.ilike.%${query.search}%`) : [];
491
+ const desde = query.dateRange?.from.slice(0, 10);
492
+ const vencidas = desde && query.includeOverdue ? [`due_date.gte.${desde}`, `and(due_date.lt.${desde},status.in.(overdue,partial))`] : [];
493
+ const grupoOr = invoiceLineOrFilter([unidades, buscas, vencidas]);
494
+ if (grupoOr) qb2 = qb2.or(grupoOr);
495
+ if (query.dateRange) {
496
+ if (!vencidas.length) qb2 = qb2.gte("due_date", desde);
497
+ qb2 = qb2.lte("due_date", query.dateRange.to.slice(0, 10));
498
+ }
499
+ return qb2;
500
+ };
501
+ let qb = filtrar(pub.from("v_financial_invoice_lines_due").select(COLUNAS, { count: "exact" }));
479
502
  const page = query.page ?? 1;
480
503
  const pageSize = query.pageSize ?? 50;
481
- qb = qb.range((page - 1) * pageSize, page * pageSize - 1);
504
+ qb = qb.range((page - 1) * pageSize, page * pageSize);
482
505
  qb = query.sort === "recent" ? qb.order("created_at", { ascending: false }).order("due_date", { ascending: true }) : qb.order("due_date", { ascending: true });
483
506
  const { data, count, error } = await qb;
484
507
  if (error) throw error;
485
- const linhas = (data ?? []).map(rowToInvoiceLine);
508
+ const rows = data ?? [];
509
+ const nextDueDate = rows.length > pageSize ? rows[pageSize].due_date ?? null : null;
510
+ const linhas = rows.slice(0, pageSize).map(rowToInvoiceLine);
511
+ const totals = query.withTotals ? await sumInvoiceLines(() => filtrar(
512
+ pub.from("v_financial_invoice_lines_due").select("amount,paid,status,invoice:plg_financial_invoices(currency)")
513
+ )) : void 0;
486
514
  const titulos = [...new Set(linhas.map((l) => l.invoiceId).filter(Boolean))];
487
515
  if (titulos.length) {
488
516
  const { data: itemRows } = await pub.from("v_financial_invoice_lines").select("invoice_id,name,description,quantity").in("invoice_id", titulos);
@@ -522,7 +550,7 @@ function createSupabaseFinancialProvider() {
522
550
  }
523
551
  }
524
552
  await attachCurrency(pub, linhas);
525
- return { data: linhas, total: count ?? 0 };
553
+ return { data: linhas, total: count ?? 0, totals, nextDueDate };
526
554
  },
527
555
  async getInvoiceById(id) {
528
556
  const { pub } = getClients();
@@ -2823,5 +2851,5 @@ function createSupabaseFinancialProvider() {
2823
2851
  }
2824
2852
 
2825
2853
  export { createSupabaseFinancialProvider, invoiceLineOrFilter };
2826
- //# sourceMappingURL=chunk-5OIB54V6.js.map
2827
- //# sourceMappingURL=chunk-5OIB54V6.js.map
2854
+ //# sourceMappingURL=chunk-AYMB572M.js.map
2855
+ //# sourceMappingURL=chunk-AYMB572M.js.map