39 Commits

Author SHA1 Message Date
Torsten Schulz (local)
36bf99c013 Add MyTischtennis fetch log functionality and new endpoints
Enhance MyTischtennis integration by introducing fetch log capabilities. Implement new controller methods to retrieve fetch logs and latest successful fetches for users. Update routes to include these new endpoints. Modify the MyTischtennis model to support fetch logs and ensure proper logging of fetch operations in various services. Update frontend components to display fetch statistics, improving user experience and data visibility.
2025-10-14 23:07:57 +02:00
Torsten Schulz (local)
7549fb5730 Implement league table functionality and MyTischtennis integration. Add new endpoints for retrieving and updating league tables in matchController and matchRoutes. Enhance Team model with additional fields for match statistics. Update frontend components to display league tables and allow fetching data from MyTischtennis, improving user experience and data accuracy. 2025-10-14 22:55:39 +02:00
Torsten Schulz (local)
1517d83f6c Refactor backend to enhance MyTischtennis integration. Update package.json to change main entry point to server.js. Modify server.js to improve scheduler service logging. Add new fields to ClubTeam, League, Match, and Member models for MyTischtennis data. Update routes to include new MyTischtennis URL parsing and configuration endpoints. Enhance services for fetching team data and scheduling match results. Improve frontend components for MyTischtennis URL configuration and display match results with scores. 2025-10-14 21:58:21 +02:00
Torsten Schulz (local)
993e12d4a5 Update MyTischtennis functionality to support automatic rating updates. Introduce new autoUpdateRatings field in MyTischtennis model and enhance MyTischtennisController to handle update history retrieval. Integrate node-cron for scheduling daily updates at 6:00 AM. Update frontend components to allow users to enable/disable automatic updates and display last update timestamps. 2025-10-09 00:18:41 +02:00
Torsten Schulz (local)
806cb527d4 Refactor group creation and assignment logic in DiaryView. Update group creation to allow specifying the number of groups, enhance participant assignment with group selection, and improve UI elements for better user experience. 2025-10-08 19:21:15 +02:00
Torsten Schulz (local)
7e9d2d2c4f Update member count calculations in MembersView to exclude inactive test memberships. Adjust activeMembersCount and testMembersCount computed properties for improved accuracy in member statistics. 2025-10-08 18:15:18 +02:00
Torsten Schulz (local)
ec9b92000e Update Member model to allow optional birthDate and enhance QuickAddMemberDialog for better input handling. Refactor DiaryView to remove default birthDate logic and improve member creation process. Adjust MembersView to handle empty birthDate gracefully in formatting. 2025-10-08 18:06:22 +02:00
Torsten Schulz (local)
d110900e85 Implement member statistics dropdown in MembersView. Add computed properties for active, test, and inactive member counts, and introduce a toggle for displaying member info. Enhance styling for the dropdown and member stats for improved user experience. 2025-10-08 17:47:43 +02:00
Torsten Schulz (local)
cd3c3502f6 Add tournament name column to OfficialTournaments view. Update data structure to include tournament names for better clarity in participation details. 2025-10-08 15:44:37 +02:00
Torsten Schulz (local)
ccce9bffac Enhance MembersView by adding a new row style for test memberships. Update the member row class to include 'row-test' for better visual distinction of test members, improving user experience in member management. 2025-10-08 15:00:38 +02:00
Torsten Schulz (local)
f1ba25f9f5 Implement logic to determine the quarter with the highest training data in TrainingStatsView. Update average participation calculation to reflect the best quarter's total participants, enhancing accuracy in participation metrics. 2025-10-08 14:54:57 +02:00
Torsten Schulz (local)
548f51ac54 Refactor participation metrics in TrainingStatsView to use total participant counts instead of member participation estimates. Update methods for calculating average participation across different time periods to enhance accuracy and maintainability. 2025-10-08 14:47:30 +02:00
Torsten Schulz (local)
946e4fce1e Enhance SeasonSelector and TeamManagementView with dialog components for improved user interaction. Introduce new dialog states and helper methods for consistent handling of information and confirmations. Update styles in TrainingStatsView to reflect new participation metrics and improve layout. Refactor document display in TeamManagementView to a table format for better readability. 2025-10-08 14:43:53 +02:00
Torsten Schulz (local)
40dcd0e54c Refactor modals in DiaryView, MembersView, OfficialTournaments, ScheduleView, and TrainingStatsView to use dedicated dialog components for improved maintainability and user experience. Update styles and structure for consistency across the application. 2025-10-08 12:49:42 +02:00
Torsten Schulz (local)
bd338b86df Implementiert InfoDialog und ConfirmDialog in mehreren Komponenten, um die Benutzerinteraktion zu verbessern. Fügt Dialogzustände und Hilfsmethoden hinzu, die eine konsistente Handhabung von Informationen und Bestätigungen ermöglichen. Diese Änderungen erhöhen die Benutzerfreundlichkeit und verbessern die visuelle Rückmeldung in der Anwendung. 2025-10-08 11:46:07 +02:00
Torsten Schulz (local)
1d4aa43b02 Aktualisiert das Styling in App.vue durch Hinzufügen von Padding am unteren Rand für die Statusleiste. Ändert den Hintergrund und die Polsterung in DialogManager.vue, um das visuelle Design zu verbessern und die Benutzeroberfläche zu optimieren. 2025-10-08 11:22:45 +02:00
Torsten Schulz (local)
cc08f4ba43 Verbessert die Lesbarkeit und Struktur des Codes in DiaryView.vue durch Anpassungen der Einrückungen und Formatierungen. Optimiert die Anzeige von Aktivitätsvisualisierungen und aktualisiert die Logik für die Eingabefelder, um die Benutzerfreundlichkeit zu erhöhen. Diese Änderungen tragen zur allgemeinen Verbesserung der Benutzeroberfläche und der Codequalität bei. 2025-10-08 11:14:20 +02:00
Torsten Schulz (local)
d0ccaa9e54 Fügt eine neue Methode hasActivityVisual in DiaryView.vue hinzu, um die Sichtbarkeit von Aktivitätsvisualisierungen zu überprüfen. Aktualisiert die Bedingungen für die Anzeige von Icons, die Bilder oder Zeichnungen darstellen, um die Benutzeroberfläche zu verbessern und die Logik zu optimieren. 2025-10-08 11:00:20 +02:00
Torsten Schulz (local)
dc0eff4e4c Entfernt die PDF-Datei 9_code_list_1759357969975.pdf und implementiert eine Sidebar-Toggle-Funktionalität in App.vue. Die Sidebar kann nun auf mobilen Geräten ein- und ausgeklappt werden, um die Benutzeroberfläche zu optimieren. Zudem wurden Titelattribute zu Navigationslinks hinzugefügt, um die Benutzerfreundlichkeit zu verbessern. Der Vuex-Store wurde aktualisiert, um den Zustand der Sidebar zu speichern und zu verwalten. 2025-10-08 10:52:07 +02:00
Torsten Schulz (local)
db9e404372 Aktualisiert die Logik zum Löschen eines Datums in DiaryView.vue. Die Schaltfläche zum Löschen wird nun nur angezeigt, wenn keine Inhalte (Trainingplan, Teilnehmer, Aktivitäten, Unfälle oder Notizen) vorhanden sind. Fügt eine neue Methode canDeleteCurrentDate hinzu, die diese Überprüfung durchführt, um die Benutzerfreundlichkeit zu verbessern und versehentliche Löschungen zu verhindern. 2025-10-04 02:30:23 +02:00
Torsten Schulz (local)
60ac89636e Ändert das Eingabefeld für den Nachnamen in der Mitgliederregistrierung auf optional und aktualisiert die Validierungslogik entsprechend. Setzt ein Standard-Geburtsdatum für neue Mitglieder auf den 01.01. des aktuellen Jahres minus 10 Jahre, wenn kein Geburtsdatum eingegeben wird. Diese Änderungen verbessern die Benutzerfreundlichkeit und Flexibilität bei der Registrierung neuer Mitglieder. 2025-10-04 02:27:49 +02:00
Torsten Schulz (local)
2b1365339e Fügt die Funktion zum Drehen von Mitgliedsbildern hinzu. Implementiert die Logik zur Bildrotation in MemberService und aktualisiert die entsprechenden Routen und Frontend-Komponenten, um die Benutzeroberfläche für die Bildbearbeitung zu verbessern. Ermöglicht das Drehen von Bildern über die Mitgliederansicht und aktualisiert die Anzeige nach der Bearbeitung. 2025-10-04 01:59:21 +02:00
Torsten Schulz (local)
0cf2351c79 Erweitert die Funktionalität von updateRatingsFromMyTischtennis, um eine automatische Anmeldung bei abgelaufener Session zu ermöglichen. Fügt Fehlerbehandlung für den Login-Prozess hinzu und entfernt die Bestätigungsabfrage vor der Aktualisierung der TTR/QTTR-Werte, um den Benutzerfluss zu verbessern. 2025-10-04 01:49:30 +02:00
Torsten Schulz (local)
5c32fad34e Fügt eine bedingte Navigation in App.vue hinzu, die eine leere Navigationsleiste anzeigt, wenn keine Authentifizierung vorliegt. Diese Änderung verbessert die Benutzeroberfläche und sorgt für eine klarere Struktur der Navigation. 2025-10-04 01:43:37 +02:00
Torsten Schulz (local)
7f0b681e88 Ermöglicht die Bearbeitung von Spielergebnissen in TournamentsView.vue durch klickbare Labels und editierbare Eingabefelder. Fügt Logik zum Speichern und Abbrechen von Änderungen hinzu. Aktualisiert das Styling für Eingabefelder und klickbare Texte, um die Benutzererfahrung zu verbessern. 2025-10-04 01:38:27 +02:00
Torsten Schulz (local)
cc964da9cf Fügt einen Dialog-Manager hinzu, um die Verwaltung von Dialogen zu ermöglichen. Aktualisiert den Vuex-Store mit neuen Mutationen und Aktionen zur Handhabung von Dialogen. Integriert den MatchReportDialog in ScheduleView.vue und ermöglicht das Öffnen von Spielberichten über die Benutzeroberfläche. Verbessert die Benutzererfahrung durch neue Schaltflächen und CSS-Stile für die Dialoge. 2025-10-02 11:44:27 +02:00
Torsten Schulz (local)
dbede48d4f Entfernt Konsolenausgaben aus der MyTischtennisClient-Klasse, um die Codequalität zu verbessern und die Lesbarkeit zu erhöhen. Diese Änderungen betreffen die Methoden getUserProfile und getClubRankings und tragen zur Optimierung der Protokollierung und Performance bei. 2025-10-02 10:40:24 +02:00
Torsten Schulz (local)
6cd3c3a020 Entfernt Konsolenausgaben aus verschiedenen Controllern und Services, um die Codequalität zu verbessern und die Lesbarkeit zu erhöhen. Diese Änderungen betreffen die Controller für Clubs, Club-Teams, Mitglieder, Tagebuch-Tags, Saisons und Teams sowie die zugehörigen Services. Ziel ist es, die Protokollierung zu optimieren und die Performance zu steigern. 2025-10-02 10:34:56 +02:00
Torsten Schulz (local)
7ecbef806d Entfernt Konsolenausgaben aus mehreren Komponenten, um den Code zu bereinigen und die Lesbarkeit zu verbessern. Betroffene Dateien sind CourtDrawingRender.vue, CourtDrawingTool.vue, SeasonSelector.vue, PredefinedActivities.vue, ScheduleView.vue, TeamManagementView.vue und TournamentsView.vue. Diese Änderungen tragen zur Optimierung der Performance und zur Reduzierung von unnötigen Protokollierungen bei. 2025-10-02 10:13:03 +02:00
Torsten Schulz (local)
1c70ca97bb Fügt Unterstützung für Team-Dokumente hinzu. Aktualisiert die Backend-Modelle und -Routen, um Team-Dokumente zu verwalten, einschließlich Upload- und Parsing-Funktionen für Code- und Pin-Listen. Ergänzt die Benutzeroberfläche in TeamManagementView.vue zur Anzeige und Verwaltung von Team-Dokumenten sowie zur Integration von PDF-Parsing. Aktualisiert die Match-Modelle, um zusätzliche Felder für Spiel-Codes und PINs zu berücksichtigen. 2025-10-02 09:04:19 +02:00
Torsten Schulz (local)
a6493990d3 Erweitert die Backend- und Frontend-Funktionalität zur Unterstützung von Teams und Saisons. Fügt neue Routen für Team- und Club-Team-Management hinzu, aktualisiert die Match- und Team-Modelle zur Berücksichtigung von Saisons, und implementiert die Saison-Auswahl in der Benutzeroberfläche. Optimiert die Logik zur Abfrage von Ligen und Spielen basierend auf der ausgewählten Saison. 2025-10-01 22:47:13 +02:00
Torsten Schulz (local)
f8f4d23c4e Aktualisiert die Schaltflächen im MyTischtennisAccount.vue, um die Benutzeroberfläche zu verbessern. Ändert den Text der Schaltfläche "Verbindung testen" in "Erneut einloggen" und entfernt die Testausgabe für Login-Tests. Optimiert die Erfolgsmeldung nach erfolgreichem Login und aktualisiert die Account-Daten. Entfernt die nicht mehr benötigte Funktionalität für den Login-Flow-Test. 2025-10-01 13:52:14 +02:00
Torsten Schulz (local)
1ef1711eea Merge branch 'main' into httv 2025-10-01 13:49:26 +02:00
Torsten Schulz (local)
85981a880d Ändert die Navigationsstruktur in App.vue, indem die Klasse der Fußzeile von "nav-menu" zu "sidebar-footer" geändert wird. Fügt eine neue CSS-Klasse "nav-menu-no-flex" hinzu, um das Layout der Navigation zu optimieren und die Flexbox-Eigenschaften anzupassen. 2025-10-01 13:49:13 +02:00
Torsten Schulz (local)
84503b6404 Merge branch 'httv' 2025-10-01 13:31:41 +02:00
Torsten Schulz (local)
bcc3ce036d Ersetzt Konsolenausgaben durch eine bedingte Entwicklungsprotokollierungsfunktion in mehreren Controllern und Services. Dies verbessert die Protokollierung und Fehlerverfolgung im gesamten Code. Aktualisiert die Benutzer-Utils, um die neue Protokollierungsfunktion zu verwenden. 2025-10-01 13:29:49 +02:00
Torsten Schulz (local)
0fe0514660 Verbessert die Protokollierung in den Club-Controller- und Benutzer-Utils-Dateien, indem die Konsolenausgaben durch eine bedingte Entwicklungsprotokollierungsfunktion ersetzt werden. Aktualisiert die Fehlerbehandlung, um detailliertere Fehlermeldungen auszugeben. 2025-10-01 13:24:16 +02:00
Torsten Schulz (local)
431ec861ba Erweitert die Trainingsstatistik-Funktionalität im TrainingStatsController um die Abfrage und Formatierung von Trainingstagen der letzten 12 Monate. Aktualisiert die Benutzeroberfläche in TrainingStatsView.vue zur Anzeige dieser Trainingstage in einer aufklappbaren Tabelle. Fügt Funktionen zum Umschalten der Sichtbarkeit von Trainingstagen und Mitgliedern hinzu. 2025-10-01 13:20:36 +02:00
Torsten Schulz (local)
648b608036 Erweitert die Trainingsstatistik-Funktionalität im TrainingStatsController, um die Anzahl der Trainings in den letzten 12 und 3 Monaten zu berechnen und zurückzugeben. Aktualisiert die Benutzeroberfläche in TrainingStatsView.vue zur Anzeige dieser neuen Daten. Ändert die Navigation in App.vue, um direkt zu den Trainingsstatistiken zu führen. 2025-10-01 13:01:54 +02:00
163 changed files with 20156 additions and 1687 deletions

View File

View File

@@ -0,0 +1,212 @@
# MyTischtennis Automatischer Datenabruf
## Übersicht
Dieses System ermöglicht den automatischen Abruf von Spielergebnissen und Statistiken von myTischtennis.de.
## Scheduler
### 6:00 Uhr - Rating Updates
- **Service:** `autoUpdateRatingsService.js`
- **Funktion:** Aktualisiert TTR/QTTR-Werte für Spieler
- **TODO:** Implementierung der eigentlichen Rating-Update-Logik
### 6:30 Uhr - Spielergebnisse
- **Service:** `autoFetchMatchResultsService.js`
- **Funktion:** Ruft Spielerbilanzen für konfigurierte Teams ab
- **Status:** ✅ Grundlegende Implementierung fertig
## Benötigte Konfiguration
### 1. MyTischtennis-Account
- Account muss in den MyTischtennis-Settings verknüpft sein
- Checkbox "Automatische Updates" aktivieren
- Passwort speichern (erforderlich für automatische Re-Authentifizierung)
### 2. League-Konfiguration
Für jede Liga müssen folgende Felder ausgefüllt werden:
```sql
UPDATE league SET
my_tischtennis_group_id = '504417', -- Group ID von myTischtennis
association = 'HeTTV', -- Verband (z.B. HeTTV, DTTB)
groupname = '1.Kreisklasse' -- Gruppenname für URL
WHERE id = 1;
```
**Beispiel-URL:**
```
https://www.mytischtennis.de/click-tt/HeTTV/25--26/ligen/1.Kreisklasse/gruppe/504417/...
^^^^^ ^^^^^^^^^^^^^^ ^^^^^^
association groupname group_id
```
### 3. Team-Konfiguration
Für jedes Team muss die myTischtennis Team-ID gesetzt werden:
```sql
UPDATE club_team SET
my_tischtennis_team_id = '2995094' -- Team ID von myTischtennis
WHERE id = 1;
```
**Beispiel-URL:**
```
.../mannschaft/2995094/Harheimer_TC_(J11)/spielerbilanzen/gesamt
^^^^^^^
team_id
```
### 4. Spieler-Zuordnung (Optional)
Spieler werden automatisch anhand des Namens zugeordnet. Für genauere Zuordnung kann die myTischtennis Player-ID gesetzt werden:
```sql
UPDATE member SET
my_tischtennis_player_id = 'NU2705037' -- Player ID von myTischtennis
WHERE id = 1;
```
## Migrationen
Folgende Migrationen müssen ausgeführt werden:
```bash
# 1. MyTischtennis Auto-Update-Felder
mysql -u root -p trainingstagebuch < backend/migrations/add_auto_update_ratings_to_my_tischtennis.sql
# 2. MyTischtennis Update-History-Tabelle
mysql -u root -p trainingstagebuch < backend/migrations/create_my_tischtennis_update_history.sql
# 3. League MyTischtennis-Felder
mysql -u root -p trainingstagebuch < backend/migrations/add_mytischtennis_fields_to_league.sql
# 4. Team MyTischtennis-ID
mysql -u root -p trainingstagebuch < backend/migrations/add_mytischtennis_team_id_to_club_team.sql
# 5. Member MyTischtennis Player-ID
mysql -u root -p trainingstagebuch < backend/migrations/add_mytischtennis_player_id_to_member.sql
# 6. Match Result-Felder
mysql -u root -p trainingstagebuch < backend/migrations/add_match_result_fields.sql
```
## Abgerufene Daten
Von der myTischtennis API werden folgende Daten abgerufen:
### Einzelstatistiken
- Player ID, Vorname, Nachname
- Gewonnene/Verlorene Punkte
- Anzahl Spiele
- Detaillierte Statistiken nach Gegner-Position
### Doppelstatistiken
- Player IDs, Namen der beiden Spieler
- Gewonnene/Verlorene Punkte
- Anzahl Spiele
### Team-Informationen
- Teamname, Liga, Saison
- Gesamtpunkte (gewonnen/verloren)
- Doppel- und Einzelpunkte
## Implementierungsdetails
### Datenfluss
1. **Scheduler** (6:30 Uhr):
- `schedulerService.js` triggert `autoFetchMatchResultsService.executeAutomaticFetch()`
2. **Account-Verarbeitung**:
- Lädt alle MyTischtennis-Accounts mit `autoUpdateRatings = true`
- Prüft Session-Gültigkeit
- Re-Authentifizierung bei abgelaufener Session
3. **Team-Abfrage**:
- Lädt alle Teams mit konfigurierten myTischtennis-IDs
- Baut API-URL dynamisch zusammen
- Führt authentifizierten GET-Request durch
4. **Datenverarbeitung**:
- Parst JSON-Response
- Matched Spieler anhand von ID oder Name
- Speichert myTischtennis Player-ID bei Mitgliedern
- Loggt Statistiken
### Player-Matching-Algorithmus
```javascript
1. Suche nach myTischtennis Player-ID (exakte Übereinstimmung)
2. Falls nicht gefunden: Suche nach Name (case-insensitive)
3. Falls gefunden: Speichere myTischtennis Player-ID für zukünftige Abfragen
```
**Hinweis:** Da Namen verschlüsselt gespeichert werden, müssen für den Namens-Abgleich alle Members geladen und entschlüsselt werden. Dies ist bei großen Datenbanken ineffizient.
## TODO / Offene Punkte
### Noch zu implementieren:
1. **TTR/QTTR Updates** (6:00 Uhr Job):
- Endpoint für TTR/QTTR-Daten identifizieren
- Daten abrufen und in Member-Tabelle speichern
2. **Spielergebnis-Details**:
- Einzelne Matches mit Satzständen speichern
- Tabelle für Match-Historie erstellen
3. **History-Tabelle für Spielergebnis-Abrufe** (optional):
- Ähnlich zu `my_tischtennis_update_history`
- Speichert Erfolg/Fehler der Abrufe
4. **Benachrichtigungen** (optional):
- Email/Push bei neuen Ergebnissen
- Highlights für besondere Siege
5. **Performance-Optimierung**:
- Caching für Player-Matches
- Incremental Updates (nur neue Daten)
## Manueller Test
```javascript
// Im Node-Backend-Code oder über API-Endpoint:
import schedulerService from './services/schedulerService.js';
// Rating Updates manuell triggern
await schedulerService.triggerRatingUpdates();
// Spielergebnisse manuell abrufen
await schedulerService.triggerMatchResultsFetch();
```
## API-Dokumentation
### MyTischtennis Spielerbilanzen-Endpoint
**URL-Format:**
```
https://www.mytischtennis.de/click-tt/{association}/{season}/ligen/{groupname}/gruppe/{groupId}/mannschaft/{teamId}/{teamname}/spielerbilanzen/gesamt?_data=routes%2Fclick-tt%2B%2F%24association%2B%2F%24season%2B%2F%24type%2B%2F%28%24groupname%29.gruppe.%24urlid_.mannschaft.%24teamid.%24teamname%2B%2Fspielerbilanzen.%24filter
```
**Parameter:**
- `{association}`: Verband (z.B. "HeTTV")
- `{season}`: Saison im Format "25--26"
- `{groupname}`: Gruppenname URL-encoded (z.B. "1.Kreisklasse")
- `{groupId}`: Gruppen-ID (numerisch, z.B. "504417")
- `{teamId}`: Team-ID (numerisch, z.B. "2995094")
- `{teamname}`: Teamname URL-encoded mit Underscores (z.B. "Harheimer_TC_(J11)")
**Response:** JSON mit `data.balancesheet` Array
## Sicherheit
- ✅ Automatische Session-Verwaltung
- ✅ Re-Authentifizierung bei abgelaufenen Sessions
- ✅ Passwörter verschlüsselt gespeichert
- ✅ Fehlerbehandlung und Logging
- ✅ Graceful Degradation (einzelne Team-Fehler stoppen nicht den gesamten Prozess)

View File

@@ -0,0 +1,328 @@
# MyTischtennis URL Parser
## Übersicht
Der URL-Parser ermöglicht es, myTischtennis-Team-URLs automatisch zu parsen und die Konfiguration für automatische Datenabrufe vorzunehmen.
## Verwendung
### 1. URL Parsen
**Endpoint:** `POST /api/mytischtennis/parse-url`
**Request:**
```json
{
"url": "https://www.mytischtennis.de/click-tt/HeTTV/25--26/ligen/1.Kreisklasse/gruppe/504417/mannschaft/2995094/Harheimer_TC_(J11)/spielerbilanzen/gesamt"
}
```
**Response:**
```json
{
"success": true,
"data": {
"association": "HeTTV",
"season": "25/26",
"type": "ligen",
"groupname": "1.Kreisklasse",
"groupId": "504417",
"teamId": "2995094",
"teamname": "Harheimer TC (J11)",
"originalUrl": "https://www.mytischtennis.de/click-tt/...",
"clubId": "43030",
"clubName": "Harheimer TC",
"teamName": "Jugend 11",
"leagueName": "Jugend 13 1. Kreisklasse",
"region": "Frankfurt",
"tableRank": 8,
"matchesWon": 0,
"matchesLost": 3
}
}
```
### 2. Team Automatisch Konfigurieren
**Endpoint:** `POST /api/mytischtennis/configure-team`
**Request:**
```json
{
"url": "https://www.mytischtennis.de/click-tt/HeTTV/25--26/ligen/1.Kreisklasse/gruppe/504417/mannschaft/2995094/Harheimer_TC_(J11)/spielerbilanzen/gesamt",
"clubTeamId": 1,
"createLeague": false,
"createSeason": false
}
```
**Parameter:**
- `url` (required): Die myTischtennis-URL
- `clubTeamId` (required): Die ID des lokalen Club-Teams
- `createLeague` (optional): Wenn `true`, wird eine neue League erstellt
- `createSeason` (optional): Wenn `true`, wird eine neue Season erstellt
**Response:**
```json
{
"success": true,
"message": "Team configured successfully",
"data": {
"team": {
"id": 1,
"name": "Jugend 11",
"myTischtennisTeamId": "2995094"
},
"league": {
"id": 5,
"name": "Jugend 13 1. Kreisklasse",
"myTischtennisGroupId": "504417",
"association": "HeTTV",
"groupname": "1.Kreisklasse"
},
"season": {
"id": 2,
"name": "25/26"
},
"parsedData": { ... }
}
}
```
### 3. URL für Team Abrufen
**Endpoint:** `GET /api/mytischtennis/team-url/:teamId`
**Response:**
```json
{
"success": true,
"url": "https://www.mytischtennis.de/click-tt/HeTTV/25--26/ligen/1.Kreisklasse/gruppe/504417/mannschaft/2995094/Harheimer%20TC%20%28J11%29/spielerbilanzen/gesamt"
}
```
## URL-Format
### Unterstützte URL-Muster
```
https://www.mytischtennis.de/click-tt/{association}/{season}/{type}/{groupname}/gruppe/{groupId}/mannschaft/{teamId}/{teamname}/...
```
**Komponenten:**
- `{association}`: Verband (z.B. "HeTTV", "DTTB", "WestD")
- `{season}`: Saison im Format "YY--YY" (z.B. "25--26" für 2025/2026)
- `{type}`: Typ (meist "ligen")
- `{groupname}`: Gruppenname URL-encoded (z.B. "1.Kreisklasse", "Kreisliga")
- `{groupId}`: Numerische Gruppen-ID (z.B. "504417")
- `{teamId}`: Numerische Team-ID (z.B. "2995094")
- `{teamname}`: Teamname URL-encoded mit Underscores (z.B. "Harheimer_TC_(J11)")
### Beispiel-URLs
**Spielerbilanzen:**
```
https://www.mytischtennis.de/click-tt/HeTTV/25--26/ligen/1.Kreisklasse/gruppe/504417/mannschaft/2995094/Harheimer_TC_(J11)/spielerbilanzen/gesamt
```
**Spielplan:**
```
https://www.mytischtennis.de/click-tt/HeTTV/25--26/ligen/1.Kreisklasse/gruppe/504417/mannschaft/2995094/Harheimer_TC_(J11)/spielplan
```
**Tabelle:**
```
https://www.mytischtennis.de/click-tt/HeTTV/25--26/ligen/1.Kreisklasse/gruppe/504417/mannschaft/2995094/Harheimer_TC_(J11)/tabelle
```
## Datenfluss
### Ohne MyTischtennis-Login
1. URL wird geparst
2. Nur URL-Komponenten werden extrahiert
3. Zusätzliche Daten (clubName, leagueName, etc.) sind nicht verfügbar
### Mit MyTischtennis-Login
1. URL wird geparst
2. API-Request an myTischtennis mit Authentication
3. Vollständige Team-Daten werden abgerufen
4. Alle Felder sind verfügbar
## Frontend-Integration
### Vue.js Beispiel
```javascript
<template>
<div>
<input
v-model="myTischtennisUrl"
placeholder="MyTischtennis URL einfügen..."
@blur="parseUrl"
/>
<div v-if="parsedData">
<h3>{{ parsedData.teamname }}</h3>
<p>Liga: {{ parsedData.leagueName }}</p>
<p>Verband: {{ parsedData.association }}</p>
<p>Tabelle: Platz {{ parsedData.tableRank }}</p>
<button @click="configureTeam">Team konfigurieren</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
myTischtennisUrl: '',
parsedData: null
};
},
methods: {
async parseUrl() {
if (!this.myTischtennisUrl) return;
try {
const response = await fetch('/api/mytischtennis/parse-url', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'userid': this.userId,
'authcode': this.authCode
},
body: JSON.stringify({
url: this.myTischtennisUrl
})
});
const result = await response.json();
this.parsedData = result.data;
} catch (error) {
console.error('Fehler beim Parsen:', error);
alert('URL konnte nicht geparst werden');
}
},
async configureTeam() {
try {
const response = await fetch('/api/mytischtennis/configure-team', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'userid': this.userId,
'authcode': this.authCode
},
body: JSON.stringify({
url: this.myTischtennisUrl,
clubTeamId: this.selectedTeamId,
createLeague: false,
createSeason: true
})
});
const result = await response.json();
if (result.success) {
alert('Team erfolgreich konfiguriert!');
}
} catch (error) {
console.error('Fehler bei Konfiguration:', error);
alert('Team konnte nicht konfiguriert werden');
}
}
}
};
</script>
```
## Workflow
### Empfohlener Workflow für Benutzer
1. **MyTischtennis-URL kopieren:**
- Auf myTischtennis.de zum Team navigieren
- URL aus Adresszeile kopieren
2. **URL in Trainingstagebuch einfügen:**
- Zu Team-Verwaltung navigieren
- URL einfügen
- Automatisches Parsen
3. **Konfiguration überprüfen:**
- Geparste Daten werden angezeigt
- Benutzer kann Daten überprüfen und bei Bedarf anpassen
4. **Team konfigurieren:**
- Auf "Konfigurieren" klicken
- System speichert alle benötigten IDs
- Automatischer Datenabruf ist ab sofort aktiv
## Fehlerbehandlung
### Häufige Fehler
**"Invalid myTischtennis URL format"**
- URL entspricht nicht dem erwarteten Format
- Lösung: Vollständige URL von der Spielerbilanzen-Seite kopieren
**"Season not found"**
- Saison existiert noch nicht in der Datenbank
- Lösung: `createSeason: true` setzen
**"Team has no league assigned"**
- Team hat keine verknüpfte Liga
- Lösung: `createLeague: true` setzen oder Liga manuell zuweisen
**"HTTP 401: Unauthorized"**
- MyTischtennis-Login abgelaufen oder nicht vorhanden
- Lösung: In MyTischtennis-Settings erneut anmelden
## Sicherheit
- ✅ Alle Endpoints erfordern Authentifizierung
- ✅ UserID wird aus Header-Parameter gelesen
- ✅ MyTischtennis-Credentials werden sicher gespeichert
- ✅ Keine sensiblen Daten in URLs
## Technische Details
### Service: `myTischtennisUrlParserService`
**Methoden:**
- `parseUrl(url)` - Parst URL und extrahiert Komponenten
- `fetchTeamData(parsedUrl, cookie, accessToken)` - Ruft zusätzliche Daten ab
- `getCompleteConfig(url, cookie, accessToken)` - Kombination aus Parsen + Abrufen
- `isValidTeamUrl(url)` - Validiert URL-Format
- `buildUrl(config)` - Baut URL aus Komponenten
### Controller: `myTischtennisUrlController`
**Endpoints:**
- `POST /api/mytischtennis/parse-url` - URL parsen
- `POST /api/mytischtennis/configure-team` - Team konfigurieren
- `GET /api/mytischtennis/team-url/:teamId` - URL abrufen
## Zukünftige Erweiterungen
### Geplante Features
1. **Bulk-Import:**
- Mehrere URLs gleichzeitig importieren
- Alle Teams einer Liga auf einmal konfigurieren
2. **Auto-Discovery:**
- Automatisches Finden aller Teams eines Vereins
- Vorschläge für ähnliche Teams
3. **Validierung:**
- Prüfung, ob Team bereits konfiguriert ist
- Warnung bei Duplikaten
4. **History:**
- Speichern der URL-Konfigurationen
- Versionierung bei Änderungen

View File

@@ -149,13 +149,11 @@ class MyTischtennisClient {
* @returns {Promise<Object>} User profile with club info
*/
async getUserProfile(cookie) {
console.log('[getUserProfile] - Calling /?_data=root with cookie:', cookie?.substring(0, 50) + '...');
const result = await this.authenticatedRequest('/?_data=root', cookie, {
method: 'GET'
});
console.log('[getUserProfile] - Result success:', result.success);
if (result.success) {
console.log('[getUserProfile] - Response structure:', {
@@ -169,8 +167,6 @@ class MyTischtennisClient {
qttr: result.data?.userProfile?.qttr
});
console.log('[getUserProfile] - Full userProfile.club:', result.data?.userProfile?.club);
console.log('[getUserProfile] - Full userProfile.organization:', result.data?.userProfile?.organization);
return {
success: true,
@@ -199,12 +195,10 @@ class MyTischtennisClient {
let currentPage = 0;
let hasMorePages = true;
console.log('[getClubRankings] - Starting to fetch rankings for club', clubId);
while (hasMorePages) {
const endpoint = `/rankings/andro-rangliste?all-players=on&clubnr=${clubId}&fednickname=${fedNickname}&results-per-page=100&page=${currentPage}&_data=routes%2F%24`;
console.log(`[getClubRankings] - Fetching page ${currentPage}...`);
const result = await this.authenticatedRequest(endpoint, cookie, {
method: 'GET'
@@ -245,7 +239,6 @@ class MyTischtennisClient {
};
}
console.log(`[getClubRankings] - Page ${currentPage}: Found ${entries.length} entries`);
// Füge Entries hinzu
allEntries.push(...entries);
@@ -255,19 +248,15 @@ class MyTischtennisClient {
// Oder wenn wir alle erwarteten Einträge haben
if (entries.length === 0) {
hasMorePages = false;
console.log('[getClubRankings] - No more entries, stopping');
} else if (rankingData.numberOfPages && currentPage >= rankingData.numberOfPages - 1) {
hasMorePages = false;
console.log(`[getClubRankings] - Reached last page (${rankingData.numberOfPages})`);
} else if (allEntries.length >= rankingData.resultLength) {
hasMorePages = false;
console.log(`[getClubRankings] - Got all entries (${allEntries.length}/${rankingData.resultLength})`);
} else {
currentPage++;
}
}
console.log(`[getClubRankings] - Total entries fetched: ${allEntries.length}`);
return {
success: true,

View File

@@ -0,0 +1,128 @@
import ClubTeamService from '../services/clubTeamService.js';
import { getUserByToken } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';
export const getClubTeams = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubid: clubId } = req.params;
const { seasonid: seasonId } = req.query;
const user = await getUserByToken(token);
// Check if user has access to this club
const clubTeams = await ClubTeamService.getAllClubTeamsByClub(clubId, seasonId);
res.status(200).json(clubTeams);
} catch (error) {
console.error('[getClubTeams] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const getClubTeam = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubteamid: clubTeamId } = req.params;
const user = await getUserByToken(token);
const clubTeam = await ClubTeamService.getClubTeamById(clubTeamId);
if (!clubTeam) {
return res.status(404).json({ error: "notfound" });
}
res.status(200).json(clubTeam);
} catch (error) {
console.error('[getClubTeam] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const createClubTeam = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubid: clubId } = req.params;
const { name, leagueId, seasonId } = req.body;
const user = await getUserByToken(token);
if (!name) {
return res.status(400).json({ error: "missingname" });
}
const clubTeamData = {
name,
clubId: parseInt(clubId),
leagueId: leagueId ? parseInt(leagueId) : null,
seasonId: seasonId ? parseInt(seasonId) : null
};
const newClubTeam = await ClubTeamService.createClubTeam(clubTeamData);
res.status(201).json(newClubTeam);
} catch (error) {
console.error('[createClubTeam] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const updateClubTeam = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubteamid: clubTeamId } = req.params;
const { name, leagueId, seasonId } = req.body;
const user = await getUserByToken(token);
const updateData = {};
if (name !== undefined) updateData.name = name;
if (leagueId !== undefined) updateData.leagueId = leagueId ? parseInt(leagueId) : null;
if (seasonId !== undefined) updateData.seasonId = seasonId ? parseInt(seasonId) : null;
const success = await ClubTeamService.updateClubTeam(clubTeamId, updateData);
if (!success) {
return res.status(404).json({ error: "notfound" });
}
const updatedClubTeam = await ClubTeamService.getClubTeamById(clubTeamId);
res.status(200).json(updatedClubTeam);
} catch (error) {
console.error('[updateClubTeam] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const deleteClubTeam = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubteamid: clubTeamId } = req.params;
const user = await getUserByToken(token);
const success = await ClubTeamService.deleteClubTeam(clubTeamId);
if (!success) {
return res.status(404).json({ error: "notfound" });
}
res.status(200).json({ message: "Club team deleted successfully" });
} catch (error) {
console.error('[deleteClubTeam] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const getLeagues = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubid: clubId } = req.params;
const { seasonid: seasonId } = req.query;
const user = await getUserByToken(token);
const leagues = await ClubTeamService.getLeaguesByClub(clubId, seasonId);
res.status(200).json(leagues);
} catch (error) {
console.error('[getLeagues] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};

View File

@@ -1,77 +1,57 @@
import ClubService from '../services/clubService.js';
import { getUserByToken } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';
export const getClubs = async (req, res) => {
try {
console.log('[getClubs] - get clubs');
const clubs = await ClubService.getAllClubs();
console.log('[getClubs] - prepare response');
res.status(200).json(clubs);
console.log('[getClubs] - done');
} catch (error) {
console.log('[getClubs] - error');
console.log(error);
console.error('[getClubs] - error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const addClub = async (req, res) => {
console.log('[addClub] - Read out parameters');
const { authcode: token } = req.headers;
const { name: clubName } = req.body;
try {
console.log('[addClub] - find club by name');
const club = await ClubService.findClubByName(clubName);
console.log('[addClub] - get user');
const user = await getUserByToken(token);
console.log('[addClub] - check if club already exists');
if (club) {
res.status(409).json({ error: "alreadyexists" });
return;
}
console.log('[addClub] - create club');
const newClub = await ClubService.createClub(clubName);
console.log('[addClub] - add user to new club');
await ClubService.addUserToClub(user.id, newClub.id);
console.log('[addClub] - prepare response');
res.status(200).json(newClub);
console.log('[addClub] - done');
} catch (error) {
console.log('[addClub] - error');
console.log(error);
console.error('[addClub] - error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const getClub = async (req, res) => {
console.log('[getClub] - start');
try {
const { authcode: token } = req.headers;
const { clubid: clubId } = req.params;
console.log('[getClub] - get user');
const user = await getUserByToken(token);
console.log('[getClub] - get users club');
const access = await ClubService.getUserClubAccess(user.id, clubId);
console.log('[getClub] - check access');
if (access.length === 0 || !access[0].approved) {
res.status(403).json({ error: "noaccess", status: access.length === 0 ? "notrequested" : "requested" });
return;
}
console.log('[getClub] - get club');
const club = await ClubService.findClubById(clubId);
console.log('[getClub] - check club exists');
if (!club) {
return res.status(404).json({ message: 'Club not found' });
}
console.log('[getClub] - set response');
res.status(200).json(club);
console.log('[getClub] - done');
} catch (error) {
console.log(error);
console.error('[getClub] - error:', error);
res.status(500).json({ message: 'Server error' });
}
};
@@ -82,7 +62,6 @@ export const requestClubAccess = async (req, res) => {
try {
const user = await getUserByToken(token);
console.log(user);
await ClubService.requestAccessToClub(user.id, clubId);
res.status(200).json({});
@@ -92,6 +71,7 @@ export const requestClubAccess = async (req, res) => {
} else if (error.message === 'clubnotfound') {
res.status(404).json({ err: "clubnotfound" });
} else {
console.error('[requestClubAccess] - error:', error);
res.status(500).json({ err: "internalerror" });
}
}

View File

@@ -1,6 +1,7 @@
import diaryService from '../services/diaryService.js';
import HttpError from '../exceptions/HttpError.js';
import { devLog } from '../utils/logger.js';
const getDatesForClub = async (req, res) => {
try {
const { clubId } = req.params;
@@ -38,7 +39,7 @@ const updateTrainingTimes = async (req, res) => {
const { authcode: userToken } = req.headers;
const { dateId, trainingStart, trainingEnd } = req.body;
if (!dateId || !trainingStart) {
console.log(dateId, trainingStart, trainingEnd);
devLog(dateId, trainingStart, trainingEnd);
throw new HttpError('notallfieldsfilled', 400);
}
const updatedDate = await diaryService.updateTrainingTimes(userToken, clubId, dateId, trainingStart, trainingEnd);

View File

@@ -1,5 +1,6 @@
import diaryDateActivityService from '../services/diaryDateActivityService.js';
import { devLog } from '../utils/logger.js';
export const createDiaryDateActivity = async (req, res) => {
try {
const { authcode: userToken } = req.headers;
@@ -15,7 +16,7 @@ export const createDiaryDateActivity = async (req, res) => {
});
res.status(201).json(activityItem);
} catch (error) {
console.log(error);
devLog(error);
res.status(500).json({ error: 'Error creating activity' });
}
};
@@ -58,7 +59,7 @@ export const updateDiaryDateActivityOrder = async (req, res) => {
const updatedActivity = await diaryDateActivityService.updateActivityOrder(userToken, clubId, id, orderId);
res.status(200).json(updatedActivity);
} catch (error) {
console.log(error);
devLog(error);
res.status(500).json({ error: 'Error updating activity order' });
}
};
@@ -70,7 +71,7 @@ export const getDiaryDateActivities = async (req, res) => {
const activities = await diaryDateActivityService.getActivities(userToken, clubId, diaryDateId);
res.status(200).json(activities);
} catch (error) {
console.log(error);
devLog(error);
res.status(500).json({ error: 'Error getting activities' });
}
}
@@ -82,7 +83,7 @@ export const addGroupActivity = async(req, res) => {
const activityItem = await diaryDateActivityService.addGroupActivity(userToken, clubId, diaryDateId, groupId, activity);
res.status(201).json(activityItem);
} catch (error) {
console.log(error);
devLog(error);
res.status(500).json({ error: 'Error adding group activity' });
}
}

View File

@@ -1,7 +1,8 @@
import diaryDateTagService from "../services/diaryDateTagService.js"
import { devLog } from '../utils/logger.js';
export const getDiaryDateMemberTags = async (req, res) => {
console.log("getDiaryDateMemberTags");
devLog("getDiaryDateMemberTags");
try {
const { authcode: userToken } = req.headers;
const { clubId, memberId } = req.params;
@@ -14,7 +15,7 @@ export const getDiaryDateMemberTags = async (req, res) => {
}
export const addDiaryDateTag = async (req, res) => {
console.log("addDiaryDateTag");
devLog("addDiaryDateTag");
try {
const { authcode: userToken } = req.headers;
const { clubId } = req.params;

View File

@@ -1,11 +1,12 @@
import DiaryMemberService from '../services/diaryMemberService.js';
import { devLog } from '../utils/logger.js';
const getMemberTags = async (req, res) => {
try {
const { diaryDateId, memberId } = req.query;
const { clubId } = req.params;
const { authcode: userToken } = req.headers;
console.log(diaryDateId, memberId, clubId);
devLog(diaryDateId, memberId, clubId);
const tags = await DiaryMemberService.getTagsForMemberAndDate(userToken, clubId, diaryDateId, memberId);
res.status(200).json(tags);
} catch (error) {
@@ -19,7 +20,7 @@ const getMemberNotes = async (req, res) => {
const { diaryDateId, memberId } = req.query;
const { clubId } = req.params;
const { authcode: userToken } = req.headers;
console.log('---------->', userToken, clubId);
devLog('---------->', userToken, clubId);
const notes = await DiaryMemberService.getNotesForMember(userToken, clubId, diaryDateId, memberId);
res.status(200).json(notes);
} catch (error) {

View File

@@ -1,5 +1,6 @@
import { DiaryTag, DiaryDateTag } from '../models/index.js';
import { devLog } from '../utils/logger.js';
export const getTags = async (req, res) => {
try {
const tags = await DiaryTag.findAll();
@@ -12,11 +13,10 @@ export const getTags = async (req, res) => {
export const createTag = async (req, res) => {
try {
const { name } = req.body;
console.log(name);
devLog(name);
const newTag = await DiaryTag.findOrCreate({ where: { name }, defaults: { name } });
res.status(201).json(newTag);
} catch (error) {
console.log('[createTag] - Error:', error);
res.status(500).json({ error: 'Error creating tag' });
}
};

View File

@@ -1,6 +1,7 @@
import HttpError from '../exceptions/HttpError.js';
import groupService from '../services/groupService.js';
import { devLog } from '../utils/logger.js';
const addGroup = async(req, res) => {
try {
const { authcode: userToken } = req.headers;
@@ -9,7 +10,7 @@ const addGroup = async(req, res) => {
res.status(201).json(result);
} catch (error) {
console.error('[addGroup] - Error:', error);
console.log(req.params, req.headers, req.body)
devLog(req.params, req.headers, req.body)
res.status(error.statusCode || 500).json({ error: error.message });
}
}

View File

@@ -1,6 +1,7 @@
import MatchService from '../services/matchService.js';
import fs from 'fs';
import { devLog } from '../utils/logger.js';
export const uploadCSV = async (req, res) => {
try {
const { clubId } = req.body;
@@ -21,10 +22,11 @@ export const uploadCSV = async (req, res) => {
export const getLeaguesForCurrentSeason = async (req, res) => {
try {
console.log(req.headers, req.params);
devLog(req.headers, req.params);
const { authcode: userToken } = req.headers;
const { clubId } = req.params;
const leagues = await MatchService.getLeaguesForCurrentSeason(userToken, clubId);
const { seasonid: seasonId } = req.query;
const leagues = await MatchService.getLeaguesForCurrentSeason(userToken, clubId, seasonId);
return res.status(200).json(leagues);
} catch (error) {
console.error('Error retrieving leagues:', error);
@@ -36,7 +38,8 @@ export const getMatchesForLeagues = async (req, res) => {
try {
const { authcode: userToken } = req.headers;
const { clubId } = req.params;
const matches = await MatchService.getMatchesForLeagues(userToken, clubId);
const { seasonid: seasonId } = req.query;
const matches = await MatchService.getMatchesForLeagues(userToken, clubId, seasonId);
return res.status(200).json(matches);
} catch (error) {
console.error('Error retrieving matches:', error);
@@ -55,3 +58,47 @@ export const getMatchesForLeague = async (req, res) => {
return res.status(500).json({ error: 'Failed to retrieve matches' });
}
};
export const getLeagueTable = async (req, res) => {
try {
const { authcode: userToken } = req.headers;
const { clubId, leagueId } = req.params;
const table = await MatchService.getLeagueTable(userToken, clubId, leagueId);
return res.status(200).json(table);
} catch (error) {
console.error('Error retrieving league table:', error);
return res.status(500).json({ error: 'Failed to retrieve league table' });
}
};
export const fetchLeagueTableFromMyTischtennis = async (req, res) => {
try {
const { authcode: userToken } = req.headers;
const { clubId, leagueId } = req.params;
const { userid: userIdOrEmail } = req.headers;
// Convert email to userId if needed
let userId = userIdOrEmail;
if (isNaN(userIdOrEmail)) {
const User = (await import('../models/User.js')).default;
const user = await User.findOne({ where: { email: userIdOrEmail } });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
userId = user.id;
}
const autoFetchService = (await import('../services/autoFetchMatchResultsService.js')).default;
await autoFetchService.fetchAndUpdateLeagueTable(userId, leagueId);
// Return updated table data
const table = await MatchService.getLeagueTable(userToken, clubId, leagueId);
return res.status(200).json({
message: 'League table updated from MyTischtennis',
data: table
});
} catch (error) {
console.error('Error fetching league table from MyTischtennis:', error);
return res.status(500).json({ error: 'Failed to fetch league table from MyTischtennis' });
}
};

View File

@@ -1,5 +1,6 @@
import MemberService from "../services/memberService.js";
import { devLog } from '../utils/logger.js';
const getClubMembers = async(req, res) => {
try {
const { authcode: userToken } = req.headers;
@@ -9,24 +10,17 @@ const getClubMembers = async(req, res) => {
}
res.status(200).json(await MemberService.getClubMembers(userToken, clubId, showAll));
} catch(error) {
console.log('[getClubMembers] - Error: ', error);
res.status(500).json({ error: 'systemerror' });
}
}
const getWaitingApprovals = async(req, res) => {
try {
console.log('[getWaitingApprovals] - Start');
const { id: clubId } = req.params;
console.log('[getWaitingApprovals] - get token');
const { authcode: userToken } = req.headers;
console.log('[getWaitingApprovals] - load for waiting approvals');
const waitingApprovals = await MemberService.getApprovalRequests(userToken, clubId);
console.log('[getWaitingApprovals] - set response');
res.status(200).json(waitingApprovals);
console.log('[getWaitingApprovals] - done');
} catch(error) {
console.log('[getWaitingApprovals] - Error: ', error);
res.status(403).json({ error: error });
}
}
@@ -59,7 +53,6 @@ const uploadMemberImage = async (req, res) => {
};
const getMemberImage = async (req, res) => {
console.log('[getMemberImage]');
try {
const { clubId, memberId } = req.params;
const { authcode: userToken } = req.headers;
@@ -76,7 +69,6 @@ const getMemberImage = async (req, res) => {
};
const updateRatingsFromMyTischtennis = async (req, res) => {
console.log('[updateRatingsFromMyTischtennis]');
try {
const { id: clubId } = req.params;
const { authcode: userToken } = req.headers;
@@ -88,4 +80,25 @@ const updateRatingsFromMyTischtennis = async (req, res) => {
}
};
export { getClubMembers, getWaitingApprovals, setClubMembers, uploadMemberImage, getMemberImage, updateRatingsFromMyTischtennis };
const rotateMemberImage = async (req, res) => {
try {
const { clubId, memberId } = req.params;
const { direction } = req.body;
const { authcode: userToken } = req.headers;
if (!direction || !['left', 'right'].includes(direction)) {
return res.status(400).json({
success: false,
error: 'Ungültige Drehrichtung. Verwenden Sie "left" oder "right".'
});
}
const result = await MemberService.rotateMemberImage(userToken, clubId, memberId, direction);
res.status(result.status).json(result.response);
} catch (error) {
console.error('[rotateMemberImage] - Error:', error);
res.status(500).json({ success: false, error: 'Failed to rotate image' });
}
};
export { getClubMembers, getWaitingApprovals, setClubMembers, uploadMemberImage, getMemberImage, updateRatingsFromMyTischtennis, rotateMemberImage };

View File

@@ -1,15 +1,14 @@
import MemberNoteService from "../services/memberNoteService.js";
import { devLog } from '../utils/logger.js';
const getMemberNotes = async (req, res) => {
try {
const { authcode: userToken } = req.headers;
const { memberId } = req.params;
const { clubId } = req.query;
console.log('[getMemberNotes]', userToken, memberId, clubId);
const notes = await MemberNoteService.getNotesForMember(userToken, clubId, memberId);
res.status(200).json(notes);
} catch (error) {
console.log('[getMemberNotes] - Error: ', error);
res.status(500).json({ error: 'systemerror' });
}
};
@@ -18,12 +17,10 @@ const addMemberNote = async (req, res) => {
try {
const { authcode: userToken } = req.headers;
const { memberId, content, clubId } = req.body;
console.log('[addMemberNote]', userToken, memberId, content, clubId);
await MemberNoteService.addNoteToMember(userToken, clubId, memberId, content);
const notes = await MemberNoteService.getNotesForMember(userToken, clubId, memberId);
res.status(201).json(notes);
} catch (error) {
console.log('[addMemberNote] - Error: ', error);
res.status(500).json({ error: 'systemerror' });
}
};
@@ -33,13 +30,11 @@ const deleteMemberNote = async (req, res) => {
const { authcode: userToken } = req.headers;
const { noteId } = req.params;
const { clubId } = req.body;
console.log('[deleteMemberNote]', userToken, noteId, clubId);
const memberId = await MemberNoteService.getMemberIdForNote(noteId); // Member ID ermitteln
await MemberNoteService.deleteNoteForMember(userToken, clubId, noteId);
const notes = await MemberNoteService.getNotesForMember(userToken, clubId, memberId);
res.status(200).json(notes);
} catch (error) {
console.log('[deleteMemberNote] - Error: ', error);
res.status(500).json({ error: 'systemerror' });
}
};

View File

@@ -42,7 +42,7 @@ class MyTischtennisController {
async upsertAccount(req, res, next) {
try {
const userId = req.user.id;
const { email, password, savePassword, userPassword } = req.body;
const { email, password, savePassword, autoUpdateRatings, userPassword } = req.body;
if (!email) {
throw new HttpError(400, 'E-Mail-Adresse erforderlich');
@@ -58,6 +58,7 @@ class MyTischtennisController {
email,
password,
savePassword || false,
autoUpdateRatings || false,
userPassword
);
@@ -127,6 +128,77 @@ class MyTischtennisController {
next(error);
}
}
/**
* GET /api/mytischtennis/update-history
* Get update ratings history
*/
async getUpdateHistory(req, res, next) {
try {
const userId = req.user.id;
const history = await myTischtennisService.getUpdateHistory(userId);
res.status(200).json({ history });
} catch (error) {
next(error);
}
}
/**
* Get fetch logs for current user
*/
async getFetchLogs(req, res, next) {
try {
const { userid: userIdOrEmail } = req.headers;
// Convert email to userId if needed
let userId = userIdOrEmail;
if (isNaN(userIdOrEmail)) {
const User = (await import('../models/User.js')).default;
const user = await User.findOne({ where: { email: userIdOrEmail } });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
userId = user.id;
}
const fetchLogService = (await import('../services/myTischtennisFetchLogService.js')).default;
const logs = await fetchLogService.getFetchLogs(userId, {
limit: req.query.limit ? parseInt(req.query.limit) : 50,
fetchType: req.query.type
});
res.status(200).json({ logs });
} catch (error) {
next(error);
}
}
/**
* Get latest successful fetches for each type
*/
async getLatestFetches(req, res, next) {
try {
const { userid: userIdOrEmail } = req.headers;
// Convert email to userId if needed
let userId = userIdOrEmail;
if (isNaN(userIdOrEmail)) {
const User = (await import('../models/User.js')).default;
const user = await User.findOne({ where: { email: userIdOrEmail } });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
userId = user.id;
}
const fetchLogService = (await import('../services/myTischtennisFetchLogService.js')).default;
const latestFetches = await fetchLogService.getLatestSuccessfulFetches(userId);
res.status(200).json({ latestFetches });
} catch (error) {
next(error);
}
}
}
export default new MyTischtennisController();

View File

@@ -0,0 +1,477 @@
import myTischtennisUrlParserService from '../services/myTischtennisUrlParserService.js';
import myTischtennisService from '../services/myTischtennisService.js';
import autoFetchMatchResultsService from '../services/autoFetchMatchResultsService.js';
import ClubTeam from '../models/ClubTeam.js';
import League from '../models/League.js';
import Season from '../models/Season.js';
import User from '../models/User.js';
import HttpError from '../exceptions/HttpError.js';
import { devLog } from '../utils/logger.js';
class MyTischtennisUrlController {
/**
* Parse myTischtennis URL and return configuration data
* POST /api/mytischtennis/parse-url
* Body: { url: string }
*/
async parseUrl(req, res, next) {
try {
const { url } = req.body;
if (!url) {
throw new HttpError(400, 'URL is required');
}
// Validate URL
if (!myTischtennisUrlParserService.isValidTeamUrl(url)) {
throw new HttpError(400, 'Invalid myTischtennis URL format');
}
// Parse URL
const parsedData = myTischtennisUrlParserService.parseUrl(url);
// Try to fetch additional data if user is authenticated
const userIdOrEmail = req.headers.userid;
let completeData = parsedData;
if (userIdOrEmail) {
// Get actual user ID
let userId = userIdOrEmail;
if (isNaN(userIdOrEmail)) {
const user = await User.findOne({ where: { email: userIdOrEmail } });
if (user) userId = user.id;
}
try {
const account = await myTischtennisService.getAccount(userId);
if (account && account.accessToken) {
completeData = await myTischtennisUrlParserService.fetchTeamData(
parsedData,
account.cookie,
account.accessToken
);
}
} catch (error) {
console.error('Error fetching additional team data:', error);
// Continue with parsed data only
}
}
res.json({
success: true,
data: completeData
});
} catch (error) {
next(error);
}
}
/**
* Configure team from myTischtennis URL
* POST /api/mytischtennis/configure-team
* Body: { url: string, clubTeamId: number, createLeague?: boolean, createSeason?: boolean }
*/
async configureTeam(req, res, next) {
try {
const { url, clubTeamId, createLeague, createSeason } = req.body;
const userIdOrEmail = req.headers.userid;
if (!url || !clubTeamId) {
throw new HttpError(400, 'URL and clubTeamId are required');
}
// Get actual user ID
let userId = userIdOrEmail;
if (isNaN(userIdOrEmail)) {
const user = await User.findOne({ where: { email: userIdOrEmail } });
if (!user) {
throw new HttpError(404, 'User not found');
}
userId = user.id;
}
// Parse URL
const parsedData = myTischtennisUrlParserService.parseUrl(url);
// Try to fetch additional data
let completeData = parsedData;
const account = await myTischtennisService.getAccount(userId);
if (account && account.accessToken) {
try {
completeData = await myTischtennisUrlParserService.fetchTeamData(
parsedData,
account.cookie,
account.accessToken
);
} catch (error) {
console.error('Error fetching team data:', error);
}
}
// Find or create season
let season = await Season.findOne({
where: { season: completeData.season }
});
if (!season && createSeason) {
season = await Season.create({
season: completeData.season
});
}
if (!season) {
throw new HttpError(404, `Season ${completeData.season} not found. Set createSeason=true to create it.`);
}
// Find or create league
const team = await ClubTeam.findByPk(clubTeamId);
if (!team) {
throw new HttpError(404, 'Club team not found');
}
let league;
// First, try to find existing league by name and season
const leagueName = completeData.leagueName || completeData.groupname;
league = await League.findOne({
where: {
name: leagueName,
seasonId: season.id,
clubId: team.clubId
}
});
if (league) {
devLog(`Found existing league: ${league.name} (ID: ${league.id})`);
// Update myTischtennis fields
await league.update({
myTischtennisGroupId: completeData.groupId,
association: completeData.association,
groupname: completeData.groupname
});
} else if (team.leagueId) {
// Team has a league assigned, update it
league = await League.findByPk(team.leagueId);
if (league) {
devLog(`Updating team's existing league: ${league.name} (ID: ${league.id})`);
await league.update({
name: leagueName,
myTischtennisGroupId: completeData.groupId,
association: completeData.association,
groupname: completeData.groupname
});
}
} else if (createLeague) {
// Create new league
devLog(`Creating new league: ${leagueName}`);
league = await League.create({
name: leagueName,
seasonId: season.id,
clubId: team.clubId,
myTischtennisGroupId: completeData.groupId,
association: completeData.association,
groupname: completeData.groupname
});
} else {
throw new HttpError(400, 'League not found and team has no league assigned. Set createLeague=true to create one.');
}
// Update team
await team.update({
myTischtennisTeamId: completeData.teamId,
leagueId: league.id,
seasonId: season.id
});
res.json({
success: true,
message: 'Team configured successfully',
data: {
team: {
id: team.id,
name: team.name,
myTischtennisTeamId: completeData.teamId
},
league: {
id: league.id,
name: league.name,
myTischtennisGroupId: completeData.groupId,
association: completeData.association,
groupname: completeData.groupname
},
season: {
id: season.id,
name: season.season
},
parsedData: completeData
}
});
} catch (error) {
next(error);
}
}
/**
* Manually fetch team data from myTischtennis
* POST /api/mytischtennis/fetch-team-data
* Body: { clubTeamId: number }
*/
async fetchTeamData(req, res, next) {
try {
const { clubTeamId } = req.body;
const userIdOrEmail = req.headers.userid;
if (!clubTeamId) {
throw new HttpError(400, 'clubTeamId is required');
}
// Get actual user ID (userid header might be email address)
let userId = userIdOrEmail;
if (isNaN(userIdOrEmail)) {
// It's an email, find the user
const user = await User.findOne({ where: { email: userIdOrEmail } });
if (!user) {
throw new HttpError(404, 'User not found');
}
userId = user.id;
}
// Get myTischtennis session (similar to memberService.updateRatingsFromMyTischtennis)
console.log('Fetching session for userId:', userId, '(from header:', userIdOrEmail, ')');
let session;
try {
session = await myTischtennisService.getSession(userId);
console.log('Session found:', !!session);
} catch (sessionError) {
console.log('Session invalid, attempting login...', sessionError.message);
// Versuche automatischen Login mit gespeicherten Credentials
try {
await myTischtennisService.verifyLogin(userId);
session = await myTischtennisService.getSession(userId);
console.log('Automatic login successful');
} catch (loginError) {
console.error('Automatic login failed:', loginError.message);
throw new HttpError(401, 'MyTischtennis-Session abgelaufen und automatischer Login fehlgeschlagen. Bitte melden Sie sich in den MyTischtennis-Einstellungen an.');
}
}
// Get account data (for clubId, etc.)
const account = await myTischtennisService.getAccount(userId);
if (!account) {
throw new HttpError(404, 'MyTischtennis-Account nicht verknüpft. Bitte verknüpfen Sie Ihren Account in den MyTischtennis-Einstellungen.');
}
console.log('Using session:', {
email: account.email,
hasCookie: !!session.cookie,
hasAccessToken: !!session.accessToken,
expiresAt: new Date(session.expiresAt * 1000)
});
// Get team with league and season
const team = await ClubTeam.findByPk(clubTeamId, {
include: [
{
model: League,
as: 'league',
include: [
{
model: Season,
as: 'season'
}
]
}
]
});
if (!team) {
throw new HttpError(404, 'Team not found');
}
console.log('Team data:', {
id: team.id,
name: team.name,
myTischtennisTeamId: team.myTischtennisTeamId,
hasLeague: !!team.league,
leagueData: team.league ? {
id: team.league.id,
name: team.league.name,
myTischtennisGroupId: team.league.myTischtennisGroupId,
association: team.league.association,
groupname: team.league.groupname,
hasSeason: !!team.league.season
} : null
});
if (!team.myTischtennisTeamId || !team.league || !team.league.myTischtennisGroupId) {
throw new HttpError(400, 'Team is not configured for myTischtennis');
}
// Fetch data for this specific team
const startTime = Date.now();
let matchResultsSuccess = false;
let tableUpdateSuccess = false;
let matchResultsCount = 0;
let tableUpdateCount = 0;
try {
const result = await autoFetchMatchResultsService.fetchTeamResults(
{
userId: account.userId,
email: account.email,
cookie: session.cookie,
accessToken: session.accessToken,
expiresAt: session.expiresAt,
getPassword: () => null // Not needed for manual fetch
},
team
);
matchResultsSuccess = true;
matchResultsCount = result.fetchedCount || 0;
// Log match results fetch
const fetchLogService = (await import('../services/myTischtennisFetchLogService.js')).default;
await fetchLogService.logFetch(
account.userId,
'match_results',
true,
`${matchResultsCount} Spielergebnisse erfolgreich abgerufen`,
{
recordsProcessed: matchResultsCount,
executionTime: Date.now() - startTime,
isAutomatic: false
}
);
} catch (error) {
console.error('Error fetching match results:', error);
const fetchLogService = (await import('../services/myTischtennisFetchLogService.js')).default;
await fetchLogService.logFetch(
account.userId,
'match_results',
false,
'Fehler beim Abrufen der Spielergebnisse',
{
errorDetails: error.message,
executionTime: Date.now() - startTime,
isAutomatic: false
}
);
}
// Also fetch and update league table data
let tableUpdateResult = null;
const tableStartTime = Date.now();
try {
await autoFetchMatchResultsService.fetchAndUpdateLeagueTable(account.userId, team.league.id);
tableUpdateResult = 'League table updated successfully';
tableUpdateSuccess = true;
tableUpdateCount = 1; // One table updated
console.log('✓ League table updated for league:', team.league.id);
// Log league table fetch
const fetchLogService = (await import('../services/myTischtennisFetchLogService.js')).default;
await fetchLogService.logFetch(
account.userId,
'league_table',
true,
'Ligatabelle erfolgreich aktualisiert',
{
recordsProcessed: tableUpdateCount,
executionTime: Date.now() - tableStartTime,
isAutomatic: false
}
);
} catch (error) {
console.error('Error fetching league table data:', error);
tableUpdateResult = 'League table update failed: ' + error.message;
// Log league table fetch failure
const fetchLogService = (await import('../services/myTischtennisFetchLogService.js')).default;
await fetchLogService.logFetch(
account.userId,
'league_table',
false,
'Fehler beim Aktualisieren der Ligatabelle',
{
errorDetails: error.message,
executionTime: Date.now() - tableStartTime,
isAutomatic: false
}
);
// Don't fail the entire request if table update fails
}
res.json({
success: true,
message: `${matchResultsCount} Datensätze abgerufen und verarbeitet`,
data: {
fetchedCount: matchResultsCount,
teamName: team.name,
tableUpdate: tableUpdateResult
}
});
} catch (error) {
console.error('Error in fetchTeamData:', error);
console.error('Error stack:', error.stack);
next(error);
}
}
/**
* Get myTischtennis URL for a team
* GET /api/mytischtennis/team-url/:teamId
*/
async getTeamUrl(req, res, next) {
try {
const { teamId } = req.params;
const team = await ClubTeam.findByPk(teamId, {
include: [
{
model: League,
as: 'league',
include: [
{
model: Season,
as: 'season'
}
]
}
]
});
if (!team) {
throw new HttpError(404, 'Team not found');
}
if (!team.myTischtennisTeamId || !team.league || !team.league.myTischtennisGroupId) {
throw new HttpError(400, 'Team is not configured for myTischtennis');
}
const url = myTischtennisUrlParserService.buildUrl({
association: team.league.association,
season: team.league.season.name,
groupname: team.league.groupname,
groupId: team.league.myTischtennisGroupId,
teamId: team.myTischtennisTeamId,
teamname: team.name
});
res.json({
success: true,
url
});
} catch (error) {
next(error);
}
}
}
export default new MyTischtennisUrlController();

View File

@@ -1,12 +1,13 @@
import Participant from '../models/Participant.js';
import { devLog } from '../utils/logger.js';
export const getParticipants = async (req, res) => {
try {
const { dateId } = req.params;
const participants = await Participant.findAll({ where: { diaryDateId: dateId } });
res.status(200).json(participants);
} catch (error) {
console.log(error);
devLog(error);
res.status(500).json({ error: 'Fehler beim Abrufen der Teilnehmer' });
}
};
@@ -17,7 +18,7 @@ export const addParticipant = async (req, res) => {
const participant = await Participant.create({ diaryDateId, memberId });
res.status(201).json(participant);
} catch (error) {
console.log(error);
devLog(error);
res.status(500).json({ error: 'Fehler beim Hinzufügen des Teilnehmers' });
}
};
@@ -28,7 +29,7 @@ export const removeParticipant = async (req, res) => {
await Participant.destroy({ where: { diaryDateId, memberId } });
res.status(200).json({ message: 'Teilnehmer entfernt' });
} catch (error) {
console.log(error);
devLog(error);
res.status(500).json({ error: 'Fehler beim Entfernen des Teilnehmers' });
}
};

View File

@@ -5,6 +5,7 @@ import path from 'path';
import fs from 'fs';
import sharp from 'sharp';
import { devLog } from '../utils/logger.js';
export const uploadPredefinedActivityImage = async (req, res) => {
try {
const { id } = req.params; // predefinedActivityId
@@ -35,7 +36,6 @@ export const uploadPredefinedActivityImage = async (req, res) => {
// Extrahiere Zeichnungsdaten aus dem Request
const drawingData = req.body.drawingData ? JSON.parse(req.body.drawingData) : null;
console.log('[uploadPredefinedActivityImage] - drawingData:', drawingData);
const imageRecord = await PredefinedActivityImage.create({
predefinedActivityId: id,

View File

@@ -0,0 +1,103 @@
import SeasonService from '../services/seasonService.js';
import { getUserByToken } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';
export const getSeasons = async (req, res) => {
try {
const { authcode: token } = req.headers;
const user = await getUserByToken(token);
const seasons = await SeasonService.getAllSeasons();
res.status(200).json(seasons);
} catch (error) {
console.error('[getSeasons] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const getCurrentSeason = async (req, res) => {
try {
const { authcode: token } = req.headers;
const user = await getUserByToken(token);
const season = await SeasonService.getOrCreateCurrentSeason();
res.status(200).json(season);
} catch (error) {
console.error('[getCurrentSeason] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const createSeason = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { season } = req.body;
const user = await getUserByToken(token);
if (!season) {
return res.status(400).json({ error: "missingseason" });
}
// Validiere Saison-Format (z.B. "2023/2024")
const seasonRegex = /^\d{4}\/\d{4}$/;
if (!seasonRegex.test(season)) {
return res.status(400).json({ error: "invalidseasonformat" });
}
const newSeason = await SeasonService.createSeason(season);
res.status(201).json(newSeason);
} catch (error) {
console.error('[createSeason] - Error:', error);
if (error.message === 'Season already exists') {
res.status(409).json({ error: "alreadyexists" });
} else {
res.status(500).json({ error: "internalerror" });
}
}
};
export const getSeason = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { seasonid: seasonId } = req.params;
const user = await getUserByToken(token);
const season = await SeasonService.getSeasonById(seasonId);
if (!season) {
return res.status(404).json({ error: "notfound" });
}
res.status(200).json(season);
} catch (error) {
console.error('[getSeason] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const deleteSeason = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { seasonid: seasonId } = req.params;
const user = await getUserByToken(token);
const success = await SeasonService.deleteSeason(seasonId);
if (!success) {
return res.status(404).json({ error: "notfound" });
}
res.status(200).json({ message: "deleted" });
} catch (error) {
console.error('[deleteSeason] - Error:', error);
if (error.message === 'Season is used by teams' || error.message === 'Season is used by leagues') {
res.status(409).json({ error: "seasoninuse" });
} else {
res.status(500).json({ error: "internalerror" });
}
}
};

View File

@@ -0,0 +1,130 @@
import TeamService from '../services/teamService.js';
import { getUserByToken } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';
export const getTeams = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubid: clubId } = req.params;
const { seasonid: seasonId } = req.query;
const user = await getUserByToken(token);
// Check if user has access to this club
const teams = await TeamService.getAllTeamsByClub(clubId, seasonId);
res.status(200).json(teams);
} catch (error) {
console.error('[getTeams] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const getTeam = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { teamid: teamId } = req.params;
const user = await getUserByToken(token);
const team = await TeamService.getTeamById(teamId);
if (!team) {
return res.status(404).json({ error: "notfound" });
}
res.status(200).json(team);
} catch (error) {
console.error('[getTeam] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const createTeam = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubid: clubId } = req.params;
const { name, leagueId, seasonId } = req.body;
const user = await getUserByToken(token);
if (!name) {
return res.status(400).json({ error: "missingname" });
}
const teamData = {
name,
clubId: parseInt(clubId),
leagueId: leagueId ? parseInt(leagueId) : null,
seasonId: seasonId ? parseInt(seasonId) : null
};
const newTeam = await TeamService.createTeam(teamData);
res.status(201).json(newTeam);
} catch (error) {
console.error('[createTeam] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const updateTeam = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { teamid: teamId } = req.params;
const { name, leagueId, seasonId } = req.body;
const user = await getUserByToken(token);
const updateData = {};
if (name !== undefined) updateData.name = name;
if (leagueId !== undefined) updateData.leagueId = leagueId ? parseInt(leagueId) : null;
if (seasonId !== undefined) updateData.seasonId = seasonId ? parseInt(seasonId) : null;
const success = await TeamService.updateTeam(teamId, updateData);
if (!success) {
return res.status(404).json({ error: "notfound" });
}
const updatedTeam = await TeamService.getTeamById(teamId);
res.status(200).json(updatedTeam);
} catch (error) {
console.error('[updateTeam] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const deleteTeam = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { teamid: teamId } = req.params;
const user = await getUserByToken(token);
const success = await TeamService.deleteTeam(teamId);
if (!success) {
return res.status(404).json({ error: "notfound" });
}
res.status(200).json({ message: "deleted" });
} catch (error) {
console.error('[deleteTeam] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const getLeagues = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubid: clubId } = req.params;
const { seasonid: seasonId } = req.query;
const user = await getUserByToken(token);
const leagues = await TeamService.getLeaguesByClub(clubId, seasonId);
res.status(200).json(leagues);
} catch (error) {
console.error('[getLeagues] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};

View File

@@ -0,0 +1,215 @@
import multer from 'multer';
import path from 'path';
import TeamDocumentService from '../services/teamDocumentService.js';
import PDFParserService from '../services/pdfParserService.js';
import { getUserByToken } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';
// Multer-Konfiguration für Datei-Uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/temp/');
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 10 * 1024 * 1024 // 10MB Limit
},
fileFilter: (req, file, cb) => {
// Erlaube nur PDF, DOC, DOCX, TXT, CSV Dateien
const allowedTypes = /pdf|doc|docx|txt|csv/;
const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = allowedTypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb(new Error('Nur PDF, DOC, DOCX, TXT und CSV Dateien sind erlaubt!'));
}
}
});
export const uploadMiddleware = upload.single('document');
export const uploadDocument = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubteamid: clubTeamId } = req.params;
const { documentType } = req.body;
const user = await getUserByToken(token);
if (!req.file) {
return res.status(400).json({ error: "nofile" });
}
if (!documentType || !['code_list', 'pin_list'].includes(documentType)) {
return res.status(400).json({ error: "invaliddocumenttype" });
}
const document = await TeamDocumentService.uploadDocument(req.file, clubTeamId, documentType);
res.status(201).json(document);
} catch (error) {
console.error('[uploadDocument] - Error:', error);
// Lösche temporäre Datei bei Fehler
if (req.file && req.file.path) {
try {
const fs = await import('fs');
fs.unlinkSync(req.file.path);
} catch (cleanupError) {
console.error('Fehler beim Löschen der temporären Datei:', cleanupError);
}
}
if (error.message === 'Club-Team nicht gefunden') {
return res.status(404).json({ error: "clubteamnotfound" });
}
res.status(500).json({ error: "internalerror" });
}
};
export const getDocuments = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { clubteamid: clubTeamId } = req.params;
const user = await getUserByToken(token);
const documents = await TeamDocumentService.getDocumentsByClubTeam(clubTeamId);
res.status(200).json(documents);
} catch (error) {
console.error('[getDocuments] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const getDocument = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { documentid: documentId } = req.params;
const user = await getUserByToken(token);
const document = await TeamDocumentService.getDocumentById(documentId);
if (!document) {
return res.status(404).json({ error: "notfound" });
}
res.status(200).json(document);
} catch (error) {
console.error('[getDocument] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const downloadDocument = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { documentid: documentId } = req.params;
const user = await getUserByToken(token);
const document = await TeamDocumentService.getDocumentById(documentId);
if (!document) {
return res.status(404).json({ error: "notfound" });
}
const filePath = await TeamDocumentService.getDocumentPath(documentId);
if (!filePath) {
return res.status(404).json({ error: "filenotfound" });
}
// Prüfe ob Datei existiert
const fs = await import('fs');
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: "filenotfound" });
}
// Setze Headers für Inline-Anzeige (PDF-Viewer)
res.setHeader('Content-Disposition', `inline; filename="${document.originalFileName}"`);
res.setHeader('Content-Type', document.mimeType);
// Sende die Datei
res.sendFile(filePath);
} catch (error) {
console.error('[downloadDocument] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const deleteDocument = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { documentid: documentId } = req.params;
const user = await getUserByToken(token);
const success = await TeamDocumentService.deleteDocument(documentId);
if (!success) {
return res.status(404).json({ error: "notfound" });
}
res.status(200).json({ message: "Document deleted successfully" });
} catch (error) {
console.error('[deleteDocument] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};
export const parsePDF = async (req, res) => {
try {
const { authcode: token } = req.headers;
const { documentid: documentId } = req.params;
const { leagueid: leagueId } = req.query;
const user = await getUserByToken(token);
if (!leagueId) {
return res.status(400).json({ error: "missingleagueid" });
}
// Hole Dokument-Informationen
const document = await TeamDocumentService.getDocumentById(documentId);
if (!document) {
return res.status(404).json({ error: "documentnotfound" });
}
// Prüfe ob es eine PDF- oder TXT-Datei ist
if (!document.mimeType.includes('pdf') && !document.mimeType.includes('text/plain')) {
return res.status(400).json({ error: "notapdfortxt" });
}
// Parse PDF
const parseResult = await PDFParserService.parsePDF(document.filePath, document.clubTeam.clubId);
// Speichere Matches in Datenbank
const saveResult = await PDFParserService.saveMatchesToDatabase(parseResult.matches, parseInt(leagueId));
res.status(200).json({
parseResult: {
matchesFound: parseResult.matches.length,
debugInfo: parseResult.debugInfo,
allLines: parseResult.allLines,
rawText: parseResult.rawText
},
saveResult: {
created: saveResult.created,
updated: saveResult.updated,
errors: saveResult.errors
}
});
} catch (error) {
console.error('[parsePDF] - Error:', error);
res.status(500).json({ error: "internalerror" });
}
};

View File

@@ -19,6 +19,25 @@ class TrainingStatsController {
}
});
// Anzahl der Trainings im jeweiligen Zeitraum berechnen
const trainingsCount12Months = await DiaryDate.count({
where: {
clubId: parseInt(clubId),
date: {
[Op.gte]: twelveMonthsAgo
}
}
});
const trainingsCount3Months = await DiaryDate.count({
where: {
clubId: parseInt(clubId),
date: {
[Op.gte]: threeMonthsAgo
}
}
});
const stats = [];
for (const member of members) {
@@ -116,7 +135,36 @@ class TrainingStatsController {
// Nach Gesamtteilnahme absteigend sortieren
stats.sort((a, b) => b.participationTotal - a.participationTotal);
res.json(stats);
// Trainingstage mit Teilnehmerzahlen abrufen (letzte 12 Monate, absteigend sortiert)
const trainingDays = await DiaryDate.findAll({
where: {
clubId: parseInt(clubId),
date: {
[Op.gte]: twelveMonthsAgo
}
},
include: [{
model: Participant,
as: 'participantList',
attributes: ['id']
}],
order: [['date', 'DESC']]
});
// Formatiere Trainingstage mit Teilnehmerzahl
const formattedTrainingDays = trainingDays.map(day => ({
id: day.id,
date: day.date,
participantCount: day.participantList ? day.participantList.length : 0
}));
// Zusätzliche Metadaten mit Trainingsanzahl zurückgeben
res.json({
members: stats,
trainingsCount12Months,
trainingsCount3Months,
trainingDays: formattedTrainingDays
});
} catch (error) {
console.error('Fehler beim Laden der Trainings-Statistik:', error);

View File

@@ -0,0 +1,13 @@
-- Migration: Add auto update ratings fields to my_tischtennis table
-- Date: 2025-01-27
-- Add auto_update_ratings column
ALTER TABLE my_tischtennis
ADD COLUMN auto_update_ratings BOOLEAN NOT NULL DEFAULT FALSE;
-- Add last_update_ratings column
ALTER TABLE my_tischtennis
ADD COLUMN last_update_ratings TIMESTAMP NULL;
-- Create index for auto_update_ratings for efficient querying
CREATE INDEX idx_my_tischtennis_auto_update_ratings ON my_tischtennis(auto_update_ratings);

View File

@@ -0,0 +1,28 @@
-- Migration: Add match result fields to match table
-- Date: 2025-01-27
-- For MariaDB
-- Add myTischtennis meeting ID
ALTER TABLE `match`
ADD COLUMN my_tischtennis_meeting_id VARCHAR(255) NULL UNIQUE COMMENT 'Meeting ID from myTischtennis (e.g. 15440488)';
-- Add home match points
ALTER TABLE `match`
ADD COLUMN home_match_points INT DEFAULT 0 NULL COMMENT 'Match points won by home team';
-- Add guest match points
ALTER TABLE `match`
ADD COLUMN guest_match_points INT DEFAULT 0 NULL COMMENT 'Match points won by guest team';
-- Add is_completed flag
ALTER TABLE `match`
ADD COLUMN is_completed BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'Whether the match is completed';
-- Add PDF URL
ALTER TABLE `match`
ADD COLUMN pdf_url VARCHAR(512) NULL COMMENT 'PDF URL from myTischtennis';
-- Create indexes
CREATE INDEX idx_match_my_tischtennis_meeting_id ON `match`(my_tischtennis_meeting_id);
CREATE INDEX idx_match_is_completed ON `match`(is_completed);

View File

@@ -0,0 +1,4 @@
-- Add matches_tied column to team table
ALTER TABLE team
ADD COLUMN matches_tied INTEGER NOT NULL DEFAULT 0 AFTER matches_lost;

View File

@@ -0,0 +1,19 @@
-- Migration: Add myTischtennis fields to league table
-- Date: 2025-01-27
-- For MariaDB
-- Add my_tischtennis_group_id column
ALTER TABLE league
ADD COLUMN my_tischtennis_group_id VARCHAR(255) NULL COMMENT 'Group ID from myTischtennis (e.g. 504417)';
-- Add association column
ALTER TABLE league
ADD COLUMN association VARCHAR(255) NULL COMMENT 'Association/Verband (e.g. HeTTV)';
-- Add groupname column
ALTER TABLE league
ADD COLUMN groupname VARCHAR(255) NULL COMMENT 'Group name for URL (e.g. 1.Kreisklasse)';
-- Create index for efficient querying
CREATE INDEX idx_league_my_tischtennis_group_id ON league(my_tischtennis_group_id);

View File

@@ -0,0 +1,11 @@
-- Migration: Add myTischtennis player ID to member table
-- Date: 2025-01-27
-- For MariaDB
-- Add my_tischtennis_player_id column
ALTER TABLE member
ADD COLUMN my_tischtennis_player_id VARCHAR(255) NULL COMMENT 'Player ID from myTischtennis (e.g. NU2705037)';
-- Create index for efficient querying
CREATE INDEX idx_member_my_tischtennis_player_id ON member(my_tischtennis_player_id);

View File

@@ -0,0 +1,11 @@
-- Migration: Add myTischtennis team ID to club_team table
-- Date: 2025-01-27
-- For MariaDB
-- Add my_tischtennis_team_id column
ALTER TABLE club_team
ADD COLUMN my_tischtennis_team_id VARCHAR(255) NULL COMMENT 'Team ID from myTischtennis (e.g. 2995094)';
-- Create index for efficient querying
CREATE INDEX idx_club_team_my_tischtennis_team_id ON club_team(my_tischtennis_team_id);

View File

@@ -0,0 +1,44 @@
-- Migration: Add season_id to teams table
-- First, add the column as nullable
ALTER TABLE `team` ADD COLUMN `season_id` INT NULL;
-- Get or create current season
SET @current_season_id = (
SELECT id FROM `season`
WHERE season = (
CASE
WHEN MONTH(CURDATE()) >= 7 THEN CONCAT(YEAR(CURDATE()), '/', YEAR(CURDATE()) + 1)
ELSE CONCAT(YEAR(CURDATE()) - 1, '/', YEAR(CURDATE()))
END
)
LIMIT 1
);
-- If no season exists, create it
INSERT IGNORE INTO `season` (season) VALUES (
CASE
WHEN MONTH(CURDATE()) >= 7 THEN CONCAT(YEAR(CURDATE()), '/', YEAR(CURDATE()) + 1)
ELSE CONCAT(YEAR(CURDATE()) - 1, '/', YEAR(CURDATE()))
END
);
-- Get the season ID again (in case we just created it)
SET @current_season_id = (
SELECT id FROM `season`
WHERE season = (
CASE
WHEN MONTH(CURDATE()) >= 7 THEN CONCAT(YEAR(CURDATE()), '/', YEAR(CURDATE()) + 1)
ELSE CONCAT(YEAR(CURDATE()) - 1, '/', YEAR(CURDATE()))
END
)
LIMIT 1
);
-- Update all existing teams to use the current season
UPDATE `team` SET `season_id` = @current_season_id WHERE `season_id` IS NULL;
-- Now make the column NOT NULL and add the foreign key constraint
ALTER TABLE `team` MODIFY COLUMN `season_id` INT NOT NULL;
ALTER TABLE `team` ADD CONSTRAINT `team_season_id_foreign_idx`
FOREIGN KEY (`season_id`) REFERENCES `season` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,11 @@
-- Migration: Add table fields to team table
-- Add fields for league table calculations
ALTER TABLE team ADD COLUMN matches_played INT NOT NULL DEFAULT 0;
ALTER TABLE team ADD COLUMN matches_won INT NOT NULL DEFAULT 0;
ALTER TABLE team ADD COLUMN matches_lost INT NOT NULL DEFAULT 0;
ALTER TABLE team ADD COLUMN sets_won INT NOT NULL DEFAULT 0;
ALTER TABLE team ADD COLUMN sets_lost INT NOT NULL DEFAULT 0;
ALTER TABLE team ADD COLUMN points_won INT NOT NULL DEFAULT 0;
ALTER TABLE team ADD COLUMN points_lost INT NOT NULL DEFAULT 0;
ALTER TABLE team ADD COLUMN table_points INT NOT NULL DEFAULT 0;

View File

@@ -0,0 +1,5 @@
-- Add table_points_won and table_points_lost columns to team table
ALTER TABLE team
ADD COLUMN table_points_won INTEGER NOT NULL DEFAULT 0 AFTER table_points,
ADD COLUMN table_points_lost INTEGER NOT NULL DEFAULT 0 AFTER table_points_won;

View File

@@ -0,0 +1,20 @@
-- Create my_tischtennis_fetch_log table for tracking data fetches
CREATE TABLE IF NOT EXISTS my_tischtennis_fetch_log (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
fetch_type ENUM('ratings', 'match_results', 'league_table') NOT NULL COMMENT 'Type of data fetch',
success BOOLEAN NOT NULL DEFAULT FALSE,
message TEXT,
error_details TEXT,
records_processed INT NOT NULL DEFAULT 0 COMMENT 'Number of records processed',
execution_time INT COMMENT 'Execution time in milliseconds',
is_automatic BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'Automatic or manual fetch',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE ON UPDATE CASCADE,
INDEX idx_user_fetch_type_created (user_id, fetch_type, created_at),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@@ -0,0 +1,23 @@
-- Migration: Create my_tischtennis_update_history table
-- Date: 2025-01-27
-- For MariaDB
CREATE TABLE IF NOT EXISTS my_tischtennis_update_history (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
success BOOLEAN NOT NULL DEFAULT FALSE,
message TEXT,
error_details TEXT,
updated_count INT DEFAULT 0,
execution_time INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT fk_my_tischtennis_update_history_user_id
FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Create indexes for efficient querying
CREATE INDEX idx_my_tischtennis_update_history_user_id ON my_tischtennis_update_history(user_id);
CREATE INDEX idx_my_tischtennis_update_history_created_at ON my_tischtennis_update_history(created_at);
CREATE INDEX idx_my_tischtennis_update_history_success ON my_tischtennis_update_history(success);

View File

@@ -0,0 +1,8 @@
-- Migration: Make locationId optional in match table
-- Date: 2025-01-27
-- For MariaDB
-- Modify locationId to allow NULL
ALTER TABLE `match`
MODIFY COLUMN location_id INT NULL;

View File

@@ -0,0 +1,60 @@
import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import Club from './Club.js';
import League from './League.js';
import Season from './Season.js';
const ClubTeam = sequelize.define('ClubTeam', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
clubId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: Club,
key: 'id',
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
leagueId: {
type: DataTypes.INTEGER,
allowNull: true,
references: {
model: League,
key: 'id',
},
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
},
seasonId: {
type: DataTypes.INTEGER,
allowNull: true,
references: {
model: Season,
key: 'id',
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
myTischtennisTeamId: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Team ID from myTischtennis (e.g. 2995094)',
field: 'my_tischtennis_team_id'
},
}, {
underscored: true,
tableName: 'club_team',
timestamps: true,
});
export default ClubTeam;

View File

@@ -34,6 +34,22 @@ const League = sequelize.define('League', {
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
myTischtennisGroupId: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Group ID from myTischtennis (e.g. 504417)',
field: 'my_tischtennis_group_id'
},
association: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Association/Verband (e.g. HeTTV)',
},
groupname: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Group name for URL (e.g. 1.Kreisklasse)',
},
}, {
underscored: true,
tableName: 'league',

View File

@@ -3,7 +3,6 @@ import sequelize from '../database.js';
import Club from './Club.js';
import League from './League.js';
import Team from './Team.js';
import Season from './Season.js';
import Location from './Location.js';
const Match = sequelize.define('Match', {
@@ -21,21 +20,13 @@ const Match = sequelize.define('Match', {
type: DataTypes.TIME,
allowNull: true,
},
seasonId: {
type: DataTypes.INTEGER,
references: {
model: Season,
key: 'id',
},
allowNull: false,
},
locationId: {
type: DataTypes.INTEGER,
references: {
model: Location,
key: 'id',
},
allowNull: false,
allowNull: true,
},
homeTeamId: {
type: DataTypes.INTEGER,
@@ -69,6 +60,55 @@ const Match = sequelize.define('Match', {
},
allowNull: false,
},
code: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Spiel-Code aus PDF-Parsing'
},
homePin: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Pin-Code für Heimteam aus PDF-Parsing'
},
guestPin: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Pin-Code für Gastteam aus PDF-Parsing'
},
myTischtennisMeetingId: {
type: DataTypes.STRING,
allowNull: true,
unique: true,
comment: 'Meeting ID from myTischtennis (e.g. 15440488)',
field: 'my_tischtennis_meeting_id'
},
homeMatchPoints: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0,
comment: 'Match points won by home team',
field: 'home_match_points'
},
guestMatchPoints: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0,
comment: 'Match points won by guest team',
field: 'guest_match_points'
},
isCompleted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
comment: 'Whether the match is completed',
field: 'is_completed'
},
pdfUrl: {
type: DataTypes.STRING,
allowNull: true,
comment: 'PDF URL from myTischtennis',
field: 'pdf_url'
},
}, {
underscored: true,
tableName: 'match',

View File

@@ -45,9 +45,9 @@ const Member = sequelize.define('Member', {
},
birthDate: {
type: DataTypes.STRING,
allowNull: false,
allowNull: true,
set(value) {
const encryptedValue = encryptData(value);
const encryptedValue = encryptData(value || '');
this.setDataValue('birthDate', encryptedValue);
},
get() {
@@ -137,6 +137,12 @@ const Member = sequelize.define('Member', {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: null
},
myTischtennisPlayerId: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Player ID from myTischtennis (e.g. NU2705037)',
field: 'my_tischtennis_player_id'
}
}, {
underscored: true,

View File

@@ -34,6 +34,12 @@ const MyTischtennis = sequelize.define('MyTischtennis', {
allowNull: false,
field: 'save_password'
},
autoUpdateRatings: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
field: 'auto_update_ratings'
},
accessToken: {
type: DataTypes.TEXT,
allowNull: true,
@@ -82,6 +88,11 @@ const MyTischtennis = sequelize.define('MyTischtennis', {
type: DataTypes.DATE,
allowNull: true,
field: 'last_login_success'
},
lastUpdateRatings: {
type: DataTypes.DATE,
allowNull: true,
field: 'last_update_ratings'
}
}, {
underscored: true,

View File

@@ -0,0 +1,72 @@
import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import User from './User.js';
const MyTischtennisFetchLog = sequelize.define('MyTischtennisFetchLog', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
userId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: User,
key: 'id',
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
fetchType: {
type: DataTypes.ENUM('ratings', 'match_results', 'league_table'),
allowNull: false,
comment: 'Type of data fetch: ratings, match_results, or league_table'
},
success: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
message: {
type: DataTypes.TEXT,
allowNull: true,
},
errorDetails: {
type: DataTypes.TEXT,
allowNull: true,
},
recordsProcessed: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
comment: 'Number of records processed (e.g., players updated, matches fetched)'
},
executionTime: {
type: DataTypes.INTEGER,
allowNull: true,
comment: 'Execution time in milliseconds'
},
isAutomatic: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
comment: 'Whether this was an automatic or manual fetch'
},
}, {
underscored: true,
tableName: 'my_tischtennis_fetch_log',
timestamps: true,
indexes: [
{
fields: ['user_id', 'fetch_type', 'created_at']
},
{
fields: ['created_at']
}
]
});
export default MyTischtennisFetchLog;

View File

@@ -0,0 +1,63 @@
import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
const MyTischtennisUpdateHistory = sequelize.define('MyTischtennisUpdateHistory', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
userId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'user',
key: 'id'
},
onDelete: 'CASCADE'
},
success: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
message: {
type: DataTypes.TEXT,
allowNull: true
},
errorDetails: {
type: DataTypes.TEXT,
allowNull: true,
field: 'error_details'
},
updatedCount: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0,
field: 'updated_count'
},
executionTime: {
type: DataTypes.INTEGER,
allowNull: true,
comment: 'Execution time in milliseconds',
field: 'execution_time'
}
}, {
underscored: true,
tableName: 'my_tischtennis_update_history',
timestamps: true,
indexes: [
{
fields: ['user_id']
},
{
fields: ['created_at']
},
{
fields: ['success']
}
]
});
export default MyTischtennisUpdateHistory;

View File

@@ -1,6 +1,8 @@
import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import Club from './Club.js';
import League from './League.js';
import Season from './Season.js';
const Team = sequelize.define('Team', {
id: {
@@ -23,6 +25,82 @@ const Team = sequelize.define('Team', {
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
leagueId: {
type: DataTypes.INTEGER,
allowNull: true,
references: {
model: League,
key: 'id',
},
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
},
seasonId: {
type: DataTypes.INTEGER,
allowNull: true,
references: {
model: Season,
key: 'id',
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
// Tabellenfelder
matchesPlayed: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
matchesWon: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
matchesLost: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
matchesTied: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
setsWon: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
setsLost: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
pointsWon: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
pointsLost: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
tablePoints: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
tablePointsWon: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
tablePointsLost: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
}, {
underscored: true,
tableName: 'team',

View File

@@ -0,0 +1,52 @@
import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import ClubTeam from './ClubTeam.js';
const TeamDocument = sequelize.define('TeamDocument', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
fileName: {
type: DataTypes.STRING,
allowNull: false,
},
originalFileName: {
type: DataTypes.STRING,
allowNull: false,
},
filePath: {
type: DataTypes.STRING,
allowNull: false,
},
fileSize: {
type: DataTypes.INTEGER,
allowNull: false,
},
mimeType: {
type: DataTypes.STRING,
allowNull: false,
},
documentType: {
type: DataTypes.ENUM('code_list', 'pin_list'),
allowNull: false,
},
clubTeamId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: ClubTeam,
key: 'id',
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
}, {
underscored: true,
tableName: 'team_document',
timestamps: true,
});
export default TeamDocument;

View File

@@ -19,6 +19,8 @@ import DiaryDateActivity from './DiaryDateActivity.js';
import Match from './Match.js';
import League from './League.js';
import Team from './Team.js';
import ClubTeam from './ClubTeam.js';
import TeamDocument from './TeamDocument.js';
import Season from './Season.js';
import Location from './Location.js';
import Group from './Group.js';
@@ -34,6 +36,8 @@ import OfficialTournament from './OfficialTournament.js';
import OfficialCompetition from './OfficialCompetition.js';
import OfficialCompetitionMember from './OfficialCompetitionMember.js';
import MyTischtennis from './MyTischtennis.js';
import MyTischtennisUpdateHistory from './MyTischtennisUpdateHistory.js';
import MyTischtennisFetchLog from './MyTischtennisFetchLog.js';
// Official tournaments relations
OfficialTournament.hasMany(OfficialCompetition, { foreignKey: 'tournamentId', as: 'competitions' });
OfficialCompetition.belongsTo(OfficialTournament, { foreignKey: 'tournamentId', as: 'tournament' });
@@ -118,8 +122,28 @@ Team.belongsTo(Club, { foreignKey: 'clubId', as: 'club' });
Club.hasMany(League, { foreignKey: 'clubId', as: 'leagues' });
League.belongsTo(Club, { foreignKey: 'clubId', as: 'club' });
Match.belongsTo(Season, { foreignKey: 'seasonId', as: 'season' });
Season.hasMany(Match, { foreignKey: 'seasonId', as: 'matches' });
Season.hasMany(League, { foreignKey: 'seasonId', as: 'leagues' });
League.belongsTo(Season, { foreignKey: 'seasonId', as: 'season' });
League.hasMany(Team, { foreignKey: 'leagueId', as: 'teams' });
Team.belongsTo(League, { foreignKey: 'leagueId', as: 'league' });
Season.hasMany(Team, { foreignKey: 'seasonId', as: 'teams' });
Team.belongsTo(Season, { foreignKey: 'seasonId', as: 'season' });
// ClubTeam relationships
Club.hasMany(ClubTeam, { foreignKey: 'clubId', as: 'clubTeams' });
ClubTeam.belongsTo(Club, { foreignKey: 'clubId', as: 'club' });
League.hasMany(ClubTeam, { foreignKey: 'leagueId', as: 'clubTeams' });
ClubTeam.belongsTo(League, { foreignKey: 'leagueId', as: 'league' });
Season.hasMany(ClubTeam, { foreignKey: 'seasonId', as: 'clubTeams' });
ClubTeam.belongsTo(Season, { foreignKey: 'seasonId', as: 'season' });
// TeamDocument relationships
ClubTeam.hasMany(TeamDocument, { foreignKey: 'clubTeamId', as: 'documents' });
TeamDocument.belongsTo(ClubTeam, { foreignKey: 'clubTeamId', as: 'clubTeam' });
Match.belongsTo(Location, { foreignKey: 'locationId', as: 'location' });
Location.hasMany(Match, { foreignKey: 'locationId', as: 'matches' });
@@ -208,6 +232,12 @@ DiaryDate.hasMany(Accident, { foreignKey: 'diaryDateId', as: 'accidents' });
User.hasOne(MyTischtennis, { foreignKey: 'userId', as: 'myTischtennis' });
MyTischtennis.belongsTo(User, { foreignKey: 'userId', as: 'user' });
User.hasMany(MyTischtennisUpdateHistory, { foreignKey: 'userId', as: 'updateHistory' });
MyTischtennisUpdateHistory.belongsTo(User, { foreignKey: 'userId', as: 'user' });
User.hasMany(MyTischtennisFetchLog, { foreignKey: 'userId', as: 'fetchLogs' });
MyTischtennisFetchLog.belongsTo(User, { foreignKey: 'userId', as: 'user' });
export {
User,
Log,
@@ -231,6 +261,8 @@ export {
Match,
League,
Team,
ClubTeam,
TeamDocument,
Group,
GroupActivity,
Tournament,
@@ -244,4 +276,6 @@ export {
OfficialCompetition,
OfficialCompetitionMember,
MyTischtennis,
MyTischtennisUpdateHistory,
MyTischtennisFetchLog,
};

View File

@@ -2816,6 +2816,15 @@
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz",
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA=="
},
"node_modules/node-cron": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-4.2.1.tgz",
"integrity": "sha512-lgimEHPE/QDgFlywTd8yTR61ptugX3Qer29efeyWw2rv259HtGBNn1vZVmp8lB9uo9wC0t/AT4iGqXxia+CJFg==",
"license": "ISC",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/node-ensure": {
"version": "0.0.0",
"resolved": "https://registry.npmjs.org/node-ensure/-/node-ensure-0.0.0.tgz",
@@ -2842,9 +2851,10 @@
}
},
"node_modules/nodemailer": {
"version": "6.9.14",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.14.tgz",
"integrity": "sha512-Dobp/ebDKBvz91sbtRKhcznLThrKxKt97GI2FAlAyy+fk19j73Uz3sBXolVtmcXjaorivqsbbbjDY+Jkt4/bQA==",
"version": "7.0.9",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.9.tgz",
"integrity": "sha512-9/Qm0qXIByEP8lEV2qOqcAW7bRpL8CR9jcTwk3NBnHJNmP9fIJ86g2fgmIXqHY+nj55ZEMwWqYAT2QTDpRUYiQ==",
"license": "MIT-0",
"engines": {
"node": ">=6.0.0"
}

View File

@@ -1,10 +1,9 @@
'use strict';
module.exports = {
upgrade: true,
reject: [
// API changes break existing tests
'proxy',
// API changes
'eslint'
'proxy'
]
};

View File

@@ -1,3 +1,5 @@
'use strict';
module.exports = {
printWidth: 160,
tabWidth: 4,

File diff suppressed because it is too large Load Diff

View File

@@ -14,22 +14,22 @@ appearance, race, religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities

View File

@@ -37,36 +37,36 @@ It's either a firewall issue, or your SMTP server blocks authentication attempts
#### I get TLS errors
- If you are running the code on your machine, check your antivirus settings. Antiviruses often mess around with email ports usage. Node.js might not recognize the MITM cert your antivirus is using.
- Latest Node versions allow only TLS versions 1.2 and higher. Some servers might still use TLS 1.1 or lower. Check Node.js docs on how to get correct TLS support for your app. You can change this with [tls.minVersion](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tls_tls_createsecurecontext_options) option
- You might have the wrong value for the `secure` option. This should be set to `true` only for port 465. For every other port, it should be `false`. Setting it to `false` does not mean that Nodemailer would not use TLS. Nodemailer would still try to upgrade the connection to use TLS if the server supports it.
- Older Node versions do not fully support the certificate chain of the newest Let's Encrypt certificates. Either set [tls.rejectUnauthorized](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tlsconnectoptions-callback) to `false` to skip chain verification or upgrade your Node version
- If you are running the code on your machine, check your antivirus settings. Antiviruses often mess around with email ports usage. Node.js might not recognize the MITM cert your antivirus is using.
- Latest Node versions allow only TLS versions 1.2 and higher. Some servers might still use TLS 1.1 or lower. Check Node.js docs on how to get correct TLS support for your app. You can change this with [tls.minVersion](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tls_tls_createsecurecontext_options) option
- You might have the wrong value for the `secure` option. This should be set to `true` only for port 465. For every other port, it should be `false`. Setting it to `false` does not mean that Nodemailer would not use TLS. Nodemailer would still try to upgrade the connection to use TLS if the server supports it.
- Older Node versions do not fully support the certificate chain of the newest Let's Encrypt certificates. Either set [tls.rejectUnauthorized](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tlsconnectoptions-callback) to `false` to skip chain verification or upgrade your Node version
```
```js
let configOptions = {
host: "smtp.example.com",
host: 'smtp.example.com',
port: 587,
tls: {
rejectUnauthorized: true,
minVersion: "TLSv1.2"
minVersion: 'TLSv1.2'
}
}
};
```
#### I have issues with DNS / hosts file
Node.js uses [c-ares](https://nodejs.org/en/docs/meta/topics/dependencies/#c-ares) to resolve domain names, not the DNS library provided by the system, so if you have some custom DNS routing set up, it might be ignored. Nodemailer runs [dns.resolve4()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnsresolve4hostname-options-callback) and [dns.resolve6()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnsresolve6hostname-options-callback) to resolve hostname into an IP address. If both calls fail, then Nodemailer will fall back to [dns.lookup()](https://nodejs.org/dist/latest-v16.x/docs/api/dns.html#dnslookuphostname-options-callback). If this does not work for you, you can hard code the IP address into the configuration like shown below. In that case, Nodemailer would not perform any DNS lookups.
```
```js
let configOptions = {
host: "1.2.3.4",
host: '1.2.3.4',
port: 465,
secure: true,
tls: {
// must provide server name, otherwise TLS certificate check will fail
servername: "example.com"
servername: 'example.com'
}
}
};
```
#### I have an issue with TypeScript types

View File

@@ -7,7 +7,6 @@
* @return {Object} Address object
*/
function _handleAddress(tokens) {
let token;
let isGroup = false;
let state = 'text';
let address;
@@ -16,28 +15,41 @@ function _handleAddress(tokens) {
address: [],
comment: [],
group: [],
text: []
text: [],
textWasQuoted: [] // Track which text tokens came from inside quotes
};
let i;
let len;
let insideQuotes = false; // Track if we're currently inside a quoted string
// Filter out <addresses>, (comments) and regular text
for (i = 0, len = tokens.length; i < len; i++) {
token = tokens[i];
let token = tokens[i];
let prevToken = i ? tokens[i - 1] : null;
if (token.type === 'operator') {
switch (token.value) {
case '<':
state = 'address';
insideQuotes = false;
break;
case '(':
state = 'comment';
insideQuotes = false;
break;
case ':':
state = 'group';
isGroup = true;
insideQuotes = false;
break;
case '"':
// Track quote state for text tokens
insideQuotes = !insideQuotes;
state = 'text';
break;
default:
state = 'text';
insideQuotes = false;
break;
}
} else if (token.value) {
if (state === 'address') {
@@ -46,7 +58,19 @@ function _handleAddress(tokens) {
// and so will we
token.value = token.value.replace(/^[^<]*<\s*/, '');
}
data[state].push(token.value);
if (prevToken && prevToken.noBreak && data[state].length) {
// join values
data[state][data[state].length - 1] += token.value;
if (state === 'text' && insideQuotes) {
data.textWasQuoted[data.textWasQuoted.length - 1] = true;
}
} else {
data[state].push(token.value);
if (state === 'text') {
data.textWasQuoted.push(insideQuotes);
}
}
}
}
@@ -59,16 +83,36 @@ function _handleAddress(tokens) {
if (isGroup) {
// http://tools.ietf.org/html/rfc2822#appendix-A.1.3
data.text = data.text.join(' ');
// Parse group members, but flatten any nested groups (RFC 5322 doesn't allow nesting)
let groupMembers = [];
if (data.group.length) {
let parsedGroup = addressparser(data.group.join(','));
// Flatten: if any member is itself a group, extract its members into the sequence
parsedGroup.forEach(member => {
if (member.group) {
// Nested group detected - flatten it by adding its members directly
groupMembers = groupMembers.concat(member.group);
} else {
groupMembers.push(member);
}
});
}
addresses.push({
name: data.text || (address && address.name),
group: data.group.length ? addressparser(data.group.join(',')) : []
group: groupMembers
});
} else {
// If no address was found, try to detect one from regular text
if (!data.address.length && data.text.length) {
for (i = data.text.length - 1; i >= 0; i--) {
if (data.text[i].match(/^[^@\s]+@[^@\s]+$/)) {
// Security fix: Do not extract email addresses from quoted strings
// RFC 5321 allows @ inside quoted local-parts like "user@domain"@example.com
// Extracting emails from quoted text leads to misrouting vulnerabilities
if (!data.textWasQuoted[i] && data.text[i].match(/^[^@\s]+@[^@\s]+$/)) {
data.address = data.text.splice(i, 1);
data.textWasQuoted.splice(i, 1);
break;
}
}
@@ -85,10 +129,13 @@ function _handleAddress(tokens) {
// still no address
if (!data.address.length) {
for (i = data.text.length - 1; i >= 0; i--) {
// fixed the regex to parse email address correctly when email address has more than one @
data.text[i] = data.text[i].replace(/\s*\b[^@\s]+@[^\s]+\b\s*/, _regexHandler).trim();
if (data.address.length) {
break;
// Security fix: Do not extract email addresses from quoted strings
if (!data.textWasQuoted[i]) {
// fixed the regex to parse email address correctly when email address has more than one @
data.text[i] = data.text[i].replace(/\s*\b[^@\s]+@[^\s]+\b\s*/, _regexHandler).trim();
if (data.address.length) {
break;
}
}
}
}
@@ -172,11 +219,12 @@ class Tokenizer {
* @return {Array} An array of operator|text tokens
*/
tokenize() {
let chr,
list = [];
let list = [];
for (let i = 0, len = this.str.length; i < len; i++) {
chr = this.str.charAt(i);
this.checkChar(chr);
let chr = this.str.charAt(i);
let nextChr = i < len - 1 ? this.str.charAt(i + 1) : null;
this.checkChar(chr, nextChr);
}
this.list.forEach(node => {
@@ -194,7 +242,7 @@ class Tokenizer {
*
* @param {String} chr Character from the address field
*/
checkChar(chr) {
checkChar(chr, nextChr) {
if (this.escaped) {
// ignore next condition blocks
} else if (chr === this.operatorExpecting) {
@@ -202,10 +250,16 @@ class Tokenizer {
type: 'operator',
value: chr
};
if (nextChr && ![' ', '\t', '\r', '\n', ',', ';'].includes(nextChr)) {
this.node.noBreak = true;
}
this.list.push(this.node);
this.node = null;
this.operatorExpecting = '';
this.escaped = false;
return;
} else if (!this.operatorExpecting && chr in this.operators) {
this.node = {

View File

@@ -35,15 +35,12 @@ function wrap(str, lineLength) {
let pos = 0;
let chunkLength = lineLength * 1024;
while (pos < str.length) {
let wrappedLines = str
.substr(pos, chunkLength)
.replace(new RegExp('.{' + lineLength + '}', 'g'), '$&\r\n')
.trim();
let wrappedLines = str.substr(pos, chunkLength).replace(new RegExp('.{' + lineLength + '}', 'g'), '$&\r\n');
result.push(wrappedLines);
pos += chunkLength;
}
return result.join('\r\n').trim();
return result.join('');
}
/**
@@ -56,7 +53,6 @@ function wrap(str, lineLength) {
class Encoder extends Transform {
constructor(options) {
super();
// init Transform
this.options = options || {};
if (this.options.lineLength !== false) {
@@ -98,17 +94,20 @@ class Encoder extends Transform {
if (this.options.lineLength) {
b64 = wrap(b64, this.options.lineLength);
// remove last line as it is still most probably incomplete
let lastLF = b64.lastIndexOf('\n');
if (lastLF < 0) {
this._curLine = b64;
b64 = '';
} else if (lastLF === b64.length - 1) {
this._curLine = '';
} else {
this._curLine = b64.substr(lastLF + 1);
b64 = b64.substr(0, lastLF + 1);
this._curLine = b64.substring(lastLF + 1);
b64 = b64.substring(0, lastLF + 1);
if (b64 && !b64.endsWith('\r\n')) {
b64 += '\r\n';
}
}
} else {
this._curLine = '';
}
if (b64) {
@@ -125,16 +124,14 @@ class Encoder extends Transform {
}
if (this._curLine) {
this._curLine = wrap(this._curLine, this.options.lineLength);
this.outputBytes += this._curLine.length;
this.push(this._curLine, 'ascii');
this.push(Buffer.from(this._curLine, 'ascii'));
this._curLine = '';
}
done();
}
}
// expose to the world
module.exports = {
encode,
wrap,

View File

@@ -12,7 +12,7 @@ const path = require('path');
const crypto = require('crypto');
const DKIM_ALGO = 'sha256';
const MAX_MESSAGE_SIZE = 128 * 1024; // buffer messages larger than this to disk
const MAX_MESSAGE_SIZE = 2 * 1024 * 1024; // buffer messages larger than this to disk
/*
// Usage:
@@ -42,7 +42,9 @@ class DKIMSigner {
this.chunks = [];
this.chunklen = 0;
this.readPos = 0;
this.cachePath = this.cacheDir ? path.join(this.cacheDir, 'message.' + Date.now() + '-' + crypto.randomBytes(14).toString('hex')) : false;
this.cachePath = this.cacheDir
? path.join(this.cacheDir, 'message.' + Date.now() + '-' + crypto.randomBytes(14).toString('hex'))
: false;
this.cache = false;
this.headers = false;

View File

@@ -41,7 +41,7 @@ module.exports = (headers, hashAlgo, bodyHash, options) => {
signer.update(canonicalizedHeaderData.headers);
try {
signature = signer.sign(options.privateKey, 'base64');
} catch (E) {
} catch (_E) {
return false;
}

View File

@@ -132,7 +132,13 @@ function nmfetch(url, options) {
});
}
if (parsed.protocol === 'https:' && parsed.hostname && parsed.hostname !== reqOptions.host && !net.isIP(parsed.hostname) && !reqOptions.servername) {
if (
parsed.protocol === 'https:' &&
parsed.hostname &&
parsed.hostname !== reqOptions.host &&
!net.isIP(parsed.hostname) &&
!reqOptions.servername
) {
reqOptions.servername = parsed.hostname;
}

View File

@@ -86,20 +86,34 @@ class MailComposer {
let icalEvent, eventObject;
let attachments = [].concat(this.mail.attachments || []).map((attachment, i) => {
let data;
let isMessageNode = /^message\//i.test(attachment.contentType);
if (/^data:/i.test(attachment.path || attachment.href)) {
attachment = this._processDataUrl(attachment);
}
let contentType = attachment.contentType || mimeFuncs.detectMimeType(attachment.filename || attachment.path || attachment.href || 'bin');
let contentType =
attachment.contentType || mimeFuncs.detectMimeType(attachment.filename || attachment.path || attachment.href || 'bin');
let isImage = /^image\//i.test(contentType);
let contentDisposition = attachment.contentDisposition || (isMessageNode || (isImage && attachment.cid) ? 'inline' : 'attachment');
let isMessageNode = /^message\//i.test(contentType);
let contentDisposition =
attachment.contentDisposition || (isMessageNode || (isImage && attachment.cid) ? 'inline' : 'attachment');
let contentTransferEncoding;
if ('contentTransferEncoding' in attachment) {
// also contains `false`, to set
contentTransferEncoding = attachment.contentTransferEncoding;
} else if (isMessageNode) {
contentTransferEncoding = '7bit';
} else {
contentTransferEncoding = 'base64'; // the default
}
data = {
contentType,
contentDisposition,
contentTransferEncoding: 'contentTransferEncoding' in attachment ? attachment.contentTransferEncoding : 'base64'
contentTransferEncoding
};
if (attachment.filename) {
@@ -200,7 +214,10 @@ class MailComposer {
eventObject;
if (this.mail.text) {
if (typeof this.mail.text === 'object' && (this.mail.text.content || this.mail.text.path || this.mail.text.href || this.mail.text.raw)) {
if (
typeof this.mail.text === 'object' &&
(this.mail.text.content || this.mail.text.path || this.mail.text.href || this.mail.text.raw)
) {
text = this.mail.text;
} else {
text = {
@@ -225,7 +242,10 @@ class MailComposer {
}
if (this.mail.amp) {
if (typeof this.mail.amp === 'object' && (this.mail.amp.content || this.mail.amp.path || this.mail.amp.href || this.mail.amp.raw)) {
if (
typeof this.mail.amp === 'object' &&
(this.mail.amp.content || this.mail.amp.path || this.mail.amp.href || this.mail.amp.raw)
) {
amp = this.mail.amp;
} else {
amp = {
@@ -260,14 +280,18 @@ class MailComposer {
}
eventObject.filename = false;
eventObject.contentType = 'text/calendar; charset=utf-8; method=' + (eventObject.method || 'PUBLISH').toString().trim().toUpperCase();
eventObject.contentType =
'text/calendar; charset=utf-8; method=' + (eventObject.method || 'PUBLISH').toString().trim().toUpperCase();
if (!eventObject.headers) {
eventObject.headers = {};
}
}
if (this.mail.html) {
if (typeof this.mail.html === 'object' && (this.mail.html.content || this.mail.html.path || this.mail.html.href || this.mail.html.raw)) {
if (
typeof this.mail.html === 'object' &&
(this.mail.html.content || this.mail.html.path || this.mail.html.href || this.mail.html.raw)
) {
html = this.mail.html;
} else {
html = {
@@ -292,7 +316,9 @@ class MailComposer {
}
data = {
contentType: alternative.contentType || mimeFuncs.detectMimeType(alternative.filename || alternative.path || alternative.href || 'txt'),
contentType:
alternative.contentType ||
mimeFuncs.detectMimeType(alternative.filename || alternative.path || alternative.href || 'txt'),
contentTransferEncoding: alternative.contentTransferEncoding
};
@@ -538,9 +564,33 @@ class MailComposer {
* @return {Object} Parsed element
*/
_processDataUrl(element) {
const dataUrl = element.path || element.href;
// Early validation to prevent ReDoS
if (!dataUrl || typeof dataUrl !== 'string') {
return element;
}
if (!dataUrl.startsWith('data:')) {
return element;
}
if (dataUrl.length > 100000) {
// 100KB limit for data URL string
// Return empty content for excessively long data URLs
return Object.assign({}, element, {
path: false,
href: false,
content: Buffer.alloc(0),
contentType: element.contentType || 'application/octet-stream'
});
}
let parsedDataUri;
if ((element.path || element.href).match(/^data:/)) {
parsedDataUri = parseDataURI(element.path || element.href);
try {
parsedDataUri = parseDataURI(dataUrl);
} catch (_err) {
return element;
}
if (!parsedDataUri) {

View File

@@ -87,6 +87,11 @@ class Mail extends EventEmitter {
this.transporter.on('idle', (...args) => {
this.emit('idle', ...args);
});
// indicates if the sender has became idle and all connections are terminated
this.transporter.on('clear', (...args) => {
this.emit('clear', ...args);
});
}
/**
@@ -236,7 +241,14 @@ class Mail extends EventEmitter {
}
getVersionString() {
return util.format('%s (%s; +%s; %s/%s)', packageData.name, packageData.version, packageData.homepage, this.transporter.name, this.transporter.version);
return util.format(
'%s (%s; +%s; %s/%s)',
packageData.name,
packageData.version,
packageData.homepage,
this.transporter.name,
this.transporter.version
);
}
_processPlugins(step, mail, callback) {

View File

@@ -64,7 +64,8 @@ class MailMessage {
if (this.data.attachments && this.data.attachments.length) {
this.data.attachments.forEach((attachment, i) => {
if (!attachment.filename) {
attachment.filename = (attachment.path || attachment.href || '').split('/').pop().split('?').shift() || 'attachment-' + (i + 1);
attachment.filename =
(attachment.path || attachment.href || '').split('/').pop().split('?').shift() || 'attachment-' + (i + 1);
if (attachment.filename.indexOf('.') < 0) {
attachment.filename += '.' + mimeFuncs.detectExtension(attachment.contentType);
}

View File

@@ -269,7 +269,7 @@ module.exports = {
// first line includes the charset and language info and needs to be encoded
// even if it does not contain any unicode characters
line = 'utf-8\x27\x27';
line = "utf-8''";
let encoded = true;
startPos = 0;
@@ -614,7 +614,7 @@ module.exports = {
try {
// might throw if we try to encode invalid sequences, eg. partial emoji
str = encodeURIComponent(str);
} catch (E) {
} catch (_E) {
// should never run
return str.replace(/[^\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]+/g, '');
}

View File

@@ -44,6 +44,7 @@ const mimeTypes = new Map([
['application/fractals', 'fif'],
['application/freeloader', 'frl'],
['application/futuresplash', 'spl'],
['application/geo+json', 'geojson'],
['application/gnutar', 'tgz'],
['application/groupwise', 'vew'],
['application/hlp', 'hlp'],
@@ -1101,7 +1102,10 @@ const extensions = new Map([
['bdm', 'application/vnd.syncml.dm+wbxml'],
['bed', 'application/vnd.realvnc.bed'],
['bh2', 'application/vnd.fujitsu.oasysprs'],
['bin', ['application/octet-stream', 'application/mac-binary', 'application/macbinary', 'application/x-macbinary', 'application/x-binary']],
[
'bin',
['application/octet-stream', 'application/mac-binary', 'application/macbinary', 'application/x-macbinary', 'application/x-binary']
],
['bm', 'image/bmp'],
['bmi', 'application/vnd.bmi'],
['bmp', ['image/bmp', 'image/x-windows-bmp']],
@@ -1146,7 +1150,10 @@ const extensions = new Map([
['cii', 'application/vnd.anser-web-certificate-issue-initiation'],
['cil', 'application/vnd.ms-artgalry'],
['cla', 'application/vnd.claymore'],
['class', ['application/octet-stream', 'application/java', 'application/java-byte-code', 'application/java-vm', 'application/x-java-class']],
[
'class',
['application/octet-stream', 'application/java', 'application/java-byte-code', 'application/java-vm', 'application/x-java-class']
],
['clkk', 'application/vnd.crick.clicker.keyboard'],
['clkp', 'application/vnd.crick.clicker.palette'],
['clkt', 'application/vnd.crick.clicker.template'],
@@ -1287,6 +1294,7 @@ const extensions = new Map([
['gac', 'application/vnd.groove-account'],
['gdl', 'model/vnd.gdl'],
['geo', 'application/vnd.dynageo'],
['geojson', 'application/geo+json'],
['gex', 'application/vnd.geometry-explorer'],
['ggb', 'application/vnd.geogebra.file'],
['ggt', 'application/vnd.geogebra.tool'],
@@ -1750,7 +1758,10 @@ const extensions = new Map([
['sbml', 'application/sbml+xml'],
['sc', 'application/vnd.ibm.secure-container'],
['scd', 'application/x-msschedule'],
['scm', ['application/vnd.lotus-screencam', 'video/x-scm', 'text/x-script.guile', 'application/x-lotusscreencam', 'text/x-script.scheme']],
[
'scm',
['application/vnd.lotus-screencam', 'video/x-scm', 'text/x-script.guile', 'application/x-lotusscreencam', 'text/x-script.scheme']
],
['scq', 'application/scvp-cv-request'],
['scs', 'application/scvp-cv-response'],
['sct', 'text/scriptlet'],

View File

@@ -552,7 +552,11 @@ class MimeNode {
this._handleContentType(structured);
if (structured.value.match(/^text\/plain\b/) && typeof this.content === 'string' && /[\u0080-\uFFFF]/.test(this.content)) {
if (
structured.value.match(/^text\/plain\b/) &&
typeof this.content === 'string' &&
/[\u0080-\uFFFF]/.test(this.content)
) {
structured.params.charset = 'utf-8';
}
@@ -963,8 +967,8 @@ class MimeNode {
setImmediate(() => {
try {
contentStream.end(content._resolvedValue);
} catch (err) {
contentStream.emit('error', err);
} catch (_err) {
contentStream.emit('error', _err);
}
});
@@ -995,8 +999,8 @@ class MimeNode {
setImmediate(() => {
try {
contentStream.end(content || '');
} catch (err) {
contentStream.emit('error', err);
} catch (_err) {
contentStream.emit('error', _err);
}
});
return contentStream;
@@ -1014,7 +1018,6 @@ class MimeNode {
return [].concat.apply(
[],
[].concat(addresses).map(address => {
// eslint-disable-line prefer-spread
if (address && address.address) {
address.address = this._normalizeAddress(address.address);
address.name = address.name || '';
@@ -1113,7 +1116,6 @@ class MimeNode {
.apply(
[],
[].concat(value || '').map(elm => {
// eslint-disable-line prefer-spread
elm = (elm || '')
.toString()
.replace(/\r?\n|\r/g, ' ')
@@ -1219,7 +1221,7 @@ class MimeNode {
try {
encodedDomain = punycode.toASCII(domain.toLowerCase());
} catch (err) {
} catch (_err) {
// keep as is?
}
@@ -1282,7 +1284,7 @@ class MimeNode {
// count latin alphabet symbols and 8-bit range symbols + control symbols
// if there are more latin characters, then use quoted-printable
// encoding, otherwise use base64
nonLatinLen = (value.match(/[\x00-\x08\x0B\x0C\x0E-\x1F\u0080-\uFFFF]/g) || []).length; // eslint-disable-line no-control-regex
nonLatinLen = (value.match(/[\x00-\x08\x0B\x0C\x0E-\x1F\u0080-\uFFFF]/g) || []).length;
latinLen = (value.match(/[a-z]/gi) || []).length;
// if there are more latin symbols than binary/unicode, then prefer Q, otherwise B
encoding = nonLatinLen < latinLen ? 'Q' : 'B';

View File

@@ -45,6 +45,13 @@ module.exports.createTransport = function (transporter, defaults) {
} else if (options.jsonTransport) {
transporter = new JSONTransport(options);
} else if (options.SES) {
if (options.SES.ses && options.SES.aws) {
let error = new Error(
'Using legacy SES configuration, expecting @aws-sdk/client-sesv2, see https://nodemailer.com/transports/ses/'
);
error.code = 'LegacyConfig';
throw error;
}
transporter = new SESTransport(options);
} else {
transporter = new SMTPTransport(options);

View File

@@ -28,7 +28,10 @@ function encode(buffer) {
for (let i = 0, len = buffer.length; i < len; i++) {
ord = buffer[i];
// if the char is in allowed range, then keep as is, unless it is a WS in the end of a line
if (checkRanges(ord, ranges) && !((ord === 0x20 || ord === 0x09) && (i === len - 1 || buffer[i + 1] === 0x0a || buffer[i + 1] === 0x0d))) {
if (
checkRanges(ord, ranges) &&
!((ord === 0x20 || ord === 0x09) && (i === len - 1 || buffer[i + 1] === 0x0a || buffer[i + 1] === 0x0d))
) {
result += String.fromCharCode(ord);
continue;
}
@@ -90,7 +93,12 @@ function wrap(str, lineLength) {
}
// ensure that utf-8 sequences are not split
while (line.length > 3 && line.length < len - pos && !line.match(/^(?:=[\da-f]{2}){1,4}$/i) && (match = line.match(/[=][\da-f]{2}$/gi))) {
while (
line.length > 3 &&
line.length < len - pos &&
!line.match(/^(?:=[\da-f]{2}){1,4}$/i) &&
(match = line.match(/[=][\da-f]{2}$/gi))
) {
code = parseInt(match[0].substr(1, 2), 16);
if (code < 128) {
break;

View File

@@ -4,15 +4,11 @@ const EventEmitter = require('events');
const packageData = require('../../package.json');
const shared = require('../shared');
const LeWindows = require('../mime-node/le-windows');
const MimeNode = require('../mime-node');
/**
* Generates a Transport object for AWS SES
*
* Possible options can be the following:
*
* * **sendingRate** optional Number specifying how many messages per second should be delivered to SES
* * **maxConnections** optional Number specifying max number of parallel connections to SES
*
* @constructor
* @param {Object} optional config parameter
*/
@@ -30,119 +26,17 @@ class SESTransport extends EventEmitter {
this.logger = shared.getLogger(this.options, {
component: this.options.component || 'ses-transport'
});
// parallel sending connections
this.maxConnections = Number(this.options.maxConnections) || Infinity;
this.connections = 0;
// max messages per second
this.sendingRate = Number(this.options.sendingRate) || Infinity;
this.sendingRateTTL = null;
this.rateInterval = 1000; // milliseconds
this.rateMessages = [];
this.pending = [];
this.idling = true;
setImmediate(() => {
if (this.idling) {
this.emit('idle');
}
});
}
/**
* Schedules a sending of a message
*
* @param {Object} emailMessage MailComposer object
* @param {Function} callback Callback function to run when the sending is completed
*/
send(mail, callback) {
if (this.connections >= this.maxConnections) {
this.idling = false;
return this.pending.push({
mail,
callback
});
getRegion(cb) {
if (this.ses.sesClient.config && typeof this.ses.sesClient.config.region === 'function') {
// promise
return this.ses.sesClient.config
.region()
.then(region => cb(null, region))
.catch(err => cb(err));
}
if (!this._checkSendingRate()) {
this.idling = false;
return this.pending.push({
mail,
callback
});
}
this._send(mail, (...args) => {
setImmediate(() => callback(...args));
this._sent();
});
}
_checkRatedQueue() {
if (this.connections >= this.maxConnections || !this._checkSendingRate()) {
return;
}
if (!this.pending.length) {
if (!this.idling) {
this.idling = true;
this.emit('idle');
}
return;
}
let next = this.pending.shift();
this._send(next.mail, (...args) => {
setImmediate(() => next.callback(...args));
this._sent();
});
}
_checkSendingRate() {
clearTimeout(this.sendingRateTTL);
let now = Date.now();
let oldest = false;
// delete older messages
for (let i = this.rateMessages.length - 1; i >= 0; i--) {
if (this.rateMessages[i].ts >= now - this.rateInterval && (!oldest || this.rateMessages[i].ts < oldest)) {
oldest = this.rateMessages[i].ts;
}
if (this.rateMessages[i].ts < now - this.rateInterval && !this.rateMessages[i].pending) {
this.rateMessages.splice(i, 1);
}
}
if (this.rateMessages.length < this.sendingRate) {
return true;
}
let delay = Math.max(oldest + 1001, now + 20);
this.sendingRateTTL = setTimeout(() => this._checkRatedQueue(), now - delay);
try {
this.sendingRateTTL.unref();
} catch (E) {
// Ignore. Happens on envs with non-node timer implementation
}
return false;
}
_sent() {
this.connections--;
this._checkRatedQueue();
}
/**
* Returns true if there are free slots in the queue
*/
isIdle() {
return this.idling;
return cb(null, false);
}
/**
@@ -151,13 +45,17 @@ class SESTransport extends EventEmitter {
* @param {Object} emailMessage MailComposer object
* @param {Function} callback Callback function to run when the sending is completed
*/
_send(mail, callback) {
send(mail, callback) {
let statObject = {
ts: Date.now(),
pending: true
};
this.connections++;
this.rateMessages.push(statObject);
let fromHeader = mail.message._headers.find(header => /^from$/i.test(header.key));
if (fromHeader) {
let mimeNode = new MimeNode('text/plain');
fromHeader = mimeNode._convertAddresses(mimeNode._parseAddresses(fromHeader.value));
}
let envelope = mail.data.envelope || mail.message.getEnvelope();
let messageId = mail.message.messageId();
@@ -227,45 +125,29 @@ class SESTransport extends EventEmitter {
}
let sesMessage = {
RawMessage: {
// required
Data: raw // required
Content: {
Raw: {
// required
Data: raw // required
}
},
Source: envelope.from,
Destinations: envelope.to
FromEmailAddress: fromHeader ? fromHeader : envelope.from,
Destination: {
ToAddresses: envelope.to
}
};
Object.keys(mail.data.ses || {}).forEach(key => {
sesMessage[key] = mail.data.ses[key];
});
let ses = (this.ses.aws ? this.ses.ses : this.ses) || {};
let aws = this.ses.aws || {};
let getRegion = cb => {
if (ses.config && typeof ses.config.region === 'function') {
// promise
return ses.config
.region()
.then(region => cb(null, region))
.catch(err => cb(err));
}
return cb(null, (ses.config && ses.config.region) || 'us-east-1');
};
getRegion((err, region) => {
this.getRegion((err, region) => {
if (err || !region) {
region = 'us-east-1';
}
let sendPromise;
if (typeof ses.send === 'function' && aws.SendRawEmailCommand) {
// v3 API
sendPromise = ses.send(new aws.SendRawEmailCommand(sesMessage));
} else {
// v2 API
sendPromise = ses.sendRawEmail(sesMessage).promise();
}
const command = new this.ses.SendEmailCommand(sesMessage);
const sendPromise = this.ses.sesClient.send(command);
sendPromise
.then(data => {
@@ -273,7 +155,7 @@ class SESTransport extends EventEmitter {
region = 'email';
}
statObject.pending = false;
statObject.pending = true;
callback(null, {
envelope: {
from: envelope.from,
@@ -309,38 +191,41 @@ class SESTransport extends EventEmitter {
*/
verify(callback) {
let promise;
let ses = (this.ses.aws ? this.ses.ses : this.ses) || {};
let aws = this.ses.aws || {};
const sesMessage = {
RawMessage: {
// required
Data: 'From: invalid@invalid\r\nTo: invalid@invalid\r\n Subject: Invalid\r\n\r\nInvalid'
},
Source: 'invalid@invalid',
Destinations: ['invalid@invalid']
};
if (!callback) {
promise = new Promise((resolve, reject) => {
callback = shared.callbackPromise(resolve, reject);
});
}
const cb = err => {
if (err && (err.code || err.Code) !== 'InvalidParameterValue') {
if (err && !['InvalidParameterValue', 'MessageRejected'].includes(err.code || err.Code || err.name)) {
return callback(err);
}
return callback(null, true);
};
if (typeof ses.send === 'function' && aws.SendRawEmailCommand) {
// v3 API
sesMessage.RawMessage.Data = Buffer.from(sesMessage.RawMessage.Data);
ses.send(new aws.SendRawEmailCommand(sesMessage), cb);
} else {
// v2 API
ses.sendRawEmail(sesMessage, cb);
}
const sesMessage = {
Content: {
Raw: {
Data: Buffer.from('From: <invalid@invalid>\r\nTo: <invalid@invalid>\r\n Subject: Invalid\r\n\r\nInvalid')
}
},
FromEmailAddress: 'invalid@invalid',
Destination: {
ToAddresses: ['invalid@invalid']
}
};
this.getRegion((err, region) => {
if (err || !region) {
region = 'us-east-1';
}
const command = new this.ses.SendEmailCommand(sesMessage);
const sendPromise = this.ses.sesClient.send(command);
sendPromise.then(data => cb(null, data)).catch(err => cb(err));
});
return promise;
}

View File

@@ -11,11 +11,19 @@ const net = require('net');
const os = require('os');
const DNS_TTL = 5 * 60 * 1000;
const CACHE_CLEANUP_INTERVAL = 30 * 1000; // Minimum 30 seconds between cleanups
const MAX_CACHE_SIZE = 1000; // Maximum number of entries in cache
let lastCacheCleanup = 0;
module.exports._lastCacheCleanup = () => lastCacheCleanup;
module.exports._resetCacheCleanup = () => {
lastCacheCleanup = 0;
};
let networkInterfaces;
try {
networkInterfaces = os.networkInterfaces();
} catch (err) {
} catch (_err) {
// fails on some systems
}
@@ -81,8 +89,8 @@ const formatDNSValue = (value, extra) => {
!value.addresses || !value.addresses.length
? null
: value.addresses.length === 1
? value.addresses[0]
: value.addresses[Math.floor(Math.random() * value.addresses.length)]
? value.addresses[0]
: value.addresses[Math.floor(Math.random() * value.addresses.length)]
},
extra || {}
);
@@ -113,7 +121,27 @@ module.exports.resolveHostname = (options, callback) => {
if (dnsCache.has(options.host)) {
cached = dnsCache.get(options.host);
if (!cached.expires || cached.expires >= Date.now()) {
// Lazy cleanup with time throttling
const now = Date.now();
if (now - lastCacheCleanup > CACHE_CLEANUP_INTERVAL) {
lastCacheCleanup = now;
// Clean up expired entries
for (const [host, entry] of dnsCache.entries()) {
if (entry.expires && entry.expires < now) {
dnsCache.delete(host);
}
}
// If cache is still too large, remove oldest entries
if (dnsCache.size > MAX_CACHE_SIZE) {
const toDelete = Math.floor(MAX_CACHE_SIZE * 0.1); // Remove 10% of entries
const keys = Array.from(dnsCache.keys()).slice(0, toDelete);
keys.forEach(key => dnsCache.delete(key));
}
}
if (!cached.expires || cached.expires >= now) {
return callback(
null,
formatDNSValue(cached.value, {
@@ -126,7 +154,11 @@ module.exports.resolveHostname = (options, callback) => {
resolver(4, options.host, options, (err, addresses) => {
if (err) {
if (cached) {
// ignore error, use expired value
dnsCache.set(options.host, {
value: cached.value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(cached.value, {
@@ -160,7 +192,11 @@ module.exports.resolveHostname = (options, callback) => {
resolver(6, options.host, options, (err, addresses) => {
if (err) {
if (cached) {
// ignore error, use expired value
dnsCache.set(options.host, {
value: cached.value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(cached.value, {
@@ -195,7 +231,11 @@ module.exports.resolveHostname = (options, callback) => {
dns.lookup(options.host, { all: true }, (err, addresses) => {
if (err) {
if (cached) {
// ignore error, use expired value
dnsCache.set(options.host, {
value: cached.value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(cached.value, {
@@ -246,9 +286,13 @@ module.exports.resolveHostname = (options, callback) => {
})
);
});
} catch (err) {
} catch (_err) {
if (cached) {
// ignore error, use expired value
dnsCache.set(options.host, {
value: cached.value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(cached.value, {
@@ -419,52 +463,74 @@ module.exports.callbackPromise = (resolve, reject) =>
};
module.exports.parseDataURI = uri => {
let input = uri;
let commaPos = input.indexOf(',');
if (!commaPos) {
return uri;
if (typeof uri !== 'string') {
return null;
}
let data = input.substring(commaPos + 1);
let metaStr = input.substring('data:'.length, commaPos);
// Early return for non-data URIs to avoid unnecessary processing
if (!uri.startsWith('data:')) {
return null;
}
// Find the first comma safely - this prevents ReDoS
const commaPos = uri.indexOf(',');
if (commaPos === -1) {
return null;
}
const data = uri.substring(commaPos + 1);
const metaStr = uri.substring('data:'.length, commaPos);
let encoding;
const metaEntries = metaStr.split(';');
let metaEntries = metaStr.split(';');
let lastMetaEntry = metaEntries.length > 1 ? metaEntries[metaEntries.length - 1] : false;
if (lastMetaEntry && lastMetaEntry.indexOf('=') < 0) {
encoding = lastMetaEntry.toLowerCase();
metaEntries.pop();
}
let contentType = metaEntries.shift() || 'application/octet-stream';
let params = {};
for (let entry of metaEntries) {
let sep = entry.indexOf('=');
if (sep >= 0) {
let key = entry.substring(0, sep);
let value = entry.substring(sep + 1);
params[key] = value;
if (metaEntries.length > 0) {
const lastEntry = metaEntries[metaEntries.length - 1].toLowerCase().trim();
// Only recognize valid encoding types to prevent manipulation
if (['base64', 'utf8', 'utf-8'].includes(lastEntry) && lastEntry.indexOf('=') === -1) {
encoding = lastEntry;
metaEntries.pop();
}
}
switch (encoding) {
case 'base64':
data = Buffer.from(data, 'base64');
break;
case 'utf8':
data = Buffer.from(data);
break;
default:
try {
data = Buffer.from(decodeURIComponent(data));
} catch (err) {
data = Buffer.from(data);
const contentType = metaEntries.length > 0 ? metaEntries.shift() : 'application/octet-stream';
const params = {};
for (let i = 0; i < metaEntries.length; i++) {
const entry = metaEntries[i];
const sepPos = entry.indexOf('=');
if (sepPos > 0) {
// Ensure there's a key before the '='
const key = entry.substring(0, sepPos).trim();
const value = entry.substring(sepPos + 1).trim();
if (key) {
params[key] = value;
}
data = Buffer.from(data);
}
}
return { data, encoding, contentType, params };
// Decode data based on encoding with proper error handling
let bufferData;
try {
if (encoding === 'base64') {
bufferData = Buffer.from(data, 'base64');
} else {
try {
bufferData = Buffer.from(decodeURIComponent(data));
} catch (_decodeError) {
bufferData = Buffer.from(data);
}
}
} catch (_bufferError) {
bufferData = Buffer.alloc(0);
}
return {
data: bufferData,
encoding: encoding || null,
contentType: contentType || 'application/octet-stream',
params
};
};
/**

View File

@@ -51,7 +51,7 @@ function httpProxyClient(proxyUrl, destinationPort, destinationHost, callback) {
finished = true;
try {
socket.destroy();
} catch (E) {
} catch (_E) {
// ignore
}
callback(err);
@@ -118,7 +118,7 @@ function httpProxyClient(proxyUrl, destinationPort, destinationHost, callback) {
if (!match || (match[1] || '').charAt(0) !== '2') {
try {
socket.destroy();
} catch (E) {
} catch (_E) {
// ignore
}
return callback(new Error('Invalid response from proxy' + ((match && ': ' + match[1]) || '')));

View File

@@ -124,7 +124,7 @@ class SMTPConnection extends EventEmitter {
/**
* The socket connecting to the server
* @publick
* @public
*/
this._socket = false;
@@ -243,6 +243,8 @@ class SMTPConnection extends EventEmitter {
if (this.options.connection) {
// connection is already opened
this._socket = this.options.connection;
setupConnectionHandlers();
if (this.secureConnection && !this.alreadySecured) {
setImmediate(() =>
this._upgradeConnection(err => {
@@ -412,8 +414,8 @@ class SMTPConnection extends EventEmitter {
if (socket && !socket.destroyed) {
try {
this._socket[closeMethod]();
} catch (E) {
socket[closeMethod]();
} catch (_E) {
// just ignore
}
}
@@ -628,6 +630,15 @@ class SMTPConnection extends EventEmitter {
let startTime = Date.now();
this._setEnvelope(envelope, (err, info) => {
if (err) {
// create passthrough stream to consume to prevent OOM
let stream = new PassThrough();
if (typeof message.pipe === 'function') {
message.pipe(stream);
} else {
stream.write(message);
stream.end();
}
return callback(err);
}
let envelopeTime = Date.now();
@@ -1283,7 +1294,12 @@ class SMTPConnection extends EventEmitter {
if (str.charAt(0) !== '2') {
if (this.options.requireTLS) {
this._onError(new Error('EHLO failed but HELO does not support required STARTTLS. response=' + str), 'ECONNECTION', str, 'EHLO');
this._onError(
new Error('EHLO failed but HELO does not support required STARTTLS. response=' + str),
'ECONNECTION',
str,
'EHLO'
);
return;
}
@@ -1465,7 +1481,9 @@ class SMTPConnection extends EventEmitter {
let challengeString = '';
if (!challengeMatch) {
return callback(this._formatError('Invalid login sequence while waiting for server challenge string', 'EAUTH', str, 'AUTH CRAM-MD5'));
return callback(
this._formatError('Invalid login sequence while waiting for server challenge string', 'EAUTH', str, 'AUTH CRAM-MD5')
);
} else {
challengeString = challengeMatch[1];
}
@@ -1608,7 +1626,7 @@ class SMTPConnection extends EventEmitter {
}
if (!this._envelope.rcptQueue.length) {
return callback(this._formatError('Can\x27t send mail - no recipients defined', 'EENVELOPE', false, 'API'));
return callback(this._formatError("Can't send mail - no recipients defined", 'EENVELOPE', false, 'API'));
} else {
this._recipientQueue = [];
@@ -1664,7 +1682,7 @@ class SMTPConnection extends EventEmitter {
});
this._sendCommand('DATA');
} else {
err = this._formatError('Can\x27t send mail - all recipients were rejected', 'EENVELOPE', str, 'RCPT TO');
err = this._formatError("Can't send mail - all recipients were rejected", 'EENVELOPE', str, 'RCPT TO');
err.rejected = this._envelope.rejected;
err.rejectedErrors = this._envelope.rejectedErrors;
return callback(err);
@@ -1803,7 +1821,7 @@ class SMTPConnection extends EventEmitter {
let defaultHostname;
try {
defaultHostname = os.hostname() || '';
} catch (err) {
} catch (_err) {
// fails on windows 7
defaultHostname = 'localhost';
}

View File

@@ -406,6 +406,10 @@ class SMTPPool extends EventEmitter {
this._continueProcessing();
}, 50);
} else {
if (!this._closed && this.idling && !this._connections.length) {
this.emit('clear');
}
this._continueProcessing();
}
});

View File

@@ -23,7 +23,8 @@ class PoolResource extends EventEmitter {
switch ((this.options.auth.type || '').toString().toUpperCase()) {
case 'OAUTH2': {
let oauth2 = new XOAuth2(this.options.auth, this.logger);
oauth2.provisionCallback = (this.pool.mailer && this.pool.mailer.get('oauth2_provision_cb')) || oauth2.provisionCallback;
oauth2.provisionCallback =
(this.pool.mailer && this.pool.mailer.get('oauth2_provision_cb')) || oauth2.provisionCallback;
this.auth = {
type: 'OAUTH2',
user: this.options.auth.user,
@@ -127,7 +128,7 @@ class PoolResource extends EventEmitter {
try {
timer.unref();
} catch (E) {
} catch (_E) {
// Ignore. Happens on envs with non-node timer implementation
}
});

View File

@@ -197,7 +197,7 @@ class SMTPTransport extends EventEmitter {
try {
timer.unref();
} catch (E) {
} catch (_E) {
// Ignore. Happens on envs with non-node timer implementation
}
});

View File

@@ -1,63 +1,120 @@
{
"1und1": {
"description": "1&1 Mail (German hosting provider)",
"host": "smtp.1und1.de",
"port": 465,
"secure": true,
"authMethod": "LOGIN"
},
"126": {
"description": "126 Mail (NetEase)",
"host": "smtp.126.com",
"port": 465,
"secure": true
},
"163": {
"description": "163 Mail (NetEase)",
"host": "smtp.163.com",
"port": 465,
"secure": true
},
"Aliyun": {
"description": "Alibaba Cloud Mail",
"domains": ["aliyun.com"],
"host": "smtp.aliyun.com",
"port": 465,
"secure": true
},
"AliyunQiye": {
"description": "Alibaba Cloud Enterprise Mail",
"host": "smtp.qiye.aliyun.com",
"port": 465,
"secure": true
},
"AOL": {
"description": "AOL Mail",
"domains": ["aol.com"],
"host": "smtp.aol.com",
"port": 587
},
"Aruba": {
"description": "Aruba PEC (Italian email provider)",
"domains": ["aruba.it", "pec.aruba.it"],
"aliases": ["Aruba PEC"],
"host": "smtps.aruba.it",
"port": 465,
"secure": true,
"authMethod": "LOGIN"
},
"Bluewin": {
"description": "Bluewin (Swiss email provider)",
"host": "smtpauths.bluewin.ch",
"domains": ["bluewin.ch"],
"port": 465
},
"BOL": {
"description": "BOL Mail (Brazilian provider)",
"domains": ["bol.com.br"],
"host": "smtp.bol.com.br",
"port": 587,
"requireTLS": true
},
"DebugMail": {
"description": "DebugMail (email testing service)",
"host": "debugmail.io",
"port": 25
},
"Disroot": {
"description": "Disroot (privacy-focused provider)",
"domains": ["disroot.org"],
"host": "disroot.org",
"port": 587,
"secure": false,
"authMethod": "LOGIN"
},
"DynectEmail": {
"description": "Dyn Email Delivery",
"aliases": ["Dynect"],
"host": "smtp.dynect.net",
"port": 25
},
"ElasticEmail": {
"description": "Elastic Email",
"aliases": ["Elastic Email"],
"host": "smtp.elasticemail.com",
"port": 465,
"secure": true
},
"Ethereal": {
"description": "Ethereal Email (email testing service)",
"aliases": ["ethereal.email"],
"host": "smtp.ethereal.email",
"port": 587
},
"FastMail": {
"description": "FastMail",
"domains": ["fastmail.fm"],
"host": "smtp.fastmail.com",
"port": 465,
"secure": true
},
"Forward Email": {
"aliases": ["FE", "ForwardEmail"],
"domains": ["forwardemail.net"],
"host": "smtp.forwardemail.net",
"port": 465,
"secure": true
},
"Feishu Mail": {
"description": "Feishu Mail (Lark)",
"aliases": ["Feishu", "FeishuMail"],
"domains": ["www.feishu.cn"],
"host": "smtp.feishu.cn",
@@ -65,13 +122,24 @@
"secure": true
},
"Forward Email": {
"description": "Forward Email (email forwarding service)",
"aliases": ["FE", "ForwardEmail"],
"domains": ["forwardemail.net"],
"host": "smtp.forwardemail.net",
"port": 465,
"secure": true
},
"GandiMail": {
"description": "Gandi Mail",
"aliases": ["Gandi", "Gandi Mail"],
"host": "mail.gandi.net",
"port": 587
},
"Gmail": {
"description": "Gmail",
"aliases": ["Google Mail"],
"domains": ["gmail.com", "googlemail.com"],
"host": "smtp.gmail.com",
@@ -79,26 +147,38 @@
"secure": true
},
"GMX": {
"description": "GMX Mail",
"domains": ["gmx.com", "gmx.net", "gmx.de"],
"host": "mail.gmx.com",
"port": 587
},
"Godaddy": {
"description": "GoDaddy Email (US)",
"host": "smtpout.secureserver.net",
"port": 25
},
"GodaddyAsia": {
"description": "GoDaddy Email (Asia)",
"host": "smtp.asia.secureserver.net",
"port": 25
},
"GodaddyEurope": {
"description": "GoDaddy Email (Europe)",
"host": "smtp.europe.secureserver.net",
"port": 25
},
"hot.ee": {
"description": "Hot.ee (Estonian email provider)",
"host": "mail.hot.ee"
},
"Hotmail": {
"description": "Outlook.com / Hotmail",
"aliases": ["Outlook", "Outlook.com", "Hotmail.com"],
"domains": ["hotmail.com", "outlook.com"],
"host": "smtp-mail.outlook.com",
@@ -106,6 +186,7 @@
},
"iCloud": {
"description": "iCloud Mail",
"aliases": ["Me", "Mac"],
"domains": ["me.com", "mac.com"],
"host": "smtp.mail.me.com",
@@ -113,72 +194,117 @@
},
"Infomaniak": {
"description": "Infomaniak Mail (Swiss hosting provider)",
"host": "mail.infomaniak.com",
"domains": ["ik.me", "ikmail.com", "etik.com"],
"port": 587
},
"KolabNow": {
"description": "KolabNow (secure email service)",
"domains": ["kolabnow.com"],
"aliases": ["Kolab"],
"host": "smtp.kolabnow.com",
"port": 465,
"secure": true,
"authMethod": "LOGIN"
},
"Loopia": {
"description": "Loopia (Swedish hosting provider)",
"host": "mailcluster.loopia.se",
"port": 465
},
"Loops": {
"description": "Loops",
"host": "smtp.loops.so",
"port": 587
},
"mail.ee": {
"description": "Mail.ee (Estonian email provider)",
"host": "smtp.mail.ee"
},
"Mail.ru": {
"description": "Mail.ru",
"host": "smtp.mail.ru",
"port": 465,
"secure": true
},
"Mailcatch.app": {
"description": "Mailcatch (email testing service)",
"host": "sandbox-smtp.mailcatch.app",
"port": 2525
},
"Maildev": {
"description": "MailDev (local email testing)",
"port": 1025,
"ignoreTLS": true
},
"MailerSend": {
"description": "MailerSend",
"host": "smtp.mailersend.net",
"port": 587
},
"Mailgun": {
"description": "Mailgun",
"host": "smtp.mailgun.org",
"port": 465,
"secure": true
},
"Mailjet": {
"description": "Mailjet",
"host": "in.mailjet.com",
"port": 587
},
"Mailosaur": {
"description": "Mailosaur (email testing service)",
"host": "mailosaur.io",
"port": 25
},
"Mailtrap": {
"description": "Mailtrap",
"host": "live.smtp.mailtrap.io",
"port": 587
},
"Mandrill": {
"description": "Mandrill (by Mailchimp)",
"host": "smtp.mandrillapp.com",
"port": 587
},
"Naver": {
"description": "Naver Mail (Korean email provider)",
"host": "smtp.naver.com",
"port": 587
},
"OhMySMTP": {
"description": "OhMySMTP (email delivery service)",
"host": "smtp.ohmysmtp.com",
"port": 587,
"secure": false
},
"One": {
"description": "One.com Email",
"host": "send.one.com",
"port": 465,
"secure": true
},
"OpenMailBox": {
"description": "OpenMailBox",
"aliases": ["OMB", "openmailbox.org"],
"host": "smtp.openmailbox.org",
"port": 465,
@@ -186,30 +312,37 @@
},
"Outlook365": {
"description": "Microsoft 365 / Office 365",
"host": "smtp.office365.com",
"port": 587,
"secure": false
},
"OhMySMTP": {
"host": "smtp.ohmysmtp.com",
"port": 587,
"secure": false
},
"Postmark": {
"description": "Postmark",
"aliases": ["PostmarkApp"],
"host": "smtp.postmarkapp.com",
"port": 2525
},
"Proton": {
"description": "Proton Mail",
"aliases": ["ProtonMail", "Proton.me", "Protonmail.com", "Protonmail.ch"],
"domains": ["proton.me", "protonmail.com", "pm.me", "protonmail.ch"],
"host": "smtp.protonmail.ch",
"port": 587,
"requireTLS": true
},
"qiye.aliyun": {
"description": "Alibaba Mail Enterprise Edition",
"host": "smtp.mxhichina.com",
"port": "465",
"secure": true
},
"QQ": {
"description": "QQ Mail",
"domains": ["qq.com"],
"host": "smtp.qq.com",
"port": 465,
@@ -217,6 +350,7 @@
},
"QQex": {
"description": "QQ Enterprise Mail",
"aliases": ["QQ Enterprise"],
"domains": ["exmail.qq.com"],
"host": "smtp.exmail.qq.com",
@@ -224,89 +358,204 @@
"secure": true
},
"Resend": {
"description": "Resend",
"host": "smtp.resend.com",
"port": 465,
"secure": true
},
"Runbox": {
"description": "Runbox (Norwegian email provider)",
"domains": ["runbox.com"],
"host": "smtp.runbox.com",
"port": 465,
"secure": true
},
"SendCloud": {
"description": "SendCloud (Chinese email delivery)",
"host": "smtp.sendcloud.net",
"port": 2525
},
"SendGrid": {
"description": "SendGrid",
"host": "smtp.sendgrid.net",
"port": 587
},
"SendinBlue": {
"description": "Brevo (formerly Sendinblue)",
"aliases": ["Brevo"],
"host": "smtp-relay.brevo.com",
"port": 587
},
"SendPulse": {
"description": "SendPulse",
"host": "smtp-pulse.com",
"port": 465,
"secure": true
},
"SES": {
"description": "AWS SES US East (N. Virginia)",
"host": "email-smtp.us-east-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-EAST-1": {
"host": "email-smtp.us-east-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-WEST-2": {
"host": "email-smtp.us-west-2.amazonaws.com",
"port": 465,
"secure": true
},
"SES-EU-WEST-1": {
"host": "email-smtp.eu-west-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-AP-SOUTH-1": {
"host": "email-smtp.ap-south-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-AP-NORTHEAST-1": {
"description": "AWS SES Asia Pacific (Tokyo)",
"host": "email-smtp.ap-northeast-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-AP-NORTHEAST-2": {
"description": "AWS SES Asia Pacific (Seoul)",
"host": "email-smtp.ap-northeast-2.amazonaws.com",
"port": 465,
"secure": true
},
"SES-AP-NORTHEAST-3": {
"description": "AWS SES Asia Pacific (Osaka)",
"host": "email-smtp.ap-northeast-3.amazonaws.com",
"port": 465,
"secure": true
},
"SES-AP-SOUTH-1": {
"description": "AWS SES Asia Pacific (Mumbai)",
"host": "email-smtp.ap-south-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-AP-SOUTHEAST-1": {
"description": "AWS SES Asia Pacific (Singapore)",
"host": "email-smtp.ap-southeast-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-AP-SOUTHEAST-2": {
"description": "AWS SES Asia Pacific (Sydney)",
"host": "email-smtp.ap-southeast-2.amazonaws.com",
"port": 465,
"secure": true
},
"SES-CA-CENTRAL-1": {
"description": "AWS SES Canada (Central)",
"host": "email-smtp.ca-central-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-EU-CENTRAL-1": {
"description": "AWS SES Europe (Frankfurt)",
"host": "email-smtp.eu-central-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-EU-NORTH-1": {
"description": "AWS SES Europe (Stockholm)",
"host": "email-smtp.eu-north-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-EU-WEST-1": {
"description": "AWS SES Europe (Ireland)",
"host": "email-smtp.eu-west-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-EU-WEST-2": {
"description": "AWS SES Europe (London)",
"host": "email-smtp.eu-west-2.amazonaws.com",
"port": 465,
"secure": true
},
"SES-EU-WEST-3": {
"description": "AWS SES Europe (Paris)",
"host": "email-smtp.eu-west-3.amazonaws.com",
"port": 465,
"secure": true
},
"SES-SA-EAST-1": {
"description": "AWS SES South America (São Paulo)",
"host": "email-smtp.sa-east-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-EAST-1": {
"description": "AWS SES US East (N. Virginia)",
"host": "email-smtp.us-east-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-EAST-2": {
"description": "AWS SES US East (Ohio)",
"host": "email-smtp.us-east-2.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-GOV-EAST-1": {
"description": "AWS SES GovCloud (US-East)",
"host": "email-smtp.us-gov-east-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-GOV-WEST-1": {
"description": "AWS SES GovCloud (US-West)",
"host": "email-smtp.us-gov-west-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-WEST-1": {
"description": "AWS SES US West (N. California)",
"host": "email-smtp.us-west-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-WEST-2": {
"description": "AWS SES US West (Oregon)",
"host": "email-smtp.us-west-2.amazonaws.com",
"port": 465,
"secure": true
},
"Seznam": {
"description": "Seznam Email (Czech email provider)",
"aliases": ["Seznam Email"],
"domains": ["seznam.cz", "email.cz", "post.cz", "spoluzaci.cz"],
"host": "smtp.seznam.cz",
"port": 465,
"secure": true
},
"SMTP2GO": {
"description": "SMTP2GO",
"host": "mail.smtp2go.com",
"port": 2525
},
"Sparkpost": {
"description": "SparkPost",
"aliases": ["SparkPost", "SparkPost Mail"],
"domains": ["sparkpost.com"],
"host": "smtp.sparkpostmail.com",
@@ -315,11 +564,21 @@
},
"Tipimail": {
"description": "Tipimail (email delivery service)",
"host": "smtp.tipimail.com",
"port": 587
},
"Tutanota": {
"description": "Tutanota (Tuta Mail)",
"domains": ["tutanota.com", "tuta.com", "tutanota.de", "tuta.io"],
"host": "smtp.tutanota.com",
"port": 465,
"secure": true
},
"Yahoo": {
"description": "Yahoo Mail",
"domains": ["yahoo.com"],
"host": "smtp.mail.yahoo.com",
"port": 465,
@@ -327,28 +586,26 @@
},
"Yandex": {
"description": "Yandex Mail",
"domains": ["yandex.ru"],
"host": "smtp.yandex.ru",
"port": 465,
"secure": true
},
"Zimbra": {
"description": "Zimbra Mail Server",
"aliases": ["Zimbra Collaboration"],
"host": "smtp.zimbra.com",
"port": 587,
"requireTLS": true
},
"Zoho": {
"description": "Zoho Mail",
"host": "smtp.zoho.com",
"port": 465,
"secure": true,
"authMethod": "LOGIN"
},
"126": {
"host": "smtp.126.com",
"port": 465,
"secure": true
},
"163": {
"host": "smtp.163.com",
"port": 465,
"secure": true
}
}

View File

@@ -72,6 +72,9 @@ class XOAuth2 extends Stream {
let timeout = Math.max(Number(this.options.timeout) || 0, 0);
this.expires = (timeout && Date.now() + timeout * 1000) || 0;
}
this.renewing = false; // Track if renewal is in progress
this.renewalQueue = []; // Queue for pending requests during renewal
}
/**
@@ -82,14 +85,61 @@ class XOAuth2 extends Stream {
*/
getToken(renew, callback) {
if (!renew && this.accessToken && (!this.expires || this.expires > Date.now())) {
this.logger.debug(
{
tnx: 'OAUTH2',
user: this.options.user,
action: 'reuse'
},
'Reusing existing access token for %s',
this.options.user
);
return callback(null, this.accessToken);
}
let generateCallback = (...args) => {
if (args[0]) {
// check if it is possible to renew, if not, return the current token or error
if (!this.provisionCallback && !this.options.refreshToken && !this.options.serviceClient) {
if (this.accessToken) {
this.logger.debug(
{
tnx: 'OAUTH2',
user: this.options.user,
action: 'reuse'
},
'Reusing existing access token (no refresh capability) for %s',
this.options.user
);
return callback(null, this.accessToken);
}
this.logger.error(
{
tnx: 'OAUTH2',
user: this.options.user,
action: 'renew'
},
'Cannot renew access token for %s: No refresh mechanism available',
this.options.user
);
return callback(new Error("Can't create new access token for user"));
}
// If renewal already in progress, queue this request instead of starting another
if (this.renewing) {
return this.renewalQueue.push({ renew, callback });
}
this.renewing = true;
// Handles token renewal completion - processes queued requests and cleans up
const generateCallback = (err, accessToken) => {
this.renewalQueue.forEach(item => item.callback(err, accessToken));
this.renewalQueue = [];
this.renewing = false;
if (err) {
this.logger.error(
{
err: args[0],
err,
tnx: 'OAUTH2',
user: this.options.user,
action: 'renew'
@@ -108,7 +158,8 @@ class XOAuth2 extends Stream {
this.options.user
);
}
callback(...args);
// Complete original request
callback(err, accessToken);
};
if (this.provisionCallback) {
@@ -166,8 +217,8 @@ class XOAuth2 extends Stream {
let token;
try {
token = this.jwtSignRS256(tokenData);
} catch (err) {
return callback(new Error('Can\x27t generate token. Check your auth options'));
} catch (_err) {
return callback(new Error("Can't generate token. Check your auth options"));
}
urlOptions = {
@@ -181,7 +232,7 @@ class XOAuth2 extends Stream {
};
} else {
if (!this.options.refreshToken) {
return callback(new Error('Can\x27t create new access token for user'));
return callback(new Error("Can't create new access token for user"));
}
// web app - https://developers.google.com/identity/protocols/OAuth2WebServer

View File

@@ -1,12 +1,15 @@
{
"name": "nodemailer",
"version": "6.9.14",
"version": "7.0.9",
"description": "Easy as cake e-mail sending from your Node.js applications",
"main": "lib/nodemailer.js",
"scripts": {
"test": "node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js",
"test:coverage": "c8 node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js",
"format": "prettier --write \"**/*.{js,json,md}\"",
"format:check": "prettier --check \"**/*.{js,json,md}\"",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"update": "rm -rf node_modules/ package-lock.json && ncu -u && npm install"
},
"repository": {
@@ -23,19 +26,20 @@
},
"homepage": "https://nodemailer.com/",
"devDependencies": {
"@aws-sdk/client-ses": "3.600.0",
"@aws-sdk/client-sesv2": "3.901.0",
"bunyan": "1.8.15",
"c8": "10.1.2",
"eslint": "8.57.0",
"eslint-config-nodemailer": "1.2.0",
"eslint-config-prettier": "9.1.0",
"c8": "10.1.3",
"eslint": "^9.37.0",
"eslint-config-prettier": "^10.1.8",
"globals": "^16.4.0",
"libbase64": "1.3.0",
"libmime": "5.3.5",
"libqp": "2.1.0",
"libmime": "5.3.7",
"libqp": "2.1.1",
"nodemailer-ntlm-auth": "1.0.4",
"prettier": "^3.6.2",
"proxy": "1.0.2",
"proxy-test-server": "1.0.0",
"smtp-server": "3.13.4"
"smtp-server": "3.14.0"
},
"engines": {
"node": ">=6.0.0"

View File

@@ -22,7 +22,8 @@
"jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1",
"mysql2": "^3.10.3",
"nodemailer": "^6.9.14",
"node-cron": "^4.2.1",
"nodemailer": "^7.0.9",
"pdf-parse": "^1.1.1",
"sequelize": "^6.37.3",
"sharp": "^0.33.5"
@@ -2827,6 +2828,15 @@
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz",
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA=="
},
"node_modules/node-cron": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-4.2.1.tgz",
"integrity": "sha512-lgimEHPE/QDgFlywTd8yTR61ptugX3Qer29efeyWw2rv259HtGBNn1vZVmp8lB9uo9wC0t/AT4iGqXxia+CJFg==",
"license": "ISC",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/node-ensure": {
"version": "0.0.0",
"resolved": "https://registry.npmjs.org/node-ensure/-/node-ensure-0.0.0.tgz",
@@ -2853,9 +2863,10 @@
}
},
"node_modules/nodemailer": {
"version": "6.9.14",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.14.tgz",
"integrity": "sha512-Dobp/ebDKBvz91sbtRKhcznLThrKxKt97GI2FAlAyy+fk19j73Uz3sBXolVtmcXjaorivqsbbbjDY+Jkt4/bQA==",
"version": "7.0.9",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.9.tgz",
"integrity": "sha512-9/Qm0qXIByEP8lEV2qOqcAW7bRpL8CR9jcTwk3NBnHJNmP9fIJ86g2fgmIXqHY+nj55ZEMwWqYAT2QTDpRUYiQ==",
"license": "MIT-0",
"engines": {
"node": ">=6.0.0"
}

View File

@@ -1,7 +1,7 @@
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"main": "server.js",
"type": "module",
"scripts": {
"postinstall": "cd ../frontend && npm install && npm run build",
@@ -26,7 +26,8 @@
"jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1",
"mysql2": "^3.10.3",
"nodemailer": "^6.9.14",
"node-cron": "^4.2.1",
"nodemailer": "^7.0.9",
"pdf-parse": "^1.1.1",
"sequelize": "^6.37.3",
"sharp": "^0.33.5"

View File

@@ -0,0 +1,32 @@
import express from 'express';
import { authenticate } from '../middleware/authMiddleware.js';
import {
getClubTeams,
getClubTeam,
createClubTeam,
updateClubTeam,
deleteClubTeam,
getLeagues
} from '../controllers/clubTeamController.js';
const router = express.Router();
// Get all club teams for a club
router.get('/club/:clubid', authenticate, getClubTeams);
// Create a new club team
router.post('/club/:clubid', authenticate, createClubTeam);
// Get leagues for a club
router.get('/leagues/:clubid', authenticate, getLeagues);
// Get a specific club team
router.get('/:clubteamid', authenticate, getClubTeam);
// Update a club team
router.put('/:clubteamid', authenticate, updateClubTeam);
// Delete a club team
router.delete('/:clubteamid', authenticate, deleteClubTeam);
export default router;

View File

@@ -1,5 +1,5 @@
import express from 'express';
import { uploadCSV, getLeaguesForCurrentSeason, getMatchesForLeagues, getMatchesForLeague } from '../controllers/matchController.js';
import { uploadCSV, getLeaguesForCurrentSeason, getMatchesForLeagues, getMatchesForLeague, getLeagueTable, fetchLeagueTableFromMyTischtennis } from '../controllers/matchController.js';
import { authenticate } from '../middleware/authMiddleware.js';
import multer from 'multer';
@@ -11,6 +11,8 @@ router.post('/import', authenticate, upload.single('file'), uploadCSV);
router.get('/leagues/current/:clubId', authenticate, getLeaguesForCurrentSeason);
router.get('/leagues/:clubId/matches/:leagueId', authenticate, getMatchesForLeague);
router.get('/leagues/:clubId/matches', authenticate, getMatchesForLeagues);
router.get('/leagues/:clubId/table/:leagueId', authenticate, getLeagueTable);
router.post('/leagues/:clubId/table/:leagueId/fetch', authenticate, fetchLeagueTableFromMyTischtennis);
export default router;

View File

@@ -1,4 +1,4 @@
import { getClubMembers, getWaitingApprovals, setClubMembers, uploadMemberImage, getMemberImage, updateRatingsFromMyTischtennis } from '../controllers/memberController.js';
import { getClubMembers, getWaitingApprovals, setClubMembers, uploadMemberImage, getMemberImage, updateRatingsFromMyTischtennis, rotateMemberImage } from '../controllers/memberController.js';
import express from 'express';
import { authenticate } from '../middleware/authMiddleware.js';
import multer from 'multer';
@@ -14,5 +14,6 @@ router.get('/get/:id/:showAll', authenticate, getClubMembers);
router.post('/set/:id', authenticate, setClubMembers);
router.get('/notapproved/:id', authenticate, getWaitingApprovals);
router.post('/update-ratings/:id', authenticate, updateRatingsFromMyTischtennis);
router.post('/rotate-image/:clubId/:memberId', authenticate, rotateMemberImage);
export default router;

View File

@@ -1,5 +1,6 @@
import express from 'express';
import myTischtennisController from '../controllers/myTischtennisController.js';
import myTischtennisUrlController from '../controllers/myTischtennisUrlController.js';
import { authenticate } from '../middleware/authMiddleware.js';
const router = express.Router();
@@ -25,5 +26,26 @@ router.post('/verify', myTischtennisController.verifyLogin);
// GET /api/mytischtennis/session - Get stored session
router.get('/session', myTischtennisController.getSession);
// GET /api/mytischtennis/update-history - Get update ratings history
router.get('/update-history', myTischtennisController.getUpdateHistory);
// GET /api/mytischtennis/fetch-logs - Get fetch logs
router.get('/fetch-logs', myTischtennisController.getFetchLogs);
// GET /api/mytischtennis/latest-fetches - Get latest successful fetches
router.get('/latest-fetches', myTischtennisController.getLatestFetches);
// POST /api/mytischtennis/parse-url - Parse myTischtennis URL
router.post('/parse-url', myTischtennisUrlController.parseUrl);
// POST /api/mytischtennis/configure-team - Configure team from URL
router.post('/configure-team', myTischtennisUrlController.configureTeam);
// POST /api/mytischtennis/fetch-team-data - Manually fetch team data
router.post('/fetch-team-data', myTischtennisUrlController.fetchTeamData);
// GET /api/mytischtennis/team-url/:teamId - Get myTischtennis URL for team
router.get('/team-url/:teamId', myTischtennisUrlController.getTeamUrl);
export default router;

View File

@@ -0,0 +1,28 @@
import express from 'express';
import { authenticate } from '../middleware/authMiddleware.js';
import {
getSeasons,
getCurrentSeason,
createSeason,
getSeason,
deleteSeason
} from '../controllers/seasonController.js';
const router = express.Router();
// Get all seasons
router.get('/', authenticate, getSeasons);
// Get current season (creates if not exists)
router.get('/current', authenticate, getCurrentSeason);
// Get a specific season
router.get('/:seasonid', authenticate, getSeason);
// Create a new season
router.post('/', authenticate, createSeason);
// Delete a season
router.delete('/:seasonid', authenticate, deleteSeason);
export default router;

View File

@@ -0,0 +1,33 @@
import express from 'express';
import { authenticate } from '../middleware/authMiddleware.js';
import {
uploadMiddleware,
uploadDocument,
getDocuments,
getDocument,
downloadDocument,
deleteDocument,
parsePDF
} from '../controllers/teamDocumentController.js';
const router = express.Router();
// Upload eines Dokuments für ein Club-Team
router.post('/club-team/:clubteamid/upload', authenticate, uploadMiddleware, uploadDocument);
// Alle Dokumente für ein Club-Team abrufen
router.get('/club-team/:clubteamid', authenticate, getDocuments);
// Ein spezifisches Dokument abrufen
router.get('/:documentid', authenticate, getDocument);
// Ein Dokument herunterladen
router.get('/:documentid/download', authenticate, downloadDocument);
// Ein Dokument löschen
router.delete('/:documentid', authenticate, deleteDocument);
// PDF parsen und Matches extrahieren
router.post('/:documentid/parse', authenticate, parsePDF);
export default router;

View File

@@ -0,0 +1,32 @@
import express from 'express';
import { authenticate } from '../middleware/authMiddleware.js';
import {
getTeams,
getTeam,
createTeam,
updateTeam,
deleteTeam,
getLeagues
} from '../controllers/teamController.js';
const router = express.Router();
// Get all teams for a club
router.get('/club/:clubid', authenticate, getTeams);
// Get leagues for a club
router.get('/leagues/:clubid', authenticate, getLeagues);
// Get a specific team
router.get('/:teamid', authenticate, getTeam);
// Create a new team
router.post('/club/:clubid', authenticate, createTeam);
// Update a team
router.put('/:teamid', authenticate, updateTeam);
// Delete a team
router.delete('/:teamid', authenticate, deleteTeam);
export default router;

View File

@@ -6,9 +6,9 @@ import cors from 'cors';
import {
User, Log, Club, UserClub, Member, DiaryDate, Participant, Activity, MemberNote,
DiaryNote, DiaryTag, MemberDiaryTag, DiaryDateTag, DiaryMemberNote, DiaryMemberTag,
PredefinedActivity, PredefinedActivityImage, DiaryDateActivity, DiaryMemberActivity, Match, League, Team, Group,
PredefinedActivity, PredefinedActivityImage, DiaryDateActivity, DiaryMemberActivity, Match, League, Team, ClubTeam, TeamDocument, Group,
GroupActivity, Tournament, TournamentGroup, TournamentMatch, TournamentResult,
TournamentMember, Accident, UserToken, OfficialTournament, OfficialCompetition, OfficialCompetitionMember, MyTischtennis
TournamentMember, Accident, UserToken, OfficialTournament, OfficialCompetition, OfficialCompetitionMember, MyTischtennis, MyTischtennisUpdateHistory, MyTischtennisFetchLog
} from './models/index.js';
import authRoutes from './routes/authRoutes.js';
import clubRoutes from './routes/clubRoutes.js';
@@ -34,6 +34,11 @@ import accidentRoutes from './routes/accidentRoutes.js';
import trainingStatsRoutes from './routes/trainingStatsRoutes.js';
import officialTournamentRoutes from './routes/officialTournamentRoutes.js';
import myTischtennisRoutes from './routes/myTischtennisRoutes.js';
import teamRoutes from './routes/teamRoutes.js';
import clubTeamRoutes from './routes/clubTeamRoutes.js';
import teamDocumentRoutes from './routes/teamDocumentRoutes.js';
import seasonRoutes from './routes/seasonRoutes.js';
import schedulerService from './services/schedulerService.js';
const app = express();
const port = process.env.PORT || 3000;
@@ -79,6 +84,10 @@ app.use('/api/accident', accidentRoutes);
app.use('/api/training-stats', trainingStatsRoutes);
app.use('/api/official-tournaments', officialTournamentRoutes);
app.use('/api/mytischtennis', myTischtennisRoutes);
app.use('/api/teams', teamRoutes);
app.use('/api/club-teams', clubTeamRoutes);
app.use('/api/team-documents', teamDocumentRoutes);
app.use('/api/seasons', seasonRoutes);
app.use(express.static(path.join(__dirname, '../frontend/dist')));
@@ -179,9 +188,17 @@ app.get('*', (req, res) => {
await safeSync(Accident);
await safeSync(UserToken);
await safeSync(MyTischtennis);
await safeSync(MyTischtennisUpdateHistory);
await safeSync(MyTischtennisFetchLog);
// Start scheduler service
schedulerService.start();
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
console.log('Scheduler service started:');
console.log(' - Rating updates: 6:00 AM daily');
console.log(' - Match results fetch: 6:30 AM daily');
});
} catch (err) {
console.error('Unable to synchronize the database:', err);

1778
backend/server.log Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,7 @@ import DiaryDate from '../models/DiaryDates.js';
import Member from '../models/Member.js';
import { checkAccess, getUserByToken} from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';
class AccidentService {
async createAccident(userToken, clubId, memberId, diaryDateId, accident) {
await checkAccess(userToken, clubId);
@@ -14,7 +15,7 @@ class AccidentService {
if (!member || member.clubId != clubId) {
throw new Error('Member not found');
}
console.log(diaryDateId);
devLog(diaryDateId);
const diaryDate = await DiaryDate.findByPk(diaryDateId);
if (!diaryDate || diaryDate.clubId != clubId) {
throw new Error('Diary date not found');

View File

@@ -4,6 +4,7 @@ import User from '../models/User.js';
import UserToken from '../models/UserToken.js';
import { sendActivationEmail } from './emailService.js';
import { devLog } from '../utils/logger.js';
const register = async (email, password) => {
try {
const activationCode = Math.random().toString(36).substring(2, 15);
@@ -11,7 +12,7 @@ const register = async (email, password) => {
await sendActivationEmail(email, activationCode);
return user;
} catch (error) {
console.log(error);
devLog(error);
return null;
}
};

View File

@@ -0,0 +1,829 @@
import myTischtennisService from './myTischtennisService.js';
import myTischtennisClient from '../clients/myTischtennisClient.js';
import MyTischtennis from '../models/MyTischtennis.js';
import ClubTeam from '../models/ClubTeam.js';
import League from '../models/League.js';
import Season from '../models/Season.js';
import Member from '../models/Member.js';
import Match from '../models/Match.js';
import Team from '../models/Team.js';
import { Op } from 'sequelize';
import { devLog } from '../utils/logger.js';
class AutoFetchMatchResultsService {
/**
* Execute automatic match results fetching for all users with enabled auto-updates
*/
async executeAutomaticFetch() {
devLog('Starting automatic match results fetch...');
try {
// Find all users with auto-updates enabled
const accounts = await MyTischtennis.findAll({
where: {
autoUpdateRatings: true, // Nutze das gleiche Flag
savePassword: true // Must have saved password
},
attributes: ['id', 'userId', 'email', 'encryptedPassword', 'accessToken', 'expiresAt', 'cookie']
});
devLog(`Found ${accounts.length} accounts with auto-updates enabled for match results`);
if (accounts.length === 0) {
devLog('No accounts found with auto-updates enabled');
return;
}
// Process each account
for (const account of accounts) {
await this.processAccount(account);
}
devLog('Automatic match results fetch completed');
} catch (error) {
console.error('Error in automatic match results fetch:', error);
}
}
/**
* Process a single account for match results fetching
*/
async processAccount(account) {
const startTime = Date.now();
let success = false;
let message = '';
let errorDetails = null;
let fetchedCount = 0;
try {
devLog(`Processing match results for account ${account.email} (User ID: ${account.userId})`);
// Check if session is still valid
if (!account.accessToken || !account.expiresAt || account.expiresAt < Date.now() / 1000) {
devLog(`Session expired for ${account.email}, attempting re-login`);
// Try to re-login with stored password
const password = account.getPassword();
if (!password) {
throw new Error('No stored password available for re-login');
}
const loginResult = await myTischtennisClient.login(account.email, password);
if (!loginResult.success) {
throw new Error(`Re-login failed: ${loginResult.error}`);
}
// Update session data
account.accessToken = loginResult.accessToken;
account.refreshToken = loginResult.refreshToken;
account.expiresAt = loginResult.expiresAt;
account.cookie = loginResult.cookie;
await account.save();
devLog(`Successfully re-logged in for ${account.email}`);
}
// Perform match results fetch
const fetchResult = await this.fetchMatchResults(account);
fetchedCount = fetchResult.fetchedCount || 0;
success = true;
message = `Successfully fetched ${fetchedCount} match results`;
devLog(`Fetched ${fetchedCount} match results for ${account.email}`);
} catch (error) {
success = false;
message = 'Match results fetch failed';
errorDetails = error.message;
console.error(`Error fetching match results for ${account.email}:`, error);
}
const executionTime = Date.now() - startTime;
// TODO: Log the attempt to a dedicated match results history table
devLog(`Match results fetch for ${account.email}: ${success ? 'SUCCESS' : 'FAILED'} (${executionTime}ms)`);
}
/**
* Fetch match results for a specific account
*/
async fetchMatchResults(account) {
devLog(`Fetching match results for ${account.email}`);
let totalFetched = 0;
try {
// Get all teams for this user's clubs that have myTischtennis IDs configured
const teams = await ClubTeam.findAll({
where: {
myTischtennisTeamId: {
[Op.ne]: null
}
},
include: [
{
model: League,
as: 'league',
where: {
myTischtennisGroupId: {
[Op.ne]: null
},
association: {
[Op.ne]: null
}
},
include: [
{
model: Season,
as: 'season'
}
]
}
]
});
devLog(`Found ${teams.length} teams with myTischtennis configuration`);
// Fetch results for each team
for (const team of teams) {
try {
const result = await this.fetchTeamResults(account, team);
totalFetched += result.fetchedCount;
} catch (error) {
console.error(`Error fetching results for team ${team.name}:`, error);
}
}
return {
success: true,
fetchedCount: totalFetched
};
} catch (error) {
console.error('Error in fetchMatchResults:', error);
throw error;
}
}
/**
* Fetch results for a specific team
*/
async fetchTeamResults(account, team) {
const league = team.league;
const season = league.season;
// Build the myTischtennis URL
// Convert full season (e.g. "2025/2026") to short format (e.g. "25/26") for API
const seasonFull = season.season; // e.g. "2025/2026"
const seasonParts = seasonFull.split('/');
const seasonShort = seasonParts.length === 2
? `${seasonParts[0].slice(-2)}/${seasonParts[1].slice(-2)}`
: seasonFull;
const seasonStr = seasonShort.replace('/', '--'); // e.g. "25/26" -> "25--26"
const teamnameEncoded = encodeURIComponent(team.name.replace(/\s/g, '_'));
devLog(`=== FETCH TEAM RESULTS ===`);
devLog(`Team name (from ClubTeam): ${team.name}`);
devLog(`Team name encoded: ${teamnameEncoded}`);
devLog(`MyTischtennis Team ID: ${team.myTischtennisTeamId}`);
let totalProcessed = 0;
try {
// 1. Fetch player statistics (Spielerbilanzen)
const playerStatsUrl = `https://www.mytischtennis.de/click-tt/${league.association}/${seasonStr}/ligen/${league.groupname}/gruppe/${league.myTischtennisGroupId}/mannschaft/${team.myTischtennisTeamId}/${teamnameEncoded}/spielerbilanzen/gesamt?_data=routes%2Fclick-tt%2B%2F%24association%2B%2F%24season%2B%2F%24type%2B%2F%28%24groupname%29.gruppe.%24urlid_.mannschaft.%24teamid.%24teamname%2B%2Fspielerbilanzen.%24filter`;
devLog(`Fetching player stats from: ${playerStatsUrl}`);
const playerStatsResponse = await fetch(playerStatsUrl, {
headers: {
'Cookie': account.cookie || '',
'Authorization': `Bearer ${account.accessToken}`,
'Accept': 'application/json'
}
});
if (playerStatsResponse.ok) {
const playerStatsData = await playerStatsResponse.json();
// Log complete response for debugging
console.log('=== PLAYER STATS RESPONSE START ===');
console.log(JSON.stringify(playerStatsData, null, 2));
console.log('=== PLAYER STATS RESPONSE END ===');
const playerCount = await this.processTeamData(team, playerStatsData);
totalProcessed += playerCount;
devLog(`Processed ${playerCount} player statistics`);
}
// Note: Match results are already included in the player stats response above
// in tableData.meetings_excerpt.meetings, so we don't need a separate call
// Also fetch and update league table data for this team
if (account.userId) {
try {
await this.fetchAndUpdateLeagueTable(account.userId, team.leagueId);
devLog(`✓ League table updated for league ${team.leagueId}`);
} catch (error) {
console.error(`Error updating league table for league ${team.leagueId}:`, error);
// Don't fail the entire process if table update fails
}
} else {
devLog(`Skipping league table update - no userId available`);
}
return {
success: true,
fetchedCount: totalProcessed
};
} catch (error) {
console.error(`Error fetching team results for ${team.name}:`, error);
throw error;
}
}
/**
* Process and store team data from myTischtennis
*/
async processTeamData(team, data) {
// TODO: Implement data processing and storage
// This would typically involve:
// 1. Extract player statistics from data.data.balancesheet
// 2. Match players with local Member records (by player_id or name)
// 3. Update or create match statistics
// 4. Store historical data for tracking changes
devLog(`Processing data for team ${team.name}`);
if (!data.data || !data.data.balancesheet || !Array.isArray(data.data.balancesheet)) {
devLog('No balancesheet data found');
return 0;
}
let processedCount = 0;
for (const teamData of data.data.balancesheet) {
// Process single player statistics
if (teamData.single_player_statistics) {
for (const playerStat of teamData.single_player_statistics) {
devLog(`Player: ${playerStat.player_firstname} ${playerStat.player_lastname} (ID: ${playerStat.player_id})`);
devLog(` Points won: ${playerStat.points_won}, Points lost: ${playerStat.points_lost}`);
// Try to match player with local Member
const member = await this.matchPlayer(
playerStat.player_id,
playerStat.player_firstname,
playerStat.player_lastname
);
if (member) {
devLog(` Matched with local member: ${member.firstName} ${member.lastName} (ID: ${member.id})`);
// Update player statistics (TTR/QTTR would be fetched from different endpoint)
// For now, we just ensure the myTischtennis ID is stored
if (!member.myTischtennisPlayerId) {
member.myTischtennisPlayerId = playerStat.player_id;
await member.save();
devLog(` Updated myTischtennis Player ID for ${member.firstName} ${member.lastName}`);
}
} else {
devLog(` No local member found for ${playerStat.player_firstname} ${playerStat.player_lastname}`);
}
processedCount++;
}
}
// Process double player statistics
if (teamData.double_player_statistics) {
for (const doubleStat of teamData.double_player_statistics) {
devLog(`Double: ${doubleStat.firstname_player_1} ${doubleStat.lastname_player_1} / ${doubleStat.firstname_player_2} ${doubleStat.lastname_player_2}`);
devLog(` Points won: ${doubleStat.points_won}, Points lost: ${doubleStat.points_lost}`);
// TODO: Store double statistics
processedCount++;
}
}
}
// Also process meetings from the player stats response
if (data.data && data.data.balancesheet && data.data.balancesheet[0]) {
const teamData = data.data.balancesheet[0];
// Check for meetings_excerpt in the tableData section
if (data.tableData && data.tableData.meetings_excerpt && data.tableData.meetings_excerpt.meetings) {
devLog('Found meetings_excerpt in tableData, processing matches...');
const meetingsProcessed = await this.processMatchResults(team, { data: data.tableData });
devLog(`Processed ${meetingsProcessed} matches from player stats response`);
}
}
return processedCount;
}
/**
* Process match results from schedule/table data
*/
async processMatchResults(team, data) {
devLog(`Processing match results for team ${team.name}`);
// Handle different response structures from different endpoints
const meetingsExcerpt = data.data?.meetings_excerpt || data.tableData?.meetings_excerpt;
if (!meetingsExcerpt) {
devLog('No meetings_excerpt data found in response');
return 0;
}
let processedCount = 0;
// Handle both response structures:
// 1. With meetings property: meetings_excerpt.meetings (array of date objects)
// 2. Direct array: meetings_excerpt (array of date objects)
const meetings = meetingsExcerpt.meetings || meetingsExcerpt;
if (!Array.isArray(meetings) || meetings.length === 0) {
devLog('No meetings array found or empty');
return 0;
}
devLog(`Found ${meetings.length} items in meetings array`);
// Check if meetings is an array of date objects or an array of match objects
const firstItem = meetings[0];
const isDateGrouped = firstItem && typeof firstItem === 'object' && !firstItem.meeting_id;
if (isDateGrouped) {
// Format 1: Array of date objects (Spielerbilanzen, Spielplan)
devLog('Processing date-grouped meetings...');
for (const dateGroup of meetings) {
for (const [date, matchList] of Object.entries(dateGroup)) {
for (const match of matchList) {
devLog(`Match: ${match.team_home} vs ${match.team_away}`);
devLog(` Date: ${match.date}`);
devLog(` Status: ${match.state} (${match.is_meeting_complete ? 'complete' : 'incomplete'})`);
devLog(` Result: ${match.matches_won}:${match.matches_lost}`);
devLog(` Meeting ID: ${match.meeting_id}`);
try {
await this.storeMatchResult(team, match, false);
processedCount++;
} catch (error) {
console.error(`Error storing match result for meeting ${match.meeting_id}:`, error);
}
}
}
}
} else {
// Format 2: Flat array of match objects (Tabelle)
devLog('Processing flat meetings array...');
for (const match of meetings) {
devLog(`Match: ${match.team_home} vs ${match.team_away}`);
devLog(` Date: ${match.date}`);
devLog(` Status: ${match.state} (${match.is_meeting_complete ? 'complete' : 'incomplete'})`);
devLog(` Result: ${match.matches_won}:${match.matches_lost}`);
devLog(` Meeting ID: ${match.meeting_id}`);
try {
await this.storeMatchResult(team, match, false);
processedCount++;
} catch (error) {
console.error(`Error storing match result for meeting ${match.meeting_id}:`, error);
}
}
}
devLog(`Processed ${processedCount} matches in league ${team.leagueId}`);
return processedCount;
}
/**
* Store or update match result in database
*/
async storeMatchResult(ourClubTeam, matchData, isHomeTeam) {
// Parse match points from myTischtennis data
// matchData.matches_won/lost are ALWAYS from the perspective of team_home in myTischtennis
// So we need to assign them correctly based on whether WE are home or guest
const mtHomePoints = parseInt(matchData.matches_won) || 0;
const mtGuestPoints = parseInt(matchData.matches_lost) || 0;
// If matchData has team_home and team_away, we can determine our role
// But isHomeTeam parameter tells us if WE (ourClubTeam) are playing at home
const homeMatchPoints = mtHomePoints;
const guestMatchPoints = mtGuestPoints;
devLog(`Match points from myTischtennis: ${mtHomePoints}:${mtGuestPoints} (from team_home perspective)`);
// Find existing match by meeting ID OR by date and team names
devLog(`Searching for existing match with meeting ID: ${matchData.meeting_id}`);
let match = await Match.findOne({
where: { myTischtennisMeetingId: matchData.meeting_id }
});
if (match) {
devLog(`Found match by meeting ID: ${match.id}`);
}
// If not found by meeting ID, try to find by date and teams
if (!match) {
devLog(`No match found by meeting ID, searching by date and teams...`);
const matchDate = new Date(matchData.date);
const startOfDay = new Date(matchDate.setHours(0, 0, 0, 0));
const endOfDay = new Date(matchDate.setHours(23, 59, 59, 999));
devLog(`Searching matches on ${matchData.date} in league ${ourClubTeam.leagueId}`);
const potentialMatches = await Match.findAll({
where: {
date: {
[Op.between]: [startOfDay, endOfDay]
},
leagueId: ourClubTeam.leagueId
},
include: [
{ model: Team, as: 'homeTeam' },
{ model: Team, as: 'guestTeam' }
]
});
devLog(`Found ${potentialMatches.length} potential matches on this date`);
// Find by team names
for (const m of potentialMatches) {
devLog(` Checking match ${m.id}: ${m.homeTeam?.name} vs ${m.guestTeam?.name}`);
devLog(` Against: ${matchData.team_home} vs ${matchData.team_away}`);
const homeNameMatch = m.homeTeam?.name === matchData.team_home ||
m.homeTeam?.name.includes(matchData.team_home) ||
matchData.team_home.includes(m.homeTeam?.name);
const guestNameMatch = m.guestTeam?.name === matchData.team_away ||
m.guestTeam?.name.includes(matchData.team_away) ||
matchData.team_away.includes(m.guestTeam?.name);
devLog(` Home match: ${homeNameMatch}, Guest match: ${guestNameMatch}`);
if (homeNameMatch && guestNameMatch) {
match = m;
devLog(` ✓ Found existing match by date and teams: ${match.id}`);
break;
}
}
if (!match) {
devLog(`No existing match found, will create new one`);
}
}
if (match) {
// Update existing match
// IMPORTANT: Check if the teams are in the same order as in myTischtennis
// Load the match with team associations to compare
const matchWithTeams = await Match.findByPk(match.id, {
include: [
{ model: Team, as: 'homeTeam' },
{ model: Team, as: 'guestTeam' }
]
});
// Compare team names to determine if we need to swap points
const dbHomeTeamName = matchWithTeams.homeTeam?.name || '';
const dbGuestTeamName = matchWithTeams.guestTeam?.name || '';
const mtHomeTeamName = matchData.team_home;
const mtGuestTeamName = matchData.team_away;
// Check if teams are in the same order
const teamsMatch = (
dbHomeTeamName === mtHomeTeamName ||
dbHomeTeamName.includes(mtHomeTeamName) ||
mtHomeTeamName.includes(dbHomeTeamName)
);
let finalHomePoints, finalGuestPoints;
if (teamsMatch) {
// Teams are in same order
finalHomePoints = homeMatchPoints;
finalGuestPoints = guestMatchPoints;
devLog(`Teams in same order: ${dbHomeTeamName} = ${mtHomeTeamName}`);
} else {
// Teams are swapped - need to swap points!
finalHomePoints = guestMatchPoints;
finalGuestPoints = homeMatchPoints;
devLog(`Teams are SWAPPED! DB: ${dbHomeTeamName} vs ${dbGuestTeamName}, MyTT: ${mtHomeTeamName} vs ${mtGuestTeamName}`);
devLog(`Swapping points: ${homeMatchPoints}:${guestMatchPoints}${finalHomePoints}:${finalGuestPoints}`);
}
const updateData = {
homeMatchPoints: finalHomePoints,
guestMatchPoints: finalGuestPoints,
isCompleted: matchData.is_meeting_complete,
pdfUrl: matchData.pdf_url,
myTischtennisMeetingId: matchData.meeting_id // Store meeting ID for future updates
};
await match.update(updateData);
devLog(`Updated existing match ${match.id} (Meeting ${matchData.meeting_id}): ${finalHomePoints}:${finalGuestPoints} (${matchData.is_meeting_complete ? 'complete' : 'incomplete'})`);
} else {
// Create new match
devLog(`Creating new match for meeting ${matchData.meeting_id}`);
try {
// Find or create home and guest teams based on myTischtennis team IDs
const homeTeam = await this.findOrCreateTeam(
matchData.team_home,
matchData.team_home_id,
ourClubTeam
);
const guestTeam = await this.findOrCreateTeam(
matchData.team_away,
matchData.team_away_id,
ourClubTeam
);
// Extract time from date
const matchDate = new Date(matchData.date);
const time = `${String(matchDate.getHours()).padStart(2, '0')}:${String(matchDate.getMinutes()).padStart(2, '0')}:00`;
// Create match (points are already correctly set from matchData)
match = await Match.create({
date: matchData.date,
time: time,
locationId: null, // Location is not provided by myTischtennis
homeTeamId: homeTeam.id,
guestTeamId: guestTeam.id,
leagueId: ourClubTeam.leagueId,
clubId: ourClubTeam.clubId,
myTischtennisMeetingId: matchData.meeting_id,
homeMatchPoints: homeMatchPoints,
guestMatchPoints: guestMatchPoints,
isCompleted: matchData.is_meeting_complete,
pdfUrl: matchData.pdf_url
});
devLog(`Created new match ${match.id}: ${matchData.team_home} vs ${matchData.team_away} (${homeMatchPoints}:${guestMatchPoints}, ${matchData.is_meeting_complete ? 'complete' : 'incomplete'})`);
} catch (error) {
console.error(`Error creating match for meeting ${matchData.meeting_id}:`, error);
devLog(` Home: ${matchData.team_home} (myTT ID: ${matchData.team_home_id})`);
devLog(` Guest: ${matchData.team_away} (myTT ID: ${matchData.team_away_id})`);
}
}
return match;
}
/**
* Find or create a Team in the team table
* All teams (own and opponents) are stored in the team table
*/
async findOrCreateTeam(teamName, myTischtennisTeamId, ourClubTeam) {
devLog(`Finding team: ${teamName} (myTT ID: ${myTischtennisTeamId})`);
// Search in team table for all teams in this league
const allTeamsInLeague = await Team.findAll({
where: {
leagueId: ourClubTeam.leagueId,
seasonId: ourClubTeam.seasonId
}
});
devLog(` Searching in ${allTeamsInLeague.length} teams in league ${ourClubTeam.leagueId}`);
// Try exact match first
let team = allTeamsInLeague.find(t => t.name === teamName);
if (team) {
devLog(` ✓ Found team by exact name: ${team.name} (ID: ${team.id})`);
return team;
}
// If not found, try fuzzy match
team = allTeamsInLeague.find(t =>
t.name.includes(teamName) ||
teamName.includes(t.name)
);
if (team) {
devLog(` ✓ Found team by fuzzy match: ${team.name} (ID: ${team.id})`);
return team;
}
// Team not found - create it
team = await Team.create({
name: teamName,
clubId: ourClubTeam.clubId,
leagueId: ourClubTeam.leagueId,
seasonId: ourClubTeam.seasonId
});
devLog(` ✓ Created new team: ${team.name} (ID: ${team.id})`);
return team;
}
/**
* Match a myTischtennis player with a local Member
*/
async matchPlayer(playerId, firstName, lastName) {
// First, try to find by myTischtennis Player ID
if (playerId) {
const member = await Member.findOne({
where: { myTischtennisPlayerId: playerId }
});
if (member) {
return member;
}
}
// If not found, try to match by name (fuzzy matching)
// Note: Since names are encrypted, we need to get all members and decrypt
// This is not efficient for large databases, but works for now
const allMembers = await Member.findAll();
for (const member of allMembers) {
const memberFirstName = member.firstName?.toLowerCase().trim();
const memberLastName = member.lastName?.toLowerCase().trim();
const searchFirstName = firstName?.toLowerCase().trim();
const searchLastName = lastName?.toLowerCase().trim();
if (memberFirstName === searchFirstName && memberLastName === searchLastName) {
return member;
}
}
return null;
}
/**
* Get all accounts with auto-fetch enabled (for manual execution)
*/
async getAutoFetchAccounts() {
return await MyTischtennis.findAll({
where: {
autoUpdateRatings: true
},
attributes: ['userId', 'email', 'autoUpdateRatings']
});
}
/**
* Fetch and update league table data from MyTischtennis
* @param {number} userId - User ID
* @param {number} leagueId - League ID
*/
async fetchAndUpdateLeagueTable(userId, leagueId) {
try {
devLog(`Fetching league table for user ${userId}, league ${leagueId}`);
// Get user's MyTischtennis account
const myTischtennisAccount = await MyTischtennis.findOne({
where: { userId }
});
if (!myTischtennisAccount) {
throw new Error('MyTischtennis account not found');
}
// Get league info
const league = await League.findByPk(leagueId, {
include: [{ model: Season, as: 'season' }]
});
if (!league) {
throw new Error('League not found');
}
// Login to MyTischtennis if needed
let session = await myTischtennisService.getSession(userId);
if (!session || !session.isValid) {
if (!myTischtennisAccount.savePassword) {
throw new Error('MyTischtennis account not connected or session expired');
}
devLog('Session expired, re-logging in...');
await myTischtennisService.verifyLogin(userId);
session = await myTischtennisService.getSession(userId);
}
// Convert full season (e.g. "2025/2026") to short format (e.g. "25/26") and then to URL format (e.g. "25--26")
const seasonFull = league.season.season; // e.g. "2025/2026"
const seasonParts = seasonFull.split('/');
const seasonShort = seasonParts.length === 2
? `${seasonParts[0].slice(-2)}/${seasonParts[1].slice(-2)}`
: seasonFull;
const seasonStr = seasonShort.replace('/', '--'); // e.g. "25/26" -> "25--26"
// Fetch table data from MyTischtennis
const tableUrl = `https://www.mytischtennis.de/click-tt/${league.association}/${seasonStr}/ligen/${league.groupname}/gruppe/${league.myTischtennisGroupId}/tabelle/gesamt?_data=routes%2Fclick-tt%2B%2F%24association%2B%2F%24season%2B%2F%24type%2B%2F%24groupname.gruppe.%24urlid%2B%2Ftabelle.%24filter`;
console.log(`[fetchAndUpdateLeagueTable] Fetching table from URL: ${tableUrl}`);
const response = await myTischtennisClient.authenticatedRequest(tableUrl, session.cookie, {
method: 'GET'
});
if (!response.success) {
throw new Error(`Failed to fetch table data: ${response.error}`);
}
const tableData = await this.parseTableData(JSON.stringify(response.data), leagueId);
// Update teams with table data
await this.updateTeamsWithTableData(tableData, leagueId);
devLog(`✓ Updated league table for league ${leagueId} with ${tableData.length} teams`);
} catch (error) {
console.error(`Error fetching league table for league ${leagueId}:`, error);
throw error;
}
}
/**
* Parse table data from MyTischtennis response
* @param {string} jsonResponse - JSON response from MyTischtennis
* @param {number} leagueId - League ID
* @returns {Array} Parsed table data
*/
async parseTableData(jsonResponse, leagueId) {
devLog('Parsing table data from MyTischtennis response...');
try {
const data = JSON.parse(jsonResponse);
if (!data.data || !data.data.league_table) {
devLog('No league table data found in response');
return [];
}
const leagueTable = data.data.league_table;
const parsedData = [];
for (const teamData of leagueTable) {
parsedData.push({
teamName: teamData.team_name,
matchesPlayed: teamData.matches_won + teamData.matches_lost,
matchesWon: teamData.matches_won,
matchesLost: teamData.matches_lost,
matchesTied: teamData.meetings_tie || 0, // Unentschiedene Begegnungen
setsWon: teamData.sets_won,
setsLost: teamData.sets_lost,
pointsWon: teamData.games_won, // MyTischtennis uses "games" for Ballpunkte
pointsLost: teamData.games_lost,
tablePointsWon: teamData.points_won, // Liga-Tabellenpunkte gewonnen
tablePointsLost: teamData.points_lost, // Liga-Tabellenpunkte verloren
tableRank: teamData.table_rank
});
}
devLog(`Parsed ${parsedData.length} teams from MyTischtennis table data`);
return parsedData;
} catch (error) {
console.error('Error parsing MyTischtennis table data:', error);
return [];
}
}
/**
* Update teams with table data
* @param {Array} tableData - Parsed table data
* @param {number} leagueId - League ID
*/
async updateTeamsWithTableData(tableData, leagueId) {
for (const teamData of tableData) {
try {
// Find team by name in this league
const team = await Team.findOne({
where: {
leagueId: leagueId,
name: { [Op.like]: `%${teamData.teamName}%` }
}
});
if (team) {
await team.update({
matchesPlayed: teamData.matchesPlayed || 0,
matchesWon: teamData.matchesWon || 0,
matchesLost: teamData.matchesLost || 0,
matchesTied: teamData.matchesTied || 0,
setsWon: teamData.setsWon || 0,
setsLost: teamData.setsLost || 0,
pointsWon: teamData.pointsWon || 0,
pointsLost: teamData.pointsLost || 0,
tablePoints: (teamData.tablePointsWon || 0), // Legacy field (keep for compatibility)
tablePointsWon: teamData.tablePointsWon || 0,
tablePointsLost: teamData.tablePointsLost || 0
});
devLog(` ✓ Updated team ${team.name} with table data`);
} else {
devLog(` ⚠ Team not found: ${teamData.teamName}`);
}
} catch (error) {
console.error(`Error updating team ${teamData.teamName}:`, error);
}
}
}
}
export default new AutoFetchMatchResultsService();

View File

@@ -0,0 +1,141 @@
import myTischtennisService from './myTischtennisService.js';
import myTischtennisClient from '../clients/myTischtennisClient.js';
import MyTischtennis from '../models/MyTischtennis.js';
import { devLog } from '../utils/logger.js';
class AutoUpdateRatingsService {
/**
* Execute automatic rating updates for all users with enabled auto-updates
*/
async executeAutomaticUpdates() {
devLog('Starting automatic rating updates...');
try {
// Find all users with auto-updates enabled
const accounts = await MyTischtennis.findAll({
where: {
autoUpdateRatings: true,
savePassword: true // Must have saved password
},
attributes: ['id', 'userId', 'email', 'encryptedPassword', 'accessToken', 'expiresAt', 'cookie']
});
devLog(`Found ${accounts.length} accounts with auto-updates enabled`);
if (accounts.length === 0) {
devLog('No accounts found with auto-updates enabled');
return;
}
// Process each account
for (const account of accounts) {
await this.processAccount(account);
}
devLog('Automatic rating updates completed');
} catch (error) {
console.error('Error in automatic rating updates:', error);
}
}
/**
* Process a single account for rating updates
*/
async processAccount(account) {
const startTime = Date.now();
let success = false;
let message = '';
let errorDetails = null;
let updatedCount = 0;
try {
devLog(`Processing account ${account.email} (User ID: ${account.userId})`);
// Check if session is still valid
if (!account.accessToken || !account.expiresAt || account.expiresAt < Date.now() / 1000) {
devLog(`Session expired for ${account.email}, attempting re-login`);
// Try to re-login with stored password
const password = account.getPassword();
if (!password) {
throw new Error('No stored password available for re-login');
}
const loginResult = await myTischtennisClient.login(account.email, password);
if (!loginResult.success) {
throw new Error(`Re-login failed: ${loginResult.error}`);
}
// Update session data
account.accessToken = loginResult.accessToken;
account.refreshToken = loginResult.refreshToken;
account.expiresAt = loginResult.expiresAt;
account.cookie = loginResult.cookie;
await account.save();
devLog(`Successfully re-logged in for ${account.email}`);
}
// Perform rating update
const updateResult = await this.updateRatings(account);
updatedCount = updateResult.updatedCount || 0;
success = true;
message = `Successfully updated ${updatedCount} ratings`;
devLog(`Updated ${updatedCount} ratings for ${account.email}`);
} catch (error) {
success = false;
message = 'Update failed';
errorDetails = error.message;
console.error(`Error updating ratings for ${account.email}:`, error);
}
const executionTime = Date.now() - startTime;
// Log the attempt
await myTischtennisService.logUpdateAttempt(
account.userId,
success,
message,
errorDetails,
updatedCount,
executionTime
);
}
/**
* Update ratings for a specific account
*/
async updateRatings(account) {
// TODO: Implement actual rating update logic
// This would typically involve:
// 1. Fetching current ratings from myTischtennis
// 2. Comparing with local data
// 3. Updating local member ratings
devLog(`Updating ratings for ${account.email}`);
// For now, simulate an update
await new Promise(resolve => setTimeout(resolve, 1000));
return {
success: true,
updatedCount: Math.floor(Math.random() * 10) // Simulate some updates
};
}
/**
* Get all accounts with auto-updates enabled (for manual execution)
*/
async getAutoUpdateAccounts() {
return await MyTischtennis.findAll({
where: {
autoUpdateRatings: true
},
attributes: ['userId', 'email', 'autoUpdateRatings', 'lastUpdateRatings']
});
}
}
export default new AutoUpdateRatingsService();

View File

@@ -0,0 +1,183 @@
import ClubTeam from '../models/ClubTeam.js';
import League from '../models/League.js';
import Season from '../models/Season.js';
import SeasonService from './seasonService.js';
import { devLog } from '../utils/logger.js';
class ClubTeamService {
/**
* Holt alle ClubTeams für einen Verein, optional gefiltert nach Saison.
* Wenn keine Saison-ID angegeben ist, wird die aktuelle Saison verwendet.
* @param {number} clubId - Die ID des Vereins.
* @param {number|null} seasonId - Optionale Saison-ID.
* @returns {Promise<Array<ClubTeam>>} Eine Liste von ClubTeams.
*/
static async getAllClubTeamsByClub(clubId, seasonId = null) {
try {
// Wenn keine Saison angegeben, verwende die aktuelle
if (!seasonId) {
const currentSeason = await SeasonService.getOrCreateCurrentSeason();
seasonId = currentSeason.id;
}
const clubTeams = await ClubTeam.findAll({
where: { clubId, seasonId },
order: [['name', 'ASC']]
});
// Manuelle Datenanreicherung für Liga und Saison
const enrichedClubTeams = [];
for (const clubTeam of clubTeams) {
const enrichedTeam = {
id: clubTeam.id,
name: clubTeam.name,
clubId: clubTeam.clubId,
leagueId: clubTeam.leagueId,
seasonId: clubTeam.seasonId,
myTischtennisTeamId: clubTeam.myTischtennisTeamId,
createdAt: clubTeam.createdAt,
updatedAt: clubTeam.updatedAt,
league: { name: 'Unbekannt' },
season: { season: 'Unbekannt' }
};
// Lade Liga-Daten
if (clubTeam.leagueId) {
const league = await League.findByPk(clubTeam.leagueId, {
attributes: ['id', 'name', 'myTischtennisGroupId', 'association', 'groupname']
});
if (league) enrichedTeam.league = league;
}
// Lade Saison-Daten
if (clubTeam.seasonId) {
const season = await Season.findByPk(clubTeam.seasonId, { attributes: ['season'] });
if (season) enrichedTeam.season = season;
}
enrichedClubTeams.push(enrichedTeam);
}
return enrichedClubTeams;
} catch (error) {
console.error('[ClubTeamService.getAllClubTeamsByClub] - Error:', error);
throw error;
}
}
/**
* Holt ein ClubTeam anhand seiner ID
* @param {number} clubTeamId - Die ID des ClubTeams
* @returns {Promise<ClubTeam|null>} Das ClubTeam oder null, wenn nicht gefunden
*/
static async getClubTeamById(clubTeamId) {
try {
const clubTeam = await ClubTeam.findByPk(clubTeamId, {
include: [
{
model: League,
as: 'league',
attributes: ['id', 'name']
},
{
model: Season,
as: 'season',
attributes: ['id', 'season']
}
]
});
return clubTeam;
} catch (error) {
console.error('[ClubTeamService.getClubTeamById] - Error:', error);
throw error;
}
}
/**
* Erstellt ein neues ClubTeam.
* Wenn keine Saison-ID angegeben ist, wird die aktuelle Saison zugewiesen.
* @param {object} clubTeamData - Die Daten des neuen ClubTeams (name, clubId, optional leagueId, seasonId).
* @returns {Promise<ClubTeam>} Das erstellte ClubTeam.
*/
static async createClubTeam(clubTeamData) {
try {
// Wenn keine Saison angegeben, verwende die aktuelle
if (!clubTeamData.seasonId) {
const currentSeason = await SeasonService.getOrCreateCurrentSeason();
clubTeamData.seasonId = currentSeason.id;
}
const clubTeam = await ClubTeam.create(clubTeamData);
return clubTeam;
} catch (error) {
console.error('[ClubTeamService.createClubTeam] - Error:', error);
throw error;
}
}
/**
* Aktualisiert ein bestehendes ClubTeam.
* @param {number} clubTeamId - Die ID des zu aktualisierenden ClubTeams.
* @param {object} updateData - Die zu aktualisierenden Daten.
* @returns {Promise<boolean>} True, wenn das ClubTeam aktualisiert wurde, sonst false.
*/
static async updateClubTeam(clubTeamId, updateData) {
try {
const [updatedRowsCount] = await ClubTeam.update(updateData, {
where: { id: clubTeamId }
});
return updatedRowsCount > 0;
} catch (error) {
console.error('[ClubTeamService.updateClubTeam] - Error:', error);
throw error;
}
}
/**
* Löscht ein ClubTeam.
* @param {number} clubTeamId - Die ID des zu löschenden ClubTeams.
* @returns {Promise<boolean>} True, wenn das ClubTeam gelöscht wurde, sonst false.
*/
static async deleteClubTeam(clubTeamId) {
try {
const deletedRows = await ClubTeam.destroy({
where: { id: clubTeamId }
});
return deletedRows > 0;
} catch (error) {
console.error('[ClubTeamService.deleteClubTeam] - Error:', error);
throw error;
}
}
/**
* Holt alle Ligen für einen Verein, optional gefiltert nach Saison.
* Wenn keine Saison-ID angegeben ist, wird die aktuelle Saison verwendet.
* @param {number} clubId - Die ID des Vereins.
* @param {number|null} seasonId - Optionale Saison-ID.
* @returns {Promise<Array<League>>} Eine Liste von Ligen.
*/
static async getLeaguesByClub(clubId, seasonId = null) {
try {
// Wenn keine Saison angegeben, verwende die aktuelle
if (!seasonId) {
const currentSeason = await SeasonService.getOrCreateCurrentSeason();
seasonId = currentSeason.id;
}
const leagues = await League.findAll({
where: { clubId, seasonId },
attributes: ['id', 'name', 'seasonId'],
order: [['name', 'ASC']]
});
return leagues;
} catch (error) {
console.error('[ClubTeamService.getLeaguesByClub] - Error:', error);
throw error;
}
}
}
export default ClubTeamService;

View File

@@ -6,12 +6,11 @@ import PredefinedActivityImage from '../models/PredefinedActivityImage.js';
import { checkAccess } from '../utils/userUtils.js';
import { Op } from 'sequelize';
import { devLog } from '../utils/logger.js';
class DiaryDateActivityService {
async createActivity(userToken, clubId, data) {
console.log('[DiaryDateActivityService::createActivity] - check user access');
await checkAccess(userToken, clubId);
console.log('[DiaryDateActivityService::createActivity] - add: ', data);
const { activity, ...restData } = data;
// Versuche, die PredefinedActivity robust zu finden:
// 1) per übergebener ID
@@ -59,23 +58,18 @@ class DiaryDateActivityService {
});
const newOrderId = maxOrderId !== null ? maxOrderId + 1 : 1;
restData.orderId = newOrderId;
console.log('[DiaryDateActivityService::createActivity] - create diary date activity');
return await DiaryDateActivity.create(restData);
}
async updateActivity(userToken, clubId, id, data) {
console.log('[DiaryDateActivityService::updateActivity] - check user access');
await checkAccess(userToken, clubId);
console.log('[DiaryDateActivityService::updateActivity] - load activity', id);
const activity = await DiaryDateActivity.findByPk(id);
if (!activity) {
console.log('[DiaryDateActivityService::updateActivity] - activity not found');
throw new Error('Activity not found');
}
// Wenn customActivityName gesendet wird, müssen wir die PredefinedActivity behandeln
if (data.customActivityName) {
console.log('[DiaryDateActivityService::updateActivity] - handling customActivityName:', data.customActivityName);
// Suche nach einer existierenden PredefinedActivity mit diesem Namen
let predefinedActivity = await PredefinedActivity.findOne({
@@ -84,7 +78,6 @@ class DiaryDateActivityService {
if (!predefinedActivity) {
// Erstelle eine neue PredefinedActivity
console.log('[DiaryDateActivityService::updateActivity] - creating new PredefinedActivity');
predefinedActivity = await PredefinedActivity.create({
name: data.customActivityName,
description: data.description || '',
@@ -99,7 +92,6 @@ class DiaryDateActivityService {
delete data.customActivityName;
}
console.log('[DiaryDateActivityService::updateActivity] - update activity', clubId, id, data, JSON.stringify(data));
return await activity.update(data);
}
@@ -113,22 +105,14 @@ class DiaryDateActivityService {
}
async updateActivityOrder(userToken, clubId, id, newOrderId) {
console.log(`[DiaryDateActivityService::updateActivityOrder] - Start update for activity id: ${id}`);
console.log(`[DiaryDateActivityService::updateActivityOrder] - User token: ${userToken}, Club id: ${clubId}, New order id: ${newOrderId}`);
console.log('[DiaryDateActivityService::updateActivityOrder] - Checking user access');
await checkAccess(userToken, clubId);
console.log('[DiaryDateActivityService::updateActivityOrder] - User access confirmed');
console.log(`[DiaryDateActivityService::updateActivityOrder] - Finding activity with id: ${id}`);
const activity = await DiaryDateActivity.findByPk(id);
if (!activity) {
console.error('[DiaryDateActivityService::updateActivityOrder] - Activity not found, throwing error');
throw new Error('Activity not found');
}
console.log('[DiaryDateActivityService::updateActivityOrder] - Activity found:', activity);
const currentOrderId = activity.orderId;
console.log(`[DiaryDateActivityService::updateActivityOrder] - Current order id: ${currentOrderId}`);
if (newOrderId < currentOrderId) {
console.log(`[DiaryDateActivityService::updateActivityOrder] - Shifting items down. Moving activities with orderId between ${newOrderId} and ${currentOrderId - 1}`);
await DiaryDateActivity.increment(
{ orderId: 1 },
{
@@ -138,9 +122,7 @@ class DiaryDateActivityService {
},
}
);
console.log(`[DiaryDateActivityService::updateActivityOrder] - Items shifted down`);
} else if (newOrderId > currentOrderId) {
console.log(`[DiaryDateActivityService::updateActivityOrder] - Shifting items up. Moving activities with orderId between ${currentOrderId + 1} and ${newOrderId}`);
await DiaryDateActivity.decrement(
{ orderId: 1 },
{
@@ -150,16 +132,10 @@ class DiaryDateActivityService {
},
}
);
console.log(`[DiaryDateActivityService::updateActivityOrder] - Items shifted up`);
} else {
console.log('[DiaryDateActivityService::updateActivityOrder] - New order id is the same as the current order id. No shift required.');
}
console.log(`[DiaryDateActivityService::updateActivityOrder] - Setting new order id for activity id: ${id}`);
activity.orderId = newOrderId;
console.log('[DiaryDateActivityService::updateActivityOrder] - Saving activity with new order id');
const savedActivity = await activity.save();
console.log('[DiaryDateActivityService::updateActivityOrder] - Activity saved:', savedActivity);
console.log(`[DiaryDateActivityService::updateActivityOrder] - Finished update for activity id: ${id}`);
return savedActivity;
}
@@ -256,9 +232,7 @@ class DiaryDateActivityService {
}
async addGroupActivity(userToken, clubId, diaryDateId, groupId, activity) {
console.log('[DiaryDateActivityService::addGroupActivity] Check user access');
await checkAccess(userToken, clubId);
console.log('[DiaryDateActivityService::addGroupActivity] Check diary date');
const diaryDateActivity = await DiaryDateActivity.findOne({
where: {
diaryDateId,
@@ -271,26 +245,23 @@ class DiaryDateActivityService {
console.error('[DiaryDateActivityService::addGroupActivity] Activity not found');
throw new Error('Activity not found');
}
console.log('[DiaryDateActivityService::addGroupActivity] Check group');
const group = await Group.findByPk(groupId);
if (!group || group.diaryDateId !== diaryDateActivity.diaryDateId) {
console.error('[DiaryDateActivityService::addGroupActivity] Group and date don\'t fit');
throw new Error('Group isn\'t related to date');
}
console.log('[DiaryDateActivityService::addGroupActivity] Get predefined activity');
const [predefinedActivity, created] = await PredefinedActivity.findOrCreate({
where: {
name: activity
}
});
console.log('[DiaryDateActivityService::addGroupActivity] Add group activity');
console.log(predefinedActivity);
devLog(predefinedActivity);
const activityData = {
diaryDateActivity: diaryDateActivity.id,
groupId: groupId,
customActivity: predefinedActivity.id
}
console.log(activityData);
devLog(activityData);
return await GroupActivity.create(activityData);
}
}

View File

@@ -6,6 +6,7 @@ import Member from "../models/Member.js";
import { checkAccess } from '../utils/userUtils.js';
import { Op, literal } from "sequelize";
import { devLog } from '../utils/logger.js';
class DiaryDateTagService {
async getDiaryDateMemberTags(userToken, clubId, memberId) {
await checkAccess(userToken, clubId);
@@ -35,7 +36,7 @@ class DiaryDateTagService {
}
async addDiaryDateTag(userToken, clubId, diaryDateId, memberId, tag) {
console.log(userToken, clubId, diaryDateId, memberId, tag);
devLog(userToken, clubId, diaryDateId, memberId, tag);
await checkAccess(userToken, clubId);
const tagObject = await DiaryTag.findOne({ where: { id: tag.id } });
if (!tagObject) {

View File

@@ -3,6 +3,7 @@ import DiaryMemberTag from '../models/DiaryMemberTag.js';
import { DiaryTag } from '../models/DiaryTag.js';
import { checkAccess } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';
class DiaryMemberService {
async addNoteToMember(userToken, clubId, diaryDateId, memberId, content) {
await checkAccess(userToken, clubId);
@@ -14,7 +15,7 @@ class DiaryMemberService {
async getNotesForMember(userToken, clubId, diaryDateId, memberId) {
await checkAccess(userToken, clubId);
console.log(clubId, diaryDateId, memberId);
devLog(clubId, diaryDateId, memberId);
return await DiaryMemberNote.findAll({ where: { diaryDateId, memberId }, order: [['createdAt', 'DESC']] });
}
@@ -50,7 +51,7 @@ class DiaryMemberService {
if (tagLink) {
await tagLink.destroy();
} else {
console.log(diaryDateId, memberId, tagId);
devLog(diaryDateId, memberId, tagId);
throw new Error('Das Tag ist nicht verknüpft.');
}
}

View File

@@ -7,16 +7,14 @@ import DiaryDateTag from '../models/DiaryDateTag.js';
import { checkAccess } from '../utils/userUtils.js';
import HttpError from '../exceptions/HttpError.js';
import { devLog } from '../utils/logger.js';
class DiaryService {
async getDatesForClub(userToken, clubId) {
console.log('[DiaryService::getDatesForClub] - Check user access');
await checkAccess(userToken, clubId);
console.log('[DiaryService::getDatesForClub] - Validate club existence');
const club = await Club.findByPk(clubId);
if (!club) {
throw new HttpError('Club not found', 404);
}
console.log('[DiaryService::getDatesForClub] - Load diary dates');
const dates = await DiaryDate.findAll({
where: { clubId },
include: [
@@ -29,14 +27,11 @@ class DiaryService {
}
async createDateForClub(userToken, clubId, date, trainingStart, trainingEnd) {
console.log('[DiaryService::createDateForClub] - Check user access');
await checkAccess(userToken, clubId);
console.log('[DiaryService::createDateForClub] - Validate club existence');
const club = await Club.findByPk(clubId);
if (!club) {
throw new HttpError('Club not found', 404);
}
console.log('[DiaryService::createDateForClub] - Validate date');
const parsedDate = new Date(date);
if (isNaN(parsedDate.getTime())) {
throw new HttpError('Invalid date format', 400);
@@ -44,7 +39,6 @@ class DiaryService {
if (trainingStart && trainingEnd && trainingStart >= trainingEnd) {
throw new HttpError('Training start time must be before training end time', 400);
}
console.log('[DiaryService::createDateForClub] - Create new diary date');
const newDate = await DiaryDate.create({
date: parsedDate,
clubId,
@@ -56,9 +50,7 @@ class DiaryService {
}
async updateTrainingTimes(userToken, clubId, dateId, trainingStart, trainingEnd) {
console.log('[DiaryService::updateTrainingTimes] - Check user access');
await checkAccess(userToken, clubId);
console.log('[DiaryService::updateTrainingTimes] - Validate date');
const diaryDate = await DiaryDate.findOne({ where: { clubId, id: dateId } });
if (!diaryDate) {
throw new HttpError('Diary entry not found', 404);
@@ -66,7 +58,6 @@ class DiaryService {
if (trainingStart && trainingEnd && trainingStart >= trainingEnd) {
throw new HttpError('Training start time must be before training end time', 400);
}
console.log('[DiaryService::updateTrainingTimes] - Update training times');
diaryDate.trainingStart = trainingStart || null;
diaryDate.trainingEnd = trainingEnd || null;
await diaryDate.save();
@@ -74,14 +65,12 @@ class DiaryService {
}
async addNoteToDate(userToken, diaryDateId, content) {
console.log('[DiaryService::addNoteToDate] - Add note');
await checkAccess(userToken, diaryDateId);
await DiaryNote.create({ diaryDateId, content });
return await DiaryNote.findAll({ where: { diaryDateId }, order: [['createdAt', 'DESC']] });
}
async deleteNoteFromDate(userToken, noteId) {
console.log('[DiaryService::deleteNoteFromDate] - Delete note');
const note = await DiaryNote.findByPk(noteId);
if (!note) {
throw new HttpError('Note not found', 404);
@@ -92,7 +81,6 @@ class DiaryService {
}
async addTagToDate(userToken, diaryDateId, tagName) {
console.log('[DiaryService::addTagToDate] - Add tag');
await checkAccess(userToken, diaryDateId);
let tag = await DiaryTag.findOne({ where: { name: tagName } });
if (!tag) {
@@ -105,29 +93,24 @@ class DiaryService {
async addTagToDiaryDate(userToken, clubId, diaryDateId, tagId) {
checkAccess(userToken, clubId);
console.log(`[DiaryService::addTagToDiaryDate] - diaryDateId: ${diaryDateId}, tagId: ${tagId}`);
const diaryDate = await DiaryDate.findByPk(diaryDateId);
if (!diaryDate) {
throw new HttpError('DiaryDate not found', 404);
}
console.log('[DiaryService::addTagToDiaryDate] - Add tag to diary date');
const existingEntry = await DiaryDateTag.findOne({
where: { diaryDateId, tagId }
});
if (existingEntry) {
return;
}
console.log('[DiaryService::addTagToDiaryDate] - Tag not found, creating new entry');
const tag = await DiaryTag.findByPk(tagId);
if (!tag) {
throw new HttpError('Tag not found', 404);
}
console.log('[DiaryService::addTagToDiaryDate] - Add tag to diary date');
await DiaryDateTag.create({
diaryDateId,
tagId
});
console.log('[DiaryService::addTagToDiaryDate] - Get tags');
const tags = await DiaryDateTag.findAll({ where: {
diaryDateId: diaryDateId },
include: {
@@ -135,12 +118,11 @@ class DiaryService {
as: 'tag'
}
});
console.log(tags);
devLog(tags);
return tags.map(tag => tag.tag);
}
async getDiaryNotesForDateAndMember(diaryDateId, memberId) {
console.log('[DiaryService::getDiaryNotesForDateAndMember] - Fetching notes');
return await DiaryNote.findAll({
where: { diaryDateId, memberId },
order: [['createdAt', 'DESC']]
@@ -153,19 +135,15 @@ class DiaryService {
}
async removeDateForClub(userToken, clubId, dateId) {
console.log('[DiaryService::removeDateForClub] - Check user access');
await checkAccess(userToken, clubId);
console.log('[DiaryService::removeDateForClub] - Validate date');
const diaryDate = await DiaryDate.findOne({ where: { id: dateId, clubId } });
if (!diaryDate) {
throw new HttpError('Diary entry not found', 404);
}
console.log('[DiaryService::removeDateForClub] - Check for activities');
const activityCount = await DiaryDateActivity.count({ where: { diaryDateId: dateId } });
if (activityCount > 0) {
throw new HttpError('Cannot delete date with activities', 409);
}
console.log('[DiaryService::removeDateForClub] - Delete diary date');
await diaryDate.destroy();
return { ok: true };
}

View File

@@ -3,6 +3,7 @@ import DiaryDate from '../models/DiaryDates.js';
import HttpError from '../exceptions/HttpError.js';
import Group from '../models/Group.js';
import { devLog } from '../utils/logger.js';
class GroupService {
async checkDiaryDateToClub(clubId, dateId) {
@@ -40,7 +41,7 @@ class GroupService {
}
async changeGroup(userToken, groupId, clubId, dateId, name, lead) {
console.log("changeGroup: ", groupId, clubId, dateId, name, lead);
devLog("changeGroup: ", groupId, clubId, dateId, name, lead);
await checkAccess(userToken, clubId);
await this.checkDiaryDateToClub(clubId, dateId);
const group = await Group.findOne({

View File

@@ -0,0 +1,94 @@
import League from '../models/League.js';
import Season from '../models/Season.js';
import SeasonService from './seasonService.js';
import { devLog } from '../utils/logger.js';
class LeagueService {
static async getAllLeaguesByClub(clubId, seasonId = null) {
try {
// Wenn keine Saison angegeben, verwende die aktuelle
if (!seasonId) {
const currentSeason = await SeasonService.getOrCreateCurrentSeason();
seasonId = currentSeason.id;
}
const leagues = await League.findAll({
where: { clubId, seasonId },
include: [
{
model: Season,
as: 'season',
attributes: ['id', 'season']
}
],
order: [['name', 'ASC']]
});
return leagues;
} catch (error) {
console.error('[LeagueService.getAllLeaguesByClub] - Error:', error);
throw error;
}
}
static async getLeagueById(leagueId) {
try {
const league = await League.findByPk(leagueId, {
include: [
{
model: Season,
as: 'season',
attributes: ['id', 'season']
}
]
});
return league;
} catch (error) {
console.error('[LeagueService.getLeagueById] - Error:', error);
throw error;
}
}
static async createLeague(leagueData) {
try {
// Wenn keine Saison angegeben, verwende die aktuelle
if (!leagueData.seasonId) {
const currentSeason = await SeasonService.getOrCreateCurrentSeason();
leagueData.seasonId = currentSeason.id;
}
const league = await League.create(leagueData);
return league;
} catch (error) {
console.error('[LeagueService.createLeague] - Error:', error);
throw error;
}
}
static async updateLeague(leagueId, updateData) {
try {
const [updatedRowsCount] = await League.update(updateData, {
where: { id: leagueId }
});
return updatedRowsCount > 0;
} catch (error) {
console.error('[LeagueService.updateLeague] - Error:', error);
throw error;
}
}
static async deleteLeague(leagueId) {
try {
const deletedRowsCount = await League.destroy({
where: { id: leagueId }
});
return deletedRowsCount > 0;
} catch (error) {
console.error('[LeagueService.deleteLeague] - Error:', error);
throw error;
}
}
}
export default LeagueService;

View File

@@ -7,11 +7,55 @@ import Season from '../models/Season.js';
import Location from '../models/Location.js';
import League from '../models/League.js';
import Team from '../models/Team.js';
import ClubTeam from '../models/ClubTeam.js';
import Club from '../models/Club.js';
import SeasonService from './seasonService.js';
import { checkAccess } from '../utils/userUtils.js';
import { Op } from 'sequelize';
import { devLog } from '../utils/logger.js';
class MatchService {
/**
* Format team name with age class suffix
* @param {string} teamName - Base team name (e.g. "Harheimer TC")
* @param {string} ageClass - Age class (e.g. "Jugend 11", "Senioren", "Frauen", "Erwachsene")
* @returns {string} Formatted team name (e.g. "Harheimer TC (J11)")
*/
formatTeamNameWithAgeClass(teamName, ageClass) {
if (!ageClass || ageClass.trim() === '' || ageClass === 'Erwachsene') {
return teamName;
}
// Parse age class
const ageClassLower = ageClass.toLowerCase().trim();
// Senioren = S
if (ageClassLower.includes('senioren')) {
return `${teamName} (S)`;
}
// Frauen = F
if (ageClassLower.includes('frauen')) {
return `${teamName} (F)`;
}
// Jugend XX = JXX
const jugendMatch = ageClass.match(/jugend\s+(\d+)/i);
if (jugendMatch) {
return `${teamName} (J${jugendMatch[1]})`;
}
// Mädchen XX = MXX
const maedchenMatch = ageClass.match(/m[aä]dchen\s+(\d+)/i);
if (maedchenMatch) {
return `${teamName} (M${maedchenMatch[1]})`;
}
// Default: return as is
return teamName;
}
generateSeasonString(date = new Date()) {
const currentYear = date.getFullYear();
let seasonStartYear;
@@ -21,8 +65,7 @@ class MatchService {
seasonStartYear = currentYear - 1;
}
const seasonEndYear = seasonStartYear + 1;
const seasonEndYearString = seasonEndYear.toString().slice(-2);
return `${seasonStartYear}/${seasonEndYearString}`;
return `${seasonStartYear}/${seasonEndYear}`;
}
async importCSV(userToken, clubId, filePath) {
@@ -46,8 +89,20 @@ class MatchService {
seasonId: season.id,
},
});
const homeTeamId = await this.getOrCreateTeamId(row['HeimMannschaft'], clubId);
const guestTeamId = await this.getOrCreateTeamId(row['GastMannschaft'], clubId);
const homeTeamId = await this.getOrCreateTeamId(
row['HeimMannschaft'],
row['HeimMannschaftAltersklasse'],
clubId,
league.id,
season.id
);
const guestTeamId = await this.getOrCreateTeamId(
row['GastMannschaft'],
row['GastMannschaftAltersklasse'],
clubId,
league.id,
season.id
);
const [location] = await Location.findOrCreate({
where: {
name: row['HalleName'],
@@ -57,7 +112,6 @@ class MatchService {
},
});
matches.push({
seasonId: season.id,
date: parsedDate,
time: row['Termin'].split(' ')[1],
homeTeamId: homeTeamId,
@@ -71,60 +125,71 @@ class MatchService {
if (seasonString) {
season = await Season.findOne({ where: { season: seasonString } });
if (season) {
await Match.destroy({ where: { clubId, seasonId: season.id } });
// Lösche alle Matches für Ligen dieser Saison
const leagues = await League.findAll({
where: { seasonId: season.id, clubId }
});
const leagueIds = leagues.map(league => league.id);
if (leagueIds.length > 0) {
await Match.destroy({ where: { clubId, leagueId: leagueIds } });
}
}
}
const result = await Match.bulkCreate(matches);
return result;
} catch (error) {
console.log('Error during CSV import:', error);
devLog('Error during CSV import:', error);
throw error;
}
}
async getOrCreateTeamId(teamName, clubId) {
async getOrCreateTeamId(teamName, ageClass, clubId, leagueId, seasonId) {
// Format team name with age class
const formattedTeamName = this.formatTeamNameWithAgeClass(teamName, ageClass);
devLog(`Team: "${teamName}" + "${ageClass}" -> "${formattedTeamName}"`);
const [team] = await Team.findOrCreate({
where: {
name: teamName,
clubId: clubId
name: formattedTeamName,
clubId: clubId,
leagueId: leagueId,
seasonId: seasonId
},
defaults: {
name: teamName,
clubId: clubId
name: formattedTeamName,
clubId: clubId,
leagueId: leagueId,
seasonId: seasonId
}
});
return team.id;
}
async getLeaguesForCurrentSeason(userToken, clubId) {
async getLeaguesForCurrentSeason(userToken, clubId, seasonId = null) {
await checkAccess(userToken, clubId);
const seasonString = this.generateSeasonString();
const season = await Season.findOne({
where: {
season: {
[Op.like]: `%${seasonString}%`
}
// Verwende SeasonService für korrekte Saison-Verwaltung
let season;
if (!seasonId) {
season = await SeasonService.getOrCreateCurrentSeason();
} else {
season = await SeasonService.getSeasonById(seasonId);
if (!season) {
throw new Error('Season not found');
}
});
if (!season) {
await Season.create({ season: seasonString });
throw new Error('Season not found');
}
try {
const leagues = await League.findAll({
include: [{
model: Match,
as: 'leagueMatches',
where: {
seasonId: season.id,
clubId: clubId
},
attributes: [],
}],
where: {
clubId: clubId,
seasonId: season.id
},
attributes: ['id', 'name'],
group: ['League.id'],
order: [['name', 'ASC']]
});
return leagues;
} catch (error) {
@@ -133,48 +198,73 @@ class MatchService {
}
}
async getMatchesForLeagues(userToken, clubId) {
async getMatchesForLeagues(userToken, clubId, seasonId = null) {
await checkAccess(userToken, clubId);
const seasonString = this.generateSeasonString();
const season = await Season.findOne({
where: {
season: {
[Op.like]: `%${seasonString}%`
}
// Wenn keine Saison angegeben, verwende die aktuelle
let season;
if (!seasonId) {
season = await SeasonService.getOrCreateCurrentSeason();
} else {
season = await SeasonService.getSeasonById(seasonId);
if (!season) {
throw new Error('Season not found');
}
});
if (!season) {
throw new Error('Season not found');
}
const matches = await Match.findAll({
where: {
seasonId: season.id,
clubId: clubId,
},
include: [
{
model: League,
as: 'leagueDetails',
attributes: ['name'],
},
{
model: Team,
as: 'homeTeam', // Assuming your associations are set correctly
attributes: ['name'],
},
{
model: Team,
as: 'guestTeam',
attributes: ['name'],
},
{
model: Location,
as: 'location',
attributes: ['name', 'address', 'city', 'zip'],
}
]
}
});
return matches;
// Filtere Matches nach Liga-Saison und lade Daten manuell
const enrichedMatches = [];
for (const match of matches) {
// Lade Liga-Daten
const league = await League.findByPk(match.leagueId, { attributes: ['name', 'seasonId'] });
if (!league || league.seasonId !== season.id) {
continue; // Skip matches from other seasons
}
const enrichedMatch = {
id: match.id,
date: match.date,
time: match.time,
homeTeamId: match.homeTeamId,
guestTeamId: match.guestTeamId,
locationId: match.locationId,
leagueId: match.leagueId,
code: match.code,
homePin: match.homePin,
guestPin: match.guestPin,
homeMatchPoints: match.homeMatchPoints || 0,
guestMatchPoints: match.guestMatchPoints || 0,
isCompleted: match.isCompleted || false,
pdfUrl: match.pdfUrl,
homeTeam: { name: 'Unbekannt' },
guestTeam: { name: 'Unbekannt' },
location: { name: 'Unbekannt', address: '', city: '', zip: '' },
leagueDetails: { name: league.name }
};
if (match.homeTeamId) {
const homeTeam = await Team.findByPk(match.homeTeamId, { attributes: ['name'] });
if (homeTeam) enrichedMatch.homeTeam = homeTeam;
}
if (match.guestTeamId) {
const guestTeam = await Team.findByPk(match.guestTeamId, { attributes: ['name'] });
if (guestTeam) enrichedMatch.guestTeam = guestTeam;
}
if (match.locationId) {
const location = await Location.findByPk(match.locationId, {
attributes: ['name', 'address', 'city', 'zip']
});
if (location) enrichedMatch.location = location;
}
enrichedMatches.push(enrichedMatch);
}
return enrichedMatches;
}
async getMatchesForLeague(userToken, clubId, leagueId) {
@@ -190,36 +280,154 @@ class MatchService {
if (!season) {
throw new Error('Season not found');
}
const matches = await Match.findAll({
// Get club name from database
const club = await Club.findByPk(clubId, { attributes: ['name'] });
if (!club) {
throw new Error('Club not found');
}
const clubName = club.name;
devLog(`Filtering matches for club: ${clubName}`);
// Find all club teams in this league
const clubTeams = await ClubTeam.findAll({
where: {
seasonId: season.id,
clubId: clubId,
leagueId: leagueId
},
include: [
{
model: League,
as: 'leagueDetails',
attributes: ['name'],
},
{
model: Team,
as: 'homeTeam',
attributes: ['name'],
},
{
model: Team,
as: 'guestTeam',
attributes: ['name'],
},
{
model: Location,
as: 'location',
attributes: ['name', 'address', 'city', 'zip'],
}
]
attributes: ['id', 'name']
});
return matches;
devLog(`Club teams in league ${leagueId}: ${clubTeams.map(ct => ct.name).join(', ')}`);
// Find all Team entries that contain our club name
const ownTeams = await Team.findAll({
where: {
name: {
[Op.like]: `${clubName}%`
},
leagueId: leagueId
},
attributes: ['id', 'name']
});
const ownTeamIds = ownTeams.map(t => t.id);
devLog(`Own team IDs in this league: ${ownTeamIds.join(', ')} (${ownTeams.map(t => t.name).join(', ')})`);
// Load matches
let matches;
if (ownTeamIds.length > 0) {
// Load only matches where one of our teams is involved
matches = await Match.findAll({
where: {
leagueId: leagueId,
[Op.or]: [
{ homeTeamId: { [Op.in]: ownTeamIds } },
{ guestTeamId: { [Op.in]: ownTeamIds } }
]
}
});
devLog(`Found ${matches.length} matches for our teams`);
} else {
// No own teams found - show nothing
devLog('No own teams found in this league, showing no matches');
matches = [];
}
// Lade Team- und Location-Daten manuell
const enrichedMatches = [];
for (const match of matches) {
const enrichedMatch = {
id: match.id,
date: match.date,
time: match.time,
homeTeamId: match.homeTeamId,
guestTeamId: match.guestTeamId,
locationId: match.locationId,
leagueId: match.leagueId,
code: match.code,
homePin: match.homePin,
guestPin: match.guestPin,
homeMatchPoints: match.homeMatchPoints || 0,
guestMatchPoints: match.guestMatchPoints || 0,
isCompleted: match.isCompleted || false,
pdfUrl: match.pdfUrl,
homeTeam: { name: 'Unbekannt' },
guestTeam: { name: 'Unbekannt' },
location: { name: 'Unbekannt', address: '', city: '', zip: '' },
leagueDetails: { name: 'Unbekannt' }
};
if (match.homeTeamId) {
const homeTeam = await Team.findByPk(match.homeTeamId, { attributes: ['name'] });
if (homeTeam) enrichedMatch.homeTeam = homeTeam;
}
if (match.guestTeamId) {
const guestTeam = await Team.findByPk(match.guestTeamId, { attributes: ['name'] });
if (guestTeam) enrichedMatch.guestTeam = guestTeam;
}
if (match.locationId) {
const location = await Location.findByPk(match.locationId, {
attributes: ['name', 'address', 'city', 'zip']
});
if (location) enrichedMatch.location = location;
}
if (match.leagueId) {
const league = await League.findByPk(match.leagueId, { attributes: ['name'] });
if (league) enrichedMatch.leagueDetails = league;
}
enrichedMatches.push(enrichedMatch);
}
return enrichedMatches;
}
/**
* Get league table for a specific league
* @param {string} userToken - User authentication token
* @param {string} clubId - Club ID
* @param {string} leagueId - League ID
* @returns {Array} League table data
*/
async getLeagueTable(userToken, clubId, leagueId) {
await checkAccess(userToken, clubId);
try {
// Get all teams in this league
const teams = await Team.findAll({
where: {
leagueId: leagueId
},
attributes: [
'id', 'name', 'matchesPlayed', 'matchesWon', 'matchesLost', 'matchesTied',
'setsWon', 'setsLost', 'pointsWon', 'pointsLost', 'tablePoints', 'tablePointsWon', 'tablePointsLost'
],
order: [
['tablePointsWon', 'DESC'], // Highest table points first
['matchesWon', 'DESC'], // Then by matches won
['setsWon', 'DESC'] // Then by sets won
]
});
// Format table data
const tableData = teams.map(team => {
return {
teamId: team.id,
teamName: team.name,
setsWon: team.setsWon,
setsLost: team.setsLost,
matchPoints: team.matchesWon + ':' + team.matchesLost,
tablePoints: team.tablePointsWon + ':' + team.tablePointsLost, // Tabellenpunkte (points_won:points_lost)
pointRatio: team.pointsWon + ':' + team.pointsLost // Ballpunkte (games_won:games_lost)
};
});
return tableData;
} catch (error) {
console.error('Error getting league table:', error);
throw new Error('Failed to get league table');
}
}
}

View File

@@ -1,6 +1,7 @@
import MemberNote from '../models/MemberNote.js';
import { checkAccess } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';
class MemberNoteService {
async addNoteToMember(userToken, clubId, memberId, content) {
await checkAccess(userToken, clubId);
@@ -8,7 +9,7 @@ class MemberNoteService {
}
async getNotesForMember(userToken, clubId, memberId) {
console.log(userToken, clubId);
devLog(userToken, clubId);
await checkAccess(userToken, clubId);
return await MemberNote.findAll({
where: { memberId },

View File

@@ -6,13 +6,11 @@ import path from 'path';
import fs from 'fs';
import sharp from 'sharp';
import { devLog } from '../utils/logger.js';
class MemberService {
async getApprovalRequests(userToken, clubId) {
console.log('[MemberService::getApprovalRequest] - Check user access');
await checkAccess(userToken, clubId);
console.log('[MemberService::getApprovalRequest] - Load user');
const user = await getUserByToken(userToken);
console.log('[MemberService::getApprovalRequest] - Load userclub');
return await UserClub.findAll({
where: {
clubId: clubId,
@@ -23,9 +21,7 @@ class MemberService {
}
async getClubMembers(userToken, clubId, showAll) {
console.log('[getClubMembers] - Check access');
await checkAccess(userToken, clubId);
console.log('[getClubMembers] - Find members');
const where = {
clubId: clubId
};
@@ -44,7 +40,6 @@ class MemberService {
});
})
.then(membersWithImageStatus => {
console.log('[getClubMembers] - return members');
return membersWithImageStatus;
})
.catch(error => {
@@ -56,15 +51,11 @@ class MemberService {
async setClubMember(userToken, clubId, memberId, firstName, lastName, street, city, birthdate, phone, email, active = true, testMembership = false,
picsInInternetAllowed = false, gender = 'unknown', ttr = null, qttr = null) {
try {
console.log('[setClubMembers] - Check access');
await checkAccess(userToken, clubId);
console.log('[setClubMembers] - set default member');
let member = null;
console.log('[setClubMembers] - load member if possible');
if (memberId) {
member = await Member.findOne({ where: { id: memberId } });
}
console.log('[setClubMembers] - set member');
if (member) {
member.firstName = firstName;
member.lastName = lastName;
@@ -98,13 +89,12 @@ class MemberService {
qttr: qttr,
});
}
console.log('[setClubMembers] - return response');
return {
status: 200,
response: { result: "success" },
}
} catch (error) {
console.log(error);
devLog(error);
return {
status: error.statusCode || 500,
response: { error: "nocreation" }
@@ -114,7 +104,7 @@ class MemberService {
async uploadMemberImage(userToken, clubId, memberId, imageBuffer) {
try {
console.log('------>', userToken, clubId, memberId, imageBuffer);
devLog('------>', userToken, clubId, memberId, imageBuffer);
await checkAccess(userToken, clubId);
const member = await Member.findOne({ where: { id: memberId, clubId: clubId } });
if (!member) {
@@ -152,34 +142,50 @@ class MemberService {
}
async updateRatingsFromMyTischtennis(userToken, clubId) {
console.log('[updateRatingsFromMyTischtennis] - Check access');
await checkAccess(userToken, clubId);
const user = await getUserByToken(userToken);
console.log('[updateRatingsFromMyTischtennis] - User:', user.id);
const startTime = Date.now();
const myTischtennisService = (await import('./myTischtennisService.js')).default;
const myTischtennisClient = (await import('../clients/myTischtennisClient.js')).default;
const fetchLogService = (await import('./myTischtennisFetchLogService.js')).default;
try {
// 1. myTischtennis-Session abrufen
console.log('[updateRatingsFromMyTischtennis] - Get session for user', user.id);
const session = await myTischtennisService.getSession(user.id);
console.log('[updateRatingsFromMyTischtennis] - Session retrieved:', {
hasAccessToken: !!session.accessToken,
hasCookie: !!session.cookie,
expiresAt: session.expiresAt
});
// 1. myTischtennis-Session abrufen oder Login durchführen
let session;
try {
session = await myTischtennisService.getSession(user.id);
} catch (sessionError) {
console.log('[updateRatingsFromMyTischtennis] - Session invalid, attempting login...', sessionError.message);
// Versuche automatischen Login mit gespeicherten Credentials
try {
await myTischtennisService.verifyLogin(user.id);
const freshSession = await myTischtennisService.getSession(user.id);
session = {
cookie: freshSession.cookie,
accessToken: freshSession.accessToken,
refreshToken: freshSession.refreshToken,
expiresAt: freshSession.expiresAt,
userData: freshSession.userData
};
console.log('[updateRatingsFromMyTischtennis] - Automatic login successful');
} catch (loginError) {
console.error('[updateRatingsFromMyTischtennis] - Automatic login failed:', loginError.message);
return {
status: 401,
response: {
message: 'Session abgelaufen und automatischer Login fehlgeschlagen. Bitte einmal in myTischtennis einloggen.',
updated: 0,
errors: [loginError.message],
needsReauth: true
}
};
}
}
const account = await myTischtennisService.getAccount(user.id);
console.log('[updateRatingsFromMyTischtennis] - Account data:', {
id: account?.id,
email: account?.email,
clubId: account?.clubId,
clubName: account?.clubName,
fedNickname: account?.fedNickname,
hasSession: !!(account?.accessToken)
});
if (!account) {
console.error('[updateRatingsFromMyTischtennis] - No account found!');
@@ -216,24 +222,12 @@ class MemberService {
}
// 2. Rangliste vom Verein abrufen
console.log('[updateRatingsFromMyTischtennis] - Get club rankings', {
clubId: account.clubId,
fedNickname: account.fedNickname,
hasCookie: !!session.cookie
});
const rankings = await myTischtennisClient.getClubRankings(
session.cookie,
account.clubId,
account.fedNickname
);
console.log('[updateRatingsFromMyTischtennis] - Rankings result:', {
success: rankings.success,
entriesCount: rankings.entries?.length || 0,
error: rankings.error
});
if (!rankings.success) {
return {
status: 500,
@@ -251,9 +245,7 @@ class MemberService {
}
// 3. Alle Mitglieder des Clubs laden
console.log('[updateRatingsFromMyTischtennis] - Load club members for clubId:', clubId);
const members = await Member.findAll({ where: { clubId } });
console.log('[updateRatingsFromMyTischtennis] - Found members:', members.length);
let updated = 0;
const errors = [];
@@ -284,7 +276,6 @@ class MemberService {
oldTtr: oldTtr,
newTtr: rankingEntry.fedRank
});
console.log(`[updateRatingsFromMyTischtennis] - Updated ${firstName} ${lastName}: TTR ${oldTtr}${rankingEntry.fedRank}`);
} catch (error) {
console.error(`[updateRatingsFromMyTischtennis] - Error updating ${firstName} ${lastName}:`, error);
errors.push({
@@ -294,12 +285,10 @@ class MemberService {
}
} else {
notFound.push(`${firstName} ${lastName}`);
console.log(`[updateRatingsFromMyTischtennis] - Not found in rankings: ${firstName} ${lastName}`);
}
}
console.log('[updateRatingsFromMyTischtennis] - Update complete');
console.log(`Updated: ${updated}, Not found: ${notFound.length}, Errors: ${errors.length}`);
devLog(`Updated: ${updated}, Not found: ${notFound.length}, Errors: ${errors.length}`);
let message = `${updated} Mitglied(er) aktualisiert.`;
if (notFound.length > 0) {
@@ -309,6 +298,19 @@ class MemberService {
message += ` ${errors.length} Fehler beim Speichern.`;
}
// Log successful ratings fetch
await fetchLogService.logFetch(
user.id,
'ratings',
true,
message,
{
recordsProcessed: updated,
executionTime: Date.now() - startTime,
isAutomatic: false
}
);
return {
status: 200,
response: {
@@ -323,6 +325,20 @@ class MemberService {
};
} catch (error) {
console.error('[updateRatingsFromMyTischtennis] - Error:', error);
// Log failed ratings fetch
await fetchLogService.logFetch(
user.id,
'ratings',
false,
'Fehler beim Aktualisieren der Wertungen',
{
errorDetails: error.message,
executionTime: Date.now() - startTime,
isAutomatic: false
}
);
return {
status: 500,
response: {
@@ -333,6 +349,56 @@ class MemberService {
};
}
}
async rotateMemberImage(userToken, clubId, memberId, direction) {
try {
await checkAccess(userToken, clubId);
const member = await Member.findOne({ where: { id: memberId, clubId: clubId } });
if (!member) {
return { status: 404, response: { success: false, error: 'Member not found in this club' } };
}
const imagePath = path.join('images', 'members', `${memberId}.jpg`);
if (!fs.existsSync(imagePath)) {
return { status: 404, response: { success: false, error: 'Image not found' } };
}
// Read the image
const imageBuffer = await fs.promises.readFile(imagePath);
// Calculate rotation angle (-90 for left, +90 for right)
const rotationAngle = direction === 'left' ? -90 : 90;
// Rotate the image
const rotatedBuffer = await sharp(imageBuffer)
.rotate(rotationAngle)
.jpeg({ quality: 80 })
.toBuffer();
// Save the rotated image
await fs.promises.writeFile(imagePath, rotatedBuffer);
return {
status: 200,
response: {
success: true,
message: `Bild um ${rotationAngle}° gedreht`,
direction: direction,
rotation: rotationAngle
}
};
} catch (error) {
console.error('[rotateMemberImage] - Error:', error);
return {
status: 500,
response: {
success: false,
error: 'Fehler beim Drehen des Bildes: ' + error.message
}
};
}
}
}
export default new MemberService();

View File

@@ -0,0 +1,129 @@
import MyTischtennisFetchLog from '../models/MyTischtennisFetchLog.js';
import { devLog } from '../utils/logger.js';
import { Op } from 'sequelize';
import sequelize from '../database.js';
class MyTischtennisFetchLogService {
/**
* Log a fetch attempt
*/
async logFetch(userId, fetchType, success, message, options = {}) {
try {
await MyTischtennisFetchLog.create({
userId,
fetchType,
success,
message,
errorDetails: options.errorDetails || null,
recordsProcessed: options.recordsProcessed || 0,
executionTime: options.executionTime || null,
isAutomatic: options.isAutomatic || false
});
devLog(`[FetchLog] ${fetchType} - ${success ? 'SUCCESS' : 'FAILED'} - User ${userId}`);
} catch (error) {
console.error('Error logging fetch:', error);
// Don't throw - logging failures shouldn't break the main operation
}
}
/**
* Get fetch logs for a user
*/
async getFetchLogs(userId, options = {}) {
try {
const where = { userId };
if (options.fetchType) {
where.fetchType = options.fetchType;
}
if (options.success !== undefined) {
where.success = options.success;
}
const logs = await MyTischtennisFetchLog.findAll({
where,
order: [['createdAt', 'DESC']],
limit: options.limit || 50,
attributes: [
'id', 'fetchType', 'success', 'message', 'errorDetails',
'recordsProcessed', 'executionTime', 'isAutomatic', 'createdAt'
]
});
return logs;
} catch (error) {
console.error('Error getting fetch logs:', error);
throw error;
}
}
/**
* Get latest successful fetch for each type
*/
async getLatestSuccessfulFetches(userId) {
try {
const fetchTypes = ['ratings', 'match_results', 'league_table'];
const results = {};
for (const fetchType of fetchTypes) {
const latestFetch = await MyTischtennisFetchLog.findOne({
where: {
userId,
fetchType,
success: true
},
order: [['createdAt', 'DESC']],
attributes: ['createdAt', 'recordsProcessed', 'executionTime']
});
results[fetchType] = latestFetch ? {
lastFetch: latestFetch.createdAt,
recordsProcessed: latestFetch.recordsProcessed,
executionTime: latestFetch.executionTime
} : null;
}
return results;
} catch (error) {
console.error('Error getting latest successful fetches:', error);
throw error;
}
}
/**
* Get fetch statistics
*/
async getFetchStatistics(userId, days = 30) {
try {
const since = new Date();
since.setDate(since.getDate() - days);
const stats = await MyTischtennisFetchLog.findAll({
where: {
userId,
createdAt: {
[Op.gte]: since
}
},
attributes: [
'fetchType',
[sequelize.fn('COUNT', sequelize.col('id')), 'totalFetches'],
[sequelize.fn('SUM', sequelize.literal('CASE WHEN success = true THEN 1 ELSE 0 END')), 'successfulFetches'],
[sequelize.fn('SUM', sequelize.col('records_processed')), 'totalRecordsProcessed'],
[sequelize.fn('AVG', sequelize.col('execution_time')), 'avgExecutionTime']
],
group: ['fetchType']
});
return stats;
} catch (error) {
console.error('Error getting fetch statistics:', error);
throw error;
}
}
}
export default new MyTischtennisFetchLogService();

Some files were not shown because too many files have changed in this diff Show More