@fayz-ai/plugin-financial 0.29.10 → 0.30.1

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.
package/dist/index.js CHANGED
@@ -3,17 +3,17 @@ export { FINANCIAL_INVOICE_ZONES } from './chunk-W7T7RTC4.js';
3
3
  import './chunk-XGBGRXZ3.js';
4
4
  import './chunk-7VKJLBYY.js';
5
5
  import { FINANCIAL_MODULE_DEFAULTS } from './chunk-POYZFEAN.js';
6
- import { FinancialContextProvider, useFinancialProvider, formatCurrency, useFinancialConfig, useFinancialStore } from './chunk-CNXAVGSW.js';
6
+ import { FinancialContextProvider, useFinancialProvider, formatCurrency as formatCurrency$1, useFinancialConfig, useFinancialStore } from './chunk-CNXAVGSW.js';
7
7
  import * as React3 from 'react';
8
8
  import React3__default, { useEffect } from 'react';
9
- import { CircleDollarSign, FileText, Wallet, ArrowUpRight, ArrowDownRight, AlertTriangle, EyeOff, Eye, CreditCard } from 'lucide-react';
10
- import { registerTranslations, tl, recordRailFields, RECORD_GROUP, activeFacet, lazyComponent, createConnectionStore, connectionSettings, connectionStatus, settingsStatus, connectionRuns, useTranslation, resolveDataProvider, emitDataChanged, registerMessageDefaults, countByTenant, onAppPathChange, resolveCurrency } from '@fayz-ai/core';
11
- import { Button, Badge, Input, ModalTask, SegmentedControl, TreeManager, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, SearchSelect, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, Modal, ModalContent, ModalHeader, ModalTitle, ModalDescription, ModalBody, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget, useDashboardNavigate, GoldCard } from '@fayz-ai/ui';
9
+ import { Landmark, Loader2, CheckCircle2, Unplug, ExternalLink, CircleDollarSign, FileText, Wallet, ArrowUpRight, ArrowDownRight, AlertTriangle, EyeOff, Eye, CreditCard } from 'lucide-react';
10
+ import { registerTranslations, tl, recordRailFields, RECORD_GROUP, activeFacet, lazyComponent, createConnectionStore, connectionSettings, connectionStatus, settingsStatus, connectionRuns, useTranslation, formatCurrency, formatDate, formatDateTime, resolveDataProvider, getSupabaseClientOptional, getActiveTenantId, getActiveUnitId, emitDataChanged, registerMessageDefaults, countByTenant, onAppPathChange, resolveCurrency } from '@fayz-ai/core';
11
+ import { Card, CardHeader, CardTitle, CardDescription, CardContent, Button, Input, ConfirmDialog, Badge, ModalTask, toast, SegmentedControl, TreeManager, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, SearchSelect, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, Modal, ModalContent, ModalHeader, ModalTitle, ModalDescription, ModalBody, KpiCard, ChartWidget, TableWidget, useDashboardNavigate, GoldCard } from '@fayz-ai/ui';
12
12
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
13
13
  import { createSafeFinancialProvider, createFinancialStore } from '@fayz-ai/financial/store';
14
14
  export { createSafeFinancialProvider } from '@fayz-ai/financial/store';
15
15
  import { FINANCIAL_ZONES } from '@fayz-ai/financial/views/zones';
16
- import { draftAllProductsForPriceTable, addAllProductsToPriceTable, fayzConnectorOAuth, defineSettingsTab, RightRailPage, useConnectors, useConnectorsPanelAvailable, SettingsForm, ConnectorMark, StateChip, ConnectorDetail, usePermissionOptional, openConnectorsPanel, createCrudPage, PluginSettingsPanel, useTenantPluginSettings } from '@fayz-ai/admin';
16
+ import { draftAllProductsForPriceTable, addAllProductsToPriceTable, fayzConnectorOAuth, defineSettingsTab, RightRailPage, usePermissionOptional, useConnectors, useConnectorsPanelAvailable, SettingsForm, ConnectorMark, StateChip, ConnectorDetail, openConnectorsPanel, serviceBaseUrl, createCrudPage, PluginSettingsPanel, useTenantPluginSettings } from '@fayz-ai/admin';
17
17
  import { invoiceOpensForEditing } from '@fayz-ai/financial/domain/invoice';
18
18
  import { T } from '@fayz-ai/financial/data/tables';
19
19
  import { buildChartTree, isGroupNode, compareCodes, suggestNextCode, accountLabel, descendantIds, childIds } from '@fayz-ai/financial/domain/chart-of-accounts';
@@ -133,23 +133,23 @@ function TotalBalanceKpi() {
133
133
  const summary = useFinancialStore((s) => s.summary);
134
134
  const loading = useFinancialStore((s) => s.summaryLoading);
135
135
  useEnsureSummary();
136
- const left = (summary?.excluded ?? []).map((x) => formatCurrency(x.balance || x.receivable - x.payable || x.inflow - x.outflow, resolveCurrency(currency, x.currency))).join(" \xB7 ");
136
+ const left = (summary?.excluded ?? []).map((x) => formatCurrency$1(x.balance || x.receivable - x.payable || x.inflow - x.outflow, resolveCurrency(currency, x.currency))).join(" \xB7 ");
137
137
  const sub = left ? `Fora do total, sem c\xE2mbio dispon\xEDvel: ${left}` : t("financial.summary.allAccounts");
138
- return /* @__PURE__ */ jsx(KpiCard, { label: t("financial.summary.totalBalance"), icon: "Wallet", value: formatCurrency(summary?.totalBalance ?? 0, currency), sub: loading ? void 0 : sub });
138
+ return /* @__PURE__ */ jsx(KpiCard, { label: t("financial.summary.totalBalance"), icon: "Wallet", value: formatCurrency$1(summary?.totalBalance ?? 0, currency), sub: loading ? void 0 : sub });
139
139
  }
140
140
  function ReceivableKpi() {
141
141
  const t = useTranslation();
142
142
  const { currency } = useFinancialConfig();
143
143
  const summary = useFinancialStore((s) => s.summary);
144
144
  useEnsureSummary();
145
- return /* @__PURE__ */ jsx(KpiCard, { label: t("financial.summary.receivable"), icon: "TrendingUp", value: formatCurrency(summary?.totalReceivable ?? 0, currency), sub: t("financial.summary.overdue", { count: String(summary?.overdueReceivableCount ?? 0) }) });
145
+ return /* @__PURE__ */ jsx(KpiCard, { label: t("financial.summary.receivable"), icon: "TrendingUp", value: formatCurrency$1(summary?.totalReceivable ?? 0, currency), sub: t("financial.summary.overdue", { count: String(summary?.overdueReceivableCount ?? 0) }) });
146
146
  }
147
147
  function PayableKpi() {
148
148
  const t = useTranslation();
149
149
  const { currency } = useFinancialConfig();
150
150
  const summary = useFinancialStore((s) => s.summary);
151
151
  useEnsureSummary();
152
- return /* @__PURE__ */ jsx(KpiCard, { label: t("financial.summary.payable"), icon: "TrendingDown", value: formatCurrency(summary?.totalPayable ?? 0, currency), sub: t("financial.summary.overdue", { count: String(summary?.overduePayableCount ?? 0) }) });
152
+ return /* @__PURE__ */ jsx(KpiCard, { label: t("financial.summary.payable"), icon: "TrendingDown", value: formatCurrency$1(summary?.totalPayable ?? 0, currency), sub: t("financial.summary.overdue", { count: String(summary?.overduePayableCount ?? 0) }) });
153
153
  }
154
154
  function MonthlyFlowKpi() {
155
155
  const t = useTranslation();
@@ -158,7 +158,7 @@ function MonthlyFlowKpi() {
158
158
  useEnsureSummary();
159
159
  const inflow = summary?.monthlyInflow ?? 0;
160
160
  const outflow = summary?.monthlyOutflow ?? 0;
161
- return /* @__PURE__ */ jsx(KpiCard, { label: t("financial.summary.monthlyFlow"), icon: "BarChart3", value: formatCurrency(inflow - outflow, currency), sub: inflow >= outflow ? t("financial.summary.positiveBalance") : t("financial.summary.negativeBalance") });
161
+ return /* @__PURE__ */ jsx(KpiCard, { label: t("financial.summary.monthlyFlow"), icon: "BarChart3", value: formatCurrency$1(inflow - outflow, currency), sub: inflow >= outflow ? t("financial.summary.positiveBalance") : t("financial.summary.negativeBalance") });
162
162
  }
163
163
  function CashFlowChart() {
164
164
  const t = useTranslation();
@@ -197,7 +197,7 @@ function CashFlowBreakdown() {
197
197
  /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full bg-success" }),
198
198
  t("financial.summary.received")
199
199
  ] }),
200
- /* @__PURE__ */ jsx("span", { className: "font-medium", children: formatCurrency(inflow, currency) })
200
+ /* @__PURE__ */ jsx("span", { className: "font-medium", children: formatCurrency$1(inflow, currency) })
201
201
  ] }),
202
202
  /* @__PURE__ */ jsx("div", { className: "h-2 overflow-hidden rounded-full bg-muted", children: /* @__PURE__ */ jsx("div", { className: "h-full rounded-full bg-success", style: { width: `${inflow / total * 100}%` } }) })
203
203
  ] }),
@@ -207,13 +207,13 @@ function CashFlowBreakdown() {
207
207
  /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full bg-destructive" }),
208
208
  t("financial.summary.paid")
209
209
  ] }),
210
- /* @__PURE__ */ jsx("span", { className: "font-medium", children: formatCurrency(outflow, currency) })
210
+ /* @__PURE__ */ jsx("span", { className: "font-medium", children: formatCurrency$1(outflow, currency) })
211
211
  ] }),
212
212
  /* @__PURE__ */ jsx("div", { className: "h-2 overflow-hidden rounded-full bg-muted", children: /* @__PURE__ */ jsx("div", { className: "h-full rounded-full bg-destructive", style: { width: `${outflow / total * 100}%` } }) })
213
213
  ] }),
214
214
  /* @__PURE__ */ jsx("div", { className: "border-t pt-2", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs", children: [
215
215
  /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("financial.summary.net") }),
216
- /* @__PURE__ */ jsx("span", { className: `font-semibold ${inflow - outflow >= 0 ? "text-success" : "text-destructive"}`, children: formatCurrency(inflow - outflow, currency) })
216
+ /* @__PURE__ */ jsx("span", { className: `font-semibold ${inflow - outflow >= 0 ? "text-success" : "text-destructive"}`, children: formatCurrency$1(inflow - outflow, currency) })
217
217
  ] }) })
218
218
  ] })
219
219
  ] });
@@ -238,7 +238,7 @@ function OverdueAlerts() {
238
238
  /* @__PURE__ */ jsx(item.Icon, { className: `h-3.5 w-3.5 ${item.color}` }),
239
239
  /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: item.label })
240
240
  ] }),
241
- /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: formatCurrency(item.value, currency) })
241
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: formatCurrency$1(item.value, currency) })
242
242
  ] }, item.label)),
243
243
  items.every((i) => i.count === 0) ? /* @__PURE__ */ jsx("p", { className: "border-t pt-3 text-xs text-muted-foreground", children: t("financial.summary.noOverdue") }) : null
244
244
  ] })
@@ -267,7 +267,7 @@ function RecentTransactions() {
267
267
  ] }) },
268
268
  { accessorKey: "totalAmount", header: "", cell: ({ row }) => /* @__PURE__ */ jsxs("span", { className: `font-semibold ${row.original.direction === "credit" ? "text-success" : "text-destructive"}`, children: [
269
269
  row.original.direction === "credit" ? "+" : "-",
270
- formatCurrency(row.original.totalAmount, currency)
270
+ formatCurrency$1(row.original.totalAmount, currency)
271
271
  ] }) }
272
272
  ];
273
273
  return /* @__PURE__ */ jsx(TableWidget, { title: t("financial.summary.recentTransactions"), icon: "CircleDollarSign", columns, data: invoices, emptyMessage: t("financial.summary.noTransactions") });
@@ -292,7 +292,7 @@ function BalanceHero() {
292
292
  const navigate = useDashboardNavigate();
293
293
  useEnsureSummary();
294
294
  const [hidden, setHidden] = React3__default.useState(false);
295
- const money = (v) => hidden ? "\u2022\u2022\u2022\u2022\u2022\u2022" : formatCurrency(v ?? 0, currency);
295
+ const money = (v) => hidden ? "\u2022\u2022\u2022\u2022\u2022\u2022" : formatCurrency$1(v ?? 0, currency);
296
296
  const inflow = summary?.monthlyInflow ?? 0;
297
297
  const outflow = summary?.monthlyOutflow ?? 0;
298
298
  return /* @__PURE__ */ jsxs(GoldCard, { branded: true, className: "px-5 py-4 text-center md:px-8 md:py-5", children: [
@@ -434,7 +434,7 @@ function UpcomingBills() {
434
434
  /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium text-foreground", children: bill.notes ?? t("financial.home.bill") }),
435
435
  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: dueLabel(bill.dueDate) })
436
436
  ] }),
437
- /* @__PURE__ */ jsx("span", { className: "shrink-0 text-sm font-semibold tabular-nums text-foreground", children: formatCurrency(bill.amount - bill.paidAmount, currency) })
437
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 text-sm font-semibold tabular-nums text-foreground", children: formatCurrency$1(bill.amount - bill.paidAmount, currency) })
438
438
  ] }, bill.id)) })
439
439
  ] });
440
440
  }
@@ -459,11 +459,11 @@ function CreditCards() {
459
459
  /* @__PURE__ */ jsx(CreditCard, { className: "h-5 w-5 opacity-80" })
460
460
  ] }),
461
461
  /* @__PURE__ */ jsx("p", { className: "mt-6 text-[11px] uppercase tracking-wide opacity-70", children: t("financial.home.currentBill") }),
462
- /* @__PURE__ */ jsx("p", { className: "text-xl font-bold tabular-nums", children: formatCurrency(fatura, currency) }),
462
+ /* @__PURE__ */ jsx("p", { className: "text-xl font-bold tabular-nums", children: formatCurrency$1(fatura, currency) }),
463
463
  /* @__PURE__ */ jsxs("p", { className: "mt-2 text-[11px] opacity-70", children: [
464
464
  t("financial.home.availableLimit"),
465
465
  " ",
466
- formatCurrency(limite, currency)
466
+ formatCurrency$1(limite, currency)
467
467
  ] })
468
468
  ] }, card.id);
469
469
  }),
@@ -1670,7 +1670,71 @@ var en = {
1670
1670
  "financial.chartTree.error.codeRequired": "Enter the account code.",
1671
1671
  "financial.chartTree.error.nameRequired": "Enter the account name.",
1672
1672
  "financial.chartTree.error.codeTaken": 'Code {{code}} is already used by "{{name}}".',
1673
- "financial.chartTree.error.leafWithChildren": "An account with accounts inside it must stay a group."
1673
+ "financial.chartTree.error.leafWithChildren": "An account with accounts inside it must stay a group.",
1674
+ // Open Finance connection panel of a bank account (OpenFinancePanel).
1675
+ "financial.openFinance.title": "Bank statement (Open Finance)",
1676
+ "financial.openFinance.description": "Connect this account to Open Finance so its statement reaches Reconciliation on its own.",
1677
+ "financial.openFinance.loading": "Checking the connection\u2026",
1678
+ "financial.openFinance.refreshing": "Checking with the bank\u2026",
1679
+ "financial.openFinance.state.none": "This account is not connected to Open Finance yet.",
1680
+ "financial.openFinance.state.pending": "Waiting for your authorization at the bank",
1681
+ "financial.openFinance.state.active": "Connected",
1682
+ "financial.openFinance.state.adopted": "Connected (V1)",
1683
+ "financial.openFinance.state.revoked": "The authorization was revoked",
1684
+ "financial.openFinance.state.error": "Could not connect",
1685
+ "financial.openFinance.note.none": "You will authorize the sharing on your bank's website. Nothing is moved: only the statement is read.",
1686
+ "financial.openFinance.note.pending": "Open the authorization, finish it at the bank and come back. The first statement arrives 6 to 24 hours after you authorize.",
1687
+ "financial.openFinance.note.pendingNoLink": "The authorization link is not ready yet. Check again in a moment. The first statement arrives 6 to 24 hours after you authorize.",
1688
+ "financial.openFinance.note.revoked": "The statement stopped arriving. Lines already imported stay here.",
1689
+ "financial.openFinance.since": "Connected since",
1690
+ "financial.openFinance.lastStatement": "Last statement",
1691
+ "financial.openFinance.lastStatementNever": "Not arrived yet",
1692
+ "financial.openFinance.nextStatement": "Next fetch",
1693
+ "financial.openFinance.balance": "Bank balance",
1694
+ "financial.openFinance.balanceAt": "updated {{when}}",
1695
+ "financial.openFinance.missingTitle": "Complete what the bank asks for",
1696
+ "financial.openFinance.missingElsewhere": "Some details must be fixed on the account itself before connecting.",
1697
+ "financial.openFinance.action.connect": "Connect Open Finance",
1698
+ "financial.openFinance.action.openConsent": "Open authorization at the bank",
1699
+ "financial.openFinance.action.confirmAuthorized": "I have authorized",
1700
+ "financial.openFinance.action.fetchStatement": "Fetch statement now",
1701
+ "financial.openFinance.action.renew": "Renew authorization",
1702
+ "financial.openFinance.action.disconnect": "Disconnect",
1703
+ "financial.openFinance.action.reconnect": "Reconnect",
1704
+ "financial.openFinance.action.retry": "Try again",
1705
+ "financial.openFinance.action.cancel": "Cancel",
1706
+ "financial.openFinance.inactiveAccount": "Reactivate the account to manage its connection.",
1707
+ "financial.openFinance.readOnly": "You are not allowed to change this account's connection.",
1708
+ "financial.openFinance.supportCode": "Code for support: {{code}}",
1709
+ "financial.openFinance.fetchRequested": "We asked the bank for the statement. New lines show up in Reconciliation as soon as it answers.",
1710
+ "financial.openFinance.disconnected": "Account disconnected. Lines already imported stay in Reconciliation.",
1711
+ "financial.openFinance.confirm.disconnectTitle": "Disconnect from Open Finance?",
1712
+ "financial.openFinance.confirm.disconnectBody": "This account's statement stops arriving. Lines already imported and reconciliations already made stay as they are.",
1713
+ "financial.openFinance.confirm.renewTitle": "Renew the authorization?",
1714
+ "financial.openFinance.confirm.renewBody": "You will authorize again on the bank's website. Until then fetching this account's statement is paused; nothing already imported is lost.",
1715
+ "financial.openFinance.field.accountDigit": "Account check digit",
1716
+ "financial.openFinance.field.agencyDigit": "Agency check digit",
1717
+ "financial.openFinance.field.holderDocument": "Holder CPF/CNPJ",
1718
+ "financial.openFinance.field.holderName": "Holder name",
1719
+ "financial.openFinance.field.street": "Street",
1720
+ "financial.openFinance.field.number": "Number",
1721
+ "financial.openFinance.field.complement": "Complement",
1722
+ "financial.openFinance.field.district": "District",
1723
+ "financial.openFinance.field.city": "City",
1724
+ "financial.openFinance.field.state": "State",
1725
+ "financial.openFinance.field.postalCode": "Postal code",
1726
+ "financial.openFinance.error.notConfigured": "Open Finance is not available for this account yet. Contact support.",
1727
+ "financial.openFinance.error.providerRefused": "The bank refused this account's registration. Check agency, account and holder on the account and try again.",
1728
+ "financial.openFinance.error.alreadyConnected": "This account is already connected to Open Finance.",
1729
+ "financial.openFinance.error.payerIncomplete": "Fill in the missing details to continue.",
1730
+ "financial.openFinance.error.unsupportedBank": "This bank does not offer its statement through Open Finance yet.",
1731
+ "financial.openFinance.error.rateLimited": "The bank asked for a pause between fetches. Try again shortly.",
1732
+ "financial.openFinance.error.rateLimitedUntil": "The bank asked for a pause between fetches. Try again from {{when}}.",
1733
+ "financial.openFinance.error.unauthorized": "Your session expired. Sign in again to continue.",
1734
+ "financial.openFinance.error.forbidden": "You are not allowed to change this account's connection.",
1735
+ "financial.openFinance.error.unavailable": "Could not reach the service right now. Try again in a moment.",
1736
+ "financial.openFinance.error.statementFailed": "The last statement request failed. Try again; if it keeps failing, renew the authorization.",
1737
+ "financial.openFinance.error.generic": "Something went wrong talking to the bank. Try again in a moment."
1674
1738
  };
1675
1739
 
1676
1740
  // src/locales/pt-BR.ts
@@ -2703,7 +2767,71 @@ var ptBR = {
2703
2767
  "financial.chartTree.error.codeRequired": "Informe o c\xF3digo da conta.",
2704
2768
  "financial.chartTree.error.nameRequired": "Informe o nome da conta.",
2705
2769
  "financial.chartTree.error.codeTaken": 'O c\xF3digo {{code}} j\xE1 \xE9 usado por "{{name}}".',
2706
- "financial.chartTree.error.leafWithChildren": "Uma conta com contas dentro dela precisa continuar como grupo."
2770
+ "financial.chartTree.error.leafWithChildren": "Uma conta com contas dentro dela precisa continuar como grupo.",
2771
+ // Open Finance connection panel of a bank account (OpenFinancePanel).
2772
+ "financial.openFinance.title": "Extrato banc\xE1rio (Open Finance)",
2773
+ "financial.openFinance.description": "Conecte esta conta ao Open Finance para o extrato chegar sozinho na Concilia\xE7\xE3o.",
2774
+ "financial.openFinance.loading": "Consultando a conex\xE3o\u2026",
2775
+ "financial.openFinance.refreshing": "Conferindo com o banco\u2026",
2776
+ "financial.openFinance.state.none": "Esta conta ainda n\xE3o est\xE1 conectada ao Open Finance.",
2777
+ "financial.openFinance.state.pending": "Aguardando sua autoriza\xE7\xE3o no banco",
2778
+ "financial.openFinance.state.active": "Conectada",
2779
+ "financial.openFinance.state.adopted": "Conectada (V1)",
2780
+ "financial.openFinance.state.revoked": "A autoriza\xE7\xE3o foi revogada",
2781
+ "financial.openFinance.state.error": "N\xE3o foi poss\xEDvel conectar",
2782
+ "financial.openFinance.note.none": "Voc\xEA vai autorizar o compartilhamento no site do seu banco. Nada \xE9 movimentado: s\xF3 o extrato \xE9 lido.",
2783
+ "financial.openFinance.note.pending": "Abra a autoriza\xE7\xE3o, conclua no banco e volte aqui. O primeiro extrato chega entre 6 e 24 horas depois da autoriza\xE7\xE3o.",
2784
+ "financial.openFinance.note.pendingNoLink": "O link de autoriza\xE7\xE3o ainda n\xE3o est\xE1 pronto. Confira de novo em instantes. O primeiro extrato chega entre 6 e 24 horas depois da autoriza\xE7\xE3o.",
2785
+ "financial.openFinance.note.revoked": "O extrato parou de chegar. As linhas j\xE1 importadas continuam aqui.",
2786
+ "financial.openFinance.since": "Conectada desde",
2787
+ "financial.openFinance.lastStatement": "\xDAltimo extrato",
2788
+ "financial.openFinance.lastStatementNever": "Ainda n\xE3o chegou",
2789
+ "financial.openFinance.nextStatement": "Pr\xF3xima busca",
2790
+ "financial.openFinance.balance": "Saldo no banco",
2791
+ "financial.openFinance.balanceAt": "atualizado em {{when}}",
2792
+ "financial.openFinance.missingTitle": "Complete os dados que o banco pede",
2793
+ "financial.openFinance.missingElsewhere": "Alguns dados precisam ser corrigidos no cadastro da conta antes de conectar.",
2794
+ "financial.openFinance.action.connect": "Conectar Open Finance",
2795
+ "financial.openFinance.action.openConsent": "Abrir autoriza\xE7\xE3o no banco",
2796
+ "financial.openFinance.action.confirmAuthorized": "J\xE1 autorizei",
2797
+ "financial.openFinance.action.fetchStatement": "Buscar extrato agora",
2798
+ "financial.openFinance.action.renew": "Renovar autoriza\xE7\xE3o",
2799
+ "financial.openFinance.action.disconnect": "Desconectar",
2800
+ "financial.openFinance.action.reconnect": "Reconectar",
2801
+ "financial.openFinance.action.retry": "Tentar novamente",
2802
+ "financial.openFinance.action.cancel": "Cancelar",
2803
+ "financial.openFinance.inactiveAccount": "Reative a conta para gerenciar a conex\xE3o.",
2804
+ "financial.openFinance.readOnly": "Voc\xEA n\xE3o tem permiss\xE3o para alterar a conex\xE3o desta conta.",
2805
+ "financial.openFinance.supportCode": "C\xF3digo para o suporte: {{code}}",
2806
+ "financial.openFinance.fetchRequested": "Pedimos o extrato ao banco. As novas linhas aparecem na Concilia\xE7\xE3o assim que ele responder.",
2807
+ "financial.openFinance.disconnected": "Conta desconectada. As linhas j\xE1 importadas continuam na Concilia\xE7\xE3o.",
2808
+ "financial.openFinance.confirm.disconnectTitle": "Desconectar do Open Finance?",
2809
+ "financial.openFinance.confirm.disconnectBody": "O extrato desta conta deixa de chegar. As linhas j\xE1 importadas e as concilia\xE7\xF5es feitas continuam como est\xE3o.",
2810
+ "financial.openFinance.confirm.renewTitle": "Renovar a autoriza\xE7\xE3o?",
2811
+ "financial.openFinance.confirm.renewBody": "Voc\xEA vai autorizar de novo no site do banco. At\xE9 l\xE1, a busca do extrato desta conta fica pausada; nada do que j\xE1 foi importado se perde.",
2812
+ "financial.openFinance.field.accountDigit": "D\xEDgito da conta",
2813
+ "financial.openFinance.field.agencyDigit": "D\xEDgito da ag\xEAncia",
2814
+ "financial.openFinance.field.holderDocument": "CPF/CNPJ do titular",
2815
+ "financial.openFinance.field.holderName": "Nome do titular",
2816
+ "financial.openFinance.field.street": "Rua",
2817
+ "financial.openFinance.field.number": "N\xFAmero",
2818
+ "financial.openFinance.field.complement": "Complemento",
2819
+ "financial.openFinance.field.district": "Bairro",
2820
+ "financial.openFinance.field.city": "Cidade",
2821
+ "financial.openFinance.field.state": "UF",
2822
+ "financial.openFinance.field.postalCode": "CEP",
2823
+ "financial.openFinance.error.notConfigured": "A conex\xE3o com o Open Finance ainda n\xE3o est\xE1 dispon\xEDvel para esta conta. Fale com o suporte.",
2824
+ "financial.openFinance.error.providerRefused": "O banco recusou o cadastro desta conta. Confira ag\xEAncia, conta e titular no cadastro e tente de novo.",
2825
+ "financial.openFinance.error.alreadyConnected": "Esta conta j\xE1 est\xE1 conectada ao Open Finance.",
2826
+ "financial.openFinance.error.payerIncomplete": "Preencha os dados que faltam para continuar.",
2827
+ "financial.openFinance.error.unsupportedBank": "Este banco ainda n\xE3o oferece extrato pelo Open Finance.",
2828
+ "financial.openFinance.error.rateLimited": "O banco pediu um intervalo entre as buscas. Tente de novo daqui a pouco.",
2829
+ "financial.openFinance.error.rateLimitedUntil": "O banco pediu um intervalo entre as buscas. Tente de novo a partir de {{when}}.",
2830
+ "financial.openFinance.error.unauthorized": "Sua sess\xE3o expirou. Entre de novo para continuar.",
2831
+ "financial.openFinance.error.forbidden": "Voc\xEA n\xE3o tem permiss\xE3o para alterar a conex\xE3o desta conta.",
2832
+ "financial.openFinance.error.unavailable": "N\xE3o foi poss\xEDvel falar com o servi\xE7o agora. Tente de novo em instantes.",
2833
+ "financial.openFinance.error.statementFailed": "A \xFAltima busca de extrato falhou. Tente buscar de novo; se continuar, renove a autoriza\xE7\xE3o.",
2834
+ "financial.openFinance.error.generic": "Algo deu errado ao falar com o banco. Tente de novo em instantes."
2707
2835
  };
2708
2836
 
2709
2837
  // src/locales/index.ts
@@ -2821,7 +2949,7 @@ function ClientAccountPanel({
2821
2949
  tiles.push({
2822
2950
  label: "A executar",
2823
2951
  value: aExecutar,
2824
- hint: (account?.paidToExecute ?? 0) > 0 ? `${formatCurrency(account?.paidToExecute ?? 0, currency)} j\xE1 pagos \u2014 servi\xE7o que a casa ainda deve prestar` : "Contratado e ainda n\xE3o executado"
2952
+ hint: (account?.paidToExecute ?? 0) > 0 ? `${formatCurrency$1(account?.paidToExecute ?? 0, currency)} j\xE1 pagos \u2014 servi\xE7o que a casa ainda deve prestar` : "Contratado e ainda n\xE3o executado"
2825
2953
  });
2826
2954
  }
2827
2955
  if (account === null) {
@@ -2840,7 +2968,7 @@ function ClientAccountPanel({
2840
2968
  clientName && /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: clientName }),
2841
2969
  /* @__PURE__ */ jsx("div", { className: `fz-tiles ${tiles.length > 3 ? "fz-tiles-4" : "fz-tiles-3"}`, children: tiles.map((t) => /* @__PURE__ */ jsxs("div", { title: t.hint, className: "rounded-xl border px-3 py-2", children: [
2842
2970
  /* @__PURE__ */ jsx("p", { className: "text-[10px] uppercase text-muted-foreground", children: t.label }),
2843
- /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-sm font-semibold tabular-nums", children: formatCurrency(t.value, currency) })
2971
+ /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-sm font-semibold tabular-nums", children: formatCurrency$1(t.value, currency) })
2844
2972
  ] }, t.label)) }),
2845
2973
  provider.prepayServices && !comprando && /* @__PURE__ */ jsx(
2846
2974
  Button,
@@ -2873,7 +3001,7 @@ function ClientAccountPanel({
2873
3001
  "aria-label": `Quantidade de ${e.name}`
2874
3002
  }
2875
3003
  ) }),
2876
- /* @__PURE__ */ jsx("span", { className: "w-20 shrink-0 text-right text-xs tabular-nums", children: formatCurrency(e.price * e.qtd, currency) }),
3004
+ /* @__PURE__ */ jsx("span", { className: "w-20 shrink-0 text-right text-xs tabular-nums", children: formatCurrency$1(e.price * e.qtd, currency) }),
2877
3005
  /* @__PURE__ */ jsx(
2878
3006
  Button,
2879
3007
  {
@@ -2905,7 +3033,7 @@ function ClientAccountPanel({
2905
3033
  className: "font-normal justify-start whitespace-normal flex w-full items-center gap-2 rounded px-2 py-1 text-left hover:bg-muted",
2906
3034
  children: [
2907
3035
  /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate text-xs", children: c.name }),
2908
- /* @__PURE__ */ jsx("span", { className: "shrink-0 text-[11px] tabular-nums text-muted-foreground", children: formatCurrency(c.price, currency) })
3036
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 text-[11px] tabular-nums text-muted-foreground", children: formatCurrency$1(c.price, currency) })
2909
3037
  ]
2910
3038
  }
2911
3039
  ) }, c.id)) }),
@@ -2934,7 +3062,7 @@ function ClientAccountPanel({
2934
3062
  onClick: confirmarCompra,
2935
3063
  disabled: comprandoBusy || !escolhidos.length,
2936
3064
  className: "rounded-button bg-foreground px-3 py-1.5 text-xs font-semibold text-background disabled:opacity-40",
2937
- children: comprandoBusy ? "Registrando\u2026" : `Registrar \xB7 ${formatCurrency(
3065
+ children: comprandoBusy ? "Registrando\u2026" : `Registrar \xB7 ${formatCurrency$1(
2938
3066
  escolhidos.reduce((t, e) => t + e.price * e.qtd, 0),
2939
3067
  currency
2940
3068
  )}`
@@ -2989,8 +3117,8 @@ function ClientAccountPanel({
2989
3117
  /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground", children: i.competenceDate ?? "" })
2990
3118
  ] }),
2991
3119
  /* @__PURE__ */ jsxs("div", { className: "text-right", children: [
2992
- /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold tabular-nums", children: formatCurrency(i.total, currency) }),
2993
- /* @__PURE__ */ jsx("p", { className: `text-[10px] tabular-nums ${i.balance > 0 ? "text-destructive" : "text-success"}`, children: i.balance > 0 ? `resta ${formatCurrency(i.balance, currency)}` : "pago" })
3120
+ /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold tabular-nums", children: formatCurrency$1(i.total, currency) }),
3121
+ /* @__PURE__ */ jsx("p", { className: `text-[10px] tabular-nums ${i.balance > 0 ? "text-destructive" : "text-success"}`, children: i.balance > 0 ? `resta ${formatCurrency$1(i.balance, currency)}` : "pago" })
2994
3122
  ] }),
2995
3123
  /* @__PURE__ */ jsx(
2996
3124
  Button,
@@ -3409,6 +3537,464 @@ function AccountEditor({ ctx, nodes, fullTree, side, busy, onSave }) {
3409
3537
  )
3410
3538
  );
3411
3539
  }
3540
+ var ConnectionError = class extends Error {
3541
+ constructor(status, code, details = {}) {
3542
+ super(code);
3543
+ this.status = status;
3544
+ this.code = code;
3545
+ this.details = details;
3546
+ this.name = "ConnectionError";
3547
+ }
3548
+ };
3549
+ async function request(method, path, body) {
3550
+ const base = serviceBaseUrl();
3551
+ const supabase = getSupabaseClientOptional();
3552
+ if (!base || !supabase) throw new ConnectionError(503, "no_client");
3553
+ const { data } = await supabase.auth.getSession();
3554
+ const token = data?.session?.access_token;
3555
+ if (!token) throw new ConnectionError(401, "unauthorized");
3556
+ const tenant = getActiveTenantId();
3557
+ const unit = getActiveUnitId();
3558
+ let response;
3559
+ try {
3560
+ response = await fetch(`${base}${path}`, {
3561
+ method,
3562
+ headers: {
3563
+ authorization: `Bearer ${token}`,
3564
+ ...tenant ? { "x-fayz-tenant": tenant } : {},
3565
+ ...unit ? { "x-fayz-unit": unit } : {},
3566
+ ...body === void 0 ? {} : { "content-type": "application/json" }
3567
+ },
3568
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
3569
+ });
3570
+ } catch {
3571
+ throw new ConnectionError(503, "unavailable");
3572
+ }
3573
+ const text = await response.text();
3574
+ let payload = null;
3575
+ try {
3576
+ payload = text ? JSON.parse(text) : null;
3577
+ } catch {
3578
+ }
3579
+ if (response.ok) return payload;
3580
+ const code = typeof payload?.code === "string" ? payload.code : typeof payload?.error === "string" ? payload.error : response.status === 429 ? "rate_limited" : "unavailable";
3581
+ throw new ConnectionError(response.status, code, {
3582
+ missing: Array.isArray(payload?.missing) ? payload.missing : void 0,
3583
+ retryAt: typeof payload?.retryAt === "string" ? payload.retryAt : void 0,
3584
+ internalCode: payload?.internalCode != null ? String(payload.internalCode) : void 0
3585
+ });
3586
+ }
3587
+ var connection = (id, rest = "") => `/v1/banking/connections/${encodeURIComponent(id)}${rest}`;
3588
+ var openFinanceClient = {
3589
+ status: (accountId) => request("GET", `/v1/banking/connections?accountId=${encodeURIComponent(accountId)}`),
3590
+ connect: (accountId, supplied) => request("POST", "/v1/banking/connections", supplied ? { accountId, supplied } : { accountId }),
3591
+ refresh: (connectionId) => request("GET", connection(connectionId, "?refresh=true")),
3592
+ renew: (connectionId) => request("PATCH", connection(connectionId), { consent: "renewing" }),
3593
+ disconnect: (connectionId) => request("PATCH", connection(connectionId), { active: false }),
3594
+ fetchStatement: (connectionId) => request("POST", connection(connectionId, "/statement-requests"))
3595
+ };
3596
+ function safeConsentLink(link) {
3597
+ if (!link) return null;
3598
+ let url;
3599
+ try {
3600
+ url = new URL(link);
3601
+ } catch {
3602
+ return null;
3603
+ }
3604
+ if (url.protocol !== "https:" || url.username || url.password) return null;
3605
+ const host = url.hostname.toLowerCase();
3606
+ return host === "pagamentobancario.com.br" || host.endsWith(".pagamentobancario.com.br") ? url.toString() : null;
3607
+ }
3608
+ function connectionPanel(view, ctx) {
3609
+ const allowed = ctx.canEdit && ctx.accountActive;
3610
+ const only = (actions) => allowed ? actions : [];
3611
+ const consentLink = safeConsentLink(view.consentLink);
3612
+ const refreshOnOpen = view.state === "pending" || view.adopted === true;
3613
+ switch (view.state) {
3614
+ case "pending":
3615
+ return {
3616
+ title: "financial.openFinance.state.pending",
3617
+ tone: "warning",
3618
+ actions: only(consentLink ? ["openConsent", "confirmAuthorized"] : ["confirmAuthorized"]),
3619
+ consentLink,
3620
+ note: consentLink ? "financial.openFinance.note.pending" : "financial.openFinance.note.pendingNoLink",
3621
+ refreshOnOpen
3622
+ };
3623
+ case "active":
3624
+ return {
3625
+ title: view.adopted ? "financial.openFinance.state.adopted" : "financial.openFinance.state.active",
3626
+ tone: "success",
3627
+ actions: only(["fetchStatement", "renew", "disconnect"]),
3628
+ consentLink: null,
3629
+ refreshOnOpen
3630
+ };
3631
+ case "revoked":
3632
+ return {
3633
+ title: "financial.openFinance.state.revoked",
3634
+ tone: "warning",
3635
+ actions: only(["reconnect"]),
3636
+ consentLink: null,
3637
+ note: "financial.openFinance.note.revoked",
3638
+ refreshOnOpen
3639
+ };
3640
+ case "error":
3641
+ return {
3642
+ title: "financial.openFinance.state.error",
3643
+ tone: "error",
3644
+ actions: only(["retry"]),
3645
+ consentLink: null,
3646
+ errorKey: connectionErrorKey(view.error?.code),
3647
+ refreshOnOpen
3648
+ };
3649
+ case "none":
3650
+ default:
3651
+ return {
3652
+ title: "financial.openFinance.state.none",
3653
+ tone: "muted",
3654
+ actions: only(["connect"]),
3655
+ consentLink: null,
3656
+ note: "financial.openFinance.note.none",
3657
+ refreshOnOpen
3658
+ };
3659
+ }
3660
+ }
3661
+ var ERROR_KEYS = {
3662
+ not_configured: "notConfigured",
3663
+ no_client: "notConfigured",
3664
+ plugbank_refused: "providerRefused",
3665
+ already_connected: "alreadyConnected",
3666
+ payer_incomplete: "payerIncomplete",
3667
+ unsupported_bank: "unsupportedBank",
3668
+ rate_limited: "rateLimited",
3669
+ // Codes the integration service also answers with (control-sdk-backend #94).
3670
+ not_ready: "notConfigured",
3671
+ no_owner: "notConfigured",
3672
+ not_allowed: "forbidden",
3673
+ plugbank_unavailable: "unavailable",
3674
+ statement_failed: "statementFailed",
3675
+ unauthorized: "unauthorized",
3676
+ forbidden: "forbidden",
3677
+ unavailable: "unavailable"
3678
+ };
3679
+ function connectionErrorKey(error) {
3680
+ const code = error instanceof ConnectionError ? error.code : typeof error === "string" ? error : void 0;
3681
+ if (code && ERROR_KEYS[code]) return `financial.openFinance.error.${ERROR_KEYS[code]}`;
3682
+ if (error instanceof ConnectionError && error.status === 403) return "financial.openFinance.error.forbidden";
3683
+ return "financial.openFinance.error.generic";
3684
+ }
3685
+ var INPUTS = {
3686
+ accountDigit: { label: "financial.openFinance.field.accountDigit", digits: true, maxLength: 2 },
3687
+ agencyDigit: { label: "financial.openFinance.field.agencyDigit", digits: true, maxLength: 2 },
3688
+ holderDocument: { label: "financial.openFinance.field.holderDocument", digits: true, maxLength: 14 },
3689
+ holderName: { label: "financial.openFinance.field.holderName", maxLength: 250 },
3690
+ street: { label: "financial.openFinance.field.street", maxLength: 250 },
3691
+ number: { label: "financial.openFinance.field.number", maxLength: 10 },
3692
+ complement: { label: "financial.openFinance.field.complement", maxLength: 100 },
3693
+ district: { label: "financial.openFinance.field.district", maxLength: 250 },
3694
+ city: { label: "financial.openFinance.field.city", maxLength: 250 },
3695
+ state: { label: "financial.openFinance.field.state", maxLength: 2, upper: true },
3696
+ postalCode: { label: "financial.openFinance.field.postalCode", digits: true, maxLength: 8 }
3697
+ };
3698
+ var ADDRESS_KEYS = /* @__PURE__ */ new Set(["street", "number", "complement", "district", "city", "state", "postalCode"]);
3699
+ var bare = (key) => key.replace(/^address\./, "");
3700
+ function missingInputs(missing) {
3701
+ const inputs = [];
3702
+ const unknown = [];
3703
+ const seen = /* @__PURE__ */ new Set();
3704
+ for (const raw of missing ?? []) {
3705
+ const key = bare(raw);
3706
+ if (seen.has(key)) continue;
3707
+ seen.add(key);
3708
+ const def = INPUTS[key];
3709
+ if (def) inputs.push({ key, ...def });
3710
+ else unknown.push(raw);
3711
+ }
3712
+ return { inputs, unknown };
3713
+ }
3714
+ function suppliedFrom(values) {
3715
+ const supplied = {};
3716
+ const address = {};
3717
+ for (const [rawKey, rawValue] of Object.entries(values)) {
3718
+ const value = rawValue.trim();
3719
+ if (!value) continue;
3720
+ const key = bare(rawKey);
3721
+ if (ADDRESS_KEYS.has(key)) address[key] = value;
3722
+ else if (key in INPUTS) supplied[key] = value;
3723
+ }
3724
+ if (Object.keys(address).length) supplied.address = address;
3725
+ return supplied;
3726
+ }
3727
+ function firstBlank(inputs, values) {
3728
+ return inputs.find((input) => input.key !== "complement" && !(values[input.key] ?? "").trim()) ?? null;
3729
+ }
3730
+ var TONE = {
3731
+ muted: "text-muted-foreground",
3732
+ success: "text-emerald-700 dark:text-emerald-500",
3733
+ warning: "text-amber-600 dark:text-amber-500",
3734
+ error: "text-destructive"
3735
+ };
3736
+ var when = (iso2) => iso2 ? formatDateTime(iso2) : null;
3737
+ var day = (iso2) => iso2 ? formatDate(iso2) : null;
3738
+ function refusalSentence(error, t) {
3739
+ if (error instanceof ConnectionError && error.code === "rate_limited" && error.details.retryAt) {
3740
+ const at = when(error.details.retryAt);
3741
+ if (at) return t("financial.openFinance.error.rateLimitedUntil", { when: at });
3742
+ }
3743
+ return t(connectionErrorKey(error));
3744
+ }
3745
+ function OpenFinancePanel({ item }) {
3746
+ const account = item ?? {};
3747
+ const accountId = account.id;
3748
+ const accountActive = (account.isActive ?? account.is_active) !== false;
3749
+ const t = useTranslation();
3750
+ const can = usePermissionOptional();
3751
+ const canEdit = can("financial", "edit");
3752
+ const [view, setView] = React3__default.useState(null);
3753
+ const [loadError, setLoadError] = React3__default.useState(null);
3754
+ const [busy, setBusy] = React3__default.useState("load");
3755
+ const [actionError, setActionError] = React3__default.useState(null);
3756
+ const [asking, setAsking] = React3__default.useState(null);
3757
+ const [values, setValues] = React3__default.useState({});
3758
+ const [confirm, setConfirm] = React3__default.useState(null);
3759
+ const generation = React3__default.useRef(0);
3760
+ const run = React3__default.useCallback(async (action, call) => {
3761
+ const token = generation.current;
3762
+ setBusy(action);
3763
+ setActionError(null);
3764
+ try {
3765
+ const result = await call();
3766
+ return token === generation.current ? result : void 0;
3767
+ } catch (error) {
3768
+ if (token !== generation.current) return void 0;
3769
+ if (action === "load") setLoadError(error);
3770
+ else setActionError(error);
3771
+ return void 0;
3772
+ } finally {
3773
+ if (token === generation.current) setBusy(null);
3774
+ }
3775
+ }, []);
3776
+ const load = React3__default.useCallback(async () => {
3777
+ if (!accountId) return;
3778
+ setLoadError(null);
3779
+ const first = await run("load", () => openFinanceClient.status(accountId));
3780
+ if (first) setView(first);
3781
+ }, [accountId, run]);
3782
+ React3__default.useEffect(() => {
3783
+ generation.current += 1;
3784
+ setView(null);
3785
+ setAsking(null);
3786
+ setValues({});
3787
+ setActionError(null);
3788
+ void load();
3789
+ return () => {
3790
+ generation.current += 1;
3791
+ };
3792
+ }, [load]);
3793
+ const connect = async (supplied) => {
3794
+ if (!accountId) return;
3795
+ try {
3796
+ await openFinanceClient.connect(accountId, supplied);
3797
+ const next = await openFinanceClient.status(accountId);
3798
+ setView(next);
3799
+ setAsking(null);
3800
+ setValues({});
3801
+ return next;
3802
+ } catch (error) {
3803
+ if (error instanceof ConnectionError && error.code === "payer_incomplete" && error.details.missing?.length) {
3804
+ setAsking(error.details.missing);
3805
+ return void 0;
3806
+ }
3807
+ throw error;
3808
+ }
3809
+ };
3810
+ const startConnect = (action) => {
3811
+ if (view?.missing?.length) {
3812
+ setAsking(view.missing);
3813
+ return;
3814
+ }
3815
+ void run(action, () => connect());
3816
+ };
3817
+ const onAction = (action) => {
3818
+ const id = view?.connectionId;
3819
+ switch (action) {
3820
+ case "connect":
3821
+ case "reconnect":
3822
+ case "retry":
3823
+ startConnect(action);
3824
+ return;
3825
+ case "confirmAuthorized":
3826
+ if (id && accountId) void run(action, async () => {
3827
+ await openFinanceClient.refresh(id);
3828
+ setView(await openFinanceClient.status(accountId));
3829
+ });
3830
+ return;
3831
+ case "fetchStatement":
3832
+ if (id) {
3833
+ void run(action, async () => {
3834
+ await openFinanceClient.fetchStatement(id);
3835
+ toast.success(t("financial.openFinance.fetchRequested"));
3836
+ });
3837
+ }
3838
+ return;
3839
+ case "renew":
3840
+ case "disconnect":
3841
+ setConfirm(action);
3842
+ return;
3843
+ case "openConsent":
3844
+ return;
3845
+ }
3846
+ };
3847
+ const confirmAction = () => {
3848
+ const id = view?.connectionId;
3849
+ const action = confirm;
3850
+ setConfirm(null);
3851
+ if (!id || !action || !accountId) return;
3852
+ void run(action, async () => {
3853
+ if (action === "renew") await openFinanceClient.renew(id);
3854
+ else await openFinanceClient.disconnect(id);
3855
+ setView(await openFinanceClient.status(accountId));
3856
+ if (action === "disconnect") toast.success(t("financial.openFinance.disconnected"));
3857
+ });
3858
+ };
3859
+ const asked = asking ? missingInputs(asking) : null;
3860
+ const submitMissing = (event) => {
3861
+ event.preventDefault();
3862
+ if (!asked) return;
3863
+ const blank = firstBlank(asked.inputs, values);
3864
+ if (blank) {
3865
+ setActionError(new ConnectionError(422, "payer_incomplete"));
3866
+ return;
3867
+ }
3868
+ void run("submit", () => connect(suppliedFrom(values)));
3869
+ };
3870
+ const panel = view ? connectionPanel(view, { canEdit, accountActive }) : null;
3871
+ return /* @__PURE__ */ jsxs(Card, { children: [
3872
+ /* @__PURE__ */ jsxs(CardHeader, { children: [
3873
+ /* @__PURE__ */ jsxs(CardTitle, { className: "flex items-center gap-2 text-base", children: [
3874
+ /* @__PURE__ */ jsx(Landmark, { className: "h-4 w-4 text-muted-foreground" }),
3875
+ t("financial.openFinance.title")
3876
+ ] }),
3877
+ /* @__PURE__ */ jsx(CardDescription, { children: t("financial.openFinance.description") })
3878
+ ] }),
3879
+ /* @__PURE__ */ jsxs(CardContent, { className: "space-y-4", children: [
3880
+ !view && busy === "load" && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
3881
+ /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }),
3882
+ t("financial.openFinance.loading")
3883
+ ] }),
3884
+ !view && loadError != null && busy !== "load" && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
3885
+ /* @__PURE__ */ jsx("p", { role: "alert", className: "text-sm text-destructive", children: refusalSentence(loadError, t) }),
3886
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => void load(), children: t("financial.openFinance.action.retry") })
3887
+ ] }),
3888
+ view && panel && /* @__PURE__ */ jsxs(Fragment, { children: [
3889
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
3890
+ /* @__PURE__ */ jsxs("p", { className: `flex items-center gap-2 text-sm font-medium ${TONE[panel.tone]}`, children: [
3891
+ view.state === "active" ? /* @__PURE__ */ jsx(CheckCircle2, { className: "h-4 w-4" }) : view.state === "revoked" ? /* @__PURE__ */ jsx(Unplug, { className: "h-4 w-4" }) : null,
3892
+ t(panel.title)
3893
+ ] }),
3894
+ panel.errorKey && /* @__PURE__ */ jsx("p", { className: "text-sm", children: t(panel.errorKey) }),
3895
+ panel.note && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(panel.note) })
3896
+ ] }),
3897
+ view.state === "active" && /* @__PURE__ */ jsxs("dl", { className: "grid grid-cols-1 gap-x-6 gap-y-2 text-sm sm:grid-cols-2", children: [
3898
+ view.since && !view.adopted && /* @__PURE__ */ jsx(Detail, { label: t("financial.openFinance.since"), value: day(view.since) }),
3899
+ /* @__PURE__ */ jsx(
3900
+ Detail,
3901
+ {
3902
+ label: t("financial.openFinance.lastStatement"),
3903
+ value: when(view.lastStatementAt) ?? t("financial.openFinance.lastStatementNever")
3904
+ }
3905
+ ),
3906
+ view.nextStatementAt && /* @__PURE__ */ jsx(Detail, { label: t("financial.openFinance.nextStatement"), value: when(view.nextStatementAt) }),
3907
+ view.balance && /* @__PURE__ */ jsx(
3908
+ Detail,
3909
+ {
3910
+ label: t("financial.openFinance.balance"),
3911
+ value: formatCurrency(view.balance.amount),
3912
+ sub: t("financial.openFinance.balanceAt", { when: when(view.balance.updatedAt) ?? "" })
3913
+ }
3914
+ )
3915
+ ] }),
3916
+ asked ? /* @__PURE__ */ jsxs("form", { className: "space-y-3", onSubmit: submitMissing, children: [
3917
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("financial.openFinance.missingTitle") }),
3918
+ asked.unknown.length > 0 && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("financial.openFinance.missingElsewhere") }),
3919
+ /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2", children: asked.inputs.map((input) => /* @__PURE__ */ jsxs("label", { className: "space-y-1 text-sm", children: [
3920
+ /* @__PURE__ */ jsx("span", { className: "block font-medium", children: t(input.label) }),
3921
+ /* @__PURE__ */ jsx(
3922
+ Input,
3923
+ {
3924
+ value: values[input.key] ?? "",
3925
+ maxLength: input.maxLength,
3926
+ inputMode: input.digits ? "numeric" : "text",
3927
+ disabled: busy !== null,
3928
+ onChange: (e) => {
3929
+ let next = e.target.value;
3930
+ if (input.digits) next = next.replace(/\D/g, "");
3931
+ if (input.upper) next = next.replace(/[^a-z]/gi, "").toUpperCase();
3932
+ setValues((prev) => ({ ...prev, [input.key]: next }));
3933
+ setActionError(null);
3934
+ }
3935
+ }
3936
+ )
3937
+ ] }, input.key)) }),
3938
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", children: [
3939
+ /* @__PURE__ */ jsxs(Button, { type: "submit", size: "sm", disabled: busy !== null || asked.inputs.length === 0, children: [
3940
+ busy === "submit" && /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }),
3941
+ t("financial.openFinance.action.connect")
3942
+ ] }),
3943
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", disabled: busy !== null, onClick: () => {
3944
+ setAsking(null);
3945
+ setActionError(null);
3946
+ }, children: t("financial.openFinance.action.cancel") })
3947
+ ] })
3948
+ ] }) : panel.actions.length > 0 ? /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: panel.actions.map((action) => action === "openConsent" && panel.consentLink ? /* @__PURE__ */ jsx(Button, { asChild: true, size: "sm", children: /* @__PURE__ */ jsxs("a", { href: panel.consentLink, target: "_blank", rel: "noopener noreferrer", children: [
3949
+ /* @__PURE__ */ jsx(ExternalLink, { className: "h-4 w-4" }),
3950
+ t("financial.openFinance.action.openConsent")
3951
+ ] }) }, action) : /* @__PURE__ */ jsxs(
3952
+ Button,
3953
+ {
3954
+ type: "button",
3955
+ size: "sm",
3956
+ variant: action === "disconnect" ? "outline" : action === panel.actions[0] ? "default" : "outline",
3957
+ disabled: busy !== null,
3958
+ onClick: () => onAction(action),
3959
+ children: [
3960
+ busy === action && /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }),
3961
+ t(`financial.openFinance.action.${action}`)
3962
+ ]
3963
+ },
3964
+ action
3965
+ )) }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: !accountActive ? t("financial.openFinance.inactiveAccount") : !canEdit ? t("financial.openFinance.readOnly") : null }),
3966
+ busy === "load" && /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
3967
+ /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin" }),
3968
+ t("financial.openFinance.refreshing")
3969
+ ] })
3970
+ ] }),
3971
+ actionError != null && /* @__PURE__ */ jsxs("div", { role: "alert", className: "space-y-1 text-sm text-destructive", children: [
3972
+ /* @__PURE__ */ jsx("p", { children: refusalSentence(actionError, t) }),
3973
+ actionError instanceof ConnectionError && actionError.details.internalCode && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("financial.openFinance.supportCode", { code: actionError.details.internalCode }) })
3974
+ ] })
3975
+ ] }),
3976
+ /* @__PURE__ */ jsx(
3977
+ ConfirmDialog,
3978
+ {
3979
+ open: confirm !== null,
3980
+ variant: confirm === "disconnect" ? "destructive" : "warning",
3981
+ title: t(confirm === "disconnect" ? "financial.openFinance.confirm.disconnectTitle" : "financial.openFinance.confirm.renewTitle"),
3982
+ description: t(confirm === "disconnect" ? "financial.openFinance.confirm.disconnectBody" : "financial.openFinance.confirm.renewBody"),
3983
+ confirmLabel: t(confirm === "disconnect" ? "financial.openFinance.action.disconnect" : "financial.openFinance.action.renew"),
3984
+ cancelLabel: t("financial.openFinance.action.cancel"),
3985
+ onConfirm: confirmAction,
3986
+ onCancel: () => setConfirm(null)
3987
+ }
3988
+ )
3989
+ ] });
3990
+ }
3991
+ function Detail({ label, value, sub }) {
3992
+ return /* @__PURE__ */ jsxs("div", { children: [
3993
+ /* @__PURE__ */ jsx("dt", { className: "text-xs text-muted-foreground", children: label }),
3994
+ /* @__PURE__ */ jsx("dd", { className: "font-medium", children: value }),
3995
+ sub && /* @__PURE__ */ jsx("dd", { className: "text-xs text-muted-foreground", children: sub })
3996
+ ] });
3997
+ }
3412
3998
 
3413
3999
  // src/data/registries.ts
3414
4000
  var paymentMethodTypeEntity = {
@@ -3619,6 +4205,18 @@ var bankAccountEntity = {
3619
4205
  visibleWhen: (v) => isBank(v.kind),
3620
4206
  group: "bank"
3621
4207
  },
4208
+ // The check digits sit beside the number they check, so the two-column
4209
+ // group reads «Agência | Dígito» and «Conta | Dígito». The Open Finance
4210
+ // payer registration asks for them separately (138).
4211
+ {
4212
+ key: "agencyDigit",
4213
+ label: tl("Agency check digit", "D\xEDgito da ag\xEAncia"),
4214
+ type: "text",
4215
+ showInTable: false,
4216
+ max: 2,
4217
+ visibleWhen: (v) => isBank(v.kind),
4218
+ group: "bank"
4219
+ },
3622
4220
  {
3623
4221
  key: "accountNumber",
3624
4222
  label: "N\xFAmero da conta",
@@ -3627,6 +4225,15 @@ var bankAccountEntity = {
3627
4225
  visibleWhen: (v) => isBank(v.kind),
3628
4226
  group: "bank"
3629
4227
  },
4228
+ {
4229
+ key: "accountDigit",
4230
+ label: tl("Account check digit", "D\xEDgito da conta"),
4231
+ type: "text",
4232
+ showInTable: false,
4233
+ max: 2,
4234
+ visibleWhen: (v) => isBank(v.kind),
4235
+ group: "bank"
4236
+ },
3630
4237
  // TITULAR. A conta de uma rede raramente está no nome da rede: está no do
3631
4238
  // sócio, da holding, da empresa de serviços. Quem confere um extrato precisa
3632
4239
  // saber de quem é a conta antes de bater o valor, e quem faz uma
@@ -3761,6 +4368,18 @@ var bankAccountEntity = {
3761
4368
  // canto do título, observações e etiquetas. Ver recordRailFields.
3762
4369
  ...recordRailFields({ tagsTable: "plg_financial_accounts", activeLabel: "Ativa" })
3763
4370
  ],
4371
+ // The Open Finance connection of a bank account: a tab only on accounts of
4372
+ // kind `bank` (a cash drawer has no statement to connect; credit cards are
4373
+ // not connected from here).
4374
+ detailTabs: [
4375
+ {
4376
+ id: "bank-statement",
4377
+ label: tl("Bank statement", "Extrato banc\xE1rio"),
4378
+ icon: "Landmark",
4379
+ component: OpenFinancePanel,
4380
+ visibleWhen: (item) => isBank(item.kind)
4381
+ }
4382
+ ],
3764
4383
  // The canonical table — the same one getBankAccounts reads.
3765
4384
  data: {
3766
4385
  table: "plg_financial_accounts",
@@ -4841,11 +5460,11 @@ var stripeConnectorDef = {
4841
5460
  ],
4842
5461
  ...connectionStatus(
4843
5462
  STRIPE_CONNECTOR_ID,
4844
- (connection) => ({
4845
- connected: !!connection?.active,
4846
- detail: methodsDetail(connection?.settings?.paymentMethods),
5463
+ (connection2) => ({
5464
+ connected: !!connection2?.active,
5465
+ detail: methodsDetail(connection2?.settings?.paymentMethods),
4847
5466
  plane: "sync",
4848
- ...settingsStatus(STRIPE_SETTINGS, connection)
5467
+ ...settingsStatus(STRIPE_SETTINGS, connection2)
4849
5468
  }),
4850
5469
  { store: () => store }
4851
5470
  ),
@@ -4965,11 +5584,11 @@ var mercadoPagoConnectorDef = {
4965
5584
  ],
4966
5585
  ...connectionStatus(
4967
5586
  MERCADOPAGO_CONNECTOR_ID,
4968
- (connection) => ({
4969
- connected: !!connection?.active,
4970
- detail: methodsDetail2(METHOD_LABELS2, connection?.settings?.methods),
5587
+ (connection2) => ({
5588
+ connected: !!connection2?.active,
5589
+ detail: methodsDetail2(METHOD_LABELS2, connection2?.settings?.methods),
4971
5590
  plane: "sync",
4972
- ...settingsStatus(MERCADOPAGO_SETTINGS, connection)
5591
+ ...settingsStatus(MERCADOPAGO_SETTINGS, connection2)
4973
5592
  }),
4974
5593
  { store: () => store2 }
4975
5594
  ),
@@ -5026,11 +5645,11 @@ var pagBankConnectorDef = {
5026
5645
  ],
5027
5646
  ...connectionStatus(
5028
5647
  PAGBANK_CONNECTOR_ID,
5029
- (connection) => ({
5030
- connected: !!connection?.active,
5031
- detail: methodsDetail2(METHOD_LABELS3, connection?.settings?.methods),
5648
+ (connection2) => ({
5649
+ connected: !!connection2?.active,
5650
+ detail: methodsDetail2(METHOD_LABELS3, connection2?.settings?.methods),
5032
5651
  plane: "sync",
5033
- ...settingsStatus(PAGBANK_SETTINGS, connection)
5652
+ ...settingsStatus(PAGBANK_SETTINGS, connection2)
5034
5653
  }),
5035
5654
  { store: () => store3 }
5036
5655
  ),
@@ -5089,11 +5708,11 @@ var cieloConnectorDef = {
5089
5708
  ],
5090
5709
  ...connectionStatus(
5091
5710
  CIELO_CONNECTOR_ID,
5092
- (connection) => ({
5093
- connected: !!connection?.active,
5094
- detail: methodsDetail2(METHOD_LABELS4, connection?.settings?.methods),
5711
+ (connection2) => ({
5712
+ connected: !!connection2?.active,
5713
+ detail: methodsDetail2(METHOD_LABELS4, connection2?.settings?.methods),
5095
5714
  plane: "sync",
5096
- ...settingsStatus(CIELO_SETTINGS, connection)
5715
+ ...settingsStatus(CIELO_SETTINGS, connection2)
5097
5716
  }),
5098
5717
  { store: () => store4 }
5099
5718
  ),
@@ -5151,11 +5770,11 @@ var stoneConnectorDef = {
5151
5770
  ],
5152
5771
  ...connectionStatus(
5153
5772
  STONE_CONNECTOR_ID,
5154
- (connection) => ({
5155
- connected: !!connection?.active,
5156
- detail: methodsDetail2(METHOD_LABELS5, connection?.settings?.methods),
5773
+ (connection2) => ({
5774
+ connected: !!connection2?.active,
5775
+ detail: methodsDetail2(METHOD_LABELS5, connection2?.settings?.methods),
5157
5776
  plane: "sync",
5158
- ...settingsStatus(STONE_SETTINGS, connection)
5777
+ ...settingsStatus(STONE_SETTINGS, connection2)
5159
5778
  }),
5160
5779
  { store: () => store5 }
5161
5780
  ),