// apps/admin/src/app/(admin)/subscriptions/page.tsx // D3RO Voice — Subscription Operations Console import { Box, Typography, Button } from '@mui/material' import { C, FONT_SANS, FONT_MONO, panelSx, tableSx, filterBtnSx, statusBadgeSx, primaryButtonSx } from '@/lib/console-theme' import { DoubleBezelCard, TactileBadge, StatRing } from '@d3ro/ui/components/ds' import { getSupabaseAdminClient, isSupabaseAdminConfigured } from '@/lib/supabase-admin' import { UnavailableAdminPanel } from '@/components/unavailable-admin-panel' import { hasMinRole, requireManager } from '@/lib/admin-guard' import { LicenseIssuerButton } from '@/components/license-issuer-button' import Link from 'next/link' interface SubRow { id: string user_id: string tier: string status: string payment_provider: string current_period_end: string | null cancel_at: string | null renewal_failures: number profile_name: string | null } interface PageProps { searchParams: Promise<{ status?: string }> } export default async function AdminSubscriptionsPage({ searchParams }: PageProps): Promise { if (!isSupabaseAdminConfigured()) { return ( ) } const params = await searchParams const statusFilter = params.status ?? 'all' if (!['all', 'active', 'canceled', 'past_due', 'expired'].includes(statusFilter)) { throw new Error('Invalid subscription status filter') } const admin = await requireManager() const supabase = await getSupabaseAdminClient() const rawSubsArr: Array> = [] for (let page = 0; page < 100; page += 1) { let query = supabase .from('subscriptions') .select('id, user_id, tier, status, payment_provider, current_period_end, cancel_at, renewal_failures') .order('current_period_end', { ascending: true }) .range(page * 500, page * 500 + 499) if (statusFilter !== 'all') query = query.eq('status', statusFilter) const { data, error } = await query if (error) throw new Error('Supabase subscriptions failed') rawSubsArr.push(...((data ?? []) as Array>)) if ((data?.length ?? 0) < 500) break if (page === 99) throw new Error('Supabase subscription directory exceeds the supported administrative window') } let subs: SubRow[] = [] if (rawSubsArr.length > 0) { const userIds = rawSubsArr.map((s) => s.user_id as string) const profileChunks = await Promise.all(Array.from({ length: Math.ceil(userIds.length / 200) }, (_, index) => supabase.from('profiles').select('id, name').in('id', userIds.slice(index * 200, index * 200 + 200)))) if (profileChunks.some((result) => result.error)) throw new Error('Supabase subscription profiles failed') const rawProfiles = profileChunks.flatMap((result) => result.data ?? []) const profileMap = new Map( ((rawProfiles ?? []) as Array>).map((p) => [p.id as string, (p.name as string) ?? null]) ) subs = rawSubsArr.map((row) => { if (typeof row.id !== 'string' || typeof row.user_id !== 'string' || typeof row.tier !== 'string' || typeof row.status !== 'string' || typeof row.payment_provider !== 'string' || !Number.isInteger(row.renewal_failures)) { throw new Error('Supabase subscription response contains an invalid row') } return { id: row.id, user_id: row.user_id, tier: row.tier, status: row.status, payment_provider: row.payment_provider, current_period_end: typeof row.current_period_end === 'string' ? row.current_period_end : null, cancel_at: typeof row.cancel_at === 'string' ? row.cancel_at : null, renewal_failures: row.renewal_failures as number, profile_name: profileMap.get(row.user_id) ?? null, } }) } const filteredSubs = statusFilter === 'all' ? subs : subs.filter((s) => s.status === statusFilter) return ( <> {/* Header */} Subscription Operations {subs.length} RECORDS Supabase subscriptions, payment providers, renewal state {['all', 'active', 'canceled', 'past_due', 'expired'].map((s) => ( {s.toUpperCase().replace('_', ' ')} ))} {hasMinRole(admin, 'super_admin') && } {hasMinRole(admin, 'admin') && ( )} {/* Revenue & Tier Distribution Top Bento */} Total Subscription Records # {subs.length.toLocaleString()} Persisted in Supabase Active Subscriptions ON {subs.filter((subscription) => subscription.status === 'active').length.toLocaleString()} Current status = active Renewal Failures % {subs.reduce((total, subscription) => total + subscription.renewal_failures, 0).toLocaleString()} Persisted retry failures {/* Subscription Table */} Subscription Contracts SHOWING {filteredSubs.length} RECORDS SUBSCRIBER TIER STATUS RENEWAL FAILURES PROVIDER EXPIRES / RENEWS ACTION {filteredSubs.length === 0 ? ( NO SUBSCRIPTIONS FOUND ) : ( filteredSubs.map((s) => { const isProPlus = s.tier === 'pro_plus' const isPro = s.tier === 'pro' return ( {s.profile_name ?? s.user_id} {s.user_id} {isProPlus ? 'PRO+ VIP' : s.tier.toUpperCase()} {s.status.toUpperCase()} {s.renewal_failures} {s.payment_provider} {s.current_period_end ? new Date(s.current_period_end).toLocaleDateString() : 'Not set'} ) }) )} ) }