bugfix
This commit is contained in:
@@ -1,100 +1,35 @@
|
||||
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
|
||||
|
||||
# --- Konfiguration ---
|
||||
CSV_FILENAME = 'Namensliste.csv'
|
||||
GOOGLE_DOC_TITLE = f"Gruppenlisten Kinderhaus St. Martin Neuching (Service Acc) - {datetime.now().strftime('%Y-%m-%d_%H-%M')}"
|
||||
TARGET_FOLDER_ID = "18DNQaH9zbcBzwhckJI-4Uah-WXTXg6bg"
|
||||
|
||||
EINRICHTUNG = "Kinderhaus St. Martin Neuching"
|
||||
FOTODATUM = "02. - 05.06.2025"
|
||||
GRUPPENNAME_SUFFIX = "gruppe"
|
||||
|
||||
FOTOGRAF_NAME = "Kinderfotos Erding"
|
||||
FOTOGRAF_ADRESSE = "Gartenstr. 10 85445 Oberding"
|
||||
FOTOGRAF_WEB = "www.kinderfotos-erding.de"
|
||||
FOTOGRAF_TEL = "08122-8470867"
|
||||
|
||||
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("Google Docs API Service erstellt.")
|
||||
except Exception as e_docs: print(f"Fehler Docs Service: {e_docs}")
|
||||
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("Google Drive API Service erstellt.")
|
||||
else: print("WARNUNG: Kein Drive Scope für Drive Service.")
|
||||
except Exception as e_drive: print(f"Fehler Drive Service: {e_drive}")
|
||||
return docs_service, drive_service
|
||||
# (Imports und Konfiguration bleiben wie zuvor)
|
||||
# (Funktion get_services_with_service_account bleibt wie zuvor)
|
||||
|
||||
def create_and_fill_doc_plain_text(docs_service, drive_service, folder_id, doc_title):
|
||||
document_id = None
|
||||
if drive_service and folder_id:
|
||||
file_metadata = {'name': doc_title, 'mimeType': 'application/vnd.google-apps.document', 'parents': [folder_id]}
|
||||
try:
|
||||
created_file = drive_service.files().create(body=file_metadata, fields='id').execute()
|
||||
document_id = created_file.get('id')
|
||||
print(f"Doc via Drive API in Ordner '{folder_id}' erstellt, ID: {document_id}")
|
||||
except HttpError as err: print(f"Fehler Drive API Erstellung: {err}\n Versuche Fallback...")
|
||||
except Exception as e: print(f"Allg. Fehler Drive API Erstellung: {e}\n Versuche Fallback...")
|
||||
if not document_id:
|
||||
if not docs_service: print("FEHLER: Docs Service nicht da."); return None
|
||||
try:
|
||||
doc = docs_service.documents().create(body={'title': doc_title}).execute()
|
||||
document_id = doc.get('documentId')
|
||||
print(f"Doc via Docs API (Root SA) erstellt, ID: {document_id}")
|
||||
if folder_id: print(f" BITTE manuell in Ordner '{folder_id}' verschieben.")
|
||||
except Exception as e: print(f"Konnte Doc auch nicht mit Docs API erstellen: {e}"); return None
|
||||
if not document_id: print("Konnte keine Doc-ID erhalten."); return None
|
||||
|
||||
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 document_id
|
||||
if not kinder_nach_gruppen: print("Keine CSV-Daten."); return document_id
|
||||
for gk in kinder_nach_gruppen: kinder_nach_gruppen[gk].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")
|
||||
# ... (Dokumenterstellung und CSV-Lesen bleiben wie zuvor) ...
|
||||
# kinder_nach_gruppen, sorted_gruppen_namen, stand_zeit werden hier korrekt befüllt
|
||||
|
||||
requests = []
|
||||
col_width_nachname = 25 # Ggf. anpassen für besseres Padding
|
||||
col_width_vorname = 25 # Ggf. anpassen
|
||||
# Spaltenbreiten für die tabellarischen Daten (ggf. anpassen)
|
||||
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
|
||||
page_text_lines = []
|
||||
page_text_lines.append(f"{EINRICHTUNG}\t\t\t{FOTOGRAF_NAME}")
|
||||
page_text_lines.append(FOTODATUM); page_text_lines.append("")
|
||||
|
||||
page_text_lines = [] # Beginne für jede Seite/Gruppe eine neue Liste von Zeilen
|
||||
|
||||
# --- ANGEPASSTER HEADER ---
|
||||
# Zeile 1: Einrichtungsname links, Fotografenname rechts
|
||||
# Wir simulieren die rechte Ausrichtung mit Tabulatoren.
|
||||
# Die genaue Anzahl der Tabs hängt von der Seitenbreite und Schriftart ab.
|
||||
# Beginnen wir mit einer großzügigen Anzahl.
|
||||
header_line1 = f"{EINRICHTUNG}\t\t\t\t\t\t{FOTOGRAF_NAME}" # Viele Tabs für Abstand
|
||||
page_text_lines.append(header_line1)
|
||||
|
||||
# Zeile 2: Datum der Veranstaltung (linksbündig unter Einrichtungsname)
|
||||
page_text_lines.append(FOTODATUM)
|
||||
page_text_lines.append("") # Leerzeile für Abstand vor der "Tabelle"
|
||||
|
||||
# "Tabellen"-Daten als Text (wie zuvor)
|
||||
kopf_nachname = "Nachname".ljust(col_width_nachname)
|
||||
kopf_vorname = "Vorname".ljust(col_width_vorname)
|
||||
page_text_lines.append(f"{kopf_nachname}\t{kopf_vorname}\tGruppe")
|
||||
@@ -102,46 +37,68 @@ def create_and_fill_doc_plain_text(docs_service, drive_service, folder_id, doc_t
|
||||
nachname_gepadded = kind['Nachname'].ljust(col_width_nachname)
|
||||
vorname_gepadded = kind['Vorname'].ljust(col_width_vorname)
|
||||
page_text_lines.append(f"{nachname_gepadded}\t{vorname_gepadded}\t{gruppe_display_name}")
|
||||
page_text_lines.append("")
|
||||
|
||||
page_text_lines.append(f"{anzahl_kinder} angemeldete Kinder"); page_text_lines.append("")
|
||||
page_text_lines.append("") # Leerzeile nach der "Tabelle"
|
||||
|
||||
# --- ANGEPASSTER FOOTER (Textblock unten auf der Seite) ---
|
||||
page_text_lines.append(f"{anzahl_kinder} angemeldete Kinder")
|
||||
page_text_lines.append("") # Leerzeile
|
||||
page_text_lines.append("Dies ist die Liste der bereits angemeldeten Kinder. Bitte die Eltern der noch fehlenden")
|
||||
page_text_lines.append("Kinder an die Anmeldung erinnern."); page_text_lines.append("")
|
||||
page_text_lines.append(f"Stand {stand_zeit}"); page_text_lines.append("")
|
||||
page_text_lines.append(FOTOGRAF_NAME); page_text_lines.append(FOTOGRAF_ADRESSE)
|
||||
page_text_lines.append(FOTOGRAF_WEB); page_text_lines.append(FOTOGRAF_TEL)
|
||||
page_text_lines.append("Kinder an die Anmeldung erinnern.")
|
||||
page_text_lines.append("") # Leerzeile
|
||||
page_text_lines.append(f"Stand {stand_zeit}")
|
||||
|
||||
full_page_text = "\n".join(page_text_lines) + "\n"
|
||||
if i == 0:
|
||||
# Leerzeilen für Abstand vor dem unteren Fotografen-Block (wie im Beispiel)
|
||||
page_text_lines.append("")
|
||||
page_text_lines.append("")
|
||||
# page_text_lines.append("") # Ggf. weitere Leerzeilen für mehr Abstand
|
||||
|
||||
# Unterer Footer-Block (linksbündig)
|
||||
page_text_lines.append(FOTOGRAF_NAME)
|
||||
page_text_lines.append(FOTOGRAF_ADRESSE)
|
||||
page_text_lines.append(FOTOGRAF_WEB)
|
||||
page_text_lines.append(FOTOGRAF_TEL)
|
||||
|
||||
full_page_text = "\n".join(page_text_lines) + "\n" # Alle Zeilen mit Newline verbinden
|
||||
|
||||
# Einfügen des gesamten Textblocks für die Seite
|
||||
if i == 0: # Erster Block an Index 1
|
||||
requests.append({'insertText': {'location': {'index': 1}, 'text': full_page_text}})
|
||||
else:
|
||||
else: # Weitere Blöcke nach einem PageBreak anhängen
|
||||
requests.append({'insertText': {'endOfSegmentLocation': {}, 'text': full_page_text}})
|
||||
|
||||
# Seitenumbruch nach jeder Gruppe, außer der letzten
|
||||
if i < len(sorted_gruppen_namen) - 1:
|
||||
requests.append({'insertPageBreak': {'endOfSegmentLocation': {}}})
|
||||
|
||||
# Batch-Update ausführen (Rest der Funktion bleibt gleich)
|
||||
if requests:
|
||||
if not docs_service: print("FEHLER: Docs Service nicht da."); return document_id
|
||||
try:
|
||||
print(f"Sende Batch Update (reiner Text) für Doc ID '{document_id}'...")
|
||||
print(f"Sende Batch Update (angepasster Header/Footer) für Doc ID '{document_id}'...")
|
||||
docs_service.documents().batchUpdate(documentId=document_id, body={'requests': requests}).execute()
|
||||
print("Dokument erfolgreich mit reinem Text befüllt.")
|
||||
print("Dokument erfolgreich mit angepasstem Header/Footer befüllt.")
|
||||
print("HINWEIS: Fügen Sie das Logo manuell ein und wandeln Sie Text ggf. in Tabellen um.")
|
||||
except HttpError as err:
|
||||
print(f"Fehler beim Befüllen (reiner Text) Doc ID '{document_id}': {err}")
|
||||
print(f"Fehler beim Befüllen (angepasster Header/Footer) Doc ID '{document_id}': {err}")
|
||||
# ... (Fehlerdetails) ...
|
||||
return document_id
|
||||
return document_id
|
||||
|
||||
# --- Main execution block ---
|
||||
if __name__ == "__main__":
|
||||
# ... (main Block bleibt wie in der letzten funktionierenden Version) ...
|
||||
print(f"Info: Fotodatum: {FOTODATUM}, Suffix: '{GRUPPENNAME_SUFFIX}', Ordner: '{TARGET_FOLDER_ID}'")
|
||||
docs_api_service, drive_api_service = get_services_with_service_account()
|
||||
if docs_api_service:
|
||||
final_doc_id = create_and_fill_doc_plain_text( # Funktionsname hier geändert
|
||||
final_doc_id = create_and_fill_doc_plain_text(
|
||||
docs_api_service, drive_api_service, TARGET_FOLDER_ID, GOOGLE_DOC_TITLE )
|
||||
if final_doc_id:
|
||||
print(f"\n--- SKRIPT BEENDET ---")
|
||||
print(f"Dokument-ID: {final_doc_id}")
|
||||
print(f"Link: https://docs.google.com/document/d/{final_doc_id}/edit")
|
||||
print("HINWEIS: Die 'Tabellen' wurden als tabulatorgetrennter Text eingefügt.")
|
||||
print(" Markieren Sie den Text in Google Docs und verwenden Sie 'Einfügen > Tabelle > Tabelle aus Text erstellen...'")
|
||||
if not drive_api_service or not TARGET_FOLDER_ID:
|
||||
print("Das Dokument wurde im Root-Verzeichnis des Servicekontos erstellt.")
|
||||
print("HINWEIS ZUM LOGO: Das 'Kinderfotos Erding' Logo muss manuell oben rechts eingefügt werden.")
|
||||
print(" URL: https://storage.e.jimdo.com/cdn-cgi/image/quality=85,fit=scale-down,format=auto,trim=0;0;0;0,width=800,height=266/image/286734604/d028c721-a942-4be7-9f07-a0f22b432760.png")
|
||||
else: print("\n--- FEHLGESCHLAGEN ---")
|
||||
else: print("Konnte Docs Service nicht initialisieren.")
|
||||
Reference in New Issue
Block a user