You are a senior full-stack developer tasked with building a fully functional MVP of PlayerPulse, an AI-powered SaaS platform designed to help game studios proactively identify and mitigate player churn. The platform analyzes player behavior data to predict potential drops in engagement and offers personalized intervention strategies.
PROJECT OVERVIEW:
PlayerPulse aims to solve the critical problem of declining player engagement and revenue in the gaming industry, a challenge highlighted by recent industry trends like Epic Games' layoffs due to falling Fortnite usage. The platform will ingest player data, utilize AI to predict churn risk, and provide actionable insights and strategies to game studios. The core value proposition is to empower studios with data-driven foresight, enabling them to retain players, optimize monetization, and foster sustainable growth.
TECH STACK:
- Frontend: React (Next.js App Router)
- Styling: Tailwind CSS
- ORM: Drizzle ORM (with PostgreSQL as the database)
- UI Components: shadcn/ui
- Authentication: NextAuth.js (for secure user management)
- State Management: Zustand or React Context API for global state
- Data Fetching: React Server Components, Server Actions, and client-side fetching with SWR or TanStack Query
- Charting: Recharts or Chart.js for data visualization
- Backend: Node.js (via Next.js API routes/server components)
- Database: PostgreSQL
- Deployment: Vercel
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. **users** table:
- `id` (UUID, Primary Key)
- `name` (VARCHAR(255))
- `email` (VARCHAR(255), Unique)
- `emailVerified` (TIMESTAMP WITH TIME ZONE)
- `image` (VARCHAR(255))
- `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
- `updatedAt` (TIMESTAMP WITH TIME ZONE, Default: now())
2. **accounts** table (for NextAuth.js):
- `id` (VARCHAR(255), Primary Key)
- `userId` (UUID, Foreign Key to users.id)
- `type` (VARCHAR(255))
- `provider` (VARCHAR(255))
- `providerAccountId` (VARCHAR(255))
- `refresh_token` (TEXT)
- `access_token` (TEXT)
- `expires_at` (BIGINT)
- `token_type` (VARCHAR(255))
- `scope` (VARCHAR(255))
- `id_token` (TEXT)
- `session_state` (VARCHAR(255))
3. **sessions** table (for NextAuth.js):
- `sessionToken` (VARCHAR(255), Primary Key)
- `userId` (UUID, Foreign Key to users.id)
- `expires` (TIMESTAMP WITH TIME ZONE)
4. **verificationTokens** table (for NextAuth.js):
- `identifier` (VARCHAR(255))
- `token` (VARCHAR(255))
- `expires` (TIMESTAMP WITH TIME ZONE)
5. **studios** table:
- `id` (UUID, Primary Key)
- `userId` (UUID, Foreign Key to users.id, Unique)
- `studioName` (VARCHAR(255), Not Null)
- `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
- `updatedAt` (TIMESTAMP WITH TIME ZONE, Default: now())
6. **games** table:
- `id` (UUID, Primary Key)
- `studioId` (UUID, Foreign Key to studios.id)
- `gameName` (VARCHAR(255), Not Null)
- `platform` (VARCHAR(255))
- `genre` (VARCHAR(255))
- `releaseDate` (DATE)
- `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
- `updatedAt` (TIMESTAMP WITH TIME ZONE, Default: now())
7. **player_data** table:
- `id` (BIGSERIAL, Primary Key)
- `gameId` (UUID, Foreign Key to games.id)
- `playerId` (VARCHAR(255), Not Null) -- Unique identifier for the player within the game
- `sessionStartTime` (TIMESTAMP WITH TIME ZONE)
- `sessionEndTime` (TIMESTAMP WITH TIME ZONE)
- `sessionDurationMinutes` (INTEGER)
- `purchaseAmount` (DECIMAL(10, 2))
- `purchaseDate` (TIMESTAMP WITH TIME ZONE)
- `achievementsUnlocked` (INTEGER)
- `levelReached` (INTEGER)
- `lastLoginDate` (TIMESTAMP WITH TIME ZONE)
- `registrationDate` (TIMESTAMP WITH TIME ZONE)
- `country` (VARCHAR(100))
- `deviceType` (VARCHAR(50))
- `eventTimestamp` (TIMESTAMP WITH TIME ZONE, Default: now())
- UNIQUE (`gameId`, `playerId`, `eventTimestamp`) -- To prevent duplicate events within a short timeframe
8. **churn_predictions** table:
- `id` (BIGSERIAL, Primary Key)
- `gameId` (UUID, Foreign Key to games.id)
- `playerId` (VARCHAR(255), Not Null)
- `predictionDate` (TIMESTAMP WITH TIME ZONE, Default: now())
- `churnProbability` (DECIMAL(5, 4), Not Null) -- e.g., 0.7530 (75.30%)
- `predictionModelVersion` (VARCHAR(50))
- `isActive` (BOOLEAN, Default: true)
- `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
9. **intervention_strategies** table:
- `id` (BIGSERIAL, Primary Key)
- `gameId` (UUID, Foreign Key to games.id)
- `strategyName` (VARCHAR(255), Not Null)
- `strategyDescription` (TEXT)
- `targetSegment` (VARCHAR(255)) -- e.g., 'High Churn Risk', 'Low Spenders'
- `recommendedActions` (TEXT) -- e.g., 'Offer 10% discount coupon', 'New content drop announcement'
- `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
CORE FEATURES & USER FLOW:
1. **Authentication Flow (Email/Password & OAuth with Google/GitHub):**
- User lands on the homepage.
- Clicks 'Sign Up' or 'Sign In'.
- Sign Up: Enters email, password, confirms password. Upon successful validation, an account is created, and a verification email is sent (basic implementation for MVP, actual verification can be deferred). User is redirected to onboarding.
- Sign In: Enters email and password. Validates credentials. Upon success, redirects to the dashboard. Supports 'Forgot Password' flow (simulated in MVP, actual reset mechanism can be added later).
- OAuth: Clicks 'Sign in with Google/GitHub'. Redirected to the provider's authentication page. Upon successful authentication, user is redirected back, and their account is created/linked.
- Protected Routes: All application routes except public landing/auth pages require authentication. Redirects unauthenticated users to the sign-in page.
2. **Studio & Game Onboarding:**
- After initial login, users are prompted to set up their studio profile (`studioName`).
- Users can then add their games (`gameName`, `platform`, `genre`, `releaseDate`). This is crucial for data segregation and analysis.
- Provide clear instructions on how to integrate their game data (API key generation, data schema examples).
3. **Data Ingestion (Simulated for MVP):
- A dedicated section/API endpoint (`/api/data-ingestion`) to receive player data. For MVP, this can be a mock endpoint or a manual CSV upload feature.
- The backend validates incoming data against the `player_data` schema and stores it.
- Cron jobs or background tasks (simulated via Next.js server actions/cron package) will periodically trigger the AI prediction model.
- The AI model (mocked for MVP - e.g., simple rule-based or random assignment) processes `player_data` and populates `churn_predictions` and suggests `intervention_strategies`.
4. **Dashboard & Key Metrics:**
- Upon login, users see their main dashboard filtered by the selected game (dropdown menu).
- Display core metrics using charts (Recharts):
- Player Count (Daily/Weekly Active Users - DAU/WAU)
- Retention Rate (e.g., Day 1, Day 7, Day 30)
- Average Session Duration
- Total Revenue / Average Revenue Per User (ARPU)
- New Player Registrations
- Data should be fetched efficiently using Server Components where possible, and client-side fetching for interactive charts.
5. **Churn Prediction & Early Warning:
- A dedicated page ('Churn Analysis') showing predicted churn probabilities for players.
- Display a list of players identified as high churn risks (e.g., `churnProbability > 0.7`).
- Show key factors contributing to the churn prediction (simulated in MVP - e.g., 'Low session frequency', 'No recent purchases').
- Visual indicators (e.g., red/amber/green status) for churn risk levels.
6. **Intervention Strategies:**
- A section displaying suggested intervention strategies based on AI analysis and churn predictions.
- Each strategy includes a description, target player segment, and recommended actions.
- Ability to mark strategies as 'Implemented' or 'Dismissed' (for tracking).
API & DATA FETCHING:
- **API Routes (Next.js App Router):** Use Server Actions for mutations (e.g., adding games, updating user settings) and Route Handlers (`app/api/.../route.ts`) for GET requests where necessary, especially for external integrations (simulated).
- **Data Fetching:** Leverage React Server Components (RSC) for initial data loading on pages like the Dashboard and Churn Analysis for optimal performance and SEO. Use client-side fetching (SWR/TanStack Query) for dynamic data, updates, and interactive elements within components.
- **Authentication:** Utilize `next-auth` library for session management and protected route checks.
- **Example API (Conceptual for Data Ingestion):**
```
POST /api/games/[gameId]/ingest-player-data
Headers: {"X-API-KEY": "YOUR_STUDIO_API_KEY"}
Body: [
{
"playerId": "player_123",
"sessionStartTime": "2023-10-27T10:00:00Z",
"sessionDurationMinutes": 60,
"purchaseAmount": 19.99,
"lastLoginDate": "2023-10-27T10:00:00Z",
// ... other fields
}
]
Response: 200 OK or 400 Bad Request
```
- **Example Data Fetching (RSC):**
```typescript
// app/dashboard/page.tsx (Example within a Server Component)
import { db } from '@/lib/db';
import { games, playerData } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import MetricsChart from './MetricsChart'; // Client Component
async function getGameData(gameId: string) {
// Simplified data aggregation for MVP
const data = await db.query.playerData.findMany({
where: eq(playerData.gameId, gameId),
// Consider more efficient aggregation queries for production
});
// Process data for charts
return processDataForCharts(data);
}
export default async function DashboardPage({ params }: { params: { gameId: string } }) {
const gameData = await getGameData(params.gameId);
return (
<div>
<h1>Dashboard for {params.gameId}</h1>
<MetricsChart data={gameData} />
</div>
);
}
```
COMPONENT BREAKDOWN (Next.js App Router Structure):
- **`app/`**
- **`layout.tsx`**: Root layout (includes `html`, `body`, global providers, shadcn/ui ThemeProvider).
- **`page.tsx`**: Public landing page.
- **`auth/`**
- `sign-in/page.tsx`: Sign-in form component.
- `sign-up/page.tsx`: Sign-up form component.
- `layout.tsx`: Auth specific layout (minimal header/footer).
- **`onboarding/`**
- `studio/page.tsx`: Studio creation form.
- `games/page.tsx`: Game addition form.
- `layout.tsx`: Onboarding specific layout.
- **`dashboard/`**
- `page.tsx`: Main dashboard page (RSC, fetches selected game data).
- `layout.tsx`: Main application layout with sidebar navigation.
- `MetricsChart.tsx`: Client component for displaying charts (uses SWR/RQ for updates).
- `GameSelector.tsx`: Client component for selecting the active game.
- **`churn/`**
- `page.tsx`: Churn prediction overview page (RSC).
- `PlayerList.tsx`: Client component displaying high-risk players with filtering/sorting.
- `ChurnFactors.tsx`: Component showing contributing factors (mocked).
- **`strategies/`**
- `page.tsx`: Intervention strategies page (RSC).
- `StrategyCard.tsx`: Component to display individual strategy details.
- `StrategyForm.tsx`: (Future) Form to create/edit strategies.
- **`settings/`**
- `profile/page.tsx`: User profile settings.
- `studio/page.tsx`: Studio settings.
- `games/[gameId]/page.tsx`: Individual game settings.
- **`api/`**
- `auth/[...nextauth]/route.ts`: NextAuth.js handler.
- `games/[gameId]/ingest-player-data/route.ts`: (Conceptual) Data ingestion API endpoint.
- **`components/`**
- **`ui/`**: Re-exported components from `shadcn/ui` (Button, Card, Input, Sheet, Table, DropdownMenu, etc.).
- **`shared/`**: Common components like Header, Sidebar, Footer, ErrorMessage, LoadingSpinner.
- **`charts/`**: Reusable chart components.
- **`forms/`**: Form components (e.g., `StudioForm`, `GameForm`).
- **`lib/`**
- **`db.ts`**: Drizzle ORM database connection setup.
- **`auth.ts`**: NextAuth.js configuration.
- **`utils.ts`**: Utility functions.
- **`ai`**: (Placeholder) AI model integration logic.
- **`hooks/`**: Custom React hooks (e.g., `usePlayerData`, `useChurnPredictions`).
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, Clean, Data-Driven.
- **Color Palette:**
- Primary: `#4F46E5` (Indigo-500) - For key actions, active states.
- Secondary: `#6366F1` (Indigo-600) - Accents, secondary buttons.
- Background: `#F9FAFB` (Light Gray) - Main background.
- Surface: `#FFFFFF` (White) - Card backgrounds, content areas.
- Text (Primary): `#111827` (Gray-900) - Main text.
- Text (Secondary): `#6B7280` (Gray-500) - Subtitles, less important text.
- Accent (Success): `#10B981` (Green-500)
- Accent (Warning): `#F59E0B` (Amber-500)
- Accent (Danger): `#EF4444` (Red-500)
- **Typography:**
- Headings: Inter (Variable Font),wght 700
- Body: Inter (Variable Font), Wght 400/500
- **Layout:** Sidebar navigation on the left, main content area on the right. Consistent spacing and padding using Tailwind's utility classes (e.g., `p-6`, `space-y-4`). Use `max-w-7xl` and `mx-auto` for content containers.
- **Visual Elements:** Clean data visualizations with clear labels. Subtle use of gradients for primary buttons or active states. Minimalistic icons.
- **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows into single columns. Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`).
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/out using Next.js `AnimatePresence` (optional for MVP, but recommended for polish).
- **Hover Effects:** Slight scale-up or background color change on interactive elements (buttons, cards).
- **Loading States:** Use shadcn/ui's `Skeleton` component or a custom loading spinner within buttons/data fetching states. Display a subtle loading indicator when fetching data.
- **Transitions:** Smooth transitions for UI element changes (e.g., dropdown menus, modal appearances) using Tailwind CSS transitions.
EDGE CASES:
- **Authentication:** Handle invalid credentials, expired sessions, OAuth callback errors gracefully. Redirect users appropriately.
- **Empty States:** Design informative empty states for dashboards, player lists, etc., when no data is available. Include calls to action (e.g., 'Upload your first data file', 'Add your first game').
- **Data Validation:** Implement robust server-side validation for all incoming data (API ingestion, form submissions) using Zod with Drizzle schema.
- **Error Handling:** Implement global error handling (e.g., using an Error Boundary in React and appropriate API error responses). Display user-friendly error messages.
- **Authorization:** Ensure users can only access and manage data belonging to their own studio.
- **API Rate Limiting:** (Future) Implement rate limiting for the data ingestion API.
SAMPLE DATA (for `player_data` table):
1. **Player: 'player_abc', Game: 'Cosmic Raiders', High Engagement:**
```json
{
"playerId": "player_abc",
"gameId": "<game-uuid-1>",
"sessionStartTime": "2023-10-26T14:00:00Z",
"sessionEndTime": "2023-10-26T16:30:00Z",
"sessionDurationMinutes": 150,
"purchaseAmount": 29.99,
"purchaseDate": "2023-10-26T15:00:00Z",
"achievementsUnlocked": 5,
"levelReached": 15,
"lastLoginDate": "2023-10-27T09:00:00Z",
"registrationDate": "2023-09-01T10:00:00Z",
"country": "USA",
"deviceType": "PC"
}
```
2. **Player: 'player_def', Game: 'Cosmic Raiders', Low Engagement, Recent Login:**
```json
{
"playerId": "player_def",
"gameId": "<game-uuid-1>",
"sessionStartTime": "2023-10-27T11:00:00Z",
"sessionEndTime": "2023-10-27T11:15:00Z",
"sessionDurationMinutes": 15,
"purchaseAmount": 0.00,
"lastLoginDate": "2023-10-27T11:00:00Z",
"registrationDate": "2023-10-01T12:00:00Z",
"country": "Canada",
"deviceType": "Mobile"
}
```
3. **Player: 'player_ghi', Game: 'Pixel Pioneers', High Purchase Activity:**
```json
{
"playerId": "player_ghi",
"gameId": "<game-uuid-2>",
"sessionStartTime": "2023-10-25T20:00:00Z",
"sessionEndTime": "2023-10-25T22:00:00Z",
"sessionDurationMinutes": 120,
"purchaseAmount": 99.99,
"purchaseDate": "2023-10-25T21:00:00Z",
"achievementsUnlocked": 10,
"levelReached": 25,
"lastLoginDate": "2023-10-26T18:00:00Z",
"registrationDate": "2023-08-15T08:00:00Z",
"country": "Germany",
"deviceType": "Tablet"
}
```
4. **Player: 'player_jkl', Game: 'Cosmic Raiders', Long Time Inactive:**
```json
{
"playerId": "player_jkl",
"gameId": "<game-uuid-1>",
"sessionStartTime": null,
"sessionEndTime": null,
"sessionDurationMinutes": null,
"purchaseAmount": 10.00,
"purchaseDate": "2023-09-10T14:00:00Z",
"achievementsUnlocked": 1,
"levelReached": 5,
"lastLoginDate": "2023-09-15T10:00:00Z",
"registrationDate": "2023-09-01T10:00:00Z",
"country": "USA",
"deviceType": "PC"
}
```
5. **Player: 'player_mno', Game: 'Pixel Pioneers', New Player, Low Activity:**
```json
{
"playerId": "player_mno",
"gameId": "<game-uuid-2>",
"sessionStartTime": "2023-10-27T15:00:00Z",
"sessionEndTime": "2023-10-27T15:20:00Z",
"sessionDurationMinutes": 20,
"purchaseAmount": 0.00,
"lastLoginDate": "2023-10-27T15:00:00Z",
"registrationDate": "2023-10-27T14:55:00Z",
"country": "UK",
"deviceType": "Mobile"
}
```
6. **Player: 'player_pqr', Game: 'Cosmic Raiders', Frequent but Short Sessions:**
```json
{
"playerId": "player_pqr",
"gameId": "<game-uuid-1>",
"sessionStartTime": "2023-10-27T08:00:00Z",
"sessionEndTime": "2023-10-27T08:10:00Z",
"sessionDurationMinutes": 10,
"purchaseAmount": 5.00,
"purchaseDate": "2023-10-27T08:05:00Z",
"achievementsUnlocked": 0,
"levelReached": 2,
"lastLoginDate": "2023-10-27T08:00:00Z",
"registrationDate": "2023-10-26T11:00:00Z",
"country": "USA",
"deviceType": "Mobile"
}
```
TURKISH TRANSLATIONS (Key UI Elements):
- Sign In: Giriş Yap
- Sign Up: Kayıt Ol
- Dashboard: Kontrol Paneli
- Games: Oyunlar
- Players: Oyuncular
- Churn Probability: Düşüş Olasılığı
- Intervention Strategies: Müdahale Stratejileri
- Settings: Ayarlar
- Add Game: Oyun Ekle
- Studio Name: Stüdyo Adı
- Active Players: Aktif Oyuncular
- Retention Rate: Elde Tutma Oranı
- Average Session: Ortalama Oturum Süresi
- Total Revenue: Toplam Gelir
- High Risk: Yüksek Risk
- Low Risk: Düşük Risk
- Apply Strategy: Stratejiyi Uygula
- Dismiss: Reddet
- Loading: Yükleniyor...
- No Data Available: Veri Mevcut Değil
- Submit: Gönder
- Save Changes: Değişiklikleri Kaydet
- Welcome: Hoş Geldiniz
- Log Out: Çıkış Yap