Commit 29021fee authored by Mahmoud Aglan's avatar Mahmoud Aglan

docs: FULL_SYNC_PLAN — complete managementplayer integration roadmap

Comprehensive plan documenting:
- 11 features player app writes that management can't see
- 10 management features player app doesn't integrate with
- 7 upgrade phases with estimated ~20 hours total effort
- Database functions needed (atomic coin award, ban check)
- 7 new management modules needed (rewards-config, seasons, etc.)
- Architecture diagram showing both systems' data flow
- Security gaps (no rate limit, no ban enforcement, no validation)
- Priority-ordered execution plan

Based on parallel audits of:
- el3ab-management: 38 modules, 425+ routes, tournament/player/economy systems
- el3ab-player: 27 API endpoints, tables used, admin visibility needs

Key finding: Both systems work independently but critical bridges are missing
(tournament registration, match visibility, reward configuration, ban enforcement)
Co-Authored-By: 's avatarClaude Opus 4.6 <noreply@anthropic.com>
parent 4de6634a
# EL3AB — Full Sync Plan (Management ↔ Player App)
## Overview
Both systems share the SAME Supabase database (106 tables). The management panel uses SERVICE_ROLE key (bypasses RLS). The player app uses ANON key + user JWT (RLS enforced).
**Management repo:** `/Users/mahmoudaglan/el3ab-management/` — 38 admin modules
**Player repo:** `/Users/mahmoudaglan/el3ab-player/` — 27 API endpoints
---
## CRITICAL GAPS: Management Doesn't Know About
These player features write to the DB but the management panel has NO visibility or control:
| Player Feature | DB Table | Management Gap |
|---------------|----------|---------------|
| Daily challenges | profiles, economy_transactions | No challenge config UI, no claim tracking |
| Battle pass / Season | profiles | Season config hardcoded in PHP, no admin UI |
| Daily reward claims | profiles, economy_transactions | No claim log view, no cooldown enforcement |
| Match coin/XP rewards | profiles, economy_transactions | No reward config (hardcoded 50/20/10) |
| Rating calculations | profiles, rating_history | K-factor hardcoded, no admin adjustment |
| Friend system | friendships | No admin moderation of friendships |
| Activity feed | activity_feed | No admin write to activity feed |
| Ludo matchmaking | ludo_queue, ludo_matches | No Ludo match admin view |
| Domino matches | domino_matches | No Domino match admin view |
| Puzzle progress | (not tracked) | Puzzle rating not persisted |
| Emote/chat in games | matches.game_state | No chat moderation tools |
---
## CRITICAL GAPS: Player App Doesn't Use Management Features
These management features exist but the player app doesn't integrate:
| Management Feature | Module | Player Gap |
|-------------------|--------|-----------|
| Feature flags with rollout % | feature-flags | Player reads flags but no rollout logic |
| Branding/theme from DB | branding | Player has own admin (/admin/branding.php), not synced |
| Moderation (ban/mute) | moderation | Player doesn't check ban status on actions |
| Workflow rules | workflows | Player ignores workflow approvals |
| Ads system | ads | Player has no ad rendering |
| Analytics events | analytics | Player sends no analytics |
| Notification sending | notifications | Management can't push to player app |
| Org events (RSVP) | org-events | Player shows events but no RSVP |
| Org chat channels | org-chat | Player has no org chat UI |
| Achievement definitions | (in DB) | Player reads but can't mark completion server-side |
---
## UPGRADE PLAN (Priority Order)
### Phase 1: Security & Integrity (URGENT)
**1.1 — Server-side move validation**
- Management needs: match replay tool, cheat detection dashboard
- Player needs: game.php validates FEN transitions are legal
- Tables: matches (add `validated` boolean column)
**1.2 — Economy atomicity**
- Management needs: transaction log viewer, balance audit tool
- Player needs: PostgreSQL functions for atomic coin/gem operations
- Action: Create `fn_award_coins(player_id, amount, reason)` DB function
**1.3 — Ban enforcement**
- Management has: moderation module with ban/mute
- Player needs: check `is_banned` on EVERY authenticated request
- Action: Add ban check to `includes/auth.php``requireAuth()`
**1.4 — Rate limiting**
- Neither has rate limiting
- Action: Add nginx-level rate limit OR PHP middleware
### Phase 2: Economy Sync
**2.1 — Reward configuration (admin-controlled)**
- Create `reward_config` table: key, value, updated_by
- Management: new "Rewards" module → CRUD for reward values
- Player: reads config instead of hardcoded values
- Keys: `chess_win_coins`, `chess_loss_coins`, `daily_reward_base`, `challenge_multiplier`, etc.
**2.2 — Battle pass seasons (admin-controlled)**
- Management: new "Seasons" module → create/edit seasons
- Table: `seasons` (id, name, starts_at, ends_at, tiers_json, is_active)
- Player: reads active season from DB instead of hardcoded PHP
**2.3 — Daily challenges (admin-controlled)**
- Management: new "Challenges" module → define challenge templates
- Table: `challenge_templates` (id, type, target, reward_coins, reward_xp, icon)
- Player: picks from templates instead of hardcoded array
**2.4 — Economy transaction viewer**
- Management already has `economy` module but needs:
- View all transactions for a player
- Filter by type (game_reward, daily, purchase, challenge)
- Bulk coin grant tool
- Balance adjustment with audit trail
### Phase 3: Game Management
**3.1 — Live matches dashboard**
- Management: new view in `games` module showing active matches
- Query: matches WHERE status='in_progress'
- Show: players, game_key, time_control, move_count, started_at
- Actions: Force-end match, flag for review
**3.2 — Ludo/Domino match viewer**
- Management: add ludo_matches and domino_matches to game browser
- Show: room_code, players, status, created_at
- Currently only chess matches visible
**3.3 — Match replay tool**
- Management: given a match ID, replay move by move
- Read: matches.moves (JSON array of moves) + matches.pgn
- Render: simple board viewer (doesn't need to be interactive)
**3.4 — Bot configuration sync**
- Management has: chess-bots module (CRUD on Stockfish API bots)
- Player has: hardcoded bot ELOs in game.js
- Fix: Player should fetch bot list from API (already does via bots.php → Stockfish)
- Remove hardcoded `botElos` object from game.js
### Phase 4: Tournament Sync
**4.1 — Tournament lifecycle**
- Management creates tournaments → player app shows them
- Already working but missing:
- Start time enforcement (player can register after start)
- Max player enforcement on registration
- Status transitions (draft → registration → in_progress → completed)
**4.2 — Swiss pairing visibility**
- Management generates pairings via SwissApiService
- Player reads pairings via swiss.php
- Already connected but needs:
- Real-time pairing notifications
- "Your next game is ready" push
**4.3 — Tournament results**
- After tournament completes:
- Prize distribution (coins/gems) — management triggers
- Player sees prize in notification
- Rating adjustments for tournament games
### Phase 5: Content Management
**5.1 — Puzzle management**
- Management: add puzzle import/create tool
- Currently puzzles table has ~100 entries (seeded)
- Need: bulk import from Lichess puzzle database
- Track: player puzzle ratings in new `player_puzzle_ratings` table
**5.2 — Cosmetics management**
- Management has cosmetics CRUD (assumed in economy module)
- Player reads/purchases correctly
- Missing: limited-time items, featured items rotation
**5.3 — Achievement management**
- Management: define achievements with conditions
- Player: check conditions on game events
- Missing: server-side achievement completion trigger
### Phase 6: Analytics & Monitoring
**6.1 — Player analytics**
- Track: DAU/MAU, games per day, average session, retention
- Management: new "Analytics" module with charts
- Player: send events to `analytics_events` table
**6.2 — Economy health**
- Track: coins minted vs spent, inflation rate
- Management: economy dashboard showing totals
- Alert: if coin generation exceeds spending by >2x
**6.3 — Match quality**
- Track: average game length, abandon rate, disconnect rate
- Management: quality dashboard
- Player: send match_ended event with metadata
### Phase 7: Notification Sync
**7.1 — Push from management to player**
- Management sends notifications (already writes to `notifications` table)
- Player reads notifications (already polls)
- Missing: real-time push (Supabase Realtime subscription)
- Action: Player subscribes to notifications INSERT events
**7.2 — System announcements**
- Management: "Send announcement to all players" button
- Inserts into notifications with type='system_announcement'
- Player: shows as toast on next load
---
## DATABASE FUNCTIONS NEEDED
```sql
-- Atomic coin award (prevents race conditions)
CREATE OR REPLACE FUNCTION award_coins(p_player_id UUID, p_amount INT, p_reason TEXT)
RETURNS INT AS $$
DECLARE new_balance INT;
BEGIN
UPDATE profiles SET coins = coins + p_amount WHERE id = p_player_id
RETURNING coins INTO new_balance;
INSERT INTO economy_transactions (player_id, type, currency, amount, balance_after, reason)
VALUES (p_player_id, 'reward', 'coins', p_amount, new_balance, p_reason);
RETURN new_balance;
END;
$$ LANGUAGE plpgsql;
-- Check and enforce ban
CREATE OR REPLACE FUNCTION is_player_banned(p_player_id UUID)
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM profiles
WHERE id = p_player_id AND is_banned = true
AND (ban_expires_at IS NULL OR ban_expires_at > NOW())
);
END;
$$ LANGUAGE plpgsql;
```
---
## NEW MANAGEMENT MODULES NEEDED
| Module | Purpose | Priority |
|--------|---------|----------|
| `rewards-config` | Configure all reward values (coins per win, daily, etc.) | HIGH |
| `seasons` | Create/manage battle pass seasons | HIGH |
| `challenge-templates` | Define daily challenge types | MEDIUM |
| `live-matches` | View active matches across all games | MEDIUM |
| `match-replay` | Replay any completed match | LOW |
| `economy-health` | Dashboard showing coin mint/spend rates | MEDIUM |
| `player-analytics` | DAU/MAU/retention charts | LOW |
---
## IMMEDIATE ACTIONS (This Session)
1. Add ban check to player app's `requireAuth()`
2. Create `reward_config` table and read from it in player APIs
3. Remove hardcoded economy values from player PHP files
4. Add match-history visibility to management's games module
5. Ensure management's tournament creation properly sets all required fields
---
## ARCHITECTURE DIAGRAM
```
┌─────────────────────────────────────────────────────────────┐
│ SUPABASE (PostgreSQL) │
│ 106 tables · RLS enforced · Realtime enabled │
├─────────────────────────────────────────────────────────────┤
│ │ │ │
│ Player App Management Panel │
│ (el3ab-player) (el3ab-management) │
│ │
│ • ANON key + JWT • SERVICE_ROLE key │
│ • RLS enforced • Bypasses RLS │
│ • 27 API endpoints • 38 admin modules │
│ • Reads config/flags • Writes config/flags │
│ • Awards coins (needs atomic) • Adjusts balances │
│ • Creates matches • Views/moderates matches │
│ • Registers for tournaments • Creates tournaments │
│ • Records ratings • Can override ratings │
│ • Handles matchmaking • Monitors queue health │
│ │
│ MISSING: MISSING: │
│ - Ban enforcement - Reward config UI │
│ - Rate limiting - Season/battlepass UI │
│ - Analytics events - Ludo/Domino match view │
│ - Server move validation - Challenge config UI │
│ - Atomic coin operations - Economy health dashboard │
└─────────────────────────────────────────────────────────────┘
```
---
## ESTIMATED EFFORT
| Phase | Effort | Impact |
|-------|--------|--------|
| Phase 1 (Security) | 2-3 hours | Critical — prevents cheating/exploits |
| Phase 2 (Economy) | 4-5 hours | High — admin controls all rewards |
| Phase 3 (Games) | 3-4 hours | Medium — visibility into live games |
| Phase 4 (Tournaments) | 2 hours | Medium — lifecycle enforcement |
| Phase 5 (Content) | 3 hours | Medium — puzzle/cosmetic management |
| Phase 6 (Analytics) | 4 hours | Low — monitoring (can defer) |
| Phase 7 (Notifications) | 1 hour | Medium — real-time push |
| **TOTAL** | **~20 hours** | |
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment