diff --git a/apps/sim/app/api/organizations/[id]/usage/adoption/breakdown/route.ts b/apps/sim/app/api/organizations/[id]/usage/adoption/breakdown/route.ts new file mode 100644 index 00000000000..50e38997186 --- /dev/null +++ b/apps/sim/app/api/organizations/[id]/usage/adoption/breakdown/route.ts @@ -0,0 +1,28 @@ +import { getOrganizationAdoptionBreakdownContract } from '@/lib/api/contracts/organization-adoption' +import { + defineInternalJsonRoute, + internalRateLimits, + internalSessionAuth, +} from '@/lib/api/server/routes' +import { getOrganizationAdoptionBreakdown } from '@/lib/billing/application/organization-usage/get-organization-adoption' +import { organizationUsageOperations } from '@/lib/billing/application/organization-usage/operations' +import { organizationUsageErrorPolicy } from '@/app/api/organizations/[id]/usage/error-policy' + +export const dynamic = 'force-dynamic' + +export const GET = defineInternalJsonRoute({ + contract: getOrganizationAdoptionBreakdownContract, + auth: internalSessionAuth, + operation: organizationUsageOperations.readAdoption, + rateLimit: internalRateLimits.user({ bucketName: 'organization-adoption' }), + errorPolicy: organizationUsageErrorPolicy, + staticResponseHeaders: { 'Cache-Control': 'private, no-store' }, + mapInput: ({ params, query }) => ({ + ...query, + organizationId: params.id, + startDate: query.startDate ? new Date(query.startDate) : undefined, + endDate: query.endDate ? new Date(query.endDate) : undefined, + }), + useCase: getOrganizationAdoptionBreakdown, + present: (result) => result, +}) diff --git a/apps/sim/app/api/organizations/[id]/usage/adoption/export/route.ts b/apps/sim/app/api/organizations/[id]/usage/adoption/export/route.ts new file mode 100644 index 00000000000..154aebb7233 --- /dev/null +++ b/apps/sim/app/api/organizations/[id]/usage/adoption/export/route.ts @@ -0,0 +1,95 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { type NextRequest, NextResponse } from 'next/server' +import { + ADOPTION_SURFACE_LABELS, + ADOPTION_SURFACES, + exportOrganizationAdoptionContract, + type OrganizationAdoptionMember, +} from '@/lib/api/contracts/organization-adoption' +import { getValidationErrorMessage, parseRequest } from '@/lib/api/server' +import { projectInternalError } from '@/lib/api/server/routes' +import { getSession } from '@/lib/auth' +import { exportOrganizationAdoption } from '@/lib/billing/application/organization-usage/get-organization-adoption' +import { enforceUserRateLimit } from '@/lib/core/rate-limiter/route-helpers' +import { formatCsvValue, toCsvRow } from '@/lib/core/utils/csv' +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { organizationUsageErrorPolicy } from '@/app/api/organizations/[id]/usage/error-policy' + +const logger = createLogger('OrganizationAdoptionExportAPI') + +const CSV_HEADER = toCsvRow([ + 'Name', + 'Email', + 'Department', + 'Days active', + ...ADOPTION_SURFACES.map((surface) => ADOPTION_SURFACE_LABELS[surface]), + 'Last active in period (UTC)', +]) + +/** `formatCsvValue` neutralizes formula injection: names and departments are user-controlled. */ +function toCsvLine(row: OrganizationAdoptionMember): string { + return toCsvRow([ + formatCsvValue(row.name), + formatCsvValue(row.email), + formatCsvValue(row.department ?? ''), + formatCsvValue(String(row.daysActive)), + ...ADOPTION_SURFACES.map((surface) => formatCsvValue(String(row.uses[surface]))), + formatCsvValue(row.lastActiveAt ?? ''), + ]) +} + +/** + * One CSV row per member over the window. A raw handler rather than a JSON builder: the body is + * `text/csv`, and `X-Export-Truncated` tells the client when the member list was capped. + */ +export const GET = withRouteHandler(async (request: NextRequest, context) => { + try { + const session = await getSession() + const sessionId = session?.session?.id + if (!session?.user?.id || !sessionId) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + const limited = await enforceUserRateLimit('organization-adoption-export', session.user.id) + if (limited) return limited + + const parsed = await parseRequest(exportOrganizationAdoptionContract, request, context, { + validationErrorResponse: (error) => + NextResponse.json( + { error: getValidationErrorMessage(error, 'Invalid query parameters') }, + { status: 400 } + ), + }) + if (!parsed.success) return parsed.response + + const { query, params } = parsed.data + const result = await exportOrganizationAdoption.execute({ + principal: { kind: 'session', userId: session.user.id, sessionId }, + input: { + organizationId: params.id, + preset: query.preset, + startDate: query.startDate ? new Date(query.startDate) : undefined, + endDate: query.endDate ? new Date(query.endDate) : undefined, + timezone: query.timezone, + }, + }) + + const csv = [CSV_HEADER, ...result.rows.map(toCsvLine)].join('\n') + return new NextResponse(csv, { + headers: { + 'Content-Type': 'text/csv; charset=utf-8', + // Every member's activity for one organization, behind session auth; never cached. + 'Cache-Control': 'no-store', + 'Content-Disposition': `attachment; filename="organization-adoption-${params.id}.csv"`, + ...(result.truncated ? { 'X-Export-Truncated': '1' } : {}), + }, + }) + } catch (error) { + const refusal = projectInternalError(organizationUsageErrorPolicy, error) + if (refusal) { + return NextResponse.json(refusal.body, { status: refusal.status, headers: refusal.headers }) + } + logger.error('Failed to export organization adoption', { error: getErrorMessage(error) }) + return NextResponse.json({ error: 'Failed to export adoption' }, { status: 500 }) + } +}) diff --git a/apps/sim/app/api/organizations/[id]/usage/adoption/members/route.ts b/apps/sim/app/api/organizations/[id]/usage/adoption/members/route.ts new file mode 100644 index 00000000000..239fcb8fbcc --- /dev/null +++ b/apps/sim/app/api/organizations/[id]/usage/adoption/members/route.ts @@ -0,0 +1,28 @@ +import { listOrganizationAdoptionMembersContract } from '@/lib/api/contracts/organization-adoption' +import { + defineInternalJsonRoute, + internalRateLimits, + internalSessionAuth, +} from '@/lib/api/server/routes' +import { listOrganizationAdoptionMembers } from '@/lib/billing/application/organization-usage/get-organization-adoption' +import { organizationUsageOperations } from '@/lib/billing/application/organization-usage/operations' +import { organizationUsageErrorPolicy } from '@/app/api/organizations/[id]/usage/error-policy' + +export const dynamic = 'force-dynamic' + +export const GET = defineInternalJsonRoute({ + contract: listOrganizationAdoptionMembersContract, + auth: internalSessionAuth, + operation: organizationUsageOperations.readAdoption, + rateLimit: internalRateLimits.user({ bucketName: 'organization-adoption' }), + errorPolicy: organizationUsageErrorPolicy, + staticResponseHeaders: { 'Cache-Control': 'private, no-store' }, + mapInput: ({ params, query }) => ({ + ...query, + organizationId: params.id, + startDate: query.startDate ? new Date(query.startDate) : undefined, + endDate: query.endDate ? new Date(query.endDate) : undefined, + }), + useCase: listOrganizationAdoptionMembers, + present: (result) => result, +}) diff --git a/apps/sim/app/api/organizations/[id]/usage/adoption/summary/route.ts b/apps/sim/app/api/organizations/[id]/usage/adoption/summary/route.ts new file mode 100644 index 00000000000..78d24c4fde6 --- /dev/null +++ b/apps/sim/app/api/organizations/[id]/usage/adoption/summary/route.ts @@ -0,0 +1,28 @@ +import { getOrganizationAdoptionSummaryContract } from '@/lib/api/contracts/organization-adoption' +import { + defineInternalJsonRoute, + internalRateLimits, + internalSessionAuth, +} from '@/lib/api/server/routes' +import { getOrganizationAdoptionSummary } from '@/lib/billing/application/organization-usage/get-organization-adoption' +import { organizationUsageOperations } from '@/lib/billing/application/organization-usage/operations' +import { organizationUsageErrorPolicy } from '@/app/api/organizations/[id]/usage/error-policy' + +export const dynamic = 'force-dynamic' + +export const GET = defineInternalJsonRoute({ + contract: getOrganizationAdoptionSummaryContract, + auth: internalSessionAuth, + operation: organizationUsageOperations.readAdoption, + rateLimit: internalRateLimits.user({ bucketName: 'organization-adoption' }), + errorPolicy: organizationUsageErrorPolicy, + staticResponseHeaders: { 'Cache-Control': 'private, no-store' }, + mapInput: ({ params, query }) => ({ + ...query, + organizationId: params.id, + startDate: query.startDate ? new Date(query.startDate) : undefined, + endDate: query.endDate ? new Date(query.endDate) : undefined, + }), + useCase: getOrganizationAdoptionSummary, + present: (result) => result, +}) diff --git a/apps/sim/ee/organization-usage/components/activity-summary.tsx b/apps/sim/ee/organization-usage/components/activity-summary.tsx index 0d590c02a40..32cccae2ead 100644 --- a/apps/sim/ee/organization-usage/components/activity-summary.tsx +++ b/apps/sim/ee/organization-usage/components/activity-summary.tsx @@ -52,7 +52,7 @@ interface ActivitySummaryProps { onRetry?: () => void } -export function formatFailureRate(rate: number | null): string { +export function formatPercent(rate: number | null): string { return rate === null ? '—' : new Intl.NumberFormat(undefined, { @@ -101,7 +101,7 @@ export function ActivitySummary({ summary, loading, error, onRetry }: ActivitySu }, { label: 'Failure rate', - value: formatFailureRate(totals?.failureRate ?? null), + value: formatPercent(totals?.failureRate ?? null), description: 'Failed workflows as a share of completed and failed workflows.', }, { diff --git a/apps/sim/ee/organization-usage/components/activity-table.tsx b/apps/sim/ee/organization-usage/components/activity-table.tsx index 2614f9f9a95..0ec903fcc26 100644 --- a/apps/sim/ee/organization-usage/components/activity-table.tsx +++ b/apps/sim/ee/organization-usage/components/activity-table.tsx @@ -14,7 +14,7 @@ import { import { formatDuration } from '@sim/utils/formatting' import type { OrganizationActivityBreakdown } from '@/lib/api/contracts/organization-activity' import type { ActivityDimension } from '@/lib/billing/core/organization-activity' -import { formatFailureRate } from '@/ee/organization-usage/components/activity-summary' +import { formatPercent } from '@/ee/organization-usage/components/activity-summary' interface ActivityTableProps { rows: OrganizationActivityBreakdown['rows'] @@ -108,7 +108,7 @@ export function ActivityTable({ rows, dimension, onSelectWorkspace }: ActivityTa )} - {formatFailureRate(row.failureRate)} + {formatPercent(row.failureRate)} {row.averageDurationMs === null diff --git a/apps/sim/ee/organization-usage/components/adoption-panel.tsx b/apps/sim/ee/organization-usage/components/adoption-panel.tsx new file mode 100644 index 00000000000..8ace2b5ad2a --- /dev/null +++ b/apps/sim/ee/organization-usage/components/adoption-panel.tsx @@ -0,0 +1,395 @@ +'use client' + +import { useState } from 'react' +import { + Avatar, + BarChart, + ChartFrame, + Chip, + ChipDropdown, + cn, + DashboardMetric, + OverflowText, + scrollFadeAttributes, + scrollFadeXClass, + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, + useScrollEdges, +} from '@sim/emcn' +import { + ADOPTION_MAX_PAGE, + ADOPTION_SURFACE_LABELS, + ADOPTION_SURFACES, + type AdoptionBreakdownDimension, + type AdoptionMemberSort, + type OrganizationAdoptionBreakdown, + type OrganizationAdoptionMembers, +} from '@/lib/api/contracts/organization-adoption' +import { formatDateShort } from '@/lib/core/utils/date-display' +import { SettingsEmptyState } from '@/app/workspace/[workspaceId]/settings/components/settings-empty-state' +import { SettingsSection } from '@/app/workspace/[workspaceId]/settings/components/settings-section/settings-section' +import { formatPercent } from '@/ee/organization-usage/components/activity-summary' +import { USAGE_CHAT_COLOR, USAGE_PALETTE_CLASS } from '@/ee/organization-usage/constants' +import { useUsageWindow } from '@/ee/organization-usage/hooks/use-usage-window' +import { + useOrganizationAdoptionBreakdown, + useOrganizationAdoptionMembers, + useOrganizationAdoptionSummary, +} from '@/hooks/queries/organization-adoption' + +const CHART_HEIGHT = 180 + +const MEMBER_SORTS = [ + { value: 'days', label: 'Most days active' }, + { value: 'uses', label: 'Most uses' }, + { value: 'recent', label: 'Most recent' }, + { value: 'name', label: 'Name' }, +] as const + +const DIMENSIONS = [ + { value: 'department', label: 'Departments' }, + { value: 'mcp_tool', label: 'Search MCP tools' }, + { value: 'mcp_client', label: 'Search MCP clients' }, +] as const + +const BREAKDOWN_LABELS: Record = { + department: { row: 'Department', total: 'Members' }, + mcp_tool: { row: 'Tool', total: 'Calls' }, + mcp_client: { row: 'Client', total: 'Calls' }, +} + +/** Rows with no department, client name, or other key read as this. */ +const UNLABELED: Record = { + department: 'No department', + mcp_tool: 'Unknown tool', + mcp_client: 'Unnamed client', +} + +function breakdownLabel(dimension: AdoptionBreakdownDimension, label: string): string { + return label || UNLABELED[dimension] +} + +function count(value: number | undefined): string | undefined { + return value?.toLocaleString() +} + +interface AdoptionPanelProps { + organizationId: string +} + +export function AdoptionPanel({ organizationId }: AdoptionPanelProps) { + const { window, adoptionSort, adoptionPage, adoptionDimension, setState } = useUsageWindow() + const summary = useOrganizationAdoptionSummary(organizationId, window) + const members = useOrganizationAdoptionMembers(organizationId, window, adoptionSort, adoptionPage) + const breakdown = useOrganizationAdoptionBreakdown(organizationId, window, adoptionDimension) + + const data = summary.data + const metrics = [ + { + label: 'Active, last day', + value: count(data?.activeMembers.day), + description: 'Members active on the last day of the period, or today.', + }, + { + label: 'Active, last 7 days', + value: count(data?.activeMembers.week), + description: 'The 7 days ending with the period, or today.', + }, + { + label: 'Active, last 28 days', + value: count(data?.activeMembers.month), + description: 'The 28 days ending with the period, or today.', + }, + { + label: 'Coverage', + value: data ? formatPercent(data.coverage) : undefined, + description: 'Members active in this period, as a share of all members.', + }, + { + label: 'Stickiness', + value: data ? formatPercent(data.stickiness) : undefined, + description: 'Average daily active members, as a share of members active in this period.', + }, + ] + const series = data?.series.map((point) => ({ + timestamp: point.timestamp, + value: point.activeMembers, + })) + + return ( + <> + +
+
+ {metrics.map((metric) => ( + + ))} +
+ void summary.refetch()} + > + + + {data && ( +
+ + + + Surface + + Active members + + + Uses + + + + + {data.surfaces.map((row) => ( + + {ADOPTION_SURFACE_LABELS[row.surface]} + + {row.activeMembers.toLocaleString()} + + + {row.uses.toLocaleString()} + + + ))} + +
+
+ )} +
+
+ + +
+ + void setState({ adoptionSort: value as AdoptionMemberSort, adoptionPage: 0 }) + } + aria-label='Sort members by' + /> + {members.isError ? ( + + Couldn't load members. void members.refetch()}>Retry + + ) : !members.data ? ( + Loading members… + ) : ( + + )} + {(adoptionPage > 0 || members.data?.hasMore) && ( +
+ void setState({ adoptionPage: adoptionPage - 1 })} + > + Previous + + + {adoptionPage + 1} + + = ADOPTION_MAX_PAGE + } + onClick={() => void setState({ adoptionPage: adoptionPage + 1 })} + > + Next + +
+ )} + {adoptionPage >= ADOPTION_MAX_PAGE && members.data?.hasMore && ( + + The list and the CSV export both stop at 10,000 members. + + )} +
+
+ + +
+ + void setState({ adoptionDimension: value as AdoptionBreakdownDimension }) + } + aria-label='Break adoption down by' + /> + {breakdown.isError ? ( + + Couldn't load the breakdown.{' '} + void breakdown.refetch()}>Retry + + ) : !breakdown.data ? ( + Loading breakdown… + ) : breakdown.data.rows.length === 0 ? ( + No activity in this period. + ) : ( + <> + + {breakdown.data.truncated && ( + + Showing the 500 largest groups. + + )} + + )} +
+
+ + ) +} + +interface AdoptionMembersTableProps { + rows: OrganizationAdoptionMembers['rows'] +} + +function AdoptionMembersTable({ rows }: AdoptionMembersTableProps) { + /** The table scrolls inside its own wrapper; the fades follow that wrapper. */ + const [table, setTable] = useState(null) + const edges = useScrollEdges(table?.parentElement ?? null, { axis: 'x' }) + return ( +
+ + + + Member + Department + + Days active + + {ADOPTION_SURFACES.map((surface) => ( + + {ADOPTION_SURFACE_LABELS[surface]} + + ))} + + Last active in period + + + + + {rows.map((row) => ( + + +
+ +
+ + +
+
+
+ + + + + {row.daysActive.toLocaleString()} + + {ADOPTION_SURFACES.map((surface) => ( + + {row.uses[surface].toLocaleString()} + + ))} + + {row.lastActiveAt ? formatDateShort(row.lastActiveAt.slice(0, 10)) : '—'} + +
+ ))} +
+
+
+ ) +} + +interface AdoptionBreakdownTableProps { + rows: OrganizationAdoptionBreakdown['rows'] + dimension: AdoptionBreakdownDimension +} + +function AdoptionBreakdownTable({ rows, dimension }: AdoptionBreakdownTableProps) { + const labels = BREAKDOWN_LABELS[dimension] + const isMcp = dimension !== 'department' + return ( +
+ + + + {labels.row} + + Active members + + + {labels.total} + + {isMcp && ( + + Error rate + + )} + + + + {rows.map((row) => ( + + + + + + {row.activeMembers.toLocaleString()} + + + {row.total.toLocaleString()} + + {isMcp && ( + + {formatPercent(row.total ? (row.failed ?? 0) / row.total : null)} + + )} + + ))} + +
+
+ ) +} diff --git a/apps/sim/ee/organization-usage/components/usage-monitoring.tsx b/apps/sim/ee/organization-usage/components/usage-monitoring.tsx index d913a4cf14d..84473576846 100644 --- a/apps/sim/ee/organization-usage/components/usage-monitoring.tsx +++ b/apps/sim/ee/organization-usage/components/usage-monitoring.tsx @@ -27,6 +27,7 @@ import { SettingsSection } from '@/app/workspace/[workspaceId]/settings/componen import { serializeAuditLogFilters } from '@/ee/audit-logs/search-params' import { ActivityPanel } from '@/ee/organization-usage/components/activity-panel' import { OrganizationActivityOverview } from '@/ee/organization-usage/components/activity-summary' +import { AdoptionPanel } from '@/ee/organization-usage/components/adoption-panel' import { UsageCalendar } from '@/ee/organization-usage/components/usage-calendar' import { UsageConsumers } from '@/ee/organization-usage/components/usage-consumers' import { UsageCredits } from '@/ee/organization-usage/components/usage-credits' @@ -116,10 +117,11 @@ export function UsageMonitoring({ const isWorkspaceDetail = isWorkspaceSelected && (workspaceList.isLoading || workspaceName !== undefined) - /** Overview and Activity draw no ranked list of their own; the value is never fetched. */ + /** Overview, Activity and Adoption draw no ranked list of their own; the value is never fetched. */ + const drawsOwnPanel = isOverview || tab === 'activity' || tab === 'adoption' const dimension: UsageBreakdownDimension = isWorkspaceDetail ? 'workflow' - : isOverview || tab === 'activity' + : drawsOwnPanel ? 'member' : (tab as UsageBreakdownDimension) @@ -137,7 +139,7 @@ export function UsageMonitoring({ : undefined const breakdown = useOrganizationUsageBreakdown(organizationId, window, dimension, { - enabled: !isOverview && tab !== 'activity', + enabled: !drawsOwnPanel, limit: rowLimitFor(dimension), ...(isWorkspaceDetail && workspace ? { workspaceId: workspace } : {}), }) @@ -166,6 +168,7 @@ export function UsageMonitoring({ startDate: null, endDate: null, activityPage: 0, + adoptionPage: 0, }) } @@ -177,7 +180,13 @@ export function UsageMonitoring({ toast.error(`Select a range of ${MAX_CUSTOM_RANGE_DAYS} days or fewer`) return } - void setState({ preset: 'custom', startDate: nextStart, endDate: nextEnd, activityPage: 0 }) + void setState({ + preset: 'custom', + startDate: nextStart, + endDate: nextEnd, + activityPage: 0, + adoptionPage: 0, + }) setDatePickerOpen(false) } @@ -192,23 +201,28 @@ export function UsageMonitoring({ if (window.endDate) params.set('endDate', window.endDate) try { + const isAdoption = tab === 'adoption' // boundary-raw-fetch: downloads a CSV blob and reads X-Export-Truncated before saving — a plain anchor navigation can do neither const response = await fetch( - `/api/organizations/${organizationId}/usage/export?${params.toString()}` + `/api/organizations/${organizationId}/usage/${isAdoption ? 'adoption/' : ''}export?${params.toString()}` ) if (!response.ok) { toast.error('Failed to export usage') return } if (response.headers.get('X-Export-Truncated') === '1') { - toast.info('Export truncated — narrow the date range to see everything') + toast.info( + isAdoption + ? 'Export truncated — it includes the most active members' + : 'Export truncated — narrow the date range to see everything' + ) } const blob = await response.blob() const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url - link.download = `organization-usage-${new Date().toISOString().slice(0, 10)}.csv` + link.download = `organization-${isAdoption ? 'adoption' : 'usage'}-${new Date().toISOString().slice(0, 10)}.csv` document.body.appendChild(link) link.click() link.remove() @@ -306,6 +320,7 @@ export function UsageMonitoring({ workspace: null, expanded: null, activityPage: 0, + adoptionPage: 0, }) } /> @@ -361,13 +376,21 @@ export function UsageMonitoring({ isOverviewError={overview.isError} isOverviewPlaceholderData={overview.isPlaceholderData} onViewAll={(target) => - void setState({ tab: target, workspace: null, expanded: null, activityPage: 0 }) + void setState({ + tab: target, + workspace: null, + expanded: null, + activityPage: 0, + adoptionPage: 0, + }) } /> ) : tab === 'activity' ? ( + ) : tab === 'adoption' ? ( + ) : ( = { overview: 'Overview', activity: 'Activity', + adoption: 'Adoption', member: 'Members', workspace: 'Workspaces', model: 'Models', diff --git a/apps/sim/ee/organization-usage/hooks/use-usage-window.ts b/apps/sim/ee/organization-usage/hooks/use-usage-window.ts index 428844b5d50..3b1c136594d 100644 --- a/apps/sim/ee/organization-usage/hooks/use-usage-window.ts +++ b/apps/sim/ee/organization-usage/hooks/use-usage-window.ts @@ -2,6 +2,7 @@ import { getBrowserTimezone, isCalendarDate } from '@sim/utils/timezone' import { useQueryStates } from 'nuqs' +import { ADOPTION_MAX_PAGE } from '@/lib/api/contracts/organization-adoption' import { MAX_CUSTOM_RANGE_DAYS, type UsageWindowPreset, @@ -55,6 +56,9 @@ export function useUsageWindow() { activityDimension: state.activityDimension, activitySort: state.activitySort, activityPage: Math.min(ACTIVITY_MAX_PAGE, Math.max(0, state.activityPage)), + adoptionSort: state.adoptionSort, + adoptionPage: Math.min(ADOPTION_MAX_PAGE, Math.max(0, state.adoptionPage)), + adoptionDimension: state.adoptionDimension, expanded: state.expanded, preset, startDate: state.startDate, diff --git a/apps/sim/ee/organization-usage/search-params.ts b/apps/sim/ee/organization-usage/search-params.ts index 201ab5a7da9..51185d8b6c9 100644 --- a/apps/sim/ee/organization-usage/search-params.ts +++ b/apps/sim/ee/organization-usage/search-params.ts @@ -5,6 +5,10 @@ import { parseAsString, parseAsStringLiteral, } from 'nuqs/server' +import { + ADOPTION_BREAKDOWN_DIMENSIONS, + ADOPTION_MEMBER_SORTS, +} from '@/lib/api/contracts/organization-adoption' import { USAGE_BREAKDOWN_DIMENSIONS, USAGE_WINDOW_PRESETS, @@ -28,6 +32,9 @@ export const organizationUsageParsers = { activityDimension: parseAsStringLiteral(ACTIVITY_DIMENSIONS).withDefault('workspace'), activitySort: parseAsStringLiteral(ACTIVITY_SORTS).withDefault('runs'), activityPage: parseAsInteger.withDefault(0), + adoptionSort: parseAsStringLiteral(ADOPTION_MEMBER_SORTS).withDefault('days'), + adoptionPage: parseAsInteger.withDefault(0), + adoptionDimension: parseAsStringLiteral(ADOPTION_BREAKDOWN_DIMENSIONS).withDefault('department'), /** Track expanded dimensions separately because workspace detail contains multiple lists. */ expanded: parseAsArrayOf(parseAsStringLiteral(USAGE_BREAKDOWN_DIMENSIONS)).withDefault([]), } as const @@ -43,6 +50,9 @@ export const organizationUsageUrlKeys = { activityDimension: 'activity-group', activitySort: 'activity-sort', activityPage: 'activity-page', + adoptionSort: 'adoption-sort', + adoptionPage: 'adoption-page', + adoptionDimension: 'adoption-group', }, } as const diff --git a/apps/sim/hooks/queries/organization-adoption.ts b/apps/sim/hooks/queries/organization-adoption.ts new file mode 100644 index 00000000000..e257428ec09 --- /dev/null +++ b/apps/sim/hooks/queries/organization-adoption.ts @@ -0,0 +1,90 @@ +import { useQuery } from '@tanstack/react-query' +import { requestJson } from '@/lib/api/client/request' +import { + type AdoptionBreakdownDimension, + type AdoptionMemberSort, + getOrganizationAdoptionBreakdownContract, + getOrganizationAdoptionSummaryContract, + listOrganizationAdoptionMembersContract, +} from '@/lib/api/contracts/organization-adoption' +import { + type OrganizationUsageWindowKey, + organizationUsageKeys, +} from '@/hooks/queries/utils/organization-usage-keys' + +const ORGANIZATION_ADOPTION_STALE_TIME = 60 * 1000 + +const organizationAdoptionKeys = { + all: (organizationId: string) => + [...organizationUsageKeys.all(organizationId), 'adoption'] as const, + summary: (organizationId: string, window: OrganizationUsageWindowKey) => + [...organizationAdoptionKeys.all(organizationId), 'summary', window] as const, + members: ( + organizationId: string, + window: OrganizationUsageWindowKey, + sort: AdoptionMemberSort, + page: number + ) => [...organizationAdoptionKeys.all(organizationId), 'members', window, sort, page] as const, + breakdown: ( + organizationId: string, + window: OrganizationUsageWindowKey, + dimension: AdoptionBreakdownDimension + ) => [...organizationAdoptionKeys.all(organizationId), 'breakdown', window, dimension] as const, +} + +/** Active members by window and surface, and the daily active series, for one Insights period. */ +export function useOrganizationAdoptionSummary( + organizationId: string, + window: OrganizationUsageWindowKey +) { + return useQuery({ + queryKey: organizationAdoptionKeys.summary(organizationId, window), + queryFn: ({ signal }) => + requestJson(getOrganizationAdoptionSummaryContract, { + params: { id: organizationId }, + query: window, + signal, + }), + enabled: Boolean(organizationId), + staleTime: ORGANIZATION_ADOPTION_STALE_TIME, + }) +} + +/** One page of members with their use of each surface in the period. */ +export function useOrganizationAdoptionMembers( + organizationId: string, + window: OrganizationUsageWindowKey, + sort: AdoptionMemberSort, + page: number +) { + return useQuery({ + queryKey: organizationAdoptionKeys.members(organizationId, window, sort, page), + queryFn: ({ signal }) => + requestJson(listOrganizationAdoptionMembersContract, { + params: { id: organizationId }, + query: { ...window, sort, page }, + signal, + }), + enabled: Boolean(organizationId), + staleTime: ORGANIZATION_ADOPTION_STALE_TIME, + }) +} + +/** Adoption grouped by department, Search MCP tool, or Search MCP client. */ +export function useOrganizationAdoptionBreakdown( + organizationId: string, + window: OrganizationUsageWindowKey, + dimension: AdoptionBreakdownDimension +) { + return useQuery({ + queryKey: organizationAdoptionKeys.breakdown(organizationId, window, dimension), + queryFn: ({ signal }) => + requestJson(getOrganizationAdoptionBreakdownContract, { + params: { id: organizationId }, + query: { ...window, dimension }, + signal, + }), + enabled: Boolean(organizationId), + staleTime: ORGANIZATION_ADOPTION_STALE_TIME, + }) +} diff --git a/apps/sim/lib/api/contracts/organization-adoption.ts b/apps/sim/lib/api/contracts/organization-adoption.ts new file mode 100644 index 00000000000..d62250563eb --- /dev/null +++ b/apps/sim/lib/api/contracts/organization-adoption.ts @@ -0,0 +1,158 @@ +import { z } from 'zod' +import { organizationUsageSummaryQuerySchema } from '@/lib/api/contracts/organization-usage' +import { organizationIdSchema } from '@/lib/api/contracts/primitives' +import { defineRouteContract } from '@/lib/api/contracts/types' + +/** + * Organization adoption (enterprise): which members use which Sim surfaces, read from the daily + * per-member activity counts. Days are UTC calendar days. + */ + +export const ADOPTION_SURFACES = [ + 'assistant', + 'agent', + 'search', + 'search_mcp', + 'slack', + 'workflows', +] as const +export type AdoptionSurface = (typeof ADOPTION_SURFACES)[number] + +/** Total over the surfaces, so a new surface cannot ship without a label in the view and the export. */ +export const ADOPTION_SURFACE_LABELS: Record = { + assistant: 'Assistant', + agent: 'Agent chats', + search: 'Search page', + search_mcp: 'Search MCP', + slack: 'Slack', + workflows: 'Workflow runs', +} + +export const ADOPTION_MEMBER_SORTS = ['days', 'uses', 'recent', 'name'] as const +export type AdoptionMemberSort = (typeof ADOPTION_MEMBER_SORTS)[number] + +export const ADOPTION_BREAKDOWN_DIMENSIONS = ['department', 'mcp_tool', 'mcp_client'] as const +export type AdoptionBreakdownDimension = (typeof ADOPTION_BREAKDOWN_DIMENSIONS)[number] + +export const ADOPTION_PAGE_SIZE = 50 +export const ADOPTION_MAX_PAGE = 199 + +const adoptionWindowQuerySchema = organizationUsageSummaryQuerySchema.omit({ workspaceId: true }) + +const useCount = z.number().int().nonnegative() +const surfaceCountsSchema = z.object({ + assistant: useCount, + agent: useCount, + search: useCount, + search_mcp: useCount, + slack: useCount, + workflows: useCount, +}) satisfies z.ZodType> + +const organizationAdoptionSummarySchema = z.object({ + /** Current members of the organization. */ + members: z.number().int().nonnegative(), + /** Distinct members active in the 1, 7 and 28 days ending at the window's end (or now). */ + activeMembers: z.object({ + day: z.number().int().nonnegative(), + week: z.number().int().nonnegative(), + month: z.number().int().nonnegative(), + }), + /** Members active at least once in the window, and the share of members that is. */ + windowActiveMembers: z.number().int().nonnegative(), + coverage: z.number().min(0).max(1).nullable(), + /** Average daily active members over the window's active members. */ + stickiness: z.number().min(0).max(1).nullable(), + surfaces: z + .array( + z.object({ + surface: z.enum(ADOPTION_SURFACES), + activeMembers: z.number().int().nonnegative(), + uses: z.number().int().nonnegative(), + }) + ) + .length(ADOPTION_SURFACES.length), + series: z + .array(z.object({ timestamp: z.string(), activeMembers: z.number().int().nonnegative() })) + .max(1000), +}) +export type OrganizationAdoptionSummary = z.output + +const organizationAdoptionMembersQuerySchema = adoptionWindowQuerySchema.extend({ + sort: z.enum(ADOPTION_MEMBER_SORTS).default('days'), + page: z.coerce.number().int().min(0).max(ADOPTION_MAX_PAGE).default(0), +}) + +const organizationAdoptionMemberSchema = z.object({ + userId: z.string(), + name: z.string(), + email: z.string(), + image: z.string().optional(), + department: z.string().nullable(), + daysActive: z.number().int().nonnegative(), + uses: surfaceCountsSchema, + lastActiveAt: z.string().nullable(), +}) +export type OrganizationAdoptionMember = z.output + +const organizationAdoptionMembersSchema = z.object({ + rows: z.array(organizationAdoptionMemberSchema).max(ADOPTION_PAGE_SIZE), + hasMore: z.boolean(), +}) +export type OrganizationAdoptionMembers = z.output + +const organizationAdoptionBreakdownQuerySchema = adoptionWindowQuerySchema.extend({ + dimension: z.enum(ADOPTION_BREAKDOWN_DIMENSIONS).default('department'), +}) + +const organizationAdoptionBreakdownSchema = z.object({ + rows: z + .array( + z.object({ + id: z.string(), + label: z.string(), + activeMembers: z.number().int().nonnegative(), + /** Members in a department; calls for a Search MCP tool or client. */ + total: z.number().int().nonnegative(), + /** Search MCP calls that ended in an error. */ + failed: z.number().int().nonnegative().optional(), + }) + ) + .max(500), + /** More groups exist than the 500 returned, largest first. */ + truncated: z.boolean(), +}) +export type OrganizationAdoptionBreakdown = z.output + +export const getOrganizationAdoptionSummaryContract = defineRouteContract({ + method: 'GET', + path: '/api/organizations/[id]/usage/adoption/summary', + params: z.object({ id: organizationIdSchema }), + query: adoptionWindowQuerySchema, + response: { mode: 'json', schema: organizationAdoptionSummarySchema }, +}) + +export const listOrganizationAdoptionMembersContract = defineRouteContract({ + method: 'GET', + path: '/api/organizations/[id]/usage/adoption/members', + params: z.object({ id: organizationIdSchema }), + query: organizationAdoptionMembersQuerySchema, + response: { mode: 'json', schema: organizationAdoptionMembersSchema }, +}) + +export const getOrganizationAdoptionBreakdownContract = defineRouteContract({ + method: 'GET', + path: '/api/organizations/[id]/usage/adoption/breakdown', + params: z.object({ id: organizationIdSchema }), + query: organizationAdoptionBreakdownQuerySchema, + response: { mode: 'json', schema: organizationAdoptionBreakdownSchema }, +}) + +/** `mode: 'text'`: one CSV row per member over the window. */ +export const exportOrganizationAdoptionContract = defineRouteContract({ + method: 'GET', + path: '/api/organizations/[id]/usage/adoption/export', + params: z.object({ id: organizationIdSchema }), + query: adoptionWindowQuerySchema, + response: { mode: 'text' }, +}) diff --git a/apps/sim/lib/api/server/routes/index.ts b/apps/sim/lib/api/server/routes/index.ts index 23aefbfdbec..2eb8a1ff248 100644 --- a/apps/sim/lib/api/server/routes/index.ts +++ b/apps/sim/lib/api/server/routes/index.ts @@ -12,6 +12,7 @@ export { internalOrchestrationErrorPolicy, internalRateLimits, internalSessionAuth, + projectInternalError, } from '@/lib/api/server/routes/internal-json-route' export { concealCrossTenantResourceError, diff --git a/apps/sim/lib/billing/application/organization-usage/get-organization-adoption.ts b/apps/sim/lib/billing/application/organization-usage/get-organization-adoption.ts new file mode 100644 index 00000000000..97c42d8d96a --- /dev/null +++ b/apps/sim/lib/billing/application/organization-usage/get-organization-adoption.ts @@ -0,0 +1,73 @@ +import type { + AdoptionBreakdownDimension, + AdoptionMemberSort, +} from '@/lib/api/contracts/organization-adoption' +import { + type AuthorizedOrganizationUsageContext, + defineAuthorizedOrganizationUsageUseCase, +} from '@/lib/billing/application/organization-usage/authorized-organization-usage-use-case' +import type { OrganizationUsageSummaryInput } from '@/lib/billing/application/organization-usage/get-organization-usage-summary' +import { organizationUsageOperations } from '@/lib/billing/application/organization-usage/operations' +import { + ADOPTION_EXPORT_MAX_ROWS, + adoptionDays, + readAdoptionBreakdown, + readAdoptionMemberPage, + readAdoptionMembers, + readAdoptionSummary, +} from '@/lib/billing/core/organization-adoption' +import { resolveUsageAnalyticsWindow, usageWindowBounds } from '@/lib/billing/core/usage-analytics' + +type AdoptionWindowInput = Omit + +function resolveAdoptionDays( + input: AdoptionWindowInput, + context: AuthorizedOrganizationUsageContext +) { + const window = resolveUsageAnalyticsWindow({ + preset: input.preset, + period: context.period, + customStart: input.startDate, + customEnd: input.endDate, + timezone: input.timezone, + }) + return adoptionDays(context.organizationId, usageWindowBounds(window)) +} + +export const getOrganizationAdoptionSummary = defineAuthorizedOrganizationUsageUseCase({ + operation: organizationUsageOperations.readAdoption, + organizationId: (input: AdoptionWindowInput) => input.organizationId, + execute: ({ input, context }) => readAdoptionSummary(resolveAdoptionDays(input, context)), +}) + +export const listOrganizationAdoptionMembers = defineAuthorizedOrganizationUsageUseCase({ + operation: organizationUsageOperations.readAdoption, + organizationId: (input: AdoptionWindowInput & { sort: AdoptionMemberSort; page: number }) => + input.organizationId, + execute: ({ input, context }) => + readAdoptionMemberPage(resolveAdoptionDays(input, context), input.sort, input.page), +}) + +export const getOrganizationAdoptionBreakdown = defineAuthorizedOrganizationUsageUseCase({ + operation: organizationUsageOperations.readAdoption, + organizationId: (input: AdoptionWindowInput & { dimension: AdoptionBreakdownDimension }) => + input.organizationId, + execute: ({ input, context }) => + readAdoptionBreakdown(resolveAdoptionDays(input, context), input.dimension), +}) + +/** Every member, most active first, up to {@link ADOPTION_EXPORT_MAX_ROWS}. */ +export const exportOrganizationAdoption = defineAuthorizedOrganizationUsageUseCase({ + operation: organizationUsageOperations.exportAdoption, + organizationId: (input: AdoptionWindowInput) => input.organizationId, + async execute({ input, context }) { + const rows = await readAdoptionMembers(resolveAdoptionDays(input, context), 'days', { + limit: ADOPTION_EXPORT_MAX_ROWS + 1, + offset: 0, + }) + return { + rows: rows.slice(0, ADOPTION_EXPORT_MAX_ROWS), + truncated: rows.length > ADOPTION_EXPORT_MAX_ROWS, + } + }, +}) diff --git a/apps/sim/lib/billing/application/organization-usage/operations.ts b/apps/sim/lib/billing/application/organization-usage/operations.ts index e3bb9e686ed..269beac8350 100644 --- a/apps/sim/lib/billing/application/organization-usage/operations.ts +++ b/apps/sim/lib/billing/application/organization-usage/operations.ts @@ -57,6 +57,24 @@ export const organizationUsageOperations = { capability: 'none', ...BASE, }), + /** + * permission-group-exempt: organization adoption shows each member's use of Sim surfaces, governed by organization admin authority like the activity it sits beside + */ + readAdoption: defineOrganizationOperation({ + id: 'organization_usage.adoption.read', + contentDelivery: 'none', + capability: 'none', + ...BASE, + }), + /** + * permission-group-exempt: exports the same per-member adoption under the same organization admin authority + */ + exportAdoption: defineOrganizationOperation({ + id: 'organization_usage.adoption.export', + contentDelivery: 'none', + capability: 'none', + ...BASE, + }), /** * permission-group-exempt: the Insights overview reads the same pooled ledger as the summary, governed by organization billing-admin authority */ diff --git a/apps/sim/lib/billing/core/organization-adoption.integration.ts b/apps/sim/lib/billing/core/organization-adoption.integration.ts new file mode 100644 index 00000000000..d92f7f0e2aa --- /dev/null +++ b/apps/sim/lib/billing/core/organization-adoption.integration.ts @@ -0,0 +1,239 @@ +/** + * Organization adoption reads against real PostgreSQL: whose activity they count, the 1/7/28-day + * bounds, coverage and stickiness, the member list (inactive members included), and the + * department and Search MCP breakdowns. + */ +import { db } from '@sim/db' +import { + member, + memberProfile, + organization, + organizationMemberActivityDaily, + organizationSearchMcpInvocation, + user, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { and, eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import type { AdoptionSurface } from '@/lib/api/contracts/organization-adoption' +import { + adoptionDays, + readAdoptionBreakdown, + readAdoptionMemberPage, + readAdoptionSummary, +} from '@/lib/billing/core/organization-adoption' + +const organizationId = generateId() +const otherOrganizationId = generateId() +const [ana, ben, cal, formerId, otherOrgUser] = Array.from({ length: 5 }, () => generateId()) +const users = [ana, ben, cal, formerId, otherOrgUser] +const names = ['Ana', 'Ben', 'Cal', 'Former', 'Other'] +const anaMember = generateId() +const benMember = generateId() + +/** A 28-day window ending at the start of 2026-11-29 (UTC), so its last day is 2026-11-28. */ +const days = adoptionDays( + organizationId, + { start: new Date('2026-11-01T00:00:00Z'), end: new Date('2026-11-29T00:00:00Z') }, + new Date('2026-12-15T00:00:00Z') +) + +function activity( + userId: string, + day: string, + surface: AdoptionSurface, + eventCount = 1, + orgId = organizationId +) { + const at = new Date(`${day}T12:00:00Z`) + return { organizationId: orgId, userId, day, surface, eventCount, firstAt: at, lastAt: at } +} + +describe('organization adoption', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + users.map((id, index) => ({ + id, + name: names[index] ?? '', + email: `${id}@adoption.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db.insert(organization).values( + [organizationId, otherOrganizationId].map((id) => ({ + id, + name: 'Adoption fixture', + slug: `adoption-${id}`, + })) + ) + await db.insert(member).values([ + { id: anaMember, userId: ana, organizationId, role: 'member' }, + { id: benMember, userId: ben, organizationId, role: 'member' }, + { id: generateId(), userId: cal, organizationId, role: 'member' }, + { + id: generateId(), + userId: otherOrgUser, + organizationId: otherOrganizationId, + role: 'member', + }, + ]) + await db.insert(memberProfile).values([ + { memberId: anaMember, department: 'Engineering' }, + { memberId: benMember, department: 'Engineering' }, + ]) + await db + .insert(organizationMemberActivityDaily) + .values([ + activity(ana, '2026-11-28', 'assistant', 3), + activity(ana, '2026-11-25', 'search'), + activity(ana, '2026-11-02', 'slack'), + activity(ben, '2026-11-10', 'search_mcp', 4), + activity(ana, '2026-10-31', 'assistant'), + activity(formerId, '2026-11-28', 'assistant'), + activity(otherOrgUser, '2026-11-28', 'assistant', 1, otherOrganizationId), + ]) + await db.insert(organizationSearchMcpInvocation).values( + [ + ['search', 'success', '2026-11-10T09:00:00Z', null], + ['search', 'error', '2026-11-10T09:05:00Z', null], + ['chat', 'success', '2026-11-11T09:00:00Z', 'Claude'], + ['search', 'success', '2026-10-31T23:59:00Z', null], + ['search', 'success', '2026-11-12T09:00:00Z', null, formerId], + ].map(([toolName, outcome, createdAt, clientName, userId]) => ({ + id: generateId(), + organizationId, + userId: userId ?? ben, + authKind: clientName ? ('oauth_access_token' as const) : ('personal_api_key' as const), + oauthClientId: clientName ? 'client' : null, + clientName, + toolName: toolName as 'search' | 'chat', + outcome: outcome as 'success' | 'error', + durationMs: 5, + createdAt: new Date(createdAt as string), + })) + ) + }) + + afterAll(async () => { + await db + .delete(organization) + .where(inArray(organization.id, [organizationId, otherOrganizationId])) + await db.delete(user).where(inArray(user.id, users)) + }) + + it('counts current members only, over 1, 7 and 28 days ending at the window end', async () => { + const summary = await readAdoptionSummary(days) + + expect(summary.members).toBe(3) + expect(summary.activeMembers).toEqual({ day: 1, week: 1, month: 2 }) + expect(summary.windowActiveMembers).toBe(2) + expect(summary.coverage).toBeCloseTo(2 / 3) + expect( + Object.fromEntries(summary.surfaces.map((s) => [s.surface, [s.activeMembers, s.uses]])) + ).toEqual({ + assistant: [1, 3], + agent: [0, 0], + search: [1, 1], + search_mcp: [1, 4], + slack: [1, 1], + workflows: [0, 0], + }) + }) + + it('draws one point per day of the window and derives stickiness from it', async () => { + const summary = await readAdoptionSummary(days) + + expect(summary.series).toHaveLength(28) + expect(summary.series[0]).toEqual({ timestamp: '2026-11-01T00:00:00.000Z', activeMembers: 0 }) + expect(summary.series.at(-1)).toEqual({ + timestamp: '2026-11-28T00:00:00.000Z', + activeMembers: 1, + }) + expect(summary.stickiness).toBeCloseTo(4 / 28 / 2) + }) + + it('reads a window that starts after today as empty, with headlines still ending today', async () => { + const future = adoptionDays( + organizationId, + { start: new Date('2027-01-01T00:00:00Z'), end: new Date('2027-02-01T00:00:00Z') }, + new Date('2026-11-28T12:00:00Z') + ) + expect(future.from).toBe(future.to) + const summary = await readAdoptionSummary(future) + expect([summary.windowActiveMembers, summary.series.length]).toEqual([0, 0]) + expect(summary.activeMembers.day).toBe(1) + expect( + (await readAdoptionMemberPage(future, 'days', 0)).rows.every((row) => !row.daysActive) + ).toBe(true) + }) + + it('lists every current member, inactive ones included, most days active first', async () => { + const page = await readAdoptionMemberPage(days, 'days', 0) + + expect(page.hasMore).toBe(false) + expect(page.rows.map((row) => [row.name, row.daysActive, row.department])).toEqual([ + ['Ana', 3, 'Engineering'], + ['Ben', 1, 'Engineering'], + ['Cal', 0, null], + ]) + expect(page.rows[0]?.uses).toEqual({ + assistant: 3, + agent: 0, + search: 1, + search_mcp: 0, + slack: 1, + workflows: 0, + }) + expect(page.rows[0]?.lastActiveAt).toBe('2026-11-28T12:00:00.000Z') + expect(page.rows[2]?.lastActiveAt).toBeNull() + }) + + it('orders members by uses and by most recent activity', async () => { + const byUses = await readAdoptionMemberPage(days, 'uses', 0) + expect(byUses.rows.map((row) => [row.name, row.daysActive])).toEqual([ + ['Ana', 3], + ['Ben', 1], + ['Cal', 0], + ]) + await db + .insert(organizationMemberActivityDaily) + .values(activity(ben, '2026-11-27', 'search_mcp', 2)) + const byUsesAfter = await readAdoptionMemberPage(days, 'uses', 0) + expect(byUsesAfter.rows.map((row) => row.name)).toEqual(['Ben', 'Ana', 'Cal']) + const recent = await readAdoptionMemberPage(days, 'recent', 0) + expect(recent.rows.map((row) => row.name)).toEqual(['Ana', 'Ben', 'Cal']) + await db + .delete(organizationMemberActivityDaily) + .where( + and( + eq(organizationMemberActivityDaily.organizationId, organizationId), + eq(organizationMemberActivityDaily.userId, ben), + eq(organizationMemberActivityDaily.day, '2026-11-27') + ) + ) + }) + + it('breaks adoption down by department, with members who have none', async () => { + const { rows } = await readAdoptionBreakdown(days, 'department') + expect(rows.map((row) => [row.label, row.activeMembers, row.total])).toEqual([ + ['Engineering', 2, 2], + ['', 0, 1], + ]) + }) + + it('breaks Search MCP calls by current members in the window down by tool and by client', async () => { + const tools = await readAdoptionBreakdown(days, 'mcp_tool') + expect(tools.rows.map((row) => [row.label, row.total, row.failed, row.activeMembers])).toEqual([ + ['search', 2, 1, 1], + ['chat', 1, 0, 1], + ]) + const clients = await readAdoptionBreakdown(days, 'mcp_client') + expect(clients.rows.map((row) => [row.label, row.total])).toEqual([ + ['Personal API key', 2], + ['Claude', 1], + ]) + }) +}) diff --git a/apps/sim/lib/billing/core/organization-adoption.ts b/apps/sim/lib/billing/core/organization-adoption.ts new file mode 100644 index 00000000000..1fa2cdd2ed9 --- /dev/null +++ b/apps/sim/lib/billing/core/organization-adoption.ts @@ -0,0 +1,268 @@ +import { dbReplica } from '@sim/db' +import { + member, + memberProfile, + organizationMemberActivityDaily, + organizationSearchMcpInvocation, + user, +} from '@sim/db/schema' +import { type SQL, sql } from 'drizzle-orm' +import { + ADOPTION_PAGE_SIZE, + ADOPTION_SURFACES, + type AdoptionBreakdownDimension, + type AdoptionMemberSort, + type AdoptionSurface, + type OrganizationAdoptionBreakdown, + type OrganizationAdoptionMember, + type OrganizationAdoptionSummary, +} from '@/lib/api/contracts/organization-adoption' + +const DAY_MS = 86_400_000 +/** Groups per breakdown; past this the response says it is truncated. */ +const BREAKDOWN_MAX_ROWS = 500 +/** The longest export, in members; an organization larger than this exports its most active. */ +export const ADOPTION_EXPORT_MAX_ROWS = 10_000 + +/** A window as the UTC calendar days the daily counts are keyed by: `[from, to)`. */ +export interface AdoptionDays { + organizationId: string + from: string + to: string + /** The exclusive day the headline 1/7/28-day counts end at: the window's end, or today. */ + asOf: string + /** The instant the window started, for the Search MCP log, which keeps exact times. */ + start: Date + end: Date +} + +function utcDay(instant: Date): string { + return instant.toISOString().slice(0, 10) +} + +/** The UTC days a window touches, ending no later than today. */ +export function adoptionDays( + organizationId: string, + window: { start: Date; end: Date }, + now = new Date() +): AdoptionDays { + const end = window.end < now ? window.end : now + /** A window that starts after today is empty, not a window that runs backwards. */ + const asOf = utcDay(new Date(end.getTime() - 1 + DAY_MS)) + if (window.start >= end) { + const today = utcDay(end) + return { organizationId, from: today, to: today, asOf, start: end, end } + } + return { organizationId, from: utcDay(window.start), to: asOf, asOf, start: window.start, end } +} + +function dayBefore(day: string, days: number): string { + return utcDay(new Date(new Date(`${day}T00:00:00.000Z`).getTime() - days * DAY_MS)) +} + +/** Activity of current members only, so coverage and member lists agree with the member count. */ +function memberActivity(days: { organizationId: string; from: string; to: string }): SQL { + return sql` + SELECT d.user_id, d.day, d.surface, d.event_count, d.last_at + FROM ${organizationMemberActivityDaily} d + JOIN ${member} m ON m.user_id = d.user_id AND m.organization_id = d.organization_id + WHERE d.organization_id = ${days.organizationId} + AND d.day >= ${days.from}::date AND d.day < ${days.to}::date` +} + +function ratio(part: number, whole: number): number | null { + return whole > 0 ? Math.min(1, part / whole) : null +} + +export async function readAdoptionSummary( + days: AdoptionDays +): Promise { + const monthFrom = dayBefore(days.asOf, 28) + const from = monthFrom < days.from ? monthFrom : days.from + const activity = memberActivity({ organizationId: days.organizationId, from, to: days.asOf }) + const [[counts], surfaceRows, seriesRows] = await Promise.all([ + dbReplica.execute<{ + members: number + day: number + week: number + month: number + window_active: number + }>(sql` + WITH a AS (${activity}) + SELECT + (SELECT count(*)::int FROM ${member} WHERE organization_id = ${days.organizationId}) AS members, + count(DISTINCT user_id) FILTER (WHERE day >= ${dayBefore(days.asOf, 1)}::date)::int AS day, + count(DISTINCT user_id) FILTER (WHERE day >= ${dayBefore(days.asOf, 7)}::date)::int AS week, + count(DISTINCT user_id) FILTER (WHERE day >= ${monthFrom}::date)::int AS month, + count(DISTINCT user_id) FILTER ( + WHERE day >= ${days.from}::date AND day < ${days.to}::date + )::int AS window_active + FROM a`), + dbReplica.execute<{ + surface: AdoptionSurface + active_members: number + uses: number + }>(sql` + SELECT surface, count(DISTINCT user_id)::int AS active_members, sum(event_count)::int AS uses + FROM (${memberActivity(days)}) a + GROUP BY surface`), + dbReplica.execute<{ day: string; active_members: number }>(sql` + SELECT g.day::date::text AS day, count(DISTINCT a.user_id)::int AS active_members + FROM generate_series(${days.from}::date, ${days.to}::date - 1, interval '1 day') AS g(day) + LEFT JOIN (${memberActivity(days)}) a ON a.day = g.day::date + GROUP BY g.day + ORDER BY g.day`), + ]) + + const members = counts?.members ?? 0 + const windowActive = counts?.window_active ?? 0 + const bySurface = new Map(surfaceRows.map((row) => [row.surface, row])) + const dailyTotal = seriesRows.reduce((total, row) => total + row.active_members, 0) + return { + members, + activeMembers: { day: counts?.day ?? 0, week: counts?.week ?? 0, month: counts?.month ?? 0 }, + windowActiveMembers: windowActive, + coverage: ratio(windowActive, members), + stickiness: seriesRows.length ? ratio(dailyTotal / seriesRows.length, windowActive) : null, + surfaces: ADOPTION_SURFACES.map((surface) => ({ + surface, + activeMembers: bySurface.get(surface)?.active_members ?? 0, + uses: bySurface.get(surface)?.uses ?? 0, + })), + series: seriesRows.map((row) => ({ + timestamp: `${row.day}T00:00:00.000Z`, + activeMembers: row.active_members, + })), + } +} + +const MEMBER_ORDER: Record = { + days: sql`days_active DESC, uses DESC, name ASC, user_id ASC`, + uses: sql`uses DESC, days_active DESC, name ASC, user_id ASC`, + recent: sql`last_active_at DESC NULLS LAST, name ASC, user_id ASC`, + name: sql`name ASC, user_id ASC`, +} + +type MemberRow = { + user_id: string + name: string + email: string + image: string | null + department: string | null + days_active: number + uses: number + last_active_at: string | null +} & Record + +/** Every current member with their use of each surface in the window, inactive members included. */ +export async function readAdoptionMembers( + days: AdoptionDays, + sort: AdoptionMemberSort, + { limit, offset }: { limit: number; offset: number } +): Promise { + const perSurface = ADOPTION_SURFACES.map( + (surface) => + sql`coalesce(sum(a.event_count) FILTER (WHERE a.surface = ${surface}), 0)::int AS ${sql.identifier(surface)}` + ) + const rows = await dbReplica.execute(sql` + SELECT m.user_id, u.name, u.email, u.image, p.department, + count(DISTINCT a.day)::int AS days_active, + coalesce(sum(a.event_count), 0)::int AS uses, + ${sql.join(perSurface, sql`, `)}, + max(a.last_at) AS last_active_at + FROM ${member} m + JOIN ${user} u ON u.id = m.user_id + LEFT JOIN ${memberProfile} p ON p.member_id = m.id + LEFT JOIN (${memberActivity(days)}) a ON a.user_id = m.user_id + WHERE m.organization_id = ${days.organizationId} + GROUP BY m.user_id, u.name, u.email, u.image, p.department + ORDER BY ${MEMBER_ORDER[sort]} + LIMIT ${limit} OFFSET ${offset}`) + return rows.map((row) => ({ + userId: row.user_id, + name: row.name, + email: row.email, + ...(row.image ? { image: row.image } : {}), + department: row.department, + daysActive: row.days_active, + uses: { + assistant: row.assistant, + agent: row.agent, + search: row.search, + search_mcp: row.search_mcp, + slack: row.slack, + workflows: row.workflows, + }, + lastActiveAt: row.last_active_at ? new Date(row.last_active_at).toISOString() : null, + })) +} + +export async function readAdoptionMemberPage( + days: AdoptionDays, + sort: AdoptionMemberSort, + page: number +) { + const rows = await readAdoptionMembers(days, sort, { + limit: ADOPTION_PAGE_SIZE + 1, + offset: page * ADOPTION_PAGE_SIZE, + }) + return { rows: rows.slice(0, ADOPTION_PAGE_SIZE), hasMore: rows.length > ADOPTION_PAGE_SIZE } +} + +type BreakdownRow = { id: string; label: string; active_members: number; total: number } + +export async function readAdoptionBreakdown( + days: AdoptionDays, + dimension: AdoptionBreakdownDimension +): Promise { + if (dimension === 'department') { + const rows = await dbReplica.execute(sql` + SELECT coalesce(p.department, '') AS id, coalesce(p.department, '') AS label, + count(DISTINCT a.user_id)::int AS active_members, count(DISTINCT m.user_id)::int AS total + FROM ${member} m + LEFT JOIN ${memberProfile} p ON p.member_id = m.id + LEFT JOIN (${memberActivity(days)}) a ON a.user_id = m.user_id + WHERE m.organization_id = ${days.organizationId} + GROUP BY coalesce(p.department, '') + ORDER BY active_members DESC, total DESC, label ASC + LIMIT ${BREAKDOWN_MAX_ROWS + 1}`) + return { + truncated: rows.length > BREAKDOWN_MAX_ROWS, + rows: rows.slice(0, BREAKDOWN_MAX_ROWS).map((row) => ({ + id: row.id, + label: row.label, + activeMembers: row.active_members, + total: row.total, + })), + } + } + const key = + dimension === 'mcp_tool' + ? sql`i.tool_name` + : sql`coalesce(i.client_name, CASE i.auth_kind + WHEN 'personal_api_key' THEN 'Personal API key' + WHEN 'workspace_api_key' THEN 'Workspace API key' + ELSE '' END)` + const rows = await dbReplica.execute(sql` + SELECT ${key} AS id, ${key} AS label, + count(DISTINCT i.user_id)::int AS active_members, count(*)::int AS total, + count(*) FILTER (WHERE i.outcome = 'error')::int AS failed + FROM ${organizationSearchMcpInvocation} i + JOIN ${member} m ON m.user_id = i.user_id AND m.organization_id = i.organization_id + WHERE i.organization_id = ${days.organizationId} + AND i.created_at >= ${days.start.toISOString()}::timestamptz + AND i.created_at < ${days.end.toISOString()}::timestamptz + GROUP BY 1 + ORDER BY total DESC, label ASC + LIMIT ${BREAKDOWN_MAX_ROWS + 1}`) + return { + truncated: rows.length > BREAKDOWN_MAX_ROWS, + rows: rows.slice(0, BREAKDOWN_MAX_ROWS).map((row) => ({ + id: row.id, + label: row.label, + activeMembers: row.active_members, + total: row.total, + failed: row.failed, + })), + } +}