Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Expose local commercial funnel diagnostics

rcourtmand8d94c48e184
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8d5e01ab96..78a42e553b 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -1354,6 +1354,12 @@ for lifecycle-adjacent diagnostics surfaces, legacy aliases and empty
fallback-reason fields must still normalize onto the governed canonical reason
contract instead of depending on monitor-owned snapshot accessors to have run
first.
+That same shared diagnostics dependency now also assumes any local commercial
+funnel diagnostics stay org-scoped at the cache boundary: when
+`internal/api/diagnostics.go` adds self-hosted upgrade-metric summaries beside
+lifecycle diagnostics, the shared diagnostics cache must key by authenticated
+org context so lifecycle-adjacent admin surfaces do not cross-tenant leak local
+commerce telemetry.
That same shared `internal/api/` dependency now also assumes auth persistence
compatibility is handled as an explicit migration/import boundary: legacy
raw-token `sessions.json` and `csrf_tokens.json` files may load for upgrade
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 360c646e1d..ecec36b00d 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1480,6 +1480,14 @@ That same diagnostics boundary must also backfill canonical fallback reasons
when a raw snapshot reaches the API layer without one, so
`buildMemorySourceDiagnostics` stays self-consistent even if a caller bypasses
`GetDiagnosticSnapshots()` and hands diagnostics a legacy alias directly.
+That same diagnostics boundary now also owns org-scoped local commercial funnel
+serialization when the self-hosted privacy contract allows it: if
+`internal/api/diagnostics.go` exposes local upgrade-metric summaries, daily
+buckets, or surface/capability breakdowns, it must read them from the local
+conversion store through the licensing bridge, keep diagnostics caching scoped
+to the authenticated org context, and preserve the canonical camelCase
+diagnostics payload shape instead of leaking pkg/licensing types or inferring
+hosted checkout stages from the local API layer.
That same public-demo API boundary must also hide runtime-admin operations
surfaces instead of treating them as harmless reads. Demo sessions must receive
`404` for `/api/diagnostics`, `/api/diagnostics/docker/prepare-token`, and the
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index aff250b0dd..34857dcc66 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -328,6 +328,14 @@ Insights`, rather than reviving generic `AI Patrol` or `AI ... analysis`
portal stages from referrer state, and the commercial service must keep
those self-hosted handoffs on release track `v6` even while the public
site remains on `v5` before GA.
+13. Keep local commercial funnel reporting inside the self-hosted privacy
+ boundary: `internal/api/diagnostics.go` and
+ `frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx`
+ may expose org-scoped local upgrade-metric summaries, daily buckets, and
+ surface/capability breakdowns to authenticated admins, but they must read
+ from the local conversion store instead of exporting those event rows to
+ the commercial service or reconstructing them from hosted checkout
+ telemetry.
## Current State
@@ -1572,6 +1580,11 @@ The browser app must not try to recreate those Pulse Account stages from
referrer state, and the commercial service must not collapse self-hosted v6
handoffs back onto the public-site release track when production public GA is
still on v5.
+That same local conversion store is now the canonical read model for
+self-hosted commercial diagnostics too: the admin-only diagnostics surface
+reads a structured 30-day local funnel report with daily, surface, and
+capability breakdowns directly from `pkg/licensing/conversion_store.go`
+without exporting those per-event rows outside the Pulse instance.
Stripe checkout and subscription webhook persistence now also follows the
canonical Cloud/MSP limit rule: when paid state is granted, billing-state
writes must persist authoritative `limits.max_monitored_systems` derived from canonical
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 3701d06cd1..d1113bfeb6 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -1425,6 +1425,12 @@ run/export lifecycle, results rendering, sanitization/model helpers, and
customer-facing diagnostics copy. The shell must not re-accumulate inline API
calls, export-download plumbing, diagnostics-card composition, or diagnostics
surface copy.
+That same diagnostics owner split now also covers local commercial funnel
+rendering: if diagnostics surfaces expose self-hosted pricing, checkout, or
+activation summaries, `DiagnosticsResultsPanel.tsx` and `diagnosticsModel.ts`
+must own the card composition, label humanization, and typed payload shape,
+while the shell remains a layout/composition owner and does not reintroduce
+inline diagnostics fetches or commerce-specific rendering logic.
The settings shell registry now also treats extracted feature prop contracts as
canonical shell inputs instead of reaching back into feature panels for type
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 9615cd1809..a23a081a65 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -447,6 +447,12 @@ querying, and the operator-facing storage health presentation layer.
behavior by fanning out per-pool `/api/metrics-store/history` reads, by
pulling the full storage-page `/api/storage-charts` payload, or by
inventing a dashboard-only storage history transport.
+15a. Keep shared diagnostics cache scope honest when storage/recovery-adjacent
+ surfaces reuse `internal/api/diagnostics.go`. If the shared diagnostics
+ payload includes local commercial funnel summaries, those values must stay
+ scoped to the authenticated org and sourced from the local conversion
+ store, so recovery-adjacent diagnostics do not inherit cross-tenant
+ leakage or hosted/local telemetry drift through the shared backend route.
16. Keep storage summary interaction scoped through the same canonical IDs.
17. Keep adjacent AI settings persistence vendor-neutral on the shared
`internal/api/` boundary. When storage- or recovery-adjacent hosted flows
@@ -1667,6 +1673,12 @@ source breakdowns backfill canonical fallback reasons even when a raw legacy
snapshot reaches `internal/api/diagnostics.go` without one, so
recovery-adjacent consumers do not observe alias-normalized sources paired
with empty or drifted fallback-reason payloads.
+That same shared `internal/api/` dependency now also assumes any local
+commercial funnel diagnostics remain cache-scoped to the authenticated org and
+read from the local conversion store instead of a hosted telemetry surrogate,
+so recovery-adjacent diagnostics surfaces can safely share the backend
+diagnostics route without inheriting cross-tenant leakage or hosted/local
+semantic drift.
That same shared `internal/api/` dependency now also assumes auth persistence
compatibility stays on an explicit migration/import boundary: legacy
raw-token `sessions.json` and `csrf_tokens.json` files may load for upgrade
diff --git a/frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx b/frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx
index 3d38345fa9..6f9ffefa2f 100644
--- a/frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx
+++ b/frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx
@@ -5,6 +5,7 @@ import { Card } from '@/components/shared/Card';
import Activity from 'lucide-solid/icons/activity';
import AlertTriangle from 'lucide-solid/icons/alert-triangle';
import CheckCircle from 'lucide-solid/icons/check-circle';
+import CreditCard from 'lucide-solid/icons/credit-card';
import Cpu from 'lucide-solid/icons/cpu';
import Database from 'lucide-solid/icons/database';
import HardDrive from 'lucide-solid/icons/hard-drive';
@@ -22,7 +23,12 @@ import {
DIAGNOSTICS_EMPTY_STATE_COPY,
DIAGNOSTICS_PANEL_COPY,
} from '@/utils/diagnosticsPresentation';
-import type { DiagnosticsData } from '@/components/Settings/diagnosticsModel';
+import { titleCaseDelimitedLabel } from '@/utils/textPresentation';
+import type {
+ CommercialFunnelDimensionBreakdown,
+ CommercialFunnelStageCounts,
+ DiagnosticsData,
+} from '@/components/Settings/diagnosticsModel';
const DiagnosticCard: Component<{
children: JSX.Element;
@@ -79,6 +85,68 @@ const MetricRow: Component<{
</div>
);
+const formatCommercialBreakdownLabel = (value?: string): string =>
+ titleCaseDelimitedLabel(value, { fallback: 'Unknown' });
+
+const formatCommercialDayLabel = (day?: string): string => {
+ if (!day) return 'Unknown';
+ const parsed = new Date(`${day}T00:00:00Z`);
+ if (Number.isNaN(parsed.getTime())) return day;
+ return parsed.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+};
+
+const getCommercialFunnelBadge = (
+ status?: string,
+): {
+ badgeStatus: 'online' | 'offline' | 'warning' | 'unknown';
+ label: string;
+} => {
+ switch (status) {
+ case 'active':
+ return { badgeStatus: 'online', label: 'Active' };
+ case 'warning':
+ return { badgeStatus: 'warning', label: 'Needs Review' };
+ case 'error':
+ return { badgeStatus: 'offline', label: 'Error' };
+ case 'unavailable':
+ return { badgeStatus: 'offline', label: 'Unavailable' };
+ default:
+ return { badgeStatus: 'unknown', label: 'Idle' };
+ }
+};
+
+const formatCommercialBreakdownSummary = (entry: CommercialFunnelDimensionBreakdown): string => {
+ const segments: string[] = [];
+ if (entry.pricing_viewed > 0) {
+ segments.push(`Pricing ${entry.pricing_viewed}`);
+ }
+ if (entry.checkout_clicked > 0) {
+ segments.push(`Checkout ${entry.checkout_clicked}`);
+ }
+ if (entry.trial_started > 0) {
+ segments.push(`Trials ${entry.trial_started}`);
+ }
+ if (entry.license_activated > 0) {
+ segments.push(`Activated ${entry.license_activated}`);
+ }
+ return segments.join(' • ') || 'No recorded activity';
+};
+
+const totalCommercialSignals = (summary?: CommercialFunnelStageCounts | null): number => {
+ if (!summary) return 0;
+ return (
+ summary.pricing_viewed +
+ summary.paywall_viewed +
+ summary.trial_started +
+ summary.upgrade_clicked +
+ summary.checkout_clicked +
+ summary.checkout_started +
+ summary.checkout_completed +
+ summary.license_activated +
+ summary.license_activation_failed
+ );
+};
+
interface DiagnosticsResultsPanelProps {
diagnosticsData: DiagnosticsData | null;
loading: boolean;
@@ -298,6 +366,162 @@ export const DiagnosticsResultsPanel: Component<DiagnosticsResultsPanelProps> =
</Card>
</Show>
+ <Show when={props.diagnosticsData?.commercialFunnel}>
+ <Card padding="md" class="lg:col-span-2">
+ <div class="mb-4 flex items-center gap-3 border-b border-border pb-3">
+ <div class="rounded-md bg-blue-100 p-2 dark:bg-blue-900">
+ <CreditCard class="h-4 w-4 text-blue-600 dark:text-blue-400" />
+ </div>
+ <div>
+ <h4 class="text-sm font-semibold text-base-content">Commercial Funnel</h4>
+ <p class="text-xs text-muted">
+ Local pricing, checkout, and activation activity over the last{' '}
+ {props.diagnosticsData?.commercialFunnel?.windowDays ?? 0} days.
+ </p>
+ </div>
+ <div class="ml-auto">
+ <StatusBadge
+ status={getCommercialFunnelBadge(props.diagnosticsData?.commercialFunnel?.status).badgeStatus}
+ label={getCommercialFunnelBadge(props.diagnosticsData?.commercialFunnel?.status).label}
+ />
+ </div>
+ </div>
+
+ <div class="grid gap-4 xl:grid-cols-[minmax(0,220px)_minmax(0,1fr)_minmax(0,1fr)]">
+ <div class="space-y-2 text-xs">
+ <MetricRow
+ label="Signals"
+ value={totalCommercialSignals(props.diagnosticsData?.commercialFunnel?.summary)}
+ />
+ <MetricRow
+ label="Pricing Views"
+ value={props.diagnosticsData?.commercialFunnel?.summary?.pricing_viewed ?? 0}
+ />
+ <MetricRow
+ label="Checkout Clicks"
+ value={props.diagnosticsData?.commercialFunnel?.summary?.checkout_clicked ?? 0}
+ />
+ <MetricRow
+ label="Checkout Starts"
+ value={props.diagnosticsData?.commercialFunnel?.summary?.checkout_started ?? 0}
+ />
+ <MetricRow
+ label="Activations"
+ value={props.diagnosticsData?.commercialFunnel?.summary?.license_activated ?? 0}
+ />
+ <MetricRow
+ label="Activation Failures"
+ value={
+ props.diagnosticsData?.commercialFunnel?.summary?.license_activation_failed ?? 0
+ }
+ />
+ </div>
+
+ <div>
+ <div class="mb-2 flex items-center justify-between">
+ <h5 class="text-xs font-semibold uppercase tracking-wide text-muted">
+ Recent Daily Trend
+ </h5>
+ <span class="text-[11px] text-muted">UTC day buckets</span>
+ </div>
+ <div class="space-y-2">
+ <Show
+ when={(props.diagnosticsData?.commercialFunnel?.daily?.length || 0) > 0}
+ fallback={<p class="text-xs text-muted">No daily activity recorded.</p>}
+ >
+ <For each={props.diagnosticsData?.commercialFunnel?.daily?.slice(-7) || []}>
+ {(bucket) => (
+ <div class="rounded-md border border-border-subtle px-3 py-2 text-xs">
+ <div class="flex items-center justify-between gap-3">
+ <span class="font-medium text-base-content">
+ {formatCommercialDayLabel(bucket.day)}
+ </span>
+ <span class="text-muted">
+ Pricing {bucket.pricing_viewed} • Checkout {bucket.checkout_clicked} •
+ Activated {bucket.license_activated}
+ </span>
+ </div>
+ </div>
+ )}
+ </For>
+ </Show>
+ </div>
+ </div>
+
+ <div class="grid gap-4 md:grid-cols-2 xl:grid-cols-1">
+ <div>
+ <div class="mb-2 text-xs font-semibold uppercase tracking-wide text-muted">
+ Top Surfaces
+ </div>
+ <div class="space-y-2">
+ <Show
+ when={(props.diagnosticsData?.commercialFunnel?.surfaces?.length || 0) > 0}
+ fallback={<p class="text-xs text-muted">No surface attribution recorded.</p>}
+ >
+ <For each={props.diagnosticsData?.commercialFunnel?.surfaces?.slice(0, 4) || []}>
+ {(entry) => (
+ <div class="rounded-md border border-border-subtle px-3 py-2 text-xs">
+ <div class="font-medium text-base-content">
+ {formatCommercialBreakdownLabel(entry.key)}
+ </div>
+ <div class="mt-1 text-muted">
+ {formatCommercialBreakdownSummary(entry)}
+ </div>
+ </div>
+ )}
+ </For>
+ </Show>
+ </div>
+ </div>
+
+ <div>
+ <div class="mb-2 text-xs font-semibold uppercase tracking-wide text-muted">
+ Top Capabilities
+ </div>
+ <div class="space-y-2">
+ <Show
+ when={(props.diagnosticsData?.commercialFunnel?.capabilities?.length || 0) > 0}
+ fallback={<p class="text-xs text-muted">No capability attribution recorded.</p>}
+ >
+ <For each={props.diagnosticsData?.commercialFunnel?.capabilities?.slice(0, 4) || []}>
+ {(entry) => (
+ <div class="rounded-md border border-border-subtle px-3 py-2 text-xs">
+ <div class="font-medium text-base-content">
+ {formatCommercialBreakdownLabel(entry.key)}
+ </div>
+ <div class="mt-1 text-muted">
+ {formatCommercialBreakdownSummary(entry)}
+ </div>
+ </div>
+ )}
+ </For>
+ </Show>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <Show when={(props.diagnosticsData?.commercialFunnel?.notes?.length || 0) > 0}>
+ <div class="mt-4 rounded-md border border-amber-200 bg-amber-50 p-2 dark:border-amber-800 dark:bg-amber-900">
+ <div class="flex items-start gap-2 text-xs text-amber-700 dark:text-amber-300">
+ <AlertTriangle class="mt-0.5 h-4 w-4 flex-shrink-0" />
+ <div class="space-y-1">
+ <For each={props.diagnosticsData?.commercialFunnel?.notes || []}>
+ {(note) => <div>{note}</div>}
+ </For>
+ </div>
+ </div>
+ </div>
+ </Show>
+
+ <Show when={props.diagnosticsData?.commercialFunnel?.error}>
+ <div class="mt-3 rounded-md border border-red-200 bg-red-50 p-2 text-xs text-red-700 dark:border-red-800 dark:bg-red-900 dark:text-red-300">
+ {props.diagnosticsData?.commercialFunnel?.error}
+ </div>
+ </Show>
+ </Card>
+ </Show>
+
<Show when={props.diagnosticsData?.apiTokens}>
<Card padding="md">
<div class="mb-4 flex items-center gap-3 border-b border-border pb-3">
diff --git a/frontend-modern/src/components/Settings/__tests__/DiagnosticsResultsPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/DiagnosticsResultsPanel.test.tsx
new file mode 100644
index 0000000000..c8ba1b085c
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/DiagnosticsResultsPanel.test.tsx
@@ -0,0 +1,119 @@
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it } from 'vitest';
+import { DiagnosticsResultsPanel } from '@/components/Settings/DiagnosticsResultsPanel';
+import type { DiagnosticsData } from '@/components/Settings/diagnosticsModel';
+
+describe('DiagnosticsResultsPanel', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('renders the commercial funnel card with readable breakdown labels', () => {
+ const diagnosticsData: DiagnosticsData = {
+ version: '6.0.0',
+ runtime: 'go',
+ uptime: 3600,
+ nodes: [],
+ pbs: [],
+ system: {
+ os: 'linux',
+ arch: 'amd64',
+ goVersion: 'go1.25',
+ numCPU: 8,
+ numGoroutine: 32,
+ memoryMB: 128,
+ },
+ commercialFunnel: {
+ enabled: true,
+ status: 'active',
+ windowDays: 30,
+ summary: {
+ pricing_viewed: 3,
+ paywall_viewed: 0,
+ trial_started: 1,
+ upgrade_clicked: 0,
+ checkout_clicked: 2,
+ checkout_started: 2,
+ checkout_completed: 1,
+ license_activated: 1,
+ license_activation_failed: 0,
+ period: {
+ from: '2026-03-19T00:00:00Z',
+ to: '2026-04-18T00:00:00Z',
+ },
+ },
+ daily: [
+ {
+ day: '2026-04-17',
+ pricing_viewed: 1,
+ paywall_viewed: 0,
+ trial_started: 0,
+ upgrade_clicked: 0,
+ checkout_clicked: 1,
+ checkout_started: 1,
+ checkout_completed: 0,
+ license_activated: 0,
+ license_activation_failed: 0,
+ },
+ {
+ day: '2026-04-18',
+ pricing_viewed: 2,
+ paywall_viewed: 0,
+ trial_started: 1,
+ upgrade_clicked: 0,
+ checkout_clicked: 1,
+ checkout_started: 1,
+ checkout_completed: 1,
+ license_activated: 1,
+ license_activation_failed: 0,
+ },
+ ],
+ surfaces: [
+ {
+ key: 'settings_self_hosted_billing_compare_prompt',
+ pricing_viewed: 0,
+ paywall_viewed: 0,
+ trial_started: 0,
+ upgrade_clicked: 0,
+ checkout_clicked: 2,
+ checkout_started: 0,
+ checkout_completed: 0,
+ license_activated: 0,
+ license_activation_failed: 0,
+ },
+ ],
+ capabilities: [
+ {
+ key: 'self_hosted_plan',
+ pricing_viewed: 3,
+ paywall_viewed: 0,
+ trial_started: 0,
+ upgrade_clicked: 0,
+ checkout_clicked: 2,
+ checkout_started: 2,
+ checkout_completed: 1,
+ license_activated: 1,
+ license_activation_failed: 0,
+ },
+ ],
+ notes: ['Local pricing and activation events show at least one completed conversion.'],
+ },
+ errors: [],
+ };
+
+ render(() => (
+ <DiagnosticsResultsPanel
+ diagnosticsData={diagnosticsData}
+ loading={false}
+ onRunDiagnostics={() => {}}
+ />
+ ));
+
+ expect(screen.getByText('Commercial Funnel')).toBeInTheDocument();
+ expect(screen.getByText('Pricing Views')).toBeInTheDocument();
+ expect(screen.getByText('Checkout Clicks')).toBeInTheDocument();
+ expect(screen.getByText('Self Hosted Plan')).toBeInTheDocument();
+ expect(screen.getByText('Settings Self Hosted Billing Compare Prompt')).toBeInTheDocument();
+ expect(screen.getByText(/Pricing 3/i)).toBeInTheDocument();
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index a43feea145..30ffade29c 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -10,6 +10,8 @@ import connectionEditorSource from '../ConnectionEditor/ConnectionEditor.tsx?raw
import addressProbeStepSource from '../ConnectionEditor/AddressProbeStep.tsx?raw';
import connectionEditorStateSource from '../ConnectionEditor/useConnectionEditor.ts?raw';
import nodeCredentialSlotSource from '../ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx?raw';
+import diagnosticsResultsPanelSource from '../DiagnosticsResultsPanel.tsx?raw';
+import diagnosticsModelSource from '../diagnosticsModel.ts?raw';
describe('settings architecture guardrails', () => {
it('keeps Settings on the canonical page shell boundary', () => {
@@ -120,4 +122,13 @@ describe('settings architecture guardrails', () => {
expect(nodeCredentialSlotSource).toContain('<NodeModalStatusFooter');
expect(nodeCredentialSlotSource).not.toContain('<Dialog');
});
+
+ it('keeps diagnostics commercial funnel rendering on the shared results/model boundary', () => {
+ expect(diagnosticsResultsPanelSource).toContain('Commercial Funnel');
+ expect(diagnosticsResultsPanelSource).toContain('titleCaseDelimitedLabel');
+ expect(diagnosticsResultsPanelSource).not.toContain("apiFetchJSON('/api/diagnostics')");
+
+ expect(diagnosticsModelSource).toContain('export interface CommercialFunnelDiagnostic');
+ expect(diagnosticsModelSource).toContain('export interface CommercialFunnelSummary');
+ });
});
diff --git a/frontend-modern/src/components/Settings/diagnosticsModel.ts b/frontend-modern/src/components/Settings/diagnosticsModel.ts
index 474343bcd0..75ac5a0933 100644
--- a/frontend-modern/src/components/Settings/diagnosticsModel.ts
+++ b/frontend-modern/src/components/Settings/diagnosticsModel.ts
@@ -87,6 +87,45 @@ export interface MetricsStoreDiagnostic {
error?: string;
}
+export interface CommercialFunnelStageCounts {
+ pricing_viewed: number;
+ paywall_viewed: number;
+ trial_started: number;
+ upgrade_clicked: number;
+ checkout_clicked: number;
+ checkout_started: number;
+ checkout_completed: number;
+ license_activated: number;
+ license_activation_failed: number;
+}
+
+export interface CommercialFunnelSummary extends CommercialFunnelStageCounts {
+ period: {
+ from: string;
+ to: string;
+ };
+}
+
+export interface CommercialFunnelDayBreakdown extends CommercialFunnelStageCounts {
+ day: string;
+}
+
+export interface CommercialFunnelDimensionBreakdown extends CommercialFunnelStageCounts {
+ key: string;
+}
+
+export interface CommercialFunnelDiagnostic {
+ enabled: boolean;
+ status: 'active' | 'idle' | 'warning' | 'error' | 'unavailable';
+ windowDays: number;
+ summary: CommercialFunnelSummary;
+ daily: CommercialFunnelDayBreakdown[];
+ surfaces: CommercialFunnelDimensionBreakdown[];
+ capabilities: CommercialFunnelDimensionBreakdown[];
+ notes?: string[];
+ error?: string;
+}
+
export interface AIChatDiagnostic {
enabled: boolean;
running: boolean;
@@ -107,6 +146,7 @@ export interface DiagnosticsData {
pbs: DiagnosticsPBS[];
system: SystemDiagnostic;
metricsStore?: MetricsStoreDiagnostic | null;
+ commercialFunnel?: CommercialFunnelDiagnostic | null;
apiTokens?: APITokenDiagnostic | null;
dockerAgents?: DockerAgentDiagnostic | null;
alerts?: AlertsDiagnostic | null;
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index c647320a71..1609f23c00 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -7096,6 +7096,67 @@ func TestContract_HostedRelayConfigResponseJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, rec.Body.Bytes(), want)
}
+func TestContract_DiagnosticsInfoJSONSnapshot(t *testing.T) {
+ payload := EmptyDiagnosticsInfo()
+ commercialFunnel := (&CommercialFunnelDiagnostic{
+ Enabled: true,
+ Status: "idle",
+ WindowDays: 30,
+ Summary: conversionFunnelSummary{
+ Period: struct {
+ From time.Time `json:"from"`
+ To time.Time `json:"to"`
+ }{
+ From: time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC),
+ To: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC),
+ },
+ },
+ }).NormalizeCollections()
+ payload.CommercialFunnel = &commercialFunnel
+
+ got, err := json.Marshal(payload.NormalizeCollections())
+ if err != nil {
+ t.Fatalf("marshal diagnostics info: %v", err)
+ }
+
+ const want = `{
+ "version":"",
+ "runtime":"",
+ "uptime":0,
+ "nodes":[],
+ "pbs":[],
+ "system":{"os":"","arch":"","goVersion":"","numCPU":0,"numGoroutine":0,"memoryMB":0},
+ "commercialFunnel":{
+ "enabled":true,
+ "status":"idle",
+ "windowDays":30,
+ "summary":{
+ "pricing_viewed":0,
+ "paywall_viewed":0,
+ "trial_started":0,
+ "upgrade_clicked":0,
+ "checkout_clicked":0,
+ "checkout_started":0,
+ "checkout_completed":0,
+ "license_activated":0,
+ "license_activation_failed":0,
+ "period":{"from":"2026-04-01T00:00:00Z","to":"2026-05-01T00:00:00Z"}
+ },
+ "daily":[],
+ "surfaces":[],
+ "capabilities":[],
+ "notes":[]
+ },
+ "errors":[],
+ "nodeSnapshots":[],
+ "guestSnapshots":[],
+ "memorySources":[],
+ "memorySourceBreakdown":[]
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_UpdatePlanManualFallbackJSONSnapshot(t *testing.T) {
payload := updates.UpdatePlan{
CanAutoUpdate: false,
diff --git a/internal/api/diagnostics.go b/internal/api/diagnostics.go
index 436574cf83..4878e8b8db 100644
--- a/internal/api/diagnostics.go
+++ b/internal/api/diagnostics.go
@@ -28,19 +28,20 @@ import (
// DiagnosticsInfo contains comprehensive diagnostic information
type DiagnosticsInfo struct {
- Version string `json:"version"`
- Runtime string `json:"runtime"`
- Uptime float64 `json:"uptime"`
- Nodes []NodeDiagnostic `json:"nodes"`
- PBS []PBSDiagnostic `json:"pbs"`
- System SystemDiagnostic `json:"system"`
- MetricsStore *MetricsStoreDiagnostic `json:"metricsStore,omitempty"`
- Discovery *DiscoveryDiagnostic `json:"discovery,omitempty"`
- APITokens *APITokenDiagnostic `json:"apiTokens,omitempty"`
- DockerAgents *DockerAgentDiagnostic `json:"dockerAgents,omitempty"`
- Alerts *AlertsDiagnostic `json:"alerts,omitempty"`
- AIChat *AIChatDiagnostic `json:"aiChat,omitempty"`
- Errors []string `json:"errors"`
+ Version string `json:"version"`
+ Runtime string `json:"runtime"`
+ Uptime float64 `json:"uptime"`
+ Nodes []NodeDiagnostic `json:"nodes"`
+ PBS []PBSDiagnostic `json:"pbs"`
+ System SystemDiagnostic `json:"system"`
+ MetricsStore *MetricsStoreDiagnostic `json:"metricsStore,omitempty"`
+ CommercialFunnel *CommercialFunnelDiagnostic `json:"commercialFunnel,omitempty"`
+ Discovery *DiscoveryDiagnostic `json:"discovery,omitempty"`
+ APITokens *APITokenDiagnostic `json:"apiTokens,omitempty"`
+ DockerAgents *DockerAgentDiagnostic `json:"dockerAgents,omitempty"`
+ Alerts *AlertsDiagnostic `json:"alerts,omitempty"`
+ AIChat *AIChatDiagnostic `json:"aiChat,omitempty"`
+ Errors []string `json:"errors"`
// NodeSnapshots captures the raw memory payload and derived usage Pulse last observed per node.
NodeSnapshots []monitoring.NodeMemorySnapshot `json:"nodeSnapshots"`
// GuestSnapshots captures recent per-guest memory breakdowns (VM/LXC) with the raw Proxmox fields.
@@ -87,6 +88,10 @@ func (d DiagnosticsInfo) NormalizeCollections() DiagnosticsInfo {
normalized := d.MetricsStore.NormalizeCollections()
d.MetricsStore = &normalized
}
+ if d.CommercialFunnel != nil {
+ normalized := d.CommercialFunnel.NormalizeCollections()
+ d.CommercialFunnel = &normalized
+ }
if d.Discovery != nil {
normalized := d.Discovery.NormalizeCollections()
d.Discovery = &normalized
@@ -204,6 +209,34 @@ func (d MetricsStoreDiagnostic) NormalizeCollections() MetricsStoreDiagnostic {
return d
}
+type CommercialFunnelDiagnostic struct {
+ Enabled bool `json:"enabled"`
+ Status string `json:"status"`
+ WindowDays int `json:"windowDays"`
+ Summary conversionFunnelSummary `json:"summary"`
+ Daily []conversionFunnelDayBreakdown `json:"daily"`
+ Surfaces []conversionFunnelDimensionBreakdown `json:"surfaces"`
+ Capabilities []conversionFunnelDimensionBreakdown `json:"capabilities"`
+ Notes []string `json:"notes"`
+ Error string `json:"error,omitempty"`
+}
+
+func (d CommercialFunnelDiagnostic) NormalizeCollections() CommercialFunnelDiagnostic {
+ if d.Daily == nil {
+ d.Daily = []conversionFunnelDayBreakdown{}
+ }
+ if d.Surfaces == nil {
+ d.Surfaces = []conversionFunnelDimensionBreakdown{}
+ }
+ if d.Capabilities == nil {
+ d.Capabilities = []conversionFunnelDimensionBreakdown{}
+ }
+ if d.Notes == nil {
+ d.Notes = []string{}
+ }
+ return d
+}
+
func isFallbackMemorySource(source string) bool {
return monitoring.MemorySourceIsFallback(source)
}
@@ -381,14 +414,88 @@ func buildMetricsStoreDiagnostic(monitor *monitoring.Monitor) *MetricsStoreDiagn
}
}
+func buildCommercialFunnelDiagnostic(ctx context.Context, store *conversionStore, now time.Time) *CommercialFunnelDiagnostic {
+ diag := (&CommercialFunnelDiagnostic{
+ Enabled: store != nil,
+ Status: "idle",
+ WindowDays: commercialFunnelDiagnosticsWindowDays,
+ Notes: []string{},
+ }).NormalizeCollections()
+
+ if store == nil {
+ diag.Status = "unavailable"
+ diag.Error = "conversion store not initialized"
+ diag.Notes = append(diag.Notes, "Local upgrade metrics are unavailable on this instance.")
+ return &diag
+ }
+
+ to := now.UTC().Truncate(24 * time.Hour).Add(24 * time.Hour)
+ from := to.AddDate(0, 0, -commercialFunnelDiagnosticsWindowDays)
+ orgID := diagnosticsCommercialOrgID(ctx)
+
+ report, err := store.FunnelReport(orgID, from, to)
+ if err != nil {
+ diag.Status = "error"
+ diag.Error = "failed to query local upgrade metrics"
+ diag.Notes = append(diag.Notes, "Diagnostics could not read the local upgrade funnel store.")
+ return &diag
+ }
+
+ diag.Summary = report.Summary
+ diag.Daily = report.Daily
+ diag.Surfaces = report.Surfaces
+ diag.Capabilities = report.Capabilities
+
+ totalSignal := report.Summary.PricingViewed +
+ report.Summary.PaywallViewed +
+ report.Summary.TrialStarted +
+ report.Summary.UpgradeClicked +
+ report.Summary.CheckoutClicked +
+ report.Summary.CheckoutStarted +
+ report.Summary.CheckoutCompleted +
+ report.Summary.LicenseActivated +
+ report.Summary.LicenseActivationFailed
+
+ switch {
+ case totalSignal == 0:
+ diag.Status = "idle"
+ diag.Notes = append(diag.Notes, "No local upgrade funnel activity was recorded in the last 30 days.")
+ case report.Summary.LicenseActivationFailed > 0:
+ diag.Status = "warning"
+ diag.Notes = append(diag.Notes, "At least one local activation attempt failed in the current window.")
+ case report.Summary.CheckoutClicked > 0 && report.Summary.LicenseActivated == 0:
+ diag.Status = "warning"
+ diag.Notes = append(diag.Notes, "Checkout interest is present, but no local activation completed in the current window.")
+ case report.Summary.LicenseActivated > 0:
+ diag.Status = "active"
+ diag.Notes = append(diag.Notes, "Local pricing and activation events show at least one completed conversion in the current window.")
+ default:
+ diag.Status = "active"
+ }
+
+ if report.Summary.PricingViewed > 0 && report.Summary.CheckoutClicked == 0 {
+ diag.Notes = append(diag.Notes, "Pricing views are not yet turning into checkout clicks.")
+ }
+ if report.Summary.CheckoutClicked > report.Summary.CheckoutStarted {
+ diag.Notes = append(diag.Notes, "Some checkout clicks leave the app before a local checkout-start event is recorded.")
+ }
+
+ return &diag
+}
+
const diagnosticsCacheTTL = 45 * time.Second
+const commercialFunnelDiagnosticsWindowDays = 30
+
+type cachedDiagnosticsEntry struct {
+ diag DiagnosticsInfo
+ cachedAt time.Time
+}
var (
diagnosticsMetricsOnce sync.Once
- diagnosticsCacheMu sync.RWMutex
- diagnosticsCache DiagnosticsInfo
- diagnosticsCacheTimestamp time.Time
+ diagnosticsCacheMu sync.RWMutex
+ diagnosticsCache = map[string]cachedDiagnosticsEntry{}
diagnosticsCacheHits = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "pulse",
@@ -413,6 +520,20 @@ var (
})
)
+func diagnosticsScopeKey(ctx context.Context) string {
+ if orgID := strings.TrimSpace(GetOrgID(ctx)); orgID != "" {
+ return orgID
+ }
+ return "__default__"
+}
+
+func diagnosticsCommercialOrgID(ctx context.Context) string {
+ if orgID := strings.TrimSpace(GetOrgID(ctx)); orgID != "" {
+ return orgID
+ }
+ return "default"
+}
+
// NodeDiagnostic contains diagnostic info for a Proxmox node
type NodeDiagnostic struct {
ID string `json:"id"`
@@ -701,15 +822,15 @@ func (r *Router) handleDiagnostics(w http.ResponseWriter, req *http.Request) {
})
now := time.Now()
+ scopeKey := diagnosticsScopeKey(req.Context())
diagnosticsCacheMu.RLock()
- cachedDiag := diagnosticsCache
- cachedAt := diagnosticsCacheTimestamp
+ cachedEntry, ok := diagnosticsCache[scopeKey]
diagnosticsCacheMu.RUnlock()
- if !cachedAt.IsZero() && now.Sub(cachedAt) <= diagnosticsCacheTTL {
+ if ok && !cachedEntry.cachedAt.IsZero() && now.Sub(cachedEntry.cachedAt) <= diagnosticsCacheTTL {
diagnosticsCacheHits.Inc()
- writeDiagnosticsResponse(w, cachedDiag, cachedAt)
+ writeDiagnosticsResponse(w, cachedEntry.diag, cachedEntry.cachedAt)
return
}
@@ -723,9 +844,11 @@ func (r *Router) handleDiagnostics(w http.ResponseWriter, req *http.Request) {
diagnosticsRefreshDuration.Observe(time.Since(start).Seconds())
diagnosticsCacheMu.Lock()
- diagnosticsCache = fresh
- diagnosticsCacheTimestamp = time.Now()
- cachedAt = diagnosticsCacheTimestamp
+ cachedAt := time.Now()
+ diagnosticsCache[scopeKey] = cachedDiagnosticsEntry{
+ diag: fresh,
+ cachedAt: cachedAt,
+ }
diagnosticsCacheMu.Unlock()
writeDiagnosticsResponse(w, fresh, cachedAt)
@@ -772,6 +895,7 @@ func (r *Router) computeDiagnostics(ctx context.Context) DiagnosticsInfo {
diag.APITokens = buildAPITokenDiagnostic(r.config, r.monitor)
diag.MetricsStore = buildMetricsStoreDiagnostic(r.monitor)
+ diag.CommercialFunnel = buildCommercialFunnelDiagnostic(ctx, r.conversionStore, time.Now().UTC())
// Test each configured node
for _, node := range r.config.PVEInstances {
diff --git a/internal/api/diagnostics_additional_test.go b/internal/api/diagnostics_additional_test.go
index 9b92f1acb3..3c02a048cc 100644
--- a/internal/api/diagnostics_additional_test.go
+++ b/internal/api/diagnostics_additional_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -12,6 +13,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
)
@@ -94,18 +96,21 @@ func newMonitorForDiagnostics(t *testing.T, cfg *config.Config) *monitoring.Moni
func TestHandleDiagnostics_CacheHit(t *testing.T) {
cached := DiagnosticsInfo{Version: "cached"}
cachedAt := time.Now()
+ scopeKey := diagnosticsScopeKey(context.Background())
diagnosticsCacheMu.Lock()
prevCache := diagnosticsCache
- prevTimestamp := diagnosticsCacheTimestamp
- diagnosticsCache = cached
- diagnosticsCacheTimestamp = cachedAt
+ diagnosticsCache = map[string]cachedDiagnosticsEntry{
+ scopeKey: {
+ diag: cached,
+ cachedAt: cachedAt,
+ },
+ }
diagnosticsCacheMu.Unlock()
t.Cleanup(func() {
diagnosticsCacheMu.Lock()
diagnosticsCache = prevCache
- diagnosticsCacheTimestamp = prevTimestamp
diagnosticsCacheMu.Unlock()
})
@@ -130,6 +135,46 @@ func TestHandleDiagnostics_CacheHit(t *testing.T) {
}
}
+func TestHandleDiagnostics_CacheIsScopedByOrg(t *testing.T) {
+ cfg := &config.Config{DataPath: t.TempDir()}
+ monitor := newMonitorForDiagnostics(t, cfg)
+ cachedAt := time.Now()
+
+ diagnosticsCacheMu.Lock()
+ prevCache := diagnosticsCache
+ diagnosticsCache = map[string]cachedDiagnosticsEntry{
+ "org-a": {
+ diag: DiagnosticsInfo{Version: "cached-org-a"},
+ cachedAt: cachedAt,
+ },
+ }
+ diagnosticsCacheMu.Unlock()
+
+ t.Cleanup(func() {
+ diagnosticsCacheMu.Lock()
+ diagnosticsCache = prevCache
+ diagnosticsCacheMu.Unlock()
+ })
+
+ router := &Router{config: cfg, monitor: monitor}
+ req := httptest.NewRequest(http.MethodGet, "/api/diagnostics", nil)
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-b"))
+ rec := httptest.NewRecorder()
+
+ router.handleDiagnostics(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", rec.Code)
+ }
+
+ var payload DiagnosticsInfo
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode diagnostics: %v", err)
+ }
+ if payload.Version == "cached-org-a" {
+ t.Fatalf("expected org-b diagnostics to bypass org-a cache entry")
+ }
+}
+
func TestDiagnosticsInfo_UsesCanonicalEmptyCollections(t *testing.T) {
payload, err := json.Marshal(EmptyDiagnosticsInfo())
if err != nil {
@@ -164,6 +209,9 @@ func TestComputeDiagnostics_Basic(t *testing.T) {
if diag.MetricsStore == nil {
t.Fatalf("expected metrics store diagnostics")
}
+ if diag.CommercialFunnel == nil {
+ t.Fatalf("expected commercial funnel diagnostics")
+ }
if diag.APITokens == nil {
t.Fatalf("expected api token diagnostics")
}
@@ -175,6 +223,76 @@ func TestComputeDiagnostics_Basic(t *testing.T) {
}
}
+func TestComputeDiagnostics_CommercialFunnelUsesOrgScopedConversionReport(t *testing.T) {
+ cfg := &config.Config{DataPath: t.TempDir()}
+ monitor := newMonitorForDiagnostics(t, cfg)
+ store, err := pkglicensing.NewConversionStore(filepath.Join(t.TempDir(), "conversion.db"))
+ if err != nil {
+ t.Fatalf("NewConversionStore() error = %v", err)
+ }
+ defer store.Close()
+
+ base := time.Now().UTC().Truncate(time.Hour).Add(-6 * time.Hour)
+ for _, event := range []pkglicensing.StoredConversionEvent{
+ {
+ OrgID: "org-a",
+ EventType: pkglicensing.EventPricingViewed,
+ Surface: "settings_self_hosted_billing_plan",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "org-a:pricing",
+ CreatedAt: base,
+ },
+ {
+ OrgID: "org-a",
+ EventType: pkglicensing.EventCheckoutClicked,
+ Surface: "settings_self_hosted_billing_compare_prompt",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "org-a:click",
+ CreatedAt: base.Add(time.Hour),
+ },
+ {
+ OrgID: "org-a",
+ EventType: pkglicensing.EventLicenseActivated,
+ Surface: "license_api",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "org-a:activated",
+ CreatedAt: base.Add(2 * time.Hour),
+ },
+ {
+ OrgID: "org-b",
+ EventType: pkglicensing.EventPricingViewed,
+ Surface: "paywall_modal",
+ Capability: "relay",
+ IdempotencyKey: "org-b:pricing",
+ CreatedAt: base,
+ },
+ } {
+ if err := store.Record(event); err != nil {
+ t.Fatalf("Record(%s) error = %v", event.IdempotencyKey, err)
+ }
+ }
+
+ router := &Router{config: cfg, monitor: monitor, conversionStore: store}
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "org-a")
+ diag := router.computeDiagnostics(ctx)
+
+ if diag.CommercialFunnel == nil {
+ t.Fatalf("expected commercial funnel diagnostics")
+ }
+ if diag.CommercialFunnel.Summary.PricingViewed != 1 {
+ t.Fatalf("PricingViewed = %d, want 1", diag.CommercialFunnel.Summary.PricingViewed)
+ }
+ if diag.CommercialFunnel.Summary.CheckoutClicked != 1 {
+ t.Fatalf("CheckoutClicked = %d, want 1", diag.CommercialFunnel.Summary.CheckoutClicked)
+ }
+ if diag.CommercialFunnel.Summary.LicenseActivated != 1 {
+ t.Fatalf("LicenseActivated = %d, want 1", diag.CommercialFunnel.Summary.LicenseActivated)
+ }
+ if len(diag.CommercialFunnel.Surfaces) == 0 || diag.CommercialFunnel.Surfaces[0].Key != "settings_self_hosted_billing_compare_prompt" {
+ t.Fatalf("unexpected surfaces breakdown: %+v", diag.CommercialFunnel.Surfaces)
+ }
+}
+
func TestBuildAPITokenDiagnostic_WithDockerUsage(t *testing.T) {
now := time.Now()
lastUsed := now.Add(-time.Hour)
diff --git a/internal/api/diagnostics_memory_test.go b/internal/api/diagnostics_memory_test.go
index ad08b9c357..b883b39135 100644
--- a/internal/api/diagnostics_memory_test.go
+++ b/internal/api/diagnostics_memory_test.go
@@ -2,6 +2,7 @@ package api
import (
"context"
+ "path/filepath"
"reflect"
"testing"
"time"
@@ -11,6 +12,7 @@ import (
discoverysvc "github.com/rcourtman/pulse-go-rewrite/internal/discovery"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
pkgdiscovery "github.com/rcourtman/pulse-go-rewrite/pkg/discovery"
+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
func TestClassifyMemorySourceTrust(t *testing.T) {
@@ -344,6 +346,81 @@ func TestComputeDiagnostics_DiscoveryUsesStructuredErrorOwnership(t *testing.T)
}
}
+func TestBuildCommercialFunnelDiagnostic_UsesScopedLocalReport(t *testing.T) {
+ store, err := pkglicensing.NewConversionStore(filepath.Join(t.TempDir(), "conversion.db"))
+ if err != nil {
+ t.Fatalf("NewConversionStore() error = %v", err)
+ }
+ defer store.Close()
+
+ now := time.Now().UTC().Truncate(time.Hour)
+ windowEnd := now.Truncate(24 * time.Hour).Add(24 * time.Hour)
+ windowStart := windowEnd.AddDate(0, 0, -2)
+
+ for _, event := range []pkglicensing.StoredConversionEvent{
+ {
+ OrgID: "org-a",
+ EventType: pkglicensing.EventPricingViewed,
+ Surface: "settings_self_hosted_billing_plan",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "diag:pricing",
+ CreatedAt: windowStart.Add(2 * time.Hour),
+ },
+ {
+ OrgID: "org-a",
+ EventType: pkglicensing.EventCheckoutClicked,
+ Surface: "settings_self_hosted_billing_compare_prompt",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "diag:checkout",
+ CreatedAt: windowStart.Add(3 * time.Hour),
+ },
+ {
+ OrgID: "org-a",
+ EventType: pkglicensing.EventLicenseActivated,
+ Surface: "license_api",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "diag:activated",
+ CreatedAt: windowStart.Add(4 * time.Hour),
+ },
+ {
+ OrgID: "org-b",
+ EventType: pkglicensing.EventPricingViewed,
+ Surface: "paywall_modal",
+ Capability: "relay",
+ IdempotencyKey: "diag:other-org",
+ CreatedAt: windowStart.Add(2 * time.Hour),
+ },
+ } {
+ if err := store.Record(event); err != nil {
+ t.Fatalf("Record(%s) error = %v", event.IdempotencyKey, err)
+ }
+ }
+
+ diag := buildCommercialFunnelDiagnostic(
+ context.WithValue(context.Background(), OrgIDContextKey, "org-a"),
+ store,
+ now,
+ )
+ if diag == nil {
+ t.Fatal("expected commercial funnel diagnostics")
+ }
+ if diag.Status != "active" {
+ t.Fatalf("Status = %q, want active", diag.Status)
+ }
+ if diag.Summary.PricingViewed != 1 || diag.Summary.CheckoutClicked != 1 || diag.Summary.LicenseActivated != 1 {
+ t.Fatalf("unexpected summary: %+v", diag.Summary)
+ }
+ if len(diag.Daily) < 2 {
+ t.Fatalf("len(Daily) = %d, want >= 2", len(diag.Daily))
+ }
+ if len(diag.Surfaces) == 0 || diag.Surfaces[0].Key != "settings_self_hosted_billing_compare_prompt" {
+ t.Fatalf("unexpected surfaces breakdown: %+v", diag.Surfaces)
+ }
+ if len(diag.Capabilities) == 0 || diag.Capabilities[0].Key != "self_hosted_plan" {
+ t.Fatalf("unexpected capabilities breakdown: %+v", diag.Capabilities)
+ }
+}
+
func setDiagnosticsUnexportedField(t *testing.T, target interface{}, fieldName string, value interface{}) {
t.Helper()
diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.go
index 15344217c2..2745842134 100644
--- a/internal/api/licensing_bridge.go
+++ b/internal/api/licensing_bridge.go
@@ -55,6 +55,11 @@ type conversionStore = pkglicensing.ConversionStore
type conversionEvent = pkglicensing.ConversionEvent
type conversionHealthStatus = pkglicensing.HealthStatus
type conversionCollectionConfigSnapshot = pkglicensing.CollectionConfigSnapshot
+type conversionFunnelStageCounts = pkglicensing.FunnelStageCounts
+type conversionFunnelSummary = pkglicensing.FunnelSummary
+type conversionFunnelDayBreakdown = pkglicensing.FunnelDayBreakdown
+type conversionFunnelDimensionBreakdown = pkglicensing.FunnelDimensionBreakdown
+type conversionFunnelReport = pkglicensing.FunnelReport
type trialActivationClaimsModel = pkglicensing.TrialActivationClaims
type purchaseReturnClaimsModel = pkglicensing.PurchaseReturnClaims
type entitlementLeaseClaimsModel = pkglicensing.EntitlementLeaseClaims
diff --git a/internal/license/conversion/store.go b/internal/license/conversion/store.go
index 956c3ab821..f16188ef4d 100644
--- a/internal/license/conversion/store.go
+++ b/internal/license/conversion/store.go
@@ -4,7 +4,11 @@ import pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
type ConversionStore = pkglicensing.ConversionStore
type StoredConversionEvent = pkglicensing.StoredConversionEvent
+type FunnelStageCounts = pkglicensing.FunnelStageCounts
type FunnelSummary = pkglicensing.FunnelSummary
+type FunnelDayBreakdown = pkglicensing.FunnelDayBreakdown
+type FunnelDimensionBreakdown = pkglicensing.FunnelDimensionBreakdown
+type FunnelReport = pkglicensing.FunnelReport
func NewConversionStore(dbPath string) (*ConversionStore, error) {
return pkglicensing.NewConversionStore(dbPath)
diff --git a/internal/license/conversion/store_test.go b/internal/license/conversion/store_test.go
index ac6fb5a6ee..4300ef8d91 100644
--- a/internal/license/conversion/store_test.go
+++ b/internal/license/conversion/store_test.go
@@ -186,6 +186,124 @@ func TestConversionStoreFunnelSummaryAggregation(t *testing.T) {
}
}
+func TestConversionStoreFunnelReportIncludesDailySurfaceAndCapabilityBreakdowns(t *testing.T) {
+ tmp := t.TempDir()
+ store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
+ if err != nil {
+ t.Fatalf("NewConversionStore() error = %v", err)
+ }
+ defer store.Close()
+
+ from := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
+ to := from.Add(3 * 24 * time.Hour)
+
+ events := []StoredConversionEvent{
+ {
+ OrgID: "org-a",
+ EventType: EventPricingViewed,
+ Surface: "settings_self_hosted_billing_plan",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "funnel:1",
+ CreatedAt: from.Add(2 * time.Hour),
+ },
+ {
+ OrgID: "org-a",
+ EventType: EventCheckoutClicked,
+ Surface: "settings_self_hosted_billing_compare_prompt",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "funnel:2",
+ CreatedAt: from.Add(3 * time.Hour),
+ },
+ {
+ OrgID: "org-a",
+ EventType: EventCheckoutStarted,
+ Surface: "license_api",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "funnel:3",
+ CreatedAt: from.Add(4 * time.Hour),
+ },
+ {
+ OrgID: "org-a",
+ EventType: EventLicenseActivated,
+ Surface: "license_api",
+ Capability: "self_hosted_plan",
+ IdempotencyKey: "funnel:4",
+ CreatedAt: from.Add(27 * time.Hour),
+ },
+ {
+ OrgID: "org-a",
+ EventType: EventTrialStarted,
+ Surface: "license_panel",
+ Capability: "relay",
+ IdempotencyKey: "funnel:5",
+ CreatedAt: from.Add(28 * time.Hour),
+ },
+ {
+ OrgID: "org-a",
+ EventType: EventPricingViewed,
+ Surface: "paywall_modal",
+ Capability: "relay",
+ IdempotencyKey: "funnel:6",
+ CreatedAt: from.Add(50 * time.Hour),
+ },
+ }
+ for _, ev := range events {
+ if err := store.Record(ev); err != nil {
+ t.Fatalf("Record(%s) error = %v", ev.IdempotencyKey, err)
+ }
+ }
+
+ report, err := store.FunnelReport("org-a", from, to)
+ if err != nil {
+ t.Fatalf("FunnelReport() error = %v", err)
+ }
+
+ if report.Summary.PricingViewed != 2 {
+ t.Fatalf("Summary.PricingViewed = %d, want 2", report.Summary.PricingViewed)
+ }
+ if report.Summary.CheckoutClicked != 1 {
+ t.Fatalf("Summary.CheckoutClicked = %d, want 1", report.Summary.CheckoutClicked)
+ }
+ if report.Summary.LicenseActivated != 1 {
+ t.Fatalf("Summary.LicenseActivated = %d, want 1", report.Summary.LicenseActivated)
+ }
+ if len(report.Daily) != 3 {
+ t.Fatalf("len(Daily) = %d, want 3", len(report.Daily))
+ }
+ if report.Daily[0].Day != "2026-04-01" || report.Daily[0].PricingViewed != 1 || report.Daily[0].CheckoutClicked != 1 {
+ t.Fatalf("unexpected first daily bucket: %+v", report.Daily[0])
+ }
+ if report.Daily[1].Day != "2026-04-02" || report.Daily[1].LicenseActivated != 1 || report.Daily[1].TrialStarted != 1 {
+ t.Fatalf("unexpected second daily bucket: %+v", report.Daily[1])
+ }
+ if report.Daily[2].Day != "2026-04-03" || report.Daily[2].PricingViewed != 1 {
+ t.Fatalf("unexpected third daily bucket: %+v", report.Daily[2])
+ }
+
+ if len(report.Surfaces) < 3 {
+ t.Fatalf("len(Surfaces) = %d, want >= 3", len(report.Surfaces))
+ }
+ if report.Surfaces[0].Key != "settings_self_hosted_billing_compare_prompt" {
+ t.Fatalf("Surfaces[0].Key = %q, want settings_self_hosted_billing_compare_prompt", report.Surfaces[0].Key)
+ }
+ if report.Surfaces[0].CheckoutClicked != 1 {
+ t.Fatalf("Surfaces[0].CheckoutClicked = %d, want 1", report.Surfaces[0].CheckoutClicked)
+ }
+
+ if len(report.Capabilities) != 2 {
+ t.Fatalf("len(Capabilities) = %d, want 2", len(report.Capabilities))
+ }
+ if report.Capabilities[0].Key != "self_hosted_plan" {
+ t.Fatalf("Capabilities[0].Key = %q, want self_hosted_plan", report.Capabilities[0].Key)
+ }
+ if report.Capabilities[0].PricingViewed != 1 || report.Capabilities[0].LicenseActivated != 1 {
+ t.Fatalf("unexpected self_hosted_plan capability bucket: %+v", report.Capabilities[0])
+ }
+ if report.Capabilities[1].Key != "relay" {
+ t.Fatalf("Capabilities[1].Key = %q, want relay", report.Capabilities[1].Key)
+ }
+}
+
func TestConversionStoreOrgIsolation(t *testing.T) {
tmp := t.TempDir()
store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
@@ -231,6 +349,12 @@ func TestConversionStoreRequiresOrgScopeForReads(t *testing.T) {
if _, err := store.FunnelSummary("", now.Add(-time.Minute), now.Add(time.Minute)); err == nil {
t.Fatal("FunnelSummary() with empty org_id error = nil, want error")
}
+ if _, err := store.FunnelDailyBreakdown("", now.Add(-time.Minute), now.Add(time.Minute)); err == nil {
+ t.Fatal("FunnelDailyBreakdown() with empty org_id error = nil, want error")
+ }
+ if _, err := store.FunnelDimensionBreakdown("", now.Add(-time.Minute), now.Add(time.Minute), "surface"); err == nil {
+ t.Fatal("FunnelDimensionBreakdown() with empty org_id error = nil, want error")
+ }
}
func TestConversionStoreTimeRangeFiltering(t *testing.T) {
diff --git a/pkg/licensing/conversion_store.go b/pkg/licensing/conversion_store.go
index 9d5f033560..fe18af48c5 100644
--- a/pkg/licensing/conversion_store.go
+++ b/pkg/licensing/conversion_store.go
@@ -7,6 +7,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "sort"
"strings"
"time"
@@ -33,7 +34,7 @@ type StoredConversionEvent struct {
CreatedAt time.Time
}
-type FunnelSummary struct {
+type FunnelStageCounts struct {
PricingViewed int64 `json:"pricing_viewed"`
PaywallViewed int64 `json:"paywall_viewed"`
TrialStarted int64 `json:"trial_started"`
@@ -43,12 +44,91 @@ type FunnelSummary struct {
CheckoutCompleted int64 `json:"checkout_completed"`
LicenseActivated int64 `json:"license_activated"`
LicenseActivationFailed int64 `json:"license_activation_failed"`
- Period struct {
+}
+
+type FunnelSummary struct {
+ FunnelStageCounts
+ Period struct {
From time.Time `json:"from"`
To time.Time `json:"to"`
} `json:"period"`
}
+type FunnelDayBreakdown struct {
+ Day string `json:"day"`
+ FunnelStageCounts
+}
+
+type FunnelDimensionBreakdown struct {
+ Key string `json:"key"`
+ FunnelStageCounts
+}
+
+type FunnelReport struct {
+ Summary FunnelSummary `json:"summary"`
+ Daily []FunnelDayBreakdown `json:"daily"`
+ Surfaces []FunnelDimensionBreakdown `json:"surfaces"`
+ Capabilities []FunnelDimensionBreakdown `json:"capabilities"`
+}
+
+func applyFunnelStageCount(counts *FunnelStageCounts, eventType string, count int64) {
+ if counts == nil {
+ return
+ }
+
+ switch strings.TrimSpace(eventType) {
+ case EventPricingViewed:
+ counts.PricingViewed = count
+ case EventPaywallViewed:
+ counts.PaywallViewed = count
+ case EventTrialStarted:
+ counts.TrialStarted = count
+ case EventUpgradeClicked:
+ counts.UpgradeClicked = count
+ case EventCheckoutClicked:
+ counts.CheckoutClicked = count
+ case EventCheckoutStarted:
+ counts.CheckoutStarted = count
+ case EventCheckoutCompleted:
+ counts.CheckoutCompleted = count
+ case EventLicenseActivated:
+ counts.LicenseActivated = count
+ case EventLicenseActivationFailed:
+ counts.LicenseActivationFailed = count
+ }
+}
+
+func compareFunnelBreakdowns(a, b FunnelDimensionBreakdown) int {
+ switch {
+ case a.CheckoutClicked != b.CheckoutClicked:
+ if a.CheckoutClicked > b.CheckoutClicked {
+ return -1
+ }
+ return 1
+ case a.PricingViewed != b.PricingViewed:
+ if a.PricingViewed > b.PricingViewed {
+ return -1
+ }
+ return 1
+ case a.LicenseActivated != b.LicenseActivated:
+ if a.LicenseActivated > b.LicenseActivated {
+ return -1
+ }
+ return 1
+ case a.TrialStarted != b.TrialStarted:
+ if a.TrialStarted > b.TrialStarted {
+ return -1
+ }
+ return 1
+ case a.Key < b.Key:
+ return -1
+ case a.Key > b.Key:
+ return 1
+ default:
+ return 0
+ }
+}
+
func ensureOwnerOnlyDir(dir string) error {
return securityutil.EnsureSecureStorageDir(dir, privateDirPerm)
}
@@ -346,26 +426,7 @@ func (s *ConversionStore) FunnelSummary(orgID string, from, to time.Time) (summa
if err := rows.Scan(&eventType, &count); err != nil {
return nil, fmt.Errorf("failed to scan funnel summary row: %w", err)
}
- switch strings.TrimSpace(eventType) {
- case EventPricingViewed:
- summary.PricingViewed = count
- case EventPaywallViewed:
- summary.PaywallViewed = count
- case EventTrialStarted:
- summary.TrialStarted = count
- case EventUpgradeClicked:
- summary.UpgradeClicked = count
- case EventCheckoutClicked:
- summary.CheckoutClicked = count
- case EventCheckoutStarted:
- summary.CheckoutStarted = count
- case EventCheckoutCompleted:
- summary.CheckoutCompleted = count
- case EventLicenseActivated:
- summary.LicenseActivated = count
- case EventLicenseActivationFailed:
- summary.LicenseActivationFailed = count
- }
+ applyFunnelStageCount(&summary.FunnelStageCounts, eventType, count)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("failed to iterate funnel summary rows: %w", err)
@@ -373,6 +434,189 @@ func (s *ConversionStore) FunnelSummary(orgID string, from, to time.Time) (summa
return summary, nil
}
+func (s *ConversionStore) FunnelDailyBreakdown(orgID string, from, to time.Time) (breakdown []FunnelDayBreakdown, retErr error) {
+ if s == nil || s.db == nil {
+ return nil, fmt.Errorf("conversion store is not initialized")
+ }
+ if from.IsZero() || to.IsZero() {
+ return nil, fmt.Errorf("from/to are required")
+ }
+
+ orgID = strings.TrimSpace(orgID)
+ if orgID == "" {
+ return nil, fmt.Errorf("org_id is required")
+ }
+
+ startDay := from.UTC().Truncate(24 * time.Hour)
+ endDay := to.UTC().Truncate(24 * time.Hour)
+ if !to.UTC().Equal(endDay) {
+ endDay = endDay.Add(24 * time.Hour)
+ }
+ if !startDay.Before(endDay) {
+ return []FunnelDayBreakdown{}, nil
+ }
+
+ query := `
+ SELECT strftime('%Y-%m-%d', created_at) AS bucket_day, event_type, COUNT(1)
+ FROM conversion_events
+ WHERE created_at >= ? AND created_at < ? AND org_id = ?
+ GROUP BY bucket_day, event_type
+ ORDER BY bucket_day ASC
+ `
+
+ rows, err := s.db.Query(
+ query,
+ from.UTC().Truncate(time.Second).Format(time.RFC3339),
+ to.UTC().Truncate(time.Second).Format(time.RFC3339),
+ orgID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to query funnel daily breakdown: %w", err)
+ }
+ defer func() {
+ if closeErr := rows.Close(); closeErr != nil {
+ wrappedCloseErr := fmt.Errorf("close funnel daily rows: %w", closeErr)
+ if retErr != nil {
+ retErr = errors.Join(retErr, wrappedCloseErr)
+ return
+ }
+ retErr = wrappedCloseErr
+ }
+ }()
+
+ buckets := make(map[string]*FunnelDayBreakdown)
+ breakdown = make([]FunnelDayBreakdown, 0, int(endDay.Sub(startDay)/(24*time.Hour)))
+ for day := startDay; day.Before(endDay); day = day.Add(24 * time.Hour) {
+ entry := FunnelDayBreakdown{Day: day.Format("2006-01-02")}
+ breakdown = append(breakdown, entry)
+ buckets[entry.Day] = &breakdown[len(breakdown)-1]
+ }
+
+ for rows.Next() {
+ var day string
+ var eventType string
+ var count int64
+ if err := rows.Scan(&day, &eventType, &count); err != nil {
+ return nil, fmt.Errorf("failed to scan funnel daily row: %w", err)
+ }
+ if entry := buckets[strings.TrimSpace(day)]; entry != nil {
+ applyFunnelStageCount(&entry.FunnelStageCounts, eventType, count)
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("failed to iterate funnel daily rows: %w", err)
+ }
+
+ return breakdown, nil
+}
+
+func (s *ConversionStore) FunnelDimensionBreakdown(orgID string, from, to time.Time, dimension string) (breakdown []FunnelDimensionBreakdown, retErr error) {
+ if s == nil || s.db == nil {
+ return nil, fmt.Errorf("conversion store is not initialized")
+ }
+ if from.IsZero() || to.IsZero() {
+ return nil, fmt.Errorf("from/to are required")
+ }
+
+ orgID = strings.TrimSpace(orgID)
+ if orgID == "" {
+ return nil, fmt.Errorf("org_id is required")
+ }
+
+ column := ""
+ switch strings.TrimSpace(dimension) {
+ case "surface":
+ column = "surface"
+ case "capability":
+ column = "capability"
+ default:
+ return nil, fmt.Errorf("unsupported breakdown dimension %q", dimension)
+ }
+
+ query := fmt.Sprintf(`
+ SELECT %s AS bucket_key, event_type, COUNT(1)
+ FROM conversion_events
+ WHERE created_at >= ? AND created_at < ? AND org_id = ? AND TRIM(%s) <> ''
+ GROUP BY bucket_key, event_type
+ `, column, column)
+
+ rows, err := s.db.Query(
+ query,
+ from.UTC().Truncate(time.Second).Format(time.RFC3339),
+ to.UTC().Truncate(time.Second).Format(time.RFC3339),
+ orgID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to query funnel %s breakdown: %w", dimension, err)
+ }
+ defer func() {
+ if closeErr := rows.Close(); closeErr != nil {
+ wrappedCloseErr := fmt.Errorf("close funnel %s rows: %w", dimension, closeErr)
+ if retErr != nil {
+ retErr = errors.Join(retErr, wrappedCloseErr)
+ return
+ }
+ retErr = wrappedCloseErr
+ }
+ }()
+
+ buckets := make(map[string]*FunnelDimensionBreakdown)
+ for rows.Next() {
+ var key string
+ var eventType string
+ var count int64
+ if err := rows.Scan(&key, &eventType, &count); err != nil {
+ return nil, fmt.Errorf("failed to scan funnel %s row: %w", dimension, err)
+ }
+ key = strings.TrimSpace(key)
+ if key == "" {
+ continue
+ }
+ entry, ok := buckets[key]
+ if !ok {
+ breakdown = append(breakdown, FunnelDimensionBreakdown{Key: key})
+ entry = &breakdown[len(breakdown)-1]
+ buckets[key] = entry
+ }
+ applyFunnelStageCount(&entry.FunnelStageCounts, eventType, count)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("failed to iterate funnel %s rows: %w", dimension, err)
+ }
+
+ sort.SliceStable(breakdown, func(i, j int) bool {
+ return compareFunnelBreakdowns(breakdown[i], breakdown[j]) < 0
+ })
+
+ return breakdown, nil
+}
+
+func (s *ConversionStore) FunnelReport(orgID string, from, to time.Time) (*FunnelReport, error) {
+ summary, err := s.FunnelSummary(orgID, from, to)
+ if err != nil {
+ return nil, err
+ }
+ daily, err := s.FunnelDailyBreakdown(orgID, from, to)
+ if err != nil {
+ return nil, err
+ }
+ surfaces, err := s.FunnelDimensionBreakdown(orgID, from, to, "surface")
+ if err != nil {
+ return nil, err
+ }
+ capabilities, err := s.FunnelDimensionBreakdown(orgID, from, to, "capability")
+ if err != nil {
+ return nil, err
+ }
+
+ return &FunnelReport{
+ Summary: *summary,
+ Daily: daily,
+ Surfaces: surfaces,
+ Capabilities: capabilities,
+ }, nil
+}
+
func (s *ConversionStore) Close() error {
if s == nil || s.db == nil {
return nil
diff --git a/pkg/licensing/conversion_store_queryplan_test.go b/pkg/licensing/conversion_store_queryplan_test.go
index 58ce9a1fb0..7ae03391d7 100644
--- a/pkg/licensing/conversion_store_queryplan_test.go
+++ b/pkg/licensing/conversion_store_queryplan_test.go
@@ -85,6 +85,39 @@ func TestConversionStoreQueryPlansUseIndexes(t *testing.T) {
wantIndex: "idx_conversion_events_org_time",
allowTempBTreeGroupBy: true,
},
+ {
+ name: "funnel daily breakdown by org and time range",
+ query: `
+ SELECT strftime('%Y-%m-%d', created_at) AS bucket_day, event_type, COUNT(1)
+ FROM conversion_events
+ WHERE created_at >= ? AND created_at < ? AND org_id = ?
+ GROUP BY bucket_day, event_type
+ ORDER BY bucket_day ASC
+ `,
+ args: []any{
+ time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
+ time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
+ "org-03",
+ },
+ wantIndex: "idx_conversion_events_org_time",
+ allowTempBTreeGroupBy: true,
+ },
+ {
+ name: "funnel surface breakdown by org and time range",
+ query: `
+ SELECT surface AS bucket_key, event_type, COUNT(1)
+ FROM conversion_events
+ WHERE created_at >= ? AND created_at < ? AND org_id = ? AND TRIM(surface) <> ''
+ GROUP BY bucket_key, event_type
+ `,
+ args: []any{
+ time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
+ time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
+ "org-03",
+ },
+ wantIndex: "idx_conversion_events_org_time",
+ allowTempBTreeGroupBy: true,
+ },
}
for _, tt := range tests {
diff --git a/tests/integration/tests/61-diagnostics-commercial-funnel.spec.ts b/tests/integration/tests/61-diagnostics-commercial-funnel.spec.ts
new file mode 100644
index 0000000000..31d9133698
--- /dev/null
+++ b/tests/integration/tests/61-diagnostics-commercial-funnel.spec.ts
@@ -0,0 +1,260 @@
+import { expect, test } from "@playwright/test";
+
+const COMMERCIAL_DIAGNOSTICS_PAYLOAD = {
+ version: "6.0.0",
+ runtime: "go",
+ uptime: 7200,
+ nodes: [],
+ pbs: [],
+ system: {
+ os: "linux",
+ arch: "amd64",
+ goVersion: "go1.25",
+ numCPU: 8,
+ numGoroutine: 42,
+ memoryMB: 256,
+ },
+ metricsStore: {
+ enabled: true,
+ status: "healthy",
+ dbSize: 1024 * 1024,
+ rawCount: 200,
+ minuteCount: 100,
+ hourlyCount: 20,
+ dailyCount: 10,
+ totalPoints: 330,
+ bufferSize: 0,
+ notes: [],
+ },
+ commercialFunnel: {
+ enabled: true,
+ status: "active",
+ windowDays: 30,
+ summary: {
+ pricing_viewed: 4,
+ paywall_viewed: 1,
+ trial_started: 1,
+ upgrade_clicked: 0,
+ checkout_clicked: 2,
+ checkout_started: 2,
+ checkout_completed: 1,
+ license_activated: 1,
+ license_activation_failed: 0,
+ period: {
+ from: "2026-03-21T00:00:00Z",
+ to: "2026-04-20T00:00:00Z",
+ },
+ },
+ daily: [
+ {
+ day: "2026-04-18",
+ pricing_viewed: 1,
+ paywall_viewed: 0,
+ trial_started: 0,
+ upgrade_clicked: 0,
+ checkout_clicked: 1,
+ checkout_started: 1,
+ checkout_completed: 0,
+ license_activated: 0,
+ license_activation_failed: 0,
+ },
+ {
+ day: "2026-04-19",
+ pricing_viewed: 2,
+ paywall_viewed: 1,
+ trial_started: 1,
+ upgrade_clicked: 0,
+ checkout_clicked: 1,
+ checkout_started: 1,
+ checkout_completed: 1,
+ license_activated: 1,
+ license_activation_failed: 0,
+ },
+ {
+ day: "2026-04-20",
+ pricing_viewed: 1,
+ paywall_viewed: 0,
+ trial_started: 0,
+ upgrade_clicked: 0,
+ checkout_clicked: 0,
+ checkout_started: 0,
+ checkout_completed: 0,
+ license_activated: 0,
+ license_activation_failed: 0,
+ },
+ ],
+ surfaces: [
+ {
+ key: "settings_self_hosted_billing_compare_prompt",
+ pricing_viewed: 0,
+ paywall_viewed: 0,
+ trial_started: 0,
+ upgrade_clicked: 0,
+ checkout_clicked: 2,
+ checkout_started: 0,
+ checkout_completed: 0,
+ license_activated: 0,
+ license_activation_failed: 0,
+ },
+ {
+ key: "settings_self_hosted_billing_plan",
+ pricing_viewed: 4,
+ paywall_viewed: 0,
+ trial_started: 0,
+ upgrade_clicked: 0,
+ checkout_clicked: 0,
+ checkout_started: 0,
+ checkout_completed: 0,
+ license_activated: 0,
+ license_activation_failed: 0,
+ },
+ ],
+ capabilities: [
+ {
+ key: "self_hosted_plan",
+ pricing_viewed: 4,
+ paywall_viewed: 0,
+ trial_started: 0,
+ upgrade_clicked: 0,
+ checkout_clicked: 2,
+ checkout_started: 2,
+ checkout_completed: 1,
+ license_activated: 1,
+ license_activation_failed: 0,
+ },
+ {
+ key: "relay",
+ pricing_viewed: 0,
+ paywall_viewed: 1,
+ trial_started: 1,
+ upgrade_clicked: 0,
+ checkout_clicked: 0,
+ checkout_started: 0,
+ checkout_completed: 0,
+ license_activated: 0,
+ license_activation_failed: 0,
+ },
+ ],
+ notes: [
+ "Local pricing and activation events show at least one completed conversion in the current window.",
+ ],
+ },
+ apiTokens: {
+ enabled: true,
+ tokenCount: 1,
+ recommendTokenSetup: false,
+ unusedTokenCount: 0,
+ notes: [],
+ },
+ dockerAgents: null,
+ alerts: null,
+ aiChat: null,
+ discovery: null,
+ errors: [],
+};
+
+test("renders the commercial funnel diagnostics card in the browser", async ({
+ page,
+}, testInfo) => {
+ await page.addInitScript(() => {
+ sessionStorage.setItem(
+ "pulse_auth",
+ JSON.stringify({
+ type: "token",
+ value: "playwright-token",
+ }),
+ );
+ sessionStorage.setItem("pulse_auth_user", "admin");
+ localStorage.setItem("pulse_whats_new_v2_shown", "true");
+ });
+
+ await page.route("**/api/security/status", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ hasAuthentication: true,
+ hideLocalLogin: false,
+ ssoProviders: [],
+ sessionCapabilities: {},
+ }),
+ });
+ });
+
+ await page.route("**/api/state", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ ok: true }),
+ });
+ });
+
+ await page.route("**/api/system/settings", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ theme: "system",
+ fullWidthMode: false,
+ }),
+ });
+ });
+
+ for (const path of [
+ "**/api/license/runtime-capabilities",
+ "**/api/license/commercial-posture",
+ "**/api/license/entitlements",
+ ]) {
+ await page.route(path, async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ capabilities: [],
+ limits: [],
+ monitored_system_capacity: null,
+ subscription_state: "free",
+ upgrade_reasons: [],
+ tier: "free",
+ trial_eligible: false,
+ hosted_mode: false,
+ legacy_connections: {
+ proxmox_nodes: 0,
+ docker_hosts: 0,
+ kubernetes_clusters: 0,
+ },
+ has_migration_gap: false,
+ }),
+ });
+ });
+ }
+
+ await page.route("**/api/diagnostics", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(COMMERCIAL_DIAGNOSTICS_PAYLOAD),
+ });
+ });
+
+ await page.goto("/operations/diagnostics", { waitUntil: "domcontentloaded" });
+
+ const runDiagnosticsButton = page
+ .locator("button")
+ .filter({ hasText: /^Run Diagnostics$/ })
+ .first();
+
+ await expect(runDiagnosticsButton).toBeVisible();
+ await runDiagnosticsButton.click();
+
+ await expect(page.getByText("Commercial Funnel", { exact: true })).toBeVisible();
+ await expect(page.getByText("Self Hosted Plan", { exact: true })).toBeVisible();
+ await expect(
+ page.getByText("Settings Self Hosted Billing Compare Prompt", { exact: true }),
+ ).toBeVisible();
+ await expect(page.getByText(/Pricing 4/i).first()).toBeVisible();
+
+ const screenshotPath = testInfo.outputPath("diagnostics-commercial-funnel.png");
+ await page.screenshot({ path: screenshotPath, fullPage: true });
+ console.log(`[diagnostics-commercial-funnel] screenshot: ${screenshotPath}`);
+});