d3ro-voice/apps/admin/src/app/(admin)/subscriptions/page.tsx

325 lines
14 KiB
TypeScript

// 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<React.ReactElement> {
if (!isSupabaseAdminConfigured()) {
return (
<UnavailableAdminPanel
title="Subscription Management"
capability="Plans, billing, payment history"
reason="SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY 환경변수가 설정되지 않아 Supabase 관리 데이터에 연결할 수 없습니다. 환경변수를 설정하면 실데이터가 표시됩니다."
/>
)
}
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<Record<string, unknown>> = []
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<Record<string, unknown>>))
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<Record<string, unknown>>).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 */}
<Box
sx={{
...panelSx,
minHeight: 84,
px: { xs: 2.5, md: 4 },
py: 2,
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
justifyContent: 'space-between',
gap: 2,
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Box
sx={{
width: 4,
height: 32,
borderRadius: '999px',
background: 'linear-gradient(180deg, var(--d3-tag-purple) 0%, var(--d3-accent-main) 100%)',
}}
/>
<Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
<Typography
component="h1"
sx={{
fontFamily: FONT_SANS,
fontSize: '20px',
fontWeight: 500,
color: C.bright,
letterSpacing: '-0.02em',
m: 0,
}}
>
Subscription Operations
</Typography>
<TactileBadge ledColor="purple" ledPulse tone="accent" mono>
{subs.length} RECORDS
</TactileBadge>
</Box>
<Typography
sx={{
fontFamily: FONT_MONO,
fontSize: '11px',
color: C.dim,
letterSpacing: 0,
mt: 0.25,
}}
>
Supabase subscriptions, payment providers, renewal state
</Typography>
</Box>
</Box>
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap' }}>
{['all', 'active', 'canceled', 'past_due', 'expired'].map((s) => (
<Link key={s} href={`/subscriptions?status=${s}`} style={{ textDecoration: 'none' }}>
<Box sx={filterBtnSx(statusFilter === s)}>
{s.toUpperCase().replace('_', ' ')}
</Box>
</Link>
))}
<Box sx={{ height: 20, width: '1px', bgcolor: C.borderHl, mx: 0.5 }} />
{hasMinRole(admin, 'super_admin') && <LicenseIssuerButton />}
{hasMinRole(admin, 'admin') && (
<Link href="/subscriptions/new" style={{ textDecoration: 'none' }}>
<Button variant="contained" size="small" sx={primaryButtonSx}>
+ Create Subscription
</Button>
</Link>
)}
</Box>
</Box>
{/* Revenue & Tier Distribution Top Bento */}
<Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', sm: 'repeat(3, 1fr)' }, gap: 2.5 }}>
<DoubleBezelCard interactive bezelPadding="5px" innerPadding="20px">
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1.5 }}>
<Typography sx={{ fontFamily: FONT_SANS, fontSize: '11px', fontWeight: 600, color: C.dim }}>
Total Subscription Records
</Typography>
<StatRing color="purple" size={38}>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '11px', fontWeight: 500 }}>#</Typography>
</StatRing>
</Box>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '24px', fontWeight: 500, color: C.bright }}>
{subs.length.toLocaleString()}
</Typography>
<Typography sx={{ fontFamily: FONT_SANS, fontSize: '11px', color: C.green400, mt: 0.5 }}>
Persisted in Supabase
</Typography>
</DoubleBezelCard>
<DoubleBezelCard interactive bezelPadding="5px" innerPadding="20px">
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1.5 }}>
<Typography sx={{ fontFamily: FONT_SANS, fontSize: '11px', fontWeight: 600, color: C.dim }}>
Active Subscriptions
</Typography>
<StatRing color="blue" size={38}>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '11px', fontWeight: 500 }}>ON</Typography>
</StatRing>
</Box>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '24px', fontWeight: 500, color: C.bright }}>
{subs.filter((subscription) => subscription.status === 'active').length.toLocaleString()}
</Typography>
<Typography sx={{ fontFamily: FONT_SANS, fontSize: '11px', color: C.cyanLight, mt: 0.5 }}>
Current status = active
</Typography>
</DoubleBezelCard>
<DoubleBezelCard interactive bezelPadding="5px" innerPadding="20px">
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1.5 }}>
<Typography sx={{ fontFamily: FONT_SANS, fontSize: '11px', fontWeight: 600, color: C.dim }}>
Renewal Failures
</Typography>
<StatRing color="green" size={38}>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '11px', fontWeight: 500 }}>%</Typography>
</StatRing>
</Box>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '24px', fontWeight: 500, color: C.green400 }}>
{subs.reduce((total, subscription) => total + subscription.renewal_failures, 0).toLocaleString()}
</Typography>
<Typography sx={{ fontFamily: FONT_SANS, fontSize: '11px', color: C.dim, mt: 0.5 }}>
Persisted retry failures
</Typography>
</DoubleBezelCard>
</Box>
{/* Subscription Table */}
<DoubleBezelCard bezelPadding="6px" innerPadding="24px">
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2.5 }}>
<Typography sx={{ fontFamily: FONT_SANS, fontSize: '16px', fontWeight: 500, color: C.bright }}>
Subscription Contracts
</Typography>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '11px', color: C.dim }}>
SHOWING {filteredSubs.length} RECORDS
</Typography>
</Box>
<Box sx={{ overflowX: 'auto' }}>
<Box component="table" sx={tableSx}>
<Box component="thead">
<Box component="tr">
<Box component="th">SUBSCRIBER</Box>
<Box component="th">TIER</Box>
<Box component="th">STATUS</Box>
<Box component="th">RENEWAL FAILURES</Box>
<Box component="th">PROVIDER</Box>
<Box component="th">EXPIRES / RENEWS</Box>
<Box component="th" sx={{ textAlign: 'right' }}>ACTION</Box>
</Box>
</Box>
<Box component="tbody">
{filteredSubs.length === 0 ? (
<Box component="tr">
<Box component="td" colSpan={7} sx={{ textAlign: 'center', color: C.dim, py: 4 }}>
NO SUBSCRIPTIONS FOUND
</Box>
</Box>
) : (
filteredSubs.map((s) => {
const isProPlus = s.tier === 'pro_plus'
const isPro = s.tier === 'pro'
return (
<Box component="tr" key={s.id}>
<Box component="td">
<Link href={`/users/${s.user_id}`} style={{ textDecoration: 'none' }}>
<Typography sx={{ fontFamily: FONT_SANS, fontSize: '13px', fontWeight: 600, color: C.accentLight }}>
{s.profile_name ?? s.user_id}
</Typography>
<Typography sx={{ fontFamily: FONT_MONO, fontSize: '11px', color: C.dim }}>
{s.user_id}
</Typography>
</Link>
</Box>
<Box component="td">
<Box component="span" sx={statusBadgeSx(isProPlus ? 'purple' : isPro ? 'green' : 'blue')}>
{isProPlus ? 'PRO+ VIP' : s.tier.toUpperCase()}
</Box>
</Box>
<Box component="td">
<Box component="span" sx={statusBadgeSx(s.status === 'active' ? 'green' : s.status === 'expired' ? 'red' : 'orange')}>
{s.status.toUpperCase()}
</Box>
</Box>
<Box component="td" sx={{ fontFamily: FONT_MONO, fontSize: '13px', fontWeight: 500, color: C.bright }}>
{s.renewal_failures}
</Box>
<Box component="td" sx={{ fontFamily: FONT_MONO, fontSize: '11px', color: C.dim }}>
{s.payment_provider}
</Box>
<Box component="td" sx={{ fontFamily: FONT_MONO, fontSize: '11px', color: C.text }}>
{s.current_period_end ? new Date(s.current_period_end).toLocaleDateString() : 'Not set'}
</Box>
<Box component="td" sx={{ textAlign: 'right' }}>
<Link href={`/subscriptions/${s.user_id}`} style={{ textDecoration: 'none' }}>
<Button
size="small"
variant="outlined"
sx={{
fontFamily: FONT_SANS,
fontSize: '11px',
fontWeight: 600,
color: C.accentLight,
borderColor: C.borderHl,
borderRadius: '8px',
textTransform: 'none',
px: 1.5,
'&:hover': { bgcolor: 'var(--d3-accent-glow)', borderColor: C.accentLight },
}}
>
Edit →
</Button>
</Link>
</Box>
</Box>
)
})
)}
</Box>
</Box>
</Box>
</DoubleBezelCard>
</>
)
}