Files
Brancheneinstufung2/list_generator.py
2025-05-27 05:50:16 +00:00

161 lines
8.6 KiB
Python

import csv
from datetime import datetime
import collections
import os.path
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# Importiere die Bibliothek - korrigierter Import basierend auf Dateisystem
from gdoctableapppy.gdoctableapp import gdoctableapp
# --- Konfiguration ---
CSV_FILENAME = 'Namensliste.csv'
GOOGLE_DOC_TITLE = f"Gruppenlisten_{datetime.now().strftime('%Y-%m-%d_%H-%M')}"
TARGET_FOLDER_ID = "18DNQaH9zbcBzwhckJI-4Uah-WXTXg6bg"
EINRICHTUNG_INFO = "Kinderhaus St. Martin Neuching"
FOTODATUM_INFO = "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_services_with_service_account():
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_tables_with_gdoctableapp(docs_api_service, document_id_to_fill):
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")
try:
resource_for_lib = {"docsService": docs_api_service, "documentId": document_id_to_fill}
gtable_manager = gdoctableapp(resource_for_lib)
# --- DEBUGGING: Methoden der Instanz anzeigen ---
print("\n--- Verfügbare Methoden/Attribute auf gtable_manager Objekt: ---")
print(dir(gtable_manager))
print("--- Ende Debugging Ausgabe ---\n")
print("INFO: Skript wird nach dir() Ausgabe beendet für Debugging.")
exit() # Das Skript hier abbrechen, um die Ausgabe zu sehen
# --- ENDE DEBUGGING ---
except Exception as e_dta_init:
print(f"Fehler bei der Initialisierung von gdoctableapp: {e_dta_init}"); return False
additional_requests_fallback = [] # Nur für den unwahrscheinlichen Fall, dass wir es brauchen
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
table_values = []
table_values.append(["Nachname", "Vorname", "Gruppe"])
for kind in kinder_liste:
table_values.append([kind['Nachname'], kind['Vorname'], gruppe_display_name])
try:
print(f"Versuche Tabelle für Gruppe '{gruppe_original}' mit gdoctableapp einzufügen...")
# HIER WÜRDEN DIE KORREKTEN METHODENAUFRUFE STEHEN, SOBALD WIR SIE KENNEN
# z.B. res_table_obj = gtable_manager.RICHTIGER_NAME_FUER_CREATE_TABLE(values=table_values, index=None)
# ... (Logik für Fettformatierung mit korrekten Methodennamen) ...
# ... (Logik für Footer-Text mit korrekten Methodennamen) ...
pass # Platzhalter, da die eigentlichen Aufrufe noch unklar sind
except AttributeError as e_attr:
print(f"AttributeError bei Gruppe '{gruppe_original}': {e_attr}")
except Exception as e_table:
print(f"Allgemeiner Fehler bei Tabelle/Footer für Gruppe '{gruppe_original}': {e_table}")
additional_requests_fallback.append({'insertText': {'endOfSegmentLocation': {}, 'text': f"\nFEHLER BEI TABELLE {gruppe_original}\n"}})
# if i < len(sorted_gruppen_namen) - 1:
# try:
# # HIER DER KORREKTE METHODENAUFRUF FÜR PAGEBREAK
# # gtable_manager.RICHTIGER_NAME_FUER_PAGEBREAK(index=None)
# pass
# except Exception as e_pb:
# print(f"Fehler beim Einfügen des PageBreak nach {gruppe_original}: {e_pb}")
# additional_requests_fallback.append({'insertPageBreak': {'endOfSegmentLocation': {}}})
if additional_requests_fallback and docs_api_service:
try:
print(f"Sende zusätzliche Fallback-Requests für Doc ID '{document_id_to_fill}'...")
docs_api_service.documents().batchUpdate(documentId=document_id_to_fill, body={'requests': additional_requests_fallback}).execute()
except HttpError as err: print(f"Fehler bei zusätzlichen Fallback-Requests: {err}")
return True
# --- Main execution block ---
if __name__ == "__main__":
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
# 1. Dokument erstellen
if drive_api_service and TARGET_FOLDER_ID:
file_metadata = {'name': GOOGLE_DOC_TITLE, '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: {e}\n Versuche Fallback...")
if not document_id:
try:
doc = docs_api_service.documents().create(body={'title': GOOGLE_DOC_TITLE}).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:
# 2. Einmalige Info am Anfang
initial_info_lines = ["Info zum Kopieren für Ihre manuelle Kopfzeile:", EINRICHTUNG_INFO, FOTODATUM_INFO, "\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 eingefügt.")
except HttpError as err: print(f"Fehler bei einmaliger Info: {err}")
# 3. Dokument mit Tabellen befüllen (wird nach dir() Ausgabe beendet)
success_filling = generate_tables_with_gdoctableapp(docs_api_service, document_id) # Name beibehalten
if success_filling: # Wird hier nicht viel bedeuten, da das Skript vorher abbricht
print(f"\n--- SKRIPT DEBUG-LAUF BEENDET (NACH dir()) ---")
print(f"Dokument-ID: {document_id}")
print(f"Link: https://docs.google.com/document/d/{document_id}/edit")
print("Bitte die Ausgabe von 'dir(gtable_manager)' prüfen.")
else: print("\n--- FEHLER VOR DEM EIGENTLICHEN BEFÜLLEN (DEBUG-LAUF) ---")
else: print("\n--- FEHLGESCHLAGEN: Kein Dokument erstellt ---")