147 lines
7.6 KiB
Python
147 lines
7.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
|
|
|
|
# --- 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
|
|
|
|
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")
|
|
|
|
requests = []
|
|
col_width_nachname = 25 # Ggf. anpassen für besseres Padding
|
|
col_width_vorname = 25 # Ggf. anpassen
|
|
|
|
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("")
|
|
|
|
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")
|
|
for kind in kinder_liste:
|
|
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("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)
|
|
|
|
full_page_text = "\n".join(page_text_lines) + "\n"
|
|
if i == 0:
|
|
requests.append({'insertText': {'location': {'index': 1}, 'text': full_page_text}})
|
|
else:
|
|
requests.append({'insertText': {'endOfSegmentLocation': {}, 'text': full_page_text}})
|
|
if i < len(sorted_gruppen_namen) - 1:
|
|
requests.append({'insertPageBreak': {'endOfSegmentLocation': {}}})
|
|
|
|
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}'...")
|
|
docs_service.documents().batchUpdate(documentId=document_id, body={'requests': requests}).execute()
|
|
print("Dokument erfolgreich mit reinem Text befüllt.")
|
|
except HttpError as err:
|
|
print(f"Fehler beim Befüllen (reiner Text) Doc ID '{document_id}': {err}")
|
|
# ... (Fehlerdetails) ...
|
|
return document_id
|
|
return document_id
|
|
|
|
if __name__ == "__main__":
|
|
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
|
|
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...'")
|
|
else: print("\n--- FEHLGESCHLAGEN ---")
|
|
else: print("Konnte Docs Service nicht initialisieren.") |