Files
Brancheneinstufung2/list_generator.py
Floke c9ae3d733a feat: Add user input for date/facility, save inputs, adjust layout
- Prompts user for event date and facility name at script start.
- Saves last entered values to a JSON file for future default.
- Uses user-provided values for the initial info block on page 1.
- Adds two line breaks before each group's data block for spacing.
- Document title now includes the facility name for better identification.
2025-05-28 07:58:14 +00:00

206 lines
10 KiB
Python

import csv
from datetime import datetime
import collections
import os.path
import json # Für das Speichern/Laden der letzten Eingaben
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# --- Konfiguration ---
CSV_FILENAME = 'Namensliste.csv'
# GOOGLE_DOC_TITLE wird jetzt dynamischer mit dem Einrichtungsnamen
TARGET_FOLDER_ID = "18DNQaH9zbcBzwhckJI-4Uah-WXTXg6bg"
LAST_INPUT_FILE = "last_input.json" # Datei zum Speichern der letzten Eingaben
# Standardwerte, falls keine gespeicherten Werte vorhanden sind
DEFAULT_EINRICHTUNG = "Kinderhaus St. Martin Neuching"
DEFAULT_FOTODATUM = "02. - 05.06.2025"
GRUPPENNAME_SUFFIX = "gruppe"
SCOPES = [
'https://www.googleapis.com/auth/documents',
'https://www.googleapis.com/auth/drive.file'
]
SERVICE_ACCOUNT_FILE = 'service_account.json'
# --- Ende Konfiguration ---
def get_last_inputs():
"""Lädt die zuletzt verwendeten Eingaben aus einer JSON-Datei."""
try:
with open(LAST_INPUT_FILE, 'r') as f:
data = json.load(f)
return data.get("einrichtung", DEFAULT_EINRICHTUNG), data.get("fotodatum", DEFAULT_FOTODATUM)
except (FileNotFoundError, json.JSONDecodeError):
return DEFAULT_EINRICHTUNG, DEFAULT_FOTODATUM
def save_last_inputs(einrichtung, fotodatum):
"""Speichert die aktuellen Eingaben in einer JSON-Datei."""
try:
with open(LAST_INPUT_FILE, 'w') as f:
json.dump({"einrichtung": einrichtung, "fotodatum": fotodatum}, f)
except IOError:
print("Fehler beim Speichern der letzten Eingaben.")
def get_services_with_service_account():
# ... (Diese Funktion bleibt unverändert) ...
creds = None; docs_service = None; drive_service = None
try: creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
except Exception as e: print(f"Fehler Credentials: {e}"); return None, None
try: docs_service = build('docs', 'v1', credentials=creds); print("Docs API Service erstellt.")
except Exception as e: print(f"Fehler Docs Service: {e}")
try:
if any(s in SCOPES for s in ['https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive']):
drive_service = build('drive', 'v3', credentials=creds); print("Drive API Service erstellt.")
else: print("WARNUNG: Kein Drive Scope für Drive Service.")
except Exception as e: print(f"Fehler Drive Service: {e}")
return docs_service, drive_service
def generate_group_data_for_doc(docs_service, document_id_to_fill):
# ... (CSV-Lesen und initiale Datenaufbereitung bleiben unverändert) ...
kinder_nach_gruppen = collections.defaultdict(list)
try:
with open(CSV_FILENAME, mode='r', encoding='utf-8-sig', newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter=';')
for row in reader:
vorname = row.get('Vorname','').strip(); nachname = row.get('Nachname','').strip(); gruppe_original = row.get('Gruppe','').strip()
if not vorname or not nachname or not gruppe_original: continue
kinder_nach_gruppen[gruppe_original].append({'Nachname': nachname, 'Vorname': vorname})
except Exception as e: print(f"FEHLER CSV-Lesen: {e}"); return False
if not kinder_nach_gruppen: print("Keine CSV-Daten."); return False
for gk_key in kinder_nach_gruppen:
kinder_nach_gruppen[gk_key].sort(key=lambda x: (x['Nachname'].lower(), x['Vorname'].lower()))
sorted_gruppen_namen = sorted(kinder_nach_gruppen.keys())
stand_zeit = datetime.now().strftime("%d.%m.%Y %H:%M Uhr")
requests = []
col_width_nachname = 25
col_width_vorname = 25
for i, gruppe_original in enumerate(sorted_gruppen_namen):
kinder_liste = kinder_nach_gruppen[gruppe_original]
anzahl_kinder = len(kinder_liste)
gruppe_display_name = gruppe_original + GRUPPENNAME_SUFFIX
group_block_lines = []
# --- ANPASSUNG: Zwei Zeilenumbrüche vor der "Tabelle" ---
group_block_lines.append("") # Erster zusätzlicher Zeilenumbruch
group_block_lines.append("") # Zweiter zusätzlicher Zeilenumbruch
kopf_nachname = "Nachname".ljust(col_width_nachname)
kopf_vorname = "Vorname".ljust(col_width_vorname)
group_block_lines.append(f"{kopf_nachname}\t{kopf_vorname}\tGruppe")
for kind in kinder_liste:
nachname_gepadded = kind['Nachname'].ljust(col_width_nachname)
vorname_gepadded = kind['Vorname'].ljust(col_width_vorname)
group_block_lines.append(f"{nachname_gepadded}\t{vorname_gepadded}\t{gruppe_display_name}")
group_block_lines.append("")
group_block_lines.append(f"{anzahl_kinder} angemeldete Kinder")
group_block_lines.append("")
group_block_lines.append("Dies ist die Liste der bereits angemeldeten Kinder. Bitte die Eltern der noch fehlenden")
group_block_lines.append("Kinder an die Anmeldung erinnern.")
group_block_lines.append("")
group_block_lines.append(f"Stand {stand_zeit}")
group_block_lines.append("")
full_group_block_text = "\n".join(group_block_lines) + "\n"
requests.append({'insertText': {'endOfSegmentLocation': {}, 'text': full_group_block_text}})
if i < len(sorted_gruppen_namen) - 1:
requests.append({'insertPageBreak': {'endOfSegmentLocation': {}}})
if requests:
# ... (Rest der Funktion: Batch-Update ausführen, bleibt unverändert) ...
if not docs_service: print("FEHLER: Docs Service nicht da für Befüllung."); return False
try:
print(f"Sende Batch Update (Gruppenlisten, Anzahl, Stand) für Doc ID '{document_id_to_fill}'...")
docs_service.documents().batchUpdate(documentId=document_id_to_fill, body={'requests': requests}).execute()
print("Dokument erfolgreich mit Gruppenlisten, Anzahl und Stand befüllt.")
return True
except HttpError as err:
print(f"Fehler beim Befüllen (Gruppenlisten, Anzahl, Stand) Doc ID '{document_id_to_fill}': {err}")
# ... (Fehlerdetails) ...
return False
return True
# --- Main execution block ---
if __name__ == "__main__":
# 1. Zuletzt verwendete Eingaben laden oder Standardwerte verwenden
last_einrichtung, last_fotodatum = get_last_inputs()
# 2. Benutzer nach Einrichtung und Datum fragen, mit Vorschlägen
print("\nBitte geben Sie die Details für die Gruppenlisten ein:")
user_einrichtung = input(f"Name der Einrichtung [{last_einrichtung}]: ") or last_einrichtung
user_fotodatum = input(f"Datum der Veranstaltung (z.B. TT.MM.JJJJ - TT.MM.JJJJ) [{last_fotodatum}]: ") or last_fotodatum
# 3. Aktuelle Eingaben für den nächsten Lauf speichern
save_last_inputs(user_einrichtung, user_fotodatum)
# Dynamischen Dokumenttitel erstellen
GOOGLE_DOC_TITLE_DYNAMIC = f"Gruppenlisten {user_einrichtung.replace(' ', '_')}_{datetime.now().strftime('%Y-%m-%d_%H-%M')}"
print(f"\nInfo: Erstelle Dokument '{GOOGLE_DOC_TITLE_DYNAMIC}'")
print(f"Info: Ordner-ID für Dokument: '{TARGET_FOLDER_ID}'")
docs_api_service, drive_api_service = get_services_with_service_account()
if not docs_api_service:
print("Konnte Google Docs API Service nicht initialisieren. Skript wird beendet.")
else:
document_id = None
# Dokument erstellen
if drive_api_service and TARGET_FOLDER_ID:
file_metadata = {'name': GOOGLE_DOC_TITLE_DYNAMIC, 'mimeType': 'application/vnd.google-apps.document', 'parents': [TARGET_FOLDER_ID]}
try:
created_file = drive_api_service.files().create(body=file_metadata, fields='id').execute()
document_id = created_file.get('id')
print(f"Neues leeres Doc via Drive API in Ordner '{TARGET_FOLDER_ID}' erstellt, ID: {document_id}")
except Exception as e: print(f"Fehler Drive API Erstellung für leeres Doc: {e}\n Versuche Fallback...")
if not document_id:
try:
doc = docs_api_service.documents().create(body={'title': GOOGLE_DOC_TITLE_DYNAMIC}).execute()
document_id = doc.get('documentId')
print(f"Neues leeres Doc via Docs API (Root SA) erstellt, ID: {document_id}")
if TARGET_FOLDER_ID: print(f" BITTE manuell in Ordner '{TARGET_FOLDER_ID}' verschieben.")
except Exception as e: print(f"Konnte leeres Doc auch nicht mit Docs API erstellen: {e}")
if document_id:
# Einmalige Info (Kita, Datum aus Benutzereingabe) GANZ AM ANFANG einfügen
initial_info_lines = [
"Info zum Kopieren für Ihre manuelle Kopfzeile:",
user_einrichtung, # Verwendet die Benutzereingabe
user_fotodatum, # Verwendet die Benutzereingabe
"\n" + "="*70 + "\n"
]
initial_text = "\n".join(initial_info_lines) + "\n"
initial_requests = [{'insertText': {'location': {'index': 1}, 'text': initial_text}}]
try:
docs_api_service.documents().batchUpdate(documentId=document_id, body={'requests': initial_requests}).execute()
print("Einmalige Info am Dokumentanfang eingefügt.")
except HttpError as err:
print(f"Fehler beim Einfügen der einmaligen Info: {err}")
# Dokument mit gruppenspezifischen Daten befüllen
success_filling = generate_group_data_for_doc(docs_api_service, document_id)
if success_filling:
print(f"\n--- SKRIPT BEENDET ---")
print(f"Dokument-ID: {document_id}")
print(f"Link: https://docs.google.com/document/d/{document_id}/edit")
# ... (Restliche Hinweise bleiben gleich) ...
print("HINWEIS: Die Kinderlisten wurden als tabulatorgetrennter Text eingefügt.")
print(" Markieren Sie den Text in Google Docs und verwenden Sie 'Einfügen > Tabelle > Tabelle aus Text erstellen...'")
print(" Formatieren Sie die Überschriften 'Nachname, Vorname, Gruppe' danach manuell fett.")
else:
print("\n--- FEHLER BEIM BEFÜLLEN DES DOKUMENTS MIT GRUPPENDATEN ---")
else:
print("\n--- FEHLGESCHLAGEN: Konnte kein Dokument erstellen ---")