Files
RobandClaude Opus 5.5 cb059ac20d Geführtes Update: "Anwendung ersetzen" im Update-Hinweis
Der Update-Hinweis bietet neben "Update Ordner öffnen" nun den Button
"Anwendung ersetzen". Er kopiert das ZIP vom SMB-Laufwerk lokal, prüft es,
entpackt es in einen eigenen Ordner neben der aktuellen Installation,
übernimmt input/, output/ und eigene Templates und startet die neue EXE.
Die alte Installation bleibt als Rückfallebene erhalten; eine angepasste
settings.ini wird als settings.vorherige-version.ini aufbewahrt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:55:12 +01:00

589 lines
26 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Tätigkeitsnachweis-Generator – Streamlit App."""
import os
import subprocess
import sys
from pathlib import Path
import streamlit as st
# Projekt-Root zum Python-Path hinzufügen
# Im gebundelten Modus (PyInstaller) zeigt APP_BASE_DIR auf das Verzeichnis der .exe,
# wo config/, input/, template/, output/ liegen. Im Entwicklungsmodus bleibt es None
# und PROJECT_ROOT wird aus __file__ abgeleitet.
_BASE_DIR = os.environ.get("APP_BASE_DIR")
if _BASE_DIR:
PROJECT_ROOT = Path(_BASE_DIR).resolve()
else:
PROJECT_ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(PROJECT_ROOT))
from src.config import (
load_settings,
load_input_schema,
load_output_mapping,
get_available_input_files,
get_available_templates,
)
from src.models import AppConfig
from src.parser import parse_input_file, group_by_employee, get_unique_antragsnummern, get_unique_employees
from src.validator import validate_input_file, validate_template
from src.writer import generate_activity_reports
from version_check import UPDATE_DIR, get_latest_version
from update_installer import can_replace_application, install_update, start_application
def open_input_folder(directory: Path):
directory.mkdir(parents=True, exist_ok=True)
if sys.platform == "win32":
os.startfile(str(directory))
else:
subprocess.run(["open" if sys.platform == "darwin" else "xdg-open", str(directory)], check=True)
def set_active_employee(employee_name: str):
"""Merkt die zuletzt angeklickte Person für die Monatsliste."""
st.session_state.active_month_employee = employee_name
def sync_employee_months(employee_name: str, months: list[str]):
"""Übernimmt Monats-Checkboxen vor dem nächsten UI-Rendern."""
st.session_state.employee_months[employee_name] = {
month for month in months
if st.session_state.get(f"month_{employee_name}_{month}", False)
}
def set_all_employee_months(employee_name: str, months: list[str], selected: bool):
"""Setzt alle Monats-Checkboxen einer Person gesammelt."""
st.session_state.employee_months[employee_name] = set(months) if selected else set()
for month in months:
st.session_state[f"month_{employee_name}_{month}"] = selected
# --- Seite konfigurieren ---
st.set_page_config(
page_title="Tätigkeitsnachweis-Generator",
page_icon="📋",
layout="wide",
)
st.title("📋 Tätigkeitsnachweis-Generator")
st.markdown("Erstellt Tätigkeitsnachweise aus Input-Daten und einem Excel-Template.")
# --- Konfiguration laden ---
CONFIG_DIR = PROJECT_ROOT / "config"
@st.cache_data
def load_app_config():
config = load_settings(CONFIG_DIR, PROJECT_ROOT)
config.input_schema = load_input_schema(CONFIG_DIR)
config.output_mapping = load_output_mapping(CONFIG_DIR)
return config
try:
app_config = load_app_config()
except Exception as e:
st.error(f"Fehler beim Laden der Konfiguration: {e}")
st.stop()
# --- Versionsinformation für die dezente Anzeige am Seitenende ---
current_version_text = ""
try:
local_version, latest_version = get_latest_version()
current_version_text = f"v{'.'.join(map(str, local_version))}"
if latest_version:
available_version, update_path = latest_version
version_text = ".".join(map(str, available_version))
st.html(
f'''<style>
.update-notice {{
position: fixed; top: 4rem; right: 1rem; z-index: 10000;
width: 290px; padding: 8px 12px; color: #5f4700;
background: #fff8e1; border: 1px solid #e0b84c; border-radius: 8px;
box-shadow: 0 3px 12px rgba(0, 0, 0, .18); font-size: .85rem;
}}
#update-notice-dismiss {{ display:none; }}
#update-notice-dismiss:checked + .update-notice {{ display:none; }}
body:has(#update-notice-dismiss:checked) div.st-key-update_notice_open {{ display:none!important; }}
.update-notice__actions {{ display:flex; justify-content:flex-end; gap:8px; margin-top:8px; }}
.update-notice__actions--footer {{ min-height:60px; }}
.update-notice__button {{
display:inline-flex; align-items:center; justify-content:center;
width:26px; height:26px; color:#5f4700; background:#fffdf3;
border:1px solid #d9bd66; border-radius:5px; text-decoration:none;
font-size:1rem; line-height:1;
}}
.update-notice__button:hover {{ background:#f6e7b2; }}
div.st-key-update_notice_open {{
position:fixed; top:8.5rem; right:calc(1rem + 13px); z-index:10001;
width:264px; gap:6px;
}}
div.st-key-update_notice_open div[data-testid="stButton"] {{ margin:0; }}
div.st-key-update_notice_open div[data-testid="stButton"] button {{
width:100%; min-height:26px; height:26px; padding:0; color:#5f4700;
background:#fffdf3; border:1px solid #d9bd66; border-radius:5px;
}}
</style>
<input id="update-notice-dismiss" type="checkbox">
<aside class="update-notice" role="status">
<div class="update-notice__actions">
<label class="update-notice__button" for="update-notice-dismiss" title="Hinweis schließen">×</label>
</div>
<strong>Neue Version v{version_text} verfügbar</strong>
<div class="update-notice__actions update-notice__actions--footer">
</div>
</aside>'''
)
with st.container(key="update_notice_open"):
if st.button("Update Ordner öffnen 📁", key="open_update_directory", help="Update-Ordner öffnen"):
if sys.platform == "win32":
os.startfile(str(UPDATE_DIR))
replace_supported = can_replace_application()
replace_clicked = st.button(
"Anwendung ersetzen 🔄", key="replace_application",
disabled=not replace_supported or st.session_state.get("update_started", False),
help=("Neue Version neben der aktuellen einrichten, input/ und output/ übernehmen "
"und starten. Die aktuelle Version bleibt als Ordner erhalten."
if replace_supported else "Nur in der installierten Windows-Anwendung verfügbar."))
if replace_clicked:
try:
with st.spinner(f"Version v{version_text} wird eingerichtet …"):
result = install_update(update_path, PROJECT_ROOT)
start_application(result.target_dir)
except Exception as exc: # Der umgebende Block verschluckt sonst jeden Fehler.
st.error(f"Update fehlgeschlagen: {exc}\n\n"
"Alternativ das Update manuell aus dem Update-Ordner einrichten.")
else:
st.session_state.update_started = True
details = [f"Neuer Programmordner: `{result.target_dir}`"]
if result.already_installed:
details.append("Die Version war dort bereits eingerichtet und wurde nur gestartet.")
else:
details.append("Die Ordner input/ und output/ wurden übernommen.")
if result.previous_settings:
details.append(f"Die bisherige settings.ini wurde als `{result.previous_settings.name}` aufbewahrt.")
details.append("Bitte im folgenden Fenster bestätigen, dass die alte Version beendet wird. "
"Desktop-Verknüpfungen zeigen noch auf den alten Ordner.")
st.success(f"Version v{version_text} wird gestartet.\n\n" + "\n\n".join(details))
except Exception:
pass
# --- Session State initialisieren ---
if "parsed_records" not in st.session_state:
st.session_state.parsed_records = []
if "input_validated" not in st.session_state:
st.session_state.input_validated = False
if "template_validated" not in st.session_state:
st.session_state.template_validated = False
# Caches für Validierung/Parsing – nur bei Dateiwechsel neu ausführen
if "last_input_file" not in st.session_state:
st.session_state.last_input_file = None
if "last_template_file" not in st.session_state:
st.session_state.last_template_file = None
if "cached_val_result" not in st.session_state:
st.session_state.cached_val_result = None
if "cached_tpl_result" not in st.session_state:
st.session_state.cached_tpl_result = None
if "employee_months" not in st.session_state:
st.session_state.employee_months = {}
# --- Layout: zwei Spalten ---
col1, col2 = st.columns(2)
with col1:
st.subheader("1. Input-Datei")
input_files = get_available_input_files(app_config)
for message in st.session_state.pop("input_upload_messages", []):
st.success(message)
for message in st.session_state.pop("input_upload_errors", []):
st.error(message)
if not input_files:
with st.container(border=True, key="input_file_panel"):
st.markdown("**Excel-Datei hinzufügen**")
st.caption("Keine .xlsx-Dateien im Input/-Ordner gefunden.")
input_directory = Path(app_config.input_dir)
uploaded_files = st.file_uploader(
"Excel-Dateien hierher ziehen oder auswählen",
type=["xlsx"], accept_multiple_files=True,
key=f"input_upload_{st.session_state.get('input_upload_generation', 0)}",
label_visibility="collapsed",
)
if uploaded_files:
saved, errors = [], []
for uploaded_file in uploaded_files:
try:
name = uploaded_file.name
if (Path(name).name != name or "/" in name or "\\" in name
or Path(name).suffix.lower() != ".xlsx" or name.startswith("~")):
raise ValueError("Bitte eine .xlsx-Datei mit gültigem Dateinamen auswählen.")
input_directory.mkdir(parents=True, exist_ok=True)
destination = input_directory / name
counter = 1
while True:
try:
with destination.open("xb") as output:
output.write(uploaded_file.getbuffer())
break
except FileExistsError:
counter += 1
destination = input_directory / f"{Path(name).stem} ({counter}).xlsx"
saved.append(f"{destination.name} wurde in den Input-Ordner kopiert.")
except (OSError, ValueError) as exc:
errors.append(f"{uploaded_file.name} konnte nicht übernommen werden: {exc}")
st.session_state.input_upload_messages = saved
st.session_state.input_upload_errors = errors
st.session_state.input_upload_generation = st.session_state.get("input_upload_generation", 0) + 1
st.session_state.last_input_file = None
st.rerun()
st.caption("Dateien hierher ziehen oder auswählen. Sie werden automatisch im Input-Ordner gespeichert.")
folder_action, refresh_action = st.columns(2)
with folder_action:
if st.button("Ordner öffnen", icon="📁", key="open_input_directory", use_container_width=True):
try:
open_input_folder(input_directory)
except (OSError, subprocess.SubprocessError) as exc:
st.error(f"Der Input-Ordner konnte nicht geöffnet werden: {exc}")
with refresh_action:
if st.button("Neu einlesen", icon="🔄", key="refresh_input_directory", use_container_width=True,
help="Dateiliste aktualisieren, nachdem Dateien im Explorer hinzugefügt wurden."):
st.rerun()
selected_input = None
st.session_state.parsed_records = []
st.session_state.input_validated = False
st.session_state.last_input_file = None
else:
# Bei nur einer Datei: automatisch selektieren (keine Leerauswahl)
if len(input_files) == 1:
selected_input = st.selectbox(
"Input-Datei wählen:",
options=input_files,
)
else:
selected_input = st.selectbox(
"Input-Datei wählen:",
options=[""] + input_files,
format_func=lambda x: "– Bitte wählen –" if x == "" else x,
)
if selected_input:
input_path = Path(app_config.input_dir) / selected_input
# Nur validieren/parsen wenn sich die Datei geändert hat
if selected_input != st.session_state.last_input_file:
with st.spinner("Validiere Input-Datei…"):
val_result = validate_input_file(input_path, app_config.input_schema, app_config.month_sheet_pattern)
if val_result.is_valid:
records = parse_input_file(
input_path,
app_config.input_schema,
app_config.month_sheet_pattern,
app_config.skip_empty_name,
app_config.skip_empty_antragsnummer,
)
st.session_state.parsed_records = records
st.session_state.input_validated = True
else:
st.session_state.parsed_records = []
st.session_state.input_validated = False
st.session_state.cached_val_result = val_result
st.session_state.last_input_file = selected_input
else:
val_result = st.session_state.cached_val_result
if not val_result.is_valid:
st.markdown(
'<div style="border:2px solid #e74c3c; border-radius:8px; padding:12px; '
'background:#fdedec; margin-bottom:12px">'
'<span style="color:#b03a2e; font-weight:bold; font-size:1.1em">'
'❌ Validierung fehlgeschlagen</span></div>',
unsafe_allow_html=True,
)
for err in val_result.errors:
st.error(f"🔴 {err}")
st.session_state.input_validated = False
else:
if val_result.warnings:
st.markdown(
'<div style="border:2px solid #f39c12; border-radius:8px; padding:8px 12px; '
'background:#fef9e7; margin-bottom:8px">'
'<span style="color:#7d6608; font-weight:bold">'
'⚠️ Hinweise</span></div>',
unsafe_allow_html=True,
)
for warn in val_result.warnings:
st.warning(warn)
# Zeige Zusammenfassung aus gecachten Records
records = st.session_state.parsed_records
employees = get_unique_employees(records)
antragsnummern = get_unique_antragsnummern(records)
st.success(f"✅ {len(records)} Einträge in {val_result.info.get('sheets_with_data', 0)} Monats-Sheets")
pills = " ".join(
f'<span style="display:inline-block; background:#e8f0fe; color:#1a73e8; '
f'border-radius:16px; padding:4px 12px; margin:3px; font-size:0.9em; '
f'white-space:nowrap">{an}</span>'
for an in antragsnummern
)
st.markdown(f"**Antragsnummern:**<br>{pills}", unsafe_allow_html=True)
with col2:
st.subheader("2. Template")
template_files = get_available_templates(app_config)
if not template_files:
st.warning("Keine .pdf-Dateien im template/-Ordner gefunden.")
selected_template = None
else:
# Lock-Files herausfiltern
real_templates = [t for t in template_files if not t.startswith("~")]
if not real_templates:
real_templates = template_files
# Bei nur einem Template: automatisch selektieren (keine Leerauswahl)
if len(real_templates) == 1:
selected_template = st.selectbox(
"Template wählen:",
options=real_templates,
)
else:
selected_template = st.selectbox(
"Template wählen:",
options=[""] + real_templates,
format_func=lambda x: "– Bitte wählen –" if x == "" else x,
)
if selected_template:
# Nur validieren wenn sich das Template geändert hat
if selected_template != st.session_state.last_template_file:
template_path = Path(app_config.template_dir) / selected_template
with st.spinner("Validiere Template…"):
tpl_result = validate_template(template_path, app_config.output_mapping)
st.session_state.cached_tpl_result = tpl_result
st.session_state.last_template_file = selected_template
st.session_state.template_validated = tpl_result.is_valid
else:
tpl_result = st.session_state.cached_tpl_result
if not tpl_result.is_valid:
st.markdown(
'<div style="border:2px solid #e74c3c; border-radius:8px; padding:12px; '
'background:#fdedec; margin-bottom:12px">'
'<span style="color:#b03a2e; font-weight:bold; font-size:1.1em">'
'❌ Validierung fehlgeschlagen</span></div>',
unsafe_allow_html=True,
)
for err in tpl_result.errors:
st.error(f"🔴 {err}")
st.session_state.template_validated = False
else:
st.session_state.template_validated = True
found = tpl_result.info.get("found_fields", 0)
total = tpl_result.info.get("total_fields", 0)
st.success(f"✅ {found}/{total} Platzhalter-Felder gefunden")
if tpl_result.warnings:
st.markdown(
'<div style="border:2px solid #f39c12; border-radius:8px; padding:8px 12px; '
'background:#fef9e7; margin-bottom:8px">'
'<span style="color:#7d6608; font-weight:bold">'
'⚠️ Hinweise</span></div>',
unsafe_allow_html=True,
)
for warn in tpl_result.warnings:
st.warning(warn)
# --- Mitarbeiter-Auswahl ---
st.subheader("3. Mitarbeiter auswählen")
if st.session_state.input_validated and st.session_state.parsed_records:
employees = get_unique_employees(st.session_state.parsed_records)
st.caption(f"{len(employees)} Mitarbeiter gefunden – wähle aus, für wen Tätigkeitsnachweise erstellt werden sollen:")
# Monatsbezeichnungen für die kompakte Anzeige hinter dem Namen
month_labels = {
"01": "Jan", "02": "Feb", "03": "Mär", "04": "Apr",
"05": "Mai", "06": "Jun", "07": "Jul", "08": "Aug",
"09": "Sep", "10": "Okt", "11": "Nov", "12": "Dez",
}
all_groups = group_by_employee(st.session_state.parsed_records)
available_months = {}
for emp in employees:
months = sorted({
record.monat.split(".", 1)[0].zfill(2)
for record in all_groups.get(emp, [])
if record.monat and record.monat.split(".", 1)[0].isdigit()
}, key=lambda value: int(value))
available_months[emp] = months
if emp not in st.session_state.employee_months:
st.session_state.employee_months[emp] = set(months[-2:])
# Mitarbeiter- und Monatsliste teilen sich die verfügbare Breite.
employee_col, month_col = st.columns(2)
with employee_col:
employee_btn_col1, employee_btn_col2 = st.columns(2)
if employee_btn_col1.button("☑ Alle auswählen", use_container_width=True):
for emp in employees:
st.session_state[f"sel_{emp}"] = True
if employee_btn_col2.button("☐ Keine auswählen", use_container_width=True):
for emp in employees:
st.session_state[f"sel_{emp}"] = False
with st.container(border=True):
selected_employees = []
for emp in employees:
key = f"sel_{emp}"
if key not in st.session_state:
st.session_state[key] = False
selected_months = st.session_state.employee_months.get(emp, set())
short_months = ", ".join(month_labels[m] for m in available_months[emp] if m in selected_months)
label = f"{emp} ({short_months})" if short_months else f"{emp} (**keine Monate**)"
if st.checkbox(
label,
key=key,
on_change=set_active_employee,
args=(emp,),
):
selected_employees.append(emp)
with month_col:
selected_for_months = st.session_state.get("active_month_employee")
if selected_for_months not in employees:
selected_for_months = None
month_btn_col1, month_btn_col2 = st.columns(2)
month_btn_col1.button(
"☑ Alle Monate",
use_container_width=True,
disabled=not selected_for_months,
on_click=set_all_employee_months,
args=(selected_for_months, available_months[selected_for_months], True) if selected_for_months else ("", [], True),
)
month_btn_col2.button(
"☐ Keine Monate",
use_container_width=True,
disabled=not selected_for_months,
on_click=set_all_employee_months,
args=(selected_for_months, available_months[selected_for_months], False) if selected_for_months else ("", [], False),
)
with st.container(border=True):
st.caption("Monate für den angeklickten Mitarbeiter")
if selected_for_months:
st.write(selected_for_months)
month_values = {}
for month in available_months[selected_for_months]:
month_key = f"month_{selected_for_months}_{month}"
if month_key not in st.session_state:
st.session_state[month_key] = month in st.session_state.employee_months[selected_for_months]
month_values[month] = st.checkbox(
f"{month_labels[month]} ({month})",
key=month_key,
on_change=sync_employee_months,
args=(selected_for_months, available_months[selected_for_months]),
)
st.session_state.employee_months[selected_for_months] = {
month for month, checked in month_values.items() if checked
}
else:
st.info("Einen Mitarbeiter links auswählen, um seine Monate festzulegen.")
st.caption(f"{len(selected_employees)} von {len(employees)} Mitarbeitern ausgewählt")
else:
selected_employees = []
if not st.session_state.input_validated:
st.info("Bitte zuerst eine gültige Input-Datei auswählen.")
# --- Hilfsfunktion zum Öffnen von Dateien/Ordnern ---
def open_path(path_str: str):
"""Öffnet eine Datei mit dem Standardprogramm oder einen Ordner im Dateimanager.
Funktioniert plattformübergreifend: macOS, Windows, Linux."""
if sys.platform == "win32":
os.startfile(path_str)
elif sys.platform == "darwin":
subprocess.run(["open", path_str])
else:
subprocess.run(["xdg-open", path_str])
# --- Generate Button ---
st.divider()
gen_col1, gen_col2, gen_col3 = st.columns([1, 1, 2])
with gen_col1:
generate_clicked = st.button(
"🚀 Tätigkeitsnachweise generieren",
type="primary",
disabled=not (st.session_state.input_validated and st.session_state.template_validated and selected_employees),
)
if generate_clicked:
if not selected_employees:
st.error("Keine Mitarbeiter ausgewählt.")
else:
# Filtere Records auf selektierte Mitarbeiter
all_groups = group_by_employee(st.session_state.parsed_records)
selected_groups = {
name: [
record for record in all_groups[name]
if record.monat.split(".", 1)[0].zfill(2)
in st.session_state.employee_months.get(name, set())
]
for name in selected_employees
if name in all_groups
}
selected_groups = {name: records for name, records in selected_groups.items() if records}
if not selected_groups:
st.error("Für die ausgewählten Mitarbeiter sind keine Monate ausgewählt.")
st.stop()
template_path = Path(app_config.template_dir) / selected_template
output_dir = Path(app_config.output_dir)
with st.spinner(f"Generiere {len(selected_groups)} Tätigkeitsnachweise…"):
try:
generated = generate_activity_reports(
employee_records=selected_groups,
template_path=template_path,
mapping=app_config.output_mapping,
output_dir=output_dir,
filename_pattern=app_config.filename_pattern,
fontsize=app_config.fontsize,
)
st.session_state.generated_files = generated
except Exception as e:
st.error(f"Fehler bei der Generierung: {e}")
# --- Generierte Dateien anzeigen (aus Session State, übersteht Reruns) ---
if "generated_files" in st.session_state and st.session_state.generated_files:
generated = st.session_state.generated_files
st.success(f"✅ {len(generated)} Tätigkeitsnachweise erstellt:")
for i, fpath in enumerate(generated):
col_file, col_open, col_folder = st.columns([0.78, 0.11, 0.11])
with col_file:
st.markdown(f"📄 `{fpath.name}`")
with col_open:
st.button(
"🔗 Öffnen",
key=f"open_file_{i}",
on_click=open_path,
args=(str(fpath),),
help="Datei mit Standardprogramm öffnen",
use_container_width=True,
)
with col_folder:
st.button(
"📂",
key=f"open_folder_{i}",
on_click=open_path,
args=(str(fpath.parent),),
help="Ordner im Explorer öffnen",
use_container_width=True,
)
if current_version_text:
st.markdown(
f'<div style="text-align:right; color:#888; font-size:0.8em; margin-top:2em;">'
f'Programmversion {current_version_text}</div>',
unsafe_allow_html=True,
)