@payez/next-mvp 4.1.9 → 4.1.10
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.
- package/README.md +792 -792
- package/dist/api-handlers/auth/refresh.js +38 -15
- package/dist/auth/better-auth.js +7 -18
- package/dist/components/account/MobileNavDrawer.js +18 -18
- package/dist/components/account/UserAvatarMenu.js +1 -1
- package/dist/components/admin/AlertSettingsTab.js +40 -40
- package/dist/components/admin/LoggingSettingsTab.js +28 -28
- package/dist/lib/ensure-fresh-access-token.js +30 -7
- package/dist/lib/idp-fetch.js +25 -9
- package/dist/lib/session-store.d.ts +1 -0
- package/dist/lib/session-store.js +12 -8
- package/dist/pages/login/page.js +28 -28
- package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
- package/package.json +893 -893
- package/scripts/dev-broker.ps1 +35 -35
- package/scripts/dev-local.ps1 +45 -45
- package/src/api/auth-handler.ts +548 -548
- package/src/api-handlers/account/change-password.ts +142 -142
- package/src/api-handlers/account/update-phone.ts +79 -79
- package/src/api-handlers/account/verify-email.ts +125 -125
- package/src/api-handlers/account/verify-sms.ts +125 -125
- package/src/api-handlers/admin/analytics.ts +443 -443
- package/src/api-handlers/admin/audit.ts +223 -223
- package/src/api-handlers/admin/index.ts +63 -63
- package/src/api-handlers/admin/redis-sessions.ts +251 -251
- package/src/api-handlers/admin/sessions.ts +318 -318
- package/src/api-handlers/admin/site-logs.ts +365 -365
- package/src/api-handlers/admin/users.ts +242 -242
- package/src/api-handlers/admin/vibe-data.ts +324 -324
- package/src/api-handlers/auth/refresh.ts +705 -682
- package/src/api-handlers/auth/signout.ts +199 -199
- package/src/api-handlers/auth/status.ts +20 -20
- package/src/api-handlers/auth/update-session.ts +110 -110
- package/src/api-handlers/auth/verify-code.ts +112 -112
- package/src/api-handlers/session/refresh-viability.ts +36 -36
- package/src/api-handlers/test/force-expire.ts +60 -60
- package/src/auth/auth-decision.ts +229 -229
- package/src/auth/better-auth.ts +7 -18
- package/src/auth/route-config.ts +219 -219
- package/src/auth/types/auth-types.ts +555 -555
- package/src/auth/types/index.ts +7 -7
- package/src/auth/utils/idp-client.ts +445 -445
- package/src/auth/utils/index.ts +6 -6
- package/src/auth/utils/token-utils.ts +243 -243
- package/src/client/AuthContext.tsx +143 -143
- package/src/client/fetch-with-auth.ts +47 -47
- package/src/components/SessionSync.tsx +138 -138
- package/src/components/SignalRHealthCheck.tsx +131 -131
- package/src/components/account/MobileNavDrawer.tsx +305 -305
- package/src/components/account/UserAvatarMenu.tsx +266 -266
- package/src/components/account/index.ts +13 -13
- package/src/components/admin/AlertSettingsTab.tsx +728 -728
- package/src/components/admin/AnalyticsTab.tsx +703 -703
- package/src/components/admin/DataBrowserTab.tsx +505 -505
- package/src/components/admin/LoggingSettingsTab.tsx +665 -665
- package/src/components/admin/SessionsTab.tsx +414 -414
- package/src/components/admin/StatsTab.tsx +379 -379
- package/src/components/admin/VibeAdminLayout.tsx +187 -187
- package/src/components/admin/index.ts +59 -59
- package/src/components/auth/FederatedAuthSection.tsx +95 -95
- package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
- package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
- package/src/components/auth/TraditionalAuthSection.tsx +99 -99
- package/src/components/recovery/CompleteStep.tsx +36 -36
- package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
- package/src/components/recovery/SelectMethodStep.tsx +73 -73
- package/src/components/recovery/SetPasswordStep.tsx +97 -97
- package/src/components/recovery/VerifyCodeStep.tsx +90 -90
- package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
- package/src/components/reserved/ReservedStatusBox.tsx +118 -118
- package/src/components/ui/BetaBadge.tsx +58 -58
- package/src/components/ui/Footer.tsx +93 -93
- package/src/config/env.ts +57 -57
- package/src/config/logger.ts +62 -62
- package/src/config/vibe-log-transport.ts +264 -264
- package/src/hooks/useAuth.ts +117 -117
- package/src/hooks/useAuthSettings.ts +97 -97
- package/src/hooks/useAvailableProviders.ts +120 -120
- package/src/hooks/usePasswordValidation.ts +127 -127
- package/src/hooks/usePublicAuthSettings.ts +149 -149
- package/src/hooks/useSessionExpiration.ts +101 -101
- package/src/hooks/useViabilitySession.ts +336 -336
- package/src/index.ts +60 -60
- package/src/lib/api-handler.ts +643 -643
- package/src/lib/app-slug.ts +178 -178
- package/src/lib/ensure-fresh-access-token.ts +358 -335
- package/src/lib/geolocation.ts +265 -265
- package/src/lib/idp-fetch.ts +26 -10
- package/src/lib/jwt-decode.ts +82 -82
- package/src/lib/roles.ts +177 -177
- package/src/lib/session-store.ts +4 -1
- package/src/lib/site-logger.ts +245 -245
- package/src/lib/standardized-client-api.ts +901 -901
- package/src/lib/test-aware-get-token.ts +41 -41
- package/src/lib/user-agent-parser.ts +252 -252
- package/src/logging/api/admin-analytics.ts +51 -51
- package/src/logging/api/audit-log.ts +53 -53
- package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
- package/src/logging/components/AuditLogViewer.tsx +125 -125
- package/src/logging/components/ErrorMetricsCard.tsx +98 -98
- package/src/logging/components/HealthMetricsCard.tsx +70 -70
- package/src/logging/hooks/useAdminAnalytics.ts +22 -22
- package/src/logging/hooks/useAuditLog.ts +24 -24
- package/src/logging/hooks/useErrorMetrics.ts +40 -40
- package/src/logging/hooks/useHealthMetrics.ts +44 -44
- package/src/logging/index.ts +18 -18
- package/src/logging/types/analytics.ts +81 -81
- package/src/logging/types/audit.ts +31 -31
- package/src/logging/types/index.ts +3 -3
- package/src/middleware/create-middleware.ts +663 -663
- package/src/middleware/rbac-check.ts +279 -279
- package/src/middleware/twofa-presets.ts +224 -224
- package/src/pages/admin-login/page.tsx +221 -221
- package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
- package/src/pages/admin-page-permissions/index.ts +7 -7
- package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
- package/src/pages/admin-roles/modals.tsx +469 -469
- package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
- package/src/pages/client-admin/index.ts +33 -33
- package/src/pages/coming-soon/page.tsx +83 -83
- package/src/pages/login/page.tsx +456 -456
- package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
- package/src/pages/profile/index.ts +9 -9
- package/src/pages/profile/page.tsx +166 -166
- package/src/pages/recovery/page.tsx +234 -234
- package/src/pages/roles/MyRolesPage.tsx +211 -211
- package/src/pages/roles/components.tsx +294 -294
- package/src/pages/roles/index.ts +17 -17
- package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
- package/src/pages/security/index.ts +9 -9
- package/src/pages/security/page.tsx +507 -507
- package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
- package/src/pages/settings/index.ts +9 -9
- package/src/pages/settings/page.tsx +47 -47
- package/src/pages/showcase/ShowcasePage.tsx +532 -532
- package/src/pages/showcase/index.ts +13 -13
- package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
- package/src/pages/test-env/JwtInspectPage.tsx +456 -456
- package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
- package/src/pages/test-env/TestEnvPage.tsx +118 -118
- package/src/pages/test-env/index.ts +25 -25
- package/src/pages/verify-code/page.tsx +652 -652
- package/src/routes/account/update-phone.ts +13 -13
- package/src/routes/auth/logout.ts +108 -108
- package/src/routes/auth/nextauth.ts +45 -45
- package/src/routes/auth/settings.ts +75 -75
- package/src/routes/auth/viability.ts +224 -224
- package/src/server/auth-guard.ts +170 -170
- package/src/server/slim-middleware.ts +117 -117
- package/src/server/with-auth.ts +93 -93
- package/src/stores/authStore.ts +1899 -1899
- package/src/templates/instrumentation.ts +41 -41
- package/src/utils/logout.ts +30 -30
- package/src/vibe/client.ts +590 -590
- package/src/vibe/enterprise-auth.ts +208 -208
- package/src/vibe/errors.ts +185 -185
- package/src/vibe/generic.ts +431 -431
- package/src/vibe/hooks/index.ts +367 -367
- package/src/vibe/index.ts +132 -132
- package/src/vibe/sessions.ts +551 -551
- package/src/vibe/types.ts +577 -577
|
@@ -1,443 +1,443 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Admin Analytics API Handler
|
|
3
|
-
*
|
|
4
|
-
* Provides admin-level analytics data using service account credentials.
|
|
5
|
-
* Supports: geo stats, login stats, revenue stats, feature usage.
|
|
6
|
-
*
|
|
7
|
-
* @version 1.0
|
|
8
|
-
* @requires Admin role (vibe_app_admin or payez_admin)
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { NextRequest, NextResponse } from 'next/server';
|
|
12
|
-
import { getSession } from '../../server/auth';
|
|
13
|
-
import { getStartupIDPConfig } from '../../lib/startup-init';
|
|
14
|
-
import { ADMIN_ROLES, hasAnyRole } from '../../lib/roles';
|
|
15
|
-
|
|
16
|
-
interface VibeRequestOptions {
|
|
17
|
-
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
18
|
-
body?: unknown;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
async function checkAdminRole(request: NextRequest): Promise<{ isAdmin: boolean; error?: NextResponse }> {
|
|
22
|
-
const session = await getSession(request) as any;
|
|
23
|
-
|
|
24
|
-
if (!session?.user) {
|
|
25
|
-
return {
|
|
26
|
-
isAdmin: false,
|
|
27
|
-
error: NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const userRoles = (session.user?.roles as string[]) || [];
|
|
32
|
-
const hasAdminRole = ADMIN_ROLES.some(role => userRoles.includes(role));
|
|
33
|
-
|
|
34
|
-
if (!hasAdminRole) {
|
|
35
|
-
return {
|
|
36
|
-
isAdmin: false,
|
|
37
|
-
error: NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
return { isAdmin: true };
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async function vibeServiceRequest<T = unknown>(
|
|
45
|
-
endpoint: string,
|
|
46
|
-
options: VibeRequestOptions
|
|
47
|
-
): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> {
|
|
48
|
-
const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
|
|
49
|
-
const clientId = process.env.VIBE_CLIENT_ID;
|
|
50
|
-
const signingKey = process.env.VIBE_HMAC_KEY;
|
|
51
|
-
|
|
52
|
-
if (!idpUrl || !clientId || !signingKey) {
|
|
53
|
-
return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
const timestamp = Math.floor(Date.now() / 1000);
|
|
57
|
-
const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
|
|
58
|
-
|
|
59
|
-
const crypto = await import('crypto');
|
|
60
|
-
const signature = crypto
|
|
61
|
-
.createHmac('sha256', Buffer.from(signingKey, 'base64'))
|
|
62
|
-
.update(stringToSign)
|
|
63
|
-
.digest('base64');
|
|
64
|
-
|
|
65
|
-
const proxyUrl = `${idpUrl}/api/vibe/proxy`;
|
|
66
|
-
|
|
67
|
-
// Get the client slug from startup config for multi-client admin support
|
|
68
|
-
const idpConfig = getStartupIDPConfig();
|
|
69
|
-
const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
|
|
70
|
-
|
|
71
|
-
try {
|
|
72
|
-
const res = await fetch(proxyUrl, {
|
|
73
|
-
method: 'POST',
|
|
74
|
-
headers: {
|
|
75
|
-
'Content-Type': 'application/json',
|
|
76
|
-
'X-Vibe-Client-Id': clientId,
|
|
77
|
-
'X-Vibe-Timestamp': String(timestamp),
|
|
78
|
-
'X-Vibe-Signature': signature,
|
|
79
|
-
...(idpClientId && { 'X-Client-Id': idpClientId }),
|
|
80
|
-
},
|
|
81
|
-
body: JSON.stringify({
|
|
82
|
-
endpoint,
|
|
83
|
-
method: options.method,
|
|
84
|
-
data: options.body ?? null,
|
|
85
|
-
}),
|
|
86
|
-
cache: 'no-store',
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
if (res.status === 204) return { ok: true, status: 204, data: null };
|
|
90
|
-
if (!res.ok) {
|
|
91
|
-
const errorText = await res.text();
|
|
92
|
-
return { ok: false, status: res.status, data: null, error: errorText };
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const body = await res.json();
|
|
96
|
-
return { ok: true, status: res.status, data: body };
|
|
97
|
-
} catch (error) {
|
|
98
|
-
return { ok: false, status: 0, data: null, error: String(error) };
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function getCountryFlag(countryCode: string): string {
|
|
103
|
-
if (!countryCode || countryCode.length !== 2) return '';
|
|
104
|
-
const codePoints = countryCode
|
|
105
|
-
.toUpperCase()
|
|
106
|
-
.split('')
|
|
107
|
-
.map(char => 127397 + char.charCodeAt(0));
|
|
108
|
-
return String.fromCodePoint(...codePoints);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export interface AdminAnalyticsHandlerConfig {
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* POST /api/admin/analytics
|
|
116
|
-
* Body: { type: 'geo' | 'logins' | 'revenue' | 'features', period?: string }
|
|
117
|
-
*/
|
|
118
|
-
export function createAnalyticsHandler(config: AdminAnalyticsHandlerConfig) {
|
|
119
|
-
return {
|
|
120
|
-
async POST(request: NextRequest) {
|
|
121
|
-
const adminCheck = await checkAdminRole(request);
|
|
122
|
-
if (adminCheck.error) return adminCheck.error;
|
|
123
|
-
|
|
124
|
-
const body = await request.json();
|
|
125
|
-
const { type, period = '7d' } = body;
|
|
126
|
-
|
|
127
|
-
const now = new Date();
|
|
128
|
-
let startDate: Date;
|
|
129
|
-
switch (period) {
|
|
130
|
-
case '24h':
|
|
131
|
-
startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
|
132
|
-
break;
|
|
133
|
-
case '7d':
|
|
134
|
-
startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
|
135
|
-
break;
|
|
136
|
-
case '30d':
|
|
137
|
-
startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
|
138
|
-
break;
|
|
139
|
-
case '90d':
|
|
140
|
-
startDate = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
|
|
141
|
-
break;
|
|
142
|
-
default:
|
|
143
|
-
startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
if (type === 'geo') {
|
|
147
|
-
return await getGeoAnalytics(startDate);
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
if (type === 'logins') {
|
|
151
|
-
return await getLoginAnalytics(startDate);
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
if (type === 'revenue') {
|
|
155
|
-
return await getRevenueAnalytics(startDate);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
if (type === 'features') {
|
|
159
|
-
return await getFeatureUsageAnalytics(startDate);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
if (type === 'summary') {
|
|
163
|
-
return await getSummaryAnalytics(startDate);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
return NextResponse.json({ error: 'Invalid analytics type' }, { status: 400 });
|
|
167
|
-
},
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
async function getGeoAnalytics(startDate: Date) {
|
|
172
|
-
const result = await vibeServiceRequest<any>(
|
|
173
|
-
'/v1/collections/vibe_app/tables/login_sessions/query',
|
|
174
|
-
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
175
|
-
);
|
|
176
|
-
|
|
177
|
-
if (!result.ok) {
|
|
178
|
-
return NextResponse.json({ error: result.error }, { status: result.status || 500 });
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
const sessions = result.data?.data || result.data?.documents || [];
|
|
182
|
-
const recentSessions = sessions.filter((s: any) => new Date(s.created_at) >= startDate);
|
|
183
|
-
|
|
184
|
-
const byCountry: Record<string, { count: number; flag: string; cities: Set<string> }> = {};
|
|
185
|
-
const byCity: Record<string, number> = {};
|
|
186
|
-
|
|
187
|
-
recentSessions.forEach((s: any) => {
|
|
188
|
-
const country = s.country_code || s.country || 'Unknown';
|
|
189
|
-
const city = s.city || 'Unknown';
|
|
190
|
-
|
|
191
|
-
if (!byCountry[country]) {
|
|
192
|
-
byCountry[country] = { count: 0, flag: getCountryFlag(country), cities: new Set() };
|
|
193
|
-
}
|
|
194
|
-
byCountry[country].count++;
|
|
195
|
-
byCountry[country].cities.add(city);
|
|
196
|
-
|
|
197
|
-
const cityKey = `${city}, ${country}`;
|
|
198
|
-
byCity[cityKey] = (byCity[cityKey] || 0) + 1;
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
const countries = Object.entries(byCountry)
|
|
202
|
-
.map(([code, data]) => ({
|
|
203
|
-
code,
|
|
204
|
-
flag: data.flag,
|
|
205
|
-
count: data.count,
|
|
206
|
-
cities: data.cities.size,
|
|
207
|
-
}))
|
|
208
|
-
.sort((a, b) => b.count - a.count);
|
|
209
|
-
|
|
210
|
-
const cities = Object.entries(byCity)
|
|
211
|
-
.map(([name, count]) => ({ name, count }))
|
|
212
|
-
.sort((a, b) => b.count - a.count)
|
|
213
|
-
.slice(0, 20);
|
|
214
|
-
|
|
215
|
-
return NextResponse.json({
|
|
216
|
-
geo: {
|
|
217
|
-
totalSessions: recentSessions.length,
|
|
218
|
-
uniqueCountries: countries.length,
|
|
219
|
-
countries,
|
|
220
|
-
topCities: cities,
|
|
221
|
-
},
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
async function getLoginAnalytics(startDate: Date) {
|
|
226
|
-
const result = await vibeServiceRequest<any>(
|
|
227
|
-
'/v1/collections/vibe_app/tables/login_sessions/query',
|
|
228
|
-
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
229
|
-
);
|
|
230
|
-
|
|
231
|
-
if (!result.ok) {
|
|
232
|
-
return NextResponse.json({ error: result.error }, { status: result.status || 500 });
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
const sessions = result.data?.data || result.data?.documents || [];
|
|
236
|
-
const recentSessions = sessions.filter((s: any) => new Date(s.created_at) >= startDate);
|
|
237
|
-
|
|
238
|
-
// Group by day
|
|
239
|
-
const byDay: Record<string, number> = {};
|
|
240
|
-
const byHour: Record<number, number> = {};
|
|
241
|
-
const byDevice: Record<string, number> = {};
|
|
242
|
-
const byBrowser: Record<string, number> = {};
|
|
243
|
-
|
|
244
|
-
recentSessions.forEach((s: any) => {
|
|
245
|
-
const date = new Date(s.created_at);
|
|
246
|
-
const dayKey = date.toISOString().split('T')[0];
|
|
247
|
-
byDay[dayKey] = (byDay[dayKey] || 0) + 1;
|
|
248
|
-
|
|
249
|
-
const hour = date.getHours();
|
|
250
|
-
byHour[hour] = (byHour[hour] || 0) + 1;
|
|
251
|
-
|
|
252
|
-
const device = s.device_type || s.device || 'Unknown';
|
|
253
|
-
byDevice[device] = (byDevice[device] || 0) + 1;
|
|
254
|
-
|
|
255
|
-
const browser = s.browser || 'Unknown';
|
|
256
|
-
byBrowser[browser] = (byBrowser[browser] || 0) + 1;
|
|
257
|
-
});
|
|
258
|
-
|
|
259
|
-
const dailyLogins = Object.entries(byDay)
|
|
260
|
-
.map(([date, count]) => ({ date, count }))
|
|
261
|
-
.sort((a, b) => a.date.localeCompare(b.date));
|
|
262
|
-
|
|
263
|
-
const hourlyDistribution = Object.entries(byHour)
|
|
264
|
-
.map(([hour, count]) => ({ hour: parseInt(hour), count }))
|
|
265
|
-
.sort((a, b) => a.hour - b.hour);
|
|
266
|
-
|
|
267
|
-
return NextResponse.json({
|
|
268
|
-
logins: {
|
|
269
|
-
total: recentSessions.length,
|
|
270
|
-
uniqueUsers: new Set(recentSessions.map((s: any) => s.idp_user_id || s.user_id)).size,
|
|
271
|
-
dailyLogins,
|
|
272
|
-
hourlyDistribution,
|
|
273
|
-
byDevice: Object.entries(byDevice).map(([device, count]) => ({ device, count })),
|
|
274
|
-
byBrowser: Object.entries(byBrowser).map(([browser, count]) => ({ browser, count })),
|
|
275
|
-
},
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
async function getRevenueAnalytics(startDate: Date) {
|
|
280
|
-
// Try to get transactions table
|
|
281
|
-
const result = await vibeServiceRequest<any>(
|
|
282
|
-
'/v1/collections/vibe_app/tables/transactions/query',
|
|
283
|
-
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
284
|
-
);
|
|
285
|
-
|
|
286
|
-
if (!result.ok) {
|
|
287
|
-
// Table might not exist, return empty stats
|
|
288
|
-
return NextResponse.json({
|
|
289
|
-
revenue: {
|
|
290
|
-
total: 0,
|
|
291
|
-
count: 0,
|
|
292
|
-
byDay: [],
|
|
293
|
-
byTier: {},
|
|
294
|
-
message: 'No transactions table or data available',
|
|
295
|
-
},
|
|
296
|
-
});
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
const transactions = result.data?.data || result.data?.documents || [];
|
|
300
|
-
const recentTxns = transactions.filter((t: any) => new Date(t.created_at) >= startDate);
|
|
301
|
-
|
|
302
|
-
const byDay: Record<string, { count: number; amount: number }> = {};
|
|
303
|
-
const byTier: Record<string, { count: number; amount: number }> = {};
|
|
304
|
-
let totalAmount = 0;
|
|
305
|
-
|
|
306
|
-
recentTxns.forEach((t: any) => {
|
|
307
|
-
const date = new Date(t.created_at).toISOString().split('T')[0];
|
|
308
|
-
const amount = parseFloat(t.amount) || 0;
|
|
309
|
-
const tier = t.tier || t.product || 'unknown';
|
|
310
|
-
|
|
311
|
-
if (!byDay[date]) byDay[date] = { count: 0, amount: 0 };
|
|
312
|
-
byDay[date].count++;
|
|
313
|
-
byDay[date].amount += amount;
|
|
314
|
-
|
|
315
|
-
if (!byTier[tier]) byTier[tier] = { count: 0, amount: 0 };
|
|
316
|
-
byTier[tier].count++;
|
|
317
|
-
byTier[tier].amount += amount;
|
|
318
|
-
|
|
319
|
-
totalAmount += amount;
|
|
320
|
-
});
|
|
321
|
-
|
|
322
|
-
const dailyRevenue = Object.entries(byDay)
|
|
323
|
-
.map(([date, data]) => ({ date, ...data }))
|
|
324
|
-
.sort((a, b) => a.date.localeCompare(b.date));
|
|
325
|
-
|
|
326
|
-
return NextResponse.json({
|
|
327
|
-
revenue: {
|
|
328
|
-
total: totalAmount,
|
|
329
|
-
count: recentTxns.length,
|
|
330
|
-
byDay: dailyRevenue,
|
|
331
|
-
byTier,
|
|
332
|
-
},
|
|
333
|
-
});
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
async function getFeatureUsageAnalytics(startDate: Date) {
|
|
337
|
-
// Try to get feature_usage or analytics table
|
|
338
|
-
const result = await vibeServiceRequest<any>(
|
|
339
|
-
'/v1/collections/vibe_app/tables/feature_usage/query',
|
|
340
|
-
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
341
|
-
);
|
|
342
|
-
|
|
343
|
-
if (!result.ok) {
|
|
344
|
-
// Try analytics table as fallback
|
|
345
|
-
const analyticsResult = await vibeServiceRequest<any>(
|
|
346
|
-
'/v1/collections/vibe_app/tables/analytics/query',
|
|
347
|
-
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
348
|
-
);
|
|
349
|
-
|
|
350
|
-
if (!analyticsResult.ok) {
|
|
351
|
-
return NextResponse.json({
|
|
352
|
-
features: {
|
|
353
|
-
total: 0,
|
|
354
|
-
byFeature: {},
|
|
355
|
-
message: 'No feature usage data available',
|
|
356
|
-
},
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
const events = analyticsResult.data?.data || analyticsResult.data?.documents || [];
|
|
361
|
-
return processFeatureUsage(events, startDate);
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
const events = result.data?.data || result.data?.documents || [];
|
|
365
|
-
return processFeatureUsage(events, startDate);
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
function processFeatureUsage(events: any[], startDate: Date) {
|
|
369
|
-
const recentEvents = events.filter((e: any) => new Date(e.created_at) >= startDate);
|
|
370
|
-
|
|
371
|
-
const byFeature: Record<string, { count: number; uniqueUsers: Set<string> }> = {};
|
|
372
|
-
const byDay: Record<string, number> = {};
|
|
373
|
-
|
|
374
|
-
recentEvents.forEach((e: any) => {
|
|
375
|
-
const feature = e.feature || e.action || e.event_type || 'unknown';
|
|
376
|
-
const userId = e.user_id || e.idp_user_id || 'anonymous';
|
|
377
|
-
const date = new Date(e.created_at).toISOString().split('T')[0];
|
|
378
|
-
|
|
379
|
-
if (!byFeature[feature]) {
|
|
380
|
-
byFeature[feature] = { count: 0, uniqueUsers: new Set() };
|
|
381
|
-
}
|
|
382
|
-
byFeature[feature].count++;
|
|
383
|
-
byFeature[feature].uniqueUsers.add(userId);
|
|
384
|
-
|
|
385
|
-
byDay[date] = (byDay[date] || 0) + 1;
|
|
386
|
-
});
|
|
387
|
-
|
|
388
|
-
const features = Object.entries(byFeature)
|
|
389
|
-
.map(([name, data]) => ({
|
|
390
|
-
name,
|
|
391
|
-
count: data.count,
|
|
392
|
-
uniqueUsers: data.uniqueUsers.size,
|
|
393
|
-
}))
|
|
394
|
-
.sort((a, b) => b.count - a.count);
|
|
395
|
-
|
|
396
|
-
const dailyUsage = Object.entries(byDay)
|
|
397
|
-
.map(([date, count]) => ({ date, count }))
|
|
398
|
-
.sort((a, b) => a.date.localeCompare(b.date));
|
|
399
|
-
|
|
400
|
-
return NextResponse.json({
|
|
401
|
-
features: {
|
|
402
|
-
total: recentEvents.length,
|
|
403
|
-
byFeature: features,
|
|
404
|
-
dailyUsage,
|
|
405
|
-
},
|
|
406
|
-
});
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
async function getSummaryAnalytics(startDate: Date) {
|
|
410
|
-
// Get users
|
|
411
|
-
const usersResult = await vibeServiceRequest<any>(
|
|
412
|
-
'/v1/collections/vibe_app/tables/users/query',
|
|
413
|
-
{ method: 'POST', body: { page: 1, pageSize: 10000 } }
|
|
414
|
-
);
|
|
415
|
-
|
|
416
|
-
// Get sessions
|
|
417
|
-
const sessionsResult = await vibeServiceRequest<any>(
|
|
418
|
-
'/v1/collections/vibe_app/tables/login_sessions/query',
|
|
419
|
-
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
420
|
-
);
|
|
421
|
-
|
|
422
|
-
const users = usersResult.ok ? (usersResult.data?.data || usersResult.data?.documents || []) : [];
|
|
423
|
-
const sessions = sessionsResult.ok ? (sessionsResult.data?.data || sessionsResult.data?.documents || []) : [];
|
|
424
|
-
|
|
425
|
-
const recentUsers = users.filter((u: any) => new Date(u.created_at) >= startDate);
|
|
426
|
-
const recentSessions = sessions.filter((s: any) => new Date(s.created_at) >= startDate);
|
|
427
|
-
|
|
428
|
-
const tierCounts: Record<string, number> = {};
|
|
429
|
-
users.forEach((u: any) => {
|
|
430
|
-
const tier = u.tier || 'free';
|
|
431
|
-
tierCounts[tier] = (tierCounts[tier] || 0) + 1;
|
|
432
|
-
});
|
|
433
|
-
|
|
434
|
-
return NextResponse.json({
|
|
435
|
-
summary: {
|
|
436
|
-
totalUsers: users.length,
|
|
437
|
-
newUsers: recentUsers.length,
|
|
438
|
-
activeSessions: sessions.filter((s: any) => s.status === 'active').length,
|
|
439
|
-
recentLogins: recentSessions.length,
|
|
440
|
-
usersByTier: tierCounts,
|
|
441
|
-
},
|
|
442
|
-
});
|
|
443
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Admin Analytics API Handler
|
|
3
|
+
*
|
|
4
|
+
* Provides admin-level analytics data using service account credentials.
|
|
5
|
+
* Supports: geo stats, login stats, revenue stats, feature usage.
|
|
6
|
+
*
|
|
7
|
+
* @version 1.0
|
|
8
|
+
* @requires Admin role (vibe_app_admin or payez_admin)
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
12
|
+
import { getSession } from '../../server/auth';
|
|
13
|
+
import { getStartupIDPConfig } from '../../lib/startup-init';
|
|
14
|
+
import { ADMIN_ROLES, hasAnyRole } from '../../lib/roles';
|
|
15
|
+
|
|
16
|
+
interface VibeRequestOptions {
|
|
17
|
+
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
18
|
+
body?: unknown;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function checkAdminRole(request: NextRequest): Promise<{ isAdmin: boolean; error?: NextResponse }> {
|
|
22
|
+
const session = await getSession(request) as any;
|
|
23
|
+
|
|
24
|
+
if (!session?.user) {
|
|
25
|
+
return {
|
|
26
|
+
isAdmin: false,
|
|
27
|
+
error: NextResponse.json({ success: false, error: 'Please sign in' }, { status: 401 }),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const userRoles = (session.user?.roles as string[]) || [];
|
|
32
|
+
const hasAdminRole = ADMIN_ROLES.some(role => userRoles.includes(role));
|
|
33
|
+
|
|
34
|
+
if (!hasAdminRole) {
|
|
35
|
+
return {
|
|
36
|
+
isAdmin: false,
|
|
37
|
+
error: NextResponse.json({ success: false, error: 'Admin access required' }, { status: 403 }),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return { isAdmin: true };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function vibeServiceRequest<T = unknown>(
|
|
45
|
+
endpoint: string,
|
|
46
|
+
options: VibeRequestOptions
|
|
47
|
+
): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> {
|
|
48
|
+
const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
|
|
49
|
+
const clientId = process.env.VIBE_CLIENT_ID;
|
|
50
|
+
const signingKey = process.env.VIBE_HMAC_KEY;
|
|
51
|
+
|
|
52
|
+
if (!idpUrl || !clientId || !signingKey) {
|
|
53
|
+
return { ok: false, status: 500, data: null, error: 'Vibe not configured' };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
57
|
+
const stringToSign = `${timestamp}|${options.method}|${endpoint}`;
|
|
58
|
+
|
|
59
|
+
const crypto = await import('crypto');
|
|
60
|
+
const signature = crypto
|
|
61
|
+
.createHmac('sha256', Buffer.from(signingKey, 'base64'))
|
|
62
|
+
.update(stringToSign)
|
|
63
|
+
.digest('base64');
|
|
64
|
+
|
|
65
|
+
const proxyUrl = `${idpUrl}/api/vibe/proxy`;
|
|
66
|
+
|
|
67
|
+
// Get the client slug from startup config for multi-client admin support
|
|
68
|
+
const idpConfig = getStartupIDPConfig();
|
|
69
|
+
const idpClientId = idpConfig?.clientSlug || idpConfig?.clientId;
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const res = await fetch(proxyUrl, {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers: {
|
|
75
|
+
'Content-Type': 'application/json',
|
|
76
|
+
'X-Vibe-Client-Id': clientId,
|
|
77
|
+
'X-Vibe-Timestamp': String(timestamp),
|
|
78
|
+
'X-Vibe-Signature': signature,
|
|
79
|
+
...(idpClientId && { 'X-Client-Id': idpClientId }),
|
|
80
|
+
},
|
|
81
|
+
body: JSON.stringify({
|
|
82
|
+
endpoint,
|
|
83
|
+
method: options.method,
|
|
84
|
+
data: options.body ?? null,
|
|
85
|
+
}),
|
|
86
|
+
cache: 'no-store',
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
if (res.status === 204) return { ok: true, status: 204, data: null };
|
|
90
|
+
if (!res.ok) {
|
|
91
|
+
const errorText = await res.text();
|
|
92
|
+
return { ok: false, status: res.status, data: null, error: errorText };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const body = await res.json();
|
|
96
|
+
return { ok: true, status: res.status, data: body };
|
|
97
|
+
} catch (error) {
|
|
98
|
+
return { ok: false, status: 0, data: null, error: String(error) };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function getCountryFlag(countryCode: string): string {
|
|
103
|
+
if (!countryCode || countryCode.length !== 2) return '';
|
|
104
|
+
const codePoints = countryCode
|
|
105
|
+
.toUpperCase()
|
|
106
|
+
.split('')
|
|
107
|
+
.map(char => 127397 + char.charCodeAt(0));
|
|
108
|
+
return String.fromCodePoint(...codePoints);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface AdminAnalyticsHandlerConfig {
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* POST /api/admin/analytics
|
|
116
|
+
* Body: { type: 'geo' | 'logins' | 'revenue' | 'features', period?: string }
|
|
117
|
+
*/
|
|
118
|
+
export function createAnalyticsHandler(config: AdminAnalyticsHandlerConfig) {
|
|
119
|
+
return {
|
|
120
|
+
async POST(request: NextRequest) {
|
|
121
|
+
const adminCheck = await checkAdminRole(request);
|
|
122
|
+
if (adminCheck.error) return adminCheck.error;
|
|
123
|
+
|
|
124
|
+
const body = await request.json();
|
|
125
|
+
const { type, period = '7d' } = body;
|
|
126
|
+
|
|
127
|
+
const now = new Date();
|
|
128
|
+
let startDate: Date;
|
|
129
|
+
switch (period) {
|
|
130
|
+
case '24h':
|
|
131
|
+
startDate = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
|
132
|
+
break;
|
|
133
|
+
case '7d':
|
|
134
|
+
startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
|
135
|
+
break;
|
|
136
|
+
case '30d':
|
|
137
|
+
startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
|
138
|
+
break;
|
|
139
|
+
case '90d':
|
|
140
|
+
startDate = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
|
|
141
|
+
break;
|
|
142
|
+
default:
|
|
143
|
+
startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (type === 'geo') {
|
|
147
|
+
return await getGeoAnalytics(startDate);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (type === 'logins') {
|
|
151
|
+
return await getLoginAnalytics(startDate);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (type === 'revenue') {
|
|
155
|
+
return await getRevenueAnalytics(startDate);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (type === 'features') {
|
|
159
|
+
return await getFeatureUsageAnalytics(startDate);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (type === 'summary') {
|
|
163
|
+
return await getSummaryAnalytics(startDate);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return NextResponse.json({ error: 'Invalid analytics type' }, { status: 400 });
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function getGeoAnalytics(startDate: Date) {
|
|
172
|
+
const result = await vibeServiceRequest<any>(
|
|
173
|
+
'/v1/collections/vibe_app/tables/login_sessions/query',
|
|
174
|
+
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
if (!result.ok) {
|
|
178
|
+
return NextResponse.json({ error: result.error }, { status: result.status || 500 });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const sessions = result.data?.data || result.data?.documents || [];
|
|
182
|
+
const recentSessions = sessions.filter((s: any) => new Date(s.created_at) >= startDate);
|
|
183
|
+
|
|
184
|
+
const byCountry: Record<string, { count: number; flag: string; cities: Set<string> }> = {};
|
|
185
|
+
const byCity: Record<string, number> = {};
|
|
186
|
+
|
|
187
|
+
recentSessions.forEach((s: any) => {
|
|
188
|
+
const country = s.country_code || s.country || 'Unknown';
|
|
189
|
+
const city = s.city || 'Unknown';
|
|
190
|
+
|
|
191
|
+
if (!byCountry[country]) {
|
|
192
|
+
byCountry[country] = { count: 0, flag: getCountryFlag(country), cities: new Set() };
|
|
193
|
+
}
|
|
194
|
+
byCountry[country].count++;
|
|
195
|
+
byCountry[country].cities.add(city);
|
|
196
|
+
|
|
197
|
+
const cityKey = `${city}, ${country}`;
|
|
198
|
+
byCity[cityKey] = (byCity[cityKey] || 0) + 1;
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
const countries = Object.entries(byCountry)
|
|
202
|
+
.map(([code, data]) => ({
|
|
203
|
+
code,
|
|
204
|
+
flag: data.flag,
|
|
205
|
+
count: data.count,
|
|
206
|
+
cities: data.cities.size,
|
|
207
|
+
}))
|
|
208
|
+
.sort((a, b) => b.count - a.count);
|
|
209
|
+
|
|
210
|
+
const cities = Object.entries(byCity)
|
|
211
|
+
.map(([name, count]) => ({ name, count }))
|
|
212
|
+
.sort((a, b) => b.count - a.count)
|
|
213
|
+
.slice(0, 20);
|
|
214
|
+
|
|
215
|
+
return NextResponse.json({
|
|
216
|
+
geo: {
|
|
217
|
+
totalSessions: recentSessions.length,
|
|
218
|
+
uniqueCountries: countries.length,
|
|
219
|
+
countries,
|
|
220
|
+
topCities: cities,
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function getLoginAnalytics(startDate: Date) {
|
|
226
|
+
const result = await vibeServiceRequest<any>(
|
|
227
|
+
'/v1/collections/vibe_app/tables/login_sessions/query',
|
|
228
|
+
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
if (!result.ok) {
|
|
232
|
+
return NextResponse.json({ error: result.error }, { status: result.status || 500 });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const sessions = result.data?.data || result.data?.documents || [];
|
|
236
|
+
const recentSessions = sessions.filter((s: any) => new Date(s.created_at) >= startDate);
|
|
237
|
+
|
|
238
|
+
// Group by day
|
|
239
|
+
const byDay: Record<string, number> = {};
|
|
240
|
+
const byHour: Record<number, number> = {};
|
|
241
|
+
const byDevice: Record<string, number> = {};
|
|
242
|
+
const byBrowser: Record<string, number> = {};
|
|
243
|
+
|
|
244
|
+
recentSessions.forEach((s: any) => {
|
|
245
|
+
const date = new Date(s.created_at);
|
|
246
|
+
const dayKey = date.toISOString().split('T')[0];
|
|
247
|
+
byDay[dayKey] = (byDay[dayKey] || 0) + 1;
|
|
248
|
+
|
|
249
|
+
const hour = date.getHours();
|
|
250
|
+
byHour[hour] = (byHour[hour] || 0) + 1;
|
|
251
|
+
|
|
252
|
+
const device = s.device_type || s.device || 'Unknown';
|
|
253
|
+
byDevice[device] = (byDevice[device] || 0) + 1;
|
|
254
|
+
|
|
255
|
+
const browser = s.browser || 'Unknown';
|
|
256
|
+
byBrowser[browser] = (byBrowser[browser] || 0) + 1;
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
const dailyLogins = Object.entries(byDay)
|
|
260
|
+
.map(([date, count]) => ({ date, count }))
|
|
261
|
+
.sort((a, b) => a.date.localeCompare(b.date));
|
|
262
|
+
|
|
263
|
+
const hourlyDistribution = Object.entries(byHour)
|
|
264
|
+
.map(([hour, count]) => ({ hour: parseInt(hour), count }))
|
|
265
|
+
.sort((a, b) => a.hour - b.hour);
|
|
266
|
+
|
|
267
|
+
return NextResponse.json({
|
|
268
|
+
logins: {
|
|
269
|
+
total: recentSessions.length,
|
|
270
|
+
uniqueUsers: new Set(recentSessions.map((s: any) => s.idp_user_id || s.user_id)).size,
|
|
271
|
+
dailyLogins,
|
|
272
|
+
hourlyDistribution,
|
|
273
|
+
byDevice: Object.entries(byDevice).map(([device, count]) => ({ device, count })),
|
|
274
|
+
byBrowser: Object.entries(byBrowser).map(([browser, count]) => ({ browser, count })),
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function getRevenueAnalytics(startDate: Date) {
|
|
280
|
+
// Try to get transactions table
|
|
281
|
+
const result = await vibeServiceRequest<any>(
|
|
282
|
+
'/v1/collections/vibe_app/tables/transactions/query',
|
|
283
|
+
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
284
|
+
);
|
|
285
|
+
|
|
286
|
+
if (!result.ok) {
|
|
287
|
+
// Table might not exist, return empty stats
|
|
288
|
+
return NextResponse.json({
|
|
289
|
+
revenue: {
|
|
290
|
+
total: 0,
|
|
291
|
+
count: 0,
|
|
292
|
+
byDay: [],
|
|
293
|
+
byTier: {},
|
|
294
|
+
message: 'No transactions table or data available',
|
|
295
|
+
},
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const transactions = result.data?.data || result.data?.documents || [];
|
|
300
|
+
const recentTxns = transactions.filter((t: any) => new Date(t.created_at) >= startDate);
|
|
301
|
+
|
|
302
|
+
const byDay: Record<string, { count: number; amount: number }> = {};
|
|
303
|
+
const byTier: Record<string, { count: number; amount: number }> = {};
|
|
304
|
+
let totalAmount = 0;
|
|
305
|
+
|
|
306
|
+
recentTxns.forEach((t: any) => {
|
|
307
|
+
const date = new Date(t.created_at).toISOString().split('T')[0];
|
|
308
|
+
const amount = parseFloat(t.amount) || 0;
|
|
309
|
+
const tier = t.tier || t.product || 'unknown';
|
|
310
|
+
|
|
311
|
+
if (!byDay[date]) byDay[date] = { count: 0, amount: 0 };
|
|
312
|
+
byDay[date].count++;
|
|
313
|
+
byDay[date].amount += amount;
|
|
314
|
+
|
|
315
|
+
if (!byTier[tier]) byTier[tier] = { count: 0, amount: 0 };
|
|
316
|
+
byTier[tier].count++;
|
|
317
|
+
byTier[tier].amount += amount;
|
|
318
|
+
|
|
319
|
+
totalAmount += amount;
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
const dailyRevenue = Object.entries(byDay)
|
|
323
|
+
.map(([date, data]) => ({ date, ...data }))
|
|
324
|
+
.sort((a, b) => a.date.localeCompare(b.date));
|
|
325
|
+
|
|
326
|
+
return NextResponse.json({
|
|
327
|
+
revenue: {
|
|
328
|
+
total: totalAmount,
|
|
329
|
+
count: recentTxns.length,
|
|
330
|
+
byDay: dailyRevenue,
|
|
331
|
+
byTier,
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async function getFeatureUsageAnalytics(startDate: Date) {
|
|
337
|
+
// Try to get feature_usage or analytics table
|
|
338
|
+
const result = await vibeServiceRequest<any>(
|
|
339
|
+
'/v1/collections/vibe_app/tables/feature_usage/query',
|
|
340
|
+
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
341
|
+
);
|
|
342
|
+
|
|
343
|
+
if (!result.ok) {
|
|
344
|
+
// Try analytics table as fallback
|
|
345
|
+
const analyticsResult = await vibeServiceRequest<any>(
|
|
346
|
+
'/v1/collections/vibe_app/tables/analytics/query',
|
|
347
|
+
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
348
|
+
);
|
|
349
|
+
|
|
350
|
+
if (!analyticsResult.ok) {
|
|
351
|
+
return NextResponse.json({
|
|
352
|
+
features: {
|
|
353
|
+
total: 0,
|
|
354
|
+
byFeature: {},
|
|
355
|
+
message: 'No feature usage data available',
|
|
356
|
+
},
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const events = analyticsResult.data?.data || analyticsResult.data?.documents || [];
|
|
361
|
+
return processFeatureUsage(events, startDate);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const events = result.data?.data || result.data?.documents || [];
|
|
365
|
+
return processFeatureUsage(events, startDate);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function processFeatureUsage(events: any[], startDate: Date) {
|
|
369
|
+
const recentEvents = events.filter((e: any) => new Date(e.created_at) >= startDate);
|
|
370
|
+
|
|
371
|
+
const byFeature: Record<string, { count: number; uniqueUsers: Set<string> }> = {};
|
|
372
|
+
const byDay: Record<string, number> = {};
|
|
373
|
+
|
|
374
|
+
recentEvents.forEach((e: any) => {
|
|
375
|
+
const feature = e.feature || e.action || e.event_type || 'unknown';
|
|
376
|
+
const userId = e.user_id || e.idp_user_id || 'anonymous';
|
|
377
|
+
const date = new Date(e.created_at).toISOString().split('T')[0];
|
|
378
|
+
|
|
379
|
+
if (!byFeature[feature]) {
|
|
380
|
+
byFeature[feature] = { count: 0, uniqueUsers: new Set() };
|
|
381
|
+
}
|
|
382
|
+
byFeature[feature].count++;
|
|
383
|
+
byFeature[feature].uniqueUsers.add(userId);
|
|
384
|
+
|
|
385
|
+
byDay[date] = (byDay[date] || 0) + 1;
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
const features = Object.entries(byFeature)
|
|
389
|
+
.map(([name, data]) => ({
|
|
390
|
+
name,
|
|
391
|
+
count: data.count,
|
|
392
|
+
uniqueUsers: data.uniqueUsers.size,
|
|
393
|
+
}))
|
|
394
|
+
.sort((a, b) => b.count - a.count);
|
|
395
|
+
|
|
396
|
+
const dailyUsage = Object.entries(byDay)
|
|
397
|
+
.map(([date, count]) => ({ date, count }))
|
|
398
|
+
.sort((a, b) => a.date.localeCompare(b.date));
|
|
399
|
+
|
|
400
|
+
return NextResponse.json({
|
|
401
|
+
features: {
|
|
402
|
+
total: recentEvents.length,
|
|
403
|
+
byFeature: features,
|
|
404
|
+
dailyUsage,
|
|
405
|
+
},
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async function getSummaryAnalytics(startDate: Date) {
|
|
410
|
+
// Get users
|
|
411
|
+
const usersResult = await vibeServiceRequest<any>(
|
|
412
|
+
'/v1/collections/vibe_app/tables/users/query',
|
|
413
|
+
{ method: 'POST', body: { page: 1, pageSize: 10000 } }
|
|
414
|
+
);
|
|
415
|
+
|
|
416
|
+
// Get sessions
|
|
417
|
+
const sessionsResult = await vibeServiceRequest<any>(
|
|
418
|
+
'/v1/collections/vibe_app/tables/login_sessions/query',
|
|
419
|
+
{ method: 'POST', body: { page: 1, pageSize: 5000 } }
|
|
420
|
+
);
|
|
421
|
+
|
|
422
|
+
const users = usersResult.ok ? (usersResult.data?.data || usersResult.data?.documents || []) : [];
|
|
423
|
+
const sessions = sessionsResult.ok ? (sessionsResult.data?.data || sessionsResult.data?.documents || []) : [];
|
|
424
|
+
|
|
425
|
+
const recentUsers = users.filter((u: any) => new Date(u.created_at) >= startDate);
|
|
426
|
+
const recentSessions = sessions.filter((s: any) => new Date(s.created_at) >= startDate);
|
|
427
|
+
|
|
428
|
+
const tierCounts: Record<string, number> = {};
|
|
429
|
+
users.forEach((u: any) => {
|
|
430
|
+
const tier = u.tier || 'free';
|
|
431
|
+
tierCounts[tier] = (tierCounts[tier] || 0) + 1;
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
return NextResponse.json({
|
|
435
|
+
summary: {
|
|
436
|
+
totalUsers: users.length,
|
|
437
|
+
newUsers: recentUsers.length,
|
|
438
|
+
activeSessions: sessions.filter((s: any) => s.status === 'active').length,
|
|
439
|
+
recentLogins: recentSessions.length,
|
|
440
|
+
usersByTier: tierCounts,
|
|
441
|
+
},
|
|
442
|
+
});
|
|
443
|
+
}
|