@fayz-ai/financial 0.3.2 → 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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/data/reconcile.ts"],"names":["paymentId"],"mappings":";;;;AAqBA,eAAe,MAAA,CAAO,UAAoC,SAAA,EAA+C;AACvG,EAAA,MAAM,EAAE,MAAK,GAAI,MAAM,SAAS,YAAA,CAAa,EAAE,WAAW,CAAA;AAC1D,EAAA,MAAM,OAAO,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,iBAAiB,MAAM,CAAA;AACvD,EAAA,IAAI,CAAC,IAAA,EAAM,MAAM,IAAI,MAAM,gCAAgC,CAAA;AAC3D,EAAA,OAAO,IAAA;AACT;AAOA,eAAe,WAAA,CAAY,UAAoC,OAAA,EAA6C;AAC1G,EAAA,IAAI,OAAA,CAAQ,YAAA,KAAiB,SAAA,EAAW,OAAO,OAAA,CAAQ,EAAA;AACvD,EAAA,MAAM,YAAY,OAAA,CAAQ,SAAA;AAC1B,EAAA,IAAI,CAAC,SAAA,EAAW,MAAM,IAAI,MAAM,gDAA6C,CAAA;AAC7E,EAAA,MAAM,EAAE,MAAK,GAAI,MAAM,SAAS,YAAA,CAAa,EAAE,WAAW,CAAA;AAC1D,EAAA,MAAM,WAAW,IAAA,CAAK,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,iBAAiB,SAAS,CAAA;AAChE,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,QAAA,CAAS,MAAA,GAAS,CAAC,CAAA;AACzC,EAAA,IAAI,CAAC,IAAA,EAAM,MAAM,IAAI,MAAM,2DAAwD,CAAA;AACnF,EAAA,OAAO,IAAA,CAAK,EAAA;AACd;AAGA,eAAsB,kBAAA,CACpB,QAAA,EACA,IAAA,EACA,KAAA,EACgC;AAChC,EAAA,MAAM,UAAU,MAAM,QAAA,CAAS,cAAc,gBAAA,CA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,QAAA,EAAU,IAAI,CAAA;AAC/C,IAAA,MAAM,QAAA,CAAS,kBAAkB,EAAE,cAAA,EAAgB,KAAK,EAAA,EAAI,iBAAA,EAAmB,QAAQ,CAAA;AACvF,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,WAAA;AAAA,IAC7B,aAAa,IAAA,EAAM,MAAA,CAAO,YAAY,MAAA,CAAO,UAAA,EAAY,QAAQ,OAAO;AAAA,GAC1E;AACA,EAAA,MAAM,SAAA,GAAY,MAAM,WAAA,CAAY,QAAA,EAAU,OAAO,CAAA;AACrD,EAAA,MAAM,QAAA,CAAS,kBAAkB,EAAE,cAAA,EAAgB,KAAK,EAAA,EAAI,iBAAA,EAAmB,WAAW,CAAA;AAE1F,EAAA,KAAA,MAAW,OAAO,WAAA,EAAa;AAC7B,IAAA,MAAM,UAAU,MAAM,QAAA,CAAS,cAAc,iBAAA,CAAkB,IAAA,EAAM,GAAG,CAAC,CAAA;AACzE,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,QAAA,EAAU,QAAQ,EAAE,CAAA;AAC9C,IAAA,MAAM,QAAA,CAAS,WAAA;AAAA,MACb,YAAA,CAAa,IAAA,EAAM,IAAA,CAAK,EAAA,EAAI,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA,EAAG,OAAA,CAAQ,OAAA,EAAS,qBAAA,CAAsB,GAAG,CAAC;AAAA,KAC7F;AAAA,EACF;AACF","file":"chunk-IVIMTPAV.js","sourcesContent":["import type { CreateInvoiceInput, InstallmentChargeInput } from '../domain/invoice'\nimport { round2 } from '../domain/money'\nimport type { FinancialMovement, MovementQuery, PayMovementInput } from '../domain/movement'\nimport {\n adjustmentInvoice, buildBillInvoice, buildPayment, adjustmentDescription,\n type ReconcileAdjustment, type ReconcileAsBillInput, type ReconcileLine, type ReconcilePaymentInput,\n} from '../domain/reconciliation'\n\n/**\n * The provider primitives reconciling runs on. Both adapters lend theirs, so the workflow is written\n * once; `reconcileMovement` here is the raw mark, never the public method, which would re-enter.\n */\nexport interface ReconcileCapableProvider {\n createInvoice(input: CreateInvoiceInput): Promise<{ id: string }>\n getMovements(query: MovementQuery): Promise<{ data: FinancialMovement[] }>\n payMovement(input: PayMovementInput): Promise<FinancialMovement>\n reconcileMovement(input: { bankMovementId: string; matchedMovementId?: string }): Promise<void>\n /** When present, interest/fine/discount become a line of the bill being settled (V1). */\n addInstallmentCharge?(input: InstallmentChargeInput): Promise<void>\n}\n\nasync function billOf(provider: ReconcileCapableProvider, invoiceId: string): Promise<FinancialMovement> {\n const { data } = await provider.getMovements({ invoiceId })\n const bill = data.find((m) => m.movementKind === 'bill')\n if (!bill) throw new Error('A conta foi criada sem parcela')\n return bill\n}\n\n/**\n * The payment's id, not what `payMovement` returned. The Supabase adapter returns the settled\n * installment, and the line's `matched_movement_id` references movements: tying it to the\n * installment id is refused by the foreign key, leaving the bill paid and the line pending.\n */\nasync function paymentIdOf(provider: ReconcileCapableProvider, settled: FinancialMovement): Promise<string> {\n if (settled.movementKind === 'payment') return settled.id\n const invoiceId = settled.invoiceId\n if (!invoiceId) throw new Error('A parcela quitada não aponta para uma conta')\n const { data } = await provider.getMovements({ invoiceId })\n const payments = data.filter((m) => m.movementKind === 'payment')\n const last = payments[payments.length - 1]\n if (!last) throw new Error('A conta foi quitada mas o pagamento não foi encontrado')\n return last.id\n}\n\n/** \"Post as bill\": the bill is born classified, paid, and proven by the line. */\nexport async function runReconcileAsBill(\n provider: ReconcileCapableProvider,\n line: ReconcileLine,\n input: ReconcileAsBillInput,\n): Promise<{ invoiceId: string }> {\n const invoice = await provider.createInvoice(buildBillInvoice(line, input))\n const bill = await billOf(provider, invoice.id)\n const settled = await provider.payMovement({\n ...buildPayment(line, bill.id, round2(line.amount), input.payment),\n metadata: input.receiptUrl ? { receiptUrl: input.receiptUrl } : undefined,\n })\n const paymentId = await paymentIdOf(provider, settled)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n return { invoiceId: invoice.id }\n}\n\n/** \"Link\": an open bill is settled by the line; a paid one is only tied, never paid again. */\nexport async function runReconcileLink(\n provider: ReconcileCapableProvider,\n line: ReconcileLine,\n target: { movementId: string; mode: 'settle' | 'link_only'; openAmount: number },\n options: { payment?: ReconcilePaymentInput; adjustments?: ReconcileAdjustment[]; partial?: boolean } = {},\n): Promise<void> {\n if (target.mode === 'link_only') {\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: target.movementId })\n return\n }\n\n // Paid in parts: this line pays what it carries and the bill keeps the rest\n // open, so the next transfer reconciles against the same bill.\n if (options.partial) {\n const amount = round2(line.amount)\n if (amount <= 0 || amount >= round2(target.openAmount)) {\n throw new Error('Pagamento parcial só quando a linha é menor que o saldo em aberto')\n }\n const paga = await provider.payMovement(buildPayment(line, target.movementId, amount, options.payment))\n const paymentId = await paymentIdOf(provider, paga)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n return\n }\n\n // Interest, fine and discount go onto the bill itself, as in V1: the line is\n // added, the installment becomes what the bank charged, and one payment\n // settles it all. The stand-alone adjustment bill is only for a provider\n // that cannot amend.\n const adjustments = (options.adjustments ?? []).filter((adj) => round2(adj.amount) > 0)\n if (provider.addInstallmentCharge && adjustments.length) {\n let due = target.openAmount\n for (const adj of adjustments) {\n await provider.addInstallmentCharge({\n installmentId: target.movementId,\n kind: adj.type,\n amount: round2(adj.amount),\n accountId: adj.accountId,\n description: adjustmentDescription(adj),\n })\n due += adj.type === 'discount' ? -round2(adj.amount) : round2(adj.amount)\n }\n const paid = await provider.payMovement(buildPayment(line, target.movementId, round2(due), options.payment))\n const paidId = await paymentIdOf(provider, paid)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paidId })\n return\n }\n\n const settled = await provider.payMovement(\n buildPayment(line, target.movementId, target.openAmount, options.payment),\n )\n const paymentId = await paymentIdOf(provider, settled)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n\n for (const adj of adjustments) {\n const invoice = await provider.createInvoice(adjustmentInvoice(line, adj))\n const bill = await billOf(provider, invoice.id)\n await provider.payMovement(\n buildPayment(line, bill.id, round2(adj.amount), options.payment, adjustmentDescription(adj)),\n )\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/data/reconcile.ts"],"names":["paymentId"],"mappings":";;;;AAqBA,eAAe,MAAA,CAAO,UAAoC,SAAA,EAA+C;AACvG,EAAA,MAAM,EAAE,MAAK,GAAI,MAAM,SAAS,YAAA,CAAa,EAAE,WAAW,CAAA;AAC1D,EAAA,MAAM,OAAO,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,iBAAiB,MAAM,CAAA;AACvD,EAAA,IAAI,CAAC,IAAA,EAAM,MAAM,IAAI,MAAM,gCAAgC,CAAA;AAC3D,EAAA,OAAO,IAAA;AACT;AAOA,eAAe,WAAA,CAAY,UAAoC,OAAA,EAA6C;AAC1G,EAAA,IAAI,OAAA,CAAQ,YAAA,KAAiB,SAAA,EAAW,OAAO,OAAA,CAAQ,EAAA;AACvD,EAAA,MAAM,YAAY,OAAA,CAAQ,SAAA;AAC1B,EAAA,IAAI,CAAC,SAAA,EAAW,MAAM,IAAI,MAAM,gDAA6C,CAAA;AAC7E,EAAA,MAAM,EAAE,MAAK,GAAI,MAAM,SAAS,YAAA,CAAa,EAAE,WAAW,CAAA;AAC1D,EAAA,MAAM,WAAW,IAAA,CAAK,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,iBAAiB,SAAS,CAAA;AAChE,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,QAAA,CAAS,MAAA,GAAS,CAAC,CAAA;AACzC,EAAA,IAAI,CAAC,IAAA,EAAM,MAAM,IAAI,MAAM,2DAAwD,CAAA;AACnF,EAAA,OAAO,IAAA,CAAK,EAAA;AACd;AAGA,eAAsB,kBAAA,CACpB,QAAA,EACA,IAAA,EACA,KAAA,EACgC;AAChC,EAAA,MAAM,UAA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,MAAM,MAAA,GAAS,MAAM,WAAA,CAAY,QAAA,EAAU,IAAI,CAAA;AAC/C,IAAA,MAAM,QAAA,CAAS,kBAAkB,EAAE,cAAA,EAAgB,KAAK,EAAA,EAAI,iBAAA,EAAmB,QAAQ,CAAA;AACvF,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,WAAA;AAAA,IAC7B,aAAa,IAAA,EAAM,MAAA,CAAO,YAAY,MAAA,CAAO,UAAA,EAAY,QAAQ,OAAO;AAAA,GAC1E;AACA,EAAA,MAAM,SAAA,GAAY,MAAM,WAAA,CAAY,QAAA,EAAU,OAAO,CAAA;AACrD,EAAA,MAAM,QAAA,CAAS,kBAAkB,EAAE,cAAA,EAAgB,KAAK,EAAA,EAAI,iBAAA,EAAmB,WAAW,CAAA;AAE1F,EAAA,KAAA,MAAW,OAAO,WAAA,EAAa;AAC7B,IAAA,MAAM,UAAU,MAAM,QAAA,CAAS,cAAc,iBAAA,CAAkB,IAAA,EAAM,GAAG,CAAC,CAAA;AACzE,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,QAAA,EAAU,QAAQ,EAAE,CAAA;AAC9C,IAAA,MAAM,QAAA,CAAS,WAAA;AAAA,MACb,YAAA,CAAa,IAAA,EAAM,IAAA,CAAK,EAAA,EAAI,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA,EAAG,OAAA,CAAQ,OAAA,EAAS,qBAAA,CAAsB,GAAG,CAAC;AAAA,KAC7F;AAAA,EACF;AACF","file":"chunk-NONT5MVW.js","sourcesContent":["import type { CreateInvoiceInput, InstallmentChargeInput } from '../domain/invoice'\nimport { round2 } from '../domain/money'\nimport type { FinancialMovement, MovementQuery, PayMovementInput } from '../domain/movement'\nimport {\n adjustmentInvoice, buildBillInvoice, buildPayment, adjustmentDescription,\n type ReconcileAdjustment, type ReconcileAsBillInput, type ReconcileLine, type ReconcilePaymentInput,\n} from '../domain/reconciliation'\n\n/**\n * The provider primitives reconciling runs on. Both adapters lend theirs, so the workflow is written\n * once; `reconcileMovement` here is the raw mark, never the public method, which would re-enter.\n */\nexport interface ReconcileCapableProvider {\n createInvoice(input: CreateInvoiceInput): Promise<{ id: string }>\n getMovements(query: MovementQuery): Promise<{ data: FinancialMovement[] }>\n payMovement(input: PayMovementInput): Promise<FinancialMovement>\n reconcileMovement(input: { bankMovementId: string; matchedMovementId?: string }): Promise<void>\n /** When present, interest/fine/discount become a line of the bill being settled (V1). */\n addInstallmentCharge?(input: InstallmentChargeInput): Promise<void>\n}\n\nasync function billOf(provider: ReconcileCapableProvider, invoiceId: string): Promise<FinancialMovement> {\n const { data } = await provider.getMovements({ invoiceId })\n const bill = data.find((m) => m.movementKind === 'bill')\n if (!bill) throw new Error('A conta foi criada sem parcela')\n return bill\n}\n\n/**\n * The payment's id, not what `payMovement` returned. The Supabase adapter returns the settled\n * installment, and the line's `matched_movement_id` references movements: tying it to the\n * installment id is refused by the foreign key, leaving the bill paid and the line pending.\n */\nasync function paymentIdOf(provider: ReconcileCapableProvider, settled: FinancialMovement): Promise<string> {\n if (settled.movementKind === 'payment') return settled.id\n const invoiceId = settled.invoiceId\n if (!invoiceId) throw new Error('A parcela quitada não aponta para uma conta')\n const { data } = await provider.getMovements({ invoiceId })\n const payments = data.filter((m) => m.movementKind === 'payment')\n const last = payments[payments.length - 1]\n if (!last) throw new Error('A conta foi quitada mas o pagamento não foi encontrado')\n return last.id\n}\n\n/** \"Post as bill\": the bill is born classified, paid, and proven by the line. */\nexport async function runReconcileAsBill(\n provider: ReconcileCapableProvider,\n line: ReconcileLine,\n input: ReconcileAsBillInput,\n): Promise<{ invoiceId: string }> {\n const invoice = await provider.createInvoice(buildBillInvoice(line, input))\n const bill = await billOf(provider, invoice.id)\n const settled = await provider.payMovement({\n ...buildPayment(line, bill.id, round2(line.amount), input.payment),\n metadata: input.receiptUrl ? { receiptUrl: input.receiptUrl } : undefined,\n })\n const paymentId = await paymentIdOf(provider, settled)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n return { invoiceId: invoice.id }\n}\n\n/** \"Link\": an open bill is settled by the line; a paid one is only tied, never paid again. */\nexport async function runReconcileLink(\n provider: ReconcileCapableProvider,\n line: ReconcileLine,\n target: { movementId: string; mode: 'settle' | 'link_only'; openAmount: number },\n options: { payment?: ReconcilePaymentInput; adjustments?: ReconcileAdjustment[]; partial?: boolean } = {},\n): Promise<void> {\n if (target.mode === 'link_only') {\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: target.movementId })\n return\n }\n\n // Paid in parts: this line pays what it carries and the bill keeps the rest\n // open, so the next transfer reconciles against the same bill.\n if (options.partial) {\n const amount = round2(line.amount)\n if (amount <= 0 || amount >= round2(target.openAmount)) {\n throw new Error('Pagamento parcial só quando a linha é menor que o saldo em aberto')\n }\n const paga = await provider.payMovement(buildPayment(line, target.movementId, amount, options.payment))\n const paymentId = await paymentIdOf(provider, paga)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n return\n }\n\n // Interest, fine and discount go onto the bill itself, as in V1: the line is\n // added, the installment becomes what the bank charged, and one payment\n // settles it all. The stand-alone adjustment bill is only for a provider\n // that cannot amend.\n const adjustments = (options.adjustments ?? []).filter((adj) => round2(adj.amount) > 0)\n if (provider.addInstallmentCharge && adjustments.length) {\n let due = target.openAmount\n for (const adj of adjustments) {\n await provider.addInstallmentCharge({\n installmentId: target.movementId,\n kind: adj.type,\n amount: round2(adj.amount),\n accountId: adj.accountId,\n description: adjustmentDescription(adj),\n })\n due += adj.type === 'discount' ? -round2(adj.amount) : round2(adj.amount)\n }\n const paid = await provider.payMovement(buildPayment(line, target.movementId, round2(due), options.payment))\n const paidId = await paymentIdOf(provider, paid)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paidId })\n return\n }\n\n const settled = await provider.payMovement(\n buildPayment(line, target.movementId, target.openAmount, options.payment),\n )\n const paymentId = await paymentIdOf(provider, settled)\n await provider.reconcileMovement({ bankMovementId: line.id, matchedMovementId: paymentId })\n\n for (const adj of adjustments) {\n const invoice = await provider.createInvoice(adjustmentInvoice(line, adj))\n const bill = await billOf(provider, invoice.id)\n await provider.payMovement(\n buildPayment(line, bill.id, round2(adj.amount), options.payment, adjustmentDescription(adj)),\n )\n }\n}\n"]}
@@ -8,8 +8,8 @@ import { transferLegs } from './chunk-YUNLQYOZ.js';
8
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-IVIMTPAV.js';
12
- import { transferForStatementLine, statementLegOf, candidateTolerance, candidateScore, statementLinesPage, pageTotals } from './chunk-NAEXIF3W.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';
@@ -2470,6 +2470,54 @@ function createSupabaseFinancialProvider() {
2470
2470
  lastSyncError: r.last_sync_error
2471
2471
  })));
2472
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
+ },
2473
2521
  async suggestReconciliationBatch(lines) {
2474
2522
  const { core, pub } = getClients();
2475
2523
  const abertas = lines.filter((line) => !line.reconciledAt && (Number(line.amount) || 0) > 0);
@@ -2875,5 +2923,5 @@ function createSupabaseFinancialProvider() {
2875
2923
  }
2876
2924
 
2877
2925
  export { createSupabaseFinancialProvider, invoiceLineOrFilter };
2878
- //# sourceMappingURL=chunk-5FESQBPQ.js.map
2879
- //# sourceMappingURL=chunk-5FESQBPQ.js.map
2926
+ //# sourceMappingURL=chunk-Y6XGQLEV.js.map
2927
+ //# sourceMappingURL=chunk-Y6XGQLEV.js.map