From 3ea18501b86f5162cf7cf9f3dbac182611f33b08 Mon Sep 17 00:00:00 2001 From: torsten Date: Sat, 21 Nov 2026 13:29:43 +0100 Subject: [PATCH] =?UTF-8?q?Touren:=20Enddatum=20erg=C3=A4nzen=20und=20Daue?= =?UTF-8?q?r=20im=20Jahreskalender=20anzeigen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DEPLOY.md | 18 ++ motorradig/README.md | 1 + motorradig/bin/migrate.php | 8 + motorradig/public/css/custom.css | 14 ++ motorradig/src/Controllers/TourController.php | 65 ++++- motorradig/src/Models/Tour.php | 110 ++++++++- motorradig/views/tour/calendar.php | 27 +- motorradig/views/tour/create.php | 20 ++ motorradig/views/tour/edit.php | 18 ++ motorradig/views/tour/index.php | 2 +- motorradig/views/tour/index_old.php | 2 +- motorradig/views/tour/show.php | 10 + motorradig/views/tour/show_old.php | 5 + tools/backfill_tour_end_dates.py | 233 ++++++++++++++++++ tools/migrate_motorradig.py | 10 + 15 files changed, 521 insertions(+), 22 deletions(-) create mode 100644 tools/backfill_tour_end_dates.py diff --git a/DEPLOY.md b/DEPLOY.md index 36319ca..7e89d09 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -125,6 +125,24 @@ Für die Datenschutz-Funktion werden die Spalten Website über den Cookie-Fallback nutzbar; die Zustimmung wird dann aber nicht am Benutzerkonto gespeichert. +### Enddatum für Touren (einmalig) + +Touren haben seit 2027 ein optionales Enddatum (`tours.end_date`). Die Spalte +wird von `tools/migrate_motorradig.py` idempotent angelegt. Anschließend die +Enddaten einmalig aus den bestehenden Tournamen ableiten: + +```bash +cd ~/repos/motorradig2027 +python3 tools/backfill_tour_end_dates.py # Dry-Run +python3 tools/backfill_tour_end_dates.py --apply # schreiben +python3 tools/backfill_tour_end_dates.py --host 127.0.0.1 \ + --user mig_user --password mig_password --database motorradig # lokal (Docker) +``` + +Erkannt werden Zeiträume im Namen, z. B. `06-09.05.27`, +`vom 17.09. bis 19.09.2021`, `bis 17.08.2025` oder `17.05.2026 - Titel`. +Touren ohne Datum im Namen bleiben eintägig (Enddatum = Startdatum). + ## Reguläres Deployment (alle App-Dateien) ```bash diff --git a/motorradig/README.md b/motorradig/README.md index 8e7ba01..9c9595c 100644 --- a/motorradig/README.md +++ b/motorradig/README.md @@ -10,6 +10,7 @@ Keine externen Composer-Abhängigkeiten. - Mitgliederliste, Benutzerprofile mit Bild - Tourenplan mit Anmeldung, Zimmer-Buchung und Galerie - Jahreskalender (`/tour/kalender`) mit farblich markierten Touren und Jahres-Navigator +- Mehrtägige Touren mit Start- und Enddatum; Dauer erscheint im Kalender - Tour-Chat für Teilnehmer (Polling, ungelesen, Push optional) - Rollen `GUEST` / `MEMBER` / `TOUR GUIDE` / `ADMIN` - Login/Logout, Registrierung, Passwort-Reset per E-Mail diff --git a/motorradig/bin/migrate.php b/motorradig/bin/migrate.php index b26ca94..afe77a5 100644 --- a/motorradig/bin/migrate.php +++ b/motorradig/bin/migrate.php @@ -155,6 +155,14 @@ foreach ([ } } +// Touren: Enddatum ergänzen (für mehrtägige Touren) +if (!columnExists($pdo, 'tours', 'end_date')) { + $pdo->exec('ALTER TABLE `tours` ADD COLUMN `end_date` date NULL DEFAULT NULL AFTER `start`'); + $out("Spalte 'tours.end_date' angelegt"); +} else { + $out("Spalte 'tours.end_date' existiert bereits"); +} + // Tour-Chat: Nachrichten if (!tableExists($pdo, 'tour_messages')) { $pdo->exec('CREATE TABLE `tour_messages` ( diff --git a/motorradig/public/css/custom.css b/motorradig/public/css/custom.css index dd8da55..8e9fa32 100644 --- a/motorradig/public/css/custom.css +++ b/motorradig/public/css/custom.css @@ -953,6 +953,20 @@ p { background: #e5484d; } +/* Dauer mehrtägiger Touren (Starttag: "4 T", Folgetage: Punkte) */ +.calendar-day-duration { + display: block; + margin-top: .1rem; + font-size: .5rem; + font-weight: 700; + letter-spacing: .04em; + color: #0b1220; + background: rgba(255, 255, 255, .78); + border-radius: 999px; + padding: 0 .25rem; + width: fit-content; +} + .calendar-day-number { line-height: 1.05; } diff --git a/motorradig/src/Controllers/TourController.php b/motorradig/src/Controllers/TourController.php index dba8ad5..8c8ac7b 100644 --- a/motorradig/src/Controllers/TourController.php +++ b/motorradig/src/Controllers/TourController.php @@ -80,9 +80,15 @@ class TourController $selectedYear = max($firstYear, min($lastYear, $selectedYear)); $toursByDay = []; + $tourCount = 0; foreach (Tour::forYear($selectedYear) as $tour) { - $toursByDay[substr((string) $tour->start, 0, 10)][] = $tour; + $tourCount++; + + // Mehrtägige Touren erscheinen an jedem Tag ihres Zeitraums. + foreach ($tour->days() as $date) { + $toursByDay[$date][] = $tour; + } } view('tour.calendar', [ @@ -90,10 +96,33 @@ class TourController 'years' => range($firstYear, $lastYear), 'months' => $this->buildCalendarMonths($selectedYear, $toursByDay), 'todayDate' => today(), - 'tourCount' => array_sum(array_map('count', $toursByDay)), + 'tourCount' => $tourCount, ]); } + /** Enddatum aus dem Formular; null, wenn nichts angegeben wurde. */ + private function endDateFromInput(): ?string + { + $value = trim((string) input('end_date')); + + return $value === '' ? null : db_date($value); + } + + /** Das Enddatum darf nicht vor dem Startdatum liegen. */ + private function assertEndDate(): void + { + $start = trim((string) input('start')); + $end = trim((string) input('end_date')); + + if ($start === '' || $end === '' || db_date($end) >= db_date($start)) { + return; + } + + $_SESSION['_errors']['end_date'][] = 'Das Enddatum darf nicht vor dem Startdatum liegen.'; + $_SESSION['_old'] = $_POST; + back(); + } + /** * Baut das Monatsraster (Montag als erster Wochentag) für den Jahreskalender. * @@ -227,6 +256,7 @@ class TourController app_log('info', 'Tour create attempt', [ 'name' => input('name'), 'start' => input('start'), + 'end_date' => input('end_date'), 'deadline' => input('deadline'), 'max_participants' => input('max_participants'), 'is_cancelled' => input('is_cancelled'), @@ -240,19 +270,23 @@ class TourController 'name' => 'required|min:3', 'beschreibung' => 'required', 'start' => 'required|date', + 'end_date' => 'date', 'deadline' => 'required|date', 'tour_guide_id' => 'required', ]); + $this->assertEndDate(); + try { $tour = Tour::create([ 'name' => (string) input('name'), 'tour_guide_id' => (int) input('tour_guide_id'), 'beschreibung' => (string) input('beschreibung'), 'start' => db_date(input('start')), + 'end_date' => $this->endDateFromInput(), 'deadline' => db_date(input('deadline')), 'max_participants' => (int) (input('max_participants') ?: 5), - 'is_cancelled' => (bool) input('is_cancelled', false), + 'is_cancelled' => (int) (bool) input('is_cancelled', false), 'bericht' => null, 'created_at' => now(), 'updated_at' => now(), @@ -395,13 +429,18 @@ class TourController } } + $tourDays = $tour->durationDays(); + $tourEnd = $tour->endDate(); + // Vergangene Tour - if ($tour->start < today()) { + if ($tourEnd !== null && $tourEnd < today()) { $tour->start = german_date($tour->start); + $tour->end_date = $tour->isMultiDay() ? german_date((string) $tourEnd) : ''; $tour->deadline = german_date($tour->deadline); view('tour.show_old', [ 'tour' => $tour, + 'days' => $tourDays, 'users' => $users, 'guide' => $guide, 'tourImages' => $tourImages, @@ -416,10 +455,12 @@ class TourController $rooms = array_map(fn(array $row) => (object) $row, TourRoom::fetchRooms((int) $tour->id)); $tour->start = german_date($tour->start); + $tour->end_date = $tour->isMultiDay() ? german_date((string) $tourEnd) : ''; $tour->deadline = german_date($tour->deadline); view('tour.show', [ 'tour' => $tour, + 'days' => $tourDays, 'users' => $users, 'guide' => $guide, 'tourImages' => $tourImages, @@ -443,8 +484,11 @@ class TourController $tourGuide = User::find((int) $tour->tour_guide_id); $tourImages = $this->tourImages((int) $tour->id); - if ($tour->start < today()) { + $tourEnd = $tour->endDate(); + + if ($tourEnd !== null && $tourEnd < today()) { $tour->start = german_date($tour->start); + $tour->end_date = $tour->isMultiDay() ? german_date($tourEnd) : ''; $tour->deadline = german_date($tour->deadline); view('tour.edit_old', [ @@ -460,6 +504,7 @@ class TourController $rooms = array_map(fn(array $row) => (object) $row, TourRoom::fetchRooms((int) $tour->id)); $tour->start = german_date($tour->start); + $tour->end_date = $tour->isMultiDay() ? german_date($tourEnd) : ''; $tour->deadline = german_date($tour->deadline); view('tour.edit', [ @@ -491,9 +536,12 @@ class TourController 'tour_id' => 'required', 'name' => 'required|min:3', 'start' => 'required|date', + 'end_date' => 'date', 'deadline' => 'date', ]); + $this->assertEndDate(); + // Nur Admins dürfen den Tour Guide ändern. if ($current->isAdmin()) { $guide = User::find((int) input('tour_guide_id')); @@ -513,6 +561,9 @@ class TourController if (input('start') !== null) { $tour->start = db_date(input('start')); } + if (input('end_date') !== null) { + $tour->end_date = $this->endDateFromInput(); + } if (input('deadline') !== null) { $tour->deadline = db_date(input('deadline')); } @@ -520,9 +571,9 @@ class TourController $tour->max_participants = (int) input('max_participants'); } if (input('is_cancelled')) { - $tour->is_cancelled = true; + $tour->is_cancelled = 1; } else { - $tour->is_cancelled = false; + $tour->is_cancelled = 0; } if (input('bericht') !== null) { $tour->bericht = (string) input('bericht'); diff --git a/motorradig/src/Models/Tour.php b/motorradig/src/Models/Tour.php index aeabcd4..39934b6 100644 --- a/motorradig/src/Models/Tour.php +++ b/motorradig/src/Models/Tour.php @@ -13,7 +13,10 @@ class Tour extends Model /** Zukünftige (nicht abgelaufene) Touren. */ public static function upcoming(): array { - $rows = db()->fetchAll('SELECT * FROM `tours` WHERE start >= ? ORDER BY start', [today()]); + $rows = db()->fetchAll( + 'SELECT * FROM `tours` WHERE COALESCE(`end_date`, `start`) >= ? ORDER BY `start`', + [today()] + ); return array_map(fn(array $row) => static::fromRow($row), $rows); } @@ -21,7 +24,10 @@ class Tour extends Model /** Abgelaufene Touren. */ public static function past(): array { - $rows = db()->fetchAll('SELECT * FROM `tours` WHERE start < ? ORDER BY start', [today()]); + $rows = db()->fetchAll( + 'SELECT * FROM `tours` WHERE COALESCE(`end_date`, `start`) < ? ORDER BY `start` DESC', + [today()] + ); return array_map(fn(array $row) => static::fromRow($row), $rows); } @@ -42,7 +48,7 @@ class Tour extends Model { $tour = static::find($tourId); - return $tour !== null && $tour->start !== null && $tour->start < today(); + return $tour !== null && $tour->start !== null && $tour->endDate() < today(); } public static function createRoom(int $tourId, int $capacity): void @@ -55,12 +61,16 @@ class Tour extends Model ); } - /** Alle Touren eines Jahres, sortiert nach Startdatum. */ + /** Alle Touren, die in ein Jahr fallen (auch über den Jahreswechsel). */ public static function forYear(int $year): array { $rows = db()->fetchAll( - 'SELECT * FROM `tours` WHERE start IS NOT NULL AND YEAR(start) = ? ORDER BY start', - [$year] + 'SELECT * FROM `tours` + WHERE `start` IS NOT NULL + AND `start` <= ? + AND COALESCE(`end_date`, `start`) >= ? + ORDER BY `start`', + [$year . '-12-31', $year . '-01-01'] ); return array_map(fn(array $row) => static::fromRow($row), $rows); @@ -70,12 +80,98 @@ class Tour extends Model public static function years(): array { $rows = db()->fetchAll( - 'SELECT DISTINCT YEAR(start) AS jahr FROM `tours` WHERE start IS NOT NULL ORDER BY jahr' + 'SELECT DISTINCT YEAR(`start`) AS jahr FROM `tours` WHERE `start` IS NOT NULL ORDER BY jahr' ); return array_map(fn(array $row) => (int) $row['jahr'], $rows); } + /** + * Letzter Tag der Tour (ohne Enddatum: der Starttag). + */ + public function endDate(): ?string + { + if ($this->start === null) { + return null; + } + + $end = $this->attributes['end_date'] ?? null; + + return ($end !== null && $end !== '' && $end >= $this->start) ? (string) $end : (string) $this->start; + } + + /** Dauer in Tagen (mindestens 1). */ + public function durationDays(): int + { + $start = $this->start; + $end = $this->endDate(); + + if ($start === null || $end === null) { + return 1; + } + + $diff = (new \DateTimeImmutable(substr((string) $start, 0, 10))) + ->diff(new \DateTimeImmutable(substr($end, 0, 10))); + + return max(1, $diff->days + 1); + } + + public function isMultiDay(): bool + { + return $this->durationDays() > 1; + } + + /** Liegt der übergebene Tag (Y-m-d) innerhalb der Tour? */ + public function coversDate(string $date): bool + { + $start = $this->start === null ? null : substr((string) $this->start, 0, 10); + $end = $this->endDate(); + + if ($start === null || $end === null) { + return false; + } + + return $date >= $start && $date <= $end; + } + + /** Alle Tage der Tour als Y-m-d-Liste. */ + public function days(): array + { + $start = $this->start === null ? null : substr((string) $this->start, 0, 10); + $end = $this->endDate(); + + if ($start === null || $end === null) { + return []; + } + + $days = []; + $cursor = new \DateTimeImmutable($start); + $last = new \DateTimeImmutable($end); + + while ($cursor <= $last) { + $days[] = $cursor->format('Y-m-d'); + $cursor = $cursor->modify('+1 day'); + } + + return $days; + } + + /** Lesbare Zeitraumangabe, z. B. "14.05.2026 – 17.05.2026" oder "17.05.2026". */ + public function periodLabel(): string + { + if ($this->start === null) { + return ''; + } + + $end = $this->endDate(); + + if ($end === null || $end === substr((string) $this->start, 0, 10)) { + return german_date((string) $this->start); + } + + return german_date((string) $this->start) . ' – ' . german_date($end); + } + /** Admin oder der dieser Tour zugeordnete Tour Guide. */ public static function canManage(int $tourId, ?User $user): bool { diff --git a/motorradig/views/tour/calendar.php b/motorradig/views/tour/calendar.php index 3c3e5d5..fcc6bf5 100644 --- a/motorradig/views/tour/calendar.php +++ b/motorradig/views/tour/calendar.php @@ -66,14 +66,20 @@ $weekdayLabels = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']; $titles = []; foreach ($tours as $tour) { - if ((bool) $tour->is_cancelled) { - $isCancelled = true; - $titles[] = $tour->name . ' (abgesagt)'; - } else { - $titles[] = $tour->name; + $tourInfo = $tour->name; + + if ($tour->isMultiDay()) { + $tourInfo .= ' (' . $tour->periodLabel() . ', ' . $tour->durationDays() . ' Tage)'; } - if (substr((string) $tour->start, 0, 10) < $todayDate) { + if ((bool) $tour->is_cancelled) { + $isCancelled = true; + $titles[] = $tourInfo . ' (abgesagt)'; + } else { + $titles[] = $tourInfo; + } + + if ($tour->endDate() !== null && $tour->endDate() < $todayDate) { $isPast = true; } } @@ -90,12 +96,21 @@ $weekdayLabels = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']; if (count($tours) > 1) { $label .= ' +' . (count($tours) - 1); } + + // Dauer mehrtägiger Touren am Starttag einblenden. + $duration = $firstTour->durationDays(); + $isStartDay = substr((string) $firstTour->start, 0, 10) === $day['date']; + $durationBadge = $duration > 1 ? $duration . ' T' : ''; ?> + + + diff --git a/motorradig/views/tour/create.php b/motorradig/views/tour/create.php index 3716988..29a6f5a 100644 --- a/motorradig/views/tour/create.php +++ b/motorradig/views/tour/create.php @@ -47,6 +47,16 @@ +
+ + + +
+ +
+
@@ -100,6 +110,16 @@ }); } + const endDateInput = document.querySelector('input[name="end_date"]'); + if (endDateInput && typeof Datepicker !== 'undefined') { + new Datepicker(endDateInput, { + 'autohide': true, + 'format': 'dd.mm.yyyy', + 'language': 'de', + 'orientation': 'bottom' + }); + } + const deadlineInput = document.querySelector('input[name="deadline"]'); if (deadlineInput && typeof Datepicker !== 'undefined') { new Datepicker(deadlineInput, { diff --git a/motorradig/views/tour/edit.php b/motorradig/views/tour/edit.php index 1d48a5a..145ee1c 100644 --- a/motorradig/views/tour/edit.php +++ b/motorradig/views/tour/edit.php @@ -91,6 +91,16 @@ value="start) ?>" required>
+
+ + + +
+ +
+
  • - start) ?> - name) ?> + periodLabel()) ?> - name) ?> [id] ?? 0) ?>/max_participants) ?>] diff --git a/motorradig/views/tour/index_old.php b/motorradig/views/tour/index_old.php index 996b130..bf9b174 100644 --- a/motorradig/views/tour/index_old.php +++ b/motorradig/views/tour/index_old.php @@ -38,7 +38,7 @@
  • - start) ?> - name) ?> + periodLabel()) ?> - name) ?> [id] ?? 0) ?>/max_participants) ?>] diff --git a/motorradig/views/tour/show.php b/motorradig/views/tour/show.php index 126ec03..bf5dd28 100644 --- a/motorradig/views/tour/show.php +++ b/motorradig/views/tour/show.php @@ -41,6 +41,16 @@ value="start) ?>" readonly>
  • +
    + + + + Tag + +
    +
    + end_date)): ?> + + bis end_date) ?> ( Tage) + +
    diff --git a/tools/backfill_tour_end_dates.py b/tools/backfill_tour_end_dates.py new file mode 100644 index 0000000..d5e946c --- /dev/null +++ b/tools/backfill_tour_end_dates.py @@ -0,0 +1,233 @@ +#!/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()) diff --git a/tools/migrate_motorradig.py b/tools/migrate_motorradig.py index 5783c58..5cfe71a 100755 --- a/tools/migrate_motorradig.py +++ b/tools/migrate_motorradig.py @@ -188,6 +188,16 @@ MIGRATIONS = [ EXECUTE mig_stmt; DEALLOCATE PREPARE mig_stmt''', + # Touren: Enddatum ergänzen (idempotent) + '''SET @has_end_date := (SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'tours' AND COLUMN_NAME = 'end_date'); + SET @sql := IF(@has_end_date = 0, + 'ALTER TABLE `tours` ADD COLUMN `end_date` date NULL DEFAULT NULL AFTER `start`', + 'DO 0'); + PREPARE mig_stmt FROM @sql; + EXECUTE mig_stmt; + DEALLOCATE PREPARE mig_stmt''', + # Eindeutige Benutzernamen erzwingen (idempotent) '''SET @has_name_idx := (SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND INDEX_NAME = 'uniq_users_name');