Mise en forme tracker
This commit is contained in:
@@ -2,7 +2,7 @@
|
|||||||
# -------------------------------------------------------------
|
# -------------------------------------------------------------
|
||||||
# Streamlit — Gestion de la table MySQL Sondes.tracker
|
# Streamlit — Gestion de la table MySQL Sondes.tracker
|
||||||
# -------------------------------------------------------------
|
# -------------------------------------------------------------
|
||||||
# Hypothèses colonnes existantes : id (PK), address, lieu, res_bits, date (timestamp)
|
# Schéma attendu : id (PK), address, lieu, repere (optionnel), res_bits, date (timestamp)
|
||||||
# -------------------------------------------------------------
|
# -------------------------------------------------------------
|
||||||
|
|
||||||
import os
|
import os
|
||||||
@@ -22,6 +22,7 @@ TABLE_NAME = "tracker"
|
|||||||
COL_ID = "id"
|
COL_ID = "id"
|
||||||
COL_ADDRESS = "address"
|
COL_ADDRESS = "address"
|
||||||
COL_LIEU = "lieu"
|
COL_LIEU = "lieu"
|
||||||
|
COL_REPERE = "repere" # 🆕 Nouveau champ
|
||||||
COL_RESBITS = "res_bits"
|
COL_RESBITS = "res_bits"
|
||||||
COL_DATE = "date"
|
COL_DATE = "date"
|
||||||
|
|
||||||
@@ -62,38 +63,41 @@ def get_conn():
|
|||||||
# --------------
|
# --------------
|
||||||
|
|
||||||
def fetch_trackers(where_lieu: str | None = None) -> pd.DataFrame:
|
def fetch_trackers(where_lieu: str | None = None) -> pd.DataFrame:
|
||||||
query = f"SELECT {COL_ID}, {COL_ADDRESS}, {COL_LIEU}, {COL_RESBITS}, {COL_DATE} FROM {TABLE_NAME}"
|
query = (
|
||||||
|
f"SELECT {COL_ID}, {COL_ADDRESS}, {COL_LIEU}, {COL_REPERE}, {COL_RESBITS}, {COL_DATE} "
|
||||||
|
f"FROM {TABLE_NAME}"
|
||||||
|
)
|
||||||
params = []
|
params = []
|
||||||
if where_lieu:
|
if where_lieu:
|
||||||
query += f" WHERE {COL_LIEU} = %s"
|
query += f" WHERE {COL_LIEU} = %s"
|
||||||
params.append(where_lieu)
|
params.append(where_lieu)
|
||||||
query += f" ORDER BY {COL_LIEU}, {COL_ADDRESS}"
|
query += f" ORDER BY {COL_LIEU}, {COL_REPERE}, {COL_ADDRESS}"
|
||||||
with get_conn() as conn:
|
with get_conn() as conn:
|
||||||
df = pd.read_sql(query, conn, params=params)
|
df = pd.read_sql(query, conn, params=params)
|
||||||
return df
|
return df
|
||||||
|
|
||||||
|
|
||||||
def insert_tracker(address: str, lieu: str, res_bits: int) -> int:
|
def insert_tracker(address: str, lieu: str, res_bits: int, repere: str | None = None) -> int:
|
||||||
sql = f"""
|
sql = f"""
|
||||||
INSERT INTO {TABLE_NAME} ({COL_ADDRESS}, {COL_LIEU}, {COL_RESBITS})
|
INSERT INTO {TABLE_NAME} ({COL_ADDRESS}, {COL_LIEU}, {COL_REPERE}, {COL_RESBITS})
|
||||||
VALUES (%s, %s, %s)
|
VALUES (%s, %s, %s, %s)
|
||||||
"""
|
"""
|
||||||
with get_conn() as conn:
|
with get_conn() as conn:
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute(sql, (address, lieu, res_bits))
|
cur.execute(sql, (address, lieu, (repere.strip() if repere and repere.strip() else None), res_bits))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return cur.lastrowid
|
return cur.lastrowid
|
||||||
|
|
||||||
|
|
||||||
def update_tracker(row_id: int, address: str, lieu: str, res_bits: int) -> None:
|
def update_tracker(row_id: int, address: str, lieu: str, res_bits: int, repere: str | None) -> None:
|
||||||
sql = f"""
|
sql = f"""
|
||||||
UPDATE {TABLE_NAME}
|
UPDATE {TABLE_NAME}
|
||||||
SET {COL_ADDRESS}=%s, {COL_LIEU}=%s, {COL_RESBITS}=%s
|
SET {COL_ADDRESS}=%s, {COL_LIEU}=%s, {COL_REPERE}=%s, {COL_RESBITS}=%s
|
||||||
WHERE {COL_ID}=%s
|
WHERE {COL_ID}=%s
|
||||||
"""
|
"""
|
||||||
with get_conn() as conn:
|
with get_conn() as conn:
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute(sql, (address, lieu, res_bits, row_id))
|
cur.execute(sql, (address, lieu, (repere.strip() if repere and repere.strip() else None), res_bits, row_id))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
@@ -132,12 +136,12 @@ def res_label(bits: int) -> str:
|
|||||||
|
|
||||||
st.set_page_config(page_title="Gestion des sondes — tracker", page_icon="🌡️", layout="wide")
|
st.set_page_config(page_title="Gestion des sondes — tracker", page_icon="🌡️", layout="wide")
|
||||||
|
|
||||||
st.title("🌡️ Tracker - Gestion du parc de sondes")
|
st.title("🌡️ Gestion de Sondes.tracker")
|
||||||
with st.expander("Paramètres de connexion (lecture seule)"):
|
with st.expander("Paramètres de connexion (lecture seule)"):
|
||||||
st.write({k: ("***" if k in {"password"} else v) for k, v in DB_CFG.items()})
|
st.write({k: ("***" if k in {"password"} else v) for k, v in DB_CFG.items()})
|
||||||
st.caption("Configurez ces valeurs via le fichier .env (MYSQL_HOST, MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD, MYSQL_PORT)")
|
st.caption("Configurez ces valeurs via le fichier .env (MYSQL_HOST, MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD, MYSQL_PORT)")
|
||||||
|
|
||||||
# Barre latérale — Filtres et actions
|
# Barre latérale — Filtres & Actions
|
||||||
st.sidebar.header("Filtres & Actions")
|
st.sidebar.header("Filtres & Actions")
|
||||||
|
|
||||||
# Récupération de la liste des lieux existants
|
# Récupération de la liste des lieux existants
|
||||||
@@ -160,6 +164,7 @@ st.sidebar.subheader("Ajouter une sonde")
|
|||||||
with st.sidebar.form("add_form", clear_on_submit=True):
|
with st.sidebar.form("add_form", clear_on_submit=True):
|
||||||
new_address = st.text_input("Adresse ROM", placeholder="{0x28,0xFF,...}", help=rom_help())
|
new_address = st.text_input("Adresse ROM", placeholder="{0x28,0xFF,...}", help=rom_help())
|
||||||
new_lieu = st.text_input("Lieu d'installation", placeholder="Ex: Chaufferie / Saclay")
|
new_lieu = st.text_input("Lieu d'installation", placeholder="Ex: Chaufferie / Saclay")
|
||||||
|
new_repere = st.text_input("Repère (optionnel)", placeholder="Ex: R1, Panneau N°, Local 3…") # 🆕
|
||||||
new_res = st.selectbox("Résolution (bits)", options=[9,10,11,12])
|
new_res = st.selectbox("Résolution (bits)", options=[9,10,11,12])
|
||||||
submitted = st.form_submit_button("Ajouter")
|
submitted = st.form_submit_button("Ajouter")
|
||||||
if submitted:
|
if submitted:
|
||||||
@@ -168,7 +173,7 @@ with st.sidebar.form("add_form", clear_on_submit=True):
|
|||||||
elif not new_lieu.strip():
|
elif not new_lieu.strip():
|
||||||
st.warning("Lieu requis.")
|
st.warning("Lieu requis.")
|
||||||
else:
|
else:
|
||||||
rid = insert_tracker(new_address.strip(), new_lieu.strip(), int(new_res))
|
rid = insert_tracker(new_address.strip(), new_lieu.strip(), int(new_res), new_repere)
|
||||||
st.success(f"Sonde ajoutée (id={rid}).")
|
st.success(f"Sonde ajoutée (id={rid}).")
|
||||||
time.sleep(0.6)
|
time.sleep(0.6)
|
||||||
st.rerun()
|
st.rerun()
|
||||||
@@ -177,13 +182,11 @@ with st.sidebar.form("add_form", clear_on_submit=True):
|
|||||||
st.sidebar.divider()
|
st.sidebar.divider()
|
||||||
st.sidebar.subheader("Sécurité")
|
st.sidebar.subheader("Sécurité")
|
||||||
if st.sidebar.button("EXIT / Déconnexion", type="primary"):
|
if st.sidebar.button("EXIT / Déconnexion", type="primary"):
|
||||||
# Efface l'état de session Streamlit
|
|
||||||
for _k in list(st.session_state.keys()):
|
for _k in list(st.session_state.keys()):
|
||||||
try:
|
try:
|
||||||
del st.session_state[_k]
|
del st.session_state[_k]
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
# Redirige vers /logout (géré par Nginx pour renvoyer 401 et re‑demander l'auth Basic)
|
|
||||||
st.markdown('<meta http-equiv="refresh" content="0; url=/logout">', unsafe_allow_html=True)
|
st.markdown('<meta http-equiv="refresh" content="0; url=/logout">', unsafe_allow_html=True)
|
||||||
st.stop()
|
st.stop()
|
||||||
|
|
||||||
@@ -201,15 +204,16 @@ else:
|
|||||||
df["resolution"] = df[COL_RESBITS].apply(res_label)
|
df["resolution"] = df[COL_RESBITS].apply(res_label)
|
||||||
|
|
||||||
st.subheader("Enregistrements")
|
st.subheader("Enregistrements")
|
||||||
st.caption("Double-cliquez pour éditer les cellules. Les colonnes *resolution* et *date* sont dérivées et non éditables.")
|
st.caption("Double-cliquez pour éditer les cellules. Les colonnes *resolution* et *date* sont non éditables.")
|
||||||
|
|
||||||
edited = st.data_editor(
|
edited = st.data_editor(
|
||||||
df[[COL_ID, COL_ADDRESS, COL_LIEU, COL_RESBITS, "resolution", COL_DATE]],
|
df[[COL_ID, COL_ADDRESS, COL_LIEU, COL_REPERE, COL_RESBITS, "resolution", COL_DATE]],
|
||||||
hide_index=True,
|
hide_index=True,
|
||||||
column_config={
|
column_config={
|
||||||
COL_ID: st.column_config.NumberColumn("ID", disabled=True),
|
COL_ID: st.column_config.NumberColumn("ID", disabled=True),
|
||||||
COL_ADDRESS: st.column_config.TextColumn("Adresse (ROM)", help=rom_help()),
|
COL_ADDRESS: st.column_config.TextColumn("Adresse (ROM)", help=rom_help()),
|
||||||
COL_LIEU: st.column_config.TextColumn("Lieu"),
|
COL_LIEU: st.column_config.TextColumn("Lieu"),
|
||||||
|
COL_REPERE: st.column_config.TextColumn("Repère"), # 🆕 éditable
|
||||||
COL_RESBITS: st.column_config.NumberColumn("Résolution (bits)", min_value=9, max_value=12, step=1),
|
COL_RESBITS: st.column_config.NumberColumn("Résolution (bits)", min_value=9, max_value=12, step=1),
|
||||||
"resolution": st.column_config.TextColumn("Détails", disabled=True),
|
"resolution": st.column_config.TextColumn("Détails", disabled=True),
|
||||||
COL_DATE: st.column_config.DatetimeColumn("Date insertion", disabled=True, format="YYYY-MM-DD HH:mm:ss"),
|
COL_DATE: st.column_config.DatetimeColumn("Date insertion", disabled=True, format="YYYY-MM-DD HH:mm:ss"),
|
||||||
@@ -227,23 +231,30 @@ else:
|
|||||||
changed = (
|
changed = (
|
||||||
(row[COL_ADDRESS] != orig[COL_ADDRESS]) or
|
(row[COL_ADDRESS] != orig[COL_ADDRESS]) or
|
||||||
(row[COL_LIEU] != orig[COL_LIEU]) or
|
(row[COL_LIEU] != orig[COL_LIEU]) or
|
||||||
|
((str(row.get(COL_REPERE) or "").strip()) != (str(orig.get(COL_REPERE) or "").strip())) or
|
||||||
(int(row[COL_RESBITS]) != int(orig[COL_RESBITS]))
|
(int(row[COL_RESBITS]) != int(orig[COL_RESBITS]))
|
||||||
)
|
)
|
||||||
if changed:
|
if changed:
|
||||||
to_update.append(
|
to_update.append(
|
||||||
(int(row[COL_ID]), str(row[COL_ADDRESS]), str(row[COL_LIEU]), int(row[COL_RESBITS]))
|
(
|
||||||
|
int(row[COL_ID]),
|
||||||
|
str(row[COL_ADDRESS]),
|
||||||
|
str(row[COL_LIEU]),
|
||||||
|
int(row[COL_RESBITS]),
|
||||||
|
(str(row.get(COL_REPERE)).strip() if row.get(COL_REPERE) and str(row.get(COL_REPERE)).strip() else None),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
# Validation des adresses modifiées
|
# Validation des adresses modifiées
|
||||||
invalid_ids = [rid for (rid, addr, _, _) in to_update if not is_valid_rom(addr)]
|
invalid_ids = [rid for (rid, addr, *_rest) in to_update if not is_valid_rom(addr)]
|
||||||
if invalid_ids:
|
if invalid_ids:
|
||||||
st.error(f"Adresses ROM invalides pour id: {sorted(invalid_ids)}. Aucune mise à jour effectuée.")
|
st.error(f"Adresses ROM invalides pour id: {sorted(invalid_ids)}. Aucune mise à jour effectuée.")
|
||||||
else:
|
else:
|
||||||
col1, col2, col3 = st.columns([1,1,2])
|
col1, col2, col3 = st.columns([1,1,2])
|
||||||
with col1:
|
with col1:
|
||||||
if st.button("Enregistrer les modifications", disabled=(len(to_update)==0 and len(removed_ids)==0)):
|
if st.button("Enregistrer les modifications", disabled=(len(to_update)==0 and len(removed_ids)==0)):
|
||||||
for rid, addr, lieu, rbits in to_update:
|
for rid, addr, lieu, rbits, repere in to_update:
|
||||||
update_tracker(rid, addr, lieu, rbits)
|
update_tracker(rid, addr, lieu, rbits, repere)
|
||||||
for rid in removed_ids:
|
for rid in removed_ids:
|
||||||
delete_tracker(int(rid))
|
delete_tracker(int(rid))
|
||||||
st.success("Modifications enregistrées ✔️")
|
st.success("Modifications enregistrées ✔️")
|
||||||
@@ -270,5 +281,5 @@ else:
|
|||||||
st.divider()
|
st.divider()
|
||||||
st.caption(
|
st.caption(
|
||||||
"Astuce : vous pouvez coller directement une adresse ROM depuis vos logs au format {0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..}.\n"
|
"Astuce : vous pouvez coller directement une adresse ROM depuis vos logs au format {0x..,0x..,0x..,0x..,0x..,0x..,0x..,0x..}.\n"
|
||||||
"Si vos noms de colonnes diffèrent (ex. 'res.bits'), ajustez COL_RESBITS au début du fichier."
|
"Si vos noms de colonnes diffèrent (ex. 'res.bits'), ajustez les constantes en tête de fichier."
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user