Skip to content

Admin

The admin module provides a super-admin-only area for platform-wide visibility and control. It surfaces organization health, activity metrics, system configuration, provider status, and maintenance tools — all behind a strict is_super_admin gate.

Every admin endpoint calls ensure_super_admin(session) before processing. Non-super-admin users receive 403 Forbidden. The check reads session.is_super_admin — a boolean set during authentication.

pub fn ensure_super_admin(session: &Session) -> Result<(), HttpError> {
if session.is_super_admin {
Ok(())
} else {
HttpError::forbidden("Super admin access required")
}
}

The overview dashboard aggregates platform-wide KPIs, time-series charts, and attention items.

Data returned by GET /api/admin/overview:

FieldTypeDescription
total_orgsu64Total organizations on the platform
total_membersu64Total users across all orgs
active_orgsu64Orgs with activity in the selected time range
calls_in_range / messages_in_rangeu64Aggregate counts for the period
calls_change / messages_changeAdminKpiChangePeriod-over-period delta (current, previous, delta)
call_series / message_seriesVec<AdminChartPoint>Time-series data for charts
org_activity_rankingsVec<AdminOrgRankingItem>Top organizations by activity
channel_mixVec<AdminDistributionItem>Calls vs messages breakdown
twilio_mixVec<AdminDistributionItem>Managed vs BYO vs disconnected
webhook_healthVec<AdminDistributionItem>Active vs inactive webhooks
attention_orgsVec<AdminAttentionOrg>Orgs flagged with issues
recent_activityVec<AdminRecentActivityItem>Latest calls, messages, and admin actions

All time-range queries accept a TimeRange enum (Last7Days, Last30Days, Last90Days, etc.).

Lists all organizations with filtering, sorting, and health indicators.

Query parameters (AdminOrgQuery):

ParameterTypeOptions
searchOption<String>Free-text name search
twilio_statusOption<AdminTwilioStatus>NotConnected, Managed, Byo
healthAdminOrgHealthFilterAll, Healthy, NeedsAttention
activityAdminOrgActivityFilterAll, Active, Quiet
sortAdminOrgSortActivityDesc, NameAsc, CallsDesc, MessagesDesc, MembersDesc, LastActivityDesc, WebhookIssuesDesc

Each org row (AdminOrgListItem) includes member/phone counts, call/message totals, Twilio status, webhook health, and an activity_delta showing period-over-period change.

Drill into a single org via GET /api/admin/orgs/{id}. Returns AdminOrgDetailData with:

  • Metrics — members, roles, phones, calls, messages, last activity
  • Twilio diagnostics — connection status, masked SID, event sink/subscription presence, inactive webhooks
  • Attention items — list of issues requiring action
  • Config completeness — checklist of configuration steps (Vec<AdminConfigCompletenessItem>)
  • Editable config — org settings, profile, Twilio metadata (AdminOrgConfigData)
  • Audit trail — recent admin actions on this org

GET /api/admin/orgs/{id}/activity returns time-series charts, channel mix, phone inventory, top numbers by activity, and a timeline of recent events (AdminOrgActivityData).

PUT /api/admin/orgs/{id}/config accepts AdminOrgConfigData to update an org’s settings, profile, and Twilio metadata. Changes are audit-logged.

GET /api/admin/system-config returns AdminSystemConfigData — all platform-level credentials and provider settings:

FieldDescription
email_domain, email_user_adminEmail sending config
google_project_id, google_location, google_*Google Cloud / Gemini credentials
google_oauth_client_id, google_oauth_client_secretGoogle OAuth 2.0 client credentials
facebook_oauth_app_id, facebook_oauth_app_secretFacebook OAuth app credentials
twilio_main_sid, twilio_main_tokenPlatform Twilio account
openai_api_keyOpenAI API key
openrouter_api_keyOpenRouter API key
resend_api_keyResend email API key
provider_healthVec<AdminProviderHealth> — status of each provider
audit_entriesRecent system-level config changes

The System tab groups credentials into sections: Email, Google Cloud, Google sign-in (OAuth), Facebook sign-in (OAuth), Twilio, OpenAI, OpenRouter, and Resend. All credential fields default to password-masked inputs — click Reveal secrets to toggle visibility.

Update with PUT /api/admin/system-config. All credential changes are audit-logged with the actor’s user ID.

The provider readiness panel tracks configuration status for eight providers:

Provider KeyLabelChecks
twilio_mainTwilio (managed)SID + auth token present, SID starts with AC
openaiOpenAIAPI key present
openrouterOpenRouterAPI key present
resendResendAPI key present
google_vertexGoogle Vertex AIService account email + private key present
google_apiGoogle APIAPI key present
google_oauthGoogle OAuthClient ID + client secret present
facebook_oauthFacebook OAuthApp ID + app secret present

Each provider shows one of four states:

  • Missing — required credentials are empty
  • Untested — credentials present but never verified
  • Configured — credentials present and verified
  • Invalid — verification ran and failed (format or live check)

POST /api/admin/providers/{provider}/verify runs a health check against a provider. Pass the provider key as a path parameter (e.g. facebook_oauth, google_oauth). Returns AdminProviderVerificationResult with status, message, and timestamp. The verification result and timestamp are recorded in the audit log.

POST /api/admin/orgs/{id}/repair-event-sink re-provisions the Twilio SMS event sink for an organization. Use when sms_events_active is false or the event sink SID is missing.

POST /api/admin/orgs/{id}/repair-voice-webhooks re-syncs VoiceUrl webhooks on all managed phone numbers. Returns AdminRepairResult:

pub struct AdminRepairResult {
pub total: u64,
pub succeeded: u64,
pub skipped: u64,
pub failures: Vec<String>,
}

POST /api/admin/update-domain updates all Twilio phone number webhooks to the current APP_HOST. Use after DNS or hostname changes.

Every admin config change or maintenance action is recorded via record_admin_audit_entry. Query the audit log with:

GET /api/admin/config-audit?scope=system&org_id=<uuid>

Each entry (AdminConfigAuditEntry) includes:

FieldDescription
scope"system" or "org"
actionWhat was done (e.g. "update_system_config", "repair_event_sink")
title / summaryHuman-readable description
actor_nameWho performed the action
status"success" or "error"
created_atTimestamp

The Cost & Usage tab provides a unified view of AI spending, token usage, and Twilio expenses across the platform. Access it at /admin/tab/ai-costs.

Data returned by GET /api/admin/ai-costs?time_range:

The response includes AI cost KPIs, token totals, breakdowns by model/provider/feature/org, grouped time-series data for stacked charts, Twilio cost aggregations, and a grand total combining AI + Loquent-managed Twilio costs. Breakdown items include sparkline trends, efficiency metrics (cost per 1K tokens, cache hit %), and nested sub-items.

For full response shapes and Twilio pricing details, see Cost & Usage Dashboard.

MethodRouteDescription
GET/api/admin/ai-costsCost & usage analytics (AI + Twilio)
GET/api/admin/overviewPlatform KPIs and charts
GET/api/admin/orgsFilterable org list
GET/api/admin/orgs/{id}Org detail and diagnostics
GET/api/admin/orgs/{id}/activityOrg activity analytics
PUT/api/admin/orgs/{id}/configUpdate org configuration
POST/api/admin/orgs/{id}/repair-event-sinkRe-provision SMS event sink
POST/api/admin/orgs/{id}/repair-voice-webhooksRe-sync voice webhooks
GET/api/admin/system-configPlatform system config
PUT/api/admin/system-configUpdate system config
POST/api/admin/providers/{provider}/verifyVerify provider health
GET/api/admin/config-auditConfig audit log
POST/api/admin/update-domainBulk webhook domain update

All endpoints require an authenticated session with is_super_admin: true.

src/mods/admin/
├── api/ # Server function endpoints
├── components/ # UI: overview tab, organizations tab, system tab, org detail, forbidden state
├── services/ # Data aggregation, config CRUD, maintenance, audit logging
├── types/ # AdminOverviewData, AdminOrgDetailData, AdminSystemConfigData, etc.
└── views/ # Admin view (tabbed layout), org details view
  • Auth — ABAC — permission system and role checks
  • Twilio — webhook management and event sinks
  • Settings — per-org settings that admin can edit