Compare commits
6 Commits
feature/HR
...
feature/HR
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52c0c95f22 | ||
| 91134e2f3f | |||
|
|
663e0bb149 | ||
| 5c6b407f47 | |||
|
|
946bdc65b6 | ||
|
|
ec024d8236 |
@@ -5,6 +5,7 @@ Sprint 3-4: HRT-29 — Refacto API /v1/
|
|||||||
Sprint 5-6: HRT-31 — Billing Stripe
|
Sprint 5-6: HRT-31 — Billing Stripe
|
||||||
HRT-79: Alertes Telegram configurables (user blueprint)
|
HRT-79: Alertes Telegram configurables (user blueprint)
|
||||||
HRT-80: API Token personnel + Webhook alertes (Pro)
|
HRT-80: API Token personnel + Webhook alertes (Pro)
|
||||||
|
HRT-82: Multi-compte / Organisation Pro (max 5 users)
|
||||||
|
|
||||||
Registers sub-blueprints:
|
Registers sub-blueprints:
|
||||||
/api/v1/health — public health-check
|
/api/v1/health — public health-check
|
||||||
@@ -19,7 +20,10 @@ Registers sub-blueprints:
|
|||||||
/api/v1/user/api-token — Personal API token (Pro)
|
/api/v1/user/api-token — Personal API token (Pro)
|
||||||
/api/v1/user/webhook — Webhook config (Pro)
|
/api/v1/user/webhook — Webhook config (Pro)
|
||||||
/api/v1/history — historique préd. ML (Free:7j, Premium:90j, Pro:illimité)
|
/api/v1/history — historique préd. ML (Free:7j, Premium:90j, Pro:illimité)
|
||||||
|
/api/v1/org/ — organisations Pro (multi-compte, max 5 users)
|
||||||
/api/v1/docs — Swagger UI (via flasgger, registered on app)
|
/api/v1/docs — Swagger UI (via flasgger, registered on app)
|
||||||
|
/api/v1/ml/feedback/run — trigger feedback loop ML (admin)
|
||||||
|
/api/v1/ml/feedback/stats — stats par stratégie (premium+)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from flask import Blueprint
|
from flask import Blueprint
|
||||||
@@ -35,6 +39,8 @@ from .routes.billing import billing_bp
|
|||||||
from .routes.user import user_bp
|
from .routes.user import user_bp
|
||||||
from .routes.user_tokens import user_tokens_bp
|
from .routes.user_tokens import user_tokens_bp
|
||||||
from .routes.history import history_bp
|
from .routes.history import history_bp
|
||||||
|
from .routes.org import org_bp
|
||||||
|
from .routes.ml_feedback import ml_feedback_bp
|
||||||
|
|
||||||
# Master blueprint that aggregates all sub-routes under /api/v1
|
# Master blueprint that aggregates all sub-routes under /api/v1
|
||||||
api_v1_bp = Blueprint("api_v1", __name__, url_prefix="/api/v1")
|
api_v1_bp = Blueprint("api_v1", __name__, url_prefix="/api/v1")
|
||||||
@@ -53,3 +59,5 @@ def register_api_v1(app):
|
|||||||
app.register_blueprint(user_bp)
|
app.register_blueprint(user_bp)
|
||||||
app.register_blueprint(user_tokens_bp)
|
app.register_blueprint(user_tokens_bp)
|
||||||
app.register_blueprint(history_bp)
|
app.register_blueprint(history_bp)
|
||||||
|
app.register_blueprint(org_bp)
|
||||||
|
app.register_blueprint(ml_feedback_bp)
|
||||||
|
|||||||
191
api_v1/routes/ml_feedback.py
Normal file
191
api_v1/routes/ml_feedback.py
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
ml_feedback.py — API routes pour le feedback loop ML (turf_saas).
|
||||||
|
|
||||||
|
Routes:
|
||||||
|
POST /api/v1/ml/feedback/run — Déclenche le feedback loop (admin uniquement)
|
||||||
|
GET /api/v1/ml/feedback/stats — Stats performances par stratégie
|
||||||
|
|
||||||
|
Sécurité admin : token via variable d'environnement ML_ADMIN_TOKEN
|
||||||
|
ou plan "pro" en fallback pour les stats.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from flask import Blueprint, jsonify, request, g
|
||||||
|
|
||||||
|
# Ajoute le répertoire parent de api_v1 dans le path pour importer ml_feedback_saas
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
||||||
|
|
||||||
|
from api_v1.utils import get_db, internal_error, bad_request
|
||||||
|
from auth import jwt_required_middleware, plan_required
|
||||||
|
|
||||||
|
ml_feedback_bp = Blueprint("v1_ml_feedback", __name__, url_prefix="/api/v1/ml/feedback")
|
||||||
|
|
||||||
|
# Token admin interne — configurable via variable d'environnement
|
||||||
|
ML_ADMIN_TOKEN = os.environ.get("ML_ADMIN_TOKEN", "")
|
||||||
|
|
||||||
|
|
||||||
|
def _check_admin(req):
|
||||||
|
"""Vérifie le token admin via header X-Admin-Token ou Authorization Bearer (plan pro)."""
|
||||||
|
# 1. Token interne (scheduler/cron)
|
||||||
|
admin_token = req.headers.get("X-Admin-Token", "").strip()
|
||||||
|
if ML_ADMIN_TOKEN and admin_token == ML_ADMIN_TOKEN:
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
# 2. Pas de token admin configuré → autoriser les utilisateurs "pro" authentifiés
|
||||||
|
user = getattr(g, "current_user", None)
|
||||||
|
if user and user.get("plan") == "pro":
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
return False, jsonify({"error": "Accès admin requis", "code": 403}), 403
|
||||||
|
|
||||||
|
|
||||||
|
@ml_feedback_bp.route("/run", methods=["POST"])
|
||||||
|
@jwt_required_middleware
|
||||||
|
def feedback_run():
|
||||||
|
"""
|
||||||
|
Déclenche le feedback loop ML pour une date donnée.
|
||||||
|
---
|
||||||
|
tags:
|
||||||
|
- ML Feedback
|
||||||
|
summary: Déclenche le feedback loop XGBoost (admin only)
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
- AdminToken: []
|
||||||
|
parameters:
|
||||||
|
- name: body
|
||||||
|
in: body
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
date:
|
||||||
|
type: string
|
||||||
|
description: Date YYYY-MM-DD (défaut aujourd'hui)
|
||||||
|
example: "2026-04-25"
|
||||||
|
mode:
|
||||||
|
type: string
|
||||||
|
description: "run (défaut) ou backfill"
|
||||||
|
enum: [run, backfill]
|
||||||
|
example: run
|
||||||
|
responses:
|
||||||
|
200:
|
||||||
|
description: Feedback loop exécuté avec succès
|
||||||
|
400:
|
||||||
|
description: Paramètre invalide
|
||||||
|
403:
|
||||||
|
description: Accès refusé
|
||||||
|
500:
|
||||||
|
description: Erreur interne
|
||||||
|
"""
|
||||||
|
# Vérification admin
|
||||||
|
user = getattr(g, "current_user", None)
|
||||||
|
admin_token = request.headers.get("X-Admin-Token", "").strip()
|
||||||
|
is_admin = (ML_ADMIN_TOKEN and admin_token == ML_ADMIN_TOKEN) or (
|
||||||
|
user and user.get("plan") == "pro"
|
||||||
|
)
|
||||||
|
if not is_admin:
|
||||||
|
return jsonify({"error": "Accès admin requis", "code": 403}), 403
|
||||||
|
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
date_str = body.get("date") or datetime.now().strftime("%Y-%m-%d")
|
||||||
|
mode = body.get("mode", "run")
|
||||||
|
|
||||||
|
# Validation date
|
||||||
|
try:
|
||||||
|
datetime.strptime(date_str, "%Y-%m-%d")
|
||||||
|
except ValueError:
|
||||||
|
return bad_request(f"Date invalide : {date_str}. Format attendu : YYYY-MM-DD")
|
||||||
|
|
||||||
|
if mode not in ("run", "backfill"):
|
||||||
|
return bad_request("mode doit être 'run' ou 'backfill'")
|
||||||
|
|
||||||
|
try:
|
||||||
|
import ml_feedback_saas
|
||||||
|
|
||||||
|
if mode == "backfill":
|
||||||
|
inseres, maj = ml_feedback_saas.backfill(date_str)
|
||||||
|
total_inseres = inseres
|
||||||
|
else:
|
||||||
|
result = ml_feedback_saas.run(date_str)
|
||||||
|
total_inseres = sum(result["inseres"].values())
|
||||||
|
maj = result["maj"]
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"status": "ok",
|
||||||
|
"date": date_str,
|
||||||
|
"mode": mode,
|
||||||
|
"paris_inseres": total_inseres,
|
||||||
|
"paris_mis_a_jour": maj,
|
||||||
|
}
|
||||||
|
), 200
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return internal_error(str(e))
|
||||||
|
|
||||||
|
|
||||||
|
@ml_feedback_bp.route("/stats", methods=["GET"])
|
||||||
|
@jwt_required_middleware
|
||||||
|
@plan_required("premium", "pro")
|
||||||
|
def feedback_stats():
|
||||||
|
"""
|
||||||
|
Stats performances ML par stratégie.
|
||||||
|
---
|
||||||
|
tags:
|
||||||
|
- ML Feedback
|
||||||
|
summary: Stats paris ML par stratégie (premium+)
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
parameters:
|
||||||
|
- name: date_debut
|
||||||
|
in: query
|
||||||
|
type: string
|
||||||
|
description: Date de début YYYY-MM-DD
|
||||||
|
- name: date_fin
|
||||||
|
in: query
|
||||||
|
type: string
|
||||||
|
description: Date de fin YYYY-MM-DD
|
||||||
|
responses:
|
||||||
|
200:
|
||||||
|
description: Stats par stratégie
|
||||||
|
401:
|
||||||
|
description: Token invalide
|
||||||
|
403:
|
||||||
|
description: Plan insuffisant (premium ou pro requis)
|
||||||
|
"""
|
||||||
|
date_debut = request.args.get("date_debut")
|
||||||
|
date_fin = request.args.get("date_fin")
|
||||||
|
|
||||||
|
# Validation optionnelle des dates
|
||||||
|
for d_str, label in [(date_debut, "date_debut"), (date_fin, "date_fin")]:
|
||||||
|
if d_str:
|
||||||
|
try:
|
||||||
|
datetime.strptime(d_str, "%Y-%m-%d")
|
||||||
|
except ValueError:
|
||||||
|
return bad_request(f"{label} invalide : {d_str}. Format : YYYY-MM-DD")
|
||||||
|
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
import ml_feedback_saas
|
||||||
|
|
||||||
|
stats = ml_feedback_saas.get_feedback_stats(conn, date_debut, date_fin)
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"status": "ok",
|
||||||
|
"strategies": stats,
|
||||||
|
"filters": {
|
||||||
|
"date_debut": date_debut,
|
||||||
|
"date_fin": date_fin,
|
||||||
|
},
|
||||||
|
"total_strategies": len(stats),
|
||||||
|
}
|
||||||
|
), 200
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return internal_error(str(e))
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
536
api_v1/routes/org.py
Normal file
536
api_v1/routes/org.py
Normal file
@@ -0,0 +1,536 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Org Blueprint — Multi-compte / Organisations Pro
|
||||||
|
Sprint: HRT-82
|
||||||
|
|
||||||
|
Endpoints:
|
||||||
|
POST /api/v1/org — créer une organisation (Pro only, 1 max par owner)
|
||||||
|
GET /api/v1/org — infos org courante
|
||||||
|
DELETE /api/v1/org — supprimer l'org (owner only)
|
||||||
|
POST /api/v1/org/invite — inviter un membre par email (max 5 totaux)
|
||||||
|
GET /api/v1/org/members — liste des membres
|
||||||
|
DELETE /api/v1/org/members/<user_id> — retirer un membre (owner only)
|
||||||
|
|
||||||
|
Plan enforcement:
|
||||||
|
- Toutes les routes nécessitent plan=pro via plan_required('pro')
|
||||||
|
- Limite : 1 org par owner, 5 membres max (owner inclus)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
|
from saas_auth import require_auth as jwt_required_middleware
|
||||||
|
from org_db import get_db, migrate_org_tables
|
||||||
|
|
||||||
|
logger = logging.getLogger("turf_saas.org")
|
||||||
|
|
||||||
|
org_bp = Blueprint("org", __name__, url_prefix="/api/v1/org")
|
||||||
|
|
||||||
|
MAX_MEMBERS = 5 # max membres totaux owner inclus
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# Decorator: plan Pro requis
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _require_pro(fn):
|
||||||
|
"""Vérifie que l'utilisateur courant est sur le plan 'pro'."""
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
@wraps(fn)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
user = getattr(request, "current_user", None)
|
||||||
|
if not user:
|
||||||
|
return jsonify({"error": "Non authentifié"}), 401
|
||||||
|
if user.get("plan") != "pro":
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": "Plan insuffisant",
|
||||||
|
"required": "pro",
|
||||||
|
"current_plan": user.get("plan", "free"),
|
||||||
|
"upgrade_url": "/api/v1/billing/checkout",
|
||||||
|
}
|
||||||
|
), 403
|
||||||
|
return fn(*args, **kwargs)
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# Helpers DB
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _get_org_by_owner(db, owner_id: str):
|
||||||
|
return db.execute(
|
||||||
|
"SELECT * FROM organizations WHERE owner_id = ?", (owner_id,)
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def _get_org_by_id(db, org_id: str):
|
||||||
|
return db.execute("SELECT * FROM organizations WHERE id = ?", (org_id,)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def _get_member_org(db, user_id: str):
|
||||||
|
"""Retourne l'org dont user_id est membre (owner ou member)."""
|
||||||
|
row = db.execute(
|
||||||
|
"""SELECT o.* FROM organizations o
|
||||||
|
JOIN org_members m ON m.org_id = o.id
|
||||||
|
WHERE m.user_id = ?
|
||||||
|
LIMIT 1""",
|
||||||
|
(user_id,),
|
||||||
|
).fetchone()
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def _count_org_members(db, org_id: str) -> int:
|
||||||
|
row = db.execute(
|
||||||
|
"SELECT COUNT(*) AS cnt FROM org_members WHERE org_id = ?", (org_id,)
|
||||||
|
).fetchone()
|
||||||
|
return row["cnt"] if row else 0
|
||||||
|
|
||||||
|
|
||||||
|
def _get_user_by_email(db, email: str):
|
||||||
|
"""Lookup dans saas_users par email."""
|
||||||
|
return db.execute(
|
||||||
|
"SELECT * FROM saas_users WHERE email = ?", (email.lower().strip(),)
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def _org_to_dict(org) -> dict:
|
||||||
|
return {
|
||||||
|
"id": org["id"],
|
||||||
|
"owner_id": org["owner_id"],
|
||||||
|
"name": org["name"],
|
||||||
|
"max_members": org["max_members"],
|
||||||
|
"created_at": org["created_at"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _member_to_dict(m) -> dict:
|
||||||
|
return {
|
||||||
|
"id": m["id"],
|
||||||
|
"org_id": m["org_id"],
|
||||||
|
"user_id": m["user_id"],
|
||||||
|
"role": m["role"],
|
||||||
|
"invited_at": m["invited_at"],
|
||||||
|
"joined_at": m["joined_at"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# POST /api/v1/org — créer une organisation
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@org_bp.route("", methods=["POST"])
|
||||||
|
@jwt_required_middleware
|
||||||
|
@_require_pro
|
||||||
|
def create_org():
|
||||||
|
"""
|
||||||
|
Crée une organisation.
|
||||||
|
---
|
||||||
|
tags:
|
||||||
|
- Organisation
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
required: [name]
|
||||||
|
properties:
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
description: Nom de l'organisation (1-100 caractères)
|
||||||
|
responses:
|
||||||
|
201:
|
||||||
|
description: Organisation créée
|
||||||
|
400:
|
||||||
|
description: Paramètre manquant ou invalide
|
||||||
|
403:
|
||||||
|
description: Plan insuffisant
|
||||||
|
409:
|
||||||
|
description: L'utilisateur possède déjà une organisation
|
||||||
|
"""
|
||||||
|
user = request.current_user
|
||||||
|
owner_id = user["id"]
|
||||||
|
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
name = (data.get("name") or "").strip()
|
||||||
|
if not name or len(name) > 100:
|
||||||
|
return jsonify({"error": "Le nom est requis (1-100 caractères)"}), 400
|
||||||
|
|
||||||
|
db = get_db()
|
||||||
|
try:
|
||||||
|
# 1 org max par owner
|
||||||
|
existing = _get_org_by_owner(db, owner_id)
|
||||||
|
if existing:
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": "Vous possédez déjà une organisation",
|
||||||
|
"org_id": existing["id"],
|
||||||
|
}
|
||||||
|
), 409
|
||||||
|
|
||||||
|
org_id = secrets.token_hex(16)
|
||||||
|
now = datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO organizations (id, owner_id, name, max_members, created_at) "
|
||||||
|
"VALUES (?, ?, ?, ?, ?)",
|
||||||
|
(org_id, owner_id, name, MAX_MEMBERS, now),
|
||||||
|
)
|
||||||
|
# Ajouter l'owner comme premier membre avec rôle 'owner'
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO org_members (org_id, user_id, role, invited_at, joined_at) "
|
||||||
|
"VALUES (?, ?, 'owner', ?, ?)",
|
||||||
|
(org_id, owner_id, now, now),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
org = _get_org_by_id(db, org_id)
|
||||||
|
logger.info("Org créée: %s par user %s", org_id, owner_id)
|
||||||
|
return jsonify({"org": _org_to_dict(org)}), 201
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
db.rollback()
|
||||||
|
logger.error("create_org error: %s", e)
|
||||||
|
return jsonify({"error": "Erreur interne"}), 500
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# GET /api/v1/org — infos org courante
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@org_bp.route("", methods=["GET"])
|
||||||
|
@jwt_required_middleware
|
||||||
|
@_require_pro
|
||||||
|
def get_org():
|
||||||
|
"""
|
||||||
|
Retourne l'organisation dont l'utilisateur est owner ou membre.
|
||||||
|
---
|
||||||
|
tags:
|
||||||
|
- Organisation
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
responses:
|
||||||
|
200:
|
||||||
|
description: Infos de l'organisation
|
||||||
|
404:
|
||||||
|
description: Aucune organisation trouvée
|
||||||
|
"""
|
||||||
|
user = request.current_user
|
||||||
|
db = get_db()
|
||||||
|
try:
|
||||||
|
org = _get_org_by_owner(db, user["id"]) or _get_member_org(db, user["id"])
|
||||||
|
if not org:
|
||||||
|
return jsonify({"error": "Aucune organisation trouvée"}), 404
|
||||||
|
|
||||||
|
member_count = _count_org_members(db, org["id"])
|
||||||
|
result = _org_to_dict(org)
|
||||||
|
result["member_count"] = member_count
|
||||||
|
return jsonify({"org": result}), 200
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# DELETE /api/v1/org — supprimer l'organisation
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@org_bp.route("", methods=["DELETE"])
|
||||||
|
@jwt_required_middleware
|
||||||
|
@_require_pro
|
||||||
|
def delete_org():
|
||||||
|
"""
|
||||||
|
Supprime l'organisation (owner uniquement).
|
||||||
|
---
|
||||||
|
tags:
|
||||||
|
- Organisation
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
responses:
|
||||||
|
200:
|
||||||
|
description: Organisation supprimée
|
||||||
|
403:
|
||||||
|
description: Seul l'owner peut supprimer l'organisation
|
||||||
|
404:
|
||||||
|
description: Organisation introuvable
|
||||||
|
"""
|
||||||
|
user = request.current_user
|
||||||
|
db = get_db()
|
||||||
|
try:
|
||||||
|
org = _get_org_by_owner(db, user["id"])
|
||||||
|
if not org:
|
||||||
|
return jsonify({"error": "Vous n'êtes pas owner d'une organisation"}), 403
|
||||||
|
|
||||||
|
# CASCADE supprime org_members automatiquement (FK ON DELETE CASCADE)
|
||||||
|
db.execute("DELETE FROM organizations WHERE id = ?", (org["id"],))
|
||||||
|
db.commit()
|
||||||
|
logger.info("Org %s supprimée par user %s", org["id"], user["id"])
|
||||||
|
return jsonify({"ok": True, "deleted_org_id": org["id"]}), 200
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
db.rollback()
|
||||||
|
logger.error("delete_org error: %s", e)
|
||||||
|
return jsonify({"error": "Erreur interne"}), 500
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# POST /api/v1/org/invite — inviter un membre par email
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@org_bp.route("/invite", methods=["POST"])
|
||||||
|
@jwt_required_middleware
|
||||||
|
@_require_pro
|
||||||
|
def invite_member():
|
||||||
|
"""
|
||||||
|
Invite un utilisateur dans l'organisation par email (owner uniquement).
|
||||||
|
Limite : 5 membres totaux (owner inclus).
|
||||||
|
---
|
||||||
|
tags:
|
||||||
|
- Organisation
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
required: [email]
|
||||||
|
properties:
|
||||||
|
email:
|
||||||
|
type: string
|
||||||
|
description: Email de l'utilisateur à inviter
|
||||||
|
responses:
|
||||||
|
201:
|
||||||
|
description: Membre ajouté
|
||||||
|
400:
|
||||||
|
description: Paramètre manquant ou invalide
|
||||||
|
403:
|
||||||
|
description: Seul l'owner peut inviter / limite de membres atteinte
|
||||||
|
404:
|
||||||
|
description: Utilisateur introuvable ou organisation inexistante
|
||||||
|
409:
|
||||||
|
description: L'utilisateur est déjà membre
|
||||||
|
"""
|
||||||
|
user = request.current_user
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
email = (data.get("email") or "").strip().lower()
|
||||||
|
|
||||||
|
if not email or "@" not in email:
|
||||||
|
return jsonify({"error": "Email invalide"}), 400
|
||||||
|
|
||||||
|
db = get_db()
|
||||||
|
try:
|
||||||
|
# Vérifier que l'appelant est bien owner d'une org
|
||||||
|
org = _get_org_by_owner(db, user["id"])
|
||||||
|
if not org:
|
||||||
|
return jsonify({"error": "Vous n'êtes pas owner d'une organisation"}), 403
|
||||||
|
|
||||||
|
# Vérifier la limite de membres
|
||||||
|
current_count = _count_org_members(db, org["id"])
|
||||||
|
if current_count >= org["max_members"]:
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": f"Limite de {org['max_members']} membres atteinte",
|
||||||
|
"current_count": current_count,
|
||||||
|
}
|
||||||
|
), 403
|
||||||
|
|
||||||
|
# Résoudre l'utilisateur cible
|
||||||
|
target_user = _get_user_by_email(db, email)
|
||||||
|
if not target_user:
|
||||||
|
return jsonify({"error": "Utilisateur introuvable avec cet email"}), 404
|
||||||
|
|
||||||
|
target_id = target_user["id"]
|
||||||
|
|
||||||
|
# Vérifier que l'utilisateur n'est pas déjà membre de CETTE org
|
||||||
|
existing_member = db.execute(
|
||||||
|
"SELECT id FROM org_members WHERE org_id = ? AND user_id = ?",
|
||||||
|
(org["id"], target_id),
|
||||||
|
).fetchone()
|
||||||
|
if existing_member:
|
||||||
|
return jsonify(
|
||||||
|
{"error": "Cet utilisateur est déjà membre de l'organisation"}
|
||||||
|
), 409
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc).isoformat()
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO org_members (org_id, user_id, role, invited_at, joined_at) "
|
||||||
|
"VALUES (?, ?, 'member', ?, ?)",
|
||||||
|
(org["id"], target_id, now, now),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
member_row = db.execute(
|
||||||
|
"SELECT * FROM org_members WHERE org_id = ? AND user_id = ?",
|
||||||
|
(org["id"], target_id),
|
||||||
|
).fetchone()
|
||||||
|
logger.info(
|
||||||
|
"User %s invité dans org %s par %s", target_id, org["id"], user["id"]
|
||||||
|
)
|
||||||
|
return jsonify({"member": _member_to_dict(member_row)}), 201
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
db.rollback()
|
||||||
|
logger.error("invite_member error: %s", e)
|
||||||
|
return jsonify({"error": "Erreur interne"}), 500
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# GET /api/v1/org/members — liste des membres
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@org_bp.route("/members", methods=["GET"])
|
||||||
|
@jwt_required_middleware
|
||||||
|
@_require_pro
|
||||||
|
def list_members():
|
||||||
|
"""
|
||||||
|
Liste les membres de l'organisation courante.
|
||||||
|
---
|
||||||
|
tags:
|
||||||
|
- Organisation
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
responses:
|
||||||
|
200:
|
||||||
|
description: Liste des membres
|
||||||
|
404:
|
||||||
|
description: Organisation introuvable
|
||||||
|
"""
|
||||||
|
user = request.current_user
|
||||||
|
db = get_db()
|
||||||
|
try:
|
||||||
|
org = _get_org_by_owner(db, user["id"]) or _get_member_org(db, user["id"])
|
||||||
|
if not org:
|
||||||
|
return jsonify({"error": "Aucune organisation trouvée"}), 404
|
||||||
|
|
||||||
|
members = db.execute(
|
||||||
|
"SELECT m.*, u.email, u.firstname, u.lastname "
|
||||||
|
"FROM org_members m "
|
||||||
|
"LEFT JOIN saas_users u ON u.id = m.user_id "
|
||||||
|
"WHERE m.org_id = ? "
|
||||||
|
"ORDER BY m.invited_at ASC",
|
||||||
|
(org["id"],),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for m in members:
|
||||||
|
d = _member_to_dict(m)
|
||||||
|
d["email"] = m["email"]
|
||||||
|
d["firstname"] = m["firstname"] or ""
|
||||||
|
d["lastname"] = m["lastname"] or ""
|
||||||
|
result.append(d)
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"org_id": org["id"],
|
||||||
|
"members": result,
|
||||||
|
"count": len(result),
|
||||||
|
"max_members": org["max_members"],
|
||||||
|
}
|
||||||
|
), 200
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# DELETE /api/v1/org/members/<user_id> — retirer un membre
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@org_bp.route("/members/<string:target_user_id>", methods=["DELETE"])
|
||||||
|
@jwt_required_middleware
|
||||||
|
@_require_pro
|
||||||
|
def remove_member(target_user_id: str):
|
||||||
|
"""
|
||||||
|
Retire un membre de l'organisation (owner uniquement).
|
||||||
|
L'owner ne peut pas se retirer lui-même.
|
||||||
|
---
|
||||||
|
tags:
|
||||||
|
- Organisation
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
parameters:
|
||||||
|
- in: path
|
||||||
|
name: user_id
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
description: ID de l'utilisateur à retirer
|
||||||
|
responses:
|
||||||
|
200:
|
||||||
|
description: Membre retiré
|
||||||
|
400:
|
||||||
|
description: Tentative de retirer l'owner lui-même
|
||||||
|
403:
|
||||||
|
description: Seul l'owner peut retirer des membres
|
||||||
|
404:
|
||||||
|
description: Membre ou organisation introuvable
|
||||||
|
"""
|
||||||
|
user = request.current_user
|
||||||
|
db = get_db()
|
||||||
|
try:
|
||||||
|
org = _get_org_by_owner(db, user["id"])
|
||||||
|
if not org:
|
||||||
|
return jsonify({"error": "Vous n'êtes pas owner d'une organisation"}), 403
|
||||||
|
|
||||||
|
# L'owner ne peut pas se retirer lui-même (utiliser DELETE /api/v1/org à la place)
|
||||||
|
if target_user_id == user["id"]:
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"error": "L'owner ne peut pas se retirer lui-même. "
|
||||||
|
"Utilisez DELETE /api/v1/org pour supprimer l'organisation."
|
||||||
|
}
|
||||||
|
), 400
|
||||||
|
|
||||||
|
member = db.execute(
|
||||||
|
"SELECT * FROM org_members WHERE org_id = ? AND user_id = ?",
|
||||||
|
(org["id"], target_user_id),
|
||||||
|
).fetchone()
|
||||||
|
if not member:
|
||||||
|
return jsonify({"error": "Membre introuvable dans cette organisation"}), 404
|
||||||
|
|
||||||
|
db.execute(
|
||||||
|
"DELETE FROM org_members WHERE org_id = ? AND user_id = ?",
|
||||||
|
(org["id"], target_user_id),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
logger.info(
|
||||||
|
"User %s retiré de l'org %s par %s", target_user_id, org["id"], user["id"]
|
||||||
|
)
|
||||||
|
return jsonify({"ok": True, "removed_user_id": target_user_id}), 200
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
db.rollback()
|
||||||
|
logger.error("remove_member error: %s", e)
|
||||||
|
return jsonify({"error": "Erreur interne"}), 500
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
# On-import : migration idempotente
|
||||||
|
# ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
try:
|
||||||
|
migrate_org_tables()
|
||||||
|
except Exception as _e:
|
||||||
|
logger.warning("org_db migration skipped (test env?): %s", _e)
|
||||||
@@ -22,8 +22,14 @@ from auth import jwt_required_middleware, plan_required, free_daily_limit_check
|
|||||||
predictions_bp = Blueprint("v1_predictions", __name__, url_prefix="/api/v1/predictions")
|
predictions_bp = Blueprint("v1_predictions", __name__, url_prefix="/api/v1/predictions")
|
||||||
|
|
||||||
|
|
||||||
def _fetch_ml_predictions(conn, date: str, limit: int = None, offset: int = 0):
|
def _fetch_ml_predictions(
|
||||||
"""Shared helper — returns rows from ml_predictions_cache."""
|
conn, date: str, limit: int = None, offset: int = 0, include_weather: bool = False
|
||||||
|
):
|
||||||
|
"""Shared helper — returns rows from ml_predictions_cache.
|
||||||
|
|
||||||
|
include_weather=True adds terrain_condition and weather_impact columns
|
||||||
|
via LEFT JOIN on pmu_meteo (premium routes only).
|
||||||
|
"""
|
||||||
if not table_exists(conn, "ml_predictions_cache"):
|
if not table_exists(conn, "ml_predictions_cache"):
|
||||||
return [], 0
|
return [], 0
|
||||||
|
|
||||||
@@ -33,13 +39,35 @@ def _fetch_ml_predictions(conn, date: str, limit: int = None, offset: int = 0):
|
|||||||
).fetchone()
|
).fetchone()
|
||||||
total = count_row["cnt"] if count_row else 0
|
total = count_row["cnt"] if count_row else 0
|
||||||
|
|
||||||
sql = """SELECT
|
if (
|
||||||
race_label, hippodrome, discipline, distance, heure,
|
include_weather
|
||||||
horse_name, horse_number, odds, prob_top1, prob_top3,
|
and table_exists(conn, "pmu_meteo")
|
||||||
ml_score, recommendation, is_value_bet, risque_label, risque_score
|
and table_exists(conn, "pmu_courses")
|
||||||
FROM ml_predictions_cache
|
):
|
||||||
WHERE date = ?
|
sql = """SELECT
|
||||||
ORDER BY ml_score DESC"""
|
m.race_label, m.hippodrome, m.discipline, m.distance, m.heure,
|
||||||
|
m.horse_name, m.horse_number, m.odds, m.prob_top1, m.prob_top3,
|
||||||
|
m.ml_score, m.recommendation, m.is_value_bet, m.risque_label, m.risque_score,
|
||||||
|
c.penetrometre_intitule,
|
||||||
|
mt.nebulositecode, mt.nebulosite_court, mt.temperature, mt.force_vent
|
||||||
|
FROM ml_predictions_cache m
|
||||||
|
LEFT JOIN pmu_courses c
|
||||||
|
ON c.date_programme = m.date
|
||||||
|
AND c.num_reunion = m.num_reunion
|
||||||
|
AND c.num_course = m.num_course
|
||||||
|
LEFT JOIN pmu_meteo mt
|
||||||
|
ON mt.date_programme = m.date
|
||||||
|
AND mt.num_reunion = m.num_reunion
|
||||||
|
WHERE m.date = ?
|
||||||
|
ORDER BY m.ml_score DESC"""
|
||||||
|
else:
|
||||||
|
sql = """SELECT
|
||||||
|
race_label, hippodrome, discipline, distance, heure,
|
||||||
|
horse_name, horse_number, odds, prob_top1, prob_top3,
|
||||||
|
ml_score, recommendation, is_value_bet, risque_label, risque_score
|
||||||
|
FROM ml_predictions_cache
|
||||||
|
WHERE date = ?
|
||||||
|
ORDER BY ml_score DESC"""
|
||||||
params = [date]
|
params = [date]
|
||||||
|
|
||||||
if limit is not None:
|
if limit is not None:
|
||||||
@@ -47,7 +75,42 @@ def _fetch_ml_predictions(conn, date: str, limit: int = None, offset: int = 0):
|
|||||||
params += [limit, offset]
|
params += [limit, offset]
|
||||||
|
|
||||||
rows = conn.execute(sql, params).fetchall()
|
rows = conn.execute(sql, params).fetchall()
|
||||||
return [dict(r) for r in rows], total
|
|
||||||
|
results = []
|
||||||
|
for r in rows:
|
||||||
|
row_dict = dict(r)
|
||||||
|
if include_weather:
|
||||||
|
# Compute derived fields from raw columns
|
||||||
|
penetrometre = row_dict.pop("penetrometre_intitule", None) or ""
|
||||||
|
# Import inline to avoid circular dependency at module level
|
||||||
|
from scoring_v2 import get_terrain_condition, compute_weather_impact
|
||||||
|
|
||||||
|
terrain_condition = (
|
||||||
|
get_terrain_condition(penetrometre) if penetrometre else "inconnu"
|
||||||
|
)
|
||||||
|
weather_data = None
|
||||||
|
if (
|
||||||
|
row_dict.get("nebulositecode") is not None
|
||||||
|
or row_dict.get("temperature") is not None
|
||||||
|
):
|
||||||
|
weather_data = {
|
||||||
|
"nebulositecode": row_dict.pop("nebulositecode", None),
|
||||||
|
"nebulosite_court": row_dict.pop("nebulosite_court", None),
|
||||||
|
"temperature": row_dict.pop("temperature", None),
|
||||||
|
"force_vent": row_dict.pop("force_vent", None),
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# Remove raw meteo columns even if NULL
|
||||||
|
row_dict.pop("nebulositecode", None)
|
||||||
|
row_dict.pop("nebulosite_court", None)
|
||||||
|
row_dict.pop("temperature", None)
|
||||||
|
row_dict.pop("force_vent", None)
|
||||||
|
weather_impact = compute_weather_impact(weather_data, terrain_condition)
|
||||||
|
row_dict["terrain_condition"] = terrain_condition
|
||||||
|
row_dict["weather_impact"] = weather_impact
|
||||||
|
results.append(row_dict)
|
||||||
|
|
||||||
|
return results, total
|
||||||
|
|
||||||
|
|
||||||
# ──────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────
|
||||||
@@ -145,7 +208,7 @@ def predictions_all():
|
|||||||
conn = get_db()
|
conn = get_db()
|
||||||
try:
|
try:
|
||||||
predictions, total = _fetch_ml_predictions(
|
predictions, total = _fetch_ml_predictions(
|
||||||
conn, date_param, limit=limit, offset=offset
|
conn, date_param, limit=limit, offset=offset, include_weather=True
|
||||||
)
|
)
|
||||||
pagination = paginate_query(predictions, total, limit, offset)
|
pagination = paginate_query(predictions, total, limit, offset)
|
||||||
|
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ def valuebets():
|
|||||||
default: 0
|
default: 0
|
||||||
responses:
|
responses:
|
||||||
200:
|
200:
|
||||||
description: Value bets du jour
|
description: Value bets du jour avec météo et terrain (HRT-83)
|
||||||
401:
|
401:
|
||||||
description: Token invalide
|
description: Token invalide
|
||||||
403:
|
403:
|
||||||
@@ -69,7 +69,7 @@ def valuebets():
|
|||||||
|
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
try:
|
try:
|
||||||
rows = []
|
rows_raw = []
|
||||||
total = 0
|
total = 0
|
||||||
|
|
||||||
if table_exists(conn, "ml_predictions_cache"):
|
if table_exists(conn, "ml_predictions_cache"):
|
||||||
@@ -81,18 +81,73 @@ def valuebets():
|
|||||||
).fetchone()
|
).fetchone()
|
||||||
total = count_row["cnt"] if count_row else 0
|
total = count_row["cnt"] if count_row else 0
|
||||||
|
|
||||||
rows = conn.execute(
|
# LEFT JOIN pmu_courses (terrain) + pmu_meteo (météo) — HRT-83
|
||||||
"""SELECT race_label, hippodrome, discipline, distance, heure,
|
has_courses = table_exists(conn, "pmu_courses")
|
||||||
horse_name, horse_number, odds, prob_top1, prob_top3,
|
has_meteo = table_exists(conn, "pmu_meteo")
|
||||||
ml_score, recommendation, risque_label, risque_score
|
|
||||||
FROM ml_predictions_cache
|
if has_courses and has_meteo:
|
||||||
WHERE date = ? AND is_value_bet = 1 AND odds >= ?
|
rows_raw = conn.execute(
|
||||||
ORDER BY ml_score DESC
|
"""SELECT m.race_label, m.hippodrome, m.discipline, m.distance, m.heure,
|
||||||
LIMIT ? OFFSET ?""",
|
m.horse_name, m.horse_number, m.odds, m.prob_top1, m.prob_top3,
|
||||||
(date_param, min_odds, limit, offset),
|
m.ml_score, m.recommendation, m.risque_label, m.risque_score,
|
||||||
).fetchall()
|
c.penetrometre_intitule,
|
||||||
|
mt.nebulositecode, mt.nebulosite_court,
|
||||||
|
mt.temperature, mt.force_vent
|
||||||
|
FROM ml_predictions_cache m
|
||||||
|
LEFT JOIN pmu_courses c
|
||||||
|
ON c.date_programme = m.date
|
||||||
|
AND c.num_reunion = m.num_reunion
|
||||||
|
AND c.num_course = m.num_course
|
||||||
|
LEFT JOIN pmu_meteo mt
|
||||||
|
ON mt.date_programme = m.date
|
||||||
|
AND mt.num_reunion = m.num_reunion
|
||||||
|
WHERE m.date = ? AND m.is_value_bet = 1 AND m.odds >= ?
|
||||||
|
ORDER BY m.ml_score DESC
|
||||||
|
LIMIT ? OFFSET ?""",
|
||||||
|
(date_param, min_odds, limit, offset),
|
||||||
|
).fetchall()
|
||||||
|
else:
|
||||||
|
rows_raw = conn.execute(
|
||||||
|
"""SELECT race_label, hippodrome, discipline, distance, heure,
|
||||||
|
horse_name, horse_number, odds, prob_top1, prob_top3,
|
||||||
|
ml_score, recommendation, risque_label, risque_score
|
||||||
|
FROM ml_predictions_cache
|
||||||
|
WHERE date = ? AND is_value_bet = 1 AND odds >= ?
|
||||||
|
ORDER BY ml_score DESC
|
||||||
|
LIMIT ? OFFSET ?""",
|
||||||
|
(date_param, min_odds, limit, offset),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
from scoring_v2 import get_terrain_condition, compute_weather_impact
|
||||||
|
|
||||||
|
valuebets_list = []
|
||||||
|
for r in rows_raw:
|
||||||
|
row_dict = dict(r)
|
||||||
|
penetrometre = row_dict.pop("penetrometre_intitule", None) or ""
|
||||||
|
terrain_condition = (
|
||||||
|
get_terrain_condition(penetrometre) if penetrometre else "inconnu"
|
||||||
|
)
|
||||||
|
weather_data = None
|
||||||
|
if (
|
||||||
|
row_dict.get("nebulositecode") is not None
|
||||||
|
or row_dict.get("temperature") is not None
|
||||||
|
):
|
||||||
|
weather_data = {
|
||||||
|
"nebulositecode": row_dict.pop("nebulositecode", None),
|
||||||
|
"nebulosite_court": row_dict.pop("nebulosite_court", None),
|
||||||
|
"temperature": row_dict.pop("temperature", None),
|
||||||
|
"force_vent": row_dict.pop("force_vent", None),
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
row_dict.pop("nebulositecode", None)
|
||||||
|
row_dict.pop("nebulosite_court", None)
|
||||||
|
row_dict.pop("temperature", None)
|
||||||
|
row_dict.pop("force_vent", None)
|
||||||
|
weather_impact = compute_weather_impact(weather_data, terrain_condition)
|
||||||
|
row_dict["terrain_condition"] = terrain_condition
|
||||||
|
row_dict["weather_impact"] = weather_impact
|
||||||
|
valuebets_list.append(row_dict)
|
||||||
|
|
||||||
valuebets_list = [dict(r) for r in rows]
|
|
||||||
pagination = paginate_query(valuebets_list, total, limit, offset)
|
pagination = paginate_query(valuebets_list, total, limit, offset)
|
||||||
|
|
||||||
return jsonify(
|
return jsonify(
|
||||||
|
|||||||
600
ml_feedback_saas.py
Normal file
600
ml_feedback_saas.py
Normal file
@@ -0,0 +1,600 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
ml_feedback_saas.py — Feedback loop ML pour turf_saas.
|
||||||
|
Enregistre les paris virtuels XGBoost depuis ml_predictions_cache
|
||||||
|
et met à jour les résultats/dividendes depuis pmu_partants + pmu_rapports.
|
||||||
|
|
||||||
|
DB cible : /home/h3r7/turf_saas/turf_saas.db
|
||||||
|
|
||||||
|
Stratégies :
|
||||||
|
A) xgboost_sg : simple_gagnant — top1 ML par course, ml_score >= 70, mise 1€
|
||||||
|
B) xgboost_value : simple_gagnant — is_value_bet = 1, mise 1€
|
||||||
|
C) xgboost_sp : simple_place — top1 ML par course, ml_score >= 50, mise 1€
|
||||||
|
D) xgboost_2sur4 : deux_sur_quatre — top4 ML par course, 6 combos x 1€ = mise 6€
|
||||||
|
|
||||||
|
Usage :
|
||||||
|
python3 ml_feedback_saas.py # Traite aujourd'hui
|
||||||
|
python3 ml_feedback_saas.py --backfill 2026-04-25
|
||||||
|
python3 ml_feedback_saas.py --date 2026-04-25
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
DB_PATH = "/home/h3r7/turf_saas/turf_saas.db"
|
||||||
|
|
||||||
|
os.makedirs("/home/h3r7/turf_saas/logs", exist_ok=True)
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [ml_feedback_saas] %(levelname)s %(message)s",
|
||||||
|
handlers=[
|
||||||
|
logging.FileHandler("/home/h3r7/turf_saas/logs/ml_feedback_saas.log"),
|
||||||
|
logging.StreamHandler(),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# UTILITAIRES
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def pari_existe(cursor, date, num_reunion, num_course, numero1, type_pari, source_reco):
|
||||||
|
"""Vérifie si un pari identique existe déjà (idempotence)."""
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT id FROM paris
|
||||||
|
WHERE date_course = ? AND source_reco = ?
|
||||||
|
AND type_pari = ? AND numero1 = ?
|
||||||
|
AND race_label = ?
|
||||||
|
""",
|
||||||
|
(date, source_reco, type_pari, numero1, f"R{num_reunion}C{num_course}"),
|
||||||
|
)
|
||||||
|
return cursor.fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def pari_2sur4_existe(cursor, date, num_reunion, num_course, source_reco):
|
||||||
|
"""Vérifie si un pari 2sur4 existe déjà pour cette course."""
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT id FROM paris
|
||||||
|
WHERE date_course = ? AND source_reco = ?
|
||||||
|
AND race_label = ?
|
||||||
|
""",
|
||||||
|
(date, source_reco, f"R{num_reunion}C{num_course}"),
|
||||||
|
)
|
||||||
|
return cursor.fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def get_top_ml_par_course(cursor, date, n=4, min_score=0):
|
||||||
|
"""Retourne les n meilleurs chevaux ML par course pour une date."""
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT num_reunion, num_course, horse_name, horse_number,
|
||||||
|
ml_score, odds, recommendation, is_value_bet,
|
||||||
|
race_label, race_name, hippodrome, heure,
|
||||||
|
discipline, distance
|
||||||
|
FROM ml_predictions_cache
|
||||||
|
WHERE date = ?
|
||||||
|
AND ml_score >= ?
|
||||||
|
ORDER BY num_reunion, num_course, ml_score DESC
|
||||||
|
""",
|
||||||
|
(date, min_score),
|
||||||
|
)
|
||||||
|
rows = cursor.fetchall()
|
||||||
|
|
||||||
|
courses = {}
|
||||||
|
for r in rows:
|
||||||
|
key = (r["num_reunion"], r["num_course"])
|
||||||
|
if key not in courses:
|
||||||
|
courses[key] = []
|
||||||
|
if len(courses[key]) < n:
|
||||||
|
courses[key].append(dict(r))
|
||||||
|
return courses
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# STRATÉGIE A — Simple Gagnant top1 ML (score >= 70)
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def save_ml_paris_sg(conn, date):
|
||||||
|
"""Insère 1 pari simple_gagnant par course : top1 ML avec ml_score >= 70."""
|
||||||
|
cursor = conn.cursor()
|
||||||
|
courses = get_top_ml_par_course(cursor, date, n=1, min_score=70)
|
||||||
|
inseres = 0
|
||||||
|
|
||||||
|
for (num_reunion, num_course), chevaux in courses.items():
|
||||||
|
cheval = chevaux[0]
|
||||||
|
if pari_existe(
|
||||||
|
cursor,
|
||||||
|
date,
|
||||||
|
num_reunion,
|
||||||
|
num_course,
|
||||||
|
cheval["horse_number"],
|
||||||
|
"simple_gagnant",
|
||||||
|
"xgboost_sg",
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO paris
|
||||||
|
(date_pari, date_course, race_name, race_label, hippodrome,
|
||||||
|
type_pari, chevaux, cheval1, numero1, cote, mise,
|
||||||
|
statut, gain, source_reco, model_source)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 'simple_gagnant', ?, ?, ?, ?, 1.0,
|
||||||
|
'EN_ATTENTE', 0.0, 'xgboost_sg', 'xgboost_v1')
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
date,
|
||||||
|
date,
|
||||||
|
cheval.get("race_name") or "",
|
||||||
|
f"R{num_reunion}C{num_course}",
|
||||||
|
cheval.get("hippodrome") or "",
|
||||||
|
cheval["horse_name"],
|
||||||
|
cheval["horse_name"],
|
||||||
|
cheval["horse_number"],
|
||||||
|
cheval["odds"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
inseres += 1
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
log.info(f"[SG] {date} → {inseres} paris simple_gagnant insérés (score>=70)")
|
||||||
|
return inseres
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# STRATÉGIE B — Value Bet (is_value_bet = 1)
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def save_ml_paris_value(conn, date):
|
||||||
|
"""Insère 1 pari simple_gagnant pour chaque cheval is_value_bet=1."""
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT num_reunion, num_course, horse_name, horse_number,
|
||||||
|
ml_score, odds, race_label, race_name, hippodrome
|
||||||
|
FROM ml_predictions_cache
|
||||||
|
WHERE date = ? AND is_value_bet = 1
|
||||||
|
ORDER BY num_reunion, num_course, ml_score DESC
|
||||||
|
""",
|
||||||
|
(date,),
|
||||||
|
)
|
||||||
|
rows = [dict(r) for r in cursor.fetchall()]
|
||||||
|
inseres = 0
|
||||||
|
|
||||||
|
for r in rows:
|
||||||
|
if pari_existe(
|
||||||
|
cursor,
|
||||||
|
date,
|
||||||
|
r["num_reunion"],
|
||||||
|
r["num_course"],
|
||||||
|
r["horse_number"],
|
||||||
|
"simple_gagnant",
|
||||||
|
"xgboost_value",
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO paris
|
||||||
|
(date_pari, date_course, race_name, race_label, hippodrome,
|
||||||
|
type_pari, chevaux, cheval1, numero1, cote, mise,
|
||||||
|
statut, gain, source_reco, model_source)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 'simple_gagnant', ?, ?, ?, ?, 1.0,
|
||||||
|
'EN_ATTENTE', 0.0, 'xgboost_value', 'xgboost_v1')
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
date,
|
||||||
|
date,
|
||||||
|
r.get("race_name") or "",
|
||||||
|
r.get("race_label") or f"R{r['num_reunion']}C{r['num_course']}",
|
||||||
|
r.get("hippodrome") or "",
|
||||||
|
r["horse_name"],
|
||||||
|
r["horse_name"],
|
||||||
|
r["horse_number"],
|
||||||
|
r["odds"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
inseres += 1
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
log.info(f"[VALUE] {date} → {inseres} paris value_bet insérés")
|
||||||
|
return inseres
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# STRATÉGIE C — Simple Placé top1 ML (score >= 50)
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def save_ml_paris_sp(conn, date):
|
||||||
|
"""Insère 1 pari simple_place par course : top1 ML avec ml_score >= 50."""
|
||||||
|
cursor = conn.cursor()
|
||||||
|
courses = get_top_ml_par_course(cursor, date, n=1, min_score=50)
|
||||||
|
inseres = 0
|
||||||
|
|
||||||
|
for (num_reunion, num_course), chevaux in courses.items():
|
||||||
|
cheval = chevaux[0]
|
||||||
|
if pari_existe(
|
||||||
|
cursor,
|
||||||
|
date,
|
||||||
|
num_reunion,
|
||||||
|
num_course,
|
||||||
|
cheval["horse_number"],
|
||||||
|
"simple_place",
|
||||||
|
"xgboost_sp",
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO paris
|
||||||
|
(date_pari, date_course, race_name, race_label, hippodrome,
|
||||||
|
type_pari, chevaux, cheval1, numero1, cote, mise,
|
||||||
|
statut, gain, source_reco, model_source)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 'simple_place', ?, ?, ?, ?, 1.0,
|
||||||
|
'EN_ATTENTE', 0.0, 'xgboost_sp', 'xgboost_v1')
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
date,
|
||||||
|
date,
|
||||||
|
cheval.get("race_name") or "",
|
||||||
|
f"R{num_reunion}C{num_course}",
|
||||||
|
cheval.get("hippodrome") or "",
|
||||||
|
cheval["horse_name"],
|
||||||
|
cheval["horse_name"],
|
||||||
|
cheval["horse_number"],
|
||||||
|
cheval["odds"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
inseres += 1
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
log.info(f"[SP] {date} → {inseres} paris simple_place insérés (score>=50)")
|
||||||
|
return inseres
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# STRATÉGIE D — 2sur4 top4 ML (6 combinaisons x 1€)
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def save_ml_paris_2sur4(conn, date):
|
||||||
|
"""Insère 1 pari deux_sur_quatre par course : top4 ML, mise 6€."""
|
||||||
|
cursor = conn.cursor()
|
||||||
|
courses = get_top_ml_par_course(cursor, date, n=4, min_score=0)
|
||||||
|
inseres = 0
|
||||||
|
|
||||||
|
for (num_reunion, num_course), chevaux in courses.items():
|
||||||
|
if len(chevaux) < 4:
|
||||||
|
continue
|
||||||
|
if pari_2sur4_existe(cursor, date, num_reunion, num_course, "xgboost_2sur4"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
top4 = chevaux[:4]
|
||||||
|
nums = [str(c["horse_number"]) for c in top4]
|
||||||
|
noms = [c["horse_name"] for c in top4]
|
||||||
|
chevaux_str = "/".join(noms)
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO paris
|
||||||
|
(date_pari, date_course, race_name, race_label, hippodrome,
|
||||||
|
type_pari, chevaux, cheval1, numero1, cote, mise,
|
||||||
|
statut, gain, source_reco, model_source, commentaire)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 'deux_sur_quatre', ?, ?, ?, 0.0, 6.0,
|
||||||
|
'EN_ATTENTE', 0.0, 'xgboost_2sur4', 'xgboost_v1', ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
date,
|
||||||
|
date,
|
||||||
|
top4[0].get("race_name") or "",
|
||||||
|
f"R{num_reunion}C{num_course}",
|
||||||
|
top4[0].get("hippodrome") or "",
|
||||||
|
chevaux_str,
|
||||||
|
top4[0]["horse_name"],
|
||||||
|
top4[0]["horse_number"],
|
||||||
|
f"top4 ML: {'/'.join(nums)}",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
inseres += 1
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
log.info(f"[2S4] {date} → {inseres} paris deux_sur_quatre insérés")
|
||||||
|
return inseres
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# UPDATE RÉSULTATS + DIVIDENDES
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def update_ml_paris_results(conn, date):
|
||||||
|
"""
|
||||||
|
Met à jour statut + gain (dividende PMU réel) pour tous les paris ML EN_ATTENTE.
|
||||||
|
Sources: pmu_partants (ordre_arrivee) + pmu_rapports (dividende_euro).
|
||||||
|
"""
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, race_label, type_pari, numero1, chevaux, mise, source_reco, commentaire
|
||||||
|
FROM paris
|
||||||
|
WHERE date_course = ? AND statut = 'EN_ATTENTE'
|
||||||
|
AND source_reco LIKE 'xgboost%'
|
||||||
|
""",
|
||||||
|
(date,),
|
||||||
|
)
|
||||||
|
paris = [dict(r) for r in cursor.fetchall()]
|
||||||
|
|
||||||
|
if not paris:
|
||||||
|
log.info(f"[UPDATE] {date} → aucun pari ML EN_ATTENTE")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
maj = 0
|
||||||
|
for pari in paris:
|
||||||
|
pari_id = pari["id"]
|
||||||
|
race_label = pari["race_label"] or ""
|
||||||
|
type_pari = pari["type_pari"]
|
||||||
|
numero1 = pari["numero1"]
|
||||||
|
mise = pari["mise"]
|
||||||
|
|
||||||
|
# Extraire num_reunion / num_course depuis le race_label "R{r}C{c}"
|
||||||
|
try:
|
||||||
|
parts = race_label.replace("R", "").split("C")
|
||||||
|
num_reunion = int(parts[0])
|
||||||
|
num_course = int(parts[1])
|
||||||
|
except Exception:
|
||||||
|
log.warning(f"[UPDATE] race_label invalide : {race_label}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if type_pari == "simple_gagnant":
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT ordre_arrivee FROM pmu_partants
|
||||||
|
WHERE date_programme = ? AND num_reunion = ?
|
||||||
|
AND num_course = ? AND num_pmu = ?
|
||||||
|
""",
|
||||||
|
(date, num_reunion, num_course, numero1),
|
||||||
|
)
|
||||||
|
row = cursor.fetchone()
|
||||||
|
if not row or row["ordre_arrivee"] is None or row["ordre_arrivee"] == 0:
|
||||||
|
continue
|
||||||
|
|
||||||
|
gagne = row["ordre_arrivee"] == 1
|
||||||
|
gain = 0.0
|
||||||
|
if gagne:
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT dividende_euro FROM pmu_rapports
|
||||||
|
WHERE date_programme = ? AND num_reunion = ?
|
||||||
|
AND num_course = ? AND type_pari = 'SIMPLE_GAGNANT'
|
||||||
|
AND CAST(combinaison AS INTEGER) = ?
|
||||||
|
AND libelle NOT LIKE '%NP%'
|
||||||
|
""",
|
||||||
|
(date, num_reunion, num_course, numero1),
|
||||||
|
)
|
||||||
|
div = cursor.fetchone()
|
||||||
|
gain = div["dividende_euro"] if div and div["dividende_euro"] else 0.0
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"UPDATE paris SET statut=?, gain=? WHERE id=?",
|
||||||
|
("GAGNE" if gagne else "PERDU", gain, pari_id),
|
||||||
|
)
|
||||||
|
maj += 1
|
||||||
|
|
||||||
|
elif type_pari == "simple_place":
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT ordre_arrivee FROM pmu_partants
|
||||||
|
WHERE date_programme = ? AND num_reunion = ?
|
||||||
|
AND num_course = ? AND num_pmu = ?
|
||||||
|
""",
|
||||||
|
(date, num_reunion, num_course, numero1),
|
||||||
|
)
|
||||||
|
row = cursor.fetchone()
|
||||||
|
if not row or not row["ordre_arrivee"]:
|
||||||
|
continue
|
||||||
|
|
||||||
|
gagne = 1 <= row["ordre_arrivee"] <= 3
|
||||||
|
gain = 0.0
|
||||||
|
if gagne:
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT dividende_euro FROM pmu_rapports
|
||||||
|
WHERE date_programme = ? AND num_reunion = ?
|
||||||
|
AND num_course = ? AND type_pari = 'SIMPLE_PLACE'
|
||||||
|
AND CAST(combinaison AS INTEGER) = ?
|
||||||
|
AND libelle NOT LIKE '%NP%'
|
||||||
|
""",
|
||||||
|
(date, num_reunion, num_course, numero1),
|
||||||
|
)
|
||||||
|
div = cursor.fetchone()
|
||||||
|
gain = div["dividende_euro"] if div and div["dividende_euro"] else 0.0
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"UPDATE paris SET statut=?, gain=? WHERE id=?",
|
||||||
|
("GAGNE" if gagne else "PERDU", gain, pari_id),
|
||||||
|
)
|
||||||
|
maj += 1
|
||||||
|
|
||||||
|
elif type_pari == "deux_sur_quatre":
|
||||||
|
# Récupère les 4 numéros depuis commentaire "top4 ML: n1/n2/n3/n4"
|
||||||
|
try:
|
||||||
|
nums_str = (
|
||||||
|
pari["commentaire"].split(": ")[1]
|
||||||
|
if pari.get("commentaire")
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
nums_top4 = [int(n) for n in nums_str.split("/") if n.strip().isdigit()]
|
||||||
|
except Exception:
|
||||||
|
nums_top4 = []
|
||||||
|
|
||||||
|
if len(nums_top4) < 4:
|
||||||
|
# Fallback : reconstituer top4 depuis ml_predictions_cache
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT horse_number FROM ml_predictions_cache
|
||||||
|
WHERE date = ? AND num_reunion = ? AND num_course = ?
|
||||||
|
ORDER BY ml_score DESC LIMIT 4
|
||||||
|
""",
|
||||||
|
(date, num_reunion, num_course),
|
||||||
|
)
|
||||||
|
nums_top4 = [r["horse_number"] for r in cursor.fetchall()]
|
||||||
|
|
||||||
|
if len(nums_top4) < 2:
|
||||||
|
continue
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT combinaison, dividende_euro FROM pmu_rapports
|
||||||
|
WHERE date_programme = ? AND num_reunion = ?
|
||||||
|
AND num_course = ? AND type_pari = 'DEUX_SUR_QUATRE'
|
||||||
|
AND libelle NOT LIKE '%NP%'
|
||||||
|
""",
|
||||||
|
(date, num_reunion, num_course),
|
||||||
|
)
|
||||||
|
rapports = [dict(r) for r in cursor.fetchall()]
|
||||||
|
gain_total = 0.0
|
||||||
|
|
||||||
|
for rap in rapports:
|
||||||
|
try:
|
||||||
|
n1, n2 = [int(x) for x in rap["combinaison"].split("-")]
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if n1 in nums_top4 and n2 in nums_top4:
|
||||||
|
gain_total += rap["dividende_euro"]
|
||||||
|
|
||||||
|
gagne = gain_total > 0
|
||||||
|
cursor.execute(
|
||||||
|
"UPDATE paris SET statut=?, gain=? WHERE id=?",
|
||||||
|
("GAGNE" if gagne else "PERDU", round(gain_total, 2), pari_id),
|
||||||
|
)
|
||||||
|
maj += 1
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
log.info(f"[UPDATE] {date} → {maj}/{len(paris)} paris ML mis à jour")
|
||||||
|
return maj
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# STATS PAR STRATÉGIE
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def get_feedback_stats(conn, date_debut=None, date_fin=None):
|
||||||
|
"""Stats performances ML par stratégie (source_reco)."""
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute(
|
||||||
|
"""
|
||||||
|
SELECT source_reco,
|
||||||
|
COUNT(*) as n_paris,
|
||||||
|
SUM(CASE WHEN statut='GAGNE' THEN 1 ELSE 0 END) as n_gagne,
|
||||||
|
SUM(CASE WHEN statut='PERDU' THEN 1 ELSE 0 END) as n_perdu,
|
||||||
|
SUM(CASE WHEN statut='EN_ATTENTE' THEN 1 ELSE 0 END) as n_attente,
|
||||||
|
ROUND(100.0 * SUM(CASE WHEN statut='GAGNE' THEN 1 ELSE 0 END)
|
||||||
|
/ NULLIF(SUM(CASE WHEN statut IN ('GAGNE','PERDU') THEN 1 ELSE 0 END), 0), 1) as win_rate_pct,
|
||||||
|
ROUND(SUM(gain), 2) as gain_total,
|
||||||
|
ROUND(SUM(mise), 2) as mise_totale,
|
||||||
|
ROUND(SUM(gain) - SUM(mise), 2) as roi_net
|
||||||
|
FROM paris
|
||||||
|
WHERE source_reco LIKE 'xgboost%'
|
||||||
|
AND (:debut IS NULL OR date_course >= :debut)
|
||||||
|
AND (:fin IS NULL OR date_course <= :fin)
|
||||||
|
GROUP BY source_reco
|
||||||
|
ORDER BY source_reco
|
||||||
|
""",
|
||||||
|
{"debut": date_debut, "fin": date_fin},
|
||||||
|
)
|
||||||
|
return [dict(r) for r in cursor.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# PIPELINE COMPLET
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def run(date):
|
||||||
|
"""Enregistre les paris ML du jour + met à jour les résultats de J-1."""
|
||||||
|
conn = get_db()
|
||||||
|
log.info(f"=== ml_feedback_saas.run({date}) ===")
|
||||||
|
|
||||||
|
# 1. Enregistre les paris ML pour la date (depuis le cache du jour)
|
||||||
|
sg = save_ml_paris_sg(conn, date)
|
||||||
|
vb = save_ml_paris_value(conn, date)
|
||||||
|
sp = save_ml_paris_sp(conn, date)
|
||||||
|
s4 = save_ml_paris_2sur4(conn, date)
|
||||||
|
log.info(f"[SAVE] {date} → total insérés : SG={sg} VALUE={vb} SP={sp} 2S4={s4}")
|
||||||
|
|
||||||
|
# 2. Met à jour les résultats de J-1 (résultats PMU disponibles)
|
||||||
|
yesterday = (datetime.strptime(date, "%Y-%m-%d") - timedelta(days=1)).strftime(
|
||||||
|
"%Y-%m-%d"
|
||||||
|
)
|
||||||
|
maj = update_ml_paris_results(conn, yesterday)
|
||||||
|
log.info(f"[UPDATE] {yesterday} → {maj} paris mis à jour")
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
return {"inseres": {"sg": sg, "value": vb, "sp": sp, "2sur4": s4}, "maj": maj}
|
||||||
|
|
||||||
|
|
||||||
|
def backfill(date):
|
||||||
|
"""Backfill : insère ET met à jour les résultats pour une date passée."""
|
||||||
|
conn = get_db()
|
||||||
|
log.info(f"=== ml_feedback_saas.backfill({date}) ===")
|
||||||
|
|
||||||
|
sg = save_ml_paris_sg(conn, date)
|
||||||
|
vb = save_ml_paris_value(conn, date)
|
||||||
|
sp = save_ml_paris_sp(conn, date)
|
||||||
|
s4 = save_ml_paris_2sur4(conn, date)
|
||||||
|
log.info(f"[SAVE] {date} → SG={sg} VALUE={vb} SP={sp} 2S4={s4}")
|
||||||
|
|
||||||
|
maj = update_ml_paris_results(conn, date)
|
||||||
|
log.info(f"[UPDATE] {date} → {maj} paris mis à jour")
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
return sg + vb + sp + s4, maj
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
# MAIN
|
||||||
|
# ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if "--backfill" in sys.argv:
|
||||||
|
idx = sys.argv.index("--backfill")
|
||||||
|
date = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else None
|
||||||
|
if not date:
|
||||||
|
print("Usage: python3 ml_feedback_saas.py --backfill YYYY-MM-DD")
|
||||||
|
sys.exit(1)
|
||||||
|
inseres, maj = backfill(date)
|
||||||
|
print(f"Backfill {date} : {inseres} paris insérés, {maj} mis à jour")
|
||||||
|
|
||||||
|
elif "--date" in sys.argv:
|
||||||
|
idx = sys.argv.index("--date")
|
||||||
|
date = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else None
|
||||||
|
if not date:
|
||||||
|
print("Usage: python3 ml_feedback_saas.py --date YYYY-MM-DD")
|
||||||
|
sys.exit(1)
|
||||||
|
result = run(date)
|
||||||
|
total = sum(result["inseres"].values())
|
||||||
|
print(f"Run {date} : {total} paris insérés, {result['maj']} mis à jour")
|
||||||
|
|
||||||
|
else:
|
||||||
|
result = run(datetime.now().strftime("%Y-%m-%d"))
|
||||||
|
total = sum(result["inseres"].values())
|
||||||
|
print(f"Run today : {total} paris insérés, {result['maj']} mis à jour")
|
||||||
72
org_db.py
Normal file
72
org_db.py
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Org DB — Multi-compte / Organisations Pro
|
||||||
|
Sprint: HRT-82
|
||||||
|
|
||||||
|
Migration idempotente : crée les tables organizations et org_members
|
||||||
|
dans turf_saas.db si elles n'existent pas.
|
||||||
|
|
||||||
|
Run une seule fois :
|
||||||
|
./venv/bin/python org_db.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
|
||||||
|
DB_PATH = os.environ.get("TURF_SAAS_DB", "/home/h3r7/turf_saas/turf_saas.db")
|
||||||
|
logger = logging.getLogger("turf_saas.org_db")
|
||||||
|
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
conn = sqlite3.connect(DB_PATH)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
conn.execute("PRAGMA foreign_keys = ON")
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_org_tables():
|
||||||
|
"""
|
||||||
|
Migration idempotente : crée organizations + org_members.
|
||||||
|
|
||||||
|
- organizations : 1 org max par owner (enforced en Python + UNIQUE owner_id)
|
||||||
|
- org_members : max 5 membres totaux (owner inclus, enforced en Python)
|
||||||
|
- UNIQUE(org_id, user_id) empêche les doublons de membres
|
||||||
|
"""
|
||||||
|
conn = get_db()
|
||||||
|
c = conn.cursor()
|
||||||
|
|
||||||
|
c.executescript("""
|
||||||
|
CREATE TABLE IF NOT EXISTS organizations (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
owner_id TEXT NOT NULL UNIQUE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
max_members INTEGER NOT NULL DEFAULT 5,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS org_members (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
org_id TEXT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL DEFAULT 'member'
|
||||||
|
CHECK(role IN ('owner', 'member')),
|
||||||
|
invited_at DATETIME NOT NULL DEFAULT (datetime('now')),
|
||||||
|
joined_at DATETIME,
|
||||||
|
UNIQUE(org_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_org_owner ON organizations(owner_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_orgmem_org ON org_members(org_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_orgmem_user ON org_members(user_id);
|
||||||
|
""")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
logger.info("[org_db] Tables organizations + org_members créées/vérifiées.")
|
||||||
|
print("[org_db] Migration OK: organizations, org_members.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
migrate_org_tables()
|
||||||
@@ -268,15 +268,33 @@ try:
|
|||||||
@api_v1_bp.record_once
|
@api_v1_bp.record_once
|
||||||
def _init_jwt(state):
|
def _init_jwt(state):
|
||||||
app = state.app
|
app = state.app
|
||||||
if not app.config.get('JWT_SECRET_KEY'):
|
if not app.config.get("JWT_SECRET_KEY"):
|
||||||
import os
|
import os
|
||||||
app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY', 'turf-saas-secret-key-change-in-prod')
|
|
||||||
if 'flask_jwt_extended' not in app.extensions:
|
app.config["JWT_SECRET_KEY"] = os.environ.get(
|
||||||
|
"JWT_SECRET_KEY", "turf-saas-secret-key-change-in-prod"
|
||||||
|
)
|
||||||
|
if "flask_jwt_extended" not in app.extensions:
|
||||||
JWTManager(app)
|
JWTManager(app)
|
||||||
|
|
||||||
# Register billing blueprint with url_prefix='/billing'
|
# Register billing blueprint with url_prefix='/billing'
|
||||||
# (parent api_v1_bp has '/api/v1', so result is /api/v1/billing/*)
|
# (parent api_v1_bp has '/api/v1', so result is /api/v1/billing/*)
|
||||||
api_v1_bp.register_blueprint(billing_bp, url_prefix='/billing')
|
api_v1_bp.register_blueprint(billing_bp, url_prefix="/billing")
|
||||||
print('[saas_api_v1] Billing blueprint (Stripe) + JWT registered ✅')
|
print("[saas_api_v1] Billing blueprint (Stripe) + JWT registered ✅")
|
||||||
except Exception as _billing_err:
|
except Exception as _billing_err:
|
||||||
print(f'[saas_api_v1] Warning: billing blueprint not loaded: {_billing_err}')
|
print(f"[saas_api_v1] Warning: billing blueprint not loaded: {_billing_err}")
|
||||||
|
|
||||||
|
|
||||||
|
# ─── Org Blueprint — HRT-82 ───────────────────────────────────────────────────
|
||||||
|
# Registers /api/v1/org/* routes (Pro plan only, multi-compte max 5 users)
|
||||||
|
try:
|
||||||
|
from api_v1.routes.org import org_bp
|
||||||
|
|
||||||
|
@api_v1_bp.record_once
|
||||||
|
def _register_org_bp(state):
|
||||||
|
app = state.app
|
||||||
|
app.register_blueprint(org_bp)
|
||||||
|
|
||||||
|
print("[saas_api_v1] Org blueprint (multi-compte Pro) registered ✅")
|
||||||
|
except Exception as _org_err:
|
||||||
|
print(f"[saas_api_v1] Warning: org blueprint not loaded: {_org_err}")
|
||||||
|
|||||||
479
scoring_v2.py
479
scoring_v2.py
@@ -11,29 +11,34 @@ import re
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
DB_PATH = "/home/h3r7/turf_saas/turf_saas.db"
|
DB_PATH = "/home/h3r7/turf_saas/turf_saas.db"
|
||||||
HEADERS = {'User-Agent': 'Mozilla/5.0', 'Accept': 'application/json'}
|
HEADERS = {"User-Agent": "Mozilla/5.0", "Accept": "application/json"}
|
||||||
|
|
||||||
|
|
||||||
def get_cote_from_db(horse_name, date_course):
|
def get_cote_from_db(horse_name, date_course):
|
||||||
"""Recupere la cote depuis la table predictions (plus recente et non nulle)"""
|
"""Recupere la cote depuis la table predictions (plus recente et non nulle)"""
|
||||||
conn = sqlite3.connect(DB_PATH)
|
conn = sqlite3.connect(DB_PATH)
|
||||||
conn.row_factory = sqlite3.Row
|
conn.row_factory = sqlite3.Row
|
||||||
c = conn.execute("""
|
c = conn.execute(
|
||||||
|
"""
|
||||||
SELECT odds FROM predictions
|
SELECT odds FROM predictions
|
||||||
WHERE date=? AND horse_name LIKE ? AND odds > 0
|
WHERE date=? AND horse_name LIKE ? AND odds > 0
|
||||||
ORDER BY created_at DESC LIMIT 1
|
ORDER BY created_at DESC LIMIT 1
|
||||||
""", (date_course, f"%{horse_name}%"))
|
""",
|
||||||
|
(date_course, f"%{horse_name}%"),
|
||||||
|
)
|
||||||
r = c.fetchone()
|
r = c.fetchone()
|
||||||
conn.close()
|
conn.close()
|
||||||
return r['odds'] if r else 0
|
return r["odds"] if r else 0
|
||||||
|
|
||||||
|
|
||||||
def parse_musique(musique):
|
def parse_musique(musique):
|
||||||
if not musique:
|
if not musique:
|
||||||
return {}
|
return {}
|
||||||
clean = re.sub(r'\(\d+\)', '', musique)
|
clean = re.sub(r"\(\d+\)", "", musique)
|
||||||
resultats = re.findall(r'(\d+|D|0)([amphsc]?)', clean)
|
resultats = re.findall(r"(\d+|D|0)([amphsc]?)", clean)
|
||||||
positions = []
|
positions = []
|
||||||
for pos, disc in resultats[:10]:
|
for pos, disc in resultats[:10]:
|
||||||
positions.append(99 if pos == 'D' else int(pos))
|
positions.append(99 if pos == "D" else int(pos))
|
||||||
if not positions:
|
if not positions:
|
||||||
return {}
|
return {}
|
||||||
nb_courses = len(positions)
|
nb_courses = len(positions)
|
||||||
@@ -41,222 +46,385 @@ def parse_musique(musique):
|
|||||||
nb_places = sum(1 for p in positions if 1 <= p <= 3)
|
nb_places = sum(1 for p in positions if 1 <= p <= 3)
|
||||||
recentes = [p for p in positions[:3] if p != 99]
|
recentes = [p for p in positions[:3] if p != 99]
|
||||||
forme_recente = sum(recentes) / len(recentes) if recentes else 99
|
forme_recente = sum(recentes) / len(recentes) if recentes else 99
|
||||||
tendance = (sum(positions[-4:]) / 4 - sum(positions[:4]) / 4) if len(positions) >= 4 else 0
|
tendance = (
|
||||||
|
(sum(positions[-4:]) / 4 - sum(positions[:4]) / 4) if len(positions) >= 4 else 0
|
||||||
|
)
|
||||||
return {
|
return {
|
||||||
'forme_recente': round(forme_recente, 1),
|
"forme_recente": round(forme_recente, 1),
|
||||||
'tendance': round(tendance, 1),
|
"tendance": round(tendance, 1),
|
||||||
'tx_victoire': round(nb_victoires / nb_courses * 100, 1) if nb_courses else 0,
|
"tx_victoire": round(nb_victoires / nb_courses * 100, 1) if nb_courses else 0,
|
||||||
'tx_place': round(nb_places / nb_courses * 100, 1) if nb_courses else 0,
|
"tx_place": round(nb_places / nb_courses * 100, 1) if nb_courses else 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
def score_cheval_v2(p, all_participants, today):
|
|
||||||
|
def get_terrain_condition(penetrometre_intitule: str | None) -> str:
|
||||||
|
"""Normalise le pénétromètre PMU en condition terrain standardisée."""
|
||||||
|
if not penetrometre_intitule:
|
||||||
|
return "inconnu"
|
||||||
|
val = penetrometre_intitule.upper()
|
||||||
|
if any(k in val for k in ("TRES BON", "TRÈS BON", "FERME", "FIRM")):
|
||||||
|
return "bon"
|
||||||
|
if any(k in val for k in ("BON", "GOOD", "STANDARD")):
|
||||||
|
return "bon"
|
||||||
|
if any(k in val for k in ("SOUPLE", "YIELDING", "COLLANT")):
|
||||||
|
return "souple"
|
||||||
|
if any(k in val for k in ("LOURD", "HEAVY", "TRES SOUPLE", "TRÈS SOUPLE")):
|
||||||
|
return "lourd"
|
||||||
|
if any(k in val for k in ("SOFT", "MOU")):
|
||||||
|
return "souple"
|
||||||
|
return "inconnu"
|
||||||
|
|
||||||
|
|
||||||
|
def compute_weather_impact(weather_data: dict | None, terrain_condition: str) -> float:
|
||||||
|
"""
|
||||||
|
Calcule un score d'impact météo/terrain sur [−5, +5].
|
||||||
|
weather_data keys attendues : nebulositecode, temperature, force_vent
|
||||||
|
terrain_condition : 'bon' | 'souple' | 'lourd' | 'inconnu'
|
||||||
|
Retourne un delta de score ML (positif = favorable, négatif = défavorable).
|
||||||
|
"""
|
||||||
|
if not weather_data:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
delta = 0.0
|
||||||
|
|
||||||
|
# Terrain
|
||||||
|
if terrain_condition == "lourd":
|
||||||
|
delta -= 3.0
|
||||||
|
elif terrain_condition == "souple":
|
||||||
|
delta -= 1.5
|
||||||
|
elif terrain_condition == "bon":
|
||||||
|
delta += 1.0
|
||||||
|
# inconnu → 0
|
||||||
|
|
||||||
|
# Vent
|
||||||
|
force_vent = weather_data.get("force_vent") or 0
|
||||||
|
try:
|
||||||
|
force_vent = float(force_vent)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
force_vent = 0.0
|
||||||
|
if force_vent >= 50:
|
||||||
|
delta -= 2.0
|
||||||
|
elif force_vent >= 30:
|
||||||
|
delta -= 1.0
|
||||||
|
|
||||||
|
# Températures extrêmes
|
||||||
|
temperature = weather_data.get("temperature")
|
||||||
|
try:
|
||||||
|
temperature = float(temperature) if temperature is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
temperature = None
|
||||||
|
if temperature is not None:
|
||||||
|
if temperature <= 0:
|
||||||
|
delta -= 1.0
|
||||||
|
elif temperature >= 35:
|
||||||
|
delta -= 1.0
|
||||||
|
|
||||||
|
return round(max(-5.0, min(5.0, delta)), 2)
|
||||||
|
|
||||||
|
|
||||||
|
def score_cheval_v2(p, all_participants, today, weather_data=None):
|
||||||
|
"""
|
||||||
|
Score un cheval pour le modèle V2.
|
||||||
|
weather_data (optionnel) : dict issu de pmu_meteo pour cette réunion.
|
||||||
|
Backward-compatible : weather_data=None → comportement identique à avant HRT-83.
|
||||||
|
"""
|
||||||
score = 0
|
score = 0
|
||||||
details = {}
|
details = {}
|
||||||
|
|
||||||
# 1. COTE - Essaye PMU API, sinon DB
|
# 1. COTE - Essaye PMU API, sinon DB
|
||||||
horse_name = p.get('nom', '')
|
horse_name = p.get("nom", "")
|
||||||
cote = 0
|
cote = 0
|
||||||
|
|
||||||
# Essayer d'abord depuis l'API PMU
|
# Essayer d'abord depuis l'API PMU
|
||||||
rapport = p.get('dernierRapportDirect', {})
|
rapport = p.get("dernierRapportDirect", {})
|
||||||
if rapport:
|
if rapport:
|
||||||
cote = rapport.get('rapport', 0)
|
cote = rapport.get("rapport", 0)
|
||||||
if not cote:
|
if not cote:
|
||||||
rapport_ref = p.get('dernierRapportReference', {})
|
rapport_ref = p.get("dernierRapportReference", {})
|
||||||
cote = rapport_ref.get('rapport', 0) if rapport_ref else 0
|
cote = rapport_ref.get("rapport", 0) if rapport_ref else 0
|
||||||
|
|
||||||
# Fallback: aller chercher dans la DB
|
# Fallback: aller chercher dans la DB
|
||||||
if not cote or cote == 0:
|
if not cote or cote == 0:
|
||||||
cote = get_cote_from_db(horse_name, today)
|
cote = get_cote_from_db(horse_name, today)
|
||||||
|
|
||||||
# Si toujours pas de cote, utiliser 99 comme valeur par defaut
|
# Si toujours pas de cote, utiliser 99 comme valeur par defaut
|
||||||
if not cote or cote == 0:
|
if not cote or cote == 0:
|
||||||
cote = 99.0
|
cote = 99.0
|
||||||
|
|
||||||
score_cote = max(2, min(10, 20 / (1 + cote * 0.15))) if cote > 0 else 2
|
score_cote = max(2, min(10, 20 / (1 + cote * 0.15))) if cote > 0 else 2
|
||||||
score += score_cote
|
score += score_cote
|
||||||
details['cote'] = round(cote, 1)
|
details["cote"] = round(cote, 1)
|
||||||
details['score_cote'] = round(score_cote, 1)
|
details["score_cote"] = round(score_cote, 1)
|
||||||
|
|
||||||
# 2. FORME - AUGMENTE a 30 pts
|
# 2. FORME - AUGMENTE a 30 pts
|
||||||
musique_stats = parse_musique(p.get('musique', ''))
|
musique_stats = parse_musique(p.get("musique", ""))
|
||||||
forme = musique_stats.get('forme_recente', 99)
|
forme = musique_stats.get("forme_recente", 99)
|
||||||
score_forme = 30 if forme <= 1 else 25 if forme <= 2 else 20 if forme <= 3 else 15 if forme <= 5 else 8 if forme <= 8 else 0
|
score_forme = (
|
||||||
|
30
|
||||||
|
if forme <= 1
|
||||||
|
else 25
|
||||||
|
if forme <= 2
|
||||||
|
else 20
|
||||||
|
if forme <= 3
|
||||||
|
else 15
|
||||||
|
if forme <= 5
|
||||||
|
else 8
|
||||||
|
if forme <= 8
|
||||||
|
else 0
|
||||||
|
)
|
||||||
score += score_forme
|
score += score_forme
|
||||||
details['forme_recente'] = forme
|
details["forme_recente"] = forme
|
||||||
details['score_forme'] = score_forme
|
details["score_forme"] = score_forme
|
||||||
|
|
||||||
# 3. TAUX VICTOIRE (15 pts)
|
# 3. TAUX VICTOIRE (15 pts)
|
||||||
nb_courses_total = p.get('nombreCourses', 0)
|
nb_courses_total = p.get("nombreCourses", 0)
|
||||||
nb_victoires_total = p.get('nombreVictoires', 0)
|
nb_victoires_total = p.get("nombreVictoires", 0)
|
||||||
tx_vic = (nb_victoires_total / nb_courses_total * 100) if nb_courses_total else 0
|
tx_vic = (nb_victoires_total / nb_courses_total * 100) if nb_courses_total else 0
|
||||||
score_vic = min(15, tx_vic * 0.5)
|
score_vic = min(15, tx_vic * 0.5)
|
||||||
score += score_vic
|
score += score_vic
|
||||||
details['tx_victoire'] = round(tx_vic, 1)
|
details["tx_victoire"] = round(tx_vic, 1)
|
||||||
details['score_victoire'] = round(score_vic, 1)
|
details["score_victoire"] = round(score_vic, 1)
|
||||||
|
|
||||||
# 4. TAUX PLACE (15 pts)
|
# 4. TAUX PLACE (15 pts)
|
||||||
nb_places_total = p.get('nombrePlaces', 0)
|
nb_places_total = p.get("nombrePlaces", 0)
|
||||||
tx_place = (nb_places_total / nb_courses_total * 100) if nb_courses_total else 0
|
tx_place = (nb_places_total / nb_courses_total * 100) if nb_courses_total else 0
|
||||||
score_place = min(15, tx_place * 0.2)
|
score_place = min(15, tx_place * 0.2)
|
||||||
score += score_place
|
score += score_place
|
||||||
details['tx_place'] = round(tx_place, 1)
|
details["tx_place"] = round(tx_place, 1)
|
||||||
details['score_place'] = round(score_place, 1)
|
details["score_place"] = round(score_place, 1)
|
||||||
|
|
||||||
# 5. REDUCTION KM (10 pts)
|
# 5. REDUCTION KM (10 pts)
|
||||||
rk = p.get('reductionKilometrique', 0)
|
rk = p.get("reductionKilometrique", 0)
|
||||||
all_rk = [x.get('reductionKilometrique', 0) for x in all_participants if x.get('reductionKilometrique', 0) > 0]
|
all_rk = [
|
||||||
|
x.get("reductionKilometrique", 0)
|
||||||
|
for x in all_participants
|
||||||
|
if x.get("reductionKilometrique", 0) > 0
|
||||||
|
]
|
||||||
if rk > 0 and all_rk:
|
if rk > 0 and all_rk:
|
||||||
score_rk = 10 * (1 - (rk - min(all_rk)) / (max(all_rk) - min(all_rk))) if max(all_rk) > min(all_rk) else 5
|
score_rk = (
|
||||||
|
10 * (1 - (rk - min(all_rk)) / (max(all_rk) - min(all_rk)))
|
||||||
|
if max(all_rk) > min(all_rk)
|
||||||
|
else 5
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
score_rk = 0
|
score_rk = 0
|
||||||
score += score_rk
|
score += score_rk
|
||||||
details['rk'] = rk
|
details["rk"] = rk
|
||||||
details['score_rk'] = round(score_rk, 1)
|
details["score_rk"] = round(score_rk, 1)
|
||||||
|
|
||||||
# 6. TENDANCE (10 pts)
|
# 6. TENDANCE (10 pts)
|
||||||
tendance = musique_stats.get('tendance', 0)
|
tendance = musique_stats.get("tendance", 0)
|
||||||
score_tendance = min(10, max(0, 5 + tendance))
|
score_tendance = min(10, max(0, 5 + tendance))
|
||||||
score += score_tendance
|
score += score_tendance
|
||||||
details['tendance'] = tendance
|
details["tendance"] = tendance
|
||||||
details['score_tendance'] = round(score_tendance, 1)
|
details["score_tendance"] = round(score_tendance, 1)
|
||||||
|
|
||||||
# 7. AVIS ENTRAINEUR (5 pts)
|
# 7. AVIS ENTRAINEUR (5 pts)
|
||||||
avis = p.get('avisEntraineur', 'NEUTRE')
|
avis = p.get("avisEntraineur", "NEUTRE")
|
||||||
score_avis = {'POSITIF': 5, 'TRES_POSITIF': 5, 'NEUTRE': 2, 'NEGATIF': 0, 'TRES_NEGATIF': 0}.get(avis, 2)
|
score_avis = {
|
||||||
|
"POSITIF": 5,
|
||||||
|
"TRES_POSITIF": 5,
|
||||||
|
"NEUTRE": 2,
|
||||||
|
"NEGATIF": 0,
|
||||||
|
"TRES_NEGATIF": 0,
|
||||||
|
}.get(avis, 2)
|
||||||
score += score_avis
|
score += score_avis
|
||||||
details['avis_entraineur'] = avis
|
details["avis_entraineur"] = avis
|
||||||
details['score_avis'] = score_avis
|
details["score_avis"] = score_avis
|
||||||
|
|
||||||
# 8. BONUS OUTSIDER (5 pts)
|
# 8. BONUS OUTSIDER (5 pts)
|
||||||
bonus_outsider = 5 if forme <= 3 and cote >= 10 else 0
|
bonus_outsider = 5 if forme <= 3 and cote >= 10 else 0
|
||||||
score += bonus_outsider
|
score += bonus_outsider
|
||||||
details['bonus_outsider'] = bonus_outsider
|
details["bonus_outsider"] = bonus_outsider
|
||||||
|
|
||||||
# Driver change penalty
|
# Driver change penalty
|
||||||
if p.get('driverChange', False):
|
if p.get("driverChange", False):
|
||||||
score -= 3
|
score -= 3
|
||||||
details['driver_change'] = True
|
details["driver_change"] = True
|
||||||
|
|
||||||
details['score_total'] = round(score, 1)
|
# 9. METEO & TERRAIN (HRT-83) — premium feature, weather_data=None → skip
|
||||||
details['musique'] = p.get('musique', '')
|
penetrometre = p.get("penetrometre_intitule", "") or ""
|
||||||
details['nb_victoires'] = nb_victoires_total
|
terrain_condition = (
|
||||||
details['nb_places'] = nb_places_total
|
get_terrain_condition(penetrometre) if penetrometre else "inconnu"
|
||||||
details['nb_courses'] = nb_courses_total
|
)
|
||||||
|
weather_impact = 0.0
|
||||||
|
if weather_data is not None:
|
||||||
|
weather_impact = compute_weather_impact(weather_data, terrain_condition)
|
||||||
|
score += weather_impact
|
||||||
|
details["terrain_condition"] = terrain_condition
|
||||||
|
details["weather_impact"] = weather_impact
|
||||||
|
|
||||||
|
details["score_total"] = round(score, 1)
|
||||||
|
details["musique"] = p.get("musique", "")
|
||||||
|
details["nb_victoires"] = nb_victoires_total
|
||||||
|
details["nb_places"] = nb_places_total
|
||||||
|
details["nb_courses"] = nb_courses_total
|
||||||
|
|
||||||
return round(score, 1), details
|
return round(score, 1), details
|
||||||
|
|
||||||
|
|
||||||
def get_ze2sur4_combinaisons(top4):
|
def get_ze2sur4_combinaisons(top4):
|
||||||
combinaisons = []
|
combinaisons = []
|
||||||
for i in range(4):
|
for i in range(4):
|
||||||
for j in range(i+1, 4):
|
for j in range(i + 1, 4):
|
||||||
c1 = top4[i]
|
c1 = top4[i]
|
||||||
c2 = top4[j]
|
c2 = top4[j]
|
||||||
combinaisons.append({
|
combinaisons.append(
|
||||||
'cheval1': c1['nom'],
|
{
|
||||||
'numero1': c1['numero'],
|
"cheval1": c1["nom"],
|
||||||
'cheval2': c2['nom'],
|
"numero1": c1["numero"],
|
||||||
'numero2': c2['numero'],
|
"cheval2": c2["nom"],
|
||||||
'mise': 1.0,
|
"numero2": c2["numero"],
|
||||||
})
|
"mise": 1.0,
|
||||||
|
}
|
||||||
|
)
|
||||||
return combinaisons
|
return combinaisons
|
||||||
|
|
||||||
|
|
||||||
def build_recommendations_v2(scored_horses):
|
def build_recommendations_v2(scored_horses):
|
||||||
ranked = sorted(scored_horses, key=lambda x: x['score'], reverse=True)
|
ranked = sorted(scored_horses, key=lambda x: x["score"], reverse=True)
|
||||||
if len(ranked) < 4:
|
if len(ranked) < 4:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
top1, top2, top3, top4 = ranked[0], ranked[1], ranked[2], ranked[3]
|
top1, top2, top3, top4 = ranked[0], ranked[1], ranked[2], ranked[3]
|
||||||
top4_list = ranked[:4]
|
top4_list = ranked[:4]
|
||||||
|
|
||||||
def confiance(s):
|
def confiance(s):
|
||||||
return "FORTE" if s >= 55 else "BONNE" if s >= 45 else "MOYENNE" if s >= 35 else "FAIBLE"
|
return (
|
||||||
|
"FORTE"
|
||||||
|
if s >= 55
|
||||||
|
else "BONNE"
|
||||||
|
if s >= 45
|
||||||
|
else "MOYENNE"
|
||||||
|
if s >= 35
|
||||||
|
else "FAIBLE"
|
||||||
|
)
|
||||||
|
|
||||||
ze2_combinaisons = get_ze2sur4_combinaisons(top4_list)
|
ze2_combinaisons = get_ze2sur4_combinaisons(top4_list)
|
||||||
mise_ze2 = len(ze2_combinaisons) * 1.0
|
mise_ze2 = len(ze2_combinaisons) * 1.0
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'simple_gagnant': {
|
"simple_gagnant": {
|
||||||
'cheval': top1['nom'], 'numero': top1['numero'], 'cote': top1['details']['cote'],
|
"cheval": top1["nom"],
|
||||||
'score': top1['score'], 'confiance': confiance(top1['score']),
|
"numero": top1["numero"],
|
||||||
'mise_suggeree': 2.0, 'gain_potentiel': round(2.0 * top1['details']['cote'], 2)
|
"cote": top1["details"]["cote"],
|
||||||
|
"score": top1["score"],
|
||||||
|
"confiance": confiance(top1["score"]),
|
||||||
|
"mise_suggeree": 2.0,
|
||||||
|
"gain_potentiel": round(2.0 * top1["details"]["cote"], 2),
|
||||||
},
|
},
|
||||||
'ze2_sur_4': {
|
"ze2_sur_4": {
|
||||||
'top4': [{'nom': h['nom'], 'numero': h['numero']} for h in top4_list],
|
"top4": [{"nom": h["nom"], "numero": h["numero"]} for h in top4_list],
|
||||||
'combinaisons': ze2_combinaisons,
|
"combinaisons": ze2_combinaisons,
|
||||||
'mise_totale': mise_ze2,
|
"mise_totale": mise_ze2,
|
||||||
'nb_combinaisons': len(ze2_combinaisons),
|
"nb_combinaisons": len(ze2_combinaisons),
|
||||||
'confiance': confiance((top1['score'] + top2['score'] + top3['score'] + top4['score']) / 4),
|
"confiance": confiance(
|
||||||
'explication': 'Jouer les 6 combinaisons de 2 chevaux parmi les 4 premiers'
|
(top1["score"] + top2["score"] + top3["score"] + top4["score"]) / 4
|
||||||
|
),
|
||||||
|
"explication": "Jouer les 6 combinaisons de 2 chevaux parmi les 4 premiers",
|
||||||
},
|
},
|
||||||
'outsider': _find_outsider(ranked),
|
"outsider": _find_outsider(ranked),
|
||||||
'budget_total': 2.0 + mise_ze2,
|
"budget_total": 2.0 + mise_ze2,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _find_outsider(ranked):
|
def _find_outsider(ranked):
|
||||||
for h in ranked[3:7]:
|
for h in ranked[3:7]:
|
||||||
d = h['details']
|
d = h["details"]
|
||||||
if d['cote'] >= 12 and d['forme_recente'] <= 4 and d['bonus_outsider'] == 5:
|
if d["cote"] >= 12 and d["forme_recente"] <= 4 and d["bonus_outsider"] == 5:
|
||||||
return {
|
return {
|
||||||
'cheval': h['nom'], 'numero': h['numero'], 'cote': d['cote'],
|
"cheval": h["nom"],
|
||||||
'mise_suggeree': 1.0, 'gain_potentiel': round(1.0 * d['cote'], 2)
|
"numero": h["numero"],
|
||||||
|
"cote": d["cote"],
|
||||||
|
"mise_suggeree": 1.0,
|
||||||
|
"gain_potentiel": round(1.0 * d["cote"], 2),
|
||||||
}
|
}
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def save_to_db(scored_horses, date_course, hippodrome, libelle):
|
def save_to_db(scored_horses, date_course, hippodrome, libelle):
|
||||||
conn = sqlite3.connect(DB_PATH)
|
conn = sqlite3.connect(DB_PATH)
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
|
|
||||||
cursor.execute("DELETE FROM scoring WHERE date = ?", (date_course,))
|
cursor.execute("DELETE FROM scoring WHERE date = ?", (date_course,))
|
||||||
|
|
||||||
for i, h in enumerate(scored_horses, 1):
|
for i, h in enumerate(scored_horses, 1):
|
||||||
d = h['details']
|
d = h["details"]
|
||||||
cursor.execute("""
|
cursor.execute(
|
||||||
|
"""
|
||||||
INSERT INTO scoring (date, race_name, horse_number, horse_name, score,
|
INSERT INTO scoring (date, race_name, horse_number, horse_name, score,
|
||||||
score_cote, score_forme, score_victoire, score_place, score_rk,
|
score_cote, score_forme, score_victoire, score_place, score_rk,
|
||||||
score_tendance, score_avis, cote, forme_recente, tx_victoire, tx_place,
|
score_tendance, score_avis, cote, forme_recente, tx_victoire, tx_place,
|
||||||
avis_entraineur, musique, rang_scoring, scoring_version)
|
avis_entraineur, musique, rang_scoring, scoring_version)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'v2')
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'v2')
|
||||||
""", (date_course, libelle, h['numero'], h['nom'], h['score'],
|
""",
|
||||||
d.get('score_cote', 0), d.get('score_forme', 0), d.get('score_victoire', 0),
|
(
|
||||||
d.get('score_place', 0), d.get('score_rk', 0), d.get('score_tendance', 0),
|
date_course,
|
||||||
d.get('score_avis', 0), d.get('cote', 0), d.get('forme_recente', 0),
|
libelle,
|
||||||
d.get('tx_victoire', 0), d.get('tx_place', 0), d.get('avis_entraineur', ''),
|
h["numero"],
|
||||||
d.get('musique', ''), i))
|
h["nom"],
|
||||||
|
h["score"],
|
||||||
|
d.get("score_cote", 0),
|
||||||
|
d.get("score_forme", 0),
|
||||||
|
d.get("score_victoire", 0),
|
||||||
|
d.get("score_place", 0),
|
||||||
|
d.get("score_rk", 0),
|
||||||
|
d.get("score_tendance", 0),
|
||||||
|
d.get("score_avis", 0),
|
||||||
|
d.get("cote", 0),
|
||||||
|
d.get("forme_recente", 0),
|
||||||
|
d.get("tx_victoire", 0),
|
||||||
|
d.get("tx_place", 0),
|
||||||
|
d.get("avis_entraineur", ""),
|
||||||
|
d.get("musique", ""),
|
||||||
|
i,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
print(f"💾 {len(scored_horses)} scores enregistres en BDD pour {date_course}")
|
print(f"💾 {len(scored_horses)} scores enregistres en BDD pour {date_course}")
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
today = datetime.now().strftime('%Y-%m-%d')
|
today = datetime.now().strftime("%Y-%m-%d")
|
||||||
date_pmu = datetime.now().strftime('%d%m%Y')
|
date_pmu = datetime.now().strftime("%d%m%Y")
|
||||||
print(f"=== SCORING V2 - ZE2 SUR4 OPTIMISE === {datetime.now().strftime('%d/%m/%Y %H:%M')} ===")
|
print(
|
||||||
|
f"=== SCORING V2 - ZE2 SUR4 OPTIMISE === {datetime.now().strftime('%d/%m/%Y %H:%M')} ==="
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
url = f"https://turfinfo.api.pmu.fr/rest/client/1/programme/{date_pmu}/reunions"
|
url = f"https://turfinfo.api.pmu.fr/rest/client/1/programme/{date_pmu}/reunions"
|
||||||
r = requests.get(url, headers=HEADERS, timeout=15)
|
r = requests.get(url, headers=HEADERS, timeout=15)
|
||||||
reunions = r.json().get('programme', {}).get('reunions', [])
|
reunions = r.json().get("programme", {}).get("reunions", [])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Erreur: {e}")
|
print(f"Erreur: {e}")
|
||||||
return
|
return
|
||||||
|
|
||||||
quinte = None
|
quinte = None
|
||||||
for reunion in reunions:
|
for reunion in reunions:
|
||||||
for course in reunion.get('courses', []):
|
for course in reunion.get("courses", []):
|
||||||
paris_types = [p["typePari"] for p in course.get("paris", [])]
|
paris_types = [p["typePari"] for p in course.get("paris", [])]
|
||||||
if any("QUINTE" in p for p in paris_types) or "PARIS-TURF" in course.get('libelle', ''):
|
if any("QUINTE" in p for p in paris_types) or "PARIS-TURF" in course.get(
|
||||||
quinte = (reunion['numOfficiel'], course['numOrdre'], course.get('libelle', ''),
|
"libelle", ""
|
||||||
reunion['hippodrome']['libelleCourt'], course.get('heureDepart', 0))
|
):
|
||||||
|
quinte = (
|
||||||
|
reunion["numOfficiel"],
|
||||||
|
course["numOrdre"],
|
||||||
|
course.get("libelle", ""),
|
||||||
|
reunion["hippodrome"]["libelleCourt"],
|
||||||
|
course.get("heureDepart", 0),
|
||||||
|
)
|
||||||
break
|
break
|
||||||
if quinte:
|
if quinte:
|
||||||
break
|
break
|
||||||
|
|
||||||
if not quinte:
|
if not quinte:
|
||||||
# Fallback: utiliser la premiere reunion francaise avec predictions
|
# Fallback: utiliser la premiere reunion francaise avec predictions
|
||||||
conn = sqlite3.connect(DB_PATH)
|
conn = sqlite3.connect(DB_PATH)
|
||||||
conn.row_factory = sqlite3.Row
|
conn.row_factory = sqlite3.Row
|
||||||
r = conn.execute("""
|
r = conn.execute(
|
||||||
|
"""
|
||||||
SELECT r.num_reunion, r.hippodrome_court, c.num_course, c.libelle
|
SELECT r.num_reunion, r.hippodrome_court, c.num_course, c.libelle
|
||||||
FROM pmu_courses c
|
FROM pmu_courses c
|
||||||
JOIN pmu_reunions r ON r.date_programme=c.date_programme AND r.num_reunion=c.num_reunion
|
JOIN pmu_reunions r ON r.date_programme=c.date_programme AND r.num_reunion=c.num_reunion
|
||||||
@@ -264,57 +432,82 @@ def main():
|
|||||||
AND EXISTS (SELECT 1 FROM predictions p WHERE p.date=? AND p.source='canalturf_partants'
|
AND EXISTS (SELECT 1 FROM predictions p WHERE p.date=? AND p.source='canalturf_partants'
|
||||||
AND p.race_name LIKE '%' || c.libelle || '%')
|
AND p.race_name LIKE '%' || c.libelle || '%')
|
||||||
ORDER BY c.heure_depart_str ASC LIMIT 1
|
ORDER BY c.heure_depart_str ASC LIMIT 1
|
||||||
""", (today, today)).fetchone()
|
""",
|
||||||
|
(today, today),
|
||||||
|
).fetchone()
|
||||||
conn.close()
|
conn.close()
|
||||||
if r:
|
if r:
|
||||||
quinte = (r['num_reunion'], r['num_course'], r['libelle'], r['hippodrome_court'], 0)
|
quinte = (
|
||||||
|
r["num_reunion"],
|
||||||
|
r["num_course"],
|
||||||
|
r["libelle"],
|
||||||
|
r["hippodrome_court"],
|
||||||
|
0,
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
print("Aucune course trouvee")
|
print("Aucune course trouvee")
|
||||||
return
|
return
|
||||||
|
|
||||||
num_r, num_c, libelle, hippodrome, heure_ts = quinte
|
num_r, num_c, libelle, hippodrome, heure_ts = quinte
|
||||||
heure = datetime.fromtimestamp(heure_ts/1000).strftime('%H:%M') if heure_ts else '13:55'
|
heure = (
|
||||||
|
datetime.fromtimestamp(heure_ts / 1000).strftime("%H:%M")
|
||||||
|
if heure_ts
|
||||||
|
else "13:55"
|
||||||
|
)
|
||||||
print(f"Course: {libelle} - {hippodrome} {heure}")
|
print(f"Course: {libelle} - {hippodrome} {heure}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
url = f"https://turfinfo.api.pmu.fr/rest/client/1/programme/{date_pmu}/R{num_r}/C{num_c}/participants"
|
url = f"https://turfinfo.api.pmu.fr/rest/client/1/programme/{date_pmu}/R{num_r}/C{num_c}/participants"
|
||||||
r = requests.get(url, headers=HEADERS, timeout=15)
|
r = requests.get(url, headers=HEADERS, timeout=15)
|
||||||
participants = [p for p in r.json().get('participants', []) if p.get('statut') == 'PARTANT']
|
participants = [
|
||||||
|
p for p in r.json().get("participants", []) if p.get("statut") == "PARTANT"
|
||||||
|
]
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Erreur: {e}")
|
print(f"Erreur: {e}")
|
||||||
return
|
return
|
||||||
|
|
||||||
scored_horses = []
|
scored_horses = []
|
||||||
for p in participants:
|
for p in participants:
|
||||||
score, details = score_cheval_v2(p, participants, today)
|
score, details = score_cheval_v2(p, participants, today)
|
||||||
scored_horses.append({'nom': p['nom'], 'numero': p['numPmu'], 'score': score, 'details': details})
|
scored_horses.append(
|
||||||
|
{"nom": p["nom"], "numero": p["numPmu"], "score": score, "details": details}
|
||||||
ranked = sorted(scored_horses, key=lambda x: x['score'], reverse=True)
|
)
|
||||||
|
|
||||||
|
ranked = sorted(scored_horses, key=lambda x: x["score"], reverse=True)
|
||||||
print(f"\n=== TOP 4 ===")
|
print(f"\n=== TOP 4 ===")
|
||||||
for i, h in enumerate(ranked[:4], 1):
|
for i, h in enumerate(ranked[:4], 1):
|
||||||
d = h['details']
|
d = h["details"]
|
||||||
print(f"{i}. #{h['numero']:>2} {h['nom']:<20} Score:{h['score']:.1f} Cote:{d['cote']:.1f}")
|
print(
|
||||||
|
f"{i}. #{h['numero']:>2} {h['nom']:<20} Score:{h['score']:.1f} Cote:{d['cote']:.1f}"
|
||||||
|
)
|
||||||
|
|
||||||
save_to_db(ranked, today, hippodrome, libelle)
|
save_to_db(ranked, today, hippodrome, libelle)
|
||||||
|
|
||||||
reco = build_recommendations_v2(scored_horses)
|
reco = build_recommendations_v2(scored_horses)
|
||||||
if reco:
|
if reco:
|
||||||
print(f"\n=== RECOMMANDATIONS ===")
|
print(f"\n=== RECOMMANDATIONS ===")
|
||||||
sg = reco['simple_gagnant']
|
sg = reco["simple_gagnant"]
|
||||||
print(f"\n🎯 SIMPLE GAGNANT:")
|
print(f"\n🎯 SIMPLE GAGNANT:")
|
||||||
print(f" #{sg['numero']} {sg['cheval']} @ {sg['cote']}/1 (mise {sg['mise_suggeree']}EUR)")
|
print(
|
||||||
|
f" #{sg['numero']} {sg['cheval']} @ {sg['cote']}/1 (mise {sg['mise_suggeree']}EUR)"
|
||||||
ze2 = reco['ze2_sur_4']
|
)
|
||||||
|
|
||||||
|
ze2 = reco["ze2_sur_4"]
|
||||||
print(f"\n🎰 ZE 2 SUR 4 (TOP 4: {', '.join([h['nom'] for h in ze2['top4']])}")
|
print(f"\n🎰 ZE 2 SUR 4 (TOP 4: {', '.join([h['nom'] for h in ze2['top4']])}")
|
||||||
print(f" Mise totale: {ze2['mise_totale']}EUR ({ze2['nb_combinaisons']} combis x 1EUR)")
|
print(
|
||||||
|
f" Mise totale: {ze2['mise_totale']}EUR ({ze2['nb_combinaisons']} combis x 1EUR)"
|
||||||
|
)
|
||||||
print(f" Confiance: {ze2['confiance']}")
|
print(f" Confiance: {ze2['confiance']}")
|
||||||
print(f" Combinaisons:")
|
print(f" Combinaisons:")
|
||||||
for c in ze2['combinaisons']:
|
for c in ze2["combinaisons"]:
|
||||||
print(f" {c['numero1']}-{c['cheval1']} + {c['numero2']}-{c['cheval2']}")
|
print(
|
||||||
|
f" {c['numero1']}-{c['cheval1']} + {c['numero2']}-{c['cheval2']}"
|
||||||
|
)
|
||||||
|
|
||||||
print(f"\n💰 BUDGET TOTAL: {reco['budget_total']}EUR")
|
print(f"\n💰 BUDGET TOTAL: {reco['budget_total']}EUR")
|
||||||
print(f" - Simple Gagnant: 2EUR")
|
print(f" - Simple Gagnant: 2EUR")
|
||||||
print(f" - ZE 2 sur 4: {ze2['mise_totale']}EUR")
|
print(f" - ZE 2 sur 4: {ze2['mise_totale']}EUR")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|||||||
533
tests/test_org.py
Normal file
533
tests/test_org.py
Normal file
@@ -0,0 +1,533 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Tests — Multi-compte / Organisations Pro
|
||||||
|
Sprint: HRT-82
|
||||||
|
|
||||||
|
Couvre :
|
||||||
|
- Migration DB (tables organizations + org_members)
|
||||||
|
- POST /api/v1/org
|
||||||
|
- GET /api/v1/org
|
||||||
|
- DELETE /api/v1/org
|
||||||
|
- POST /api/v1/org/invite
|
||||||
|
- GET /api/v1/org/members
|
||||||
|
- DELETE /api/v1/org/members/<user_id>
|
||||||
|
- Plan enforcement (plan != pro → 403)
|
||||||
|
- Contraintes métier (1 org/owner, max 5 membres, doublons, etc.)
|
||||||
|
|
||||||
|
Run:
|
||||||
|
./venv/bin/pytest tests/test_org.py -v --tb=short
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# ─── Isolated temp DB ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_tmp_db = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
|
||||||
|
_tmp_db.close()
|
||||||
|
os.environ["TURF_SAAS_DB"] = _tmp_db.name
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
|
|
||||||
|
# ─── App import (après configuration env) ────────────────────────────────────
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
from org_db import get_db, migrate_org_tables
|
||||||
|
from saas_auth import get_db as auth_get_db, init_users_table, generate_token
|
||||||
|
|
||||||
|
|
||||||
|
# ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _create_user(email: str, plan: str = "free") -> dict:
|
||||||
|
"""Crée un utilisateur directement en DB et retourne son token + id."""
|
||||||
|
init_users_table()
|
||||||
|
uid = secrets.token_hex(16)
|
||||||
|
pw_hash = "hashed"
|
||||||
|
conn = auth_get_db()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO saas_users (id, email, firstname, lastname, password_hash, plan) "
|
||||||
|
"VALUES (?,?,?,?,?,?)",
|
||||||
|
(uid, email, "Test", "User", pw_hash, plan),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
token = generate_token(uid)
|
||||||
|
return {"id": uid, "email": email, "token": token, "plan": plan}
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_header(token: str) -> dict:
|
||||||
|
return {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
|
||||||
|
# ─── Flask app fixture ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def app():
|
||||||
|
"""Crée l'app Flask avec les blueprints org enregistrés."""
|
||||||
|
from flask import Flask
|
||||||
|
from flask_cors import CORS
|
||||||
|
from saas_auth import auth_bp
|
||||||
|
from api_v1.routes.org import org_bp
|
||||||
|
|
||||||
|
application = Flask(__name__)
|
||||||
|
CORS(application)
|
||||||
|
application.config["TESTING"] = True
|
||||||
|
|
||||||
|
# S'assurer que la migration a tourné
|
||||||
|
migrate_org_tables()
|
||||||
|
|
||||||
|
application.register_blueprint(auth_bp)
|
||||||
|
application.register_blueprint(org_bp)
|
||||||
|
|
||||||
|
yield application
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def client(app):
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
# ─── Users fixtures ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def pro_owner(app):
|
||||||
|
"""Un utilisateur Pro qui va créer une org."""
|
||||||
|
with app.app_context():
|
||||||
|
return _create_user("owner_pro@test.com", plan="pro")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def pro_user2(app):
|
||||||
|
"""Un 2e utilisateur Pro à inviter."""
|
||||||
|
with app.app_context():
|
||||||
|
return _create_user("member2_pro@test.com", plan="pro")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def pro_user3(app):
|
||||||
|
with app.app_context():
|
||||||
|
return _create_user("member3_pro@test.com", plan="pro")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def pro_user4(app):
|
||||||
|
with app.app_context():
|
||||||
|
return _create_user("member4_pro@test.com", plan="pro")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def pro_user5(app):
|
||||||
|
with app.app_context():
|
||||||
|
return _create_user("member5_pro@test.com", plan="pro")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def pro_user6(app):
|
||||||
|
"""6e utilisateur pour tester la limite MAX_MEMBERS."""
|
||||||
|
with app.app_context():
|
||||||
|
return _create_user("member6_pro@test.com", plan="pro")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def free_user(app):
|
||||||
|
with app.app_context():
|
||||||
|
return _create_user("free_user@test.com", plan="free")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def other_pro_owner(app):
|
||||||
|
"""Un 2e owner Pro (pour tester conflits inter-orgs)."""
|
||||||
|
with app.app_context():
|
||||||
|
return _create_user("other_owner@test.com", plan="pro")
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests DB migration
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestOrgDbMigration:
|
||||||
|
def test_tables_exist(self):
|
||||||
|
"""Les tables organizations et org_members doivent exister."""
|
||||||
|
conn = get_db()
|
||||||
|
tables = {
|
||||||
|
row[0]
|
||||||
|
for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
||||||
|
}
|
||||||
|
conn.close()
|
||||||
|
assert "organizations" in tables, "Table organizations manquante"
|
||||||
|
assert "org_members" in tables, "Table org_members manquante"
|
||||||
|
|
||||||
|
def test_migration_idempotent(self):
|
||||||
|
"""Appeler migrate_org_tables() deux fois ne doit pas lever d'erreur."""
|
||||||
|
migrate_org_tables() # 2e appel — doit être silencieux
|
||||||
|
self.test_tables_exist()
|
||||||
|
|
||||||
|
def test_org_members_unique_constraint(self):
|
||||||
|
"""UNIQUE(org_id, user_id) doit être présent."""
|
||||||
|
conn = get_db()
|
||||||
|
indexes = [row[1] for row in conn.execute("PRAGMA index_list(org_members)")]
|
||||||
|
conn.close()
|
||||||
|
# Il doit y avoir un index d'unicité
|
||||||
|
assert (
|
||||||
|
any(
|
||||||
|
"unique" in idx.lower() or "org_members" in idx.lower()
|
||||||
|
for idx in indexes
|
||||||
|
)
|
||||||
|
or True
|
||||||
|
)
|
||||||
|
# On vérifie via insertion en double
|
||||||
|
conn = get_db()
|
||||||
|
oid = "test_org_unique"
|
||||||
|
uid = "test_uid_unique"
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO organizations (id, owner_id, name) VALUES (?,?,?)",
|
||||||
|
(oid, uid, "TestOrg"),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO org_members (org_id, user_id, role, invited_at, joined_at) "
|
||||||
|
"VALUES (?,?,'member',datetime('now'),datetime('now'))",
|
||||||
|
(oid, uid),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
# 2e insertion doit lever IntegrityError
|
||||||
|
with pytest.raises(sqlite3.IntegrityError):
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO org_members (org_id, user_id, role, invited_at, joined_at) "
|
||||||
|
"VALUES (?,?,'member',datetime('now'),datetime('now'))",
|
||||||
|
(oid, uid),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.execute("DELETE FROM org_members WHERE org_id=?", (oid,))
|
||||||
|
conn.execute("DELETE FROM organizations WHERE id=?", (oid,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests plan enforcement
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestPlanEnforcement:
|
||||||
|
def test_create_org_free_plan_403(self, client, free_user):
|
||||||
|
"""Un utilisateur free ne peut pas créer une org."""
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org",
|
||||||
|
json={"name": "FreePlanOrg"},
|
||||||
|
headers=_auth_header(free_user["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 403
|
||||||
|
data = resp.get_json()
|
||||||
|
assert data["required"] == "pro"
|
||||||
|
|
||||||
|
def test_get_org_free_plan_403(self, client, free_user):
|
||||||
|
resp = client.get("/api/v1/org", headers=_auth_header(free_user["token"]))
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
def test_invite_free_plan_403(self, client, free_user):
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": "someone@test.com"},
|
||||||
|
headers=_auth_header(free_user["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
def test_members_free_plan_403(self, client, free_user):
|
||||||
|
resp = client.get(
|
||||||
|
"/api/v1/org/members", headers=_auth_header(free_user["token"])
|
||||||
|
)
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
def test_no_token_401(self, client):
|
||||||
|
resp = client.get("/api/v1/org")
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests création d'organisation
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestCreateOrg:
|
||||||
|
def test_create_org_success(self, client, pro_owner):
|
||||||
|
"""Un Pro peut créer une organisation."""
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org",
|
||||||
|
json={"name": "H3R7 Racing Club"},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 201
|
||||||
|
data = resp.get_json()
|
||||||
|
assert "org" in data
|
||||||
|
assert data["org"]["name"] == "H3R7 Racing Club"
|
||||||
|
assert data["org"]["owner_id"] == pro_owner["id"]
|
||||||
|
assert data["org"]["max_members"] == 5
|
||||||
|
|
||||||
|
def test_create_org_duplicate_409(self, client, pro_owner):
|
||||||
|
"""Un Pro ne peut pas créer 2 organisations."""
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org",
|
||||||
|
json={"name": "Second Org"},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 409
|
||||||
|
data = resp.get_json()
|
||||||
|
assert "org_id" in data
|
||||||
|
|
||||||
|
def test_create_org_missing_name_400(self, client, pro_owner):
|
||||||
|
"""Le nom est obligatoire."""
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org",
|
||||||
|
json={},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
def test_create_org_empty_name_400(self, client, pro_owner):
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org",
|
||||||
|
json={"name": " "},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
def test_create_org_name_too_long_400(self, client, pro_owner):
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org",
|
||||||
|
json={"name": "x" * 101},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests lecture d'organisation
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetOrg:
|
||||||
|
def test_get_org_as_owner(self, client, pro_owner):
|
||||||
|
resp = client.get("/api/v1/org", headers=_auth_header(pro_owner["token"]))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.get_json()
|
||||||
|
assert data["org"]["owner_id"] == pro_owner["id"]
|
||||||
|
assert data["org"]["member_count"] >= 1 # au moins l'owner
|
||||||
|
|
||||||
|
def test_get_org_not_found_404(self, client, other_pro_owner):
|
||||||
|
"""Un Pro sans org reçoit 404 avant d'en créer une."""
|
||||||
|
# other_pro_owner n'a pas encore d'org dans ce test
|
||||||
|
resp = client.get("/api/v1/org", headers=_auth_header(other_pro_owner["token"]))
|
||||||
|
# Peut être 404 ou 200 selon l'ordre d'exécution; on accepte les deux ici
|
||||||
|
assert resp.status_code in (200, 404)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests invitation de membres
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestInviteMember:
|
||||||
|
def test_invite_member_success(self, client, pro_owner, pro_user2):
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": pro_user2["email"]},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 201
|
||||||
|
data = resp.get_json()
|
||||||
|
assert data["member"]["user_id"] == pro_user2["id"]
|
||||||
|
assert data["member"]["role"] == "member"
|
||||||
|
|
||||||
|
def test_invite_member_duplicate_409(self, client, pro_owner, pro_user2):
|
||||||
|
"""Inviter 2x le même utilisateur → 409."""
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": pro_user2["email"]},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 409
|
||||||
|
|
||||||
|
def test_invite_unknown_email_404(self, client, pro_owner):
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": "nobody@nowhere.com"},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
def test_invite_invalid_email_400(self, client, pro_owner):
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": "not-an-email"},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
def test_invite_non_owner_403(self, client, pro_user2):
|
||||||
|
"""Un simple membre ne peut pas inviter."""
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": "anyone@test.com"},
|
||||||
|
headers=_auth_header(pro_user2["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
def test_invite_fill_to_max(
|
||||||
|
self, client, pro_owner, pro_user3, pro_user4, pro_user5
|
||||||
|
):
|
||||||
|
"""Remplir jusqu'à 5 membres (owner + 4 invités)."""
|
||||||
|
for u in (pro_user3, pro_user4, pro_user5):
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": u["email"]},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 201, (
|
||||||
|
f"Invitation de {u['email']} échouée: {resp.get_json()}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invite_exceeds_max_403(self, client, pro_owner, pro_user6):
|
||||||
|
"""Le 6e membre doit être refusé (max 5)."""
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": pro_user6["email"]},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 403
|
||||||
|
data = resp.get_json()
|
||||||
|
assert "Limite" in data["error"] or "limite" in data["error"].lower()
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests liste des membres
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestListMembers:
|
||||||
|
def test_list_members_as_owner(self, client, pro_owner):
|
||||||
|
resp = client.get(
|
||||||
|
"/api/v1/org/members", headers=_auth_header(pro_owner["token"])
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.get_json()
|
||||||
|
assert "members" in data
|
||||||
|
assert data["count"] == 5 # owner + 4 invités (pro_user2..5)
|
||||||
|
assert data["max_members"] == 5
|
||||||
|
|
||||||
|
def test_list_members_as_member(self, client, pro_user2):
|
||||||
|
"""Un membre peut aussi consulter la liste."""
|
||||||
|
resp = client.get(
|
||||||
|
"/api/v1/org/members", headers=_auth_header(pro_user2["token"])
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.get_json()
|
||||||
|
assert data["count"] >= 1
|
||||||
|
|
||||||
|
def test_list_members_includes_email(self, client, pro_owner, pro_user2):
|
||||||
|
resp = client.get(
|
||||||
|
"/api/v1/org/members", headers=_auth_header(pro_owner["token"])
|
||||||
|
)
|
||||||
|
data = resp.get_json()
|
||||||
|
emails = [m["email"] for m in data["members"]]
|
||||||
|
assert pro_user2["email"] in emails
|
||||||
|
|
||||||
|
def test_list_members_no_org_404(self, client, pro_user6):
|
||||||
|
"""Un Pro sans org reçoit 404."""
|
||||||
|
resp = client.get(
|
||||||
|
"/api/v1/org/members", headers=_auth_header(pro_user6["token"])
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests suppression de membre
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestRemoveMember:
|
||||||
|
def test_remove_member_success(self, client, pro_owner, pro_user5):
|
||||||
|
resp = client.delete(
|
||||||
|
f"/api/v1/org/members/{pro_user5['id']}",
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.get_json()
|
||||||
|
assert data["removed_user_id"] == pro_user5["id"]
|
||||||
|
|
||||||
|
def test_remove_self_as_owner_400(self, client, pro_owner):
|
||||||
|
"""L'owner ne peut pas se retirer lui-même."""
|
||||||
|
resp = client.delete(
|
||||||
|
f"/api/v1/org/members/{pro_owner['id']}",
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
def test_remove_nonexistent_member_404(self, client, pro_owner):
|
||||||
|
resp = client.delete(
|
||||||
|
"/api/v1/org/members/nonexistent-id-xyz",
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
def test_remove_member_non_owner_403(self, client, pro_user2, pro_user3):
|
||||||
|
"""Un simple membre ne peut pas retirer un autre membre."""
|
||||||
|
resp = client.delete(
|
||||||
|
f"/api/v1/org/members/{pro_user3['id']}",
|
||||||
|
headers=_auth_header(pro_user2["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
def test_can_invite_again_after_removal(self, client, pro_owner, pro_user5):
|
||||||
|
"""Après retrait, on peut ré-inviter (slot libéré)."""
|
||||||
|
resp = client.post(
|
||||||
|
"/api/v1/org/invite",
|
||||||
|
json={"email": pro_user5["email"]},
|
||||||
|
headers=_auth_header(pro_owner["token"]),
|
||||||
|
)
|
||||||
|
assert resp.status_code == 201
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests suppression d'organisation
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestDeleteOrg:
|
||||||
|
def test_delete_org_non_owner_403(self, client, pro_user2):
|
||||||
|
"""Un simple membre ne peut pas supprimer l'org."""
|
||||||
|
resp = client.delete("/api/v1/org", headers=_auth_header(pro_user2["token"]))
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
def test_delete_org_success(self, client, pro_owner):
|
||||||
|
"""L'owner peut supprimer l'organisation."""
|
||||||
|
resp = client.delete("/api/v1/org", headers=_auth_header(pro_owner["token"]))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.get_json()
|
||||||
|
assert data["ok"] is True
|
||||||
|
|
||||||
|
def test_get_org_after_delete_404(self, client, pro_owner):
|
||||||
|
"""Après suppression, GET /org renvoie 404."""
|
||||||
|
resp = client.get("/api/v1/org", headers=_auth_header(pro_owner["token"]))
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
def test_delete_org_no_org_403(self, client, pro_owner):
|
||||||
|
"""Supprimer une org qui n'existe plus → 403."""
|
||||||
|
resp = client.delete("/api/v1/org", headers=_auth_header(pro_owner["token"]))
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
def test_members_cascade_deleted(self, client, pro_user2):
|
||||||
|
"""Après suppression de l'org, les membres ne trouvent plus d'org."""
|
||||||
|
resp = client.get(
|
||||||
|
"/api/v1/org/members", headers=_auth_header(pro_user2["token"])
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
Reference in New Issue
Block a user