Initial commit

This commit is contained in:
2026-02-01 09:31:38 +01:00
commit e02db93960
4396 changed files with 1511612 additions and 0 deletions

View File

@@ -0,0 +1 @@
{"workflow_version":"1.2.0","timestamps":{"started":"2026-01-16T00:10:00Z","last_updated":"2026-01-16T00:15:00Z"},"mode":"initial_scan","scan_level":"exhaustive","project_root":"d:\\dev_new_pc\\chartbastan","output_folder":"d:\\dev_new_pc\\chartbastan\\docs","completed_steps":[{"step":"step_1","status":"completed","timestamp":"2026-01-16T00:15:00Z","summary":"Classified as greenfield web application with Next.js + FastAPI stack"}],"current_step":"step_2","findings":{"project_classification":{"project_type":"greenfield_web","repository_type":"monolith","domain":"gambling_betting_sports_analytics","complexity":"high","stack":{"frontend":"Next.js 16 + Tailwind 4 + shadcn/ui","backend":"Python FastAPI + Node.js API routes","database":"SQLite (Phase 1)","infrastructure":"VPS 5-10€/mois"},"current_phase":"planning_to_development","status":"prd_completed","brainstorming_completed":true,"architecture_in_progress":true}},"outputs_generated":["project-scan-report.json"],"resume_instructions":"Starting from step 2"}

336
docs/README-TEST.md Normal file
View File

@@ -0,0 +1,336 @@
# Guide de Test Rapide - ChartBastan
🚀 **Démarrage rapide pour tester l'application complète**
---
## 📋 Prérequis
Avant de commencer, assurez-vous d'avoir:
- ✅ Node.js 20+ ([Télécharger](https://nodejs.org/))
- ✅ Python 3.11+ ([Télécharger](https://www.python.org/))
- ✅ Git (optionnel)
**Vérifier les versions:**
```bash
node --version # Doit être 20+
python --version # Doit être 3.11+
```
---
## 🚀 Démarrage en 3 Étapes
### Étape 1: Installer les Dépendances Backend
```bash
cd backend
pip install -r requirements.txt
```
### Étape 2: Installer les Dépendances Frontend
```bash
cd ../chartbastan
npm install
```
### Étape 3: Démarrer les Deux Serveurs
**Terminal 1 - Backend:**
```bash
cd backend
python -m uvicorn app.main:app --reload --port 8000
```
Le backend démarre sur: **http://localhost:8000**
**Terminal 2 - Frontend:**
```bash
cd chartbastan
npm run dev
```
Le frontend démarre sur: **http://localhost:3000**
---
## 🎯 Tester l'Application
1. **Ouvrir votre navigateur** sur http://localhost:3000
2. **Page d'accueil** s'affiche avec le branding ChartBastan
3. **Tester l'inscription** → Créer un compte
4. **Tester le login** → Se connecter
5. **Explorer le dashboard** → Voir les matchs et prédictions
---
## 🧪 Fonctionnalités à Tester
### 1. Authentification
- [ ] Inscription d'un utilisateur
- [ ] Connexion avec identifiants valides
- [ ] Déconnexion
- [ ] Rester connecté (session persistence)
### 2. Dashboard Principal
- [ ] Affichage des matchs actuels
- [ ] Graphique d'énergie en temps réel
- [ ] Mise à jour automatique (pull-to-refresh)
### 3. Prédictions
- [ ] Faire une prédiction sur un match
- [ ] Voir les scores de confiance
- [ ] Voir l'énergie collective calculée
- [ ] Historique des prédictions
### 4. Classement (Leaderboard)
- [ ] Voir le Top 100
- [ ] Voir son propre rang
- [ ] Comparer avec d'autres utilisateurs
### 5. Badges et Gamification
- [ ] Voir les badges obtenus
- [ ] Progression des badges
- [ ] Partager les succès
### 6. Notifications
- [ ] Activer les notifications
- [ ] Recevoir des notifications de prédictions
- [ ] Gérer les préférences de notification
### 7. Historique
- [ ] Voir l'historique des prédictions
- [ ] Voir le taux de précision
- [ ] Comparer les résultats avec l'énergie collective
### 8. Parrainage
- [ ] Générer un lien de parrainage
- [ ] Voir les récompenses
### 9. Comparaison Énergie vs Stats
- [ ] Voir la comparaison énergie/stats
- [ ] Graphiques comparatifs
- [ ] Performance historique
---
## 🔧 Configuration Optionnelle
### API Documentation
Le backend fournit une documentation interactive:
- **Swagger UI:** http://localhost:8000/docs
- **ReDoc:** http://localhost:8000/redoc
### Base de Données
La base de données SQLite est créée automatiquement:
- Chemin: `chartbastan/chartbastan.db`
- Réinitialiser: Supprimer le fichier `.db` et redémarrer
### Workers Asynchrones
Les workers sont optionnels (pour scraping asynchrone):
```bash
# Scraper worker
cd backend
python workers/run_scraping_worker.py
# Sentiment worker
python workers/run_sentiment_worker.py
# Energy worker
python workers/run_energy_worker.py
```
---
## 📊 Structure des Données
### Tables Principales
- **users** - Utilisateurs authentifiés
- **matches** - Matchs de football
- **predictions** - Prédictions du système
- **user_predictions** - Prédictions utilisateurs
- **tweets** - Données Twitter scrapées
- **reddit_posts** - Données Reddit scrapées
- **sentiment_scores** - Scores de sentiment
- **energy_scores** - Scores d'énergie collective
---
## 🐛 Dépannage Rapide
### Backend ne démarre pas
```bash
# Vérifier si le port 8000 est utilisé
# Windows:
netstat -ano | findstr :8000
# Linux/Mac:
lsof -ti:8000 | xargs kill -9
# Réessayer
python -m uvicorn app.main:app --reload --port 8000
```
### Frontend ne démarre pas
```bash
# Nettoyer node_modules
rm -rf node_modules
npm install
# Réessayer
npm run dev
```
### Erreur de connexion Frontend-Backend
```bash
# Vérifier que backend tourne sur http://localhost:8000
curl http://localhost:8000/api/health
# Vérifier la configuration frontend
cat chartbastan/.env.local
# Doit contenir: NEXT_PUBLIC_API_URL=http://localhost:8000
```
### Base de données vide
```bash
cd backend
# Appliquer les migrations
alembic upgrade head
# Générer des données de test
python scripts/generate_historical_matches.py
```
---
## 📝 Commandes Utiles
### Backend
```bash
cd backend
# Linter
flake8 .
# Formatage
black .
# Tests
pytest tests/ -v
# Migrations
alembic upgrade head
```
### Frontend
```bash
cd chartbastan
# Linter
npm run lint
# Type checking
npm run type-check
# Tests
npm run test
# Build
npm run build
```
---
## 🎨 Personnalisation
### Changer le Port Frontend
```bash
cd chartbastan
npm run dev -- -p 3001
```
Mettre à jour `.env.local`:
```bash
NEXT_PUBLIC_API_URL=http://localhost:8000
NEXT_PUBLIC_PORT=3001
```
### Changer le Port Backend
```bash
cd backend
python -m uvicorn app.main:app --reload --port 8001
```
Mettre à jour `chartbastan/.env.local`:
```bash
NEXT_PUBLIC_API_URL=http://localhost:8001
```
---
## 📚 Documentation Complète
Pour plus de détails sur l'architecture et l'implémentation:
- **Documentation complète:** `docs/` (ce dossier)
- **PRD:** `_bmad-output/planning-artifacts/prd.md`
- **Architecture:** `_bmad-output/planning-artifacts/architecture.md`
- **Artefacts d'implémentation:** `_bmad-output/implementation-artifacts/` (38 fichiers)
---
## ✅ Checklist Avant le Test
- [ ] Node.js 20+ installé
- [ ] Python 3.11+ installé
- [ ] Dépendances backend installées (`pip install -r requirements.txt`)
- [ ] Dépendances frontend installées (`npm install`)
- [ ] Backend démarré sur le port 8000
- [ ] Frontend démarré sur le port 3000
- [ ] Navigateur ouvert sur http://localhost:3000
---
## 🎉 Bon Testing!
L'application est complète et tous les epics sont implémentés. Profitez de l'expérience ChartBastan!
**Pour des questions ou des problèmes:**
- Consultez la documentation Swagger: http://localhost:8000/docs
- Vérifiez les logs dans les terminaux
- Consultez les artefacts d'implémentation dans `_bmad-output/`
---
**Date de création:** 2026-01-18
**Version:** 0.1.0
**Statut:** Tous les épics complétés ✅

View File

@@ -0,0 +1,757 @@
# Patterns d'Architecture - ChartBastan
## Vue d'ensemble
ChartBastan utilise une architecture **client-serveur** avec:
- **Frontend:** Application React/Next.js (SPA avec SSR)
- **Backend:** API REST FastAPI
- **Communication:** REST API via HTTP
- **Architecture asynchrone:** RabbitMQ pour tâches lourdes
---
## Partie 1: Frontend Architecture (chartbastan/)
### Type d'Architecture: Component-Based avec App Router
**Framework:** Next.js 16 App Router
**Caractéristiques Principales:**
#### 1. Server Components vs Client Components
**Server Components (par défaut):**
- Exécutés sur le serveur
- Rendu HTML côté serveur
- Accès direct aux ressources serveur
- Pas d'hydratation nécessaire
- Utilisés pour: layouts, pages, data fetching initial
**Client Components (directive 'use client'):**
- Exécutés sur le client
- Hydratation côté client
- Interactivité utilisateur (events, state)
- Utilisés pour: formulaires, interactions, state local
**Exemple:**
```typescript
// Server Component (par défaut)
export default async function MatchPage() {
const matches = await fetchMatches(); // Exécuté sur serveur
return <MatchList matches={matches} />;
}
// Client Component
"use client";
export function MatchList({ matches }: { matches: Match[] }) {
const [selected, setSelected] = useState(null); // State local
return <div onClick={() => setSelected(matches[0])} />;
}
```
#### 2. App Router Structure
**Routing:** Système de fichiers dans `src/app/`
**Conventions:**
- `page.tsx` - Page principale de la route
- `layout.tsx` - Layout partagé pour la route et ses enfants
- `loading.tsx` - UI de chargement (automatic streaming)
- `error.tsx` - UI d'erreur (error boundary)
- `not-found.tsx` - UI pour 404
- `route.ts` - API routes (backend intégré)
**Exemple de structure:**
```
src/app/
├── layout.tsx # Layout racine
├── page.tsx # Page d'accueil (/)
├── login/
│ └── page.tsx # Page de login (/login)
├── matches/
│ ├── page.tsx # Liste des matchs (/matches)
│ ├── [id]/
│ │ └── page.tsx # Détail d'un match (/matches/123)
│ └── loading.tsx # Loading pour /matches
└── api/
└── auth/
└── route.ts # API route POST /api/auth
```
#### 3. Data Fetching Strategy
**Approche Hybride:**
**Server-Side Rendering (SSR):**
- Data fetch dans Server Components
- Cache avec React Cache
- Revalidation avec revalidatePath
- Avantages: SEO, premier rendu rapide
**Client-Side Fetching:**
- React Query pour data interactive
- Cache local et synchronisation
- Refetch automatique
- Optimistic updates
**Exemple:**
```typescript
// Server Component: SSR
import { fetchMatches } from '@/lib/data';
export default async function MatchesPage() {
const matches = await fetchMatches(); // Cache automatique
return <MatchList initialData={matches} />;
}
// Client Component: React Query
"use client";
import { useQuery } from '@tanstack/react-query';
export function MatchList({ initialData }) {
const { data } = useQuery({
queryKey: ['matches'],
queryFn: fetchMatches,
initialData, // Hydratation depuis SSR
refetchInterval: 30000, // Refetch toutes les 30s
});
}
```
#### 4. State Management
**Zustand (Global State):**
- Stores légers et simples
- Pas de Provider/Context nécessaires
- Sélecteurs pour optimisation
- DevTools intégrés
**Exemple:**
```typescript
// store/user.ts
import { create } from 'zustand';
interface UserStore {
user: User | null;
setUser: (user: User) => void;
}
export const useUserStore = create<UserStore>((set) => ({
user: null,
setUser: (user) => set({ user }),
}));
// Utilisation
export function UserProfile() {
const user = useUserStore((state) => state.user);
return <div>{user?.name}</div>;
}
```
**React Query (Server State):**
- Cache et synchronisation des données serveur
- Refetch, mutation, invalidation automatique
- Gestion optimiste
- Loading et error states
**Exemple:**
```typescript
const { data, isLoading, error } = useQuery({
queryKey: ['matches'],
queryFn: () => fetch('/api/matches').then(r => r.json()),
staleTime: 5000, // Données fraîches pendant 5s
});
if (isLoading) return <Loading />;
if (error) return <Error message={error.message} />;
return <MatchList matches={data} />;
```
#### 5. Middleware
**Next.js Middleware:**
- Authentification (better-auth)
- Protection de routes
- Redirections
- Headers et cookies
**Exemple:**
```typescript
// middleware.ts
import { auth } from "@/lib/auth";
export default auth((req) => {
const isLoggedIn = !!req.auth;
const isOnDashboard = req.nextUrl.pathname.startsWith("/dashboard");
if (!isLoggedIn && isOnDashboard) {
return Response.redirect(new URL("/login", req.url));
}
});
export const config = {
matcher: ["/dashboard/:path*", "/api/auth/:path*"],
};
```
---
### Architecture des Composants
#### 1. Component Hierarchy
**Composition de composants:**
- Pages → Layouts → Sections → Components → UI Elements
**Exemple:**
```
MatchPage (Page)
└── MatchLayout (Layout)
├── MatchHeader (Section)
│ └── MatchTitle (Component)
├── MatchContent (Section)
│ ├── MatchInfo (Component)
│ ├── MatchStats (Component)
│ │ └── StatCard (UI Element)
│ └── MatchPredictions (Component)
│ └── PredictionCard (UI Element)
└── MatchFooter (Section)
```
#### 2. Component Patterns
**Container/Presentational Pattern:**
```typescript
// Container: Logique et state
export function MatchContainer() {
const { data, isLoading } = useMatch(matchId);
const { predict } = usePrediction();
if (isLoading) return <Loading />;
return <MatchView match={data} onPredict={predict} />;
}
// Presentational: UI pure
export function MatchView({ match, onPredict }: Props) {
return (
<div>
<MatchHeader match={match} />
<PredictButton onClick={() => onPredict(match.id)} />
</div>
);
}
```
**Compound Components Pattern (shadcn/ui):**
```typescript
<Dialog>
<DialogTrigger>Open</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Title</DialogTitle>
</DialogHeader>
</DialogContent>
</Dialog>
```
#### 3. Custom Hooks
**Logique réutilisable:**
```typescript
// hooks/use-matches.ts
export function useMatches() {
return useQuery({
queryKey: ['matches'],
queryFn: fetchMatches,
});
}
// hooks/use-auth.ts
export function useAuth() {
const { user } = useUserStore();
return { isAuthenticated: !!user, user };
}
```
---
## Partie 2: Backend Architecture (backend/)
### Type d'Architecture: REST API / Layered Architecture
**Framework:** FastAPI
**Caractéristiques Principales:**
#### 1. Layered Architecture
**Couches:**
1. **API Layer** (`app/api/`)
- Endpoints REST
- Validation des requêtes
- Sérialisation des réponses
2. **Service Layer** (`app/services/`)
- Logique métier
- Orchestration des opérations
- Pas de dépendances directes aux modèles
3. **Repository/Model Layer** (`app/models/`)
- Accès aux données
- Opérations CRUD
- Abstraction de la base de données
4. **ML Layer** (`app/ml/`)
- Services de machine learning
- Analyse de sentiment
- Calcul de prédictions
5. **Scraper Layer** (`app/scrapers/`)
- Collecte de données externes
- Scraping Twitter/Reddit/RSS
- Normalisation des données
**Exemple de flux:**
```
Request: GET /api/matches/1
API Layer (matches.py)
↓ Validate request
↓ Call service
Service Layer (match_service.py)
↓ Get match from repository
↓ Calculate predictions (ML service)
↓ Calculate energy (sentiment service)
↓ Aggregate data
Repository Layer (match.py)
↓ Query database
↓ Return model
API Layer
↓ Serialize with Pydantic
↓ Return response
```
#### 2. Dependency Injection
**FastAPI Depends:**
- Injection de dépendances automatique
- Test facile avec mocks
- Gestion des cycles de vie
**Exemple:**
```python
# main.py
app = FastAPI()
# Dependency: Database session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# Dependency: Service
def get_match_service(db: Session = Depends(get_db)):
return MatchService(db)
# Usage in endpoint
@app.get("/matches/{match_id}")
async def get_match(
match_id: int,
service: MatchService = Depends(get_match_service)
):
return service.get_match(match_id)
```
#### 3. Pydantic Validation
**Schémas de validation:**
```python
# schemas/match.py
from pydantic import BaseModel
class MatchCreate(BaseModel):
home_team: str
away_team: str
scheduled_date: datetime
league: str
class MatchResponse(BaseModel):
id: int
home_team: str
away_team: str
scheduled_date: datetime
predictions: List[PredictionResponse]
class Config:
orm_mode = True
```
**Utilisation:**
```python
@app.post("/matches", response_model=MatchResponse)
async def create_match(
match_data: MatchCreate,
db: Session = Depends(get_db)
):
# Validation automatique par Pydantic
match = Match(**match_data.dict())
db.add(match)
db.commit()
return match
```
#### 4. Async/Await
**Opérations asynchrones:**
```python
# scrapers/twitter_scraper.py
async def scrape_tweets(match_id: int):
# Opération async (non-bloquante)
tweets = await twitter_client.search_tweets(...)
return tweets
# main.py
@app.post("/scrape/{match_id}")
async def scrape_match(match_id: int):
tweets = await scrape_tweets(match_id)
return {"count": len(tweets)}
```
#### 5. Background Tasks & Workers
**Background Tasks (FastAPI):**
```python
from fastapi import BackgroundTasks
@app.post("/predict/{match_id}")
async def predict_match(
match_id: int,
background_tasks: BackgroundTasks
):
# Task en arrière-plan
background_tasks.add_task(
calculate_prediction,
match_id
)
return {"message": "Prediction started"}
```
**RabbitMQ Workers (Indépendants):**
```python
# workers/scraping_worker.py
def consume_scraping_tasks():
connection = pika.BlockingConnection(...)
channel = connection.channel()
channel.queue_declare(queue='scraping')
for method_frame, properties, body in channel.consume('scraping'):
task = json.loads(body)
scrape_match(task['match_id'])
channel.basic_ack(delivery_tag=method_frame.delivery_tag)
```
---
## Architecture Intégrée (Frontend + Backend)
### Communication Pattern
**REST API Communication:**
```
Frontend Component
↓ React Query (Client)
↓ HTTP Fetch
Backend API Endpoint
↓ Pydantic Validation
↓ Service Layer
↓ Repository Layer
↓ Database (SQLAlchemy)
```
**Example Flow:**
```typescript
// Frontend: src/services/matches.ts
export function useMatches() {
return useQuery({
queryKey: ['matches'],
queryFn: () => fetch('/api/matches').then(r => r.json()),
});
}
```
```python
# Backend: app/api/matches.py
@app.get("/matches", response_model=List[MatchResponse])
async def get_matches(service: MatchService = Depends(get_match_service)):
return service.get_all_matches()
```
```python
# Backend: app/services/match_service.py
class MatchService:
def get_all_matches(self):
matches = self.db.query(Match).all()
# Add predictions, energy calculations
return matches
```
---
## Architecture Asynchrone (RabbitMQ)
### Pattern Producer-Consumer
**Queue Architecture:**
```
Frontend Request
Backend API (Producer)
↓ Publish to Queue
RabbitMQ
↓ Message
Worker (Consumer)
↓ Process Task
↓ Update Database
Database Update
Frontend Polling/Websocket
```
**Example Tasks:**
1. **Scraping Task:**
- Producer: API endpoint when user requests scrape
- Consumer: Scraping worker
- Task: Scrape Twitter/Reddit for match
2. **Analysis Task:**
- Producer: Scraping worker after data collected
- Consumer: Sentiment analysis worker
- Task: Analyze sentiment of collected tweets/posts
3. **Prediction Task:**
- Producer: Analysis worker after sentiment calculated
- Consumer: Prediction worker
- Task: Calculate prediction based on energy
---
## Architecture de Base de Données
### Phase 1: SQLite
**Schema:**
- Frontend: `chartbastan.db` (Drizzle ORM)
- Backend: Même database (SQLAlchemy)
**Tables:**
- users (authentification)
- matches (données de matchs)
- predictions (prédictions utilisateurs)
- tweets (données Twitter)
- posts (données Reddit)
- energy_scores (énergie collective)
### Phase 2: PostgreSQL
**Avantages:**
- Meilleure performance pour grandes quantités de données
- Concurrency supérieure
- Support avancé des requêtes
- Scalabilité horizontale
**Migration:**
- Même schema SQLite → PostgreSQL
- Alembic pour migrations
- Drizzle pour frontend
---
## Patterns de Sécurité
### Frontend Security
**better-auth:**
- JWT tokens
- Session management
- Password hashing (bcryptjs)
- CSRF protection
**Next.js Security:**
- Middleware pour auth
- Protected routes
- Secure cookies (httpOnly)
### Backend Security
**FastAPI Security:**
- JWT authentication
- Pydantic validation
- CORS configuration
- SQL injection prevention (SQLAlchemy)
**Example:**
```python
# middleware/auth.py
from fastapi import Security, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Security(security)
):
token = credentials.credentials
user = verify_token(token)
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
return user
@app.get("/protected")
async def protected_route(user = Depends(get_current_user)):
return {"user": user}
```
---
## Patterns de Performance
### Frontend Performance
**Code Splitting:**
- Automatic code splitting (Next.js)
- Dynamic imports for heavy components
- Route-based splitting
```typescript
// Dynamic import
const MatchDetail = dynamic(() => import('@/components/MatchDetail'), {
loading: () => <Loading />,
ssr: false,
});
```
**Optimistic Updates:**
```typescript
const mutation = useMutation({
mutationFn: predictMatch,
onMutate: async (newPrediction) => {
// Cancel pending queries
await queryClient.cancelQueries(['predictions']);
// Optimistic update
queryClient.setQueryData(['predictions'], (old) => [...old, newPrediction]);
},
onError: (err, newPrediction, context) => {
// Rollback on error
queryClient.setQueryData(['predictions'], context.previousPredictions);
},
});
```
**Streaming & Suspense:**
```typescript
export default async function Page() {
return (
<Suspense fallback={<Loading />}>
<MatchList />
</Suspense>
);
}
```
### Backend Performance
**Async Operations:**
```python
# Multiple async operations
tweets = await scrape_twitter(match_id)
posts = await scrape_reddit(match_id)
rss = await scrape_rss(match_id)
# Process in parallel
tweets, posts, rss = await asyncio.gather(
scrape_twitter(match_id),
scrape_reddit(match_id),
scrape_rss(match_id)
)
```
**Connection Pooling:**
```python
# SQLAlchemy
engine = create_engine(
DATABASE_URL,
pool_size=10,
max_overflow=20,
pool_pre_ping=True
)
```
**Caching:**
```python
from functools import lru_cache
@lru_cache(maxsize=128)
def get_prediction_model():
# Expensive operation, cached
return load_model()
```
---
## Résumé de l'Architecture
**Frontend (Next.js):**
- App Router (Server + Client Components)
- State: Zustand + React Query
- Data Fetching: SSR + Client-side
- UI: Tailwind + shadcn/ui
**Backend (FastAPI):**
- REST API Layered
- Service-oriented
- Async/await
- RabbitMQ workers
**Integration:**
- REST API communication
- Shared database (SQLite)
- Async processing with queues
**Architecture appropriée pour:**
- Application web moderne
- Real-time data
- Scaling horizontal
- Maintenance facile

483
docs/development-guide.md Normal file
View File

@@ -0,0 +1,483 @@
# Guide de Développement - ChartBastan
## Prérequis
### Outils Requis
**Frontend:**
- Node.js 20+ [Télécharger](https://nodejs.org/)
- npm (inclus avec Node.js)
**Backend:**
- Python 3.11+ [Télécharger](https://www.python.org/)
- pip (inclus avec Python)
**Optionnels:**
- RabbitMQ [Télécharger](https://www.rabbitmq.com/) - Pour workers asynchrones
- Git - Pour le versioning
### Vérification des Prérequis
```bash
# Vérifier Node.js
node --version # Doit être 20+
# Vérifier npm
npm --version
# Vérifier Python
python --version # Doit être 3.11+
# Vérifier pip
pip --version
```
---
## Installation et Configuration
### 1. Cloner le Repository
```bash
git clone <repository-url>
cd chartbastan
```
### 2. Installer les Dépendances du Backend
```bash
cd backend
# Optionnel: Créer un environnement virtuel
python -m venv venv
# Activer l'environnement (Windows)
.\venv\Scripts\activate
# Activer l'environnement (Linux/Mac)
source venv/bin/activate
# Installer les dépendances
pip install -r requirements.txt
```
### 3. Installer les Dépendances du Frontend
```bash
cd ../chartbastan
# Installer les dépendances
npm install
```
### 4. Configurer les Variables d'Environnement
**Backend (.env):**
```bash
cd ../backend
# Créer le fichier .env
touch .env
```
Contenu du fichier `.env`:
```bash
# Base de données
DATABASE_URL=sqlite:///./chartbastan.db
# Twitter API (optionnel, pour le scraping)
TWITTER_BEARER_TOKEN=your_bearer_token_here
# Reddit API (optionnel, pour le scraping)
REDDIT_CLIENT_ID=your_client_id
REDDIT_CLIENT_SECRET=your_client_secret
# RabbitMQ (optionnel, pour workers)
RABBITMQ_URL=amqp://guest:guest@localhost:5672
```
**Frontend (.env.local):**
```bash
cd ../chartbastan
# Créer le fichier .env.local
touch .env.local
```
Contenu du fichier `.env.local`:
```bash
# URL de l'API backend
NEXT_PUBLIC_API_URL=http://localhost:8000
```
---
## Démarrage de l'Application
### Démarrer le Backend
```bash
cd backend
# Optionnel: Activer l'environnement virtuel
.\venv\Scripts\activate # Windows
# ou
source venv/bin/activate # Linux/Mac
# Démarrer le serveur FastAPI
python -m uvicorn app.main:app --reload --port 8000
```
Le serveur FastAPI démarre sur:
- **API:** http://localhost:8000
- **Documentation Swagger:** http://localhost:8000/docs
- **Documentation ReDoc:** http://localhost:8000/redoc
**Alternative: Scripts de démarrage**
```bash
# Windows
.\run_server.bat
# Linux/Mac
chmod +x run_server.sh
./run_server.sh
```
### Démarrer le Frontend
```bash
cd chartbastan
# Démarrer le serveur de développement
npm run dev
```
Le serveur Next.js démarre sur:
- **Application:** http://localhost:3000
### Vérifier que Tout Fonctionne
1. Ouvrir http://localhost:3000
2. Vous devriez voir la page d'accueil de ChartBastan
3. Tester les fonctionnalités (login, matchs, prédictions)
---
## Tests Locaux
### Tests Frontend
```bash
cd chartbastan
# Linter
npm run lint
# Type checking
npm run type-check
# Tests unitaires
npm run test
# Build de production
npm run build
```
### Tests Backend
```bash
cd backend
# Linter
flake8 .
# Formatage
black .
# Tests unitaires
pytest tests/ -v
```
---
## Commandes de Développement
### Frontend (chartbastan/)
| Commande | Description |
|----------|-------------|
| `npm run dev` | Démarrer le serveur de développement (port 3000) |
| `npm run build` | Build de production |
| `npm run start` | Démarrer le serveur de production |
| `npm run lint` | Exécuter ESLint |
| `npm run type-check` | Vérifier les types TypeScript |
| `npm run test` | Exécuter les tests Vitest |
### Backend (backend/)
| Commande | Description |
|----------|-------------|
| `python -m uvicorn app.main:app --reload --port 8000` | Démarrer le serveur FastAPI |
| `flake8 .` | Linting du code Python |
| `black .` | Formatage du code Python |
| `pytest tests/` | Exécuter les tests unitaires |
| `alembic upgrade head` | Appliquer toutes les migrations |
---
## Tâches de Développement Courantes
### 1. Ajouter une Nouvelle Page (Frontend)
```bash
cd chartbastan/src/app
mkdir nouvelle-page
```
Créer `nouvelle-page/page.tsx`:
```typescript
export default function NouvellePage() {
return <div>Contenu de la nouvelle page</div>;
}
```
Accéder à: http://localhost:3000/nouvelle-page
### 2. Ajouter un Nouvel Endpoint API (Backend)
Créer `backend/app/api/new_endpoint.py`:
```python
from fastapi import APIRouter
router = APIRouter()
@router.get("/new-endpoint")
async def get_new_endpoint():
return {"message": "Hello from new endpoint"}
```
Enregistrer dans `backend/app/main.py`:
```python
from app.api import new_endpoint
app.include_router(new_endpoint.router, prefix="/api", tags=["new"])
```
Accéder à: http://localhost:8000/api/new-endpoint
### 3. Ajouter un Nouveau Composant (Frontend)
Créer `chartbastan/src/components/NewComponent.tsx`:
```typescript
export function NewComponent() {
return <div>Nouveau composant</div>;
}
```
Utiliser dans une page:
```typescript
import { NewComponent } from '@/components/NewComponent';
export default function Page() {
return <NewComponent />;
}
```
---
## Dépannage
### Backend Ne Démarre Pas
**Problème:** Port 8000 déjà utilisé
```bash
# Windows
netstat -ano | findstr :8000
taskkill /PID <PID> /F
# Linux/Mac
lsof -ti:8000 | xargs kill -9
```
**Problème:** Dépendances manquantes
```bash
cd backend
pip install -r requirements.txt --upgrade
```
### Frontend Ne Démarre Pas
**Problème:** Port 3000 déjà utilisé
```bash
# Windows
netstat -ano | findstr :3000
taskkill /PID <PID> /F
# Linux/Mac
lsof -ti:3000 | xargs kill -9
```
**Problème:** Dépendances manquantes
```bash
cd chartbastan
rm -rf node_modules
npm install
```
### Erreur de Connexion Frontend-Backend
**Vérifier:**
1. Backend en cours d'exécution sur http://localhost:8000
2. Frontend `.env.local` contient `NEXT_PUBLIC_API_URL=http://localhost:8000`
3. CORS activé sur le backend (voir `backend/app/middleware/cors.py`)
### Erreur de Base de Données
**Problème:** Base de données non initialisée
```bash
cd backend
# Appliquer les migrations
alembic upgrade head
# Optionnel: Générer des données de test
python scripts/generate_historical_matches.py
```
### Erreur de Scraping
**Problème:** Clés API manquantes
```bash
cd backend
# Vérifier le fichier .env
cat .env
# Ajouter les clés API Twitter/Reddit/RSS
```
---
## Outils de Développement
### IDE Recommandé
**Cursor / VS Code:**
- Extensions recommandées:
- ESLint
- Prettier
- Tailwind CSS IntelliSense
- Prisma (pour Drizzle)
- Python
- REST Client
### Débogage
**Frontend:**
- DevTools Chrome/Edge
- React DevTools extension
- Logger dans la console
**Backend:**
- Logs dans le terminal
- Documentation Swagger: http://localhost:8000/docs
- Debugger Python dans VS Code
### Surveillance
**Backend:**
- Vérifier les logs dans le terminal
- Monitor RabbitMQ (si utilisé): http://localhost:15672
**Frontend:**
- Network tab DevTools pour appels API
- React DevTools pour state
---
## Best Practices
### Code Style
**Frontend (TypeScript/React):**
- Utiliser `snake_case` pour les variables backend, `camelCase` pour frontend
- Typage strict avec TypeScript
- Composants réutilisables
- Separation of concerns (UI, logic, data)
**Backend (Python):**
- Style PEP 8 avec Black
- Type hints pour toutes les fonctions
- Docstrings pour les fonctions complexes
- Séparation des couches (API, service, repository)
### Git Workflow
```
main (production)
develop (staging)
feature/ma-fonctionnalité (branche de développement)
```
1. Créer une branche `feature/ma-fonctionnalité`
2. Développer la fonctionnalité
3. Commit les changements avec des messages clairs
4. Push vers la branche
5. Créer une Pull Request vers `develop`
6. Review et merge
### Commit Messages
```
feat: ajouter la fonctionnalité X
fix: corriger le bug Y
docs: mettre à jour la documentation
refactor: refactoriser le code Z
test: ajouter des tests pour X
```
---
## Ressources
### Documentation
- **Frontend:** `chartbastan/README.md`
- **Backend:** `_bmad-output/planning-artifacts/architecture.md`
- **Implémentation:** `_bmad-output/implementation-artifacts/`
- **API:** http://localhost:8000/docs (Swagger)
### Liens Utiles
- Next.js Docs: https://nextjs.org/docs
- FastAPI Docs: https://fastapi.tiangolo.com/
- React Docs: https://react.dev/
- Tailwind CSS: https://tailwindcss.com/docs
- Drizzle ORM: https://orm.drizzle.team/
- SQLAlchemy: https://docs.sqlalchemy.org/
---
## Support
Pour les problèmes ou questions:
- Consulter les artefacts d'implémentation dans `_bmad-output/implementation-artifacts/`
- Vérifier la documentation Swagger: http://localhost:8000/docs
- Consulter le README principal: `chartbastan/README.md`

View File

@@ -0,0 +1,212 @@
# Inventaire de la Documentation Existante
## Documentation Principale
### 1. README Principal
- **Chemin:** `chartbastan/README.md`
- **Type:** README
- **Description:** Documentation principale du projet avec installation, technologies et structure
- **Partie:** Frontend (mais couvre tout le projet)
**Contenu:**
- Vue d'ensemble du projet
- Fonctionnalités clés
- Technologies (Frontend + Backend)
- Instructions d'installation
- Scripts disponibles
- Structure du projet
- Processus de contribution
---
## Documentation de Planification
### 2. Product Requirements Document (PRD)
- **Chemin:** `_bmad-output/planning-artifacts/prd.md`
- **Type:** PRD
- **Description:** Document complet des exigences produit
- **Partie:** Toutes
**Contenu typique:**
- Objectifs du produit
- Fonctionnalités détaillées
- User stories
- Critères d'acceptation
- Priorités et roadmap
---
### 3. Architecture
- **Chemin:** `_bmad-output/planning-artifacts/architecture.md`
- **Type:** Architecture
- **Description:** Documentation architecturale détaillée
- **Partie:** Toutes
**Contenu:**
- Architecture globale
- Design patterns
- Choix technologiques
- Flux de données
- Diagrammes et spécifications
---
### 4. Epics
- **Chemin:** `_bmad-output/planning-artifacts/epics.md`
- **Type:** Epics
- **Description:** Liste complète des epics
- **Partie:** Toutes
**Contenu:**
- 9 epics complétés
- Chronologie de développement
- Relations entre epics
- Statuts de complétion
---
### 5. UX Design Directions
- **Chemin:** `_bmad-output/planning-artifacts/ux-design-directions.html`
- **Type:** UX Design
- **Description:** Directions de design UX
- **Partie:** Frontend
**Contenu:**
- Principes de design
- Guidelines UX
- Inspiration et références
---
### 6. UX Design Specification
- **Chemin:** `_bmad-output/planning-artifacts/ux-design-specification.md`
- **Type:** UX Design
- **Description:** Spécifications détaillées de l'interface utilisateur
- **Partie:** Frontend
**Contenu:**
- Spécifications des composants
- Layouts et patterns
- Accessibilité
- Responsive design
---
## Documentation d'Implémentation
### 7. Artefacts d'Implémentation
- **Chemin:** `_bmad-output/implementation-artifacts/`
- **Type:** Implémentation
- **Description:** 38 fichiers de documentation d'implémentation
- **Partie:** Toutes
**Contenu (38 fichiers):**
- Documentation détaillée de chaque epic
- Guides d'implémentation
- Spécifications techniques
- Exemples de code
**Exemples de fichiers:**
- `1-1-créer-l-authentification-des-utilisateurs.md`
- `2-1-créer-la-collecte-de-données-twitter.md`
- `9-1-créer-l-api-publique-avec-documentation-openapi.md`
---
## Documentation Technique Spécifique
### 8. Twitter Scraper Documentation
- **Chemin:** `backend/app/scrapers/README.md`
- **Type:** Documentation technique
- **Description:** Documentation détaillée du module de scraping Twitter
- **Partie:** Backend
**Contenu:**
- Fonctionnalités
- Installation et configuration
- Exemples d'utilisation
- Architecture (rate limiting, mode dégradé)
- Tests
- Intégration
- Dépannage
---
## Documentation BMad (Configuration)
### 9. BMad Configuration
- **Chemin:** `_bmad/` (dossier complet)
- **Type:** Configuration workflow
- **Description:** Configuration des agents et workflows BMad
- **Partie:** N/A (outil de développement)
**Contenu:**
- Configuration des agents
- Workflows automatisés
- Templates et protocoles
---
## Récapitulatif
**Total de fichiers de documentation:** 50+ fichiers
**Catégories:**
- 📋 **Documentation principale:** 1 fichier (README)
- 📊 **Documentation de planification:** 5 fichiers (PRD, Architecture, Epics, UX)
- 🛠️ **Documentation d'implémentation:** 38 fichiers (artefacts)
- 🔧 **Documentation technique:** 1 fichier (Twitter Scraper)
- ⚙️ **Configuration BMad:** Plusieurs fichiers (agents, workflows)
---
## Statut de la Documentation
**Complétude:****Excellente**
Le projet dispose d'une documentation très complète couvrant:
- ✅ Installation et setup
- ✅ Architecture technique
- ✅ Spécifications fonctionnelles (PRD)
- ✅ Implémentation détaillée (38 artefacts)
- ✅ Design UX
- ✅ Documentation technique spécifique
**Qualité:** La documentation est structurée, détaillée et prête à être utilisée pour le développement et le testing.
---
## Recommandations
### Pour le Testing (Phase Actuelle)
1. **Commencer par le README principal**
- `chartbastan/README.md`
- Instructions d'installation claires
- Scripts de démarrage
2. **Référence pour les fonctionnalités**
- `_bmad-output/implementation-artifacts/` - 38 artefacts détaillés
- Chaque fonctionnalité est documentée avec exemples
3. **Architecture pour comprendre le système**
- `_bmad-output/planning-artifacts/architecture.md`
- Vue d'ensemble et choix techniques
4. **Documentation spécifique pour debugging**
- `backend/app/scrapers/README.md` - Exemple de doc technique
- Peut servir de modèle pour d'autres modules
---
## Notes
- Tous les epics sont complétés (9/9)
- L'implémentation est terminée
- Le projet est en phase de testing
- La documentation est à jour et complète
**Prochaine étape:** Utiliser cette documentation pour:
1. Démarrer l'application
2. Tester les fonctionnalités
3. Valider le comportement attendu

361
docs/index.md Normal file
View File

@@ -0,0 +1,361 @@
# Documentation ChartBastan
🎯 **Plateforme de prédiction sportive basée sur l'analyse de l'énergie collective des réseaux sociaux**
---
## 📊 Vue d'ensemble
**Type de référentiel:** Multi-part (Frontend + Backend séparés)
**Parties du projet:**
- **Partie 1:** Frontend Next.js (chartbastan/)
- **Partie 2:** Backend FastAPI (backend/)
**Langage principal:**
- Frontend: TypeScript (Next.js 16.1.3)
- Backend: Python (FastAPI 0.128.0)
**Architecture:** Client-serveur avec REST API
---
## 🚀 Démarrage Rapide
### Pour Tester l'Application
👉 **[README de Test Rapide](./README-TEST.md)** - Guide en 3 étapes pour démarrer l'application
**Démarrage rapide:**
```bash
# Terminal 1 - Backend
cd backend
pip install -r requirements.txt
python -m uvicorn app.main:app --reload --port 8000
# Terminal 2 - Frontend
cd chartbastan
npm install
npm run dev
```
Accéder à: http://localhost:3000
---
## 📚 Documentation Générée
### Documentation Principale
- 📖 **[Structure du Projet](./project-structure.md)** - Vue d'ensemble de l'architecture
- 🔧 **[Métadonnées des Parties](./project-parts-metadata.md)** - Détails techniques de chaque partie
- 💻 **[Stack Technologique](./technology-stack.md)** - Technologies utilisées
- 🏗️ **[Patterns d'Architecture](./architecture-patterns.md)** - Patterns de conception
- 🌳 **[Analyse de l'Arbre Source](./source-tree-analysis.md)** - Structure détaillée des fichiers
- 🛠️ **[Guide de Développement](./development-guide.md)** - Guide complet de développement
- 🧪 **[README de Test Rapide](./README-TEST.md)** - Guide de testing
### Documentation Existante
- 📋 **[Inventaire de Documentation Existante](./existing-documentation-inventory.md)** - 50+ fichiers trouvés
- 👤 **[Contexte Utilisateur](./user-provided-context.md)** - Objectifs et priorités
---
## 🎯 Parties du Projet
### Part 1: Frontend (chartbastan/)
**Type:** Web Application (Next.js 16.1.3)
**Technologie principale:**
- Framework: Next.js 16.1.3 + TypeScript 5
- UI: Tailwind CSS v4 + shadcn/ui
- State: Zustand 5.0.10 + React Query 5.90.18
- Database: Drizzle ORM 0.44.7 + SQLite
- Visualization: D3.js 7.9.0 + Recharts 3.6.0
**Points d'entrée:**
- Page d'accueil: `src/app/page.tsx`
- Layout racine: `src/app/layout.tsx`
- Configuration: `package.json`, `tsconfig.json`
**Port:** 3000
**Documentation spécifique:**
- 📄 [README Frontend](../chartbastan/README.md)
---
### Part 2: Backend (backend/)
**Type:** API REST (FastAPI 0.128.0)
**Technologie principale:**
- Framework: FastAPI 0.128.0 + Python 3.11+
- ORM: SQLAlchemy 2.0.45 + Alembic 1.13.0
- Scraping: tweepy 4.14.0 + praw 7.8.1 + feedparser 6.0.11
- ML: vaderSentiment 3.3.2 + textblob 0.17.1
- Queue: pika 1.3.2 (RabbitMQ)
**Points d'entrée:**
- Application: `app/main.py`
- API Endpoints: `app/api/`
- Configuration: `requirements.txt`, `alembic.ini`
**Port:** 8000
**API Documentation:**
- Swagger: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
---
## 🔗 Intégration entre Parties
**Communication:** REST API (HTTP/HTTPS)
**Format de données:** JSON
**Base URL:** `http://localhost:8000` (développement)
**Points d'intégration:**
1. **Authentification** - better-auth (frontend) ↔ JWT (backend)
2. **Données de Matchs** - `src/services/matches.ts``app/api/matches.py`
3. **Prédictions** - `src/services/predictions.ts``app/api/predictions.py`
4. **Notifications** - Workers RabbitMQ ↔ Web Push
---
## 📂 Structure du Projet
```
chartbastan/
├── chartbastan/ # Frontend Next.js
│ ├── src/
│ │ ├── app/ # App Router (pages, layouts)
│ │ ├── components/ # Composants React (72+)
│ │ ├── services/ # Services API (27)
│ │ ├── stores/ # Zustand stores (2)
│ │ ├── hooks/ # React Hooks (9)
│ │ └── lib/ # Utilitaires (7)
│ └── package.json
├── backend/ # Backend FastAPI
│ ├── app/
│ │ ├── api/ # Endpoints REST
│ │ ├── models/ # Modèles SQLAlchemy (12)
│ │ ├── schemas/ # Schémas Pydantic (14)
│ │ ├── services/ # Services métier (8)
│ │ ├── scrapers/ # Scrapers (Twitter, Reddit, RSS)
│ │ ├── ml/ # Services ML (sentiment, prédictions)
│ │ ├── workers/ # Workers asynchrones (4)
│ │ └── main.py # Application FastAPI
│ ├── alembic/ # Migrations
│ └── requirements.txt
├── _bmad-output/ # Documentation de planification
│ ├── planning-artifacts/ # PRD, Architecture, Epics
│ └── implementation-artifacts/ # 38 fichiers d'implémentation
└── docs/ # Documentation (ce dossier)
```
---
## 📖 Documentation de Planification et Implémentation
### Artefacts de Planification
- 📋 **[PRD Complet](../_bmad-output/planning-artifacts/prd.md)** - Product Requirements Document
- 🏗️ **[Architecture](../_bmad-output/planning-artifacts/architecture.md)** - Documentation architecturale
- 📝 **[Epics](../_bmad-output/planning-artifacts/epics.md)** - 9 épics complétés
- 🎨 **[UX Design Directions](../_bmad-output/planning-artifacts/ux-design-directions.html)**
- 🎨 **[UX Design Specification](../_bmad-output/planning-artifacts/ux-design-specification.md)**
### Artefacts d'Implémentation
🛠️ **[Dossier d'Artefacts](../_bmad-output/implementation-artifacts/)** - 38 fichiers de documentation d'implémentation détaillée
**Épics complétés:**
1. Authentification des utilisateurs
2. Collecte de données (Twitter, Reddit, RSS)
3. Analyse de sentiment et énergie collective
4. Système de prédictions ML
5. Dashboard principal en temps réel
6. Système de paris et prédictions utilisateurs
7. Gamification (badges, classements, parrainage)
8. Notifications push et alertes
9. API publique et calendrier énergétique
---
## 🚀 Getting Started
### 1. Pour Tester l'Application
👉 **[README de Test Rapide](./README-TEST.md)** - Guide en 3 étapes
### 2. Pour le Développement
👉 **[Guide de Développement](./development-guide.md)** - Guide complet de développement
**Étapes rapides:**
1. Installer les dépendances: `pip install -r requirements.txt` et `npm install`
2. Configurer les variables d'environnement (.env et .env.local)
3. Démarrer le backend: `python -m uvicorn app.main:app --reload --port 8000`
4. Démarrer le frontend: `npm run dev`
5. Ouvrir http://localhost:3000
### 3. Pour Comprendre l'Architecture
👉 **[Patterns d'Architecture](./architecture-patterns.md)** - Patterns de conception détaillés
👉 **[Stack Technologique](./technology-stack.md)** - Technologies utilisées
### 4. Pour Explorer le Code
👉 **[Analyse de l'Arbre Source](./source-tree-analysis.md)** - Structure détaillée des fichiers
👉 **[Structure du Projet](./project-structure.md)** - Vue d'organisation
---
## 🧪 Testing
### Fonctionnalités à Tester
Voir le **[README de Test Rapide](./README-TEST.md)** pour la checklist complète:
- ✅ Authentification (inscription, login, déconnexion)
- ✅ Dashboard principal (matchs, graphiques)
- ✅ Prédictions (faire une prédiction, voir l'énergie)
- ✅ Classement (Top 100, rang personnel)
- ✅ Badges et gamification
- ✅ Notifications
- ✅ Historique des prédictions
- ✅ Parrainage
- ✅ Comparaison énergie vs stats
- ✅ Calendrier énergétique
### Tests Automatisés
**Frontend:**
```bash
cd chartbastan
npm run test
```
**Backend:**
```bash
cd backend
pytest tests/ -v
```
---
## 🛠️ Scripts et Commandes
### Frontend (chartbastan/)
| Commande | Description |
|----------|-------------|
| `npm run dev` | Démarrer le serveur de développement (port 3000) |
| `npm run build` | Build de production |
| `npm run start` | Démarrer le serveur de production |
| `npm run lint` | Exécuter ESLint |
| `npm run type-check` | Vérifier les types TypeScript |
| `npm run test` | Exécuter les tests Vitest |
### Backend (backend/)
| Commande | Description |
|----------|-------------|
| `python -m uvicorn app.main:app --reload --port 8000` | Démarrer le serveur FastAPI |
| `flake8 .` | Linting du code Python |
| `black .` | Formatage du code Python |
| `pytest tests/` | Exécuter les tests unitaires |
| `alembic upgrade head` | Appliquer toutes les migrations |
---
## 📚 Ressources de Référence
### Documentation API
- **Swagger UI:** http://localhost:8000/docs
- **ReDoc:** http://localhost:8000/redoc
### Documentation Externe
- **Next.js:** https://nextjs.org/docs
- **FastAPI:** https://fastapi.tiangolo.com/
- **React:** https://react.dev/
- **Tailwind CSS:** https://tailwindcss.com/docs
- **Drizzle ORM:** https://orm.drizzle.team/
- **SQLAlchemy:** https://docs.sqlalchemy.org/
---
## 📊 Statut du Projet
**Phase:** Testing (tous les épics complétés)
- ✅ PRD complet
- ✅ Architecture implémentée
- ✅ 9 épics complétés
- ✅ Frontend et Backend prêts
- 🔄 Testing en cours
**Technologie:**
- Frontend: Next.js 16.1.3 + TypeScript 5
- Backend: FastAPI 0.128.0 + Python 3.11+
- Database: SQLite (Phase 1) → PostgreSQL (Phase 2+)
- API: REST + Swagger documentation
---
## 🐛 Dépannage
Pour les problèmes courants, consulter:
- **[Guide de Développement - Dépannage](./development-guide.md#dépannage)**
- **[README de Test Rapide - Dépannage](./README-TEST.md#-dépannage)**
**Problèmes fréquents:**
- Backend ne démarre pas → Vérifier le port 8000
- Frontend ne démarre pas → Nettoyer node_modules et réinstaller
- Erreur de connexion → Vérifier que backend tourne et .env.local est configuré
- Base de données vide → Exécuter `alembic upgrade head`
---
## 🤝 Contribution
Le projet est complet et en phase de testing. Pour contribuer:
1. Fork le repository
2. Créer une branche `feature/nouvelle-fonctionnalité`
3. Développer la fonctionnalité
4. Commit avec des messages clairs
5. Push et créer une Pull Request
---
## 📄 Licence
Ce projet est sous license MIT.
---
## 📞 Contact
Pour toute question:
- Consulter les artefacts d'implémentation: `_bmad-output/implementation-artifacts/`
- Vérifier la documentation API: http://localhost:8000/docs
- Consulter le README principal: `chartbastan/README.md`
---
**Date de création:** 2026-01-18
**Version:** 0.1.0
**Statut:** Testing (tous les épics complétés) ✅

View File

@@ -0,0 +1,236 @@
# Métadonnées des Parties du Projet
## Informations Générales
- **Nom du projet:** ChartBastan
- **Type de référentiel:** multi-part
- **Nombre de parties:** 2
- **Date de la documentation:** 2026-01-18
---
## Partie 1: Frontend
```json
{
"part_id": "frontend",
"display_name": "Frontend Next.js",
"root_path": "chartbastan/",
"project_type_id": "web",
"project_type": "Web Application",
"primary_language": "TypeScript",
"primary_framework": "Next.js 16.1.3",
"entry_point": "src/app/page.tsx",
"port": 3000,
"build_tool": "Next.js",
"styling": "Tailwind CSS v4 + shadcn/ui",
"state_management": "Zustand + React Query",
"database": "SQLite (Drizzle ORM)"
}
```
### Stack Technique
**Frontend:**
- Framework: Next.js 16.1.3
- Language: TypeScript 5
- UI Library: shadcn/ui (Radix UI primitives)
- Styling: Tailwind CSS v4
- State Management: Zustand 5.0.10
- Data Fetching: React Query 5.90.18
- Authentication: better-auth 1.4.14
- Database: Drizzle ORM 0.44.7 + better-sqlite3 12.6.2
- Visualization: D3.js 7.9.0, Recharts 3.6.0
- Animations: Framer Motion 12.26.2
- Web Push: web-push 3.6.7
### Structure des Répertoires Critiques
- `src/app/` - App Router (Next.js 16)
- `src/components/` - Composants React réutilisables
- `src/services/` - Services API et logique métier
- `src/hooks/` - React Hooks personnalisés
- `src/lib/` - Utilitaires et fonctions d'aide
- `src/stores/` - Zustand stores pour l'état global
- `src/db/` - Configuration Drizzle ORM
- `drizzle/` - Migrations de base de données
---
## Partie 2: Backend
```json
{
"part_id": "backend",
"display_name": "Backend FastAPI",
"root_path": "backend/",
"project_type_id": "backend",
"project_type": "API REST",
"primary_language": "Python",
"primary_framework": "FastAPI 0.128.0",
"entry_point": "app/main.py",
"port": 8000,
"api_documentation": "/docs",
"database": "SQLite (SQLAlchemy) → PostgreSQL",
"message_queue": "RabbitMQ"
}
```
### Stack Technique
**Backend:**
- Framework: FastAPI 0.128.0
- Server: Uvicorn 0.30.0
- Language: Python 3.11+
- ORM: SQLAlchemy 2.0.45
- Migrations: Alembic 1.13.0
- Validation: Pydantic 2.7.0
- Settings: Pydantic Settings 2.3.0
**Data Scraping:**
- Twitter: tweepy 4.14.0
- Reddit: praw 7.8.1
- RSS: feedparser 6.0.11
**Machine Learning:**
- Sentiment Analysis: vaderSentiment 3.3.2
- NLP: textblob 0.17.1
**Async Communication:**
- Message Queue: pika 1.3.2 (RabbitMQ)
- Redis: ioredis 5.9.2
**Development Tools:**
- Linting: flake8 7.1.0
- Formatting: black 24.8.0
- Testing: pytest 8.3.3
### Structure des Répertoires Critiques
- `app/api/` - Endpoints REST
- `app/models/` - Modèles SQLAlchemy
- `app/schemas/` - Schémas Pydantic
- `app/services/` - Services métier
- `app/ml/` - Services ML (sentiment, prédiction)
- `app/scrapers/` - Scrapers (Twitter, Reddit, RSS)
- `app/queues/` - Gestion RabbitMQ
- `app/workers/` - Workers asynchrones
- `app/middleware/` - Middleware (auth, CORS)
- `alembic/versions/` - Migrations de base de données
- `tests/` - Tests unitaires
---
## Intégration entre Parties
### Protocole de Communication
**Type:** REST API
**Protocole:** HTTP/HTTPS
**Format de données:** JSON
### Points d'Intégration
1. **Frontend Service → Backend API**
- Services dans `src/services/` appellent les endpoints de l'API FastAPI
- Base URL: `http://localhost:8000` (dev)
2. **Authentification**
- Backend: JWT tokens via better-auth
- Frontend: Gestion des tokens dans Zustand store
3. **Synchronisation des Données**
- Real-time: Websockets (si implémenté)
- Polling: React Query pour les mises à jour périodiques
4. **Notifications**
- Backend: Workers RabbitMQ → Web Push
- Frontend: Service Worker pour notifications push
---
## Dépendances Externes
### Frontend
- Twitter API (si direct access)
- Reddit API (si direct access)
### Backend
- Twitter API (via tweepy)
- Reddit API (via praw)
- RabbitMQ (message broker)
- Redis (cache, si utilisé)
---
## Configuration de Développement
### Environnement Requis
**Frontend:**
- Node.js 20+
- npm ou yarn
**Backend:**
- Python 3.11+
- pip
**Services Optionnels:**
- RabbitMQ (pour workers asynchrones)
- Redis (pour cache, si utilisé)
### Variables d'Environnement
**Frontend (.env.local):**
- `NEXT_PUBLIC_API_URL=http://localhost:8000`
**Backend (.env):**
- `DATABASE_URL=sqlite:///./chartbastan.db`
- `TWITTER_API_KEY=...`
- `TWITTER_API_SECRET=...`
- `TWITTER_ACCESS_TOKEN=...`
- `TWITTER_ACCESS_SECRET=...`
- `REDDIT_CLIENT_ID=...`
- `REDDIT_CLIENT_SECRET=...`
- `RABBITMQ_URL=amqp://guest:guest@localhost:5672`
---
## Statut du Projet
**Phase de développement:** Testing
- ✅ Tous les epics complétés
- ✅ Architecture implémentée
- ✅ Frontend et Backend prêts
- 🔄 Testing en cours
**Prochaine étape:** Validation des fonctionnalités et correction des bugs
---
## Points d'Intérêt pour le Développement
1. **Points d'entrée API Backend:**
- `app/api/matches.py` - Endpoints de matchs
- `app/api/predictions.py` - Endpoints de prédictions
- `app/api/users.py` - Endpoints utilisateurs
2. **Services Frontend:**
- `src/services/matches.ts` - Service de matchs
- `src/services/predictions.ts` - Service de prédictions
- `src/services/auth.ts` - Service d'authentification
3. **Composants UI Clés:**
- `src/components/dashboard/` - Dashboard principal
- `src/components/predictions/` - Composants de prédictions
- `src/components/matches/` - Composants de matchs
4. **Machine Learning:**
- `backend/app/ml/sentiment_analyzer.py` - Analyse de sentiment
- `backend/app/ml/prediction_calculator.py` - Calcul de prédictions
5. **Scraping de Données:**
- `backend/app/scrapers/twitter_scraper.py` - Scraper Twitter
- `backend/app/scrapers/reddit_scraper.py` - Scraper Reddit
- `backend/app/scrapers/rss_scraper.py` - Scraper RSS

View File

@@ -0,0 +1,100 @@
{
"workflow_version": "1.2.0",
"timestamps": {
"started": "2026-01-18T20:00:00Z",
"last_updated": "2026-01-18T20:20:00Z"
},
"mode": "initial_scan",
"scan_level": "quick",
"project_root": "d:\\dev_new_pc\\chartbastan",
"output_folder": "d:\\dev_new_pc\\chartbastan\\docs",
"completed_steps": [
{
"step": "step_1",
"status": "completed",
"timestamp": "2026-01-18T20:05:00Z",
"summary": "Classified as multi-part with 2 parts: frontend (web/Next.js) and backend (backend/FastAPI)"
},
{
"step": "step_2",
"status": "completed",
"timestamp": "2026-01-18T20:10:00Z",
"summary": "Found 50+ existing documentation files including README, PRD, architecture, and 38 implementation artifacts"
},
{
"step": "step_3",
"status": "completed",
"timestamp": "2026-01-18T20:15:00Z",
"summary": "Tech stack: Next.js 16.1.3 + FastAPI 0.128.0"
},
{
"step": "step_4",
"status": "completed",
"timestamp": "2026-01-18T20:16:00Z",
"summary": "Conditional analysis complete, pattern matching done without reading source files"
},
{
"step": "step_5",
"status": "completed",
"timestamp": "2026-01-18T20:17:00Z",
"summary": "Source tree documented with folder_count: 10+ critical folders"
},
{
"step": "step_6",
"status": "completed",
"timestamp": "2026-01-18T20:18:00Z",
"summary": "Dev/deployment guides written: development-guide.md, README-TEST.md"
},
{
"step": "step_9",
"status": "completed",
"timestamp": "2026-01-18T20:19:00Z",
"summary": "All supporting docs written"
},
{
"step": "step_10",
"status": "completed",
"timestamp": "2026-01-18T20:20:00Z",
"summary": "Master index generated: index.md"
}
],
"current_step": "step_11",
"findings": {
"project_classification": {
"repository_type": "multi-part",
"parts_count": 2,
"primary_tech": "Next.js 16.1.3 + FastAPI 0.128.0"
},
"existing_docs_count": 50,
"technology_stack": {
"frontend": "Next.js 16.1.3 + TypeScript 5",
"backend": "FastAPI 0.128.0 + Python 3.11+"
}
},
"project_types": [
{
"part_id": "frontend",
"project_type_id": "web",
"display_name": "Frontend Next.js"
},
{
"part_id": "backend",
"project_type_id": "backend",
"display_name": "Backend FastAPI"
}
],
"outputs_generated": [
"project-scan-report.json",
"project-structure.md",
"project-parts-metadata.md",
"existing-documentation-inventory.md",
"user-provided-context.md",
"technology-stack.md",
"architecture-patterns.md",
"source-tree-analysis.md",
"development-guide.md",
"README-TEST.md",
"index.md"
],
"resume_instructions": "Completing final steps"
}

172
docs/project-structure.md Normal file
View File

@@ -0,0 +1,172 @@
# Structure du Projet ChartBastan
## Vue d'ensemble
**Type de référentiel:** Multi-part (Frontend + Backend séparés)
Le projet ChartBastan est divisé en deux parties distinctes qui communiquent via des API REST:
- **Frontend:** Application Next.js avec TypeScript et React
- **Backend:** API FastAPI avec Python
---
## Architecture du Projet
```
chartbastan/
├── _bmad/ # Configuration BMad (workflow/agents)
├── _bmad-output/ # Artefacts de planification et implémentation
│ ├── analysis/ # Analyses et brainstorming
│ ├── implementation-artifacts/ # Documentation d'implémentation (38 fichiers)
│ └── planning-artifacts/ # PRD, Architecture, Epics, UX
├── backend/ # Backend FastAPI (Part: api)
│ ├── alembic/ # Migrations de base de données
│ ├── app/
│ │ ├── api/ # Endpoints REST (13 fichiers)
│ │ ├── lib/ # Bibliothèques partagées
│ │ ├── main.py # Point d'entrée FastAPI
│ │ ├── middleware/ # Middleware (auth, CORS)
│ │ ├── ml/ # Services ML (sentiment, prédiction)
│ │ ├── models/ # Modèles SQLAlchemy (12 modèles)
│ │ ├── queues/ # Gestion RabbitMQ
│ │ ├── schemas/ # Schémas Pydantic (14 fichiers)
│ │ ├── scrapers/ # Scrapers (Twitter, Reddit, RSS)
│ │ ├── services/ # Services métier (8 services)
│ │ └── workers/ # Workers async (4 workers)
│ ├── scripts/ # Scripts utilitaires
│ ├── tests/ # Tests unitaires (30 fichiers)
│ ├── workers/ # Scripts d'exécution des workers
│ ├── requirements.txt # Dépendances Python
│ └── alembic.ini # Configuration Alembic
├── chartbastan/ # Frontend Next.js (Part: frontend)
│ ├── public/ # Assets statiques
│ ├── src/
│ │ ├── app/ # App Router Next.js (22 fichiers)
│ │ ├── components/ # Composants React (72 composants)
│ │ ├── db/ # Drizzle ORM
│ │ ├── hooks/ # React Hooks (9 hooks)
│ │ ├── lib/ # Utilitaires et API client (7 fichiers)
│ │ ├── middleware/ # Middleware Next.js
│ │ ├── scripts/ # Scripts de migration
│ │ ├── services/ # Services API (27 services)
│ │ ├── stores/ # Zustand stores
│ │ └── tests/ # Tests (48 fichiers)
│ ├── drizzle/ # Migrations Drizzle
│ ├── package.json # Dépendances Node.js
│ ├── tsconfig.json # Configuration TypeScript
│ └── next.config.ts # Configuration Next.js
└── docs/ # Documentation du projet
```
---
## Parties du Projet
### Part 1: Frontend (chartbastan/)
**Type:** web
**Technologie:** Next.js 16.1.3 + TypeScript
**Rôle:** Interface utilisateur et visualisation des données
**Fonctionnalités principales:**
- Dashboard en temps réel avec D3.js
- Visualisations de données et graphiques
- Gestion des utilisateurs et authentification
- Interface de paris et de prédictions
- Gamification (badges, classements)
- Notifications push
**Points d'entrée:**
- `src/app/page.tsx` - Page d'accueil
- `src/app/layout.tsx` - Layout principal
- `src/main.tsx` - Entrée React
---
### Part 2: Backend (backend/)
**Type:** backend
**Technologie:** FastAPI 0.128.0 + Python 3.11+
**Rôle:** API REST, ML, scraping de données
**Fonctionnalités principales:**
- API REST pour les données de matchs et prédictions
- Scraping de données (Twitter, Reddit, RSS)
- Analyse de sentiment (VADER, TextBlob)
- Calcul de l'énergie collective
- Machine Learning pour les prédictions
- File d'attente asynchrone (RabbitMQ)
- Authentification et gestion des utilisateurs
**Points d'entrée:**
- `app/main.py` - Application FastAPI
- `app/api/` - Endpoints REST
---
## Intégration entre Parties
Les deux parties communiquent via des appels API REST:
**Frontend → Backend:**
- Les services dans `src/services/` appellent les endpoints de l'API FastAPI
- API client dans `src/lib/` gère les requêtes HTTP
**Backend → Frontend:**
- API REST sur le port 8000
- Documentation Swagger: `http://localhost:8000/docs`
---
## Points d'Intégration
1. **Authentification:**
- Backend: `app/middleware/auth.py`
- Frontend: Services dans `src/services/auth.ts`
2. **Données de Matchs:**
- Backend: `app/models/match.py`, `app/api/matches.py`
- Frontend: `src/services/matches.ts`
3. **Prédictions:**
- Backend: `app/services/prediction.py`, `app/ml/`
- Frontend: `src/services/predictions.ts`
4. **Notifications:**
- Backend: Workers RabbitMQ dans `workers/`
- Frontend: Services web-push dans `src/services/`
---
## Artefacts de Planification
Le dossier `_bmad-output/` contient toute la documentation de planification:
- **PRD:** Product Requirements Document complet
- **Architecture:** Documentation architecturale détaillée
- **Epics:** 9 epics complétés
- **UX:** Spécifications de design et directions
- **Implementation:** 38 fichiers d'implémentation détaillée
Ces documents sont disponibles pour référence lors du développement de nouvelles fonctionnalités.
---
## Base de Données
**Phase 1:** SQLite (pour le développement et le test)
- Frontend: `chartbastan/chartbastan.db` (Drizzle ORM)
- Backend: SQLAlchemy avec Alembic (migrations)
**Phase 2+:** PostgreSQL (production)
---
## Développement Actif
**Statut:** Tous les epics sont complétés
**Phase actuelle:** Testing de l'application complète
Le projet est prêt pour le test et la validation des fonctionnalités.

View File

@@ -0,0 +1,412 @@
# Analyse de l'Arbre Source - ChartBastan
## Vue d'ensemble de la Structure
```
chartbastan/
├── _bmad/ # Configuration BMad (workflow/agents)
│ ├── _config/ # Configuration des agents et workflows
│ ├── bmm/ # Configuration BMM
│ └── core/ # Core BMad system
├── _bmad-output/ # Artefacts de planification et implémentation
│ ├── analysis/ # Analyses et brainstorming
│ ├── implementation-artifacts/ # 38 fichiers d'implémentation détaillée
│ └── planning-artifacts/ # PRD, Architecture, Epics, UX
├── backend/ # Backend FastAPI (Part: api)
│ │
│ ├── alembic/ # Migrations de base de données
│ │ ├── versions/ # Scripts de migration (10 fichiers)
│ │ ├── env.py # Configuration Alembic
│ │ └── script.py.mako # Template de migration
│ │
│ ├── app/ # Code principal de l'application
│ │ ├── api/ # Endpoints REST (2 fichiers)
│ │ │ ├── dependencies.py # Dépendances d'API
│ │ │ └── __init__.py
│ │ │
│ │ ├── lib/ # Bibliothèques partagées
│ │ │ └── badges.py # Système de badges
│ │ │
│ │ ├── main.py # Point d'entrée FastAPI ⚡
│ │ │
│ │ ├── middleware/ # Middleware
│ │ │ ├── auth.py # Middleware d'authentification
│ │ │ └── cors.py # Middleware CORS
│ │ │
│ │ ├── ml/ # Services Machine Learning (5 services)
│ │ │ ├── sentiment_analyzer.py # Analyse de sentiment (VADER)
│ │ │ ├── prediction_calculator.py # Calcul de prédictions
│ │ │ └── [autres services ML]
│ │ │
│ │ ├── models/ # Modèles SQLAlchemy (12 modèles)
│ │ │ ├── user.py # Modèle utilisateur
│ │ │ ├── match.py # Modèle match
│ │ │ ├── prediction.py # Modèle prédiction
│ │ │ ├── user_prediction.py # Prédictions utilisateur
│ │ │ ├── tweet.py # Données Twitter
│ │ │ ├── reddit_post.py # Données Reddit
│ │ │ ├── rss_article.py # Données RSS
│ │ │ ├── sentiment_score.py # Scores de sentiment
│ │ │ ├── energy_score.py # Scores d'énergie
│ │ │ ├── api_key.py # Clés API tierces
│ │ │ └── badge.py # Système de badges
│ │ │
│ │ ├── schemas/ # Schémas Pydantic (14 fichiers)
│ │ │ ├── user.py
│ │ │ ├── match.py
│ │ │ ├── prediction.py
│ │ │ ├── tweet.py
│ │ │ ├── reddit_post.py
│ │ │ ├── energy_score.py
│ │ │ ├── sentiment_score.py
│ │ │ ├── badge.py
│ │ │ ├── leaderboard.py
│ │ │ ├── backtesting.py
│ │ │ ├── public.py
│ │ │ └── [autres schémas]
│ │ │
│ │ ├── queues/ # Gestion RabbitMQ (4 fichiers)
│ │ │
│ │ ├── scrapers/ # Scrapers de données (4 scrapers)
│ │ │ ├── twitter_scraper.py # Scraper Twitter
│ │ │ ├── reddit_scraper.py # Scraper Reddit
│ │ │ ├── rss_scraper.py # Scraper RSS
│ │ │ └── README.md # Documentation scraper
│ │ │
│ │ ├── services/ # Services métier (8 services)
│ │ │
│ │ └── workers/ # Workers asynchrones (4 workers)
│ │
│ ├── scripts/ # Scripts utilitaires
│ │ └── generate_historical_matches.py # Génération de données de test
│ │
│ ├── tests/ # Tests unitaires (30 fichiers)
│ │ ├── conftest.py # Configuration pytest
│ │ ├── test_api_*.py # Tests API
│ │ ├── test_*.py # Tests divers
│ │ └── run_tests.py # Script d'exécution des tests
│ │
│ ├── workers/ # Scripts d'exécution des workers
│ │ ├── run_energy_worker.py
│ │ ├── run_scraping_worker.py
│ │ └── run_sentiment_worker.py
│ │
│ ├── requirements.txt # Dépendances Python
│ ├── alembic.ini # Configuration Alembic
│ ├── run_server.bat # Script démarrage Windows
│ └── run_server.sh # Script démarrage Linux/Mac
├── chartbastan/ # Frontend Next.js (Part: frontend)
│ │
│ ├── public/ # Assets statiques
│ │ └── [fichiers SVG pour icônes]
│ │
│ ├── src/ # Code source
│ │ │
│ │ ├── app/ # App Router Next.js (22 fichiers)
│ │ │ ├── layout.tsx # Layout racine 📄
│ │ │ ├── page.tsx # Page d'accueil 🏠
│ │ │ ├── login/ # Page de login
│ │ │ ├── register/ # Page d'inscription
│ │ │ ├── dashboard/ # Dashboard principal
│ │ │ ├── matches/ # Pages de matchs
│ │ │ ├── predictions/ # Pages de prédictions
│ │ │ ├── leaderboard/ # Classements
│ │ │ ├── history/ # Historique
│ │ │ ├── badges/ # Badges
│ │ │ ├── referrals/ # Parrainage
│ │ │ ├── api/ # API Routes Next.js
│ │ │ │ └── auth/ # Routes d'authentification
│ │ │ └── [autres pages et routes]
│ │ │
│ │ ├── components/ # Composants React (72+ composants)
│ │ │ │
│ │ │ ├── ui/ # Composants UI shadcn/ui
│ │ │ │ ├── button.tsx # Boutons
│ │ │ │ ├── card.tsx # Cartes
│ │ │ │ ├── input.tsx # Inputs
│ │ │ │ ├── dropdown-menu.tsx # Menus déroulants
│ │ │ │ ├── tooltip.tsx # Tooltips
│ │ │ │ ├── badge.tsx # Badges UI
│ │ │ │ ├── alert.tsx # Alertes
│ │ │ │ ├── switch.tsx # Switches
│ │ │ │ ├── label.tsx # Labels
│ │ │ │ └── skeleton.tsx # Skeletons de chargement
│ │ │ │
│ │ │ ├── dashboard/ # Composants Dashboard
│ │ │ │ ├── DashboardWrapper.tsx
│ │ │ │ ├── RealTimeEnergyChart.tsx
│ │ │ │ ├── EnergyWave.tsx
│ │ │ │ ├── ConfidenceMeter.tsx
│ │ │ │ ├── MatchList.tsx
│ │ │ │ ├── MatchListItem.tsx
│ │ │ │ ├── PredictionCard.tsx
│ │ │ │ ├── RefreshIndicator.tsx
│ │ │ │ ├── EnergyWaveTooltip.tsx
│ │ │ │ └── ConfidenceTooltip.tsx
│ │ │ │
│ │ │ ├── matches/ # Composants Matchs
│ │ │ │
│ │ │ ├── predictions/ # Composants Prédictions
│ │ │ │
│ │ │ ├── leaderboard/ # Composants Classement
│ │ │ │ ├── LeaderboardItem.tsx
│ │ │ │ ├── PersonalRank.tsx
│ │ │ │ └── RankBadge.tsx
│ │ │ │
│ │ │ ├── history/ # Composants Historique
│ │ │ │ ├── PredictionHistoryItem.tsx
│ │ │ │ ├── AccuracyRate.tsx
│ │ │ │ └── SuccessBadge.tsx
│ │ │ │
│ │ │ ├── badges/ # Composants Badges
│ │ │ │ ├── BadgeCard.tsx
│ │ │ │ └── BadgeShare.tsx
│ │ │ │
│ │ │ ├── referrals/ # Composants Parrainage
│ │ │ │ ├── referralLink.tsx
│ │ │ │ └── rewardsList.tsx
│ │ │ │
│ │ │ ├── notifications/ # Composants Notifications
│ │ │ │ ├── NotificationPanel.tsx
│ │ │ │ ├── NotificationPreferences.tsx
│ │ │ │ ├── NotificationToast.tsx
│ │ │ │ ├── NotificationSwitch.tsx
│ │ │ │ ├── PredictionNotificationSettings.tsx
│ │ │ │ └── SuccessAnimation.tsx
│ │ │ │
│ │ │ ├── calendar/ # Composants Calendrier
│ │ │ │ ├── EnergyCalendar.tsx
│ │ │ │ ├── CalendarMatchItem.tsx
│ │ │ │ └── CalendarFilters.tsx
│ │ │ │
│ │ │ ├── comparison/ # Composants Comparaison
│ │ │ │ ├── ComparisonChart.tsx
│ │ │ │ └── ComparisonCard.tsx
│ │ │ │
│ │ │ ├── share/ # Composants Partage
│ │ │ │ ├── ShareButton.tsx
│ │ │ │ └── ShareMenu.tsx
│ │ │ │
│ │ │ ├── auth/ # Composants Authentification
│ │ │ │ ├── LoginForm.tsx
│ │ │ │ └── RegisterForm.tsx
│ │ │ │
│ │ │ ├── landing/ # Composants Landing Page
│ │ │ │ ├── HeroSection.tsx
│ │ │ │ └── EmailCaptureForm.tsx
│ │ │ │
│ │ │ ├── onboarding/ # Composants Onboarding
│ │ │ │ ├── Step1HowItWorks.tsx
│ │ │ │ ├── Step2HowToUse.tsx
│ │ │ │ └── Step3FirstSteps.tsx
│ │ │ │
│ │ │ ├── navigation/ # Composants Navigation
│ │ │ │ ├── TopTabs.tsx
│ │ │ │ └── BottomNav.tsx
│ │ │ │
│ │ │ ├── errors/ # Composants Erreurs
│ │ │ │ └── RateLimitError.tsx
│ │ │ │
│ │ │ ├── limits/ # Composants Limites
│ │ │ │ ├── PredictionCounter.tsx
│ │ │ │ ├── LimitReached.tsx
│ │ │ │ └── PremiumWall.tsx
│ │ │ │
│ │ │ └── [tests] # Tests des composants
│ │ │
│ │ ├── db/ # Base de données Drizzle
│ │ │ └── [configuration Drizzle]
│ │ │
│ │ ├── hooks/ # React Hooks personnalisés (9 hooks)
│ │ │
│ │ ├── lib/ # Utilitaires et API client (7 fichiers)
│ │ │ └── [services d'API, helpers]
│ │ │
│ │ ├── middleware/ # Middleware Next.js (3 fichiers)
│ │ │
│ │ ├── scripts/ # Scripts de migration (3 scripts)
│ │ │
│ │ ├── services/ # Services API (27 services)
│ │ │ ├── auth.ts
│ │ │ ├── matches.ts
│ │ │ ├── predictions.ts
│ │ │ ├── [autres services]
│ │ │
│ │ ├── stores/ # Zustand stores (2 stores)
│ │ │ ├── notificationStore.ts
│ │ │ └── onboarding-store.ts
│ │ │
│ │ └── tests/ # Tests (48 fichiers)
│ │ ├── components/
│ │ └── [autres tests]
│ │
│ ├── drizzle/ # Migrations Drizzle
│ │ └── [migrations et schema]
│ │
│ ├── components.json # Configuration shadcn/ui
│ ├── drizzle.config.ts # Configuration Drizzle
│ ├── eslint.config.mjs # Configuration ESLint
│ ├── next.config.ts # Configuration Next.js
│ ├── package.json # Dépendances Node.js
│ ├── postcss.config.mjs # Configuration PostCSS
│ ├── tsconfig.json # Configuration TypeScript
│ ├── vitest.config.ts # Configuration Vitest
│ └── chartbastan.db* # Base de données SQLite
├── docs/ # Documentation du projet 📚
│ ├── project-scan-report.json # État du workflow de scan
│ ├── project-structure.md # Structure du projet
│ ├── project-parts-metadata.md # Métadonnées des parties
│ ├── existing-documentation-inventory.md # Documentation existante
│ ├── user-provided-context.md # Contexte utilisateur
│ ├── technology-stack.md # Stack technologique
│ ├── architecture-patterns.md # Patterns d'architecture
│ └── [autres fichiers générés]
├── check-prerequisites.js # Script de vérification des prérequis
└── [autres fichiers de configuration]
```
---
## Points d'Entrée Principaux
### Frontend (chartbastan/)
**Point d'entrée principal:** `src/app/page.tsx`
- Page d'accueil de l'application
- Route: `/`
**Point d'entrée Next.js:** `src/app/layout.tsx`
- Layout racine qui enveloppe toute l'application
- Définit l'UI globale et les providers
**Configuration:**
- `package.json` - Dépendances et scripts
- `next.config.ts` - Configuration Next.js
- `tsconfig.json` - Configuration TypeScript
### Backend (backend/)
**Point d'entrée principal:** `app/main.py`
- Application FastAPI
- Démarre le serveur Uvicorn sur le port 8000
**Configuration:**
- `requirements.txt` - Dépendances Python
- `alembic.ini` - Configuration des migrations
---
## Répertoires Critiques
### Frontend
| Répertoire | But | Contenu Clé |
|------------|------|--------------|
| `src/app/` | Routes et pages Next.js | `page.tsx`, `layout.tsx`, `/dashboard/` |
| `src/components/` | Composants React réutilisables | 72+ composants UI |
| `src/services/` | Services API | Communication avec le backend |
| `src/stores/` | État global | Zustand stores |
| `src/hooks/` | React Hooks personnalisés | Logique réutilisable |
| `src/lib/` | Utilitaires | Helpers et fonctions d'aide |
### Backend
| Répertoire | But | Contenu Clé |
|------------|------|--------------|
| `app/api/` | Endpoints REST | Dépendances d'API |
| `app/models/` | Modèles SQLAlchemy | 12 modèles de données |
| `app/schemas/` | Schémas Pydantic | Validation de données |
| `app/services/` | Logique métier | 8 services |
| `app/scrapers/` | Scrapers de données | Twitter, Reddit, RSS |
| `app/ml/` | Services ML | Sentiment, prédictions |
| `app/workers/` | Workers async | Tâches asynchrones |
| `tests/` | Tests unitaires | 30 tests |
---
## Points d'Intégration Frontend-Backend
### Communication API
**Frontend → Backend:**
- Services dans `src/services/` appellent `http://localhost:8000`
- Exemple: `src/services/matches.ts``GET http://localhost:8000/api/matches`
**Base de données partagée:**
- `chartbastan/chartbastan.db` - Accessible par frontend (Drizzle) et backend (SQLAlchemy)
---
## Documentation et Artefacts
**_bmad-output/:**
- `planning-artifacts/` - PRD, Architecture, Epics
- `implementation-artifacts/` - 38 fichiers d'implémentation
- `analysis/` - Analyses et brainstorming
**docs/:**
- Documentation générée par ce workflow
- Structure, stack, architecture
---
## Scripts Utilitaires
### Backend
| Script | But |
|--------|------|
| `run_server.bat` | Démarrer le serveur FastAPI (Windows) |
| `run_server.sh` | Démarrer le serveur FastAPI (Linux/Mac) |
| `scripts/generate_historical_matches.py` | Générer des données de test |
### Frontend
| Script (package.json) | But |
|---------------------|------|
| `npm run dev` | Démarrer le serveur de développement |
| `npm run build` | Build de production |
| `npm run start` | Démarrer le serveur de production |
| `npm run lint` | Exécuter ESLint |
| `npm run type-check` | Vérifier les types TypeScript |
| `npm run test` | Exécuter les tests Vitest |
---
## Base de Données
**SQLite (Phase 1):**
- Frontend: `chartbastan/chartbastan.db` (Drizzle ORM)
- Backend: Accès à la même base (SQLAlchemy)
**Migrations:**
- Frontend: `drizzle/migrations/`
- Backend: `alembic/versions/`
**Phase 2+:** PostgreSQL (production)
---
## Résumé
**Total de fichiers source:**
- Backend: ~100+ fichiers Python
- Frontend: ~300+ fichiers TypeScript/TSX
**Architecture:**
- Frontend: Next.js App Router avec composants React
- Backend: FastAPI avec architecture en couches
- Communication: REST API
- Base de données: SQLite partagée
**Points clés:**
- Entry point frontend: `src/app/page.tsx`
- Entry point backend: `app/main.py`
- Integration: Services `src/services/` → API `http://localhost:8000`
- Database: SQLite partagée à `chartbastan/chartbastan.db`

361
docs/technology-stack.md Normal file
View File

@@ -0,0 +1,361 @@
# Stack Technologique - ChartBastan
## Vue d'ensemble
Le projet ChartBastan utilise une stack moderne full-stack avec:
- **Frontend:** Next.js 16 avec TypeScript
- **Backend:** FastAPI avec Python 3.11+
- **Base de données:** SQLite (développement) → PostgreSQL (production)
- **Communication:** REST API
- **Message Queue:** RabbitMQ (pour workers asynchrones)
---
## Partie 1: Frontend (chartbastan/)
### Framework & Language
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Framework | Next.js | 16.1.3 | Framework React moderne avec SSR, SSG, et App Router |
| Language | TypeScript | 5.0 | Typage statique pour la fiabilité du code |
| Runtime | Node.js | 20+ | Environment JavaScript moderne |
### UI & Styling
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| CSS Framework | Tailwind CSS | v4 | Utilitaire-first CSS, développement rapide |
| UI Library | shadcn/ui | - | Composants Radix UI accessibles et personnalisables |
| Icons | Lucide React | 0.562.0 | Icônes SVG légères et cohérentes |
| Animation | Framer Motion | 12.26.2 | Animations fluides et performantes |
| Pull-to-refresh | react-pull-to-refresh | 2.0.1 | UX mobile native pour rafraîchir |
### State Management
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| State Store | Zustand | 5.0.10 | State management léger et simple |
| Data Fetching | React Query (@tanstack/react-query) | 5.90.18 | Cache, sync, et gestion des appels API |
### Database & ORM
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Database | SQLite | better-sqlite3 12.6.2 | Base légère pour développement |
| ORM | Drizzle ORM | 0.44.7 | ORM moderne type-safe avec SQL pur |
| Migrations | Drizzle Kit | 0.31.8 | Génération de migrations et schéma |
### Visualization
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Charts | Recharts | 3.6.0 | Graphiques React déclaratifs |
| Advanced Viz | D3.js | 7.9.0 | Visualisations complexes et personnalisées |
| Types | @types/d3 | 7.4.3 | Typage TypeScript pour D3 |
### Authentication
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Auth | better-auth | 1.4.14 | Solution d'authentification moderne pour Next.js |
| Password Hashing | bcryptjs | 3.0.3 | Hashage sécurisé des mots de passe |
### Notifications
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Web Push | web-push | 3.6.7 | Notifications push web standard W3C |
| Types | @types/web-push | 3.6.4 | Typage TypeScript |
### Validation & Forms
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Validation | Zod | 4.3.5 | Validation de schéma avec TypeScript |
### Messaging
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Redis Client | ioredis | 5.9.2 | Client Redis pour pub/sub et cache |
### Utilities
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Class Variance | class-variance-authority | 0.7.1 | Gestion des variantes de composants |
| clsx | clsx | 2.1.1 | Concaténation de classes conditionnelle |
| tailwind-merge | tailwind-merge | 3.4.0 | Fusion intelligente de classes Tailwind |
### Development Tools
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Linter | ESLint | 9 | Linting JavaScript/TypeScript |
| Testing | Vitest | 4.0.17 | Framework de test rapide et moderne |
| Testing Library | @testing-library/react | 16.3.1 | Tests de composants React |
| Testing Library | @testing-library/user-event | 14.6.1 | Simulation d'interactions utilisateur |
| Testing Library | @testing-library/jest-dom | 6.9.1 | Matchers DOM pour Jest/Vitest |
| Happy DOM | happy-dom | 20.3.1 | Léger DOM implementation pour tests |
| JSDOM | jsdom | 27.4.0 | DOM implementation pour tests |
### Architecture Pattern
**Type:** Component-based / App Router (Next.js 16)
**Caractéristiques:**
- App Router avec Server Components
- Client Components pour l'interactivité
- API Routes pour backend intégré
- Middleware pour authentification et routing
- Streaming et Suspense pour UX optimisée
**Structure:**
- `src/app/` - App Router (routes, layouts, pages)
- `src/components/` - Composants réutilisables
- `src/services/` - Services API et logique métier
- `src/hooks/` - React Hooks personnalisés
- `src/stores/` - Zustand stores
- `src/lib/` - Utilitaires et helpers
---
## Partie 2: Backend (backend/)
### Framework & Server
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Framework | FastAPI | 0.128.0 | API moderne, rapide, avec documentation auto |
| ASGI Server | Uvicorn | 0.30.0 | Server ASGI haute performance |
| Language | Python | 3.11+ | Version moderne avec typage amélioré |
### Database & ORM
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| ORM | SQLAlchemy | 2.0.45 | ORM Python mature et flexible |
| Migrations | Alembic | 1.13.0 | Outil de migration de base de données |
### Validation & Settings
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Validation | Pydantic | 2.7.0 | Validation de données avec Python |
| Settings | Pydantic Settings | 2.3.0 | Gestion des variables d'environnement |
| Email Validation | email-validator | 2.1.0 | Validation d'adresses email |
### Data Scraping
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Twitter API | tweepy | 4.14.0 | Client Python pour l'API Twitter v2 |
| Reddit API | praw | 7.8.1 | Python Reddit API Wrapper |
| RSS Parser | feedparser | 6.0.11 | Parser RSS/Atom feeds |
### Machine Learning
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Sentiment Analysis | vaderSentiment | 3.3.2 | Analyse de sentiment pour texte social media |
| NLP | textblob | 0.17.1 | Traitement du langage naturel |
### Message Queue
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| RabbitMQ Client | pika | 1.3.2 | Client AMQP pour RabbitMQ |
### Development Tools
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Linter | flake8 | 7.1.0 | Linting PEP 8 |
| Formatter | black | 24.8.0 | Formatting Python automatique |
| Testing | pytest | 8.3.3 | Framework de tests Python |
### File Upload
| Catégorie | Technologie | Version | Justification |
|-----------|-------------|---------|--------------|
| Multipart | python-multipart | 0.0.9 | Support de formulaire multipart |
### Architecture Pattern
**Type:** REST API / Service-oriented
**Caractéristiques:**
- API RESTful avec FastAPI
- Documentation auto-générée (Swagger/OpenAPI)
- Async/await pour performances
- Dependency injection
- Middleware pour auth, CORS
- Background tasks avec Celery/RabbitMQ
**Structure:**
- `app/api/` - Endpoints REST
- `app/models/` - Modèles SQLAlchemy
- `app/schemas/` - Schémas Pydantic
- `app/services/` - Business logic
- `app/ml/` - Services ML
- `app/scrapers/` - Scrapers (Twitter, Reddit, RSS)
- `app/queues/` - Gestion RabbitMQ
- `app/workers/` - Workers asynchrones
- `app/middleware/` - Middleware (auth, CORS)
---
## Architecture Globale
### Pattern de Communication
**Frontend ↔ Backend:**
- Protocol: REST API (HTTP/HTTPS)
- Format: JSON
- Base URL: `http://localhost:8000` (dev)
### Architecture de Données
**Phase 1 (Développement):**
- Frontend Database: SQLite (chartbastan.db)
- Backend Database: SQLite partagée
- ORM: Drizzle (frontend) + SQLAlchemy (backend)
**Phase 2+ (Production):**
- Database: PostgreSQL
- Cache: Redis (optionnel)
- ORM: Drizzle + SQLAlchemy
### Asynchronous Processing
**RabbitMQ:**
- Message broker pour tâches asynchrones
- Workers: scraping, analyse de sentiment, prédictions
- Découplage frontend/backend
---
## Dépendances Externes
### APIs Tierces
**Frontend:**
- Twitter API (accès direct, si configuré)
- Reddit API (accès direct, si configuré)
**Backend:**
- Twitter API v2 (via tweepy)
- Reddit API (via praw)
### Infrastructure
**Développement:**
- SQLite (base de données locale)
- RabbitMQ (optionnel, pour workers)
**Production (recommandé):**
- PostgreSQL (base de données)
- Redis (cache, sessions)
- RabbitMQ (message queue)
- VPS (hébergement)
---
## Sécurité
### Frontend
- better-auth pour authentification
- bcryptjs pour hashage des mots de passe
- Validation Zod des données d'entrée
### Backend
- Authentification JWT (via better-auth)
- Validation Pydantic
- CORS configuré
- Middleware de sécurité
---
## Performance
### Frontend Optimizations
- Next.js App Router (Server Components)
- Streaming et Suspense
- Code splitting automatique
- Optimisation d'images
- Cache React Query
### Backend Optimizations
- FastAPI async/await
- SQLAlchemy async operations
- Connection pooling
- RabbitMQ pour tâches lourdes
---
## Monitoring & Logging
### Frontend
- Logging via console (développement)
- Error tracking (à implémenter en production)
### Backend
- Logging structuré Python
- Error handling centralisé
- Monitoring (à implémenter en production)
---
## Testing
### Frontend Tests
- Vitest (framework de test)
- React Testing Library (composants)
- User Event (interactions)
- Type checking (TypeScript)
### Backend Tests
- pytest (framework de test)
- Tests unitaires et d'intégration
- Couverture de code (à implémenter)
---
## CI/CD
### Frontend
- ESLint
- TypeScript type-check
- Next.js build
- Tests Vitest
### Backend
- flake8 (linting)
- black (formatting)
- pytest (tests)
---
## Résumé de la Stack
**Frontend:**
- Framework: Next.js 16.1.3 + TypeScript 5
- UI: Tailwind CSS v4 + shadcn/ui
- State: Zustand + React Query
- Database: Drizzle ORM + SQLite
- Visualization: D3.js + Recharts
**Backend:**
- Framework: FastAPI 0.128.0 + Python 3.11+
- ORM: SQLAlchemy 2.0.45 + Alembic
- Scraping: tweepy + praw + feedparser
- ML: vaderSentiment + textblob
- Queue: RabbitMQ (pika)
**Infrastructure:**
- Database: SQLite (dev) → PostgreSQL (prod)
- Message Queue: RabbitMQ
- API Docs: Swagger/OpenAPI auto-généré
Cette stack est moderne, performante et bien adaptée aux besoins de l'application.

View File

@@ -0,0 +1,145 @@
# Contexte Utilisateur - ChartBastan
## Objectif Principal
**Créer un README simple pour tester l'application complète.**
Le projet ChartBastan est en phase finale de développement:
- ✅ Tous les 9 epics sont complétés
- ✅ L'architecture est implémentée
- ✅ Frontend et Backend sont prêts
- 🔄 **Phase actuelle: Testing de l'application**
---
## Priorités pour la Documentation
### 1. Démarrage Rapide (Testing)
Créer des instructions claires pour:
- Démarrer le frontend (Next.js)
- Démarrer le backend (FastAPI)
- Configurer l'environnement
- Vérifier que tout fonctionne
### 2. Instructions de Test
Fournir des guides pour tester:
- L'authentification des utilisateurs
- L'affichage des matchs
- Les prédictions basées sur l'énergie collective
- Le dashboard en temps réel
- Les notifications (si implémentées)
### 3. Dépannage
Inclure des sections pour résoudre:
- Problèmes de connexion
- Erreurs de base de données
- Problèmes de scraping (Twitter/Reddit)
- Problèmes de synchronisation frontend/backend
---
## Zones d'Intérêt
### Frontend (chartbastan/)
- Dashboard principal
- Visualisation des matchs
- Interface de paris/prédictions
- Gestion du profil utilisateur
- Notifications push
### Backend (backend/)
- API REST (documentation Swagger)
- Scraping de données (Twitter, Reddit, RSS)
- Analyse de sentiment
- Calcul de l'énergie collective
- Machine Learning pour les prédictions
### Intégration
- Communication Frontend ↔ Backend
- Authentification (better-auth)
- Base de données partagée (SQLite)
---
## Configuration Actuelle
### Environnement
- **OS:** Windows 10
- **Shell:** PowerShell 7
- **IDE:** Cursor (VS Code based)
### Répertoire de Travail
```
d:\dev_new_pc\chartbastan
```
### Structure
- Frontend: `chartbastan/`
- Backend: `backend/`
- Documentation: `docs/` (fichiers générés par ce workflow)
- Artefacts de planification: `_bmad-output/`
---
## Notes de l'Utilisateur
- Le projet est complet et prêt pour le test
- Tous les épics ont été implémentés
- Besoin d'un guide simple pour démarrer l'application
- Priorité: Testing et validation des fonctionnalités
---
## Exigences pour le README de Test
### Contenu Essentiel
1. **Prérequis**
- Versions de Node.js et Python requises
- Autres dépendances (RabbitMQ, Redis si nécessaires)
2. **Installation**
- Commandes pour installer les dépendances
- Configuration des variables d'environnement
- Initialisation de la base de données
3. **Démarrage**
- Commandes pour lancer le backend (FastAPI)
- Commandes pour lancer le frontend (Next.js)
- Vérification que tout fonctionne
4. **Testing**
- URLs pour accéder aux interfaces
- Scénarios de test basiques
- Comment vérifier les fonctionnalités clés
5. **Dépannage**
- Problèmes courants et solutions
- Où chercher les logs
- Comment réinitialiser l'environnement
---
## Documents de Référence Existant
Documentation disponible dans `_bmad-output/`:
- `planning-artifacts/prd.md` - Exigences complètes
- `planning-artifacts/architecture.md` - Architecture détaillée
- `planning-artifacts/epics.md` - Liste des epics
- `implementation-artifacts/` - 38 fichiers d'implémentation détaillée
- `chartbastan/README.md` - README existant (complet mais complexe)
---
## Prochaine Étape
Générer un README simple et focalisé sur le testing pour permettre à l'utilisateur de:
1. Démarrer rapidement l'application
2. Tester les fonctionnalités principales
3. Valider que tout fonctionne comme prévu
---
## Date de Création
2026-01-18