Compare commits

..

2 Commits

Author SHA1 Message Date
jfgiraud 00bd6ff6fd Menu 1 2 3 4 5 7 8 ok 2026-08-03 15:20:08 +02:00
jfgiraud f37f5b1e45 menu 1 2 3 4 5 7 operationnels 2026-08-03 10:02:12 +02:00
27 changed files with 2950 additions and 1115 deletions
+19
View File
@@ -0,0 +1,19 @@
{
"name": "bourse",
"dockerComposeFile": "../docker-compose.yml",
"service": "web",
"workspaceFolder": "/app",
"remoteUser": "appuser",
"customizations": {
"vscode": {
"extensions": [
"ms-python.python",
"ms-python.vscode-pylance"
],
"settings": {
"python.defaultInterpreterPath": "/usr/local/bin/python"
}
}
}
}
+28
View File
@@ -0,0 +1,28 @@
# VCSP
.git
.gitignore
# Environnement & secrets
.env
.env.*
# Bases de données locales
mysql_data/
*.sqlite3
# Python
__pycache__/
*.py[cod]
venv/
env/
ENV/
# IDE
.vscode/
.idea/
.DS_Store
# Docker
Dockerfile
docker-compose.yml
.dockerignore
+4
View File
@@ -16,5 +16,9 @@ __pycache__/
# Fichiers de base de données locaux (si applicable) # Fichiers de base de données locaux (si applicable)
*.sqlite3 *.sqlite3
# Fichiers de configuration locaux
.env
.env.*
# Base de données MySQL Docker # Base de données MySQL Docker
mysql_data/ mysql_data/
+231
View File
@@ -0,0 +1,231 @@
# AGENTS.md — Projet Bourse
## Description du projet
Application de gestion boursière permettant :
* le suivi des actions et titres financiers ;
* la gestion des ordres d'achat et de vente ;
* l'importation de données financières ;
* la consultation via une interface web et des API.
Le projet doit rester maintenable, sécurisé et compatible avec l'environnement Docker existant.
---
# Architecture technique
## Environnement
Système de développement :
* Ubuntu Linux
* Python 3.x
* environnement virtuel `.venv`
* Docker / Docker Compose
## Technologies principales
Backend :
* Python
* Flask
* API REST
Base de données :
* MySQL 8
* phpMyAdmin pour administration
Frontend :
* HTML
* CSS 
* JavaScript
* Tailwind
Déploiement :
* Docker
* conteneurs séparés pour application et base de données
---
# Règles générales de développement
## Avant toute modification
Toujours :
1. analyser le code existant ;
2. expliquer la cause du problème ;
3. proposer une modification ;
4. attendre validation avant les changements importants.
Ne jamais réécrire une partie complète du projet sans justification.
---
# Python
Respecter :
* PEP8 ;
* code lisible et commenté en Français ;
* fonctions courtes ;
* gestion correcte des exceptions.
Éviter :
* duplication de code ;
* variables globales inutiles ;
* modifications qui cassent l'existant.
Toujours utiliser l'environnement virtuel :
```
.venv
```
---
# Flask
Respecter l'organisation actuelle du projet.
Avant modification :
* identifier les routes existantes ;
* vérifier les dépendances ;
* vérifier les appels frontend/API.
Les nouvelles routes doivent :
* avoir une validation des entrées ;
* retourner des erreurs explicites ;
* utiliser les codes HTTP appropriés.
---
# Base de données MySQL
Règles :
* ne jamais supprimer une table sans confirmation ;
* ne jamais modifier une colonne existante sans vérifier les impacts ;
* toujours proposer une migration SQL.
Respecter les conventions :
* noms de tables en minuscules ;
* clés primaires explicites ;
* index sur les recherches fréquentes.
Avant une requête SQL complexe :
* expliquer son fonctionnement ;
* vérifier les performances.
---
# Données financières
Attention aux données :
* ticker ;
* ISIN ;
* exchange ;
* pays ;
* devise ;
* cours ;
* ordres.
Ne jamais modifier automatiquement une donnée financière sans conserver la valeur précédente si nécessaire.
---
# Docker
Avant modification :
Vérifier :
```
docker ps
docker compose ps
```
Ne jamais :
* supprimer un volume Docker ;
* supprimer une base ;
* reconstruire tous les conteneurs sans raison.
Toujours expliquer :
* quel conteneur est modifié ;
* pourquoi ;
* comment revenir en arrière.
---
# Tests
Après chaque modification importante :
Tester :
* démarrage de l'application ;
* connexion MySQL ;
* appels API ;
* affichage frontend.
Vérifier les logs :
```
docker logs <container>
```
---
# Style de réponse attendu de l'IA
Quand tu analyses ce projet :
1. commence par expliquer ce que tu observes ;
2. indique les fichiers concernés ;
3. propose une solution ;
4. donne les commandes exactes à exécuter.
Ne pas modifier plusieurs fichiers simultanément sans expliquer pourquoi.
---
# Priorités du projet
Ordre des priorités :
1. stabilité ;
2. conservation des données ;
3. sécurité ;
4. performances ;
5. nouvelles fonctionnalités.
---
# Modèle IA utilisé
Le projet utilise OpenCode avec Ollama local :
Modèle principal :
```
qwen2.5-coder:32b
```
L'IA doit privilégier :
* compréhension du code existant ;
* explications techniques ;
* modifications minimales ;
* solutions compatibles avec l'architecture actuelle.
+11 -1
View File
@@ -2,7 +2,17 @@ FROM python:3.11-slim
WORKDIR /app WORKDIR /app
RUN pip install --no-cache-dir flask flask-sqlalchemy pymysql cryptography requests mysql-connector-python # Installation des dépendances (versions fixées dans requirements.txt)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copie du code applicatif
COPY run.py .
COPY app ./app
# Utilisateur non-root pour l'exécution
RUN useradd -m appuser && chown -R appuser:appuser /app
USER appuser
EXPOSE 5000 EXPOSE 5000
+35 -8
View File
@@ -1,19 +1,44 @@
import os
import time import time
from flask import Flask, render_template from flask import Flask
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from sqlalchemy.exc import OperationalError from sqlalchemy.exc import OperationalError
from dotenv import load_dotenv
load_dotenv()
db = SQLAlchemy() db = SQLAlchemy()
csrf = CSRFProtect()
def create_app(): def create_app():
app = Flask(__name__) app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://jfgiraud:lyon4@db/bolsa'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # --- Configuration depuis l'environnement ---
app.config['SECRET_KEY'] = 'votre_cle_secrete_tres_securisee_jfgiraud04051963++fin' app.config["SECRET_KEY"] = os.environ.get(
"SECRET_KEY", "change-me-in-production"
)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db_user = os.environ.get("MYSQL_USER", "jfgiraud")
db_pass = os.environ.get("MYSQL_PASSWORD", "")
db_host = os.environ.get("MYSQL_HOST", "db")
db_port = os.environ.get("MYSQL_PORT", "3306")
db_name = os.environ.get("MYSQL_DATABASE", "bolsa")
# DATABASE_URL prend la priorité si défini
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"DATABASE_URL",
f"mysql+pymysql://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}",
)
db.init_app(app) db.init_app(app)
csrf.init_app(app)
# Tentative de connexion et création des tables au démarrage du conteneur # Enregistrement des modèles ORM (nécessaire avant db.create_all)
from app import models # noqa: F401
# Tentative de connexion au démarrage du conteneur (MySQL peut mettre du temps à être prêt)
with app.app_context(): with app.app_context():
max_retries = 15 max_retries = 15
delay = 2 delay = 2
@@ -22,8 +47,9 @@ def create_app():
db.create_all() db.create_all()
print("Base de données connectée et tables initialisées avec succès.") print("Base de données connectée et tables initialisées avec succès.")
break break
except OperationalError as e: except OperationalError:
print(f"Tentative {i+1}/{max_retries} : MySQL n'est pas encore prêt. Nouvelle tentative dans {delay}s...") print(f"Tentative {i+1}/{max_retries} : MySQL n'est pas encore prêt. "
f"Nouvelle tentative dans {delay}s...")
time.sleep(delay) time.sleep(delay)
else: else:
raise Exception("Impossible d'initialiser la base de données après plusieurs tentatives.") raise Exception("Impossible d'initialiser la base de données après plusieurs tentatives.")
@@ -34,5 +60,6 @@ def create_app():
return app return app
# Expose 'app' pour que run.py puisse l'importer directement # Expose 'app' pour que run.py puisse l'importer directement
app = create_app() app = create_app()
+114
View File
@@ -0,0 +1,114 @@
from datetime import datetime
from app import db
class Login(db.Model):
__tablename__ = "login"
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(50), nullable=False, unique=True)
nom = db.Column(db.String(100), nullable=False)
prenom = db.Column(db.String(100), nullable=False)
mail = db.Column(db.String(255), nullable=False, unique=True)
pass_ = db.Column("pass", db.String(255), nullable=False)
actif = db.Column(db.Boolean, default=True)
creer_le = db.Column(db.DateTime, default=datetime.utcnow)
modifie_le = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
reset_token = db.Column(db.String(255), nullable=True)
reset_token_created_at = db.Column(db.DateTime, nullable=True)
class Action(db.Model):
__tablename__ = "actions"
id = db.Column(db.Integer, primary_key=True)
isin = db.Column(db.String(50), nullable=False, unique=True)
ticker = db.Column(db.String(50))
company_name = db.Column(db.String(255))
exchange = db.Column(db.String(50), nullable=False)
pays = db.Column(db.String(50), nullable=False)
currency = db.Column(db.String(10), nullable=False)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class Societe(db.Model):
__tablename__ = "societe"
id = db.Column(db.Integer, primary_key=True)
nom = db.Column(db.String(60), nullable=False)
forme = db.Column(db.String(10), nullable=False)
capital = db.Column(db.Integer, nullable=False)
siren = db.Column(db.String(20), nullable=False)
siret = db.Column(db.String(20), nullable=False)
rcs = db.Column(db.String(50), nullable=False)
tva = db.Column(db.String(50), nullable=False)
naf = db.Column(db.String(10), nullable=False)
tel = db.Column(db.String(30), nullable=False)
web = db.Column(db.String(100), nullable=False)
mail = db.Column(db.String(100), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
comptes = db.relationship("Compte", backref="societe", lazy=True)
class Compte(db.Model):
__tablename__ = "compte"
id = db.Column(db.Integer, primary_key=True)
id_societe = db.Column(db.Integer, db.ForeignKey("societe.id"), nullable=False)
date_operation = db.Column(db.Date, nullable=False)
debit = db.Column(db.Numeric(15, 2), default=0)
credit = db.Column(db.Numeric(15, 2), default=0)
libelle = db.Column(db.Text)
source = db.Column(db.Enum("manuel", "ordre"), nullable=False, default="manuel")
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class Ordre(db.Model):
__tablename__ = "ordre"
id = db.Column(db.Integer, primary_key=True)
id_societe = db.Column(db.Integer, db.ForeignKey("societe.id"), nullable=False)
isin = db.Column(db.String(50), db.ForeignKey("actions.isin"), nullable=False)
plus_value = db.Column(db.Numeric(19, 4), nullable=False, default=0)
date_plus_value = db.Column(db.Date, nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
pieds = db.relationship("OrdrePied", backref="ordre", lazy=True, cascade="all, delete-orphan")
class OrdrePied(db.Model):
__tablename__ = "ordre_pied"
id = db.Column(db.Integer, primary_key=True)
id_entete = db.Column(db.Integer, db.ForeignKey("ordre.id", ondelete="CASCADE", onupdate="CASCADE"), nullable=False)
date_op = db.Column(db.Date, nullable=False)
quantite = db.Column(db.Integer, nullable=False)
prix_brut = db.Column(db.Numeric(19, 4))
frais_broker = db.Column(db.Numeric(19, 4))
frais_etat = db.Column(db.Numeric(19, 4))
frais_autre = db.Column(db.Numeric(19, 4))
sens = db.Column(db.Enum("achat", "vente"), nullable=False)
position = db.Column(db.Enum("long", "short"), nullable=False)
etat = db.Column(db.Enum("actif", "soldé", "annulé"), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class Historique(db.Model):
__tablename__ = "historique"
id = db.Column(db.Integer, primary_key=True)
isin = db.Column(db.String(50), db.ForeignKey("actions.isin"), nullable=False)
date = db.Column(db.Date, nullable=False)
price = db.Column(db.Numeric(19, 4))
open_ = db.Column("open", db.Numeric(19, 4))
hight = db.Column(db.Numeric(19, 4))
low = db.Column(db.Numeric(19, 4))
vol = db.Column(db.Integer)
change = db.Column(db.Numeric(19, 4))
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
+1361 -662
View File
File diff suppressed because it is too large Load Diff
+15 -11
View File
@@ -1,5 +1,5 @@
<!doctype html> <!doctype html>
<html lang="fr" class="dark"> <html lang="fr" class="dark h-full">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
@@ -14,15 +14,20 @@
<!-- Tailwind CSS CDN --> <!-- Tailwind CSS CDN -->
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script> <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<!-- Font Awesome -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.2/css/all.min.css"
/>
</head> </head>
<body <body
class="bg-gray-950 text-gray-100 min-h-screen flex flex-col justify-between" class="bg-gray-950 text-gray-100 h-screen flex flex-col overflow-hidden"
> >
<!-- Header Global --> <!-- Header Global -->
<header <header
class="bg-gray-900 border-b border-gray-800 px-6 py-4 flex items-center justify-between" class="flex-none bg-gray-900 border-b border-gray-800 px-6 py-4 flex items-center justify-between z-10"
> >
<!-- Gauche : Logo (taille augmentée d'environ 1.5x, ex: h-10 -> h-16) --> <!-- Gauche : Logo -->
<div class="flex items-center"> <div class="flex items-center">
<a <a
href="{{ url_for('main.menu') if session.get('user_id') else url_for('main.index') }}" href="{{ url_for('main.menu') if session.get('user_id') else url_for('main.index') }}"
@@ -35,7 +40,7 @@
</a> </a>
</div> </div>
<!-- Centre : Titre (agrandi avec text-4xl et police plus grasse) --> <!-- Centre : Titre -->
<div class="absolute left-1/2 transform -translate-x-1/2"> <div class="absolute left-1/2 transform -translate-x-1/2">
<h1 class="text-4xl font-extrabold tracking-wider text-white">Bolsa</h1> <h1 class="text-4xl font-extrabold tracking-wider text-white">Bolsa</h1>
</div> </div>
@@ -72,13 +77,13 @@
</header> </header>
<!-- Container dynamique --> <!-- Container dynamique -->
<main class="flex-grow w-full px-2 py-4"> <main class="flex-1 w-full px-2 py-4 overflow-hidden flex flex-col">
{% block content %}{% endblock %} {% block content %}{% endblock %}
</main> </main>
<!-- Footer Global --> <!-- Footer Global -->
<footer <footer
class="bg-gray-900 border-t border-gray-800 px-6 py-4 flex items-center justify-between text-xs text-gray-400" class="flex-none bg-gray-900 border-t border-gray-800 px-6 py-4 flex items-center justify-between text-xs text-gray-400 z-10"
> >
<!-- Espace vide à gauche pour équilibrer le flexbox --> <!-- Espace vide à gauche pour équilibrer le flexbox -->
<div class="w-1/3"></div> <div class="w-1/3"></div>
@@ -101,7 +106,7 @@
</div> </div>
</footer> </footer>
<!-- Script pour récupérer l'IP externe en JS --> <!-- Script pour récupérer l'IP publique en JS -->
{% if session.get('user_id') %} {% if session.get('user_id') %}
<script> <script>
fetch("https://api.ipify.org?format=json") fetch("https://api.ipify.org?format=json")
@@ -109,9 +114,8 @@
.then((data) => { .then((data) => {
document.getElementById("external-ip").textContent = data.ip; document.getElementById("external-ip").textContent = data.ip;
}) })
.catch((error) => { .catch(() => {
document.getElementById("external-ip").textContent = document.getElementById("external-ip").textContent = "IP non disponible";
"IP non disponible";
}); });
</script> </script>
{% endif %} {% endif %}
+1
View File
@@ -107,6 +107,7 @@ content %}
action="" action=""
class="space-y-4 flex-1 flex flex-col justify-between" class="space-y-4 flex-1 flex flex-col justify-between"
> >
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<input type="hidden" id="field-id" name="id" /> <input type="hidden" id="field-id" name="id" />
<div class="space-y-4"> <div class="space-y-4">
+417
View File
@@ -0,0 +1,417 @@
{% extends "base.html" %} {% block title %}Gestion des Comptes - Bolsa{%
endblock %} {% block header_title %}Gestion des comptes{% endblock %} {% block
content %}
<div
class="flex flex-col items-center justify-center w-full h-full overflow-hidden px-2"
>
<!-- Système de Toasts -->
<div
id="toast-container"
class="fixed top-6 left-1/2 transform -translate-x-1/2 z-50 space-y-3 w-full max-w-md px-4 pointer-events-none"
>
{% set messages = get_flashed_messages(with_categories=true) %} {% if
messages %} {% for category, message in messages %}
<div
class="toast-message pointer-events-auto flex items-center justify-center px-4 py-3 rounded-xl shadow-2xl text-white text-sm font-medium transition-all duration-300 transform translate-y-0 opacity-100 text-center {% if category == 'success' %} bg-emerald-600 border border-emerald-500 {% elif category == 'warning' %} bg-amber-600 border border-amber-500 {% else %} bg-rose-600 border border-rose-500 {% endif %}"
>
<span>{{ message }}</span>
</div>
{% endfor %} {% endif %}
</div>
<!-- Box principale -->
<div
class="bg-gray-900 border border-gray-800 rounded-2xl shadow-2xl w-full max-w-[98%] h-full flex flex-col overflow-hidden"
>
<!-- Header fixe de la box -->
<div
class="p-4 sm:p-6 pb-3 border-b border-gray-800 flex justify-between items-center shrink-0"
>
<div>
<h2 class="text-2xl font-extrabold text-white flex items-center gap-2">
<i class="fa-solid fa-wallet text-blue-500"></i> Comptes -
<span class="text-amber-400">{{ selected_societe }}</span>
</h2>
<p class="text-gray-400 text-sm">
Suivi des écritures comptables de la société.
</p>
</div>
<div class="flex items-center gap-4">
<form
method="POST"
action="{{ url_for('main.gestion_comptes') }}"
class="m-0"
>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<select
name="societe_id"
id="select-societe-id"
class="bg-gray-800 border border-gray-700 text-white text-sm rounded-lg px-3 py-2 focus:outline-none focus:border-blue-500 cursor-pointer"
onchange="this.form.submit()"
>
{% for soc in societes %} {% if soc.id == selected_societe_id %}
<option value="{{ soc.id }}" data-nom="{{ soc.nom }}" selected>
{{ soc.nom }}
</option>
{% else %}
<option value="{{ soc.id }}" data-nom="{{ soc.nom }}">
{{ soc.nom }}
</option>
{% endif %} {% endfor %}
</select>
</form>
<!-- Génération automatique des écritures depuis les ordres -->
<form
method="POST"
action="{{ url_for('main.generer_ecritures_ordres') }}"
class="m-0"
onsubmit="return confirm('Générer / régénérer les écritures comptables à partir des ordres de cette société ? Les écritures générées existantes seront remplacées.');"
>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<input type="hidden" name="id_societe" value="{{ selected_societe_id }}" />
<button
type="submit"
class="px-4 py-2 bg-amber-600 hover:bg-amber-500 text-white text-sm font-medium rounded-lg transition duration-200 flex items-center gap-2 cursor-pointer"
title="Générer les écritures depuis les ordres"
>
<i class="fa-solid fa-wand-magic-sparkles"></i> Générer
</button>
</form>
<a
href="{{ url_for('main.menu') }}"
class="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-200 text-sm font-medium rounded-lg transition duration-200"
>
Retour au menu
</a>
</div>
</div>
<!-- Corps scrollable -->
<div class="p-4 sm:p-6 overflow-y-auto flex-1">
<div
class="bg-gray-950 border border-gray-800 rounded-xl p-2 overflow-x-auto"
>
<table class="w-full text-left border-collapse text-sm">
<thead>
<tr
class="bg-blue-950/60 text-gray-400 uppercase tracking-wider text-xs border-b border-gray-800"
>
<th class="py-2 px-3">Date</th>
<th class="py-2 px-3">Libellé</th>
<th class="py-2 px-3 text-right">Crédit</th>
<th class="py-2 px-3 text-right">Débit</th>
<th class="py-2 px-3 text-end">
<button
type="button"
onclick="ouvrirModalCreation()"
class="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold rounded shadow transition cursor-pointer"
>
Créer
</button>
</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-800 text-gray-300">
{% if ecritures %} {% for e in ecritures %}
<tr class="hover:bg-gray-900/50 transition">
<td class="py-2 px-3 whitespace-nowrap">{{ e.date_operation }}</td>
<td class="py-2 px-3 text-gray-400">
{% if e.source == 'ordre' %}{{ e.libelle | safe }}{% else %}{{ e.libelle or '-' }}{% endif %}
</td>
<td class="py-2 px-3 text-right">
{% if e.credit and e.credit > 0 %} {{ "{:,.2f}".format(e.credit)
}} {% else %} - {% endif %}
</td>
<td class="py-2 px-3 text-right">
{% if e.debit and e.debit > 0 %} {{ "{:,.2f}".format(e.debit) }}
{% else %} - {% endif %}
</td>
<td class="py-2 px-3 text-end">
{% if e.source == 'manuel' %}
<button
type="button"
onclick="ouvrirModalModification('{{ e.id }}', '{{ e.date_operation }}', '{{ e.debit }}', '{{ e.credit }}', '{{ e.libelle | e }}')"
class="px-3.5 py-1.5 bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold rounded shadow transition inline-flex items-center justify-center cursor-pointer"
title="Modifier"
>
Modifier
</button>
{% else %}
<span
class="text-[10px] text-gray-600 italic uppercase tracking-wider"
title="Écriture générée automatiquement depuis un ordre"
>Auto</span
>
{% endif %}
</td>
</tr>
{% endfor %} {% else %}
<tr>
<td colspan="5" class="text-center text-gray-500 py-8">
Aucune écriture pour cette société.
</td>
</tr>
{% endif %}
<!-- Ligne TOTAL -->
<tr
class="bg-blue-950/60 text-white uppercase tracking-wider text-xs border-t border-b border-gray-800 font-bold"
>
<td class="py-2.5 px-3">TOTAL :</td>
<td class="py-2.5 px-3"></td>
<td class="py-2.5 px-3 text-right">
{{ "{:,.2f}".format(total_credit or 0) }}
</td>
<td class="py-2.5 px-3 text-right">
{{ "{:,.2f}".format(total_debit or 0) }}
</td>
<td class="py-2.5 px-3"></td>
</tr>
<!-- Ligne DISPO (récapitulatif financier) -->
<tr class="bg-blue-950 text-white border-b border-gray-800">
<td class="py-3 px-4" colspan="5">
<div class="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm font-extrabold">
<span>
SOLDE :
<span class="ml-1 {% if solde >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}">
{{ "{:,.2f}".format(solde | abs) }} €{% if solde < 0 %} (-){% endif %}
</span>
</span>
<span class="text-gray-400">|</span>
<span>
DISPO :
<span class="ml-1 {% if dispo >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}">
{{ "{:,.2f}".format(dispo | abs) }} €{% if dispo < 0 %} (-){% endif %}
</span>
</span>
<span class="text-gray-400">|</span>
<span>
ENGA. :
<span class="ml-1 {% if engagement >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}">
{{ "{:,.2f}".format(engagement | abs) }} €{% if engagement < 0 %} (-){% endif %}
</span>
</span>
<span class="text-gray-400">|</span>
<span>
Depot :
<span class="ml-1 {% if tcredit >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}">
{{ "{:,.2f}".format(tcredit | abs) }} €{% if tcredit < 0 %} (-){% endif %}
</span>
</span>
<span class="text-gray-400">|</span>
<span>
Retrait :
<span class="ml-1 {% if tdebit >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}">
{{ "{:,.2f}".format(tdebit | abs) }} €{% if tdebit < 0 %} (-){% endif %}
</span>
</span>
<span class="text-gray-400">|</span>
<span>
PV :
<span class="ml-1 {% if pv >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}">
{{ "{:,.2f}".format(pv | abs) }} €{% if pv < 0 %} (-){% endif %}
</span>
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Footer -->
<div
class="px-6 py-3 border-t border-gray-800 text-xs text-gray-400 text-center shrink-0 bg-gray-900"
>
Comptes : Accès sécurisé. Veillez à fermer votre session après chaque
utilisation.
</div>
</div>
</div>
<!-- Popup unique (Création et Modification d'écriture) -->
<div
id="modal-compte-ecriture"
class="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center hidden"
>
<div
class="bg-gray-900 border border-gray-800 rounded-2xl p-6 w-full max-w-lg shadow-2xl text-white relative"
>
<button
onclick="fermerModal()"
class="absolute top-4 right-4 text-gray-400 hover:text-white cursor-pointer"
>
<i class="fa-solid fa-xmark text-xl"></i>
</button>
<h3 id="modal-title" class="text-xl font-bold mb-4 flex items-center gap-2">
<i class="fa-solid fa-plus-circle text-emerald-500"></i> Nouvelle écriture
</h3>
<form
id="form-modal-ecriture"
method="POST"
action="{{ url_for('main.creer_compte_traitement') }}"
class="space-y-4"
>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<input type="hidden" name="id_societe" id="input-id-societe" value="{{ selected_societe_id }}" />
<!-- Nom de la société (affichage en lecture seule) -->
<div>
<label class="text-xs text-gray-400">Société</label>
<input
type="text"
id="input-nom-societe"
readonly
class="w-full mt-1 bg-gray-950 border border-gray-800 rounded-lg px-3 py-2 text-sm text-amber-400 font-semibold focus:outline-none cursor-default"
/>
</div>
<!-- Date + Libellé -->
<div class="grid grid-cols-2 gap-3">
<div>
<label class="text-xs text-gray-400">Date d'opération</label>
<input
type="date"
name="date_operation"
id="input-date-operation"
required
class="w-full mt-1 bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
/>
</div>
<div>
<label class="text-xs text-gray-400">Libellé</label>
<input
type="text"
name="libelle"
id="input-libelle"
placeholder="Optionnel..."
class="w-full mt-1 bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
/>
</div>
</div>
<!-- Crédit + Débit -->
<div class="grid grid-cols-2 gap-3">
<div>
<label class="text-xs text-gray-400">Crédit (€)</label>
<input
type="number"
step="0.01"
name="credit"
id="input-credit"
value="0.00"
class="w-full mt-1 bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
/>
</div>
<div>
<label class="text-xs text-gray-400">Débit (€)</label>
<input
type="number"
step="0.01"
name="debit"
id="input-debit"
value="0.00"
class="w-full mt-1 bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
/>
</div>
</div>
<div class="flex justify-end gap-2 pt-2">
<button
type="button"
onclick="fermerModal()"
class="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg text-sm transition cursor-pointer"
>
Annuler
</button>
<button
type="submit"
id="btn-valider"
class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg text-sm transition cursor-pointer"
>
Enregistrer
</button>
</div>
</form>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", () => {
const toasts = document.querySelectorAll(".toast-message");
toasts.forEach((toast) => {
setTimeout(() => {
toast.style.opacity = "0";
toast.style.transform = "translateY(-10px)";
setTimeout(() => toast.remove(), 300);
}, 4000);
});
});
function getInfosSocieteActive() {
const select = document.getElementById("select-societe-id");
if (!select) return { id: "", nom: "" };
const selectedOption = select.options[select.selectedIndex];
return {
id: select.value,
nom: selectedOption ? selectedOption.getAttribute("data-nom") : "",
};
}
function ouvrirModalCreation() {
const modal = document.getElementById("modal-compte-ecriture");
const form = document.getElementById("form-modal-ecriture");
const title = document.getElementById("modal-title");
modal.classList.remove("hidden");
form.action = "{{ url_for('main.creer_compte_traitement') }}";
title.innerHTML =
'<i class="fa-solid fa-plus-circle text-emerald-500"></i> Nouvelle écriture';
const societe = getInfosSocieteActive();
document.getElementById("input-id-societe").value = societe.id;
document.getElementById("input-nom-societe").value = societe.nom;
document.getElementById("input-date-operation").value = "";
document.getElementById("input-libelle").value = "";
document.getElementById("input-credit").value = "0.00";
document.getElementById("input-debit").value = "0.00";
document.getElementById("btn-valider").textContent = "Enregistrer";
}
function ouvrirModalModification(id, dateOp, debit, credit, libelle) {
const modal = document.getElementById("modal-compte-ecriture");
const form = document.getElementById("form-modal-ecriture");
const title = document.getElementById("modal-title");
modal.classList.remove("hidden");
form.action = "/modifier_compte/" + id;
title.innerHTML =
'<i class="fa-solid fa-pen text-blue-500"></i> Modifier l\'écriture';
const societe = getInfosSocieteActive();
document.getElementById("input-id-societe").value = societe.id;
document.getElementById("input-nom-societe").value = societe.nom;
document.getElementById("input-date-operation").value = dateOp;
document.getElementById("input-libelle").value =
libelle === "None" ? "" : libelle;
document.getElementById("input-credit").value = credit;
document.getElementById("input-debit").value = debit;
document.getElementById("btn-valider").textContent = "Modifier";
}
function fermerModal() {
document.getElementById("modal-compte-ecriture").classList.add("hidden");
}
</script>
{% endblock %}
@@ -150,6 +150,7 @@ endblock %} {% block header_title %}Gestion CSV{% endblock %} {% block content
enctype="multipart/form-data" enctype="multipart/form-data"
class="w-full sm:w-3/4 flex items-center gap-2" class="w-full sm:w-3/4 flex items-center gap-2"
> >
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<input <input
type="file" type="file"
name="file" name="file"
@@ -0,0 +1,291 @@
{% extends "base.html" %} {% block title %}Import Historique CSV - Bolsa{% endblock
%} {% block header_title %}Import historique{% endblock %} {% block content %}
<div class="flex flex-col items-center justify-center py-6 relative">
<!-- Système de Toasts -->
<div
id="toast-container"
class="fixed top-6 left-1/2 transform -translate-x-1/2 z-50 space-y-3 w-full max-w-md px-4 pointer-events-none"
>
{% set messages = get_flashed_messages(with_categories=true) %} {% if messages
%} {% for category, message in messages %}
<div
class="toast-message pointer-events-auto flex items-center justify-center px-4 py-3 rounded-xl shadow-2xl text-white text-sm font-medium transition-all duration-300 transform translate-y-0 opacity-100 text-center {% if category == 'success' %} bg-emerald-600 border border-emerald-500 {% elif category == 'warning' %} bg-amber-600 border border-amber-500 {% else %} bg-rose-600 border border-rose-500 {% endif %}"
>
<span>{{ message }}</span>
</div>
{% endfor %} {% endif %}
</div>
<!-- Box centrée principale -->
<div
class="bg-gray-900 border border-gray-800 p-8 rounded-2xl shadow-2xl w-full max-w-3xl overflow-hidden"
>
<!-- 1. En-tête -->
<div
class="flex justify-between items-center px-2 py-2 mb-6 border-b border-gray-800 pb-4"
>
<div>
<h2 class="text-xl font-extrabold text-white flex items-center gap-2">
<i class="fa-solid fa-chart-line text-blue-500"></i> Import Historique
CSV
</h2>
<p class="text-gray-400 text-sm mt-0.5">
Import du cours historique d'une action (OHLCV) par ISIN.
</p>
</div>
<a
href="{{ url_for('main.menu') }}"
class="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-200 text-sm font-medium rounded-lg transition duration-200"
>
Retour au menu
</a>
</div>
<!-- 2. Corps : Box d'importation -->
<form
id="form-import-historique"
action="{{ url_for('main.import_historique_csv') }}"
method="POST"
enctype="multipart/form-data"
class="space-y-6"
>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<div
class="bg-gray-950 border border-gray-800 rounded-xl p-6 space-y-5"
>
<h3
class="text-sm font-semibold text-gray-200 uppercase tracking-wider"
>
Paramètres d'importation
</h3>
<!-- 1. ISIN + vérification dynamique -->
<div>
<label class="block text-xs font-medium text-gray-400 mb-2"
>Code ISIN de l'action</label
>
<div class="flex gap-2">
<input
type="text"
id="input-isin"
name="isin"
required
placeholder="Ex : NL00150001Q9"
class="flex-1 bg-gray-900 border border-gray-800 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-blue-500 uppercase"
/>
<button
type="button"
id="btn-verifier-isin"
onclick="verifierIsin()"
class="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium rounded-lg transition cursor-pointer"
>
<i class="fa-solid fa-check"></i> Vérifier
</button>
</div>
<p id="isin-status" class="text-xs mt-2"></p>
</div>
<!-- 2. Nom de l'action (lecture seule, affiché après vérification) -->
<div>
<label class="block text-xs font-medium text-gray-400 mb-2"
>Nom de l'action</label
>
<div
class="flex items-center bg-gray-950 border border-gray-800 rounded-lg px-3 py-2.5"
>
<input
type="text"
id="input-company-name"
readonly
placeholder="Sera affiché après vérification de l'ISIN..."
class="flex-1 bg-transparent text-amber-400 font-semibold text-sm focus:outline-none cursor-default"
/>
<div
id="action-info"
class="hidden text-xs text-gray-300 ml-3 flex items-center gap-3"
>
<span><strong>Ticker :</strong> <span id="lbl-ticker"></span></span>
<span class="text-gray-600">|</span>
<span><strong>Devise :</strong> <span id="lbl-currency"></span></span>
</div>
</div>
</div>
<!-- 3. Sélection du fichier CSV -->
<div>
<label class="block text-xs font-medium text-gray-400 mb-2"
>Fichier CSV historique</label
>
<input
type="file"
name="file"
accept=".csv"
id="input-file"
required
class="block w-full text-xs text-gray-400 file:mr-4 file:py-3 file:px-4 file:rounded-xl file:border-0 file:text-sm file:font-semibold file:bg-blue-600 file:text-white hover:file:bg-blue-500 file:cursor-pointer cursor-pointer bg-gray-900 border border-gray-800 rounded-xl"
/>
</div>
<!-- Note sur le format attendu -->
<div
class="bg-amber-500/10 border border-amber-500/30 rounded-lg p-3 text-amber-300 text-xs flex items-start space-x-2"
>
<i class="fa-solid fa-circle-info text-amber-400 mt-0.5"></i>
<span>
Format CSV attendu (en-tête obligatoire, séparateur virgule) :
<code
class="text-amber-200 bg-gray-900 px-1.5 py-0.5 rounded font-mono"
>date,price,open,hight,low,vol,change</code
>. La colonne <code class="font-mono">vol</code> accepte les suffixes
<code class="font-mono">K</code> (x1000) et
<code class="font-mono">M</code> (x1 000 000). Les doublons (même
ISIN + même date) sont ignorés automatiquement.
</span>
</div>
</div>
<!-- 4. Bouton de validation -->
<div class="flex items-center justify-end gap-3">
<button
type="button"
onclick="reinitialiser()"
class="px-4 py-2.5 bg-gray-800 hover:bg-gray-700 text-gray-300 text-sm font-medium rounded-xl transition"
>
<i class="fa-solid fa-rotate-left"></i> Réinitialiser
</button>
<button
type="submit"
id="btn-valider"
disabled
class="px-5 py-2.5 bg-emerald-600/50 cursor-not-allowed text-white text-sm font-semibold rounded-xl shadow-lg transition"
>
<i class="fa-solid fa-upload"></i> Importer le fichier
</button>
</div>
</form>
<!-- 3. Pied de boîte -->
<div
class="px-2 py-4 mt-6 text-xs text-gray-400 italic text-center"
>
Module d'import historique sécurisé — Giraud Finance - 2026
</div>
</div>
</div>
<script>
// Disparition automatique des Toasts au bout de 4 secondes
document.addEventListener("DOMContentLoaded", () => {
const toasts = document.querySelectorAll(".toast-message");
toasts.forEach((toast) => {
setTimeout(() => {
toast.style.opacity = "0";
toast.style.transform = "translateY(10px)";
setTimeout(() => toast.remove(), 300);
}, 4000);
});
});
// Vérification dynamique de l'ISIN
function verifierIsin() {
const isin = document.getElementById("input-isin").value.trim();
const statusEl = document.getElementById("isin-status");
const infoBox = document.getElementById("action-info");
const companyInput = document.getElementById("input-company-name");
const btnValider = document.getElementById("btn-valider");
if (!isin) {
statusEl.textContent = "Veuillez saisir un code ISIN.";
statusEl.className = "text-xs mt-2 text-rose-400";
btnValider.disabled = true;
btnValider.className =
"px-5 py-2.5 bg-emerald-600/50 cursor-not-allowed text-white text-sm font-semibold rounded-xl shadow-lg transition";
return;
}
fetch("/api/verifier_isin", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isin: isin }),
})
.then((response) => response.json())
.then((data) => {
if (data.exists) {
statusEl.innerHTML =
'<i class="fa-solid fa-circle-check"></i> ISIN reconnu dans la base.';
statusEl.className = "text-xs mt-2 text-emerald-400";
companyInput.value = data.company_name || "";
document.getElementById("lbl-ticker").textContent =
data.ticker || "N/A";
document.getElementById("lbl-currency").textContent =
data.currency || "N/A";
infoBox.classList.remove("hidden");
btnValider.disabled = false;
btnValider.className =
"px-5 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white text-sm font-semibold rounded-xl shadow-lg transition cursor-pointer";
} else {
statusEl.innerHTML =
'<i class="fa-solid fa-circle-xmark"></i> Cet ISIN n\'existe pas dans la base actions.';
statusEl.className = "text-xs mt-2 text-rose-400";
companyInput.value = "";
infoBox.classList.add("hidden");
btnValider.disabled = true;
btnValider.className =
"px-5 py-2.5 bg-emerald-600/50 cursor-not-allowed text-white text-sm font-semibold rounded-xl shadow-lg transition";
}
})
.catch(() => {
statusEl.textContent = "Erreur de communication avec le serveur.";
statusEl.className = "text-xs mt-2 text-rose-400";
});
}
// Validation du formulaire : ISIN vérifié + fichier sélectionné
document
.getElementById("input-file")
.addEventListener("change", verifierBoutonValider);
function verifierBoutonValider() {
const isinOk =
document.getElementById("input-company-name").value !== "";
const fichierOk =
document.getElementById("input-file").value !== "";
const btnValider = document.getElementById("btn-valider");
if (isinOk && fichierOk) {
btnValider.disabled = false;
btnValider.className =
"px-5 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white text-sm font-semibold rounded-xl shadow-lg transition cursor-pointer";
} else {
btnValider.disabled = true;
btnValider.className =
"px-5 py-2.5 bg-emerald-600/50 cursor-not-allowed text-white text-sm font-semibold rounded-xl shadow-lg transition";
}
}
function reinitialiser() {
document.getElementById("form-import-historique").reset();
document.getElementById("isin-status").textContent = "";
document.getElementById("action-info").classList.add("hidden");
const btnValider = document.getElementById("btn-valider");
btnValider.disabled = true;
btnValider.className =
"px-5 py-2.5 bg-emerald-600/50 cursor-not-allowed text-white text-sm font-semibold rounded-xl shadow-lg transition";
}
// Toujours valider avant soumission (sécurité supplémentaire)
document
.getElementById("form-import-historique")
.addEventListener("submit", (e) => {
const isinOk =
document.getElementById("input-company-name").value !== "";
if (!isinOk) {
e.preventDefault();
alert("Veuillez vérifier l'ISIN avant d'importer.");
}
});
</script>
{% endblock %}
+162 -139
View File
@@ -1,7 +1,7 @@
{% extends "base.html" %} {% block title %}Gestion des Ordres - Bolsa{% endblock {% extends "base.html" %} {% block title %}Gestion des Ordres - Bolsa{% endblock
%} {% block header_title %}Gestion des ordres{% endblock %} {% block content %} %} {% block header_title %}Gestion des ordres{% endblock %} {% block content %}
<div <div
class="flex flex-col items-center justify-center py-2 px-2 relative w-full" class="flex flex-col items-center justify-center w-full h-full overflow-hidden px-2"
> >
<!-- Système de Toasts --> <!-- Système de Toasts -->
<div <div
@@ -18,12 +18,13 @@
{% endfor %} {% endif %} {% endfor %} {% endif %}
</div> </div>
<!-- Box principale --> <!-- Box principale : Hauteur 100% du conteneur parent (qui occupe tout l'espace libre) -->
<div <div
class="bg-gray-900 border border-gray-800 p-4 sm:p-6 rounded-2xl shadow-2xl w-full max-w-[98%]" class="bg-gray-900 border border-gray-800 rounded-2xl shadow-2xl w-full max-w-[98%] h-full flex flex-col overflow-hidden"
> >
<!-- Header fixe de la box -->
<div <div
class="flex justify-between items-center mb-4 border-b border-gray-800 pb-3" class="p-4 sm:p-6 pb-3 border-b border-gray-800 flex justify-between items-center shrink-0"
> >
<div> <div>
<h2 class="text-2xl font-extrabold text-white flex items-center gap-2"> <h2 class="text-2xl font-extrabold text-white flex items-center gap-2">
@@ -43,6 +44,7 @@
action="{{ url_for('main.gestion_ordres') }}" action="{{ url_for('main.gestion_ordres') }}"
class="flex items-center gap-2 m-0" class="flex items-center gap-2 m-0"
> >
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<!-- Conserver la société active lors du changement d'année --> <!-- Conserver la société active lors du changement d'année -->
<input <input
type="hidden" type="hidden"
@@ -71,7 +73,7 @@
<span <span
class="font-bold {% if total_plus_value_globale >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}" class="font-bold {% if total_plus_value_globale >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}"
> >
{{ "{:,.2f}".format(total_plus_value_globale or 0) }} € {{ "{:,.2f}".format(total_plus_value_globale | abs) }} €
</span> </span>
</div> </div>
</form> </form>
@@ -81,6 +83,7 @@
action="{{ url_for('main.gestion_ordres') }}" action="{{ url_for('main.gestion_ordres') }}"
class="m-0" class="m-0"
> >
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<!-- Conserver l'année active lors du changement de société --> <!-- Conserver l'année active lors du changement de société -->
<input <input
type="hidden" type="hidden"
@@ -93,9 +96,9 @@
onchange="this.form.submit()" onchange="this.form.submit()"
> >
{% for soc in societes %} {% if soc.id == selected_societe_id %} {% for soc in societes %} {% if soc.id == selected_societe_id %}
<option value="{{ soc.id }}" selected>{{ soc.Nom }}</option> <option value="{{ soc.id }}" selected>{{ soc.nom }}</option>
{% else %} {% else %}
<option value="{{ soc.id }}">{{ soc.Nom }}</option> <option value="{{ soc.id }}">{{ soc.nom }}</option>
{% endif %} {% endfor %} {% endif %} {% endfor %}
</select> </select>
</form> </form>
@@ -117,144 +120,163 @@
</div> </div>
</div> </div>
<!-- Tableau --> <!-- Corps scrollable de la box (flex-1 et overflow-y-auto pour isoler le défilement) -->
<div <div class="p-4 sm:p-6 overflow-y-auto flex-1">
class="bg-gray-950 border border-gray-800 rounded-xl p-2 overflow-x-auto" <!-- Tableau -->
> <div
<table class="w-full text-left border-collapse text-sm"> class="bg-gray-950 border border-gray-800 rounded-xl p-2 overflow-x-auto"
<tbody class="divide-y divide-gray-800 text-gray-300"> >
{% if groupes_ordres %} {% for groupe in groupes_ordres %} <table class="w-full text-left border-collapse text-sm">
<tr class="bg-blue-950 text-white font-semibold"> <tbody class="divide-y divide-gray-800 text-gray-300">
<td colspan="12" class="py-2.5 px-3 text-base"> {% if groupes_ordres %} {% for groupe in groupes_ordres %}
{{ groupe.isin }} --- {{ groupe.company_name }} ( {{ groupe.ticker <tr class="bg-blue-950 text-white font-semibold">
}} ) <td colspan="12" class="py-2.5 px-3 text-base">
</td> {{ groupe.isin }} --- {{ groupe.company_name }} ( {{
</tr> groupe.ticker }} )
</td>
</tr>
<tr <tr
class="bg-blue-950/60 text-gray-400 uppercase tracking-wider text-xs border-t border-b border-gray-800" class="bg-blue-950/60 text-gray-400 uppercase tracking-wider text-xs border-t border-b border-gray-800"
> >
<th class="py-2 px-3">Date</th> <th class="py-2 px-3">Date</th>
<th class="py-2 px-3">Qté</th> <th class="py-2 px-3">Qté</th>
<th class="py-2 px-3">Prix Brut</th> <th class="py-2 px-3">Prix Brut</th>
<th class="py-2 px-3">Frais</th> <th class="py-2 px-3">Frais</th>
<th class="py-2 px-3">Prix Net</th> <th class="py-2 px-3">Prix Net</th>
<th class="py-2 px-3">Eng. Brut</th> <th class="py-2 px-3">Eng. Brut</th>
<th class="py-2 px-3">Eng. Net</th> <th class="py-2 px-3">Eng. Net</th>
<th class="py-2 px-3">Ordre</th> <th class="py-2 px-3">Ordre</th>
<th class="py-2 px-3">Type</th> <th class="py-2 px-3">Type</th>
<th class="py-2 px-3">État</th> <th class="py-2 px-3">État</th>
<th class="py-2 px-3 text-end"> <th class="py-2 px-3 text-end">
<button <button
type="button" type="button"
onclick="ouvrirModalLigneOrdre('{{ groupe.id }}', '{{ groupe.isin }}', '{{ groupe.company_name }}', '{{ groupe.ticker }}')" onclick="ouvrirModalLigneOrdre('{{ groupe.id }}', '{{ groupe.isin }}', '{{ groupe.company_name }}', '{{ groupe.ticker }}')"
class="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold rounded shadow transition cursor-pointer" class="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold rounded shadow transition cursor-pointer"
> >
Créer Créer
</button> </button>
</th> </th>
</tr> </tr>
{% for p in groupe.pieds %} {% for p in groupe.pieds %}
<tr class="hover:bg-gray-900/50 transition"> <tr class="hover:bg-gray-900/50 transition">
<td class="py-2 px-3 whitespace-nowrap">{{ p.date_op }}</td> <td class="py-2 px-3 whitespace-nowrap">{{ p.date_op }}</td>
<td class="py-2 px-3"> <td class="py-2 px-3">
{{ "{:,.0f}".format(p.quantite).replace(",", " ") }} {{ "{:,.0f}".format(p.quantite).replace(",", " ") }}
</td> </td>
<td class="py-2 px-3">{{ "{:,.3f}".format(p.prix_brut) }}</td> <td class="py-2 px-3">
<td class="py-2 px-3">{{ "{:,.3f}".format(p.frais) }}</td> {{ "{:,.3f}".format(p.prix_brut | abs) }}
<td class="py-2 px-3">{{ "{:,.3f}".format(p.prix_net) }}</td> </td>
<td class="py-2 px-3">{{ "{:,.3f}".format(p.eng_brut) }}</td> <td class="py-2 px-3">{{ "{:,.3f}".format(p.frais | abs) }}</td>
<td class="py-2 px-3">{{ "{:,.3f}".format(p.eng_net) }}</td> <td class="py-2 px-3">
<td class="py-2 px-3"> {{ "{:,.3f}".format(p.prix_net | abs) }}
<span </td>
class="px-2 py-0.5 rounded text-xs font-semibold {% if p.ordre == 'achat' %}bg-blue-900 text-blue-200{% else %}bg-rose-900 text-rose-200{% endif %}" <td class="py-2 px-3">{{ "{:,.3f}".format(p.eng_brut) }}</td>
> <td class="py-2 px-3">{{ "{:,.3f}".format(p.eng_net) }}</td>
{{ p.ordre | upper }} <td class="py-2 px-3">
</span> <span
</td> class="px-2 py-0.5 rounded text-xs font-semibold {% if p.ordre == 'achat' %}bg-blue-900 text-blue-200{% else %}bg-rose-900 text-rose-200{% endif %}"
<td class="py-2 px-3">{{ p.type_ordre }}</td> >
<td class="py-2 px-3"> {{ p.ordre | upper }}
<span </span>
class="px-2 py-0.5 rounded text-xs font-medium {% if p.etat == 'actif' %}bg-emerald-900 text-emerald-200 {% elif p.etat == 'soldé' %}bg-gray-800 text-gray-300 {% else %}bg-amber-900 text-amber-200{% endif %}" </td>
> <td class="py-2 px-3">{{ p.type_ordre }}</td>
{{ p.etat }} <td class="py-2 px-3">
</span> <span
</td> class="px-2 py-0.5 rounded text-xs font-medium {% if p.etat == 'actif' %}bg-emerald-900 text-emerald-200 {% elif p.etat == 'soldé' %}bg-gray-800 text-gray-300 {% else %}bg-amber-900 text-amber-200{% endif %}"
<td class="py-2 px-3 text-end"> >
<button {{ p.etat }}
type="button" </span>
onclick="ouvrirModalModifierLigne('{{ p.id }}', '{{ groupe.isin }}', '{{ groupe.company_name }}', '{{ groupe.ticker }}', '{{ p.date_op }}', '{{ p.quantite }}', '{{ p.prix_brut }}', '{{ p.frais_brocker }}', '{{ p.frais_etat }}', '{{ p.frais_autre }}', '{{ p.ordre }}', '{{ p.type_ordre }}', '{{ p.etat }}')" </td>
class="px-3.5 py-1.5 bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold rounded shadow transition inline-flex items-center justify-center cursor-pointer" <td class="py-2 px-3 text-end">
title="Modifier" <button
> type="button"
Modifier onclick="ouvrirModalModifierLigne('{{ p.id }}', '{{ groupe.isin }}', '{{ groupe.company_name }}', '{{ groupe.ticker }}', '{{ p.date_op }}', '{{ p.quantite }}', '{{ p.prix_brut }}', '{{ p.frais_broker }}', '{{ p.frais_etat }}', '{{ p.frais_autre }}', '{{ p.ordre }}', '{{ p.type_ordre }}', '{{ p.etat }}')"
</button> class="px-3.5 py-1.5 bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold rounded shadow transition inline-flex items-center justify-center cursor-pointer"
</td> title="Modifier"
</tr> >
{% endfor %} Modifier
</button>
</td>
</tr>
{% endfor %}
<!-- LIGNE TOTAL --> <!-- LIGNE TOTAL -->
<tr <tr
class="bg-blue-950/60 text-white uppercase tracking-wider text-xs border-t border-b border-gray-800 font-bold" class="bg-blue-950/60 text-white uppercase tracking-wider text-xs border-t border-b border-gray-800 font-bold"
> >
<td class="py-2.5 px-3">TOTAL :</td> <td class="py-2.5 px-3">TOTAL :</td>
<td class="py-2.5 px-3"> <td class="py-2.5 px-3">
{{ "{:,.0f}".format(groupe.total_quantite).replace(",", " ") }} {{ "{:,.0f}".format(groupe.total_quantite).replace(",", " ") }}
</td> </td>
{% if groupe.total_quantite != 0 %} {% set total_prix_net_moyen = {% if groupe.total_quantite != 0 %} {% set total_prix_net_moyen =
(groupe.total_eng_net / groupe.total_quantite) | abs %} {% set (groupe.total_eng_net / groupe.total_quantite) %} {% set
total_prix_brut_moyen = (groupe.total_eng_brut / total_prix_brut_moyen = (groupe.total_eng_brut /
groupe.total_quantite) | abs %} {% set total_frais_moyen = groupe.total_quantite) %} {% set total_frais_moyen =
(total_prix_net_moyen - total_prix_brut_moyen) | abs %} (total_prix_net_moyen - total_prix_brut_moyen) %}
<td class="py-2.5 px-3"> <td class="py-2.5 px-3">
{{ "{:,.3f}".format(total_prix_brut_moyen) }} {{ "{:,.3f}".format(total_prix_brut_moyen | abs) }}
</td> </td>
<td class="py-2.5 px-3"> <td class="py-2.5 px-3">
{{ "{:,.3f}".format(total_frais_moyen) }} {{ "{:,.3f}".format(total_frais_moyen | abs) }}
</td> </td>
<td class="py-2.5 px-3"> <td class="py-2.5 px-3">
{{ "{:,.3f}".format(total_prix_net_moyen) }} {{ "{:,.3f}".format(total_prix_net_moyen | abs) }}
</td> </td>
<td class="py-2.5 px-3"> <td class="py-2.5 px-3">
{{ "{:,.3f}".format(groupe.total_eng_brut | abs) }} {{ "{:,.3f}".format(groupe.total_eng_brut) }}
</td> </td>
<td class="py-2.5 px-3"> <td class="py-2.5 px-3">
{{ "{:,.3f}".format(groupe.total_eng_net | abs) }} <span
</td> class="{% if groupe.total_eng_net >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}"
{% else %} >
<td class="py-2.5 px-3">-</td> {{ "{:,.3f}".format(groupe.total_eng_net) }}
<td class="py-2.5 px-3">-</td> </span>
<td class="py-2.5 px-3">-</td> </td>
<td class="py-2.5 px-3"> {% else %}
{{ "{:,.3f}".format(groupe.total_eng_brut | abs) }} <td class="py-2.5 px-3">-</td>
</td> <td class="py-2.5 px-3">-</td>
<td class="py-2.5 px-3"> <td class="py-2.5 px-3">-</td>
<span <td class="py-2.5 px-3">
class="{% if groupe.total_eng_net >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}" {{ "{:,.3f}".format(groupe.total_eng_brut) }}
> </td>
{{ "{:,.3f}".format(groupe.total_eng_net | abs) }} <td class="py-2.5 px-3">
</span> <span
</td> class="{% if groupe.total_eng_net >= 0 %}text-emerald-400{% else %}text-rose-400{% endif %}"
>
{{ "{:,.3f}".format(groupe.total_eng_net) }}
</span>
</td>
{% endif %}
<td class="py-2.5 px-3" colspan="4"></td>
</tr>
<tr>
<td colspan="11" class="h-3 bg-transparent border-0"></td>
</tr>
{% endfor %} {% else %}
<tr>
<td colspan="11" class="text-center text-gray-500 py-8">
Aucun ordre trouvé pour cette société.
</td>
</tr>
{% endif %} {% endif %}
</tbody>
</table>
</div>
</div>
<td class="py-2.5 px-3" colspan="4"></td> <!-- Footer fixe de la box -->
</tr> <div
class="px-6 py-3 border-t border-gray-800 text-xs text-gray-400 text-center shrink-0 bg-gray-900"
<tr> >
<td colspan="11" class="h-3 bg-transparent border-0"></td> Positions en bourse : Accès sécurisé. Veillez à fermer votre session après
</tr> chaque utilisation.
{% endfor %} {% else %}
<tr>
<td colspan="11" class="text-center text-gray-500 py-8">
Aucun ordre trouvé pour cette société.
</td>
</tr>
{% endif %}
</tbody>
</table>
</div> </div>
</div> </div>
</div> </div>
@@ -285,6 +307,7 @@
action="{{ url_for('main.creer_ordre_traitement') }}" action="{{ url_for('main.creer_ordre_traitement') }}"
class="space-y-4" class="space-y-4"
> >
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<!-- Transmettre dynamiquement l'année active dans le formulaire de la modale --> <!-- Transmettre dynamiquement l'année active dans le formulaire de la modale -->
<input <input
type="hidden" type="hidden"
@@ -385,7 +408,7 @@
type="number" type="number"
step="0.0001" step="0.0001"
id="input-frais-brocker" id="input-frais-brocker"
name="frais_brocker" name="frais_broker"
value="0.0000" value="0.0000"
oninput="calculerTotauxModal()" oninput="calculerTotauxModal()"
class="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500" class="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
+14 -13
View File
@@ -57,15 +57,15 @@ content %}
<div class="overflow-y-auto flex-1 space-y-1 pr-1"> <div class="overflow-y-auto flex-1 space-y-1 pr-1">
{% for s in societes %} {% for s in societes %}
<div <div
onclick="selectionnerSociete('{{ s.id }}', '{{ s.Nom | e }}', '{{ s.Forme | e }}', '{{ s.Capital }}', '{{ s.siren }}', '{{ s.siret }}', '{{ s.RCS | e }}', '{{ s.TVA | e }}', '{{ s.NAF | e }}', '{{ s.Tel | e }}', '{{ s.Web | e }}', '{{ s.Mail | e }}')" onclick="selectionnerSociete('{{ s.id }}', '{{ s.nom | e }}', '{{ s.forme | e }}', '{{ s.capital }}', '{{ s.siren }}', '{{ s.siret }}', '{{ s.rcs | e }}', '{{ s.tva | e }}', '{{ s.naf | e }}', '{{ s.tel | e }}', '{{ s.web | e }}', '{{ s.mail | e }}')"
class="societe-item cursor-pointer px-3 py-2.5 rounded-lg {% if loop.first %}bg-blue-600 text-white{% else %}hover:bg-gray-800 text-gray-300{% endif %} font-medium text-sm transition flex justify-between items-center" class="societe-item cursor-pointer px-3 py-2.5 rounded-lg {% if loop.first %}bg-blue-600 text-white{% else %}hover:bg-gray-800 text-gray-300{% endif %} font-medium text-sm transition flex justify-between items-center"
data-id="{{ s.id }}" data-id="{{ s.id }}"
> >
<span class="truncate pr-2 font-semibold">{{ s.Nom }}</span> <span class="truncate pr-2 font-semibold">{{ s.nom }}</span>
<span <span
class="text-xs {% if loop.first %}bg-blue-800{% else %}bg-gray-800 text-gray-400{% endif %} px-2 py-0.5 rounded whitespace-nowrap" class="text-xs {% if loop.first %}bg-blue-800{% else %}bg-gray-800 text-gray-400{% endif %} px-2 py-0.5 rounded whitespace-nowrap"
> >
{{ s.Forme or 'N/A' }} {{ s.forme or 'N/A' }}
</span> </span>
</div> </div>
{% endfor %} {% endfor %}
@@ -82,7 +82,8 @@ content %}
action="" action=""
class="space-y-4 flex-1 flex flex-col justify-between" class="space-y-4 flex-1 flex flex-col justify-between"
> >
<!-- ID technique caché --> <!-- Jeton CSRF + ID technique caché -->
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<input type="hidden" id="field-id" name="id" /> <input type="hidden" id="field-id" name="id" />
<div class="space-y-4"> <div class="space-y-4">
@@ -101,7 +102,7 @@ content %}
<input <input
type="text" type="text"
id="field-nom" id="field-nom"
name="Nom" name="nom"
required required
maxlength="60" maxlength="60"
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
@@ -114,7 +115,7 @@ content %}
<input <input
type="text" type="text"
id="field-forme" id="field-forme"
name="Forme" name="forme"
required required
maxlength="10" maxlength="10"
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
@@ -127,7 +128,7 @@ content %}
<input <input
type="number" type="number"
id="field-capital" id="field-capital"
name="Capital" name="capital"
required required
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
/> />
@@ -174,7 +175,7 @@ content %}
<input <input
type="text" type="text"
id="field-rcs" id="field-rcs"
name="RCS" name="rcs"
required required
maxlength="50" maxlength="50"
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
@@ -189,7 +190,7 @@ content %}
<input <input
type="text" type="text"
id="field-tva" id="field-tva"
name="TVA" name="tva"
required required
maxlength="50" maxlength="50"
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
@@ -204,7 +205,7 @@ content %}
<input <input
type="text" type="text"
id="field-naf" id="field-naf"
name="NAF" name="naf"
required required
maxlength="10" maxlength="10"
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
@@ -219,7 +220,7 @@ content %}
<input <input
type="text" type="text"
id="field-tel" id="field-tel"
name="Tel" name="tel"
required required
maxlength="30" maxlength="30"
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
@@ -234,7 +235,7 @@ content %}
<input <input
type="text" type="text"
id="field-web" id="field-web"
name="Web" name="web"
required required
maxlength="100" maxlength="100"
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
@@ -249,7 +250,7 @@ content %}
<input <input
type="email" type="email"
id="field-mail" id="field-mail"
name="Mail" name="mail"
required required
maxlength="100" maxlength="100"
class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500" class="w-full bg-gray-900 border border-gray-800 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-blue-500"
+2 -1
View File
@@ -83,7 +83,8 @@ content %}
action="" action=""
class="space-y-4 flex-1 flex flex-col justify-between" class="space-y-4 flex-1 flex flex-col justify-between"
> >
<!-- ID technique caché --> <!-- Jeton CSRF + ID technique caché -->
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<input type="hidden" id="field-id" name="id" /> <input type="hidden" id="field-id" name="id" />
<div class="space-y-4"> <div class="space-y-4">
+1
View File
@@ -18,6 +18,7 @@ block content %}
{% endif %} {% endwith %} {% endif %} {% endwith %}
<form method="POST" action="{{ url_for('main.index') }}" class="space-y-4"> <form method="POST" action="{{ url_for('main.index') }}" class="space-y-4">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<div> <div>
<label for="login" class="block text-sm font-medium text-gray-300 mb-1" <label for="login" class="block text-sm font-medium text-gray-300 mb-1"
>Login :</label >Login :</label
+2 -2
View File
@@ -31,7 +31,7 @@ header_title %}Tableau de bord{% endblock %} {% block content %}
<!-- btn 3 --> <!-- btn 3 -->
<a <a
href="#" href="{{ url_for('main.gestion_comptes') }}"
class="py-6 px-6 bg-gray-950 hover:bg-blue-600/30 border-2 border-gray-800 hover:border-blue-500 rounded-xl text-white text-lg font-bold tracking-wide transition-all duration-200 flex items-center justify-center shadow-lg hover:scale-[1.01]" class="py-6 px-6 bg-gray-950 hover:bg-blue-600/30 border-2 border-gray-800 hover:border-blue-500 rounded-xl text-white text-lg font-bold tracking-wide transition-all duration-200 flex items-center justify-center shadow-lg hover:scale-[1.01]"
> >
3. Comptes 3. Comptes
@@ -71,7 +71,7 @@ header_title %}Tableau de bord{% endblock %} {% block content %}
<!-- btn 8 --> <!-- btn 8 -->
<a <a
href="#" href="{{ url_for('main.gestion_import_historique_csv') }}"
class="py-6 px-6 bg-gray-950 hover:bg-blue-600/30 border-2 border-gray-800 hover:border-blue-500 rounded-xl text-white text-lg font-bold tracking-wide transition-all duration-200 flex items-center justify-center shadow-lg hover:scale-[1.01]" class="py-6 px-6 bg-gray-950 hover:bg-blue-600/30 border-2 border-gray-800 hover:border-blue-500 rounded-xl text-white text-lg font-bold tracking-wide transition-all duration-200 flex items-center justify-center shadow-lg hover:scale-[1.01]"
> >
8. Import historique CSV 8. Import historique CSV
-112
View File
@@ -1,112 +0,0 @@
import time
import requests
import mysql.connector
def importer_actions():
API_KEY = "6a6235c8a742b2.89238466"
MYSQL = {
"host": "db",
"port": 3306,
"user": "root",
"password": "sysadm-1963",
"database": "bourse"
}
EXCHANGES = [
"PA", "US", "BR", "KLSE", "LS", "XETRA", "LU", "OL", "ST", "CO", "IR", "KO", "AU", "SHE", "SHG", "AT",
"F", "STU", "MU", "HA", "DU", "HM", "VI", "SW", "TO", "AU", "HK", "TWO", "MC"
]
print("Connexion à la base de données MySQL...")
try:
db_conn = mysql.connector.connect(**MYSQL)
cursor = db_conn.cursor()
print("Connecté avec succès à la base MySQL : [bourse]")
except Exception as e:
print(f"Erreur de connexion MySQL : {e}")
return
print("Vidage de la table les_actions...")
try:
cursor.execute("TRUNCATE TABLE les_actions;")
db_conn.commit()
except Exception as e:
print(f"Erreur lors du TRUNCATE : {e}")
sql = """
INSERT INTO les_actions (isin, ticker, name, exchange, pays, devise)
VALUES (%s, %s, %s, %s, %s, %s)
"""
total_global = 0
try:
for exchange in EXCHANGES:
url = f"https://eodhd.com/api/exchange-symbol-list/{exchange}?api_token={API_KEY}&fmt=json"
print(f"\n--- Traitement de la bourse : {exchange} ---")
req_timeout = 300 if exchange == "US" else 60
try:
r = requests.get(url, timeout=req_timeout)
if r.status_code != 200:
print(f"[{exchange}] Erreur HTTP {r.status_code}")
continue
data = r.json()
except Exception as err:
print(f"[{exchange}] Erreur requête ou timeout : {err}")
continue
if not isinstance(data, list):
print(f"[{exchange}] Le format reçu n'est pas une liste.")
continue
print(f"[{exchange}] {len(data)} éléments reçus. Insertion en cours...")
lignes = []
for item in data:
isin = item.get("ISIN") or item.get("isin")
ticker = item.get("Code") or item.get("code")
name = item.get("Name") or item.get("name")
exch = item.get("Exchange") or item.get("exchange") or exchange
pays = item.get("Country") or item.get("country")
devise = item.get("Currency") or item.get("currency")
if not ticker:
continue
lignes.append((
str(isin)[:12] if isin else None,
str(ticker)[:20] if ticker else None,
str(name)[:150] if name else None,
str(exch)[:50] if exch else None,
str(pays)[:50] if pays else None,
str(devise)[:10] if devise else None
))
if lignes:
# Utilisation d'executemany par paquets pour un maximum de performance
batch_size = 5000
for i in range(0, len(lignes), batch_size):
batch = lignes[i:i + batch_size]
cursor.executemany(sql, batch)
db_conn.commit()
total_global += len(lignes)
print(f"-> Succès : {len(lignes)} actions insérées pour {exchange}.")
time.sleep(1)
# Vérification finale du nombre de lignes dans la table
cursor.execute("SELECT COUNT(*) FROM les_actions;")
count = cursor.fetchone()[0]
print(f"\nTerminé ! Total global traité : {total_global} lignes. Comptage réel en base : {count} lignes.")
except Exception as e:
print(f"Erreur générale : {e}")
finally:
cursor.close()
db_conn.close()
print("Connexion fermée.")
if __name__ == "__main__":
importer_actions()
-115
View File
@@ -1,115 +0,0 @@
#!/usr/bin/env python3
import csv
import mysql.connector
# ==========================================
# CONFIGURATION
# ==========================================
CSV_FILE = "/app/isin.csv"
# Pays associé au fichier CSV
PAYS = "France"
MYSQL = {
"host": "db",
"port": 3306,
"user": "root",
"password": "sysadm-1963",
"database": "bourse"
}
# ==========================================
# CONNEXION MYSQL
# ==========================================
try:
db = mysql.connector.connect(**MYSQL)
print("Connexion MySQL OK")
except Exception as e:
print("Erreur MySQL :", e)
exit(1)
cursor = db.cursor(dictionary=True)
# ==========================================
# CHARGEMENT DU CSV
# ==========================================
print("Chargement du CSV...")
csv_data = {}
with open(CSV_FILE, newline="", encoding="utf-8-sig") as f:
reader = csv.reader(f, delimiter=";")
for row in reader:
if len(row) < 3:
continue
isin = row[0].strip().upper()
ticker = row[2].strip().upper()
if ticker:
csv_data[(ticker, PAYS.upper())] = isin
print(f"{len(csv_data)} ISIN chargés.")
# ==========================================
# LECTURE DE LA TABLE
# ==========================================
cursor.execute("""
SELECT
id,
ticker,
pays,
isin
FROM les_actions
""")
lignes = cursor.fetchall()
print(f"{len(lignes)} actions lues.")
# ==========================================
# MISE A JOUR
# ==========================================
sql_update = """
UPDATE les_actions
SET isin = %s
WHERE id = %s
"""
update_data = []
for ligne in lignes:
ticker = (ligne["ticker"] or "").strip().upper()
pays = (ligne["pays"] or "").strip().upper()
cle = (ticker, pays)
if cle in csv_data:
update_data.append((
csv_data[cle],
ligne["id"]
))
print(f"{len(update_data)} lignes à mettre à jour.")
if update_data:
cursor.executemany(sql_update, update_data)
db.commit()
print("===================================")
print(f"{len(update_data)} ISIN mis à jour.")
print("===================================")
cursor.close()
db.close()
-31
View File
@@ -1,31 +0,0 @@
from werkzeug.security import generate_password_hash
from sqlalchemy import text
from app import app, db
with app.app_context():
# Définition des informations de l'utilisateur
login_name = "jfgiraud"
nom = "GIRAUD"
prenom = "Jean-François"
mail = "jfgiraud@giraud-finance.com"
# Génération du hash sécurisé pour le mot de passe "lyon4"
hashed_password = generate_password_hash("lyon4")
# Requête d'insertion
query = text("""
INSERT INTO login (login, nom, prenom, mail, pass, actif)
VALUES (:login, :nom, :prenom, :mail, :pass, 1)
ON DUPLICATE KEY UPDATE
pass = :pass, nom = :nom, prenom = :prenom, mail = :mail, actif = 1
""")
db.session.execute(query, {
"login": login_name,
"nom": nom,
"prenom": prenom,
"mail": mail,
"pass": hashed_password
})
db.session.commit()
print(f"Utilisateur '{login_name}' créé/mis à jour avec succès avec un mot de passe haché !")
-5
View File
@@ -1,5 +0,0 @@
Pour exécuter ce script directement à l'intérieur du conteneur web utiliser la commande suivante dans votre terminal :
docker compose exec web python create_user.py
Une fois cette commande passée, vous pourrez vous connecter sur votre page d'accueil avec le login jfgiraud et le mot de passe lyon4.
+15 -13
View File
@@ -1,13 +1,10 @@
services: services:
db: db:
image: mysql:8.0 image: mysql:8.0
environment: env_file: .env
MYSQL_ROOT_PASSWORD: sysadm-1963
MYSQL_DATABASE: bolsa
MYSQL_USER: jfgiraud
MYSQL_PASSWORD: lyon4
volumes: volumes:
- db_data:/var/lib/mysql - db_data:/var/lib/mysql
- ./migrations/schema.sql:/docker-entrypoint-initdb.d/01_schema.sql:ro
healthcheck: healthcheck:
test: test:
[ [
@@ -18,34 +15,39 @@ services:
"127.0.0.1", "127.0.0.1",
"-u", "-u",
"root", "root",
"-psysadm-1963", "-p${MYSQL_ROOT_PASSWORD}",
] ]
interval: 3s interval: 3s
timeout: 3s timeout: 3s
retries: 10 retries: 10
restart: unless-stopped
web: web:
build: . build: .
command: python run.py env_file: .env
environment:
- FLASK_ENV=${FLASK_ENV}
volumes: volumes:
- .:/app # Montage restreint au code applicatif (pas .git / mysql_data / .env)
- ./app:/app/app
ports: ports:
- "5000:5000" - "5000:5000"
environment:
- DATABASE_URL=mysql+pymysql://jfgiraud:lyon4@db/bolsa
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
restart: unless-stopped
phpmyadmin: phpmyadmin:
image: phpmyadmin/phpmyadmin image: phpmyadmin/phpmyadmin
ports: env_file: .env
- "8080:80"
environment: environment:
PMA_HOST: db PMA_HOST: db
MYSQL_ROOT_PASSWORD: sysadm-1963 ports:
# Accès local uniquement (pas d'exposition publique)
- "127.0.0.1:8080:80"
depends_on: depends_on:
- db - db
restart: unless-stopped
volumes: volumes:
db_data: db_data:
+89
View File
@@ -0,0 +1,89 @@
"""
Application séquentielle des migrations SQL du dossier `migrations/`
sur la base « bolsa ». À exécuter depuis la racine du projet :
python migrations/apply_migrations.py
Lit la configuration MySQL depuis les variables d'environnement (.env).
N'applique que les fichiers non déjà enregistrés dans la table
`__migrations__` (créée automatiquement).
"""
import os
import sys
from pathlib import Path
import pymysql
from dotenv import load_dotenv
load_dotenv()
MIGRATIONS_DIR = Path(__file__).parent
def get_connection():
return pymysql.connect(
host=os.environ.get("MYSQL_HOST", "db"),
port=int(os.environ.get("MYSQL_PORT", "3306")),
user=os.environ.get("MYSQL_USER", "jfgiraud"),
password=os.environ.get("MYSQL_PASSWORD", ""),
database=os.environ.get("MYSQL_DATABASE", "bolsa"),
charset="utf8mb4",
autocommit=False,
)
def main():
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(
"CREATE TABLE IF NOT EXISTS `__migrations__` ("
" `id` int NOT NULL AUTO_INCREMENT,"
" `filename` varchar(255) NOT NULL,"
" `applied_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,"
" PRIMARY KEY (`id`),"
" UNIQUE KEY `idx_filename` (`filename`)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
)
conn.commit()
cur.execute("SELECT filename FROM `__migrations__`")
applied = {row[0] for row in cur.fetchall()}
sql_files = sorted(
f for f in MIGRATIONS_DIR.glob("*.sql")
if f.name != "schema.sql"
)
if not sql_files:
print("Aucune migration à appliquer.")
return
for sql_file in sql_files:
if sql_file.name in applied:
print(f"[déjà appliquée] {sql_file.name}")
continue
print(f"[application] {sql_file.name}")
sql = sql_file.read_text(encoding="utf-8")
# Découpage sur les ';' pour exécuter instruction par instruction
statements = [s.strip() for s in sql.split(";") if s.strip()]
for stmt in statements:
cur.execute(stmt)
cur.execute(
"INSERT INTO `__migrations__` (filename) VALUES (%s)",
(sql_file.name,),
)
conn.commit()
print(f"[OK] {sql_file.name}")
except Exception as e:
conn.rollback()
print(f"[ERREUR] {e}", file=sys.stderr)
sys.exit(1)
finally:
conn.close()
if __name__ == "__main__":
main()
+128
View File
@@ -0,0 +1,128 @@
-- =====================================================================
# Schéma de la base « bolsa » version de référence (snake_case)
-- =====================================================================
# Tables : login, actions, societe, compte, ordre, ordre_pied
# Encodage : utf8mb4 / utf8mb4_0900_ai_ci
# Ce fichier est exécuté automatiquement par Docker sur une base vierge
# (monté dans /docker-entrypoint-initdb.d/). Sur une base existante, les
# CREATE TABLE IF NOT EXISTS sont sans effet.
-- =====================================================================
CREATE TABLE IF NOT EXISTS `login` (
`id` int NOT NULL AUTO_INCREMENT,
`login` varchar(50) NOT NULL,
`nom` varchar(100) NOT NULL,
`prenom` varchar(100) NOT NULL,
`mail` varchar(255) NOT NULL,
`pass` varchar(255) NOT NULL,
`actif` tinyint(1) DEFAULT NULL,
`creer_le` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`modifie_le` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`reset_token` varchar(255) DEFAULT NULL,
`reset_token_created_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_login` (`login`),
UNIQUE KEY `idx_mail` (`mail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `actions` (
`id` int NOT NULL AUTO_INCREMENT,
`isin` varchar(50) NOT NULL,
`ticker` varchar(50) DEFAULT NULL,
`company_name` varchar(255) DEFAULT NULL,
`exchange` varchar(50) NOT NULL,
`pays` varchar(50) NOT NULL,
`currency` varchar(10) NOT NULL,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `isin` (`isin`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `societe` (
`id` int NOT NULL AUTO_INCREMENT,
`nom` varchar(60) NOT NULL,
`forme` varchar(10) NOT NULL,
`capital` int NOT NULL,
`siren` varchar(20) NOT NULL,
`siret` varchar(20) NOT NULL,
`rcs` varchar(50) NOT NULL,
`tva` varchar(50) NOT NULL,
`naf` varchar(10) NOT NULL,
`tel` varchar(30) NOT NULL,
`web` varchar(100) NOT NULL,
`mail` varchar(100) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `compte` (
`id` int NOT NULL AUTO_INCREMENT,
`id_societe` int NOT NULL,
`date_operation` date NOT NULL,
`debit` decimal(15,2) DEFAULT '0.00',
`credit` decimal(15,2) DEFAULT '0.00',
`libelle` text,
`source` enum('manuel','ordre') NOT NULL DEFAULT 'manuel',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_compte_societe` (`id_societe`),
CONSTRAINT `fk_compte_societe` FOREIGN KEY (`id_societe`)
REFERENCES `societe` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `ordre` (
`id` int NOT NULL AUTO_INCREMENT,
`id_societe` int NOT NULL,
`isin` varchar(50) NOT NULL,
`plus_value` decimal(19,4) NOT NULL DEFAULT '0.0000',
`date_plus_value` date DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `fk_ordre_societe` (`id_societe`),
KEY `fk_ordre_actions` (`isin`),
CONSTRAINT `fk_ordre_societe` FOREIGN KEY (`id_societe`)
REFERENCES `societe` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_ordre_actions` FOREIGN KEY (`isin`)
REFERENCES `actions` (`isin`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `ordre_pied` (
`id` int NOT NULL AUTO_INCREMENT,
`id_entete` int NOT NULL,
`date_op` date NOT NULL,
`quantite` int NOT NULL,
`prix_brut` decimal(19,4) DEFAULT NULL,
`frais_broker` decimal(19,4) DEFAULT NULL,
`frais_etat` decimal(19,4) DEFAULT NULL,
`frais_autre` decimal(19,4) DEFAULT NULL,
`sens` enum('achat','vente') NOT NULL,
`position` enum('long','short') NOT NULL,
`etat` enum('actif','soldé','annulé') NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_ordre_pied_entete` (`id_entete`),
CONSTRAINT `fk_ordre_pied_entete` FOREIGN KEY (`id_entete`)
REFERENCES `ordre` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `historique` (
`id` int NOT NULL AUTO_INCREMENT,
`isin` varchar(50) NOT NULL,
`date` date NOT NULL,
`price` decimal(19,4) DEFAULT NULL,
`open` decimal(19,4) DEFAULT NULL,
`hight` decimal(19,4) DEFAULT NULL,
`low` decimal(19,4) DEFAULT NULL,
`vol` int DEFAULT NULL,
`change` decimal(19,4) DEFAULT NULL,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_isin_date` (`isin`, `date`),
CONSTRAINT `fk_historique_actions` FOREIGN KEY (`isin`)
REFERENCES `actions` (`isin`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+5
View File
@@ -1,17 +1,22 @@
blinker==1.9.0 blinker==1.9.0
certifi==2026.7.22 certifi==2026.7.22
charset-normalizer==3.4.9 charset-normalizer==3.4.9
cryptography
click==8.4.2 click==8.4.2
Flask==3.1.3 Flask==3.1.3
Flask-SQLAlchemy==3.1.1 Flask-SQLAlchemy==3.1.1
Flask-WTF==1.2.1
greenlet==3.5.4 greenlet==3.5.4
idna==3.18 idna==3.18
itsdangerous==2.2.0 itsdangerous==2.2.0
Jinja2==3.1.6 Jinja2==3.1.6
MarkupSafe==3.0.3 MarkupSafe==3.0.3
mysql-connector-python==9.7.0 mysql-connector-python==9.7.0
python-dotenv==1.1.1
PyMySQL==1.1.1
requests==2.34.2 requests==2.34.2
SQLAlchemy==2.0.51 SQLAlchemy==2.0.51
typing_extensions==4.16.0 typing_extensions==4.16.0
urllib3==2.7.0 urllib3==2.7.0
Werkzeug==3.1.8 Werkzeug==3.1.8
WTForms==3.1.2
+4 -2
View File
@@ -1,4 +1,6 @@
import os
from app import app from app import app
if __name__ == '__main__': if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True) debug = os.environ.get("FLASK_ENV") == "development"
app.run(host="0.0.0.0", port=5000, debug=debug)