@payez/next-mvp 4.1.9 → 4.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/README.md +792 -792
  2. package/dist/api-handlers/auth/refresh.js +38 -15
  3. package/dist/auth/better-auth.js +4 -3
  4. package/dist/components/account/MobileNavDrawer.js +18 -18
  5. package/dist/components/account/UserAvatarMenu.js +1 -1
  6. package/dist/components/admin/AlertSettingsTab.js +40 -40
  7. package/dist/components/admin/LoggingSettingsTab.js +28 -28
  8. package/dist/lib/ensure-fresh-access-token.js +42 -8
  9. package/dist/lib/idp-fetch.js +25 -9
  10. package/dist/lib/session-store.d.ts +1 -0
  11. package/dist/lib/session-store.js +12 -8
  12. package/dist/lib/token-lifecycle.d.ts +2 -0
  13. package/dist/lib/token-lifecycle.js +21 -3
  14. package/dist/pages/login/page.js +28 -28
  15. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  16. package/package.json +893 -893
  17. package/scripts/dev-broker.ps1 +35 -35
  18. package/scripts/dev-local.ps1 +45 -45
  19. package/src/api/auth-handler.ts +548 -548
  20. package/src/api-handlers/account/change-password.ts +142 -142
  21. package/src/api-handlers/account/update-phone.ts +79 -79
  22. package/src/api-handlers/account/verify-email.ts +125 -125
  23. package/src/api-handlers/account/verify-sms.ts +125 -125
  24. package/src/api-handlers/admin/analytics.ts +443 -443
  25. package/src/api-handlers/admin/audit.ts +223 -223
  26. package/src/api-handlers/admin/index.ts +63 -63
  27. package/src/api-handlers/admin/redis-sessions.ts +251 -251
  28. package/src/api-handlers/admin/sessions.ts +318 -318
  29. package/src/api-handlers/admin/site-logs.ts +365 -365
  30. package/src/api-handlers/admin/users.ts +242 -242
  31. package/src/api-handlers/admin/vibe-data.ts +324 -324
  32. package/src/api-handlers/auth/refresh.ts +705 -682
  33. package/src/api-handlers/auth/signout.ts +199 -199
  34. package/src/api-handlers/auth/status.ts +20 -20
  35. package/src/api-handlers/auth/update-session.ts +110 -110
  36. package/src/api-handlers/auth/verify-code.ts +112 -112
  37. package/src/api-handlers/session/refresh-viability.ts +36 -36
  38. package/src/api-handlers/test/force-expire.ts +60 -60
  39. package/src/auth/auth-decision.ts +229 -229
  40. package/src/auth/better-auth.ts +467 -466
  41. package/src/auth/route-config.ts +219 -219
  42. package/src/auth/types/auth-types.ts +555 -555
  43. package/src/auth/types/index.ts +7 -7
  44. package/src/auth/utils/idp-client.ts +445 -445
  45. package/src/auth/utils/index.ts +6 -6
  46. package/src/auth/utils/token-utils.ts +243 -243
  47. package/src/client/AuthContext.tsx +143 -143
  48. package/src/client/fetch-with-auth.ts +47 -47
  49. package/src/components/SessionSync.tsx +138 -138
  50. package/src/components/SignalRHealthCheck.tsx +131 -131
  51. package/src/components/account/MobileNavDrawer.tsx +305 -305
  52. package/src/components/account/UserAvatarMenu.tsx +266 -266
  53. package/src/components/account/index.ts +13 -13
  54. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  55. package/src/components/admin/AnalyticsTab.tsx +703 -703
  56. package/src/components/admin/DataBrowserTab.tsx +505 -505
  57. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  58. package/src/components/admin/SessionsTab.tsx +414 -414
  59. package/src/components/admin/StatsTab.tsx +379 -379
  60. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  61. package/src/components/admin/index.ts +59 -59
  62. package/src/components/auth/FederatedAuthSection.tsx +95 -95
  63. package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
  64. package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
  65. package/src/components/auth/TraditionalAuthSection.tsx +99 -99
  66. package/src/components/recovery/CompleteStep.tsx +36 -36
  67. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  68. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  69. package/src/components/recovery/SetPasswordStep.tsx +97 -97
  70. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  71. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  72. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  73. package/src/components/ui/BetaBadge.tsx +58 -58
  74. package/src/components/ui/Footer.tsx +93 -93
  75. package/src/config/env.ts +57 -57
  76. package/src/config/logger.ts +62 -62
  77. package/src/config/vibe-log-transport.ts +264 -264
  78. package/src/hooks/useAuth.ts +117 -117
  79. package/src/hooks/useAuthSettings.ts +97 -97
  80. package/src/hooks/useAvailableProviders.ts +120 -120
  81. package/src/hooks/usePasswordValidation.ts +127 -127
  82. package/src/hooks/usePublicAuthSettings.ts +149 -149
  83. package/src/hooks/useSessionExpiration.ts +101 -101
  84. package/src/hooks/useViabilitySession.ts +336 -336
  85. package/src/index.ts +60 -60
  86. package/src/lib/api-handler.ts +643 -643
  87. package/src/lib/app-slug.ts +178 -178
  88. package/src/lib/ensure-fresh-access-token.ts +369 -335
  89. package/src/lib/geolocation.ts +265 -265
  90. package/src/lib/idp-fetch.ts +26 -10
  91. package/src/lib/jwt-decode.ts +82 -82
  92. package/src/lib/roles.ts +177 -177
  93. package/src/lib/session-store.ts +4 -1
  94. package/src/lib/site-logger.ts +245 -245
  95. package/src/lib/standardized-client-api.ts +901 -901
  96. package/src/lib/test-aware-get-token.ts +41 -41
  97. package/src/lib/token-lifecycle.ts +30 -3
  98. package/src/lib/user-agent-parser.ts +252 -252
  99. package/src/logging/api/admin-analytics.ts +51 -51
  100. package/src/logging/api/audit-log.ts +53 -53
  101. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  102. package/src/logging/components/AuditLogViewer.tsx +125 -125
  103. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  104. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  105. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  106. package/src/logging/hooks/useAuditLog.ts +24 -24
  107. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  108. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  109. package/src/logging/index.ts +18 -18
  110. package/src/logging/types/analytics.ts +81 -81
  111. package/src/logging/types/audit.ts +31 -31
  112. package/src/logging/types/index.ts +3 -3
  113. package/src/middleware/create-middleware.ts +663 -663
  114. package/src/middleware/rbac-check.ts +279 -279
  115. package/src/middleware/twofa-presets.ts +224 -224
  116. package/src/pages/admin-login/page.tsx +221 -221
  117. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  118. package/src/pages/admin-page-permissions/index.ts +7 -7
  119. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  120. package/src/pages/admin-roles/modals.tsx +469 -469
  121. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  122. package/src/pages/client-admin/index.ts +33 -33
  123. package/src/pages/coming-soon/page.tsx +83 -83
  124. package/src/pages/login/page.tsx +456 -456
  125. package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
  126. package/src/pages/profile/index.ts +9 -9
  127. package/src/pages/profile/page.tsx +166 -166
  128. package/src/pages/recovery/page.tsx +234 -234
  129. package/src/pages/roles/MyRolesPage.tsx +211 -211
  130. package/src/pages/roles/components.tsx +294 -294
  131. package/src/pages/roles/index.ts +17 -17
  132. package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
  133. package/src/pages/security/index.ts +9 -9
  134. package/src/pages/security/page.tsx +507 -507
  135. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  136. package/src/pages/settings/index.ts +9 -9
  137. package/src/pages/settings/page.tsx +47 -47
  138. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  139. package/src/pages/showcase/index.ts +13 -13
  140. package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
  141. package/src/pages/test-env/JwtInspectPage.tsx +456 -456
  142. package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
  143. package/src/pages/test-env/TestEnvPage.tsx +118 -118
  144. package/src/pages/test-env/index.ts +25 -25
  145. package/src/pages/verify-code/page.tsx +652 -652
  146. package/src/routes/account/update-phone.ts +13 -13
  147. package/src/routes/auth/logout.ts +108 -108
  148. package/src/routes/auth/nextauth.ts +45 -45
  149. package/src/routes/auth/settings.ts +75 -75
  150. package/src/routes/auth/viability.ts +224 -224
  151. package/src/server/auth-guard.ts +170 -170
  152. package/src/server/slim-middleware.ts +117 -117
  153. package/src/server/with-auth.ts +93 -93
  154. package/src/stores/authStore.ts +1899 -1899
  155. package/src/templates/instrumentation.ts +41 -41
  156. package/src/utils/logout.ts +30 -30
  157. package/src/vibe/client.ts +590 -590
  158. package/src/vibe/enterprise-auth.ts +208 -208
  159. package/src/vibe/errors.ts +185 -185
  160. package/src/vibe/generic.ts +431 -431
  161. package/src/vibe/hooks/index.ts +367 -367
  162. package/src/vibe/index.ts +132 -132
  163. package/src/vibe/sessions.ts +551 -551
  164. package/src/vibe/types.ts +577 -577
@@ -1,382 +1,382 @@
1
- 'use client';
2
-
3
- /**
4
- * =============================================================================
5
- * CLIENT SITE ADMIN - Your App's Admin Dashboard
6
- * =============================================================================
7
- *
8
- * This is the foundation for YOUR app-specific admin area.
9
- * The MVP admin (/admin) handles membership - this handles YOUR data.
10
- *
11
- * SEPARATION OF CONCERNS:
12
- * ┌─────────────────────────────────────────────────────────────────────┐
13
- * │ /admin (MVP Admin) │ /admin/[your-area] (This) │
14
- * │ ───────────────── │ ──────────────────────── │
15
- * │ • User authentication │ • Your app's collections │
16
- * │ • Sessions management │ • Your app's features │
17
- * │ • Role assignments │ • Content moderation │
18
- * │ • Tier/subscription mgmt │ • App-specific analytics │
19
- * │ • Site-wide analytics │ • Custom admin tools │
20
- * │ • vibe_app collection │ • your_app collection │
21
- * └─────────────────────────────────────────────────────────────────────┘
22
- *
23
- * USAGE:
24
- * ```tsx
25
- * // app/admin/your-area/page.tsx
26
- * import { ClientSiteAdminPage } from '@payez/next-mvp/pages/client-admin';
27
- *
28
- * export default function YourAdminPage() {
29
- * return (
30
- * <ClientSiteAdminPage
31
- * title="Your Admin"
32
- * subtitle="Manage your app data"
33
- * collectionName="your_collection"
34
- * tabs={[
35
- * { id: 'overview', label: 'Overview', icon: '📊' },
36
- * { id: 'items', label: 'Items', icon: '📦', table: 'items' },
37
- * ]}
38
- * renderTabContent={(tab, data) => <YourCustomContent />}
39
- * />
40
- * );
41
- * }
42
- * ```
43
- *
44
- * =============================================================================
45
- */
46
-
47
- import React, { useEffect, useState, useCallback } from 'react';
48
- import { authClient } from '../../client/better-auth-client';
49
- import { useRouter } from 'next/navigation';
50
- import Link from 'next/link';
51
-
52
- // Icons - using basic SVGs to avoid lucide dependency issues
53
- const IconRefresh = () => (
54
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
55
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
56
- </svg>
57
- );
58
-
59
- const IconArrowLeft = () => (
60
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
61
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
62
- </svg>
63
- );
64
-
65
- const IconShield = () => (
66
- <svg className="w-16 h-16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
67
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
68
- </svg>
69
- );
70
-
71
- const IconChart = ({ className = "w-5 h-5" }: { className?: string }) => (
72
- <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
73
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
74
- </svg>
75
- );
76
-
77
- export interface ClientAdminTab {
78
- id: string;
79
- label: string;
80
- icon: string;
81
- table?: string; // If set, will auto-fetch from this table
82
- }
83
-
84
- export interface TableStats {
85
- table: string;
86
- count: number;
87
- label: string;
88
- }
89
-
90
- export interface ClientSiteAdminProps {
91
- /** Admin area title */
92
- title: string;
93
- /** Subtitle shown under title */
94
- subtitle?: string;
95
- /** Vibe collection name for this admin area */
96
- collectionName: string;
97
- /** Tabs to display */
98
- tabs: ClientAdminTab[];
99
- /** Roles that can access (defaults to vibe_app_admin) */
100
- allowedRoles?: string[];
101
- /** Custom overview content renderer */
102
- renderOverview?: (stats: TableStats[]) => React.ReactNode;
103
- /** Custom tab content renderer */
104
- renderTabContent?: (tab: ClientAdminTab, data: any[], loading: boolean) => React.ReactNode;
105
- /** Theme detection function (optional) */
106
- isDark?: boolean;
107
- /** Back link URL (defaults to /) */
108
- backUrl?: string;
109
- /** Back link label (defaults to "Back to Site") */
110
- backLabel?: string;
111
- }
112
-
113
- export function ClientSiteAdminPage({
114
- title,
115
- subtitle = 'Manage your app data',
116
- collectionName,
117
- tabs,
118
- allowedRoles = ['vibe_app_admin'],
119
- renderOverview,
120
- renderTabContent,
121
- isDark: isDarkProp,
122
- backUrl = '/',
123
- backLabel = 'Back to Site',
124
- }: ClientSiteAdminProps) {
125
- const { data: sessionData, isPending } = authClient.useSession();
126
- const session = sessionData;
127
- const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
128
- const router = useRouter();
129
-
130
- // Theme detection
131
- const [isDarkState, setIsDarkState] = useState(false);
132
- useEffect(() => {
133
- if (isDarkProp === undefined) {
134
- const checkDark = () => {
135
- const isDark = document.documentElement.classList.contains('dark') ||
136
- window.matchMedia('(prefers-color-scheme: dark)').matches;
137
- setIsDarkState(isDark);
138
- };
139
- checkDark();
140
- const mq = window.matchMedia('(prefers-color-scheme: dark)');
141
- mq.addEventListener('change', checkDark);
142
- return () => mq.removeEventListener('change', checkDark);
143
- }
144
- }, [isDarkProp]);
145
- const isDark = isDarkProp ?? isDarkState;
146
-
147
- const [activeTab, setActiveTab] = useState(tabs[0]?.id || 'overview');
148
- const [tableData, setTableData] = useState<any[]>([]);
149
- const [loading, setLoading] = useState(false);
150
- const [stats, setStats] = useState<TableStats[]>([]);
151
- const [statsLoading, setStatsLoading] = useState(false);
152
-
153
- const userRoles = (session?.user as any)?.roles || [];
154
- const hasAccess = allowedRoles.some(role => userRoles.includes(role));
155
-
156
- const themeClasses = {
157
- bg: isDark ? 'bg-slate-950' : 'bg-gray-50',
158
- cardBg: isDark ? 'bg-slate-800 border-slate-700' : 'bg-white border-gray-200',
159
- headerBg: isDark ? 'bg-slate-900 border-slate-800' : 'bg-white border-gray-200',
160
- text: isDark ? 'text-white' : 'text-gray-900',
161
- textMuted: isDark ? 'text-slate-400' : 'text-gray-600',
162
- tabBg: isDark ? 'bg-slate-800' : 'bg-gray-100',
163
- tabActive: 'bg-amber-600 text-white shadow-lg',
164
- tabInactive: isDark ? 'text-slate-400 hover:bg-slate-700' : 'text-gray-600 hover:bg-gray-200',
165
- };
166
-
167
- // Fetch collection stats
168
- const fetchStats = useCallback(async () => {
169
- setStatsLoading(true);
170
- try {
171
- const res = await fetch(`/api/vibe/collections/${collectionName}/tables`);
172
- if (res.ok) {
173
- const data = await res.json();
174
- const tables = data.tables || data || [];
175
- setStats(tables.map((tbl: any) => ({
176
- table: typeof tbl === 'string' ? tbl : tbl.name,
177
- count: typeof tbl === 'object' ? (tbl.document_count || tbl.count || 0) : 0,
178
- label: (typeof tbl === 'string' ? tbl : tbl.name)
179
- .replace(/_/g, ' ')
180
- .replace(/\b\w/g, (c: string) => c.toUpperCase()),
181
- })));
182
- }
183
- } catch (err) {
184
- console.error('Failed to fetch stats:', err);
185
- } finally {
186
- setStatsLoading(false);
187
- }
188
- }, [collectionName]);
189
-
190
- // Fetch table data
191
- const fetchTableData = useCallback(async (tableName: string) => {
192
- setLoading(true);
193
- try {
194
- const res = await fetch(`/api/vibe/data/${collectionName}/${tableName}?limit=100`);
195
- if (res.ok) {
196
- const data = await res.json();
197
- setTableData(data.data || []);
198
- }
199
- } catch (err) {
200
- console.error('Failed to fetch table:', err);
201
- setTableData([]);
202
- } finally {
203
- setLoading(false);
204
- }
205
- }, [collectionName]);
206
-
207
- // Handle tab change
208
- const handleTabChange = useCallback((tabId: string) => {
209
- setActiveTab(tabId);
210
- const tab = tabs.find(t => t.id === tabId);
211
- if (tab?.table) {
212
- fetchTableData(tab.table);
213
- }
214
- }, [tabs, fetchTableData]);
215
-
216
- // Initial load
217
- useEffect(() => {
218
- if (status === 'unauthenticated') {
219
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(window.location.pathname)}`);
220
- } else if (status === 'authenticated' && !hasAccess) {
221
- router.push('/?error=unauthorized');
222
- } else if (status === 'authenticated' && hasAccess) {
223
- fetchStats();
224
- }
225
- }, [status, hasAccess, router, fetchStats]);
226
-
227
- // Loading state
228
- if (status === 'loading') {
229
- return (
230
- <div className={`min-h-screen flex items-center justify-center ${themeClasses.bg}`}>
231
- <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-amber-500" />
232
- </div>
233
- );
234
- }
235
-
236
- // Access denied
237
- if (status === 'authenticated' && !hasAccess) {
238
- return (
239
- <div className={`min-h-screen flex items-center justify-center ${themeClasses.bg}`}>
240
- <div className="text-center">
241
- <div className={isDark ? 'text-red-400' : 'text-red-500'}><IconShield /></div>
242
- <h1 className={`text-2xl font-bold mb-2 ${themeClasses.text}`}>Access Denied</h1>
243
- <p className={`mb-6 ${themeClasses.textMuted}`}>You need admin access for this area.</p>
244
- <Link href="/" className="inline-flex items-center gap-2 px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700">
245
- <IconArrowLeft /> Return to Home
246
- </Link>
247
- </div>
248
- </div>
249
- );
250
- }
251
-
252
- if (status === 'unauthenticated') return null;
253
-
254
- const currentTab = tabs.find(t => t.id === activeTab);
255
-
256
- return (
257
- <div className={`min-h-screen ${themeClasses.bg}`}>
258
- {/* Header */}
259
- <header className={`sticky top-0 z-40 border-b ${themeClasses.headerBg}`}>
260
- <div className="container mx-auto px-4 py-4">
261
- <div className="flex items-center justify-between">
262
- <div className="flex items-center gap-3">
263
- <div className={`p-2 rounded-lg ${isDark ? 'bg-amber-900/30' : 'bg-amber-100'}`}>
264
- <IconChart className={`w-5 h-5 ${isDark ? 'text-amber-400' : 'text-amber-600'}`} />
265
- </div>
266
- <div>
267
- <h1 className={`text-xl font-bold ${themeClasses.text}`}>{title}</h1>
268
- <p className={`text-sm ${themeClasses.textMuted}`}>{subtitle}</p>
269
- </div>
270
- </div>
271
- <div className="flex items-center gap-4">
272
- <button
273
- onClick={() => { fetchStats(); if (currentTab?.table) fetchTableData(currentTab.table); }}
274
- disabled={loading || statsLoading}
275
- className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors ${themeClasses.textMuted} ${isDark ? 'hover:bg-slate-800' : 'hover:bg-gray-100'} ${(loading || statsLoading) ? 'opacity-50' : ''}`}
276
- >
277
- <span className={(loading || statsLoading) ? 'animate-spin' : ''}><IconRefresh /></span>
278
- Refresh
279
- </button>
280
- <Link href={backUrl} className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors ${themeClasses.textMuted} ${isDark ? 'hover:bg-slate-800' : 'hover:bg-gray-100'}`}>
281
- <IconArrowLeft /> {backLabel}
282
- </Link>
283
- </div>
284
- </div>
285
- </div>
286
- </header>
287
-
288
- {/* Content */}
289
- <div className="container mx-auto px-4 py-6 space-y-6">
290
- {/* Tab Navigation */}
291
- <div className={`flex flex-wrap gap-1 p-1 rounded-xl ${themeClasses.tabBg}`}>
292
- {tabs.map((tab) => (
293
- <button
294
- key={tab.id}
295
- onClick={() => handleTabChange(tab.id)}
296
- className={`py-2 px-4 rounded-lg text-sm font-medium transition-all ${
297
- activeTab === tab.id ? themeClasses.tabActive : themeClasses.tabInactive
298
- }`}
299
- >
300
- <span className="mr-2">{tab.icon}</span>
301
- {tab.label}
302
- </button>
303
- ))}
304
- </div>
305
-
306
- {/* Tab Content */}
307
- {renderTabContent ? (
308
- renderTabContent(currentTab!, tableData, loading)
309
- ) : activeTab === 'overview' || !currentTab?.table ? (
310
- // Default Overview
311
- <div className="space-y-6">
312
- <div>
313
- <h2 className={`text-lg font-semibold mb-4 ${themeClasses.text}`}>Data Overview</h2>
314
- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
315
- {stats.map((stat) => (
316
- <Link
317
- key={stat.table}
318
- href={`/admin/data?collection=${collectionName}&table=${stat.table}`}
319
- className={`p-4 rounded-xl border transition-all hover:scale-[1.02] ${themeClasses.cardBg}`}
320
- >
321
- <p className={`text-xs font-medium ${themeClasses.textMuted}`}>{stat.label}</p>
322
- <p className={`text-2xl font-bold ${themeClasses.text}`}>
323
- {statsLoading ? '...' : stat.count.toLocaleString()}
324
- </p>
325
- </Link>
326
- ))}
327
- </div>
328
- </div>
329
- {renderOverview && renderOverview(stats)}
330
- </div>
331
- ) : (
332
- // Default Table View
333
- <div>
334
- <h2 className={`text-lg font-semibold mb-4 ${themeClasses.text}`}>
335
- {currentTab.label} ({tableData.length})
336
- </h2>
337
- {loading ? (
338
- <div className="flex items-center justify-center py-12">
339
- <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-500" />
340
- </div>
341
- ) : (
342
- <div className={`rounded-lg border overflow-hidden ${themeClasses.cardBg}`}>
343
- <div className="overflow-x-auto">
344
- <table className="w-full text-sm">
345
- <thead className={isDark ? 'bg-slate-800' : 'bg-gray-50'}>
346
- <tr>
347
- <th className={`px-4 py-3 text-left font-medium ${themeClasses.textMuted}`}>ID</th>
348
- <th className={`px-4 py-3 text-left font-medium ${themeClasses.textMuted}`}>User</th>
349
- <th className={`px-4 py-3 text-left font-medium ${themeClasses.textMuted}`}>Data</th>
350
- <th className={`px-4 py-3 text-left font-medium ${themeClasses.textMuted}`}>Created</th>
351
- </tr>
352
- </thead>
353
- <tbody className={`divide-y ${isDark ? 'divide-slate-700' : 'divide-gray-200'}`}>
354
- {tableData.length === 0 ? (
355
- <tr>
356
- <td colSpan={4} className={`px-4 py-8 text-center ${themeClasses.textMuted}`}>No data found</td>
357
- </tr>
358
- ) : tableData.map((row: any) => (
359
- <tr key={row.document_id} className={isDark ? 'hover:bg-slate-800/50' : 'hover:bg-gray-50'}>
360
- <td className={`px-4 py-3 ${themeClasses.text}`}>{row.document_id}</td>
361
- <td className={`px-4 py-3 ${themeClasses.text}`}>{row.user_id}</td>
362
- <td className={`px-4 py-3 ${themeClasses.textMuted} max-w-xs truncate`}>
363
- {JSON.stringify(row.data).substring(0, 50)}...
364
- </td>
365
- <td className={`px-4 py-3 ${themeClasses.textMuted}`}>
366
- {new Date(row.created_at).toLocaleDateString()}
367
- </td>
368
- </tr>
369
- ))}
370
- </tbody>
371
- </table>
372
- </div>
373
- </div>
374
- )}
375
- </div>
376
- )}
377
- </div>
378
- </div>
379
- );
380
- }
381
-
382
- export default ClientSiteAdminPage;
1
+ 'use client';
2
+
3
+ /**
4
+ * =============================================================================
5
+ * CLIENT SITE ADMIN - Your App's Admin Dashboard
6
+ * =============================================================================
7
+ *
8
+ * This is the foundation for YOUR app-specific admin area.
9
+ * The MVP admin (/admin) handles membership - this handles YOUR data.
10
+ *
11
+ * SEPARATION OF CONCERNS:
12
+ * ┌─────────────────────────────────────────────────────────────────────┐
13
+ * │ /admin (MVP Admin) │ /admin/[your-area] (This) │
14
+ * │ ───────────────── │ ──────────────────────── │
15
+ * │ • User authentication │ • Your app's collections │
16
+ * │ • Sessions management │ • Your app's features │
17
+ * │ • Role assignments │ • Content moderation │
18
+ * │ • Tier/subscription mgmt │ • App-specific analytics │
19
+ * │ • Site-wide analytics │ • Custom admin tools │
20
+ * │ • vibe_app collection │ • your_app collection │
21
+ * └─────────────────────────────────────────────────────────────────────┘
22
+ *
23
+ * USAGE:
24
+ * ```tsx
25
+ * // app/admin/your-area/page.tsx
26
+ * import { ClientSiteAdminPage } from '@payez/next-mvp/pages/client-admin';
27
+ *
28
+ * export default function YourAdminPage() {
29
+ * return (
30
+ * <ClientSiteAdminPage
31
+ * title="Your Admin"
32
+ * subtitle="Manage your app data"
33
+ * collectionName="your_collection"
34
+ * tabs={[
35
+ * { id: 'overview', label: 'Overview', icon: '📊' },
36
+ * { id: 'items', label: 'Items', icon: '📦', table: 'items' },
37
+ * ]}
38
+ * renderTabContent={(tab, data) => <YourCustomContent />}
39
+ * />
40
+ * );
41
+ * }
42
+ * ```
43
+ *
44
+ * =============================================================================
45
+ */
46
+
47
+ import React, { useEffect, useState, useCallback } from 'react';
48
+ import { authClient } from '../../client/better-auth-client';
49
+ import { useRouter } from 'next/navigation';
50
+ import Link from 'next/link';
51
+
52
+ // Icons - using basic SVGs to avoid lucide dependency issues
53
+ const IconRefresh = () => (
54
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
55
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
56
+ </svg>
57
+ );
58
+
59
+ const IconArrowLeft = () => (
60
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
61
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
62
+ </svg>
63
+ );
64
+
65
+ const IconShield = () => (
66
+ <svg className="w-16 h-16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
67
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
68
+ </svg>
69
+ );
70
+
71
+ const IconChart = ({ className = "w-5 h-5" }: { className?: string }) => (
72
+ <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
73
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
74
+ </svg>
75
+ );
76
+
77
+ export interface ClientAdminTab {
78
+ id: string;
79
+ label: string;
80
+ icon: string;
81
+ table?: string; // If set, will auto-fetch from this table
82
+ }
83
+
84
+ export interface TableStats {
85
+ table: string;
86
+ count: number;
87
+ label: string;
88
+ }
89
+
90
+ export interface ClientSiteAdminProps {
91
+ /** Admin area title */
92
+ title: string;
93
+ /** Subtitle shown under title */
94
+ subtitle?: string;
95
+ /** Vibe collection name for this admin area */
96
+ collectionName: string;
97
+ /** Tabs to display */
98
+ tabs: ClientAdminTab[];
99
+ /** Roles that can access (defaults to vibe_app_admin) */
100
+ allowedRoles?: string[];
101
+ /** Custom overview content renderer */
102
+ renderOverview?: (stats: TableStats[]) => React.ReactNode;
103
+ /** Custom tab content renderer */
104
+ renderTabContent?: (tab: ClientAdminTab, data: any[], loading: boolean) => React.ReactNode;
105
+ /** Theme detection function (optional) */
106
+ isDark?: boolean;
107
+ /** Back link URL (defaults to /) */
108
+ backUrl?: string;
109
+ /** Back link label (defaults to "Back to Site") */
110
+ backLabel?: string;
111
+ }
112
+
113
+ export function ClientSiteAdminPage({
114
+ title,
115
+ subtitle = 'Manage your app data',
116
+ collectionName,
117
+ tabs,
118
+ allowedRoles = ['vibe_app_admin'],
119
+ renderOverview,
120
+ renderTabContent,
121
+ isDark: isDarkProp,
122
+ backUrl = '/',
123
+ backLabel = 'Back to Site',
124
+ }: ClientSiteAdminProps) {
125
+ const { data: sessionData, isPending } = authClient.useSession();
126
+ const session = sessionData;
127
+ const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
128
+ const router = useRouter();
129
+
130
+ // Theme detection
131
+ const [isDarkState, setIsDarkState] = useState(false);
132
+ useEffect(() => {
133
+ if (isDarkProp === undefined) {
134
+ const checkDark = () => {
135
+ const isDark = document.documentElement.classList.contains('dark') ||
136
+ window.matchMedia('(prefers-color-scheme: dark)').matches;
137
+ setIsDarkState(isDark);
138
+ };
139
+ checkDark();
140
+ const mq = window.matchMedia('(prefers-color-scheme: dark)');
141
+ mq.addEventListener('change', checkDark);
142
+ return () => mq.removeEventListener('change', checkDark);
143
+ }
144
+ }, [isDarkProp]);
145
+ const isDark = isDarkProp ?? isDarkState;
146
+
147
+ const [activeTab, setActiveTab] = useState(tabs[0]?.id || 'overview');
148
+ const [tableData, setTableData] = useState<any[]>([]);
149
+ const [loading, setLoading] = useState(false);
150
+ const [stats, setStats] = useState<TableStats[]>([]);
151
+ const [statsLoading, setStatsLoading] = useState(false);
152
+
153
+ const userRoles = (session?.user as any)?.roles || [];
154
+ const hasAccess = allowedRoles.some(role => userRoles.includes(role));
155
+
156
+ const themeClasses = {
157
+ bg: isDark ? 'bg-slate-950' : 'bg-gray-50',
158
+ cardBg: isDark ? 'bg-slate-800 border-slate-700' : 'bg-white border-gray-200',
159
+ headerBg: isDark ? 'bg-slate-900 border-slate-800' : 'bg-white border-gray-200',
160
+ text: isDark ? 'text-white' : 'text-gray-900',
161
+ textMuted: isDark ? 'text-slate-400' : 'text-gray-600',
162
+ tabBg: isDark ? 'bg-slate-800' : 'bg-gray-100',
163
+ tabActive: 'bg-amber-600 text-white shadow-lg',
164
+ tabInactive: isDark ? 'text-slate-400 hover:bg-slate-700' : 'text-gray-600 hover:bg-gray-200',
165
+ };
166
+
167
+ // Fetch collection stats
168
+ const fetchStats = useCallback(async () => {
169
+ setStatsLoading(true);
170
+ try {
171
+ const res = await fetch(`/api/vibe/collections/${collectionName}/tables`);
172
+ if (res.ok) {
173
+ const data = await res.json();
174
+ const tables = data.tables || data || [];
175
+ setStats(tables.map((tbl: any) => ({
176
+ table: typeof tbl === 'string' ? tbl : tbl.name,
177
+ count: typeof tbl === 'object' ? (tbl.document_count || tbl.count || 0) : 0,
178
+ label: (typeof tbl === 'string' ? tbl : tbl.name)
179
+ .replace(/_/g, ' ')
180
+ .replace(/\b\w/g, (c: string) => c.toUpperCase()),
181
+ })));
182
+ }
183
+ } catch (err) {
184
+ console.error('Failed to fetch stats:', err);
185
+ } finally {
186
+ setStatsLoading(false);
187
+ }
188
+ }, [collectionName]);
189
+
190
+ // Fetch table data
191
+ const fetchTableData = useCallback(async (tableName: string) => {
192
+ setLoading(true);
193
+ try {
194
+ const res = await fetch(`/api/vibe/data/${collectionName}/${tableName}?limit=100`);
195
+ if (res.ok) {
196
+ const data = await res.json();
197
+ setTableData(data.data || []);
198
+ }
199
+ } catch (err) {
200
+ console.error('Failed to fetch table:', err);
201
+ setTableData([]);
202
+ } finally {
203
+ setLoading(false);
204
+ }
205
+ }, [collectionName]);
206
+
207
+ // Handle tab change
208
+ const handleTabChange = useCallback((tabId: string) => {
209
+ setActiveTab(tabId);
210
+ const tab = tabs.find(t => t.id === tabId);
211
+ if (tab?.table) {
212
+ fetchTableData(tab.table);
213
+ }
214
+ }, [tabs, fetchTableData]);
215
+
216
+ // Initial load
217
+ useEffect(() => {
218
+ if (status === 'unauthenticated') {
219
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(window.location.pathname)}`);
220
+ } else if (status === 'authenticated' && !hasAccess) {
221
+ router.push('/?error=unauthorized');
222
+ } else if (status === 'authenticated' && hasAccess) {
223
+ fetchStats();
224
+ }
225
+ }, [status, hasAccess, router, fetchStats]);
226
+
227
+ // Loading state
228
+ if (status === 'loading') {
229
+ return (
230
+ <div className={`min-h-screen flex items-center justify-center ${themeClasses.bg}`}>
231
+ <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-amber-500" />
232
+ </div>
233
+ );
234
+ }
235
+
236
+ // Access denied
237
+ if (status === 'authenticated' && !hasAccess) {
238
+ return (
239
+ <div className={`min-h-screen flex items-center justify-center ${themeClasses.bg}`}>
240
+ <div className="text-center">
241
+ <div className={isDark ? 'text-red-400' : 'text-red-500'}><IconShield /></div>
242
+ <h1 className={`text-2xl font-bold mb-2 ${themeClasses.text}`}>Access Denied</h1>
243
+ <p className={`mb-6 ${themeClasses.textMuted}`}>You need admin access for this area.</p>
244
+ <Link href="/" className="inline-flex items-center gap-2 px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700">
245
+ <IconArrowLeft /> Return to Home
246
+ </Link>
247
+ </div>
248
+ </div>
249
+ );
250
+ }
251
+
252
+ if (status === 'unauthenticated') return null;
253
+
254
+ const currentTab = tabs.find(t => t.id === activeTab);
255
+
256
+ return (
257
+ <div className={`min-h-screen ${themeClasses.bg}`}>
258
+ {/* Header */}
259
+ <header className={`sticky top-0 z-40 border-b ${themeClasses.headerBg}`}>
260
+ <div className="container mx-auto px-4 py-4">
261
+ <div className="flex items-center justify-between">
262
+ <div className="flex items-center gap-3">
263
+ <div className={`p-2 rounded-lg ${isDark ? 'bg-amber-900/30' : 'bg-amber-100'}`}>
264
+ <IconChart className={`w-5 h-5 ${isDark ? 'text-amber-400' : 'text-amber-600'}`} />
265
+ </div>
266
+ <div>
267
+ <h1 className={`text-xl font-bold ${themeClasses.text}`}>{title}</h1>
268
+ <p className={`text-sm ${themeClasses.textMuted}`}>{subtitle}</p>
269
+ </div>
270
+ </div>
271
+ <div className="flex items-center gap-4">
272
+ <button
273
+ onClick={() => { fetchStats(); if (currentTab?.table) fetchTableData(currentTab.table); }}
274
+ disabled={loading || statsLoading}
275
+ className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors ${themeClasses.textMuted} ${isDark ? 'hover:bg-slate-800' : 'hover:bg-gray-100'} ${(loading || statsLoading) ? 'opacity-50' : ''}`}
276
+ >
277
+ <span className={(loading || statsLoading) ? 'animate-spin' : ''}><IconRefresh /></span>
278
+ Refresh
279
+ </button>
280
+ <Link href={backUrl} className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors ${themeClasses.textMuted} ${isDark ? 'hover:bg-slate-800' : 'hover:bg-gray-100'}`}>
281
+ <IconArrowLeft /> {backLabel}
282
+ </Link>
283
+ </div>
284
+ </div>
285
+ </div>
286
+ </header>
287
+
288
+ {/* Content */}
289
+ <div className="container mx-auto px-4 py-6 space-y-6">
290
+ {/* Tab Navigation */}
291
+ <div className={`flex flex-wrap gap-1 p-1 rounded-xl ${themeClasses.tabBg}`}>
292
+ {tabs.map((tab) => (
293
+ <button
294
+ key={tab.id}
295
+ onClick={() => handleTabChange(tab.id)}
296
+ className={`py-2 px-4 rounded-lg text-sm font-medium transition-all ${
297
+ activeTab === tab.id ? themeClasses.tabActive : themeClasses.tabInactive
298
+ }`}
299
+ >
300
+ <span className="mr-2">{tab.icon}</span>
301
+ {tab.label}
302
+ </button>
303
+ ))}
304
+ </div>
305
+
306
+ {/* Tab Content */}
307
+ {renderTabContent ? (
308
+ renderTabContent(currentTab!, tableData, loading)
309
+ ) : activeTab === 'overview' || !currentTab?.table ? (
310
+ // Default Overview
311
+ <div className="space-y-6">
312
+ <div>
313
+ <h2 className={`text-lg font-semibold mb-4 ${themeClasses.text}`}>Data Overview</h2>
314
+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
315
+ {stats.map((stat) => (
316
+ <Link
317
+ key={stat.table}
318
+ href={`/admin/data?collection=${collectionName}&table=${stat.table}`}
319
+ className={`p-4 rounded-xl border transition-all hover:scale-[1.02] ${themeClasses.cardBg}`}
320
+ >
321
+ <p className={`text-xs font-medium ${themeClasses.textMuted}`}>{stat.label}</p>
322
+ <p className={`text-2xl font-bold ${themeClasses.text}`}>
323
+ {statsLoading ? '...' : stat.count.toLocaleString()}
324
+ </p>
325
+ </Link>
326
+ ))}
327
+ </div>
328
+ </div>
329
+ {renderOverview && renderOverview(stats)}
330
+ </div>
331
+ ) : (
332
+ // Default Table View
333
+ <div>
334
+ <h2 className={`text-lg font-semibold mb-4 ${themeClasses.text}`}>
335
+ {currentTab.label} ({tableData.length})
336
+ </h2>
337
+ {loading ? (
338
+ <div className="flex items-center justify-center py-12">
339
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-500" />
340
+ </div>
341
+ ) : (
342
+ <div className={`rounded-lg border overflow-hidden ${themeClasses.cardBg}`}>
343
+ <div className="overflow-x-auto">
344
+ <table className="w-full text-sm">
345
+ <thead className={isDark ? 'bg-slate-800' : 'bg-gray-50'}>
346
+ <tr>
347
+ <th className={`px-4 py-3 text-left font-medium ${themeClasses.textMuted}`}>ID</th>
348
+ <th className={`px-4 py-3 text-left font-medium ${themeClasses.textMuted}`}>User</th>
349
+ <th className={`px-4 py-3 text-left font-medium ${themeClasses.textMuted}`}>Data</th>
350
+ <th className={`px-4 py-3 text-left font-medium ${themeClasses.textMuted}`}>Created</th>
351
+ </tr>
352
+ </thead>
353
+ <tbody className={`divide-y ${isDark ? 'divide-slate-700' : 'divide-gray-200'}`}>
354
+ {tableData.length === 0 ? (
355
+ <tr>
356
+ <td colSpan={4} className={`px-4 py-8 text-center ${themeClasses.textMuted}`}>No data found</td>
357
+ </tr>
358
+ ) : tableData.map((row: any) => (
359
+ <tr key={row.document_id} className={isDark ? 'hover:bg-slate-800/50' : 'hover:bg-gray-50'}>
360
+ <td className={`px-4 py-3 ${themeClasses.text}`}>{row.document_id}</td>
361
+ <td className={`px-4 py-3 ${themeClasses.text}`}>{row.user_id}</td>
362
+ <td className={`px-4 py-3 ${themeClasses.textMuted} max-w-xs truncate`}>
363
+ {JSON.stringify(row.data).substring(0, 50)}...
364
+ </td>
365
+ <td className={`px-4 py-3 ${themeClasses.textMuted}`}>
366
+ {new Date(row.created_at).toLocaleDateString()}
367
+ </td>
368
+ </tr>
369
+ ))}
370
+ </tbody>
371
+ </table>
372
+ </div>
373
+ </div>
374
+ )}
375
+ </div>
376
+ )}
377
+ </div>
378
+ </div>
379
+ );
380
+ }
381
+
382
+ export default ClientSiteAdminPage;