feat(web): 관리자 CRM 웹페이지 — admin role + 4개 페이지

- migration: profiles.role 컬럼 + admin RLS 정책
- admin-guard.ts: RSC용 admin 권한 체크
- /admin: CRM 대시보드 (총 유저, 유료 구독자, API 호출, 만료 예정)
- /admin/users: 유저 목록 (검색/필터/페이지네이션)
- /admin/users/[id]: 유저 상세 (프로필+구독+30일 사용량)
- /admin/subscriptions: 구독 목록 (상태 필터)
- /admin/usage: 사용량 집계 (7/14/30일)
- Sidebar에 Admin 네비게이션 추가
This commit is contained in:
윤찬 2026-04-12 20:24:26 +09:00
parent d3c2a4348d
commit 667c09242b
10 changed files with 816 additions and 0 deletions

View file

@ -0,0 +1,56 @@
'use client'
// apps/web/src/app/(app)/admin/admin-nav.tsx
// Admin 하위 네비게이션 탭
import { usePathname, useRouter } from 'next/navigation'
import { Box } from '@mui/material'
import { PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette } from '@d3ro/ui/theme'
interface NavTab {
path: string
label: string
}
const TABS: NavTab[] = [
{ path: '/admin', label: 'OVERVIEW' },
{ path: '/admin/users', label: 'USERS' },
{ path: '/admin/subscriptions', label: 'SUBSCRIPTIONS' },
{ path: '/admin/usage', label: 'USAGE' },
]
export function AdminNav(): React.ReactElement {
const pathname = usePathname()
const router = useRouter()
return (
<Box sx={{ display: 'flex', gap: 1, mb: 3 }}>
{TABS.map((tab) => {
const active = tab.path === '/admin'
? pathname === '/admin'
: pathname.startsWith(tab.path)
return (
<Box
key={tab.path}
onClick={() => router.push(tab.path)}
sx={{
px: 2,
py: 0.75,
cursor: 'pointer',
borderRadius: 1,
bgcolor: active ? d3roPalette.bg.inset : 'transparent',
borderBottom: active ? `2px solid ${d3roPalette.accent.amber}` : '2px solid transparent',
transition: 'all 0.15s ease',
'&:hover': { bgcolor: d3roPalette.bg.inset },
}}
>
<PhosphorText variant="label" sx={{ color: active ? d3roPalette.accent.amber : d3roPalette.text.secondary }}>
{tab.label}
</PhosphorText>
</Box>
)
})}
</Box>
)
}

View file

@ -0,0 +1,27 @@
// apps/web/src/app/(app)/admin/layout.tsx
// Admin 전용 레이아웃 — requireAdmin() 가드 적용
import { Box } from '@mui/material'
import { PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette } from '@d3ro/ui/theme'
import { requireAdmin } from '@/lib/admin-guard'
import { AdminNav } from './admin-nav'
export default async function AdminLayout({
children,
}: {
children: React.ReactNode
}): Promise<React.ReactElement> {
await requireAdmin()
return (
<Box sx={{ p: 4, pb: 8 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
<PhosphorText variant="title">ADMIN</PhosphorText>
<Box sx={{ height: 1, flex: 1, bgcolor: d3roPalette.border.subtle }} />
</Box>
<AdminNav />
{children}
</Box>
)
}

View file

@ -0,0 +1,61 @@
// apps/web/src/app/(app)/admin/page.tsx
// Admin CRM 대시보드 — 요약 카드 4개
import { Box, Grid } from '@mui/material'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette } from '@d3ro/ui/theme'
import { getSupabaseServerClient } from '@/lib/supabase-server'
interface StatCard {
label: string
value: string | number
color?: string
}
async function loadStats(): Promise<StatCard[]> {
const supabase = await getSupabaseServerClient()
const [profilesRes, paidRes, usageRes, expiringRes] = await Promise.all([
supabase.from('profiles').select('id', { count: 'exact', head: true }),
supabase.from('subscriptions').select('id', { count: 'exact', head: true })
.neq('tier', 'free').eq('status', 'active'),
supabase.from('daily_usage').select('count')
.eq('date', new Date().toISOString().split('T')[0]),
supabase.from('subscriptions').select('id', { count: 'exact', head: true })
.eq('status', 'active').eq('payment_provider', 'payple')
.lte('current_period_end', new Date(Date.now() + 7 * 86400000).toISOString()),
])
const todayUsage = (usageRes.data as Array<{ count: number }> | null)
?.reduce((sum, r) => sum + (r.count ?? 0), 0) ?? 0
return [
{ label: 'TOTAL USERS', value: profilesRes.count ?? 0 },
{ label: 'PAID SUBSCRIBERS', value: paidRes.count ?? 0, color: d3roPalette.tag.green },
{ label: 'TODAY API CALLS', value: todayUsage, color: d3roPalette.accent.amber },
{ label: 'EXPIRING (7D)', value: expiringRes.count ?? 0, color: d3roPalette.tag.red },
]
}
export default async function AdminPage(): Promise<React.ReactElement> {
const stats = await loadStats()
return (
<Grid container spacing={2}>
{stats.map((stat) => (
<Grid size={{ xs: 12, sm: 6, md: 3 }} key={stat.label}>
<MetalCard>
<Box sx={{ textAlign: 'center', py: 2 }}>
<PhosphorText variant="label" sx={{ mb: 1, display: 'block', color: d3roPalette.text.label }}>
{stat.label}
</PhosphorText>
<PhosphorText variant="hero" sx={{ color: stat.color ?? d3roPalette.text.primary }}>
{stat.value}
</PhosphorText>
</Box>
</MetalCard>
</Grid>
))}
</Grid>
)
}

View file

@ -0,0 +1,127 @@
// apps/web/src/app/(app)/admin/subscriptions/page.tsx
// Admin 구독 목록 — active/canceled/past_due/expired 필터
import { Box } from '@mui/material'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, d3roFontMono, d3roTypo } from '@d3ro/ui/theme'
import { getSupabaseServerClient } from '@/lib/supabase-server'
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> {
const params = await searchParams
const statusFilter = params.status ?? 'all'
const supabase = await getSupabaseServerClient()
const subQuery = supabase
.from('subscriptions')
.select('id, user_id, tier, status, payment_provider, current_period_end, cancel_at')
.order('current_period_end', { ascending: true })
.limit(100)
if (statusFilter !== 'all') {
subQuery.eq('status', statusFilter)
}
const { data: rawSubs } = await subQuery
const rawSubsArr = (rawSubs ?? []) as Array<Record<string, unknown>>
// profiles name 조회
const userIds = rawSubsArr.map((s) => s.user_id as string)
const { data: rawProfiles } = userIds.length > 0
? await supabase.from('profiles').select('id, name').in('id', userIds)
: { data: [] }
const profileMap = new Map(
((rawProfiles ?? []) as Array<Record<string, unknown>>).map((p) => [p.id as string, (p.name as string) ?? null])
)
const subs: SubRow[] = rawSubsArr.map((row) => ({
id: row.id as string,
user_id: row.user_id as string,
tier: (row.tier as string) ?? 'free',
status: (row.status as string) ?? 'unknown',
payment_provider: (row.payment_provider as string) ?? 'none',
current_period_end: row.current_period_end as string | null,
cancel_at: row.cancel_at as string | null,
renewal_failures: (row.renewal_failures as number | undefined) ?? 0,
profile_name: profileMap.get(row.user_id as string) ?? null,
}))
return (
<Box>
<Box sx={{ display: 'flex', gap: 1, mb: 2 }}>
{['all', 'active', 'canceled', 'past_due', 'expired'].map((s) => (
<Link key={s} href={`/admin/subscriptions?status=${s}`} style={{ textDecoration: 'none' }}>
<PhosphorText
variant="label"
sx={{
px: 1.5, py: 0.5, borderRadius: 1, cursor: 'pointer',
bgcolor: statusFilter === s ? d3roPalette.bg.inset : 'transparent',
color: statusFilter === s ? d3roPalette.accent.amber : d3roPalette.text.secondary,
}}
>
{s.toUpperCase().replace('_', ' ')}
</PhosphorText>
</Link>
))}
</Box>
<MetalCard sx={{ overflow: 'auto' }}>
<Box
component="table"
sx={{
width: '100%', borderCollapse: 'collapse', fontFamily: d3roFontMono, fontSize: d3roTypo.small.size,
'& th, & td': { py: 0.75, px: 1.5, textAlign: 'left', borderBottom: `1px solid ${d3roPalette.border.subtle}` },
'& th': { color: d3roPalette.text.label, textTransform: 'uppercase', letterSpacing: d3roTypo.label.spacing },
}}
>
<thead>
<tr><th>USER</th><th>TIER</th><th>STATUS</th><th>PROVIDER</th><th>EXPIRES</th><th>CANCEL</th><th>FAILS</th></tr>
</thead>
<tbody>
{subs.map((s) => (
<tr key={s.id}>
<td>
<Link href={`/admin/users/${s.user_id}`} style={{ color: d3roPalette.accent.amber, textDecoration: 'none' }}>
{s.profile_name ?? s.user_id.substring(0, 8)}
</Link>
</td>
<td style={{ color: s.tier === 'pro_plus' ? d3roPalette.tag.purple : s.tier === 'pro' ? d3roPalette.tag.green : d3roPalette.text.secondary }}>
{s.tier === 'pro_plus' ? 'PRO+' : s.tier.toUpperCase()}
</td>
<td style={{ color: s.status === 'active' ? d3roPalette.tag.green : s.status === 'expired' ? d3roPalette.tag.red : d3roPalette.accent.amber }}>
{s.status.toUpperCase()}
</td>
<td>{s.payment_provider}</td>
<td style={{ color: d3roPalette.text.muted }}>
{s.current_period_end ? new Date(s.current_period_end).toLocaleDateString() : '-'}
</td>
<td style={{ color: s.cancel_at ? d3roPalette.tag.red : d3roPalette.text.muted }}>
{s.cancel_at ? new Date(s.cancel_at).toLocaleDateString() : '-'}
</td>
<td style={{ color: s.renewal_failures > 0 ? d3roPalette.tag.red : d3roPalette.text.muted }}>
{s.renewal_failures}
</td>
</tr>
))}
</tbody>
</Box>
</MetalCard>
</Box>
)
}

View file

@ -0,0 +1,145 @@
// apps/web/src/app/(app)/admin/usage/page.tsx
// Admin 사용량 집계 — feature별, 날짜 범위
import { Box, Grid } from '@mui/material'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, d3roFontMono, d3roTypo } from '@d3ro/ui/theme'
import { getSupabaseServerClient } from '@/lib/supabase-server'
interface UsageSummary {
feature: string
total: number
uniqueUsers: number
}
interface DailyRow {
date: string
feature: string
total: number
}
interface PageProps {
searchParams: Promise<{ days?: string }>
}
export default async function AdminUsagePage({ searchParams }: PageProps): Promise<React.ReactElement> {
const params = await searchParams
const days = parseInt(params.days ?? '7', 10)
const since = new Date(Date.now() - days * 86400000).toISOString().split('T')[0]
const supabase = await getSupabaseServerClient()
const { data: rawData } = await supabase
.from('daily_usage')
.select('date, feature, count, user_id')
.gte('date', since)
.order('date', { ascending: false })
const rows = (rawData ?? []) as Array<{ date: string; feature: string; count: number; user_id: string }>
// Feature별 집계
const featureMap = new Map<string, { total: number; users: Set<string> }>()
for (const r of rows) {
const entry = featureMap.get(r.feature) ?? { total: 0, users: new Set<string>() }
entry.total += r.count
entry.users.add(r.user_id)
featureMap.set(r.feature, entry)
}
const summaries: UsageSummary[] = Array.from(featureMap.entries())
.map(([feature, { total, users }]) => ({ feature, total, uniqueUsers: users.size }))
.sort((a, b) => b.total - a.total)
// 일별 집계
const dailyMap = new Map<string, Map<string, number>>()
for (const r of rows) {
const dayEntry = dailyMap.get(r.date) ?? new Map<string, number>()
dayEntry.set(r.feature, (dayEntry.get(r.feature) ?? 0) + r.count)
dailyMap.set(r.date, dayEntry)
}
const dailyRows: DailyRow[] = []
for (const [date, features] of dailyMap) {
for (const [feature, total] of features) {
dailyRows.push({ date, feature, total })
}
}
return (
<Box>
{/* Period Filter */}
<Box sx={{ display: 'flex', gap: 1, mb: 2 }}>
{[7, 14, 30].map((d) => (
<a key={d} href={`/admin/usage?days=${d}`} style={{ textDecoration: 'none' }}>
<PhosphorText
variant="label"
sx={{
px: 1.5, py: 0.5, borderRadius: 1,
bgcolor: days === d ? d3roPalette.bg.inset : 'transparent',
color: days === d ? d3roPalette.accent.amber : d3roPalette.text.secondary,
}}
>
{d}D
</PhosphorText>
</a>
))}
</Box>
{/* Feature Summaries */}
<Grid container spacing={2} sx={{ mb: 3 }}>
{summaries.map((s) => (
<Grid size={{ xs: 6, md: 3 }} key={s.feature}>
<MetalCard>
<Box sx={{ textAlign: 'center', py: 1 }}>
<PhosphorText variant="label" sx={{ mb: 0.5, display: 'block', color: d3roPalette.text.label }}>
{s.feature.toUpperCase()}
</PhosphorText>
<PhosphorText variant="value" sx={{ color: d3roPalette.accent.amber }}>
{s.total.toLocaleString()}
</PhosphorText>
<PhosphorText variant="dim" sx={{ display: 'block', mt: 0.5 }}>
{s.uniqueUsers} users
</PhosphorText>
</Box>
</MetalCard>
</Grid>
))}
</Grid>
{/* Daily Detail Table */}
<MetalCard sx={{ overflow: 'auto' }}>
<Box sx={{ p: 1 }}>
<PhosphorText variant="label" sx={{ mb: 1, display: 'block' }}>DAILY BREAKDOWN</PhosphorText>
<Box
component="table"
sx={{
width: '100%', borderCollapse: 'collapse', fontFamily: d3roFontMono, fontSize: d3roTypo.small.size,
'& th, & td': { py: 0.5, px: 1.5, textAlign: 'left', borderBottom: `1px solid ${d3roPalette.border.subtle}` },
'& th': { color: d3roPalette.text.label, textTransform: 'uppercase' },
}}
>
<thead>
<tr><th>DATE</th><th>FEATURE</th><th>CALLS</th></tr>
</thead>
<tbody>
{dailyRows.map((r, i) => (
<tr key={i}>
<td style={{ color: d3roPalette.text.muted }}>{r.date}</td>
<td>{r.feature}</td>
<td style={{ color: d3roPalette.accent.amber }}>{r.total.toLocaleString()}</td>
</tr>
))}
{dailyRows.length === 0 && (
<tr>
<td colSpan={3} style={{ textAlign: 'center', color: d3roPalette.text.muted }}>
No usage data
</td>
</tr>
)}
</tbody>
</Box>
</Box>
</MetalCard>
</Box>
)
}

View file

@ -0,0 +1,120 @@
// apps/web/src/app/(app)/admin/users/[id]/page.tsx
// Admin 유저 상세 — 프로필 + 구독 + 30일 사용량
import { Box, Grid } from '@mui/material'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, d3roFontMono, d3roTypo } from '@d3ro/ui/theme'
import { getSupabaseServerClient } from '@/lib/supabase-server'
import { notFound } from 'next/navigation'
interface PageProps {
params: Promise<{ id: string }>
}
export default async function AdminUserDetailPage({ params }: PageProps): Promise<React.ReactElement> {
const { id } = await params
const supabase = await getSupabaseServerClient()
const [profileRes, subRes, usageRes] = await Promise.all([
supabase.from('profiles').select('*').eq('id', id).maybeSingle(),
supabase.from('subscriptions').select('*').eq('user_id', id).maybeSingle(),
supabase.from('daily_usage').select('*')
.eq('user_id', id)
.gte('date', new Date(Date.now() - 30 * 86400000).toISOString().split('T')[0])
.order('date', { ascending: false }),
])
const profile = profileRes.data as Record<string, unknown> | null
if (!profile) notFound()
const sub = subRes.data as Record<string, unknown> | null
const usage = (usageRes.data ?? []) as Array<Record<string, unknown>>
const tier = (profile.tier as string) ?? 'free'
const tierColor = tier === 'pro_plus' ? d3roPalette.tag.purple : tier === 'pro' ? d3roPalette.tag.green : d3roPalette.accent.amber
return (
<Box>
{/* Profile Card */}
<Grid container spacing={2} sx={{ mb: 3 }}>
<Grid size={{ xs: 12, md: 6 }}>
<MetalCard>
<Box sx={{ p: 1 }}>
<PhosphorText variant="label" sx={{ mb: 1, display: 'block' }}>PROFILE</PhosphorText>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75, fontFamily: d3roFontMono, fontSize: d3roTypo.small.size }}>
<Row label="ID" value={id} />
<Row label="NAME" value={(profile.name as string) ?? '-'} />
<Row label="TIER" value={tier === 'pro_plus' ? 'PRO+' : tier.toUpperCase()} valueColor={tierColor} />
<Row label="ROLE" value={((profile.role as string) ?? 'user').toUpperCase()} />
<Row label="LOCALE" value={(profile.locale as string) ?? '-'} />
<Row label="JOINED" value={new Date(profile.created_at as string).toLocaleDateString()} />
</Box>
</Box>
</MetalCard>
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<MetalCard>
<Box sx={{ p: 1 }}>
<PhosphorText variant="label" sx={{ mb: 1, display: 'block' }}>SUBSCRIPTION</PhosphorText>
{sub ? (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75, fontFamily: d3roFontMono, fontSize: d3roTypo.small.size }}>
<Row label="STATUS" value={((sub.status as string) ?? '-').toUpperCase()}
valueColor={(sub.status as string) === 'active' ? d3roPalette.tag.green : d3roPalette.tag.red} />
<Row label="PROVIDER" value={((sub.payment_provider as string) ?? '-').toUpperCase()} />
<Row label="PERIOD START" value={sub.current_period_start ? new Date(sub.current_period_start as string).toLocaleDateString() : '-'} />
<Row label="PERIOD END" value={sub.current_period_end ? new Date(sub.current_period_end as string).toLocaleDateString() : '-'} />
<Row label="CANCEL AT" value={sub.cancel_at ? new Date(sub.cancel_at as string).toLocaleDateString() : '-'} />
<Row label="FAILURES" value={String(sub.renewal_failures ?? 0)} />
</Box>
) : (
<PhosphorText variant="dim">No subscription</PhosphorText>
)}
</Box>
</MetalCard>
</Grid>
</Grid>
{/* Usage (30 days) */}
<MetalCard>
<Box sx={{ p: 1 }}>
<PhosphorText variant="label" sx={{ mb: 1, display: 'block' }}>USAGE (30 DAYS)</PhosphorText>
{usage.length === 0 ? (
<PhosphorText variant="dim">No usage data</PhosphorText>
) : (
<Box
component="table"
sx={{
width: '100%', borderCollapse: 'collapse', fontFamily: d3roFontMono, fontSize: d3roTypo.small.size,
'& th, & td': { py: 0.5, px: 1, textAlign: 'left', borderBottom: `1px solid ${d3roPalette.border.subtle}` },
'& th': { color: d3roPalette.text.label, textTransform: 'uppercase' },
}}
>
<thead>
<tr><th>DATE</th><th>FEATURE</th><th>COUNT</th></tr>
</thead>
<tbody>
{usage.map((row, i) => (
<tr key={i}>
<td>{row.date as string}</td>
<td>{row.feature as string}</td>
<td style={{ color: d3roPalette.accent.amber }}>{row.count as number}</td>
</tr>
))}
</tbody>
</Box>
)}
</Box>
</MetalCard>
</Box>
)
}
function Row({ label, value, valueColor }: { label: string; value: string; valueColor?: string }): React.ReactElement {
return (
<Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ color: d3roPalette.text.label }}>{label}</span>
<span style={{ color: valueColor ?? d3roPalette.text.primary }}>{value}</span>
</Box>
)
}

View file

@ -0,0 +1,210 @@
// apps/web/src/app/(app)/admin/users/page.tsx
// Admin 유저 목록 — profiles JOIN subscriptions, 검색/필터/페이지네이션
import { Box } from '@mui/material'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, d3roFontMono, d3roTypo } from '@d3ro/ui/theme'
import { getSupabaseServerClient } from '@/lib/supabase-server'
import Link from 'next/link'
const PAGE_SIZE = 20
interface UserRow {
id: string
name: string | null
email: string | null
tier: string
role: string
created_at: string
subscription_status: string | null
payment_provider: string | null
}
async function loadUsers(page: number, search: string, tierFilter: string): Promise<{ users: UserRow[]; total: number }> {
const supabase = await getSupabaseServerClient()
// profiles 조회 (DB 타입에 role/조인이 미정의이므로 raw cast)
const from = page * PAGE_SIZE
const to = from + PAGE_SIZE - 1
// 단순 profiles 조회 + 별도 subscriptions 조회
const profileQuery = supabase
.from('profiles')
.select('id, name, tier, created_at', { count: 'exact' })
.order('created_at', { ascending: false })
.range(from, to)
if (search) {
profileQuery.ilike('name', `%${search}%`)
}
if (tierFilter && tierFilter !== 'all') {
profileQuery.eq('tier', tierFilter as 'free' | 'pro' | 'pro_plus')
}
const { data: rawProfiles, count } = await profileQuery
const profiles = (rawProfiles ?? []) as Array<Record<string, unknown>>
// 해당 유저들의 구독 정보 조회
const userIds = profiles.map((p) => p.id as string)
const { data: rawSubs } = userIds.length > 0
? await supabase.from('subscriptions').select('user_id, status, payment_provider').in('user_id', userIds)
: { data: [] }
const subs = (rawSubs ?? []) as Array<Record<string, unknown>>
const subMap = new Map(subs.map((s) => [s.user_id as string, s]))
// role 조회 (별도 raw query — DB 타입에 role 미정의)
const { data: rawRoles } = userIds.length > 0
? await supabase.from('profiles').select('id, role').in('id', userIds)
: { data: [] }
const roles = (rawRoles ?? []) as Array<Record<string, unknown>>
const roleMap = new Map(roles.map((r) => [r.id as string, (r.role as string) ?? 'user']))
const users: UserRow[] = profiles.map((row) => {
const sub = subMap.get(row.id as string)
return {
id: row.id as string,
name: row.name as string | null,
email: null,
tier: (row.tier as string) ?? 'free',
role: roleMap.get(row.id as string) ?? 'user',
created_at: row.created_at as string,
subscription_status: (sub?.status as string) ?? null,
payment_provider: (sub?.payment_provider as string) ?? null,
}
})
return { users, total: count ?? 0 }
}
interface PageProps {
searchParams: Promise<{ page?: string; search?: string; tier?: string }>
}
export default async function AdminUsersPage({ searchParams }: PageProps): Promise<React.ReactElement> {
const params = await searchParams
const page = parseInt(params.page ?? '0', 10)
const search = params.search ?? ''
const tierFilter = params.tier ?? 'all'
const { users, total } = await loadUsers(page, search, tierFilter)
const totalPages = Math.ceil(total / PAGE_SIZE)
return (
<Box>
{/* Filters */}
<Box sx={{ display: 'flex', gap: 2, mb: 2, alignItems: 'center' }}>
<PhosphorText variant="label" sx={{ color: d3roPalette.text.label }}>
{total} USERS
</PhosphorText>
<Box sx={{ flex: 1 }} />
{['all', 'free', 'pro', 'pro_plus'].map((t) => (
<Link
key={t}
href={`/admin/users?tier=${t}&search=${search}`}
style={{ textDecoration: 'none' }}
>
<PhosphorText
variant="label"
sx={{
px: 1.5, py: 0.5, borderRadius: 1, cursor: 'pointer',
bgcolor: tierFilter === t ? d3roPalette.bg.inset : 'transparent',
color: tierFilter === t ? d3roPalette.accent.amber : d3roPalette.text.secondary,
}}
>
{t === 'all' ? 'ALL' : t === 'pro_plus' ? 'PRO+' : t.toUpperCase()}
</PhosphorText>
</Link>
))}
</Box>
{/* Table */}
<MetalCard sx={{ overflow: 'auto' }}>
<Box
component="table"
sx={{
width: '100%',
borderCollapse: 'collapse',
fontFamily: d3roFontMono,
fontSize: d3roTypo.small.size,
'& th, & td': { py: 1, px: 1.5, textAlign: 'left', borderBottom: `1px solid ${d3roPalette.border.subtle}` },
'& th': { color: d3roPalette.text.label, fontWeight: d3roTypo.label.weight, textTransform: 'uppercase', letterSpacing: d3roTypo.label.spacing },
}}
>
<thead>
<tr>
<th>NAME</th>
<th>TIER</th>
<th>ROLE</th>
<th>STATUS</th>
<th>PROVIDER</th>
<th>JOINED</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>
<Link href={`/admin/users/${u.id}`} style={{ color: d3roPalette.accent.amber, textDecoration: 'none' }}>
{u.name ?? u.id.substring(0, 8)}
</Link>
</td>
<td>
<TierBadge tier={u.tier} />
</td>
<td style={{ color: u.role === 'admin' ? d3roPalette.tag.purple : d3roPalette.text.secondary }}>
{u.role.toUpperCase()}
</td>
<td style={{ color: u.subscription_status === 'active' ? d3roPalette.tag.green : d3roPalette.text.muted }}>
{u.subscription_status?.toUpperCase() ?? '-'}
</td>
<td style={{ color: d3roPalette.text.secondary }}>
{u.payment_provider ?? '-'}
</td>
<td style={{ color: d3roPalette.text.muted }}>
{new Date(u.created_at).toLocaleDateString()}
</td>
</tr>
))}
{users.length === 0 && (
<tr>
<td colSpan={6} style={{ textAlign: 'center', color: d3roPalette.text.muted, padding: '16px 0' }}>
No users found
</td>
</tr>
)}
</tbody>
</Box>
</MetalCard>
{/* Pagination */}
{totalPages > 1 && (
<Box sx={{ display: 'flex', justifyContent: 'center', gap: 1, mt: 2 }}>
{Array.from({ length: Math.min(totalPages, 10) }, (_, i) => (
<Link
key={i}
href={`/admin/users?page=${i}&tier=${tierFilter}&search=${search}`}
style={{ textDecoration: 'none' }}
>
<PhosphorText
variant="label"
sx={{
px: 1, py: 0.5, borderRadius: 1,
bgcolor: page === i ? d3roPalette.accent.amber : d3roPalette.bg.inset,
color: page === i ? d3roPalette.bg.app : d3roPalette.text.secondary,
}}
>
{i + 1}
</PhosphorText>
</Link>
))}
</Box>
)}
</Box>
)
}
function TierBadge({ tier }: { tier: string }): React.ReactElement {
const color = tier === 'pro_plus' ? d3roPalette.tag.purple : tier === 'pro' ? d3roPalette.tag.green : d3roPalette.text.secondary
const label = tier === 'pro_plus' ? 'PRO+' : tier.toUpperCase()
return <span style={{ color }}>{label}</span>
}

View file

@ -25,6 +25,7 @@ import LibraryBooksIcon from '@mui/icons-material/LibraryBooks'
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'
import GroupsIcon from '@mui/icons-material/Groups'
import PaymentIcon from '@mui/icons-material/Payment'
import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings'
import LogoutIcon from '@mui/icons-material/Logout'
import PaletteIcon from '@mui/icons-material/Palette'
import type { ThemeMode } from '@d3ro/core/types'
@ -99,6 +100,12 @@ export function Sidebar(): React.ReactElement {
path: '/billing',
label: t('nav.billing') ?? 'Billing',
icon: <PaymentIcon />
},
{
key: 'admin',
path: '/admin',
label: 'Admin',
icon: <AdminPanelSettingsIcon />
}
]

View file

@ -0,0 +1,32 @@
// apps/web/src/lib/admin-guard.ts
// RSC용 admin 가드 — profile.role='admin' 체크, 실패 시 redirect
import { redirect } from 'next/navigation'
import { getSupabaseServerClient } from './supabase-server'
interface AdminProfile {
id: string
name: string | null
role: string
}
export async function requireAdmin(): Promise<AdminProfile> {
const supabase = await getSupabaseServerClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
redirect('/login')
}
const { data: profile } = await supabase
.from('profiles')
.select('id, name, role')
.eq('id', user.id)
.maybeSingle()
if (!profile || (profile as { role: string }).role !== 'admin') {
redirect('/dashboard')
}
return profile as AdminProfile
}