[32788f42] Keine Zusammenfassung angegeben.

Keine Zusammenfassung angegeben.
This commit is contained in:
2026-04-07 18:10:46 +00:00
parent 229ad10e6b
commit 831ec7e71c
4 changed files with 97 additions and 59 deletions

View File

@@ -36,6 +36,22 @@ logging.basicConfig(
)
logger = logging.getLogger("fotograf-scraper")
def format_job_date(date_str: str) -> str:
import re
import datetime
# Sucht nach einem Datum im Format DD.MM.YYYY
match = re.search(r'(\d{2})\.(\d{2})\.(\d{4})', date_str)
if match:
try:
day, month, year = match.groups()
dt = datetime.datetime(int(year), int(month), int(day))
next_day = dt + datetime.timedelta(days=1)
# Format: 15. + 16.04.2026
return f"{dt.day:02d}. + {next_day.strftime('%d.%m.%Y')}"
except Exception:
pass
return date_str
# Load environment variables
load_dotenv()
@@ -119,8 +135,8 @@ def generate_pdf_from_csv(csv_path: str, institution: str, date_info: str, list_
df.columns = df.columns.str.strip().str.replace("\"", "")
logger.debug(f"CSV Columns: {list(df.columns)}")
group_label = "Gruppe" if list_type == 'k' else "Klasse"
person_label_plural = "Kinder" if list_type == 'k' else "Schüler"
group_label = "Gruppe" if list_type.startswith('kiga') else "Klasse"
person_label_plural = "Kinder" if list_type.startswith('kiga') else "Schüler"
col_mapping = {}
for col in df.columns:
@@ -806,13 +822,32 @@ async def generate_appointment_list(job_id: str, event_type_name: str, db: Sessi
if not raw_events:
return JSONResponse(status_code=404, content={"message": "Keine passenden Termine für diesen Event-Typ gefunden."})
# Filter out old events (keep only today and future)
from zoneinfo import ZoneInfo
now_berlin = datetime.datetime.now(ZoneInfo("Europe/Berlin"))
midnight_today = now_berlin.replace(hour=0, minute=0, second=0, microsecond=0)
future_events = []
for event in raw_events:
try:
start_dt = datetime.datetime.fromisoformat(event['start_time'].replace('Z', '+00:00'))
start_dt_berlin = start_dt.astimezone(ZoneInfo("Europe/Berlin"))
if start_dt_berlin >= midnight_today:
future_events.append(event)
except Exception as e:
logger.warning(f"Error parsing date for event: {e}")
future_events.append(event) # Fallback: keep event if date parsing fails
if not future_events:
return JSONResponse(status_code=404, content={"message": "Keine zukünftigen Termine für diesen Event-Typ gefunden."})
# 3. Generate PDF
temp_dir = tempfile.gettempdir()
output_name = f"Terminuebersicht_{job_id}_{datetime.datetime.now().strftime('%Y%m%d')}.pdf"
output_path = os.path.join(temp_dir, output_name)
try:
generate_appointment_overview_pdf(raw_events, job_name_clean, event_type_name, output_path)
generate_appointment_overview_pdf(future_events, job_name_clean, event_type_name, output_path)
return FileResponse(path=output_path, filename=output_name, media_type="application/pdf")
except Exception as e:
logger.error(f"Error generating appointment overview pdf: {e}")
@@ -939,7 +974,7 @@ async def download_task_csv(task_id: str):
raise HTTPException(status_code=500, detail="CSV Export fehlgeschlagen.")
@app.get("/api/jobs/{job_id}/generate-pdf")
async def generate_pdf(job_id: str, account_type: str):
async def generate_pdf(job_id: str, account_type: str, db: Session = Depends(get_db)):
logger.info(f"API Request: Generate PDF for job {job_id} ({account_type})")
username = os.getenv(f"{account_type.upper()}_USER")
password = os.getenv(f"{account_type.upper()}_PW")
@@ -966,8 +1001,9 @@ async def generate_pdf(job_id: str, account_type: str):
# 1.5 Click on the "Personen" tab
logger.info("Clicking on 'Personen' tab...")
personen_tab = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-qa-id='link:photo-jobs-tabs-names_list']")))
personen_tab.click()
personen_tab = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "[data-qa-id='link:photo-jobs-tabs-names_list']")))
# Use JS click to avoid 'element click intercepted' errors from loading overlays
driver.execute_script("arguments[0].click();", personen_tab)
# Wait for the export button to become present on the new tab
logger.info("Waiting for Export Dropdown...")
@@ -1013,10 +1049,17 @@ async def generate_pdf(job_id: str, account_type: str):
output_pdf_name = f"Listen_{job_id}.pdf"
output_pdf_path = os.path.join(temp_dir, output_pdf_name)
# Hole Auftragsdatum aus der Datenbank, falls vorhanden
job_record = db.query(DBJob).filter(DBJob.id == job_id).first()
if job_record and job_record.date:
final_date_info = format_job_date(job_record.date)
else:
final_date_info = datetime.datetime.now().strftime("%d.%m.%Y")
generate_pdf_from_csv(
csv_path=csv_file,
institution=institution,
date_info=datetime.datetime.now().strftime("%d.%m.%Y"),
date_info=final_date_info,
list_type=account_type,
output_path=output_pdf_path
)