motorradig2027/tools/backfill_tour_end_dates.py

233 lines
7.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Leitet für bestehende Touren das Enddatum aus dem Tournamen ab.
Hintergrund: Bis 2026 gab es nur ein Startdatum. Mehrtägige Touren tragen
ihren Zeitraum aber im Namen, z. B.:
"Ardennen IG-Tour - Vatertag - 06-09.05.27"
"2021 Sauerland vom 17.09. bis 19.09.2021 - Tommi"
"bis 17.08.2025 Pfalz 2025 - Dirk"
"17.05.2026 - Schwarzwald Tour - Holger"
Aufruf (Standardwerte kommen aus motorradig/.credentials):
python3 tools/backfill_tour_end_dates.py # Dry-Run
python3 tools/backfill_tour_end_dates.py --apply # schreiben
Für lokale Tests lassen sich Verbindungsdaten überschreiben:
python3 tools/backfill_tour_end_dates.py --host 127.0.0.1 \\
--user mig_user --password mig_password --database motorradig
"""
from __future__ import annotations
import argparse
import datetime as dt
import os
import re
import subprocess
import sys
CRED_FILE = os.path.join(os.path.dirname(__file__), '..', 'motorradig', '.credentials')
# 1) Bereich mit "bis"/Bindestrich: "13.05 bis 16.05.2021", "03.bis 05.09.2021",
# "9.5.-12.5.", "Do15.08 bis So 18.08.2024"
RANGE_RE = re.compile(
r'(\d{1,2})\.\s*(\d{1,2})?\.?\s*(?:bis|[-\u2013])\s*'
r'(?:[A-Za-zÄÖÜäöü]{2}\.?\s*)?(\d{1,2})\.\s*(\d{1,2})\.?\s*(\d{2,4})?',
re.IGNORECASE,
)
# 2) Nur Enddatum: "bis 17.08.2025", "bis 8.9.2025"
UNTIL_RE = re.compile(
r'\bbis\s+(?:[A-Za-zÄÖÜäöü]{2}\.?\s*)?(\d{1,2})\.\s*(\d{1,2})\.?\s*(\d{2,4})?',
re.IGNORECASE,
)
# 3) Führendes Einzeldatum mit Jahr: "17.05.2026 - Schwarzwald Tour"
LEADING_RE = re.compile(r'^\s*(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{4})\s*[-\u2013]')
# 4) Tagesspanne mit Bindestrich: "06-09.05.27"
SPAN_RE = re.compile(r'(\d{1,2})\s*[-–]\s*(\d{1,2})\.\s*(\d{1,2})\.\s*(\d{2,4})')
MAX_DAYS = 31
def normalize_year(value: str | None, fallback: int) -> int:
if not value:
return fallback
number = int(value)
return 2000 + number if len(value) == 2 else number
def build_date(year: int, month: int, day: int) -> dt.date | None:
try:
return dt.date(year, month, day)
except ValueError:
return None
def guess_end_date(name: str, start: dt.date) -> dt.date | None:
"""Sucht das Enddatum im Tournamen; das Startdatum bleibt maßgeblich."""
candidates: list[dt.date] = []
match = RANGE_RE.search(name)
if match:
month, day = int(match.group(4)), int(match.group(3))
candidates.append(build_date(normalize_year(match.group(5), start.year), month, day))
candidates.append(build_date(start.year, month, day))
match = UNTIL_RE.search(name)
if match:
month, day = int(match.group(2)), int(match.group(1))
candidates.append(build_date(normalize_year(match.group(3), start.year), month, day))
candidates.append(build_date(start.year, month, day))
match = LEADING_RE.match(name)
if match:
candidates.append(build_date(int(match.group(3)), int(match.group(2)), int(match.group(1))))
match = SPAN_RE.search(name)
if match:
month = int(match.group(3))
candidates.append(build_date(normalize_year(match.group(4), start.year), month, int(match.group(2))))
candidates.append(build_date(start.year, month, int(match.group(2))))
for candidate in candidates:
if candidate is None:
continue
if candidate < start:
try:
candidate = candidate.replace(year=candidate.year + 1)
except ValueError: # 29.02.
continue
if candidate < start:
continue
if (candidate - start).days + 1 > MAX_DAYS:
continue
return candidate
return None
def load_credentials(path: str) -> dict[str, str]:
creds: dict[str, str] = {}
if not os.path.isfile(path):
return creds
with open(path, 'r', encoding='utf-8') as fh:
for line in fh:
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = line.split('=', 1)
creds[key.strip()] = value.strip()
return creds
def run_mysql(base_cmd: list[str], sql: str) -> str:
result = subprocess.run(base_cmd, input=sql.encode('utf-8'), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
raise RuntimeError(result.stderr.decode('utf-8', 'replace').strip())
return result.stdout.decode('utf-8', 'replace')
def main() -> int:
parser = argparse.ArgumentParser(description='Enddaten aus Tournamen ableiten')
parser.add_argument('--apply', action='store_true', help='Werte in die Datenbank schreiben')
parser.add_argument('--host')
parser.add_argument('--user')
parser.add_argument('--password')
parser.add_argument('--database')
args = parser.parse_args()
creds = load_credentials(CRED_FILE)
host = args.host or creds.get('DB_HOST', creds.get('FTP_URL', ''))
user = args.user or creds.get('DB_USERNAME', '')
password = args.password or creds.get('DB_PASSWORD', '')
database = args.database or creds.get('DB_NAME', creds.get('DB_DATABASE', user))
missing = [label for label, value in (
('Host', host), ('Benutzer', user), ('Passwort', password), ('Datenbank', database),
) if not value]
if missing:
print('Fehler: fehlende Verbindungsdaten: ' + ', '.join(missing), file=sys.stderr)
return 1
base_cmd = [
'mysql',
'--user=' + user,
'--password=' + password,
'--host=' + host,
'--default-character-set=utf8mb4',
'--batch',
'--skip-column-names',
database,
]
rows = run_mysql(
base_cmd,
'SELECT `id`, DATE_FORMAT(`start`, "%Y-%m-%d"), `name`, '
'IFNULL(DATE_FORMAT(`end_date`, "%Y-%m-%d"), "") FROM `tours` '
'WHERE `start` IS NOT NULL ORDER BY `start`;',
)
updates: list[str] = []
updated = unknown = 0
print(f"{'ID':<5}{'Start':<12}{'Ende neu':<12}{'Dauer':<8}Name")
print('-' * 100)
for line in rows.splitlines():
if not line.strip():
continue
tour_id, start_raw, name, current = line.split('\t', 3)
start = dt.date.fromisoformat(start_raw)
end = guess_end_date(name, start)
short_name = name[:58] + '…' if len(name) > 58 else name
if end is None:
unknown += 1
print(f'{tour_id:<5}{start_raw:<12}{current or "-":<12}{"-":<8}{short_name}')
continue
duration = (end - start).days + 1
changed = end.isoformat() != current
if changed:
updated += 1
updates.append(
f"UPDATE `tours` SET `end_date` = '{end.isoformat()}', "
f"`updated_at` = NOW() WHERE `id` = {int(tour_id)};"
)
marker = '' if changed else ' (unverändert)'
print(f'{tour_id:<5}{start_raw:<12}{end.isoformat():<12}{str(duration) + " Tage":<8}{short_name}{marker}')
print('-' * 100)
print(f'{updated} Tour(en) mit Enddatum, {unknown} ohne erkennbares Datum.')
if not args.apply:
if updated:
print('Zum Speichern erneut mit --apply ausführen.')
return 0
if updates:
run_mysql(base_cmd, '\n'.join(updates) + '\n')
print(f'{len(updates)} Datensatz/Datensätze aktualisiert.')
return 0
if __name__ == '__main__':
sys.exit(main())