@burdenoff/microfe-subscriberbot 2026.1107.7 → 2026.1110.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/node_modules/clsx/dist/clsx.js +8 -7
- package/dist/node_modules/clsx/dist/clsx.js.map +1 -1
- package/dist/node_modules/tailwind-merge/dist/bundle-mjs.js +134 -151
- package/dist/node_modules/tailwind-merge/dist/bundle-mjs.js.map +1 -1
- package/dist/subscriberbot/SubscriberBotRoot.js +10 -7
- package/dist/subscriberbot/SubscriberBotRoot.js.map +1 -1
- package/dist/subscriberbot/SubscriberBotRoutes.js +1 -2
- package/dist/subscriberbot/SubscriberBotRoutes.js.map +1 -1
- package/dist/subscriberbot/admin/AdminDashboardPage.js +9 -10
- package/dist/subscriberbot/admin/AdminDashboardPage.js.map +1 -1
- package/dist/subscriberbot/admin/AdminRoot.js +2 -3
- package/dist/subscriberbot/admin/AdminRoot.js.map +1 -1
- package/dist/subscriberbot/admin/NegotiationDeskPanel.js +56 -57
- package/dist/subscriberbot/admin/NegotiationDeskPanel.js.map +1 -1
- package/dist/subscriberbot/admin/ProcurementDeskPanel.js +107 -108
- package/dist/subscriberbot/admin/ProcurementDeskPanel.js.map +1 -1
- package/dist/subscriberbot/admin/index.js +1 -1
- package/dist/subscriberbot/components/EmptyState.js +1 -2
- package/dist/subscriberbot/components/EmptyState.js.map +1 -1
- package/dist/subscriberbot/components/MetricsCard.js +1 -2
- package/dist/subscriberbot/components/MetricsCard.js.map +1 -1
- package/dist/subscriberbot/components/Modal.js +2 -3
- package/dist/subscriberbot/components/Modal.js.map +1 -1
- package/dist/subscriberbot/components/PageLayout.js +1 -2
- package/dist/subscriberbot/components/PageLayout.js.map +1 -1
- package/dist/subscriberbot/components/PostureOptions.js +7 -8
- package/dist/subscriberbot/components/PostureOptions.js.map +1 -1
- package/dist/subscriberbot/components/StateViews.js +1 -2
- package/dist/subscriberbot/components/StateViews.js.map +1 -1
- package/dist/subscriberbot/components/StatusBadge.js +2 -3
- package/dist/subscriberbot/components/StatusBadge.js.map +1 -1
- package/dist/subscriberbot/components/decisions/DecisionBanners.js +7 -8
- package/dist/subscriberbot/components/decisions/DecisionBanners.js.map +1 -1
- package/dist/subscriberbot/components/decisions/DecisionCard.js +65 -66
- package/dist/subscriberbot/components/decisions/DecisionCard.js.map +1 -1
- package/dist/subscriberbot/components/decisions/decisionModel.js +2 -3
- package/dist/subscriberbot/components/decisions/decisionModel.js.map +1 -1
- package/dist/subscriberbot/components/decisions/index.js +4 -3
- package/dist/subscriberbot/components/index.js +8 -7
- package/dist/subscriberbot/components/mobile/MobileDashboard.js +23 -24
- package/dist/subscriberbot/components/mobile/MobileDashboard.js.map +1 -1
- package/dist/subscriberbot/components/mobile/MobileRelationshipList.js +40 -49
- package/dist/subscriberbot/components/mobile/MobileRelationshipList.js.map +1 -1
- package/dist/subscriberbot/components/mobile/MobileScreen.js +1 -2
- package/dist/subscriberbot/components/mobile/MobileScreen.js.map +1 -1
- package/dist/subscriberbot/components/mobile/RelationshipGlyph.js +1 -2
- package/dist/subscriberbot/components/mobile/RelationshipGlyph.js.map +1 -1
- package/dist/subscriberbot/components/mobile/index.js +4 -3
- package/dist/subscriberbot/components/negotiations/NegotiationStatusPill.js +1 -2
- package/dist/subscriberbot/components/negotiations/NegotiationStatusPill.js.map +1 -1
- package/dist/subscriberbot/components/negotiations/NegotiationTimeline.js +4 -5
- package/dist/subscriberbot/components/negotiations/NegotiationTimeline.js.map +1 -1
- package/dist/subscriberbot/components/negotiations/OutcomeForm.js +4 -5
- package/dist/subscriberbot/components/negotiations/OutcomeForm.js.map +1 -1
- package/dist/subscriberbot/components/negotiations/index.js +5 -4
- package/dist/subscriberbot/components/negotiations/labels.js +1 -2
- package/dist/subscriberbot/components/negotiations/labels.js.map +1 -1
- package/dist/subscriberbot/components/procurement/ProcurementOutcomeForm.js +4 -5
- package/dist/subscriberbot/components/procurement/ProcurementOutcomeForm.js.map +1 -1
- package/dist/subscriberbot/components/procurement/ProcurementStatusPill.js +1 -2
- package/dist/subscriberbot/components/procurement/ProcurementStatusPill.js.map +1 -1
- package/dist/subscriberbot/components/procurement/ProcurementThread.js +4 -5
- package/dist/subscriberbot/components/procurement/ProcurementThread.js.map +1 -1
- package/dist/subscriberbot/components/procurement/index.js +5 -4
- package/dist/subscriberbot/components/procurement/labels.js +1 -2
- package/dist/subscriberbot/components/procurement/labels.js.map +1 -1
- package/dist/subscriberbot/components/savings/SavingsCards.js +90 -91
- package/dist/subscriberbot/components/savings/SavingsCards.js.map +1 -1
- package/dist/subscriberbot/components/savings/index.js +3 -2
- package/dist/subscriberbot/components/savings/savingsModel.js +2 -3
- package/dist/subscriberbot/components/savings/savingsModel.js.map +1 -1
- package/dist/subscriberbot/components/viz.js +2 -3
- package/dist/subscriberbot/components/viz.js.map +1 -1
- package/dist/subscriberbot/context/SubscriberBotContext.js +3 -3
- package/dist/subscriberbot/context/SubscriberBotContext.js.map +1 -1
- package/dist/subscriberbot/context/index.js +1 -1
- package/dist/subscriberbot/hooks/index.js +2 -2
- package/dist/subscriberbot/hooks/useAutonomousAgentMode.js +2 -3
- package/dist/subscriberbot/hooks/useAutonomousAgentMode.js.map +1 -1
- package/dist/subscriberbot/hooks/useBankingApi.js +2 -3
- package/dist/subscriberbot/hooks/useBankingApi.js.map +1 -1
- package/dist/subscriberbot/hooks/useCompactViewport.js +1 -2
- package/dist/subscriberbot/hooks/useCompactViewport.js.map +1 -1
- package/dist/subscriberbot/hooks/useFormError.js +1 -2
- package/dist/subscriberbot/hooks/useFormError.js.map +1 -1
- package/dist/subscriberbot/hooks/useFormatters.js +1 -2
- package/dist/subscriberbot/hooks/useFormatters.js.map +1 -1
- package/dist/subscriberbot/hooks/useNegotiationApi.js +2 -3
- package/dist/subscriberbot/hooks/useNegotiationApi.js.map +1 -1
- package/dist/subscriberbot/hooks/useProcurementApi.js +2 -3
- package/dist/subscriberbot/hooks/useProcurementApi.js.map +1 -1
- package/dist/subscriberbot/hooks/useRouteSelection.js +3 -3
- package/dist/subscriberbot/hooks/useRouteSelection.js.map +1 -1
- package/dist/subscriberbot/hooks/useSubscriberBotApi.js +1 -2
- package/dist/subscriberbot/hooks/useSubscriberBotApi.js.map +1 -1
- package/dist/subscriberbot/hooks/useTr.js +1 -2
- package/dist/subscriberbot/hooks/useTr.js.map +1 -1
- package/dist/subscriberbot/index.js +9 -8
- package/dist/subscriberbot/pages/AssetVaultPage.js +34 -35
- package/dist/subscriberbot/pages/AssetVaultPage.js.map +1 -1
- package/dist/subscriberbot/pages/DashboardPage.js +86 -87
- package/dist/subscriberbot/pages/DashboardPage.js.map +1 -1
- package/dist/subscriberbot/pages/InboxPage.js +194 -199
- package/dist/subscriberbot/pages/InboxPage.js.map +1 -1
- package/dist/subscriberbot/pages/InsightsPage.js +28 -29
- package/dist/subscriberbot/pages/InsightsPage.js.map +1 -1
- package/dist/subscriberbot/pages/InvoicesPage.js +179 -188
- package/dist/subscriberbot/pages/InvoicesPage.js.map +1 -1
- package/dist/subscriberbot/pages/RenewalsPage.js +293 -298
- package/dist/subscriberbot/pages/RenewalsPage.js.map +1 -1
- package/dist/subscriberbot/pages/SavingsPage.js +25 -26
- package/dist/subscriberbot/pages/SavingsPage.js.map +1 -1
- package/dist/subscriberbot/pages/WorkflowsPage.js +67 -68
- package/dist/subscriberbot/pages/WorkflowsPage.js.map +1 -1
- package/dist/subscriberbot/pages/agents/AgentDetailPage.js +126 -127
- package/dist/subscriberbot/pages/agents/AgentDetailPage.js.map +1 -1
- package/dist/subscriberbot/pages/agents/AgentNewPage.js +10 -11
- package/dist/subscriberbot/pages/agents/AgentNewPage.js.map +1 -1
- package/dist/subscriberbot/pages/agents/AgentsListPage.js +23 -24
- package/dist/subscriberbot/pages/agents/AgentsListPage.js.map +1 -1
- package/dist/subscriberbot/pages/banking/BankConnectionsPage.js +337 -359
- package/dist/subscriberbot/pages/banking/BankConnectionsPage.js.map +1 -1
- package/dist/subscriberbot/pages/banking/ConnectBankModal.js +22 -27
- package/dist/subscriberbot/pages/banking/ConnectBankModal.js.map +1 -1
- package/dist/subscriberbot/pages/decisions/DecisionDetailPage.js +25 -26
- package/dist/subscriberbot/pages/decisions/DecisionDetailPage.js.map +1 -1
- package/dist/subscriberbot/pages/decisions/DecisionsPage.js +34 -35
- package/dist/subscriberbot/pages/decisions/DecisionsPage.js.map +1 -1
- package/dist/subscriberbot/pages/enterprise/EnterpriseSpendPage.js +125 -130
- package/dist/subscriberbot/pages/enterprise/EnterpriseSpendPage.js.map +1 -1
- package/dist/subscriberbot/pages/negotiations/NegotiationDetailPage.js +94 -95
- package/dist/subscriberbot/pages/negotiations/NegotiationDetailPage.js.map +1 -1
- package/dist/subscriberbot/pages/negotiations/NegotiationNewPage.js +15 -16
- package/dist/subscriberbot/pages/negotiations/NegotiationNewPage.js.map +1 -1
- package/dist/subscriberbot/pages/negotiations/NegotiationsPage.js +20 -21
- package/dist/subscriberbot/pages/negotiations/NegotiationsPage.js.map +1 -1
- package/dist/subscriberbot/pages/procurement/ProcurementDetailPage.js +86 -87
- package/dist/subscriberbot/pages/procurement/ProcurementDetailPage.js.map +1 -1
- package/dist/subscriberbot/pages/procurement/ProcurementNewPage.js +164 -165
- package/dist/subscriberbot/pages/procurement/ProcurementNewPage.js.map +1 -1
- package/dist/subscriberbot/pages/procurement/ProcurementPage.js +20 -21
- package/dist/subscriberbot/pages/procurement/ProcurementPage.js.map +1 -1
- package/dist/subscriberbot/pages/providers/ProviderDetailPage.js +350 -351
- package/dist/subscriberbot/pages/providers/ProviderDetailPage.js.map +1 -1
- package/dist/subscriberbot/pages/providers/ProviderInsights.js +95 -96
- package/dist/subscriberbot/pages/providers/ProviderInsights.js.map +1 -1
- package/dist/subscriberbot/pages/providers/ProviderNewPage.js +11 -12
- package/dist/subscriberbot/pages/providers/ProviderNewPage.js.map +1 -1
- package/dist/subscriberbot/pages/providers/ProvidersListPage.js +62 -63
- package/dist/subscriberbot/pages/providers/ProvidersListPage.js.map +1 -1
- package/dist/subscriberbot/pages/relationships/RelationshipDetailPage.js +166 -172
- package/dist/subscriberbot/pages/relationships/RelationshipDetailPage.js.map +1 -1
- package/dist/subscriberbot/pages/relationships/RelationshipNewPage.js +12 -13
- package/dist/subscriberbot/pages/relationships/RelationshipNewPage.js.map +1 -1
- package/dist/subscriberbot/pages/relationships/RelationshipsListPage.js +21 -22
- package/dist/subscriberbot/pages/relationships/RelationshipsListPage.js.map +1 -1
- package/dist/subscriberbot/pages/workflows/WorkflowBuilderPage.js +242 -255
- package/dist/subscriberbot/pages/workflows/WorkflowBuilderPage.js.map +1 -1
- package/dist/subscriberbot/pages/workflows/workflowBuilderGraph.js +2 -3
- package/dist/subscriberbot/pages/workflows/workflowBuilderGraph.js.map +1 -1
- package/dist/subscriberbot/services/createSandboxAssistantTransport.js +1 -2
- package/dist/subscriberbot/services/createSandboxAssistantTransport.js.map +1 -1
- package/dist/subscriberbot/store/index.js +1 -1
- package/dist/subscriberbot/store/subscriberbotStore.js +1 -2
- package/dist/subscriberbot/store/subscriberbotStore.js.map +1 -1
- package/dist/subscriberbot/utils/bankRedirectLink.js +18 -19
- package/dist/subscriberbot/utils/bankRedirectLink.js.map +1 -1
- package/dist/subscriberbot/utils/chartScale.js +1 -2
- package/dist/subscriberbot/utils/chartScale.js.map +1 -1
- package/dist/subscriberbot/utils/cn.js +2 -3
- package/dist/subscriberbot/utils/cn.js.map +1 -1
- package/dist/subscriberbot/utils/formatters.js +4 -5
- package/dist/subscriberbot/utils/formatters.js.map +1 -1
- package/dist/subscriberbot/utils/navigation.js +1 -2
- package/dist/subscriberbot/utils/navigation.js.map +1 -1
- package/dist/subscriberbot/utils/pageContext.js +3 -4
- package/dist/subscriberbot/utils/pageContext.js.map +1 -1
- package/dist/subscriberbot/utils/plaidLink.js +21 -22
- package/dist/subscriberbot/utils/plaidLink.js.map +1 -1
- package/dist/subscriberbot/utils/portfolio.d.ts +4 -3
- package/dist/subscriberbot/utils/portfolio.d.ts.map +1 -1
- package/dist/subscriberbot/utils/portfolio.js +10 -11
- package/dist/subscriberbot/utils/portfolio.js.map +1 -1
- package/dist/subscriberbot/utils/renewals.js +1 -2
- package/dist/subscriberbot/utils/renewals.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/subscriberbot/components/savings/savingsModel.ts
|
|
2
2
|
var e = [
|
|
3
3
|
{
|
|
4
4
|
id: "cancel",
|
|
@@ -101,7 +101,6 @@ function f(e) {
|
|
|
101
101
|
let n = Number(t);
|
|
102
102
|
return Number.isFinite(n) && n >= 0 ? n : NaN;
|
|
103
103
|
}
|
|
104
|
-
|
|
105
|
-
export { e as SAVINGS_SECTIONS, c as bundleMembers, r as groupDecisions, o as headlineAmounts, a as joinAmounts, f as parseBundledAmount, s as perMonth, d as projectedConsolidationSavings, i as savingsByCurrency, n as sectionOf };
|
|
104
|
+
export { e as SAVINGS_SECTIONS, u as annualCost, c as bundleMembers, r as groupDecisions, o as headlineAmounts, a as joinAmounts, f as parseBundledAmount, s as perMonth, d as projectedConsolidationSavings, i as savingsByCurrency, n as sectionOf };
|
|
106
105
|
|
|
107
106
|
//# sourceMappingURL=savingsModel.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"savingsModel.js","names":[],"sources":["../../../../src/subscriberbot/components/savings/savingsModel.ts"],"sourcesContent":["/**\n * Savings dashboard model (BOFF-4001)\n * @module subscriberbot/components/savings\n *\n * Pure helpers behind `/subscriberbot/savings`: how open decisions are grouped\n * into savings sections, how multi-currency totals read, and how a bundle's\n * consolidation is described. No data lives here; everything is computed from\n * the `subSavingsOverview` and `subListDecisions` responses.\n */\n\nimport type {\n SubOverlap,\n SubOverlapMember,\n SubDecision,\n SubDecisionRecommendation,\n SubSavingsTotal,\n} from '../../types';\n\n/** The savings sections, in the order the dashboard shows them. */\nexport type SavingsSectionId = 'cancel' | 'downgrade' | 'annual' | 'other';\n\nexport const SAVINGS_SECTIONS: Array<{\n id: SavingsSectionId;\n key: string;\n fallback: string;\n descriptionKey: string;\n descriptionFallback: string;\n}> = [\n {\n id: 'cancel',\n key: 'savings.sections.cancel',\n fallback: 'Cancel unused',\n descriptionKey: 'savings.sections.cancelDescription',\n descriptionFallback:\n 'Subscriptions you pay for but no longer use, and trials about to charge you.',\n },\n {\n id: 'downgrade',\n key: 'savings.sections.downgrade',\n fallback: 'Downgrade plan',\n descriptionKey: 'savings.sections.downgradeDescription',\n descriptionFallback: 'A cheaper plan from the same provider covers what you use.',\n },\n {\n id: 'annual',\n key: 'savings.sections.annual',\n fallback: 'Switch to annual',\n descriptionKey: 'savings.sections.annualDescription',\n descriptionFallback: 'The same plan costs less when billed yearly.',\n },\n {\n id: 'other',\n key: 'savings.sections.other',\n fallback: 'Other recommendations',\n descriptionKey: 'savings.sections.otherDescription',\n descriptionFallback: 'Pause, keep after a trial, or let it renew.',\n },\n];\n\nconst SECTION_OF: Record<SubDecisionRecommendation, SavingsSectionId> = {\n CANCEL: 'cancel',\n DOWNGRADE: 'downgrade',\n SWITCH_TO_ANNUAL: 'annual',\n PAUSE: 'other',\n CONVERT_TRIAL: 'other',\n RENEW: 'other',\n};\n\nexport function sectionOf(recommendation: SubDecisionRecommendation): SavingsSectionId {\n return SECTION_OF[recommendation];\n}\n\n/**\n * Open decisions grouped into sections, biggest saving first within each.\n * Decisions that are not PROPOSED are left out: only open advice saves money.\n */\nexport function groupDecisions(\n decisions: readonly SubDecision[]\n): Record<SavingsSectionId, SubDecision[]> {\n const groups: Record<SavingsSectionId, SubDecision[]> = {\n cancel: [],\n downgrade: [],\n annual: [],\n other: [],\n };\n for (const decision of decisions) {\n if (decision.status !== 'PROPOSED') continue;\n groups[sectionOf(decision.recommendation)].push(decision);\n }\n for (const list of Object.values(groups)) {\n list.sort(\n (a, b) => b.estimatedSavings - a.estimatedSavings || a.createdAt.localeCompare(b.createdAt)\n );\n }\n return groups;\n}\n\n/** Sum of estimated savings per currency, for a section header. */\nexport function savingsByCurrency(\n decisions: readonly Pick<SubDecision, 'estimatedSavings' | 'currency'>[]\n): Array<{ currency: string; amount: number }> {\n const sums = new Map<string, number>();\n for (const d of decisions) {\n if (!(d.estimatedSavings > 0)) continue;\n sums.set(d.currency, (sums.get(d.currency) ?? 0) + d.estimatedSavings);\n }\n return [...sums.entries()]\n .map(([currency, amount]) => ({ currency, amount: Math.round(amount * 100) / 100 }))\n .sort((a, b) => b.amount - a.amount || a.currency.localeCompare(b.currency));\n}\n\n/** Join per-currency amounts with a formatter: \"$480.00 + €50.00\". Empty list → null. */\nexport function joinAmounts(\n amounts: ReadonlyArray<{ currency: string; amount: number }>,\n format: (amount: number, currency: string) => string\n): string | null {\n const parts = amounts.filter((a) => a.amount > 0).map((a) => format(a.amount, a.currency));\n return parts.length > 0 ? parts.join(' + ') : null;\n}\n\n/** Headline totals as amounts (yearly). */\nexport function headlineAmounts(\n totals: readonly SubSavingsTotal[]\n): Array<{ currency: string; amount: number }> {\n return totals.map((t) => ({ currency: t.currency, amount: t.annualSavings }));\n}\n\n/** Monthly equivalent of a yearly amount, for the \"per month\" sub-line. */\nexport function perMonth(annual: number): number {\n return Math.round((annual / 12) * 100) / 100;\n}\n\n/**\n * A bundle's members split the way consolidating it acts on them: the one it\n * keeps, the ones it cancels, and any it leaves alone because they also cover\n * something the kept one does not.\n */\nexport function bundleMembers(bundle: SubOverlap): {\n keep: SubOverlapMember | null;\n cancel: SubOverlapMember[];\n untouched: SubOverlapMember[];\n} {\n const drop = new Set(bundle.dropRelationshipIds);\n return {\n keep: bundle.members.find((m) => m.relationshipId === bundle.keepRelationshipId) ?? null,\n cancel: bundle.members.filter((m) => drop.has(m.relationshipId)),\n untouched: bundle.members.filter(\n (m) => m.relationshipId !== bundle.keepRelationshipId && !drop.has(m.relationshipId)\n ),\n };\n}\n\nconst PERIODS_PER_YEAR: Record<string, number> = {\n DAILY: 365,\n WEEKLY: 52,\n MONTHLY: 12,\n QUARTERLY: 4,\n YEARLY: 1,\n};\n\n/** Yearly cost of an amount billed every `interval`; 0 for non-recurring intervals. */\nexport function annualCost(amount: number, interval: string): number {\n return Math.round(amount * (PERIODS_PER_YEAR[interval] ?? 0) * 100) / 100;\n}\n\n/**\n * Yearly saving of a consolidation the user is about to confirm: the kept and\n * cancelled subscriptions' yearly cost today minus the kept one afterwards\n * (at the bundled price when one is entered).\n */\nexport function projectedConsolidationSavings(\n bundle: SubOverlap,\n bundledPlan?: { amount: number; interval: string } | null\n): number {\n const { keep, cancel } = bundleMembers(bundle);\n if (!keep) return 0;\n const before = [keep, ...cancel].reduce((sum, m) => sum + annualCost(m.amount, m.interval), 0);\n const after = bundledPlan\n ? annualCost(bundledPlan.amount, bundledPlan.interval)\n : annualCost(keep.amount, keep.interval);\n return Math.round((before - after) * 100) / 100;\n}\n\n/** Parse the optional bundled-plan price field: blank → null, invalid → NaN. */\nexport function parseBundledAmount(raw: string): number | null {\n const trimmed = raw.trim();\n if (trimmed === '') return null;\n const value = Number(trimmed);\n return Number.isFinite(value) && value >= 0 ? value : Number.NaN;\n}\n"],"mappings":";AAqBA,
|
|
1
|
+
{"version":3,"file":"savingsModel.js","names":["SAVINGS_SECTIONS","SECTION_OF","sectionOf","recommendation","groupDecisions","groups","decision","decisions","list","b","a","savingsByCurrency","sums","d","currency","amount","joinAmounts","parts","amounts","format","headlineAmounts","totals","t","perMonth","annual","bundleMembers","drop","bundle","m","PERIODS_PER_YEAR","annualCost","interval","projectedConsolidationSavings","keep","before","cancel","sum","after","bundledPlan","parseBundledAmount","trimmed","raw","value"],"sources":["../../../../src/subscriberbot/components/savings/savingsModel.ts"],"sourcesContent":["/**\n * Savings dashboard model (BOFF-4001)\n * @module subscriberbot/components/savings\n *\n * Pure helpers behind `/subscriberbot/savings`: how open decisions are grouped\n * into savings sections, how multi-currency totals read, and how a bundle's\n * consolidation is described. No data lives here; everything is computed from\n * the `subSavingsOverview` and `subListDecisions` responses.\n */\n\nimport type {\n SubOverlap,\n SubOverlapMember,\n SubDecision,\n SubDecisionRecommendation,\n SubSavingsTotal,\n} from '../../types';\n\n/** The savings sections, in the order the dashboard shows them. */\nexport type SavingsSectionId = 'cancel' | 'downgrade' | 'annual' | 'other';\n\nexport const SAVINGS_SECTIONS: Array<{\n id: SavingsSectionId;\n key: string;\n fallback: string;\n descriptionKey: string;\n descriptionFallback: string;\n}> = [\n {\n id: 'cancel',\n key: 'savings.sections.cancel',\n fallback: 'Cancel unused',\n descriptionKey: 'savings.sections.cancelDescription',\n descriptionFallback:\n 'Subscriptions you pay for but no longer use, and trials about to charge you.',\n },\n {\n id: 'downgrade',\n key: 'savings.sections.downgrade',\n fallback: 'Downgrade plan',\n descriptionKey: 'savings.sections.downgradeDescription',\n descriptionFallback: 'A cheaper plan from the same provider covers what you use.',\n },\n {\n id: 'annual',\n key: 'savings.sections.annual',\n fallback: 'Switch to annual',\n descriptionKey: 'savings.sections.annualDescription',\n descriptionFallback: 'The same plan costs less when billed yearly.',\n },\n {\n id: 'other',\n key: 'savings.sections.other',\n fallback: 'Other recommendations',\n descriptionKey: 'savings.sections.otherDescription',\n descriptionFallback: 'Pause, keep after a trial, or let it renew.',\n },\n];\n\nconst SECTION_OF: Record<SubDecisionRecommendation, SavingsSectionId> = {\n CANCEL: 'cancel',\n DOWNGRADE: 'downgrade',\n SWITCH_TO_ANNUAL: 'annual',\n PAUSE: 'other',\n CONVERT_TRIAL: 'other',\n RENEW: 'other',\n};\n\nexport function sectionOf(recommendation: SubDecisionRecommendation): SavingsSectionId {\n return SECTION_OF[recommendation];\n}\n\n/**\n * Open decisions grouped into sections, biggest saving first within each.\n * Decisions that are not PROPOSED are left out: only open advice saves money.\n */\nexport function groupDecisions(\n decisions: readonly SubDecision[]\n): Record<SavingsSectionId, SubDecision[]> {\n const groups: Record<SavingsSectionId, SubDecision[]> = {\n cancel: [],\n downgrade: [],\n annual: [],\n other: [],\n };\n for (const decision of decisions) {\n if (decision.status !== 'PROPOSED') continue;\n groups[sectionOf(decision.recommendation)].push(decision);\n }\n for (const list of Object.values(groups)) {\n list.sort(\n (a, b) => b.estimatedSavings - a.estimatedSavings || a.createdAt.localeCompare(b.createdAt)\n );\n }\n return groups;\n}\n\n/** Sum of estimated savings per currency, for a section header. */\nexport function savingsByCurrency(\n decisions: readonly Pick<SubDecision, 'estimatedSavings' | 'currency'>[]\n): Array<{ currency: string; amount: number }> {\n const sums = new Map<string, number>();\n for (const d of decisions) {\n if (!(d.estimatedSavings > 0)) continue;\n sums.set(d.currency, (sums.get(d.currency) ?? 0) + d.estimatedSavings);\n }\n return [...sums.entries()]\n .map(([currency, amount]) => ({ currency, amount: Math.round(amount * 100) / 100 }))\n .sort((a, b) => b.amount - a.amount || a.currency.localeCompare(b.currency));\n}\n\n/** Join per-currency amounts with a formatter: \"$480.00 + €50.00\". Empty list → null. */\nexport function joinAmounts(\n amounts: ReadonlyArray<{ currency: string; amount: number }>,\n format: (amount: number, currency: string) => string\n): string | null {\n const parts = amounts.filter((a) => a.amount > 0).map((a) => format(a.amount, a.currency));\n return parts.length > 0 ? parts.join(' + ') : null;\n}\n\n/** Headline totals as amounts (yearly). */\nexport function headlineAmounts(\n totals: readonly SubSavingsTotal[]\n): Array<{ currency: string; amount: number }> {\n return totals.map((t) => ({ currency: t.currency, amount: t.annualSavings }));\n}\n\n/** Monthly equivalent of a yearly amount, for the \"per month\" sub-line. */\nexport function perMonth(annual: number): number {\n return Math.round((annual / 12) * 100) / 100;\n}\n\n/**\n * A bundle's members split the way consolidating it acts on them: the one it\n * keeps, the ones it cancels, and any it leaves alone because they also cover\n * something the kept one does not.\n */\nexport function bundleMembers(bundle: SubOverlap): {\n keep: SubOverlapMember | null;\n cancel: SubOverlapMember[];\n untouched: SubOverlapMember[];\n} {\n const drop = new Set(bundle.dropRelationshipIds);\n return {\n keep: bundle.members.find((m) => m.relationshipId === bundle.keepRelationshipId) ?? null,\n cancel: bundle.members.filter((m) => drop.has(m.relationshipId)),\n untouched: bundle.members.filter(\n (m) => m.relationshipId !== bundle.keepRelationshipId && !drop.has(m.relationshipId)\n ),\n };\n}\n\nconst PERIODS_PER_YEAR: Record<string, number> = {\n DAILY: 365,\n WEEKLY: 52,\n MONTHLY: 12,\n QUARTERLY: 4,\n YEARLY: 1,\n};\n\n/** Yearly cost of an amount billed every `interval`; 0 for non-recurring intervals. */\nexport function annualCost(amount: number, interval: string): number {\n return Math.round(amount * (PERIODS_PER_YEAR[interval] ?? 0) * 100) / 100;\n}\n\n/**\n * Yearly saving of a consolidation the user is about to confirm: the kept and\n * cancelled subscriptions' yearly cost today minus the kept one afterwards\n * (at the bundled price when one is entered).\n */\nexport function projectedConsolidationSavings(\n bundle: SubOverlap,\n bundledPlan?: { amount: number; interval: string } | null\n): number {\n const { keep, cancel } = bundleMembers(bundle);\n if (!keep) return 0;\n const before = [keep, ...cancel].reduce((sum, m) => sum + annualCost(m.amount, m.interval), 0);\n const after = bundledPlan\n ? annualCost(bundledPlan.amount, bundledPlan.interval)\n : annualCost(keep.amount, keep.interval);\n return Math.round((before - after) * 100) / 100;\n}\n\n/** Parse the optional bundled-plan price field: blank → null, invalid → NaN. */\nexport function parseBundledAmount(raw: string): number | null {\n const trimmed = raw.trim();\n if (trimmed === '') return null;\n const value = Number(trimmed);\n return Number.isFinite(value) && value >= 0 ? value : Number.NaN;\n}\n"],"mappings":";AAqBA,IAAaA,IAMR;CACH;EACE,IAAI;EACJ,KAAK;EACL,UAAU;EACV,gBAAgB;EAChB,qBACE;CACJ;CACA;EACE,IAAI;EACJ,KAAK;EACL,UAAU;EACV,gBAAgB;EAChB,qBAAqB;CACvB;CACA;EACE,IAAI;EACJ,KAAK;EACL,UAAU;EACV,gBAAgB;EAChB,qBAAqB;CACvB;CACA;EACE,IAAI;EACJ,KAAK;EACL,UAAU;EACV,gBAAgB;EAChB,qBAAqB;CACvB;AACF,GAEMC,IAAkE;CACtE,QAAQ;CACR,WAAW;CACX,kBAAkB;CAClB,OAAO;CACP,eAAe;CACf,OAAO;AACT;AAEA,SAAgBC,EAAU,GAA6D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";
|
|
|
2
2
|
import { cn as t } from "../utils/cn.js";
|
|
3
3
|
import { niceScale as n } from "../utils/chartScale.js";
|
|
4
4
|
import { jsx as r, jsxs as i } from "react/jsx-runtime";
|
|
5
|
-
|
|
5
|
+
// src/subscriberbot/components/viz.tsx
|
|
6
6
|
var a = [
|
|
7
7
|
"var(--color-chart-1)",
|
|
8
8
|
"var(--color-chart-2)",
|
|
@@ -253,7 +253,7 @@ var a = [
|
|
|
253
253
|
})] }, `y${t}`)),
|
|
254
254
|
M.map((e, t) => /* @__PURE__ */ r("text", {
|
|
255
255
|
x: k(e.getTime()),
|
|
256
|
-
y:
|
|
256
|
+
y: 212,
|
|
257
257
|
textAnchor: t === 0 ? "start" : t === 2 ? "end" : "middle",
|
|
258
258
|
fontSize: 11,
|
|
259
259
|
fill: "var(--color-text-secondary)",
|
|
@@ -307,7 +307,6 @@ var a = [
|
|
|
307
307
|
})]
|
|
308
308
|
});
|
|
309
309
|
};
|
|
310
|
-
//#endregion
|
|
311
310
|
export { m as BarList, a as CHART_COLORS, f as Donut, g as Gauge, p as Legend, y as MiniProgress, w as PriceHistoryChart, h as Sparkline, v as Timeline };
|
|
312
311
|
|
|
313
312
|
//# sourceMappingURL=viz.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"viz.js","names":[],"sources":["../../../src/subscriberbot/components/viz.tsx"],"sourcesContent":["/**\n * Tokenized, responsive SVG visualization primitives.\n * @module subscriberbot/components/viz\n *\n * Every color is a fe-libs semantic CSS variable (never a raw hex), so charts\n * theme automatically in light/dark and per-product themes. All charts scale to\n * their container (SVG viewBox) and carry an accessible role/label.\n */\nimport type { FC, ReactNode } from 'react';\nimport { useTr } from '../hooks/useTr';\nimport { cn } from '../utils/cn';\nimport { niceScale } from '../utils/chartScale';\n\n/** Categorical palette — fe-libs chart tokens. */\nexport const CHART_COLORS = [\n 'var(--color-chart-1)',\n 'var(--color-chart-2)',\n 'var(--color-chart-3)',\n 'var(--color-chart-4)',\n 'var(--color-chart-5)',\n 'var(--color-chart-6)',\n 'var(--color-chart-7)',\n 'var(--color-chart-8)',\n] as const;\n\nconst POSITIVE = 'var(--color-chart-positive)';\nconst NEGATIVE = 'var(--color-chart-negative)';\nconst GRID = 'var(--color-chart-grid)';\nconst WARN = 'var(--color-status-warning-text)';\nconst SUCCESS = 'var(--color-status-success-text)';\n\nexport interface Segment {\n label: string;\n value: number;\n color?: string;\n}\n\nconst colorAt = (i: number, override?: string) => override ?? CHART_COLORS[i % CHART_COLORS.length];\n\n// ---------------------------------------------------------------------------\n// Donut — proportional ring with an optional center label.\n// ---------------------------------------------------------------------------\nexport const Donut: FC<{\n data: Segment[];\n size?: number;\n thickness?: number;\n centerLabel?: string;\n centerSub?: string;\n className?: string;\n}> = ({ data, size = 160, thickness = 18, centerLabel, centerSub, className }) => {\n const total = data.reduce((s, d) => s + Math.max(0, d.value), 0);\n const r = (size - thickness) / 2;\n const c = 2 * Math.PI * r;\n const cx = size / 2;\n let offset = 0;\n const label = data.map((d) => `${d.label}: ${d.value}`).join(', ');\n\n return (\n <div className={cn('relative inline-flex items-center justify-center', className)}>\n <svg\n width={size}\n height={size}\n viewBox={`0 0 ${size} ${size}`}\n role=\"img\"\n aria-label={`Donut chart. ${label}`}\n className=\"max-w-full\"\n >\n <circle\n cx={cx}\n cy={cx}\n r={r}\n fill=\"none\"\n stroke={GRID}\n strokeWidth={thickness}\n opacity={0.4}\n />\n {total > 0 &&\n data.map((d, i) => {\n const frac = Math.max(0, d.value) / total;\n const len = frac * c;\n const seg = (\n <circle\n key={i}\n cx={cx}\n cy={cx}\n r={r}\n fill=\"none\"\n stroke={colorAt(i, d.color)}\n strokeWidth={thickness}\n strokeDasharray={`${len} ${c - len}`}\n strokeDashoffset={-offset}\n strokeLinecap=\"butt\"\n transform={`rotate(-90 ${cx} ${cx})`}\n />\n );\n offset += len;\n return seg;\n })}\n </svg>\n {(centerLabel || centerSub) && (\n <div className=\"absolute inset-0 flex flex-col items-center justify-center text-center\">\n {centerLabel && (\n <span className=\"text-xl font-bold text-text-primary tabular-nums leading-none\">\n {centerLabel}\n </span>\n )}\n {centerSub && <span className=\"mt-1 text-xs text-text-secondary\">{centerSub}</span>}\n </div>\n )}\n </div>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Legend — pairs with Donut / charts.\n// ---------------------------------------------------------------------------\nexport const Legend: FC<{\n data: Segment[];\n valueFormat?: (n: number) => string;\n className?: string;\n}> = ({ data, valueFormat, className }) => (\n <ul className={cn('space-y-2', className)}>\n {data.map((d, i) => (\n <li key={i} className=\"flex items-center gap-2 text-sm\">\n <span\n className=\"h-2.5 w-2.5 shrink-0 rounded-full\"\n style={{ backgroundColor: colorAt(i, d.color) }}\n aria-hidden\n />\n <span className=\"flex-1 truncate text-text-secondary\">{d.label}</span>\n <span className=\"font-medium text-text-primary tabular-nums\">\n {valueFormat ? valueFormat(d.value) : d.value}\n </span>\n </li>\n ))}\n </ul>\n);\n\n// ---------------------------------------------------------------------------\n// BarList — horizontal labelled bars (e.g. spend by category).\n// ---------------------------------------------------------------------------\nexport const BarList: FC<{\n data: Segment[];\n valueFormat?: (n: number) => string;\n className?: string;\n}> = ({ data, valueFormat, className }) => {\n const tr = useTr();\n const max = Math.max(1, ...data.map((d) => d.value));\n return (\n <ul className={cn('space-y-3', className)} aria-label={tr('charts.barLabel', 'Bar chart')}>\n {data.map((d, i) => (\n <li key={i}>\n <div className=\"flex items-center justify-between text-sm\">\n <span className=\"truncate text-text-secondary\">{d.label}</span>\n <span className=\"font-medium text-text-primary tabular-nums\">\n {valueFormat ? valueFormat(d.value) : d.value}\n </span>\n </div>\n <div\n className=\"mt-1.5 h-2 w-full overflow-hidden rounded-full\"\n style={{ backgroundColor: GRID }}\n >\n <div\n className=\"h-full rounded-full transition-all\"\n style={{ width: `${(d.value / max) * 100}%`, backgroundColor: colorAt(i, d.color) }}\n />\n </div>\n </li>\n ))}\n </ul>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Sparkline / area — small trend line.\n// ---------------------------------------------------------------------------\nexport const Sparkline: FC<{\n points: number[];\n width?: number;\n height?: number;\n positive?: boolean;\n className?: string;\n}> = ({ points, width = 220, height = 56, positive = true, className }) => {\n const tr = useTr();\n if (points.length < 2) return null;\n const max = Math.max(...points);\n const min = Math.min(...points);\n const span = max - min || 1;\n const stroke = positive ? POSITIVE : NEGATIVE;\n const step = width / (points.length - 1);\n const coords = points.map((p, i) => [i * step, height - ((p - min) / span) * (height - 8) - 4]);\n const line = coords\n .map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`)\n .join(' ');\n const area = `${line} L${width},${height} L0,${height} Z`;\n return (\n <svg\n width={width}\n height={height}\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label={tr('charts.trendLabel', 'Trend sparkline')}\n className={cn('max-w-full', className)}\n preserveAspectRatio=\"none\"\n >\n <path d={area} fill={stroke} opacity={0.12} />\n <path\n d={line}\n fill=\"none\"\n stroke={stroke}\n strokeWidth={2}\n strokeLinejoin=\"round\"\n strokeLinecap=\"round\"\n />\n </svg>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Gauge — 0..max semicircle (e.g. health score).\n// ---------------------------------------------------------------------------\nexport const Gauge: FC<{\n value: number;\n max?: number;\n size?: number;\n label?: string;\n className?: string;\n}> = ({ value, max = 100, size = 120, label, className }) => {\n const pct = Math.max(0, Math.min(1, value / max));\n const r = size / 2 - 10;\n const cy = size / 2;\n const circ = Math.PI * r; // half circle\n const tone = pct >= 0.66 ? SUCCESS : pct >= 0.33 ? WARN : NEGATIVE;\n return (\n <div className={cn('inline-flex flex-col items-center', className)}>\n <svg\n width={size}\n height={size / 2 + 8}\n viewBox={`0 0 ${size} ${size / 2 + 8}`}\n role=\"img\"\n aria-label={`Gauge: ${Math.round(pct * 100)} percent`}\n className=\"max-w-full\"\n >\n <path\n d={`M10 ${cy} A ${r} ${r} 0 0 1 ${size - 10} ${cy}`}\n fill=\"none\"\n stroke={GRID}\n strokeWidth={10}\n strokeLinecap=\"round\"\n />\n <path\n d={`M10 ${cy} A ${r} ${r} 0 0 1 ${size - 10} ${cy}`}\n fill=\"none\"\n stroke={tone}\n strokeWidth={10}\n strokeLinecap=\"round\"\n strokeDasharray={`${pct * circ} ${circ}`}\n />\n </svg>\n <div className=\"-mt-4 text-center\">\n <span className=\"text-lg font-bold text-text-primary tabular-nums\">\n {Math.round(value)}\n </span>\n {label && <p className=\"text-xs text-text-secondary\">{label}</p>}\n </div>\n </div>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Timeline — vertical events with a connector rail (e.g. renewals).\n// ---------------------------------------------------------------------------\nexport interface TimelineItem {\n title: string;\n sub?: string;\n meta?: ReactNode;\n tone?: 'default' | 'positive' | 'warning' | 'muted';\n}\nconst dotTone: Record<NonNullable<TimelineItem['tone']>, string> = {\n default: 'var(--color-accent-indigo)',\n positive: SUCCESS,\n warning: WARN,\n muted: 'var(--color-text-secondary)',\n};\nexport const Timeline: FC<{ items: TimelineItem[]; className?: string }> = ({\n items,\n className,\n}) => (\n <ol\n className={cn(\n 'relative space-y-5 ps-6 before:absolute before:start-[7px] before:top-1 before:bottom-1 before:w-px before:bg-border-subtle',\n className\n )}\n >\n {items.map((it, i) => (\n <li key={i} className=\"relative\">\n <span\n className=\"absolute -start-[22px] top-1 h-3 w-3 rounded-full ring-4 ring-bg-surface\"\n style={{ backgroundColor: dotTone[it.tone ?? 'default'] }}\n aria-hidden\n />\n <div className=\"flex items-baseline justify-between gap-2\">\n <p className=\"text-sm font-medium text-text-primary\">{it.title}</p>\n {it.meta && <span className=\"text-sm tabular-nums text-text-primary\">{it.meta}</span>}\n </div>\n {it.sub && <p className=\"text-xs text-text-secondary\">{it.sub}</p>}\n </li>\n ))}\n </ol>\n);\n\n// ---------------------------------------------------------------------------\n// MiniProgress — inline utilization bar (e.g. seats used).\n// ---------------------------------------------------------------------------\nexport const MiniProgress: FC<{\n value: number;\n max?: number;\n label: string;\n tone?: 'accent' | 'positive' | 'warning' | 'negative';\n className?: string;\n}> = ({ value, max = 100, label, tone = 'accent', className }) => {\n const pct = Math.max(0, Math.min(1, max ? value / max : 0));\n const color =\n tone === 'positive'\n ? SUCCESS\n : tone === 'warning'\n ? WARN\n : tone === 'negative'\n ? NEGATIVE\n : 'var(--color-accent-indigo)';\n return (\n <div\n className={cn('h-2 w-full overflow-hidden rounded-full', className)}\n style={{ backgroundColor: GRID }}\n role=\"progressbar\"\n aria-label={label}\n aria-valuenow={Math.round(pct * 100)}\n aria-valuemin={0}\n aria-valuemax={100}\n >\n <div\n className=\"h-full rounded-full transition-all\"\n style={{ width: `${pct * 100}%`, backgroundColor: color }}\n />\n </div>\n );\n};\n\n// ---------------------------------------------------------------------------\n// PriceHistoryChart — prices over time on a real date axis (BOFF-4003).\n// ---------------------------------------------------------------------------\n// Recorded prices are drawn as step lines (a price holds until it changes, and\n// the last one holds until `now`). A point with a null value is a price with no\n// monthly equivalent (lifetime, usage-based): the line stops there and resumes\n// at the next recurring price. Invoice charges are drawn as dots only,\n// since each one is a separate charge rather than a continuing price. Every\n// series must share one currency: the caller filters before passing data in.\nexport interface PriceChartPoint {\n /** ISO timestamp. */\n at: string;\n /** Monthly value; null ends a step line here (no monthly equivalent). */\n value: number | null;\n /** Text for the point's native tooltip. */\n title?: string;\n}\n\nexport interface PriceChartSeries {\n key: string;\n label: string;\n points: PriceChartPoint[];\n /** `step` holds each value until the next point; `dots` draws points only. */\n mode: 'step' | 'dots';\n}\n\nconst CHART_W = 640;\nconst CHART_H = 220;\nconst PAD = { top: 12, right: 16, bottom: 28, left: 64 };\nconst DAY_MS = 86_400_000;\n\nexport const PriceHistoryChart: FC<{\n series: PriceChartSeries[];\n /**\n * Formats a y-axis value (e.g. as currency). `fractionDigits` is the\n * precision the axis step needs so neighbouring labels never repeat.\n */\n valueFormat: (n: number, fractionDigits: number) => string;\n /** Formats an x-axis date. */\n dateFormat: (d: Date) => string;\n /** Right edge of the time axis; defaults to the latest point. */\n now?: Date;\n ariaLabel: string;\n className?: string;\n}> = ({ series, valueFormat, dateFormat, now, ariaLabel, className }) => {\n const all = series.flatMap((s) => s.points);\n const values = all.flatMap((p) => (p.value === null ? [] : [p.value]));\n if (values.length === 0) return null;\n\n const times = all.map((p) => new Date(p.at).getTime());\n let t0 = Math.min(...times);\n let t1 = Math.max(...times, now ? now.getTime() : Number.NEGATIVE_INFINITY);\n if (t1 - t0 < DAY_MS) {\n t0 -= 15 * DAY_MS;\n t1 += 15 * DAY_MS;\n }\n const vMin = Math.min(...values);\n const vMax = Math.max(...values);\n const vPad = vMax === vMin ? Math.max(Math.abs(vMax) * 0.2, 1) : (vMax - vMin) * 0.15;\n // Round the padded range out to a nice step so each gridline label is the\n // exact value it marks (never 9.7 / 10.47 / ... shown as \"$10, $11, $11\").\n const scale = niceScale(vMin >= 0 ? Math.max(0, vMin - vPad) : vMin - vPad, vMax + vPad, 4);\n const y0 = scale.min;\n const y1 = scale.max;\n\n const plotW = CHART_W - PAD.left - PAD.right;\n const plotH = CHART_H - PAD.top - PAD.bottom;\n const x = (t: number) => PAD.left + ((t - t0) / (t1 - t0)) * plotW;\n const y = (v: number) => PAD.top + plotH - ((v - y0) / (y1 - y0)) * plotH;\n\n const yTicks = scale.ticks;\n const xTicks = [0, 0.5, 1].map((f) => new Date(t0 + (t1 - t0) * f));\n\n return (\n <div className={cn('w-full', className)}>\n <svg\n viewBox={`0 0 ${CHART_W} ${CHART_H}`}\n role=\"img\"\n aria-label={ariaLabel}\n className=\"h-auto w-full\"\n >\n {yTicks.map((v, i) => (\n <g key={`y${i}`}>\n <line\n x1={PAD.left}\n x2={CHART_W - PAD.right}\n y1={y(v)}\n y2={y(v)}\n stroke={GRID}\n strokeWidth={1}\n />\n <text\n x={PAD.left - 8}\n y={y(v) + 4}\n textAnchor=\"end\"\n fontSize={11}\n fill=\"var(--color-text-secondary)\"\n >\n {valueFormat(v, scale.fractionDigits)}\n </text>\n </g>\n ))}\n {xTicks.map((d, i) => (\n <text\n key={`x${i}`}\n x={x(d.getTime())}\n y={CHART_H - 8}\n textAnchor={i === 0 ? 'start' : i === 2 ? 'end' : 'middle'}\n fontSize={11}\n fill=\"var(--color-text-secondary)\"\n >\n {dateFormat(d)}\n </text>\n ))}\n {series.map((s, si) => {\n const color = colorAt(si);\n const pts = [...s.points].sort(\n (a, b) => new Date(a.at).getTime() - new Date(b.at).getTime()\n );\n let path = '';\n if (s.mode === 'step') {\n // A segment runs from a recurring price to the next point; a null\n // point ends it, and the next recurring price starts a new one.\n let open = false;\n for (const p of pts) {\n const px = x(new Date(p.at).getTime()).toFixed(1);\n if (p.value === null) {\n if (open) path += ` H${px}`;\n open = false;\n continue;\n }\n const py = y(p.value).toFixed(1);\n path += open ? ` H${px} V${py}` : ` M${px},${py}`;\n open = true;\n }\n if (open) path += ` H${x(t1).toFixed(1)}`;\n path = path.trim();\n }\n return (\n <g key={s.key} data-series={s.key}>\n {path && (\n <path d={path} fill=\"none\" stroke={color} strokeWidth={2} strokeLinejoin=\"round\" />\n )}\n {pts.map((p, i) =>\n p.value === null ? null : (\n <circle\n key={`${s.key}-${i}`}\n cx={x(new Date(p.at).getTime())}\n cy={y(p.value)}\n r={s.mode === 'dots' ? 3.5 : 4}\n fill={s.mode === 'dots' ? 'var(--color-bg-surface)' : color}\n stroke={color}\n strokeWidth={2}\n >\n {p.title && <title>{p.title}</title>}\n </circle>\n )\n )}\n </g>\n );\n })}\n </svg>\n <ul className=\"mt-2 flex flex-wrap gap-x-4 gap-y-1\">\n {series.map((s, si) => (\n <li key={s.key} className=\"flex items-center gap-1.5 text-xs text-text-secondary\">\n <span\n className={cn(\n 'h-2.5 w-2.5 shrink-0',\n s.mode === 'dots' ? 'rounded-full border-2' : 'rounded-sm'\n )}\n style={\n s.mode === 'dots' ? { borderColor: colorAt(si) } : { backgroundColor: colorAt(si) }\n }\n aria-hidden\n />\n {s.label}\n </li>\n ))}\n </ul>\n </div>\n );\n};\n"],"mappings":";;;;;AAcA,IAA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mBP;IAEP,CAAC;GACE;MACL,kBAAC,MAAD;GAAI,WAAU;aACX,EAAO,KAAK,GAAG,MACd,kBAAC,MAAD;IAAgB,WAAU;cAA1B,CACE,kBAAC,QAAD;KACE,WAAW,EACT,wBACA,EAAE,SAAS,SAAS,0BAA0B,YAChD;KACA,OACE,EAAE,SAAS,SAAS,EAAE,aAAa,EAAQ,CAAE,EAAE,IAAI,EAAE,iBAAiB,EAAQ,CAAE,EAAE;KAEpF,eAAA;IACD,CAAA,GACA,EAAE,KACD;MAZK,EAAE,GAYP,CACL;EACC,CAAA,CACD;;AAET"}
|
|
1
|
+
{"version":3,"file":"viz.js","names":["CHART_COLORS","POSITIVE","NEGATIVE","GRID","WARN","SUCCESS","colorAt","override","i","Donut","total","data","s","d","r","size","thickness","c","cx","offset","label","cn","className","len","seg","centerLabel","centerSub","Legend","valueFormat","BarList","tr","useTr","max","Sparkline","points","min","span","stroke","positive","step","width","line","height","p","x","y","area","Gauge","pct","value","cy","circ","tone","dotTone","Timeline","items","it","MiniProgress","color","CHART_W","CHART_H","PAD","DAY_MS","PriceHistoryChart","all","series","values","times","t0","t1","now","vMin","vMax","vPad","scale","niceScale","y0","y1","plotW","plotH","t","v","yTicks","xTicks","f","ariaLabel","dateFormat","si","pts","a","b","path","open","px","py"],"sources":["../../../src/subscriberbot/components/viz.tsx"],"sourcesContent":["/**\n * Tokenized, responsive SVG visualization primitives.\n * @module subscriberbot/components/viz\n *\n * Every color is a fe-libs semantic CSS variable (never a raw hex), so charts\n * theme automatically in light/dark and per-product themes. All charts scale to\n * their container (SVG viewBox) and carry an accessible role/label.\n */\nimport type { FC, ReactNode } from 'react';\nimport { useTr } from '../hooks/useTr';\nimport { cn } from '../utils/cn';\nimport { niceScale } from '../utils/chartScale';\n\n/** Categorical palette — fe-libs chart tokens. */\nexport const CHART_COLORS = [\n 'var(--color-chart-1)',\n 'var(--color-chart-2)',\n 'var(--color-chart-3)',\n 'var(--color-chart-4)',\n 'var(--color-chart-5)',\n 'var(--color-chart-6)',\n 'var(--color-chart-7)',\n 'var(--color-chart-8)',\n] as const;\n\nconst POSITIVE = 'var(--color-chart-positive)';\nconst NEGATIVE = 'var(--color-chart-negative)';\nconst GRID = 'var(--color-chart-grid)';\nconst WARN = 'var(--color-status-warning-text)';\nconst SUCCESS = 'var(--color-status-success-text)';\n\nexport interface Segment {\n label: string;\n value: number;\n color?: string;\n}\n\nconst colorAt = (i: number, override?: string) => override ?? CHART_COLORS[i % CHART_COLORS.length];\n\n// ---------------------------------------------------------------------------\n// Donut — proportional ring with an optional center label.\n// ---------------------------------------------------------------------------\nexport const Donut: FC<{\n data: Segment[];\n size?: number;\n thickness?: number;\n centerLabel?: string;\n centerSub?: string;\n className?: string;\n}> = ({ data, size = 160, thickness = 18, centerLabel, centerSub, className }) => {\n const total = data.reduce((s, d) => s + Math.max(0, d.value), 0);\n const r = (size - thickness) / 2;\n const c = 2 * Math.PI * r;\n const cx = size / 2;\n let offset = 0;\n const label = data.map((d) => `${d.label}: ${d.value}`).join(', ');\n\n return (\n <div className={cn('relative inline-flex items-center justify-center', className)}>\n <svg\n width={size}\n height={size}\n viewBox={`0 0 ${size} ${size}`}\n role=\"img\"\n aria-label={`Donut chart. ${label}`}\n className=\"max-w-full\"\n >\n <circle\n cx={cx}\n cy={cx}\n r={r}\n fill=\"none\"\n stroke={GRID}\n strokeWidth={thickness}\n opacity={0.4}\n />\n {total > 0 &&\n data.map((d, i) => {\n const frac = Math.max(0, d.value) / total;\n const len = frac * c;\n const seg = (\n <circle\n key={i}\n cx={cx}\n cy={cx}\n r={r}\n fill=\"none\"\n stroke={colorAt(i, d.color)}\n strokeWidth={thickness}\n strokeDasharray={`${len} ${c - len}`}\n strokeDashoffset={-offset}\n strokeLinecap=\"butt\"\n transform={`rotate(-90 ${cx} ${cx})`}\n />\n );\n offset += len;\n return seg;\n })}\n </svg>\n {(centerLabel || centerSub) && (\n <div className=\"absolute inset-0 flex flex-col items-center justify-center text-center\">\n {centerLabel && (\n <span className=\"text-xl font-bold text-text-primary tabular-nums leading-none\">\n {centerLabel}\n </span>\n )}\n {centerSub && <span className=\"mt-1 text-xs text-text-secondary\">{centerSub}</span>}\n </div>\n )}\n </div>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Legend — pairs with Donut / charts.\n// ---------------------------------------------------------------------------\nexport const Legend: FC<{\n data: Segment[];\n valueFormat?: (n: number) => string;\n className?: string;\n}> = ({ data, valueFormat, className }) => (\n <ul className={cn('space-y-2', className)}>\n {data.map((d, i) => (\n <li key={i} className=\"flex items-center gap-2 text-sm\">\n <span\n className=\"h-2.5 w-2.5 shrink-0 rounded-full\"\n style={{ backgroundColor: colorAt(i, d.color) }}\n aria-hidden\n />\n <span className=\"flex-1 truncate text-text-secondary\">{d.label}</span>\n <span className=\"font-medium text-text-primary tabular-nums\">\n {valueFormat ? valueFormat(d.value) : d.value}\n </span>\n </li>\n ))}\n </ul>\n);\n\n// ---------------------------------------------------------------------------\n// BarList — horizontal labelled bars (e.g. spend by category).\n// ---------------------------------------------------------------------------\nexport const BarList: FC<{\n data: Segment[];\n valueFormat?: (n: number) => string;\n className?: string;\n}> = ({ data, valueFormat, className }) => {\n const tr = useTr();\n const max = Math.max(1, ...data.map((d) => d.value));\n return (\n <ul className={cn('space-y-3', className)} aria-label={tr('charts.barLabel', 'Bar chart')}>\n {data.map((d, i) => (\n <li key={i}>\n <div className=\"flex items-center justify-between text-sm\">\n <span className=\"truncate text-text-secondary\">{d.label}</span>\n <span className=\"font-medium text-text-primary tabular-nums\">\n {valueFormat ? valueFormat(d.value) : d.value}\n </span>\n </div>\n <div\n className=\"mt-1.5 h-2 w-full overflow-hidden rounded-full\"\n style={{ backgroundColor: GRID }}\n >\n <div\n className=\"h-full rounded-full transition-all\"\n style={{ width: `${(d.value / max) * 100}%`, backgroundColor: colorAt(i, d.color) }}\n />\n </div>\n </li>\n ))}\n </ul>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Sparkline / area — small trend line.\n// ---------------------------------------------------------------------------\nexport const Sparkline: FC<{\n points: number[];\n width?: number;\n height?: number;\n positive?: boolean;\n className?: string;\n}> = ({ points, width = 220, height = 56, positive = true, className }) => {\n const tr = useTr();\n if (points.length < 2) return null;\n const max = Math.max(...points);\n const min = Math.min(...points);\n const span = max - min || 1;\n const stroke = positive ? POSITIVE : NEGATIVE;\n const step = width / (points.length - 1);\n const coords = points.map((p, i) => [i * step, height - ((p - min) / span) * (height - 8) - 4]);\n const line = coords\n .map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`)\n .join(' ');\n const area = `${line} L${width},${height} L0,${height} Z`;\n return (\n <svg\n width={width}\n height={height}\n viewBox={`0 0 ${width} ${height}`}\n role=\"img\"\n aria-label={tr('charts.trendLabel', 'Trend sparkline')}\n className={cn('max-w-full', className)}\n preserveAspectRatio=\"none\"\n >\n <path d={area} fill={stroke} opacity={0.12} />\n <path\n d={line}\n fill=\"none\"\n stroke={stroke}\n strokeWidth={2}\n strokeLinejoin=\"round\"\n strokeLinecap=\"round\"\n />\n </svg>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Gauge — 0..max semicircle (e.g. health score).\n// ---------------------------------------------------------------------------\nexport const Gauge: FC<{\n value: number;\n max?: number;\n size?: number;\n label?: string;\n className?: string;\n}> = ({ value, max = 100, size = 120, label, className }) => {\n const pct = Math.max(0, Math.min(1, value / max));\n const r = size / 2 - 10;\n const cy = size / 2;\n const circ = Math.PI * r; // half circle\n const tone = pct >= 0.66 ? SUCCESS : pct >= 0.33 ? WARN : NEGATIVE;\n return (\n <div className={cn('inline-flex flex-col items-center', className)}>\n <svg\n width={size}\n height={size / 2 + 8}\n viewBox={`0 0 ${size} ${size / 2 + 8}`}\n role=\"img\"\n aria-label={`Gauge: ${Math.round(pct * 100)} percent`}\n className=\"max-w-full\"\n >\n <path\n d={`M10 ${cy} A ${r} ${r} 0 0 1 ${size - 10} ${cy}`}\n fill=\"none\"\n stroke={GRID}\n strokeWidth={10}\n strokeLinecap=\"round\"\n />\n <path\n d={`M10 ${cy} A ${r} ${r} 0 0 1 ${size - 10} ${cy}`}\n fill=\"none\"\n stroke={tone}\n strokeWidth={10}\n strokeLinecap=\"round\"\n strokeDasharray={`${pct * circ} ${circ}`}\n />\n </svg>\n <div className=\"-mt-4 text-center\">\n <span className=\"text-lg font-bold text-text-primary tabular-nums\">\n {Math.round(value)}\n </span>\n {label && <p className=\"text-xs text-text-secondary\">{label}</p>}\n </div>\n </div>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Timeline — vertical events with a connector rail (e.g. renewals).\n// ---------------------------------------------------------------------------\nexport interface TimelineItem {\n title: string;\n sub?: string;\n meta?: ReactNode;\n tone?: 'default' | 'positive' | 'warning' | 'muted';\n}\nconst dotTone: Record<NonNullable<TimelineItem['tone']>, string> = {\n default: 'var(--color-accent-indigo)',\n positive: SUCCESS,\n warning: WARN,\n muted: 'var(--color-text-secondary)',\n};\nexport const Timeline: FC<{ items: TimelineItem[]; className?: string }> = ({\n items,\n className,\n}) => (\n <ol\n className={cn(\n 'relative space-y-5 ps-6 before:absolute before:start-[7px] before:top-1 before:bottom-1 before:w-px before:bg-border-subtle',\n className\n )}\n >\n {items.map((it, i) => (\n <li key={i} className=\"relative\">\n <span\n className=\"absolute -start-[22px] top-1 h-3 w-3 rounded-full ring-4 ring-bg-surface\"\n style={{ backgroundColor: dotTone[it.tone ?? 'default'] }}\n aria-hidden\n />\n <div className=\"flex items-baseline justify-between gap-2\">\n <p className=\"text-sm font-medium text-text-primary\">{it.title}</p>\n {it.meta && <span className=\"text-sm tabular-nums text-text-primary\">{it.meta}</span>}\n </div>\n {it.sub && <p className=\"text-xs text-text-secondary\">{it.sub}</p>}\n </li>\n ))}\n </ol>\n);\n\n// ---------------------------------------------------------------------------\n// MiniProgress — inline utilization bar (e.g. seats used).\n// ---------------------------------------------------------------------------\nexport const MiniProgress: FC<{\n value: number;\n max?: number;\n label: string;\n tone?: 'accent' | 'positive' | 'warning' | 'negative';\n className?: string;\n}> = ({ value, max = 100, label, tone = 'accent', className }) => {\n const pct = Math.max(0, Math.min(1, max ? value / max : 0));\n const color =\n tone === 'positive'\n ? SUCCESS\n : tone === 'warning'\n ? WARN\n : tone === 'negative'\n ? NEGATIVE\n : 'var(--color-accent-indigo)';\n return (\n <div\n className={cn('h-2 w-full overflow-hidden rounded-full', className)}\n style={{ backgroundColor: GRID }}\n role=\"progressbar\"\n aria-label={label}\n aria-valuenow={Math.round(pct * 100)}\n aria-valuemin={0}\n aria-valuemax={100}\n >\n <div\n className=\"h-full rounded-full transition-all\"\n style={{ width: `${pct * 100}%`, backgroundColor: color }}\n />\n </div>\n );\n};\n\n// ---------------------------------------------------------------------------\n// PriceHistoryChart — prices over time on a real date axis (BOFF-4003).\n// ---------------------------------------------------------------------------\n// Recorded prices are drawn as step lines (a price holds until it changes, and\n// the last one holds until `now`). A point with a null value is a price with no\n// monthly equivalent (lifetime, usage-based): the line stops there and resumes\n// at the next recurring price. Invoice charges are drawn as dots only,\n// since each one is a separate charge rather than a continuing price. Every\n// series must share one currency: the caller filters before passing data in.\nexport interface PriceChartPoint {\n /** ISO timestamp. */\n at: string;\n /** Monthly value; null ends a step line here (no monthly equivalent). */\n value: number | null;\n /** Text for the point's native tooltip. */\n title?: string;\n}\n\nexport interface PriceChartSeries {\n key: string;\n label: string;\n points: PriceChartPoint[];\n /** `step` holds each value until the next point; `dots` draws points only. */\n mode: 'step' | 'dots';\n}\n\nconst CHART_W = 640;\nconst CHART_H = 220;\nconst PAD = { top: 12, right: 16, bottom: 28, left: 64 };\nconst DAY_MS = 86_400_000;\n\nexport const PriceHistoryChart: FC<{\n series: PriceChartSeries[];\n /**\n * Formats a y-axis value (e.g. as currency). `fractionDigits` is the\n * precision the axis step needs so neighbouring labels never repeat.\n */\n valueFormat: (n: number, fractionDigits: number) => string;\n /** Formats an x-axis date. */\n dateFormat: (d: Date) => string;\n /** Right edge of the time axis; defaults to the latest point. */\n now?: Date;\n ariaLabel: string;\n className?: string;\n}> = ({ series, valueFormat, dateFormat, now, ariaLabel, className }) => {\n const all = series.flatMap((s) => s.points);\n const values = all.flatMap((p) => (p.value === null ? [] : [p.value]));\n if (values.length === 0) return null;\n\n const times = all.map((p) => new Date(p.at).getTime());\n let t0 = Math.min(...times);\n let t1 = Math.max(...times, now ? now.getTime() : Number.NEGATIVE_INFINITY);\n if (t1 - t0 < DAY_MS) {\n t0 -= 15 * DAY_MS;\n t1 += 15 * DAY_MS;\n }\n const vMin = Math.min(...values);\n const vMax = Math.max(...values);\n const vPad = vMax === vMin ? Math.max(Math.abs(vMax) * 0.2, 1) : (vMax - vMin) * 0.15;\n // Round the padded range out to a nice step so each gridline label is the\n // exact value it marks (never 9.7 / 10.47 / ... shown as \"$10, $11, $11\").\n const scale = niceScale(vMin >= 0 ? Math.max(0, vMin - vPad) : vMin - vPad, vMax + vPad, 4);\n const y0 = scale.min;\n const y1 = scale.max;\n\n const plotW = CHART_W - PAD.left - PAD.right;\n const plotH = CHART_H - PAD.top - PAD.bottom;\n const x = (t: number) => PAD.left + ((t - t0) / (t1 - t0)) * plotW;\n const y = (v: number) => PAD.top + plotH - ((v - y0) / (y1 - y0)) * plotH;\n\n const yTicks = scale.ticks;\n const xTicks = [0, 0.5, 1].map((f) => new Date(t0 + (t1 - t0) * f));\n\n return (\n <div className={cn('w-full', className)}>\n <svg\n viewBox={`0 0 ${CHART_W} ${CHART_H}`}\n role=\"img\"\n aria-label={ariaLabel}\n className=\"h-auto w-full\"\n >\n {yTicks.map((v, i) => (\n <g key={`y${i}`}>\n <line\n x1={PAD.left}\n x2={CHART_W - PAD.right}\n y1={y(v)}\n y2={y(v)}\n stroke={GRID}\n strokeWidth={1}\n />\n <text\n x={PAD.left - 8}\n y={y(v) + 4}\n textAnchor=\"end\"\n fontSize={11}\n fill=\"var(--color-text-secondary)\"\n >\n {valueFormat(v, scale.fractionDigits)}\n </text>\n </g>\n ))}\n {xTicks.map((d, i) => (\n <text\n key={`x${i}`}\n x={x(d.getTime())}\n y={CHART_H - 8}\n textAnchor={i === 0 ? 'start' : i === 2 ? 'end' : 'middle'}\n fontSize={11}\n fill=\"var(--color-text-secondary)\"\n >\n {dateFormat(d)}\n </text>\n ))}\n {series.map((s, si) => {\n const color = colorAt(si);\n const pts = [...s.points].sort(\n (a, b) => new Date(a.at).getTime() - new Date(b.at).getTime()\n );\n let path = '';\n if (s.mode === 'step') {\n // A segment runs from a recurring price to the next point; a null\n // point ends it, and the next recurring price starts a new one.\n let open = false;\n for (const p of pts) {\n const px = x(new Date(p.at).getTime()).toFixed(1);\n if (p.value === null) {\n if (open) path += ` H${px}`;\n open = false;\n continue;\n }\n const py = y(p.value).toFixed(1);\n path += open ? ` H${px} V${py}` : ` M${px},${py}`;\n open = true;\n }\n if (open) path += ` H${x(t1).toFixed(1)}`;\n path = path.trim();\n }\n return (\n <g key={s.key} data-series={s.key}>\n {path && (\n <path d={path} fill=\"none\" stroke={color} strokeWidth={2} strokeLinejoin=\"round\" />\n )}\n {pts.map((p, i) =>\n p.value === null ? null : (\n <circle\n key={`${s.key}-${i}`}\n cx={x(new Date(p.at).getTime())}\n cy={y(p.value)}\n r={s.mode === 'dots' ? 3.5 : 4}\n fill={s.mode === 'dots' ? 'var(--color-bg-surface)' : color}\n stroke={color}\n strokeWidth={2}\n >\n {p.title && <title>{p.title}</title>}\n </circle>\n )\n )}\n </g>\n );\n })}\n </svg>\n <ul className=\"mt-2 flex flex-wrap gap-x-4 gap-y-1\">\n {series.map((s, si) => (\n <li key={s.key} className=\"flex items-center gap-1.5 text-xs text-text-secondary\">\n <span\n className={cn(\n 'h-2.5 w-2.5 shrink-0',\n s.mode === 'dots' ? 'rounded-full border-2' : 'rounded-sm'\n )}\n style={\n s.mode === 'dots' ? { borderColor: colorAt(si) } : { backgroundColor: colorAt(si) }\n }\n aria-hidden\n />\n {s.label}\n </li>\n ))}\n </ul>\n </div>\n );\n};\n"],"mappings":";;;;;AAcA,IAAaA,IAAe;CAC1B;C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E,KACD;GAZK,GAAAA,EAAE,GAYP,CACL;EACC,CAAA,CACD;;AAET"}
|
|
@@ -2,7 +2,7 @@ import { joinPath as e } from "../utils/navigation.js";
|
|
|
2
2
|
import { createContext as t, useCallback as n, useContext as r, useMemo as i } from "react";
|
|
3
3
|
import { MemoryRouter as a, useNavigate as o } from "react-router";
|
|
4
4
|
import { jsx as s } from "react/jsx-runtime";
|
|
5
|
-
|
|
5
|
+
// src/subscriberbot/context/SubscriberBotContext.tsx
|
|
6
6
|
var c = t(null);
|
|
7
7
|
function l() {
|
|
8
8
|
let e = r(c);
|
|
@@ -11,7 +11,8 @@ function l() {
|
|
|
11
11
|
}
|
|
12
12
|
var u = ({ children: t, basePath: r, currentUser: a, tenantId: l, workspaceId: u, apiGatewayUrl: d, authToken: f }) => {
|
|
13
13
|
let p = o(), m = r || "/", h = n((t) => e(m, t), [m]), g = n((t) => {
|
|
14
|
-
|
|
14
|
+
let n = e(m, t);
|
|
15
|
+
p(n);
|
|
15
16
|
}, [m, p]), _ = i(() => ({
|
|
16
17
|
basePath: m,
|
|
17
18
|
navigate: void 0,
|
|
@@ -79,7 +80,6 @@ var u = ({ children: t, basePath: r, currentUser: a, tenantId: l, workspaceId: u
|
|
|
79
80
|
children: t
|
|
80
81
|
}) });
|
|
81
82
|
};
|
|
82
|
-
//#endregion
|
|
83
83
|
export { f as SubscriberBotProvider, l as useSubscriberBot };
|
|
84
84
|
|
|
85
85
|
//# sourceMappingURL=SubscriberBotContext.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriberBotContext.js","names":[],"sources":["../../../src/subscriberbot/context/SubscriberBotContext.tsx"],"sourcesContent":["/**\n * SubscriberBot Context Provider\n * @module subscriberbot/context\n */\n\nimport type { FC, PropsWithChildren } from 'react';\nimport { createContext, useContext, useMemo, useCallback } from 'react';\nimport { MemoryRouter, useNavigate as useRouterNavigate } from 'react-router';\nimport type { SubscriberBotRootProps } from '../types';\nimport { joinPath } from '../utils/navigation';\n\n// ============================================================================\n// Context\n// ============================================================================\n\ninterface SubscriberBotContextValue extends Omit<\n SubscriberBotRootProps,\n 'registerNavItems' | 'registerFooterItems' | 'navigate'\n> {\n isStandalone: boolean;\n /** Shell's navigate function (only available in integrated mode) */\n navigate?: (path: string) => void;\n /** Navigate to a path relative to basePath */\n navigateTo: (relativePath: string) => void;\n /** Get the full path for a relative path */\n getPath: (relativePath: string) => string;\n}\n\nconst SubscriberBotContext = createContext<SubscriberBotContextValue | null>(null);\n\n// ============================================================================\n// Hook\n// ============================================================================\n\nexport function useSubscriberBot(): SubscriberBotContextValue {\n const context = useContext(SubscriberBotContext);\n if (!context) {\n throw new Error('useSubscriberBot must be used within a SubscriberBotProvider');\n }\n return context;\n}\n\n// ============================================================================\n// Provider Component\n// ============================================================================\n\ntype ProviderProps = Omit<SubscriberBotRootProps, 'registerNavItems' | 'registerFooterItems'> & {\n isStandalone: boolean;\n};\n\n/** Provider for standalone mode (has access to MemoryRouter) */\nconst StandaloneProviderInner: FC<PropsWithChildren<ProviderProps>> = ({\n children,\n basePath,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n}) => {\n const routerNavigate = useRouterNavigate();\n const effectiveBasePath = basePath || '/';\n\n const getPath = useCallback(\n (relativePath: string) => joinPath(effectiveBasePath, relativePath),\n [effectiveBasePath]\n );\n\n const navigateTo = useCallback(\n (relativePath: string) => {\n const fullPath = joinPath(effectiveBasePath, relativePath);\n routerNavigate(fullPath);\n },\n [effectiveBasePath, routerNavigate]\n );\n\n const contextValue = useMemo<SubscriberBotContextValue>(\n () => ({\n basePath: effectiveBasePath,\n navigate: undefined,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n isStandalone: true,\n navigateTo,\n getPath,\n }),\n [\n effectiveBasePath,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n navigateTo,\n getPath,\n ]\n );\n\n return (\n <SubscriberBotContext.Provider value={contextValue}>{children}</SubscriberBotContext.Provider>\n );\n};\n\n/** Provider for integrated mode (shell provides navigate) */\nconst IntegratedProviderInner: FC<\n PropsWithChildren<ProviderProps & { navigate: (path: string) => void }>\n> = ({\n children,\n basePath,\n navigate,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n}) => {\n const effectiveBasePath = basePath || '/';\n\n const getPath = useCallback(\n (relativePath: string) => joinPath(effectiveBasePath, relativePath),\n [effectiveBasePath]\n );\n\n const navigateTo = useCallback(\n (relativePath: string) => {\n const fullPath = joinPath(effectiveBasePath, relativePath);\n navigate(fullPath);\n },\n [effectiveBasePath, navigate]\n );\n\n const contextValue = useMemo<SubscriberBotContextValue>(\n () => ({\n basePath: effectiveBasePath,\n navigate,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n isStandalone: false,\n navigateTo,\n getPath,\n }),\n [\n effectiveBasePath,\n navigate,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n navigateTo,\n getPath,\n ]\n );\n\n return (\n <SubscriberBotContext.Provider value={contextValue}>{children}</SubscriberBotContext.Provider>\n );\n};\n\nexport const SubscriberBotProvider: FC<PropsWithChildren<SubscriberBotRootProps>> = (props) => {\n const { children, navigate } = props;\n // Standalone mode: no navigate function provided (MFE manages its own router)\n // Integrated mode: navigate function provided by shell (shell provides router)\n const isStandalone = !navigate;\n\n // Standalone mode: wrap in MemoryRouter\n if (isStandalone) {\n return (\n <MemoryRouter>\n <StandaloneProviderInner {...props} isStandalone={true}>\n {children}\n </StandaloneProviderInner>\n </MemoryRouter>\n );\n }\n\n // Integrated mode: shell provides router\n return (\n <IntegratedProviderInner {...props} navigate={navigate} isStandalone={false}>\n {children}\n </IntegratedProviderInner>\n );\n};\n"],"mappings":";;;;;AA4BA,
|
|
1
|
+
{"version":3,"file":"SubscriberBotContext.js","names":["useRouterNavigate","SubscriberBotContext","createContext","useSubscriberBot","context","useContext","StandaloneProviderInner","routerNavigate","useNavigate","effectiveBasePath","basePath","getPath","useCallback","joinPath","relativePath","navigateTo","fullPath","contextValue","useMemo","currentUser","tenantId","workspaceId","apiGatewayUrl","authToken","IntegratedProviderInner","navigate","SubscriberBotProvider","props","MemoryRouter"],"sources":["../../../src/subscriberbot/context/SubscriberBotContext.tsx"],"sourcesContent":["/**\n * SubscriberBot Context Provider\n * @module subscriberbot/context\n */\n\nimport type { FC, PropsWithChildren } from 'react';\nimport { createContext, useContext, useMemo, useCallback } from 'react';\nimport { MemoryRouter, useNavigate as useRouterNavigate } from 'react-router';\nimport type { SubscriberBotRootProps } from '../types';\nimport { joinPath } from '../utils/navigation';\n\n// ============================================================================\n// Context\n// ============================================================================\n\ninterface SubscriberBotContextValue extends Omit<\n SubscriberBotRootProps,\n 'registerNavItems' | 'registerFooterItems' | 'navigate'\n> {\n isStandalone: boolean;\n /** Shell's navigate function (only available in integrated mode) */\n navigate?: (path: string) => void;\n /** Navigate to a path relative to basePath */\n navigateTo: (relativePath: string) => void;\n /** Get the full path for a relative path */\n getPath: (relativePath: string) => string;\n}\n\nconst SubscriberBotContext = createContext<SubscriberBotContextValue | null>(null);\n\n// ============================================================================\n// Hook\n// ============================================================================\n\nexport function useSubscriberBot(): SubscriberBotContextValue {\n const context = useContext(SubscriberBotContext);\n if (!context) {\n throw new Error('useSubscriberBot must be used within a SubscriberBotProvider');\n }\n return context;\n}\n\n// ============================================================================\n// Provider Component\n// ============================================================================\n\ntype ProviderProps = Omit<SubscriberBotRootProps, 'registerNavItems' | 'registerFooterItems'> & {\n isStandalone: boolean;\n};\n\n/** Provider for standalone mode (has access to MemoryRouter) */\nconst StandaloneProviderInner: FC<PropsWithChildren<ProviderProps>> = ({\n children,\n basePath,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n}) => {\n const routerNavigate = useRouterNavigate();\n const effectiveBasePath = basePath || '/';\n\n const getPath = useCallback(\n (relativePath: string) => joinPath(effectiveBasePath, relativePath),\n [effectiveBasePath]\n );\n\n const navigateTo = useCallback(\n (relativePath: string) => {\n const fullPath = joinPath(effectiveBasePath, relativePath);\n routerNavigate(fullPath);\n },\n [effectiveBasePath, routerNavigate]\n );\n\n const contextValue = useMemo<SubscriberBotContextValue>(\n () => ({\n basePath: effectiveBasePath,\n navigate: undefined,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n isStandalone: true,\n navigateTo,\n getPath,\n }),\n [\n effectiveBasePath,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n navigateTo,\n getPath,\n ]\n );\n\n return (\n <SubscriberBotContext.Provider value={contextValue}>{children}</SubscriberBotContext.Provider>\n );\n};\n\n/** Provider for integrated mode (shell provides navigate) */\nconst IntegratedProviderInner: FC<\n PropsWithChildren<ProviderProps & { navigate: (path: string) => void }>\n> = ({\n children,\n basePath,\n navigate,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n}) => {\n const effectiveBasePath = basePath || '/';\n\n const getPath = useCallback(\n (relativePath: string) => joinPath(effectiveBasePath, relativePath),\n [effectiveBasePath]\n );\n\n const navigateTo = useCallback(\n (relativePath: string) => {\n const fullPath = joinPath(effectiveBasePath, relativePath);\n navigate(fullPath);\n },\n [effectiveBasePath, navigate]\n );\n\n const contextValue = useMemo<SubscriberBotContextValue>(\n () => ({\n basePath: effectiveBasePath,\n navigate,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n isStandalone: false,\n navigateTo,\n getPath,\n }),\n [\n effectiveBasePath,\n navigate,\n currentUser,\n tenantId,\n workspaceId,\n apiGatewayUrl,\n authToken,\n navigateTo,\n getPath,\n ]\n );\n\n return (\n <SubscriberBotContext.Provider value={contextValue}>{children}</SubscriberBotContext.Provider>\n );\n};\n\nexport const SubscriberBotProvider: FC<PropsWithChildren<SubscriberBotRootProps>> = (props) => {\n const { children, navigate } = props;\n // Standalone mode: no navigate function provided (MFE manages its own router)\n // Integrated mode: navigate function provided by shell (shell provides router)\n const isStandalone = !navigate;\n\n // Standalone mode: wrap in MemoryRouter\n if (isStandalone) {\n return (\n <MemoryRouter>\n <StandaloneProviderInner {...props} isStandalone={true}>\n {children}\n </StandaloneProviderInner>\n </MemoryRouter>\n );\n }\n\n // Integrated mode: shell provides router\n return (\n <IntegratedProviderInner {...props} navigate={navigate} isStandalone={false}>\n {children}\n </IntegratedProviderInner>\n );\n};\n"],"mappings":";;;;;AA4BA,IAAMC,IAAuBC,EAAgD,IAAI;AAMjF,SAAgBC,IAA8C;CAC5D,IAAMC,IAAUC,EAAWJ,CAAoB;CAC/C,IAAI,CAACG,GACH,MAAU,MAAM,8DAA8D;CAEhF,OAAOA;AACT;AAWA,IAAME,KAAiE,EACrE,aACA,aACA,gBACA,aACA,gBACA,kBACA,mBACI;CACJ,IAAMC,IAAiBP,EAAkB,GACnCS,IAAoBC,KAAY,KAEhCC,IAAUC,GACb,MAAyBC,EAASJ,GAAmBK,CAAY,GAClE,CAACL,CAAiB,CACpB,GAEMM,IAAaH,GAChB,MAAyB;EACxB,IAAMI,IAAWH,EAASJ,GAAmBK,CAAY;EACzD,EAAeE,CAAQ;CACzB,GACA,CAACP,GAAmBF,CAAc,CACpC,GAEMU,IAAeC,SACZ;EACL,UAAUT;EACV,UAAU,KAAA;EACV;EACA;EACA;EACA;EACA;EACA,cAAc;EACd;EACA;CACF,IACA;EACEA;EACAU;EACAC;EACAC;EACAC;EACAC;EACAR;EACAJ;CACF,CACF;CAEA,OACE,kBAACV,EAAqB,UAAtB;EAA+B,OAAOgB;EAAe;CAAwC,CAAA;AAEjG,GAGMO,KAED,EACH,aACA,aACA,aACA,gBACA,aACA,gBACA,kBACA,mBACI;CACJ,IAAMf,IAAoBC,KAAY,KAEhCC,IAAUC,GACb,MAAyBC,EAASJ,GAAmBK,CAAY,GAClE,CAACL,CAAiB,CACpB,GAEMM,IAAaH,GAChB,MAAyB;EAExB,EADiBC,EAASJ,GAAmBK,CACpC,CAAQ;CACnB,GACA,CAACL,GAAmBgB,CAAQ,CAC9B,GAEMR,IAAeC,SACZ;EACL,UAAUT;EACV;EACA;EACA;EACA;EACA;EACA;EACA,cAAc;EACd;EACA;CACF,IACA;EACEA;EACAgB;EACAN;EACAC;EACAC;EACAC;EACAC;EACAR;EACAJ;CACF,CACF;CAEA,OACE,kBAACV,EAAqB,UAAtB;EAA+B,OAAOgB;EAAe;CAAwC,CAAA;AAEjG,GAEaS,KAAwE,MAAU;CAC7F,IAAM,EAAE,aAAU,gBAAaC;CAiB/B,OAdsBF,IAepB,kBAACD,GAAD;EAAyB,GAAIG;EAAiB;EAAU,cAAc;EACnE;CACsB,CAAA,IAZvB,kBAACC,GAAD,EAAA,UACE,kBAACtB,GAAD;EAAyB,GAAIqB;EAAO,cAAc;EAC/C;CACsB,CAAA,EACb,CAAA;AAUpB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export { SubscriberBotProvider, useSubscriberBot } from "./SubscriberBotContext.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./useTr.js";
|
|
2
|
-
import "./useAutonomousAgentMode.js";
|
|
3
|
-
import "./useSubscriberBotApi.js";
|
|
4
2
|
import "./useCompactViewport.js";
|
|
5
3
|
import "./useRouteSelection.js";
|
|
4
|
+
import "./useAutonomousAgentMode.js";
|
|
5
|
+
export { useAdapterSubmissions, useApproveAdapter, useMarketplaceReports, useModerateListing, useProviders, useRejectAdapter, useUpdateProvider } from "./useSubscriberBotApi.js";
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { useFeatureFlag as e } from "@burdenoff/fe-libs/shared/feature-flags";
|
|
2
|
-
|
|
2
|
+
// src/subscriberbot/hooks/useAutonomousAgentMode.ts
|
|
3
3
|
var t = "subscriberbot.agents.autonomous";
|
|
4
4
|
function n() {
|
|
5
5
|
return e(t, !1);
|
|
6
6
|
}
|
|
7
7
|
function r(e, t, n) {
|
|
8
|
-
return e
|
|
8
|
+
return e !== "AUTONOMOUS" || t || n === "AUTONOMOUS";
|
|
9
9
|
}
|
|
10
|
-
//#endregion
|
|
11
10
|
export { t as AUTONOMOUS_AGENT_FLAG, r as isPostureSelectable, n as useAutonomousAgentMode };
|
|
12
11
|
|
|
13
12
|
//# sourceMappingURL=useAutonomousAgentMode.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAutonomousAgentMode.js","names":[],"sources":["../../../src/subscriberbot/hooks/useAutonomousAgentMode.ts"],"sourcesContent":["/**\n * useAutonomousAgentMode — fail-closed gate for the AUTONOMOUS agent posture.\n * @module subscriberbot/hooks\n *\n * The backend (`wspace-subscriberbot-svc`) rejects `subSetAgentStatus` and\n * `subCreateAgent` with `AUTONOMOUS_MODE_UNAVAILABLE` unless the\n * `subscriberbot.agents.autonomous` platform flag is explicitly enabled\n * (BOFF-3643 / BOFF-3625). The policy-evaluation engine that would let an\n * agent act on its own does not exist yet, so the UI must not offer a posture\n * the service will refuse.\n *\n * Unlike most platform flags (default-allow), this one defaults to `false`:\n * a missing, unloaded or errored flag keeps AUTONOMOUS unavailable, mirroring\n * the service's fail-closed check.\n */\n\nimport { useFeatureFlag } from '@burdenoff/fe-libs/shared/feature-flags';\nimport type { SubAgentStatus } from '../types';\n\n/** Platform feature flag that unlocks the AUTONOMOUS posture (fail-closed). */\nexport const AUTONOMOUS_AGENT_FLAG = 'subscriberbot.agents.autonomous';\n\n/** Returns `true` only when the AUTONOMOUS posture is explicitly enabled. */\nexport function useAutonomousAgentMode(): boolean {\n return useFeatureFlag(AUTONOMOUS_AGENT_FLAG, false);\n}\n\n/**\n * Whether a posture option can be chosen in an editable control.\n *\n * AUTONOMOUS is selectable only when the gate is open, or when the record is\n * already AUTONOMOUS (so the current value still renders as selected and the\n * user can move it to a safer posture).\n */\nexport function isPostureSelectable(\n option: SubAgentStatus,\n autonomousAvailable: boolean,\n currentStatus?: SubAgentStatus\n): boolean {\n if (option !== 'AUTONOMOUS') return true;\n return autonomousAvailable || currentStatus === 'AUTONOMOUS';\n}\n"],"mappings":";;AAoBA,
|
|
1
|
+
{"version":3,"file":"useAutonomousAgentMode.js","names":["AUTONOMOUS_AGENT_FLAG","useAutonomousAgentMode","useFeatureFlag","isPostureSelectable","option","autonomousAvailable","currentStatus"],"sources":["../../../src/subscriberbot/hooks/useAutonomousAgentMode.ts"],"sourcesContent":["/**\n * useAutonomousAgentMode — fail-closed gate for the AUTONOMOUS agent posture.\n * @module subscriberbot/hooks\n *\n * The backend (`wspace-subscriberbot-svc`) rejects `subSetAgentStatus` and\n * `subCreateAgent` with `AUTONOMOUS_MODE_UNAVAILABLE` unless the\n * `subscriberbot.agents.autonomous` platform flag is explicitly enabled\n * (BOFF-3643 / BOFF-3625). The policy-evaluation engine that would let an\n * agent act on its own does not exist yet, so the UI must not offer a posture\n * the service will refuse.\n *\n * Unlike most platform flags (default-allow), this one defaults to `false`:\n * a missing, unloaded or errored flag keeps AUTONOMOUS unavailable, mirroring\n * the service's fail-closed check.\n */\n\nimport { useFeatureFlag } from '@burdenoff/fe-libs/shared/feature-flags';\nimport type { SubAgentStatus } from '../types';\n\n/** Platform feature flag that unlocks the AUTONOMOUS posture (fail-closed). */\nexport const AUTONOMOUS_AGENT_FLAG = 'subscriberbot.agents.autonomous';\n\n/** Returns `true` only when the AUTONOMOUS posture is explicitly enabled. */\nexport function useAutonomousAgentMode(): boolean {\n return useFeatureFlag(AUTONOMOUS_AGENT_FLAG, false);\n}\n\n/**\n * Whether a posture option can be chosen in an editable control.\n *\n * AUTONOMOUS is selectable only when the gate is open, or when the record is\n * already AUTONOMOUS (so the current value still renders as selected and the\n * user can move it to a safer posture).\n */\nexport function isPostureSelectable(\n option: SubAgentStatus,\n autonomousAvailable: boolean,\n currentStatus?: SubAgentStatus\n): boolean {\n if (option !== 'AUTONOMOUS') return true;\n return autonomousAvailable || currentStatus === 'AUTONOMOUS';\n}\n"],"mappings":";;AAoBA,IAAaA,IAAwB;AAGrC,SAAgBC,IAAkC;CAChD,OAAOC,EAAeF,GAAuB,EAAK;AACpD;AASA,SAAgBG,EACd,GACA,GACA,GACS;CAET,OADIC,MAAW,gBACRC,KAAuBC,MAAkB;AAClD"}
|
|
@@ -2,7 +2,7 @@ import { useSubscriberBot as e } from "../context/SubscriberBotContext.js";
|
|
|
2
2
|
import "../context/index.js";
|
|
3
3
|
import { subQuery as t } from "./useSubscriberBotApi.js";
|
|
4
4
|
import { useMutation as n, useQuery as r, useQueryClient as i } from "@tanstack/react-query";
|
|
5
|
-
|
|
5
|
+
// src/subscriberbot/hooks/useBankingApi.ts
|
|
6
6
|
var a = {
|
|
7
7
|
all: ["subscriberbot", "banking"],
|
|
8
8
|
aggregators: [
|
|
@@ -26,7 +26,7 @@ var a = {
|
|
|
26
26
|
return r({
|
|
27
27
|
queryKey: a.aggregators,
|
|
28
28
|
queryFn: async () => (await t("query SubBankAggregators {\n subBankAggregators {\n aggregator displayName available environment countries requiresLink linkMode requiresCustomerIdentifier\n }\n }", {}, n)).subBankAggregators,
|
|
29
|
-
staleTime:
|
|
29
|
+
staleTime: 3e5
|
|
30
30
|
});
|
|
31
31
|
}, u = 100, d = 100;
|
|
32
32
|
async function f(e) {
|
|
@@ -99,7 +99,6 @@ var g = () => h("mutation SubCreateBankLinkSession($aggregator: SubBankAggregato
|
|
|
99
99
|
}`, "subCompleteBankLink"), v = () => h(`mutation SubImportBankStatement($input: SubImportBankStatementInput!) {
|
|
100
100
|
subImportBankStatement(input: $input) ${c}
|
|
101
101
|
}`, "subImportBankStatement"), y = () => h(`mutation SubSyncBankConnection($id: ID!) { subSyncBankConnection(id: $id) ${c} }`, "subSyncBankConnection"), b = () => h("mutation SubRemoveBankConnection($id: ID!) { subRemoveBankConnection(id: $id) }", "subRemoveBankConnection"), x = () => h(`mutation SubTrackRecurringCharge($id: ID!) { subTrackRecurringCharge(id: $id) { ${s} } }`, "subTrackRecurringCharge"), S = () => h(`mutation SubDismissRecurringCharge($id: ID!) { subDismissRecurringCharge(id: $id) { ${s} } }`, "subDismissRecurringCharge"), C = () => h(`mutation SubRestoreRecurringCharge($id: ID!) { subRestoreRecurringCharge(id: $id) { ${s} } }`, "subRestoreRecurringCharge");
|
|
102
|
-
//#endregion
|
|
103
102
|
export { l as useBankAggregators, p as useBankConnections, _ as useCompleteBankLink, g as useCreateBankLinkSession, S as useDismissRecurringCharge, v as useImportBankStatement, m as useRecurringCharges, b as useRemoveBankConnection, C as useRestoreRecurringCharge, y as useSyncBankConnection, x as useTrackRecurringCharge };
|
|
104
103
|
|
|
105
104
|
//# sourceMappingURL=useBankingApi.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useBankingApi.js","names":[],"sources":["../../../src/subscriberbot/hooks/useBankingApi.ts"],"sourcesContent":["/**\n * Bank / card aggregation hooks (BOFF-4161)\n * @module subscriberbot/hooks\n *\n * React-Query hooks for the `SubBank*` / `SubRecurringCharge*` contract of\n * wspace-subscriberbot-svc: the available aggregators, the signed-in user's\n * bank connections, statement imports, Plaid Link, sync / disconnect and the\n * recurring charges detected in the transactions. Same transport as every\n * other Subscriber Bot hook (`subQuery`).\n */\n\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { useSubscriberBot } from '../context';\nimport type { SubConnection } from '../types';\nimport type {\n SubBankAggregator,\n SubBankAggregatorInfo,\n SubBankConnection,\n SubBankLinkSession,\n SubBankSyncResult,\n SubCompleteBankLinkInput,\n SubImportBankStatementInput,\n SubRecurringCharge,\n SubRecurringChargeStatus,\n} from '../types/banking';\nimport { subQuery } from './useSubscriberBotApi';\n\nconst KEY = {\n all: ['subscriberbot', 'banking'] as const,\n aggregators: ['subscriberbot', 'banking', 'aggregators'] as const,\n connections: ['subscriberbot', 'banking', 'connections'] as const,\n charges: (status: SubRecurringChargeStatus | null) =>\n ['subscriberbot', 'banking', 'charges', status] as const,\n};\n\nconst ACCOUNT_FIELDS = `accounts { id name officialName mask type subtype currency }`;\nconst CONNECTION_FIELDS = `\n id aggregator status institutionId institutionName lastSyncedAt lastSyncError transactionCount\n consentExpiresAt createdAt updatedAt ${ACCOUNT_FIELDS}\n`;\nconst CHARGE_FIELDS = `\n id merchantKey displayName providerId relationshipId status interval averageAmount lastAmount\n currency occurrences firstChargedOn lastChargedOn nextExpectedOn confidence annualCost trackedAt dismissedAt\n`;\nconst SYNC_RESULT = `{ connection { ${CONNECTION_FIELDS} } added modified removed recurringDetected }`;\n\nexport const useBankAggregators = () => {\n const { apiGatewayUrl } = useSubscriberBot();\n return useQuery({\n queryKey: KEY.aggregators,\n queryFn: async () => {\n const result = await subQuery<{ subBankAggregators: SubBankAggregatorInfo[] }>(\n `query SubBankAggregators {\n subBankAggregators {\n aggregator displayName available environment countries requiresLink linkMode requiresCustomerIdentifier\n }\n }`,\n {},\n apiGatewayUrl\n );\n return result.subBankAggregators;\n },\n staleTime: 5 * 60 * 1000,\n });\n};\n\n/** Page size for the banking lists; every page is fetched so totals are complete. */\nconst PAGE_SIZE = 100;\n/** Upper bound on pages read per list (10,000 rows), so a runaway list cannot loop forever. */\nconst MAX_PAGES = 100;\n\n/**\n * Read every page of a connection-shaped list by offset (the workspaces\n * gateway strips cursors from federated queries, so offset is the paging key).\n */\nasync function fetchAllPages<T>(\n fetchPage: (offset: number) => Promise<SubConnection<T>>\n): Promise<SubConnection<T>> {\n const items: T[] = [];\n for (let page = 0; page < MAX_PAGES; page += 1) {\n const result = await fetchPage(page * PAGE_SIZE);\n items.push(...result.items);\n if (!result.pageInfo.hasMore) return { items, pageInfo: { hasMore: false, cursor: null } };\n }\n return { items, pageInfo: { hasMore: true, cursor: null } };\n}\n\nexport const useBankConnections = () => {\n const { apiGatewayUrl } = useSubscriberBot();\n return useQuery({\n queryKey: KEY.connections,\n queryFn: () =>\n fetchAllPages(async (offset) => {\n const result = await subQuery<{ subListBankConnections: SubConnection<SubBankConnection> }>(\n `query SubListBankConnections($pagination: PaginationInput) {\n subListBankConnections(pagination: $pagination) {\n items { ${CONNECTION_FIELDS} }\n pageInfo { hasMore cursor }\n }\n }`,\n { pagination: { limit: PAGE_SIZE, offset } },\n apiGatewayUrl\n );\n return result.subListBankConnections;\n }),\n });\n};\n\nexport const useRecurringCharges = (status: SubRecurringChargeStatus | null = null) => {\n const { apiGatewayUrl } = useSubscriberBot();\n return useQuery({\n queryKey: KEY.charges(status),\n queryFn: () =>\n fetchAllPages(async (offset) => {\n const result = await subQuery<{\n subListRecurringCharges: SubConnection<SubRecurringCharge>;\n }>(\n `query SubListRecurringCharges($status: SubRecurringChargeStatus, $pagination: PaginationInput) {\n subListRecurringCharges(status: $status, pagination: $pagination) {\n items { ${CHARGE_FIELDS} }\n pageInfo { hasMore cursor }\n }\n }`,\n { status, pagination: { limit: PAGE_SIZE, offset } },\n apiGatewayUrl\n );\n return result.subListRecurringCharges;\n }),\n });\n};\n\n/** A banking mutation that refreshes every banking query (and relationships) on success. */\nfunction useBankingMutation<TVars, TResult>(document: string, operation: string) {\n const { apiGatewayUrl } = useSubscriberBot();\n const queryClient = useQueryClient();\n return useMutation({\n mutationFn: async (variables: TVars) => {\n const result = await subQuery<Record<string, TResult>>(\n document,\n variables as Record<string, unknown>,\n apiGatewayUrl\n );\n const value = result[operation];\n if (value === undefined || value === null) throw new Error(`${operation} returned no data`);\n return value;\n },\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: KEY.all });\n void queryClient.invalidateQueries({ queryKey: ['subscriberbot', 'relationships'] });\n },\n });\n}\n\nexport const useCreateBankLinkSession = () =>\n useBankingMutation<\n { aggregator: SubBankAggregator; connectionId?: string; customerIdentifier?: string },\n SubBankLinkSession\n >(\n `mutation SubCreateBankLinkSession($aggregator: SubBankAggregator!, $connectionId: ID, $customerIdentifier: String) {\n subCreateBankLinkSession(\n aggregator: $aggregator\n connectionId: $connectionId\n customerIdentifier: $customerIdentifier\n ) { aggregator linkToken linkUrl expiresAt }\n }`,\n 'subCreateBankLinkSession'\n );\n\nexport const useCompleteBankLink = () =>\n useBankingMutation<{ input: SubCompleteBankLinkInput }, SubBankSyncResult>(\n `mutation SubCompleteBankLink($input: SubCompleteBankLinkInput!) {\n subCompleteBankLink(input: $input) ${SYNC_RESULT}\n }`,\n 'subCompleteBankLink'\n );\n\nexport const useImportBankStatement = () =>\n useBankingMutation<{ input: SubImportBankStatementInput }, SubBankSyncResult>(\n `mutation SubImportBankStatement($input: SubImportBankStatementInput!) {\n subImportBankStatement(input: $input) ${SYNC_RESULT}\n }`,\n 'subImportBankStatement'\n );\n\nexport const useSyncBankConnection = () =>\n useBankingMutation<{ id: string }, SubBankSyncResult>(\n `mutation SubSyncBankConnection($id: ID!) { subSyncBankConnection(id: $id) ${SYNC_RESULT} }`,\n 'subSyncBankConnection'\n );\n\nexport const useRemoveBankConnection = () =>\n useBankingMutation<{ id: string }, boolean>(\n `mutation SubRemoveBankConnection($id: ID!) { subRemoveBankConnection(id: $id) }`,\n 'subRemoveBankConnection'\n );\n\nexport const useTrackRecurringCharge = () =>\n useBankingMutation<{ id: string }, SubRecurringCharge>(\n `mutation SubTrackRecurringCharge($id: ID!) { subTrackRecurringCharge(id: $id) { ${CHARGE_FIELDS} } }`,\n 'subTrackRecurringCharge'\n );\n\nexport const useDismissRecurringCharge = () =>\n useBankingMutation<{ id: string }, SubRecurringCharge>(\n `mutation SubDismissRecurringCharge($id: ID!) { subDismissRecurringCharge(id: $id) { ${CHARGE_FIELDS} } }`,\n 'subDismissRecurringCharge'\n );\n\nexport const useRestoreRecurringCharge = () =>\n useBankingMutation<{ id: string }, SubRecurringCharge>(\n `mutation SubRestoreRecurringCharge($id: ID!) { subRestoreRecurringCharge(id: $id) { ${CHARGE_FIELDS} } }`,\n 'subRestoreRecurringCharge'\n );\n"],"mappings":";;;;;AA4BA,IAAM,IAAM;CACV,KAAK,CAAC,iBAAiB,SAAS;CAChC,aAAa;EAAC;EAAiB;EAAW;CAAa;CACvD,aAAa;EAAC;EAAiB;EAAW;CAAa;CACvD,UAAU,MACR;EAAC;EAAiB;EAAW;EAAW;CAAM;AAClD,GAGM,IA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,OAAO,MAAqB;GAMtC,IAAM,KAAQ,MALO,EACnB,GACA,GACA,CACF,GACqB;GACrB,IAAI,KAAiC,MAAM,MAAU,MAAM,GAAG,EAAU,kBAAkB;GAC1F,OAAO;EACT;EACA,iBAAiB;GAEf,AADA,EAAiB,kBAAkB,EAAE,UAAU,EAAI,IAAI,CAAC,GACxD,EAAiB,kBAAkB,EAAE,UAAU,CAAC,iBAAiB,eAAe,EAAE,CAAC;EACrF;CACF,CAAC;AACH;AAEA,IAAa,UACX,EAIE,2UAOA,0BACF,GAEW,UACX,EACE;2CACuC,EAAY;QAEnD,qBACF,GAEW,UACX,EACE;8CAC0C,EAAY;QAEtD,wBACF,GAEW,UACX,EACE,6EAA6E,EAAY,KACzF,uBACF,GAEW,UACX,EACE,mFACA,yBACF,GAEW,UACX,EACE,mFAAmF,EAAc,OACjG,yBACF,GAEW,UACX,EACE,uFAAuF,EAAc,OACrG,2BACF,GAEW,UACX,EACE,uFAAuF,EAAc,OACrG,2BACF"}
|
|
1
|
+
{"version":3,"file":"useBankingApi.js","names":["KEY","status","CONNECTION_FIELDS","CHARGE_FIELDS","SYNC_RESULT","useBankAggregators","useSubscriberBot","useQuery","subQuery","apiGatewayUrl","PAGE_SIZE","MAX_PAGES","fetchAllPages","items","page","result","fetchPage","useBankConnections","useRecurringCharges","useBankingMutation","queryClient","useQueryClient","useMutation","value","document","variables","operation","useCreateBankLinkSession","useCompleteBankLink","useImportBankStatement","useSyncBankConnection","useRemoveBankConnection","useTrackRecurringCharge","useDismissRecurringCharge","useRestoreRecurringCharge"],"sources":["../../../src/subscriberbot/hooks/useBankingApi.ts"],"sourcesContent":["/**\n * Bank / card aggregation hooks (BOFF-4161)\n * @module subscriberbot/hooks\n *\n * React-Query hooks for the `SubBank*` / `SubRecurringCharge*` contract of\n * wspace-subscriberbot-svc: the available aggregators, the signed-in user's\n * bank connections, statement imports, Plaid Link, sync / disconnect and the\n * recurring charges detected in the transactions. Same transport as every\n * other Subscriber Bot hook (`subQuery`).\n */\n\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { useSubscriberBot } from '../context';\nimport type { SubConnection } from '../types';\nimport type {\n SubBankAggregator,\n SubBankAggregatorInfo,\n SubBankConnection,\n SubBankLinkSession,\n SubBankSyncResult,\n SubCompleteBankLinkInput,\n SubImportBankStatementInput,\n SubRecurringCharge,\n SubRecurringChargeStatus,\n} from '../types/banking';\nimport { subQuery } from './useSubscriberBotApi';\n\nconst KEY = {\n all: ['subscriberbot', 'banking'] as const,\n aggregators: ['subscriberbot', 'banking', 'aggregators'] as const,\n connections: ['subscriberbot', 'banking', 'connections'] as const,\n charges: (status: SubRecurringChargeStatus | null) =>\n ['subscriberbot', 'banking', 'charges', status] as const,\n};\n\nconst ACCOUNT_FIELDS = `accounts { id name officialName mask type subtype currency }`;\nconst CONNECTION_FIELDS = `\n id aggregator status institutionId institutionName lastSyncedAt lastSyncError transactionCount\n consentExpiresAt createdAt updatedAt ${ACCOUNT_FIELDS}\n`;\nconst CHARGE_FIELDS = `\n id merchantKey displayName providerId relationshipId status interval averageAmount lastAmount\n currency occurrences firstChargedOn lastChargedOn nextExpectedOn confidence annualCost trackedAt dismissedAt\n`;\nconst SYNC_RESULT = `{ connection { ${CONNECTION_FIELDS} } added modified removed recurringDetected }`;\n\nexport const useBankAggregators = () => {\n const { apiGatewayUrl } = useSubscriberBot();\n return useQuery({\n queryKey: KEY.aggregators,\n queryFn: async () => {\n const result = await subQuery<{ subBankAggregators: SubBankAggregatorInfo[] }>(\n `query SubBankAggregators {\n subBankAggregators {\n aggregator displayName available environment countries requiresLink linkMode requiresCustomerIdentifier\n }\n }`,\n {},\n apiGatewayUrl\n );\n return result.subBankAggregators;\n },\n staleTime: 5 * 60 * 1000,\n });\n};\n\n/** Page size for the banking lists; every page is fetched so totals are complete. */\nconst PAGE_SIZE = 100;\n/** Upper bound on pages read per list (10,000 rows), so a runaway list cannot loop forever. */\nconst MAX_PAGES = 100;\n\n/**\n * Read every page of a connection-shaped list by offset (the workspaces\n * gateway strips cursors from federated queries, so offset is the paging key).\n */\nasync function fetchAllPages<T>(\n fetchPage: (offset: number) => Promise<SubConnection<T>>\n): Promise<SubConnection<T>> {\n const items: T[] = [];\n for (let page = 0; page < MAX_PAGES; page += 1) {\n const result = await fetchPage(page * PAGE_SIZE);\n items.push(...result.items);\n if (!result.pageInfo.hasMore) return { items, pageInfo: { hasMore: false, cursor: null } };\n }\n return { items, pageInfo: { hasMore: true, cursor: null } };\n}\n\nexport const useBankConnections = () => {\n const { apiGatewayUrl } = useSubscriberBot();\n return useQuery({\n queryKey: KEY.connections,\n queryFn: () =>\n fetchAllPages(async (offset) => {\n const result = await subQuery<{ subListBankConnections: SubConnection<SubBankConnection> }>(\n `query SubListBankConnections($pagination: PaginationInput) {\n subListBankConnections(pagination: $pagination) {\n items { ${CONNECTION_FIELDS} }\n pageInfo { hasMore cursor }\n }\n }`,\n { pagination: { limit: PAGE_SIZE, offset } },\n apiGatewayUrl\n );\n return result.subListBankConnections;\n }),\n });\n};\n\nexport const useRecurringCharges = (status: SubRecurringChargeStatus | null = null) => {\n const { apiGatewayUrl } = useSubscriberBot();\n return useQuery({\n queryKey: KEY.charges(status),\n queryFn: () =>\n fetchAllPages(async (offset) => {\n const result = await subQuery<{\n subListRecurringCharges: SubConnection<SubRecurringCharge>;\n }>(\n `query SubListRecurringCharges($status: SubRecurringChargeStatus, $pagination: PaginationInput) {\n subListRecurringCharges(status: $status, pagination: $pagination) {\n items { ${CHARGE_FIELDS} }\n pageInfo { hasMore cursor }\n }\n }`,\n { status, pagination: { limit: PAGE_SIZE, offset } },\n apiGatewayUrl\n );\n return result.subListRecurringCharges;\n }),\n });\n};\n\n/** A banking mutation that refreshes every banking query (and relationships) on success. */\nfunction useBankingMutation<TVars, TResult>(document: string, operation: string) {\n const { apiGatewayUrl } = useSubscriberBot();\n const queryClient = useQueryClient();\n return useMutation({\n mutationFn: async (variables: TVars) => {\n const result = await subQuery<Record<string, TResult>>(\n document,\n variables as Record<string, unknown>,\n apiGatewayUrl\n );\n const value = result[operation];\n if (value === undefined || value === null) throw new Error(`${operation} returned no data`);\n return value;\n },\n onSuccess: () => {\n void queryClient.invalidateQueries({ queryKey: KEY.all });\n void queryClient.invalidateQueries({ queryKey: ['subscriberbot', 'relationships'] });\n },\n });\n}\n\nexport const useCreateBankLinkSession = () =>\n useBankingMutation<\n { aggregator: SubBankAggregator; connectionId?: string; customerIdentifier?: string },\n SubBankLinkSession\n >(\n `mutation SubCreateBankLinkSession($aggregator: SubBankAggregator!, $connectionId: ID, $customerIdentifier: String) {\n subCreateBankLinkSession(\n aggregator: $aggregator\n connectionId: $connectionId\n customerIdentifier: $customerIdentifier\n ) { aggregator linkToken linkUrl expiresAt }\n }`,\n 'subCreateBankLinkSession'\n );\n\nexport const useCompleteBankLink = () =>\n useBankingMutation<{ input: SubCompleteBankLinkInput }, SubBankSyncResult>(\n `mutation SubCompleteBankLink($input: SubCompleteBankLinkInput!) {\n subCompleteBankLink(input: $input) ${SYNC_RESULT}\n }`,\n 'subCompleteBankLink'\n );\n\nexport const useImportBankStatement = () =>\n useBankingMutation<{ input: SubImportBankStatementInput }, SubBankSyncResult>(\n `mutation SubImportBankStatement($input: SubImportBankStatementInput!) {\n subImportBankStatement(input: $input) ${SYNC_RESULT}\n }`,\n 'subImportBankStatement'\n );\n\nexport const useSyncBankConnection = () =>\n useBankingMutation<{ id: string }, SubBankSyncResult>(\n `mutation SubSyncBankConnection($id: ID!) { subSyncBankConnection(id: $id) ${SYNC_RESULT} }`,\n 'subSyncBankConnection'\n );\n\nexport const useRemoveBankConnection = () =>\n useBankingMutation<{ id: string }, boolean>(\n `mutation SubRemoveBankConnection($id: ID!) { subRemoveBankConnection(id: $id) }`,\n 'subRemoveBankConnection'\n );\n\nexport const useTrackRecurringCharge = () =>\n useBankingMutation<{ id: string }, SubRecurringCharge>(\n `mutation SubTrackRecurringCharge($id: ID!) { subTrackRecurringCharge(id: $id) { ${CHARGE_FIELDS} } }`,\n 'subTrackRecurringCharge'\n );\n\nexport const useDismissRecurringCharge = () =>\n useBankingMutation<{ id: string }, SubRecurringCharge>(\n `mutation SubDismissRecurringCharge($id: ID!) { subDismissRecurringCharge(id: $id) { ${CHARGE_FIELDS} } }`,\n 'subDismissRecurringCharge'\n );\n\nexport const useRestoreRecurringCharge = () =>\n useBankingMutation<{ id: string }, SubRecurringCharge>(\n `mutation SubRestoreRecurringCharge($id: ID!) { subRestoreRecurringCharge(id: $id) { ${CHARGE_FIELDS} } }`,\n 'subRestoreRecurringCharge'\n );\n"],"mappings":";;;;;AA4BA,IAAMA,IAAM;CACV,KAAK,CAAC,iBAAiB,SAAS;CAChC,aAAa;EAAC;EAAiB;EAAW;CAAa;CACvD,aAAa;EAAC;EAAiB;EAAW;CAAa;CACvD,UAAU,MACR;EAAC;EAAiB;EAAW;EAAWC;CAAM;AAClD,GAGMC,IAAoB,6MAIpBC,IAAgB,uNAIhBC,IAAc,kBAAkBF,EAAkB,gDAE3CG,UAA2B;CACtC,IAAM,EAAE,qBAAkBC,EAAiB;CAC3C,OAAOC,EAAS;EACd,UAAUP,EAAI;EACd,SAAS,aAUA,MATcQ,EACnB,2MAKA,CAAC,GACDC,CACF,EAAA,CACc;EAEhB,WAAW;CACb,CAAC;AACH,GAGMC,IAAY,KAEZC,IAAY;AAMlB,eAAeC,EACb,GAC2B;CAC3B,IAAMC,IAAa,CAAC;CACpB,KAAK,IAAIC,IAAO,GAAGA,IAAOH,GAAW,KAAQ,GAAG;EAC9C,IAAMI,IAAS,MAAMC,EAAUF,IAAOJ,CAAS;EAE/C,IADAG,EAAM,KAAK,GAAGE,EAAO,KAAK,GACtB,CAACA,EAAO,SAAS,SAAS,OAAO;GAAE;GAAO,UAAU;IAAE,SAAS;IAAO,QAAQ;GAAK;EAAE;CAC3F;CACA,OAAO;EAAE;EAAO,UAAU;GAAE,SAAS;GAAM,QAAQ;EAAK;CAAE;AAC5D;AAEA,IAAaE,UAA2B;CACtC,IA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EACE,uFAAuFhB,EAAc,OACrG,2BACF,GAEW+B,UACXf,EACE,uFAAuFhB,EAAc,OACrG,2BACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useSyncExternalStore as e } from "react";
|
|
2
|
-
|
|
2
|
+
// src/subscriberbot/hooks/useCompactViewport.ts
|
|
3
3
|
var t = "(max-width: 767.98px)";
|
|
4
4
|
function n(e) {
|
|
5
5
|
if (typeof window > "u" || typeof window.matchMedia != "function") return () => void 0;
|
|
@@ -15,7 +15,6 @@ function i() {
|
|
|
15
15
|
function a() {
|
|
16
16
|
return e(n, r, i);
|
|
17
17
|
}
|
|
18
|
-
//#endregion
|
|
19
18
|
export { t as COMPACT_VIEWPORT_QUERY, a as useCompactViewport };
|
|
20
19
|
|
|
21
20
|
//# sourceMappingURL=useCompactViewport.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCompactViewport.js","names":[],"sources":["../../../src/subscriberbot/hooks/useCompactViewport.ts"],"sourcesContent":["import { useSyncExternalStore } from 'react';\n\n/**\n * Below Tailwind's `md` breakpoint (768px) — phones, and the installed app\n * on a phone. The shell's bottom tab bar uses the same breakpoint, so a\n * screen that branches on this hook switches layout exactly when the shell\n * swaps its chrome.\n */\nexport const COMPACT_VIEWPORT_QUERY = '(max-width: 767.98px)';\n\nfunction subscribe(onChange: () => void): () => void {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {\n return () => undefined;\n }\n const mql = window.matchMedia(COMPACT_VIEWPORT_QUERY);\n mql.addEventListener('change', onChange);\n return () => mql.removeEventListener('change', onChange);\n}\n\nfunction getSnapshot(): boolean {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false;\n return window.matchMedia(COMPACT_VIEWPORT_QUERY).matches;\n}\n\n/** SSR and environments without matchMedia render the desktop layout. */\nfunction getServerSnapshot(): boolean {\n return false;\n}\n\n/**\n * useCompactViewport — true when the viewport is phone-width, live-updating\n * on rotation and window resizes.\n */\nexport function useCompactViewport(): boolean {\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n"],"mappings":";;AAQA,
|
|
1
|
+
{"version":3,"file":"useCompactViewport.js","names":["COMPACT_VIEWPORT_QUERY","subscribe","mql","onChange","getSnapshot","getServerSnapshot","useCompactViewport","useSyncExternalStore"],"sources":["../../../src/subscriberbot/hooks/useCompactViewport.ts"],"sourcesContent":["import { useSyncExternalStore } from 'react';\n\n/**\n * Below Tailwind's `md` breakpoint (768px) — phones, and the installed app\n * on a phone. The shell's bottom tab bar uses the same breakpoint, so a\n * screen that branches on this hook switches layout exactly when the shell\n * swaps its chrome.\n */\nexport const COMPACT_VIEWPORT_QUERY = '(max-width: 767.98px)';\n\nfunction subscribe(onChange: () => void): () => void {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {\n return () => undefined;\n }\n const mql = window.matchMedia(COMPACT_VIEWPORT_QUERY);\n mql.addEventListener('change', onChange);\n return () => mql.removeEventListener('change', onChange);\n}\n\nfunction getSnapshot(): boolean {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false;\n return window.matchMedia(COMPACT_VIEWPORT_QUERY).matches;\n}\n\n/** SSR and environments without matchMedia render the desktop layout. */\nfunction getServerSnapshot(): boolean {\n return false;\n}\n\n/**\n * useCompactViewport — true when the viewport is phone-width, live-updating\n * on rotation and window resizes.\n */\nexport function useCompactViewport(): boolean {\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n"],"mappings":";;AAQA,IAAaA,IAAyB;AAEtC,SAASC,EAAU,GAAkC;CACnD,IAAI,OAAO,SAAW,OAAe,OAAO,OAAO,cAAe,YAChE,aAAa,KAAA;CAEf,IAAMC,IAAM,OAAO,WAAWF,CAAsB;CAEpD,OADAE,EAAI,iBAAiB,UAAUC,CAAQ,SAC1BD,EAAI,oBAAoB,UAAUC,CAAQ;AACzD;AAEA,SAASC,IAAuB;CAE9B,OADI,OAAO,SAAW,OAAe,OAAO,OAAO,cAAe,aAAmB,KAC9E,OAAO,WAAWJ,CAAsB,CAAC,CAAC;AACnD;AAGA,SAASK,IAA6B;CACpC,OAAO;AACT;AAMA,SAAgBC,IAA8B;CAC5C,OAAOC,EAAqBN,GAAWG,GAAaC,CAAiB;AACvE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useEffect as e, useId as t, useState as n } from "react";
|
|
2
|
-
|
|
2
|
+
// src/subscriberbot/hooks/useFormError.ts
|
|
3
3
|
function r() {
|
|
4
4
|
let r = t(), [i, a] = n(null);
|
|
5
5
|
e(() => {
|
|
@@ -22,7 +22,6 @@ function r() {
|
|
|
22
22
|
r
|
|
23
23
|
];
|
|
24
24
|
}
|
|
25
|
-
//#endregion
|
|
26
25
|
export { r as useFormError };
|
|
27
26
|
|
|
28
27
|
//# sourceMappingURL=useFormError.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useFormError.js","names":[],"sources":["../../../src/subscriberbot/hooks/useFormError.ts"],"sourcesContent":["import { useEffect, useId, useState } from 'react';\n\n/** Associate custom validation with its field; announce submission errors separately. */\nexport function useFormError() {\n const errorId = useId();\n const [failure, setFailure] = useState<{ message: string; fieldId?: string | string[] } | null>(\n null\n );\n\n useEffect(() => {\n if (failure)\n document\n .getElementById(\n (Array.isArray(failure.fieldId) ? failure.fieldId[0] : failure.fieldId) ?? errorId\n )\n ?.focus();\n }, [failure, errorId]);\n\n const setError = (message: string | null, fieldId?: string | string[]) =>\n setFailure(message ? { message, fieldId } : null);\n\n const matches = (fieldId: string) =>\n Array.isArray(failure?.fieldId)\n ? failure.fieldId.includes(fieldId)\n : failure?.fieldId === fieldId;\n const fieldErrorProps = (fieldId: string) => ({\n 'aria-invalid': matches(fieldId) || undefined,\n 'aria-describedby': matches(fieldId) ? errorId : undefined,\n onInput: () => {\n if (matches(fieldId)) setFailure(null);\n },\n });\n\n return [failure?.message ?? null, setError, fieldErrorProps, errorId] as const;\n}\n"],"mappings":";;AAGA,
|
|
1
|
+
{"version":3,"file":"useFormError.js","names":["useFormError","errorId","useId","failure","setFailure","useState","setError","message","matches","fieldId"],"sources":["../../../src/subscriberbot/hooks/useFormError.ts"],"sourcesContent":["import { useEffect, useId, useState } from 'react';\n\n/** Associate custom validation with its field; announce submission errors separately. */\nexport function useFormError() {\n const errorId = useId();\n const [failure, setFailure] = useState<{ message: string; fieldId?: string | string[] } | null>(\n null\n );\n\n useEffect(() => {\n if (failure)\n document\n .getElementById(\n (Array.isArray(failure.fieldId) ? failure.fieldId[0] : failure.fieldId) ?? errorId\n )\n ?.focus();\n }, [failure, errorId]);\n\n const setError = (message: string | null, fieldId?: string | string[]) =>\n setFailure(message ? { message, fieldId } : null);\n\n const matches = (fieldId: string) =>\n Array.isArray(failure?.fieldId)\n ? failure.fieldId.includes(fieldId)\n : failure?.fieldId === fieldId;\n const fieldErrorProps = (fieldId: string) => ({\n 'aria-invalid': matches(fieldId) || undefined,\n 'aria-describedby': matches(fieldId) ? errorId : undefined,\n onInput: () => {\n if (matches(fieldId)) setFailure(null);\n },\n });\n\n return [failure?.message ?? null, setError, fieldErrorProps, errorId] as const;\n}\n"],"mappings":";;AAGA,SAAgBA,IAAe;CAC7B,IAAMC,IAAUC,EAAM,GAChB,CAACC,GAASC,KAAcC,EAC5B,IACF;CAEA,QAAgB;EACd,AAAIF,KACF,SACG,gBACE,MAAM,QAAQA,EAAQ,OAAO,IAAIA,EAAQ,QAAQ,KAAKA,EAAQ,YAAYF,CAC7E,CAAC,EACC,MAAM;CACd,GAAG,CAACE,GAASF,CAAO,CAAC;CAErB,IAAMK,KAAY,GAAwB,MACxCF,EAAWG,IAAU;EAAE;EAAS;CAAQ,IAAI,IAAI,GAE5CC,KAAW,MACf,MAAM,QAAQL,GAAS,OAAO,IAC1BA,EAAQ,QAAQ,SAASM,CAAO,IAChCN,GAAS,YAAYM;CAS3B,OAAO;EAACN,GAAS,WAAW;EAAMG;GART,OAAqB;GAC5C,gBAAgBE,EAAQC,CAAO,KAAK,KAAA;GACpC,oBAAoBD,EAAQC,CAAO,IAAIR,IAAU,KAAA;GACjD,eAAe;IACb,AAAIO,EAAQC,CAAO,KAAGL,EAAW,IAAI;GACvC;EACF;EAE6DH;CAAO;AACtE"}
|
|
@@ -2,12 +2,11 @@ import { createFormatters as e } from "../utils/formatters.js";
|
|
|
2
2
|
import { useTr as t } from "./useTr.js";
|
|
3
3
|
import { useMemo as n } from "react";
|
|
4
4
|
import { useI18n as r } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
|
|
5
|
-
|
|
5
|
+
// src/subscriberbot/hooks/useFormatters.ts
|
|
6
6
|
function i() {
|
|
7
7
|
let { locale: i } = r(), a = t();
|
|
8
8
|
return n(() => e(i, a), [i, a]);
|
|
9
9
|
}
|
|
10
|
-
//#endregion
|
|
11
10
|
export { i as useFormatters };
|
|
12
11
|
|
|
13
12
|
//# sourceMappingURL=useFormatters.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useFormatters.js","names":[],"sources":["../../../src/subscriberbot/hooks/useFormatters.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { createFormatters } from '../utils/formatters';\nimport { useTr } from './useTr';\n\nexport function useFormatters() {\n const { locale } = useI18n();\n const tr = useTr();\n return useMemo(() => createFormatters(locale, tr), [locale, tr]);\n}\n"],"mappings":";;;;;AAKA,
|
|
1
|
+
{"version":3,"file":"useFormatters.js","names":["useFormatters","useI18n","tr","useTr","useMemo","createFormatters","locale"],"sources":["../../../src/subscriberbot/hooks/useFormatters.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { createFormatters } from '../utils/formatters';\nimport { useTr } from './useTr';\n\nexport function useFormatters() {\n const { locale } = useI18n();\n const tr = useTr();\n return useMemo(() => createFormatters(locale, tr), [locale, tr]);\n}\n"],"mappings":";;;;;AAKA,SAAgBA,IAAgB;CAC9B,IAAM,EAAE,cAAWC,EAAQ,GACrBC,IAAKC,EAAM;CACjB,OAAOC,QAAcC,EAAiBC,GAAQJ,CAAE,GAAG,CAACI,GAAQJ,CAAE,CAAC;AACjE"}
|
|
@@ -2,7 +2,7 @@ import { useSubscriberBot as e } from "../context/SubscriberBotContext.js";
|
|
|
2
2
|
import "../context/index.js";
|
|
3
3
|
import { subQuery as t } from "./useSubscriberBotApi.js";
|
|
4
4
|
import { useMutation as n, useQuery as r, useQueryClient as i } from "@tanstack/react-query";
|
|
5
|
-
|
|
5
|
+
// src/subscriberbot/hooks/useNegotiationApi.ts
|
|
6
6
|
var a = {
|
|
7
7
|
all: ["subscriberbot", "negotiations"],
|
|
8
8
|
list: (e, t) => [
|
|
@@ -39,7 +39,7 @@ var a = {
|
|
|
39
39
|
return r({
|
|
40
40
|
queryKey: a.terms,
|
|
41
41
|
queryFn: async () => (await t("query SubNegotiationTerms {\n subNegotiationTerms { authorizationVersion authorizationText managedFeeRate selfServeFeeRate maxAcceptedTermMonths }\n }", {}, n)).subNegotiationTerms,
|
|
42
|
-
staleTime:
|
|
42
|
+
staleTime: 3e5
|
|
43
43
|
});
|
|
44
44
|
}, l = (n = null, i = null, s = { limit: 50 }) => {
|
|
45
45
|
let { apiGatewayUrl: c } = e();
|
|
@@ -100,7 +100,6 @@ var p = `{ ${o} ${s} }`, m = () => f("subCreateNegotiation", `mutation SubCreate
|
|
|
100
100
|
}, i)).subAdminListNegotiations
|
|
101
101
|
});
|
|
102
102
|
}, b = () => f("subAdminSetNegotiationStatus", `mutation SubAdminSetNegotiationStatus($id: ID!, $status: SubNegotiationStatus!, $message: String) { subAdminSetNegotiationStatus(id: $id, status: $status, message: $message) ${p} }`), x = () => f("subAdminRecordNegotiationOutcome", `mutation SubAdminRecordNegotiationOutcome($id: ID!, $input: SubRecordNegotiationOutcomeInput!) { subAdminRecordNegotiationOutcome(id: $id, input: $input) ${p} }`), S = () => f("subAdminRetryNegotiationFeeBilling", `mutation SubAdminRetryNegotiationFeeBilling($id: ID!) { subAdminRetryNegotiationFeeBilling(id: $id) ${p} }`), C = () => f("subAdminWaiveNegotiationFee", `mutation SubAdminWaiveNegotiationFee($id: ID!, $reason: String!) { subAdminWaiveNegotiationFee(id: $id, reason: $reason) ${p} }`);
|
|
103
|
-
//#endregion
|
|
104
103
|
export { _ as useAddNegotiationNote, g as useCancelNegotiation, m as useCreateNegotiation, y as useDeskNegotiations, x as useDeskRecordOutcome, S as useDeskRetryFeeBilling, b as useDeskSetStatus, C as useDeskWaiveFee, u as useNegotiation, d as useNegotiationSummary, c as useNegotiationTerms, l as useNegotiations, v as useRecordNegotiationOutcome, h as useSubmitNegotiation };
|
|
105
104
|
|
|
106
105
|
//# sourceMappingURL=useNegotiationApi.js.map
|