6 Commits

Author SHA1 Message Date
42398dad21 Merge pull request 'dev' (#46) from dev into main
All checks were successful
Code Analysis and Production Deploy / analyze (push) Has been skipped
Code Analysis and Production Deploy / deploy-production (push) Successful in 2m47s
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
Reviewed-on: #46
2026-07-17 14:00:12 +02:00
d563d81584 Merge pull request 'Füge Funktion zur Umwandlung von Saison-Slugs in Labels hinzu und aktualisiere PDF-Daten mit saisonalen Informationen' (#45) from dev into main
All checks were successful
Code Analysis and Production Deploy / analyze (push) Has been skipped
Code Analysis and Production Deploy / deploy-production (push) Successful in 1m59s
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
Reviewed-on: #45
2026-07-15 11:38:20 +02:00
380d0a8332 Merge pull request 'dev' (#44) from dev into main
All checks were successful
Code Analysis and Production Deploy / analyze (push) Has been skipped
Code Analysis and Production Deploy / deploy-production (push) Successful in 2m41s
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
Reviewed-on: #44
2026-07-15 11:12:16 +02:00
301bd7acbd Merge pull request 'dev' (#43) from dev into main
All checks were successful
Code Analysis and Production Deploy / analyze (push) Has been skipped
Code Analysis and Production Deploy / deploy-production (push) Successful in 2m44s
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
Reviewed-on: #43
2026-06-23 23:50:21 +02:00
05e25aa3d1 Merge pull request 'dev' (#42) from dev into main
All checks were successful
Code Analysis and Production Deploy / analyze (push) Has been skipped
Code Analysis and Production Deploy / deploy-production (push) Successful in 2m15s
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
Reviewed-on: #42
2026-06-16 14:09:23 +02:00
ecae88af78 Merge pull request 'dev' (#41) from dev into main
All checks were successful
Code Analysis and Production Deploy / analyze (push) Has been skipped
Code Analysis and Production Deploy / deploy-production (push) Successful in 3m0s
Code Analysis and Production Deploy / deploy-test (push) Has been skipped
Reviewed-on: #41
2026-06-10 16:49:07 +02:00
69 changed files with 1029 additions and 3885 deletions

View File

@@ -13,16 +13,7 @@ jobs:
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
clean: true
# Der Analyse-Workflow benötigt keine Historie. Ein flacher Checkout
# verhindert, dass der Runner das große Repository-Pack vollständig lädt.
fetch-depth: 1
# Der Web-Workflow braucht keine Android-Artefakte. Insbesondere liegt
# dort ein großer Heap-Dump im aktuellen Commit, der auch bei einem
# flachen Checkout übertragen würde und den Runner-Checkout abbricht.
sparse-checkout: |
/*
!/android-app/
sparse-checkout-cone-mode: false
fetch-depth: 0
- name: Ensure clean workspace
run: |
@@ -121,12 +112,11 @@ jobs:
- name: OSV-Scanner (SCA)
run: |
cd "$GITHUB_WORKSPACE"
curl -L -o osv-scanner https://github.com/google/osv-scanner/releases/latest/download/osv-scanner_linux_amd64
chmod +x osv-scanner
./osv-scanner --version
test -f "$GITHUB_WORKSPACE/package-lock.json"
./osv-scanner scan -L "$GITHUB_WORKSPACE/package-lock.json" --config "$GITHUB_WORKSPACE/.osv-scanner.toml"
test -f ./package-lock.json
./osv-scanner scan -L ./package-lock.json --config ./.osv-scanner.toml
deploy-production:
runs-on: ubuntu-latest

4
.gitignore vendored
View File

@@ -94,10 +94,6 @@ dist
/android-app/**/build/
/android-app/local.properties
/android-app/gradle-local.properties
# Android Play Store / release artifacts are generated locally or in CI.
/android-app/**/*.aab
# JVM Heap-Dumps sind lokale Diagnoseartefakte und dürfen nie ins Repository.
*.hprof
# Build output (but keep production data!)
.output

View File

@@ -78,12 +78,12 @@ val ensureProductionApiBaseUrl = tasks.register("ensureProductionApiBaseUrl") {
android {
namespace = "de.harheimertc"
compileSdk = 36
compileSdk = 35
defaultConfig {
applicationId = "de.harheimertc"
minSdk = 24
targetSdk = 36
targetSdk = 35
versionCode = androidVersionCode
versionName = androidVersionName
}

Binary file not shown.

View File

@@ -21,20 +21,9 @@ import de.harheimertc.ui.navigation.NavigationViewModel
import dagger.hilt.android.AndroidEntryPoint
import android.util.Log
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.lifecycleScope
import de.harheimertc.repositories.AuthRepository
import de.harheimertc.repositories.PushTokenRepository
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject
lateinit var authRepository: AuthRepository
@Inject
lateinit var pushTokenRepository: PushTokenRepository
private val notificationRoute = mutableStateOf<String?>(null)
private val notificationPermissionLauncher = registerForActivityResult(
@@ -61,23 +50,6 @@ class MainActivity : ComponentActivity() {
notificationRoute.value = extractNotificationRoute(intent)
}
override fun onResume() {
super.onResume()
syncPushTokenWhenSignedIn()
}
/**
* Server-side tokens are persistent, but re-registering the current FCM
* token is cheap and idempotent. It restores a token if server data was
* ever recovered from a backup or manually repaired.
*/
private fun syncPushTokenWhenSignedIn() {
if (authRepository.getToken().isNullOrBlank() && authRepository.getRefreshToken().isNullOrBlank()) return
lifecycleScope.launch {
pushTokenRepository.registerCurrentDevice()
}
}
private fun extractNotificationRoute(intent: Intent?): String? =
intent?.getStringExtra(EXTRA_NOTIFICATION_ROUTE)?.takeIf { it.isNotBlank() }

View File

@@ -166,7 +166,6 @@ data class MembershipResponse(
val success: Boolean = false,
val message: String? = null,
val downloadUrl: String? = null,
val downloadToken: String? = null,
)
data class LoginRequest(
val email: String,
@@ -269,7 +268,6 @@ data class NotificationSettingsDto(
val birthdays: Boolean = false,
val newContactRequest: Boolean = false,
val newUserRegistration: Boolean = false,
val ownTtrChanges: Boolean = false,
val selectedTeamSlugs: List<String> = emptyList(),
val selectedTeamSeason: String? = null,
val notificationTime: String = "09:00",
@@ -283,7 +281,6 @@ data class PushTokenRequest(
val token: String,
val platform: String = "android",
val appVersion: String? = null,
val installationId: String? = null,
)
data class BirthdayDto(
val name: String = "",
@@ -304,7 +301,6 @@ data class QttrRowDto(
val playerName: String = "",
val clubName: String = "",
val currentQttr: Int? = null,
val currentTtr: Int? = null,
val previousQttr: Int? = null,
val birthdate: String? = null,
)
@@ -664,10 +660,7 @@ interface ApiService {
@Streaming
@GET
suspend fun downloadMembershipPdf(
@Url downloadUrl: String,
@retrofit2.http.Header("X-Membership-Download-Token") downloadToken: String? = null,
): Response<ResponseBody>
suspend fun downloadMembershipPdf(@Url downloadUrl: String): Response<ResponseBody>
@POST("/api/auth/login")
suspend fun login(@Body request: LoginRequest): Response<LoginResponse>

View File

@@ -21,7 +21,7 @@ class HarheimerMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
serviceScope.launch {
pushTokenRepository.registerCurrentDevice()
pushTokenRepository.registerToken(token)
}
}

View File

@@ -16,16 +16,14 @@ import de.harheimertc.R
import de.harheimertc.ui.navigation.Destinations
object HarheimerNotifications {
// A new ID is intentional: Android does not allow an app update to raise
// the importance of an already-created notification channel.
const val DEFAULT_CHANNEL_ID = "harheimer_tc_updates_v2"
const val DEFAULT_CHANNEL_ID = "harheimer_tc_updates"
fun createChannels(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel(
DEFAULT_CHANNEL_ID,
"Harheimer TC",
NotificationManager.IMPORTANCE_HIGH,
NotificationManager.IMPORTANCE_DEFAULT,
).apply {
description = "Benachrichtigungen des Harheimer TC"
}
@@ -49,7 +47,7 @@ object HarheimerNotifications {
.setContentTitle(title)
.setContentText(message)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(createContentIntent(context, notificationId, data))
.setAutoCancel(true)
.build()
@@ -81,7 +79,6 @@ object HarheimerNotifications {
"news", "news_expiring" -> Destinations.MemberNews.route
"event", "events_today", "events_tomorrow" -> Destinations.Termine.route
"team_matches" -> Destinations.Spielplan.route
"qttr_list_updated", "ttr_change" -> Destinations.Qttr.route
"birthdays" -> Destinations.MemberArea.route
"contact_request" -> Destinations.CmsContactRequests.route
"user_registration" -> Destinations.CmsBenutzer.route

View File

@@ -9,7 +9,7 @@ import java.io.File
import javax.inject.Inject
import javax.inject.Singleton
data class MembershipDocument(val message: String, val uri: String? = null)
data class MembershipDocument(val message: String, val uri: String)
@Singleton
class MembershipRepository @Inject constructor(
@@ -18,33 +18,21 @@ class MembershipRepository @Inject constructor(
) {
suspend fun submit(request: MembershipRequest): Result<MembershipDocument> = runCatching {
val response = api.generateMembershipPdf(request)
if (!response.isSuccessful) {
val serverMessage = response.errorBody()?.string()
?.let { Regex("\\\"(?:statusMessage|message)\\\"\\s*:\\s*\\\"([^\\\"]+)\\\"").find(it)?.groupValues?.getOrNull(1) ?: it }
?.takeIf { it.isNotBlank() }
error(serverMessage ?: "Der Antrag konnte nicht übermittelt werden (HTTP ${response.code()}).")
}
if (!response.isSuccessful) error("HTTP ${response.code()}")
val body = response.body() ?: error("Leere Antwort")
if (!body.success) error(body.message ?: "Antrag konnte nicht erstellt werden.")
val uri = body.downloadUrl?.let { downloadUrl ->
runCatching {
val documentResponse = api.downloadMembershipPdf(downloadUrl, body.downloadToken)
if (!documentResponse.isSuccessful) error("PDF konnte nicht heruntergeladen werden.")
val directory = File(context.cacheDir, "membership").apply { mkdirs() }
val file = File(directory, "beitrittserklaerung.pdf")
documentResponse.body()?.byteStream()?.use { input ->
file.outputStream().use { output -> input.copyTo(output) }
} ?: error("Leere PDF-Antwort")
FileProvider.getUriForFile(context, "${context.packageName}.files", file).toString()
}.getOrNull()
}
val downloadUrl = body.downloadUrl ?: error("PDF-Download fehlt.")
val documentResponse = api.downloadMembershipPdf(downloadUrl)
if (!documentResponse.isSuccessful) error("PDF konnte nicht heruntergeladen werden.")
val directory = File(context.cacheDir, "membership").apply { mkdirs() }
val file = File(directory, "beitrittserklaerung.pdf")
documentResponse.body()?.byteStream()?.use { input ->
file.outputStream().use { output -> input.copyTo(output) }
} ?: error("Leere PDF-Antwort")
val uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file)
MembershipDocument(
message = if (uri == null) {
"${body.message ?: "Mitgliedschaftsantrag erfolgreich übermittelt."} Das PDF konnte nicht auf diesem Gerät gespeichert werden."
} else {
body.message ?: "Beitrittsformular erfolgreich erstellt."
},
uri = uri,
message = body.message ?: "Beitrittsformular erfolgreich erstellt.",
uri = uri.toString(),
)
}
}

View File

@@ -19,7 +19,6 @@ data class NotificationPreferences(
val birthdays: Boolean = false,
val newContactRequest: Boolean = false,
val newUserRegistration: Boolean = false,
val ownTtrChanges: Boolean = false,
val selectedTeamSlugs: Set<String> = emptySet(),
val selectedTeamSeason: String? = null,
val notificationTime: String = DEFAULT_NOTIFICATION_TIME,
@@ -44,7 +43,6 @@ class NotificationPreferencesRepository @Inject constructor(
birthdays = preferences.getBoolean(KEY_BIRTHDAYS, false),
newContactRequest = preferences.getBoolean(KEY_NEW_CONTACT_REQUEST, false),
newUserRegistration = preferences.getBoolean(KEY_NEW_USER_REGISTRATION, false),
ownTtrChanges = preferences.getBoolean(KEY_OWN_TTR_CHANGES, false),
selectedTeamSlugs = preferences.getStringSet(KEY_SELECTED_TEAM_SLUGS, emptySet()).orEmpty(),
selectedTeamSeason = preferences.getString(KEY_SELECTED_TEAM_SEASON, null)?.takeIf { it.isNotBlank() },
notificationTime = preferences.getString(KEY_NOTIFICATION_TIME, DEFAULT_NOTIFICATION_TIME) ?: DEFAULT_NOTIFICATION_TIME,
@@ -71,7 +69,6 @@ class NotificationPreferencesRepository @Inject constructor(
.putBoolean(KEY_BIRTHDAYS, settings.birthdays)
.putBoolean(KEY_NEW_CONTACT_REQUEST, settings.newContactRequest)
.putBoolean(KEY_NEW_USER_REGISTRATION, settings.newUserRegistration)
.putBoolean(KEY_OWN_TTR_CHANGES, settings.ownTtrChanges)
.putStringSet(KEY_SELECTED_TEAM_SLUGS, settings.selectedTeamSlugs)
.putString(KEY_SELECTED_TEAM_SEASON, settings.selectedTeamSeason)
.putString(KEY_NOTIFICATION_TIME, settings.notificationTime)
@@ -101,7 +98,6 @@ class NotificationPreferencesRepository @Inject constructor(
const val KEY_BIRTHDAYS = "birthdays"
const val KEY_NEW_CONTACT_REQUEST = "new_contact_request"
const val KEY_NEW_USER_REGISTRATION = "new_user_registration"
const val KEY_OWN_TTR_CHANGES = "own_ttr_changes"
const val KEY_SELECTED_TEAM_SLUGS = "selected_team_slugs"
const val KEY_SELECTED_TEAM_SEASON = "selected_team_season"
const val KEY_NOTIFICATION_TIME = "notification_time"
@@ -118,7 +114,6 @@ private fun NotificationSettingsDto.toPreferences(): NotificationPreferences = N
birthdays = birthdays,
newContactRequest = newContactRequest,
newUserRegistration = newUserRegistration,
ownTtrChanges = ownTtrChanges,
selectedTeamSlugs = selectedTeamSlugs.toSet(),
selectedTeamSeason = selectedTeamSeason,
notificationTime = notificationTime,
@@ -134,7 +129,6 @@ private fun NotificationPreferences.toDto(): NotificationSettingsDto = Notificat
birthdays = birthdays,
newContactRequest = newContactRequest,
newUserRegistration = newUserRegistration,
ownTtrChanges = ownTtrChanges,
selectedTeamSlugs = selectedTeamSlugs.toList(),
selectedTeamSeason = selectedTeamSeason,
notificationTime = notificationTime,

View File

@@ -1,7 +1,6 @@
package de.harheimertc.repositories
import android.util.Log
import com.google.firebase.installations.FirebaseInstallations
import com.google.firebase.messaging.FirebaseMessaging
import de.harheimertc.BuildConfig
import de.harheimertc.data.ApiService
@@ -16,24 +15,19 @@ class PushTokenRepository @Inject constructor(
) {
suspend fun registerCurrentDevice(): Result<Unit> = runCatching {
val token = FirebaseMessaging.getInstance().token.await()
val installationId = FirebaseInstallations.getInstance().id.await()
registerToken(token, installationId).getOrThrow()
registerToken(token).getOrThrow()
}
suspend fun registerToken(token: String, installationId: String? = null): Result<Unit> = runCatching {
suspend fun registerToken(token: String): Result<Unit> = runCatching {
if (token.isBlank()) return@runCatching
retryOnNetworkFailure {
val response = api.registerPushToken(
PushTokenRequest(
token = token,
appVersion = "${BuildConfig.VERSION_NAME}+${BuildConfig.VERSION_CODE}",
installationId = installationId,
),
)
if (!response.isSuccessful) {
val detail = response.errorBody()?.string().orEmpty().replace(Regex("\\s+"), " ").take(180)
error("Push-Token konnte nicht registriert werden (HTTP ${response.code()})${if (detail.isBlank()) "" else ": $detail"}")
}
if (!response.isSuccessful) error("Push-Token konnte nicht registriert werden.")
}
}.onFailure { error ->
Log.w("PushTokenRepository", "Push-Token Registrierung fehlgeschlagen", error)

View File

@@ -472,7 +472,7 @@ private fun submenu(section: MenuSection?, state: NavigationUiState): List<MenuT
MenuSection.INTERN -> buildList {
add(MenuTarget("Übersicht", Destinations.MemberArea.route))
add(MenuTarget("Mitgliederliste", Destinations.Members.route))
add(MenuTarget("TTR / QTTR", Destinations.Qttr.route))
add(MenuTarget("QTTR", Destinations.Qttr.route))
add(MenuTarget("News", Destinations.MemberNews.route))
add(MenuTarget("Mein Profil", Destinations.Profile.route))
add(MenuTarget("Benachrichtigungen", Destinations.NotificationSettings.route))

View File

@@ -6,7 +6,6 @@ import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.harheimertc.repositories.LoginRepository
import de.harheimertc.repositories.PasskeyRepository
import de.harheimertc.repositories.PushTokenRepository
import de.harheimertc.ui.components.isValidEmail
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -30,7 +29,6 @@ data class LoginUiState(
class LoginViewModel @Inject constructor(
private val repository: LoginRepository,
private val passkeyRepository: PasskeyRepository,
private val pushTokenRepository: PushTokenRepository,
) : ViewModel() {
private val _state = MutableStateFlow(LoginUiState())
val state: StateFlow<LoginUiState> = _state
@@ -72,7 +70,6 @@ class LoginViewModel @Inject constructor(
_state.value = current.copy(loading = true, error = null, message = null)
repository.login(current.email, current.password)
.onSuccess { response ->
viewModelScope.launch { pushTokenRepository.registerCurrentDevice() }
_state.value = current.copy(
password = "",
loading = false,
@@ -95,7 +92,6 @@ class LoginViewModel @Inject constructor(
_state.value = current.copy(loading = true, error = null, message = null)
passkeyRepository.login(context, current.email)
.onSuccess { response ->
viewModelScope.launch { pushTokenRepository.registerCurrentDevice() }
_state.value = current.copy(
password = "",
loading = false,

View File

@@ -28,6 +28,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalUriHandler
import android.util.Log
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
@@ -247,7 +248,18 @@ fun QttrScreen(
viewModel: QttrViewModel = hiltViewModel(),
) {
val state by viewModel.state.collectAsState()
MemberAreaPage(navController, showBackNavigation, "TTR- und QTTR-Werte", "Aktuelle Werte der Vereinsmitglieder aus myTischtennis.") {
val uriHandler = LocalUriHandler.current
val externalUrl = "https://www.mytischtennis.de/rankings/andro-rangliste?continent=all&country=Deutschland&all-players=on&as=DE.WE.R4.07&di=DE.WE.R4.07.04&area=DE.WE.R4.07.04.43&clubnr-search=Harheimer+TC&clubnr=43030&fednickname=HeTTV&gender=all&current-ranking=yes&ttr-range=100%3B3000&birth-range=1926%3B2021"
MemberAreaPage(navController, showBackNavigation, "QTTR-Werte", "Aus technischen Gründen sind nur die QTTR-Werte verfügbar.") {
item {
Surface(color = Primary100, shape = RoundedCornerShape(12.dp)) {
Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Für TTR bitte die myTischtennis-Rangliste verwenden.", color = Primary900)
TextButton(onClick = { uriHandler.openUri(externalUrl) }) { Text("myTischtennis öffnen") }
}
}
}
item {
Surface(color = Color.White, shape = RoundedCornerShape(14.dp), shadowElevation = 3.dp) {
Column(Modifier.fillMaxWidth().padding(18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
@@ -257,9 +269,9 @@ fun QttrScreen(
}
}
when {
state.loading -> item { LoadingState("TTR- und QTTR-Werte werden geladen...") }
state.loading -> item { LoadingState("QTTR-Werte werden geladen...") }
state.error != null -> item { ErrorCard(state.error.orEmpty(), viewModel::load) }
state.rows.isEmpty() -> item { Text("Keine TTR- oder QTTR-Werte gefunden.", color = Accent700) }
state.rows.isEmpty() -> item { Text("Keine QTTR-Werte gefunden.", color = Accent700) }
else -> items(state.rows.size) { index -> QttrRowCard(state.rows[index], isOwnRow(state.rows[index].playerName, state.currentUserName)) }
}
}
@@ -376,10 +388,7 @@ private fun QttrRowCard(row: QttrRowDto, highlighted: Boolean) {
)
Text(row.clubName.ifBlank { "Harheimer TC" }, color = qttrNameColor(row.gender, isMinor(row.birthdate)).copy(alpha = 0.88f))
}
Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text("TTR ${row.currentTtr?.toString() ?: "-"}", color = Accent700, style = MaterialTheme.typography.labelLarge)
Text("QTTR ${row.currentQttr?.toString() ?: "-"}", color = Primary600, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
}
Text(row.currentQttr?.toString() ?: "-", color = Primary600, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
}
}
}

View File

@@ -121,9 +121,9 @@ private fun MemberAreaCardGrid(navController: NavController) {
onClick = { navController.navigate(Destinations.MemberNews.route) },
)
MemberAreaCard(
title = "TTR / QTTR",
description = "Aktuelle TTR- und QTTR-Werte der Vereinsmitglieder",
marker = "T",
title = "QTTR",
description = "Aktuelle QTTR-Werte der Vereinsmitglieder",
marker = "Q",
onClick = { navController.navigate(Destinations.Qttr.route) },
)
}

View File

@@ -81,10 +81,7 @@ class MembershipViewModel @Inject constructor(private val repository: Membership
_state.value = _state.value.copy(sending = false, fieldErrors = emptyMap(), message = document.message, pdfUri = document.uri)
}
.onFailure {
_state.value = _state.value.copy(
sending = false,
error = it.message ?: "Beitrittsformular konnte nicht erstellt werden.",
)
_state.value = _state.value.copy(sending = false, error = "Beitrittsformular konnte nicht erstellt werden.")
}
}
}

View File

@@ -40,7 +40,6 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import de.harheimertc.notifications.HarheimerNotifications
import de.harheimertc.BuildConfig
import de.harheimertc.repositories.Mannschaft
import de.harheimertc.repositories.NotificationPreferences
import de.harheimertc.ui.components.LoadingState
@@ -104,23 +103,6 @@ fun NotificationSettingsScreen(
}
}
item {
NotificationCard("Geräte-Registrierung") {
Text("Der Push-Token wird dem aktuell angemeldeten Konto auf diesem Server zugeordnet:", color = Accent700)
Text(BuildConfig.API_BASE_URL, color = Accent900, style = MaterialTheme.typography.bodySmall)
Button(
onClick = viewModel::registerCurrentDevice,
enabled = !state.deviceRegistrationInProgress,
modifier = Modifier.fillMaxWidth(),
) {
Text(if (state.deviceRegistrationInProgress) "Gerät wird registriert..." else "Android-Gerät jetzt registrieren")
}
state.deviceRegistrationMessage?.let { message ->
Text(message, color = if (state.deviceRegistrationError) MaterialTheme.colorScheme.error else Color(0xFF166534))
}
}
}
if (state.loading) {
item { LoadingState("Benachrichtigungseinstellungen werden geladen...") }
} else {
@@ -180,9 +162,6 @@ fun NotificationSettingsScreen(
ToggleRow("Geburtstage", state.settings.birthdays) {
viewModel.update(state.settings.copy(birthdays = it))
}
ToggleRow("Änderung meines TTR-Werts", state.settings.ownTtrChanges) {
viewModel.update(state.settings.copy(ownTtrChanges = it))
}
}
}

View File

@@ -8,7 +8,6 @@ import de.harheimertc.repositories.LoginRepository
import de.harheimertc.repositories.MannschaftenRepository
import de.harheimertc.repositories.NotificationPreferences
import de.harheimertc.repositories.NotificationPreferencesRepository
import de.harheimertc.repositories.PushTokenRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
@@ -23,9 +22,6 @@ data class NotificationSettingsUiState(
val seasons: List<String> = emptyList(),
val error: String? = null,
val saveError: String? = null,
val deviceRegistrationMessage: String? = null,
val deviceRegistrationError: Boolean = false,
val deviceRegistrationInProgress: Boolean = false,
)
@HiltViewModel
@@ -33,7 +29,6 @@ class NotificationSettingsViewModel @Inject constructor(
private val preferencesRepository: NotificationPreferencesRepository,
private val mannschaftenRepository: MannschaftenRepository,
private val loginRepository: LoginRepository,
private val pushTokenRepository: PushTokenRepository,
) : ViewModel() {
private val _state = MutableStateFlow(NotificationSettingsUiState())
val state: StateFlow<NotificationSettingsUiState> = _state
@@ -87,30 +82,6 @@ class NotificationSettingsViewModel @Inject constructor(
update(current.copy(selectedTeamSlugs = nextTeams))
}
fun registerCurrentDevice() {
viewModelScope.launch {
_state.value = _state.value.copy(
deviceRegistrationInProgress = true,
deviceRegistrationMessage = null,
deviceRegistrationError = false,
)
pushTokenRepository.registerCurrentDevice()
.onSuccess {
_state.value = _state.value.copy(
deviceRegistrationInProgress = false,
deviceRegistrationMessage = "Dieses Android-Gerät wurde beim Server registriert.",
)
}
.onFailure { error ->
_state.value = _state.value.copy(
deviceRegistrationInProgress = false,
deviceRegistrationError = true,
deviceRegistrationMessage = error.message ?: "Android-Gerät konnte nicht registriert werden.",
)
}
}
}
private suspend fun loadTeams(settings: NotificationPreferences, seasons: List<String>, currentUserName: String, syncRemote: Boolean = false) {
mannschaftenRepository.fetchMannschaften(settings.selectedTeamSeason)
.onSuccess { teams ->

View File

@@ -8,8 +8,8 @@ LOCAL_API_BASE_URL=https://harheimertc.tsschulz.de/
PRODUCTION_API_BASE_URL=https://harheimertc.de/
# Android app versioning for Play Store uploads
ANDROID_VERSION_CODE=36
ANDROID_VERSION_NAME=0.10.0
ANDROID_VERSION_CODE=29
ANDROID_VERSION_NAME=0.9.24
# Temporary hotfix: disable R8 minification for release to avoid Retrofit generic signature stripping.
RELEASE_MINIFY_ENABLED=false

BIN
android-app/java_pid672503.hprof Executable file

Binary file not shown.

View File

@@ -1,7 +1,7 @@
<template>
<div class="h-screen flex flex-col overflow-hidden">
<Navigation />
<main class="flex-1 overflow-y-auto pt-20 pb-20 sm:pb-0">
<main class="flex-1 overflow-y-auto pt-20">
<NuxtPage />
</main>
<Footer />

View File

@@ -1,39 +1,39 @@
<template>
<footer class="fixed bottom-0 left-0 right-0 z-40 border-t border-gray-200/90 bg-white/95 shadow-[0_-5px_18px_rgba(24,24,27,0.07)] backdrop-blur-sm">
<div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 py-2.5 sm:py-3">
<div class="flex flex-col sm:flex-row justify-between items-center gap-y-1 sm:gap-y-0">
<p class="text-xs sm:text-sm text-gray-600 whitespace-nowrap">
<footer class="fixed bottom-0 left-0 right-0 z-40 bg-gray-900 border-t border-gray-800 shadow-2xl">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3">
<div class="flex flex-col sm:flex-row justify-between items-center space-y-2 sm:space-y-0">
<p class="text-sm text-gray-400">
© {{ currentYear }} Harheimer TC 1954 e.V.
</p>
<div class="flex flex-wrap justify-center items-center gap-x-4 gap-y-1 text-xs sm:text-sm relative">
<div class="flex items-center space-x-6 text-sm relative">
<span
v-if="isLoggedIn && appVersion"
class="text-xs text-gray-500"
class="text-xs text-gray-600"
title="Version"
>
v{{ appVersion }}
</span>
<NuxtLink
to="/impressum"
class="text-gray-700 hover:text-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 rounded-sm transition-colors"
class="text-gray-400 hover:text-primary-400 transition-colors"
>
Impressum
</NuxtLink>
<NuxtLink
to="/datenschutz"
class="text-gray-700 hover:text-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 rounded-sm transition-colors"
class="text-gray-400 hover:text-primary-400 transition-colors"
>
Datenschutz
</NuxtLink>
<NuxtLink
to="/konto-loeschen"
class="text-gray-700 hover:text-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 rounded-sm transition-colors"
class="text-gray-400 hover:text-primary-400 transition-colors"
>
Konto loeschen
</NuxtLink>
<NuxtLink
to="/kontakt"
class="text-gray-700 hover:text-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 rounded-sm transition-colors"
class="text-gray-400 hover:text-primary-400 transition-colors"
>
Kontakt
</NuxtLink>
@@ -41,7 +41,7 @@
<!-- Login/Logout -->
<template v-if="isLoggedIn">
<button
class="flex items-center space-x-1 rounded-sm text-gray-700 hover:text-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 transition-colors"
class="flex items-center space-x-1 text-gray-400 hover:text-primary-400 transition-colors"
@click="handleLogout"
>
<User :size="16" />
@@ -53,7 +53,7 @@
class="relative"
>
<button
class="flex items-center space-x-1 rounded-sm text-gray-700 hover:text-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 transition-colors"
class="flex items-center space-x-1 text-gray-400 hover:text-primary-400 transition-colors"
@click="toggleMemberMenu"
>
<User :size="16" />
@@ -75,25 +75,25 @@
>
<div
v-if="isMemberMenuOpen"
class="absolute bottom-full right-0 mb-2 w-48 overflow-hidden rounded-md border border-gray-200 bg-white shadow-[0_12px_28px_rgba(24,24,27,0.14)] ring-1 ring-black/5"
class="absolute bottom-full right-0 mb-2 w-48 bg-gray-800 border border-gray-700 rounded-lg shadow-xl overflow-hidden"
>
<NuxtLink
to="/login"
class="block px-4 py-2 text-sm text-gray-700 hover:bg-primary-50 hover:text-primary-800 focus-visible:outline-none focus-visible:bg-primary-50 focus-visible:text-primary-800 transition-colors"
class="block px-4 py-2 text-sm text-gray-300 hover:bg-primary-600 hover:text-white transition-colors"
@click="isMemberMenuOpen = false"
>
Anmelden
</NuxtLink>
<NuxtLink
to="/registrieren"
class="block px-4 py-2 text-sm text-gray-700 hover:bg-primary-50 hover:text-primary-800 focus-visible:outline-none focus-visible:bg-primary-50 focus-visible:text-primary-800 transition-colors"
class="block px-4 py-2 text-sm text-gray-300 hover:bg-primary-600 hover:text-white transition-colors"
@click="isMemberMenuOpen = false"
>
Registrieren
</NuxtLink>
<NuxtLink
to="/passwort-vergessen"
class="block px-4 py-2 text-sm text-gray-700 hover:bg-primary-50 hover:text-primary-800 focus-visible:outline-none focus-visible:bg-primary-50 focus-visible:text-primary-800 transition-colors"
class="block px-4 py-2 text-sm text-gray-300 hover:bg-primary-600 hover:text-white transition-colors"
@click="isMemberMenuOpen = false"
>
Passwort vergessen

View File

@@ -29,9 +29,9 @@
</div>
<!-- Content -->
<div class="relative z-20 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="relative z-20 max-w-7xl mx-auto">
<div class="text-center">
<h1 class="text-4xl sm:text-6xl lg:text-7xl font-display font-bold text-gray-900 mb-6 leading-tight animate-fade-in">
<h1 class="text-5xl sm:text-6xl lg:text-7xl font-display font-bold text-gray-900 mb-6 leading-tight animate-fade-in">
Willkommen beim<br>
<span class="text-primary-600">Harheimer TC</span>
</h1>
@@ -163,3 +163,4 @@ const yearsSinceFounding = new Date().getFullYear() - foundingYear
animation: fadeIn 0.8s ease-out 0.4s both;
}
</style>

View File

@@ -58,9 +58,7 @@
</p>
</div>
<p class="text-sm text-gray-800">
{{ formatMatchTeamName(game.HeimMannschaft, game.HeimMannschaftAltersklasse, game.Altersklasse) }}
vs
{{ formatMatchTeamName(game.GastMannschaft, game.GastMannschaftAltersklasse, game.Altersklasse) }}
{{ game.HeimMannschaft }} vs {{ game.GastMannschaft }}
</p>
</div>
</div>
@@ -71,7 +69,6 @@
<script setup>
import { computed, ref, watch } from 'vue'
import { formatTeamDisplayName } from '~/utils/team-display'
const props = defineProps({
season: {
@@ -94,13 +91,10 @@ const games = ref([])
const widgetTitle = computed(() => {
if (!props.teamName) return 'Mannschaft'
return formatTeamDisplayName(props.teamName, props.teamAgeGroup)
const youth = String(props.teamAgeGroup || '').toLowerCase().includes('jugend')
return youth ? `(J) ${props.teamName}` : props.teamName
})
function formatMatchTeamName(teamName, teamAgeGroup, competitionAgeGroup) {
return formatTeamDisplayName(teamName, teamAgeGroup, competitionAgeGroup) || '-'
}
const seasonLabel = computed(() => {
const match = String(props.season || '').match(/^(\d{2})--(\d{2})$/)
if (!match) return props.season || '-'
@@ -190,4 +184,4 @@ watch(
},
{ immediate: true }
)
</script>
</script>

View File

@@ -1,7 +1,7 @@
<template>
<section class="py-8 sm:py-10 bg-gray-50">
<section class="py-16 sm:py-20 bg-gray-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="text-center mb-6 sm:mb-8">
<div class="text-center mb-12">
<h2 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-4">
Kommende Termine
</h2>
@@ -12,7 +12,7 @@
<TermineVorschau />
</div>
<div class="text-center mt-5 sm:mt-6">
<div class="text-center mt-8">
<NuxtLink
to="/termine"
class="inline-flex items-center px-6 py-3 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors"
@@ -32,3 +32,4 @@
import { ArrowRight } from 'lucide-vue-next'
import TermineVorschau from './TermineVorschau.vue'
</script>

View File

@@ -5,11 +5,11 @@
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-full">
<div class="flex flex-col justify-between h-full py-2">
<!-- Hauptmenü -->
<div class="flex min-w-0 items-center gap-3">
<div class="flex justify-between items-center">
<!-- Logo -->
<NuxtLink
to="/"
class="flex shrink-0 items-center space-x-3 origin-left hover:scale-[1.02] transition-transform"
class="flex items-center space-x-3 hover:scale-105 transition-transform"
>
<img
src="~/assets/images/logos/Harheimer TC.svg"
@@ -23,12 +23,9 @@
</div>
</NuxtLink>
<div class="flex min-w-0 flex-1 flex-col">
<div style="display:flex;flex-direction:column;">
<!-- Desktop Navigation -->
<div
class="hidden min-w-0 max-w-full lg:flex lg:items-center lg:gap-1 lg:overflow-x-auto lg:whitespace-nowrap [scrollbar-color:theme(colors.primary.700)_transparent] [scrollbar-width:thin]"
aria-label="Hauptmenü horizontal scrollbar"
>
<div class="hidden lg:flex items-center space-x-1">
<NuxtLink
to="/"
class="px-4 py-2 text-gray-300 hover:text-white font-medium transition-all rounded-lg hover:bg-primary-700/50"
@@ -114,10 +111,10 @@
</NuxtLink>
</div>
<div class="hidden min-w-0 flex-1 lg:flex items-center h-6 border-t border-primary-700/20">
<div class="hidden lg:flex items-center h-6 border-t border-primary-700/20">
<div
v-if="currentSubmenu"
:class="currentSubmenu === 'mannschaften' ? 'relative min-w-0 flex-1' : currentSubmenu === 'intern' ? 'flex min-w-0 items-center gap-1' : 'flex min-w-0 items-center gap-1 overflow-x-auto whitespace-nowrap'"
class="flex items-center space-x-1"
>
<!-- Newsletter Submenu -->
<template v-if="currentSubmenu === 'newsletter'">
@@ -191,69 +188,41 @@
<!-- Mannschaften Submenu -->
<template v-if="currentSubmenu === 'mannschaften'">
<div
ref="mannschaftenSubmenuRail"
class="flex min-w-0 items-center gap-1 overflow-x-auto whitespace-nowrap scroll-smooth px-7 [scrollbar-color:theme(colors.primary.700)_transparent] [scrollbar-width:thin]"
tabindex="0"
aria-label="Mannschaften-Untermenü horizontal scrollbar"
@scroll.passive="updateMannschaftenSubmenuControls"
<NuxtLink
to="/mannschaften"
class="px-2.5 py-1 text-xs font-semibold text-white hover:bg-primary-700/50 rounded transition-all"
active-class="bg-primary-600"
>
Übersicht
</NuxtLink>
<div class="h-3 w-px bg-primary-700" />
<template
v-for="mannschaft in mannschaften"
:key="mannschaft.slug"
>
<NuxtLink
to="/mannschaften"
class="shrink-0 px-2.5 py-1 text-xs font-semibold text-white hover:bg-primary-700/50 rounded transition-all"
active-class="bg-primary-600"
>
Übersicht
</NuxtLink>
<div class="h-3 w-px shrink-0 bg-primary-700" />
<template
v-for="mannschaft in mannschaften"
:key="mannschaft.slug"
>
<NuxtLink
:to="`/mannschaften/${mannschaft.slug}`"
class="shrink-0 whitespace-nowrap px-2.5 py-1 text-xs text-gray-300 hover:text-white hover:bg-primary-700/50 rounded transition-all"
active-class="text-white bg-primary-600"
>
{{ mannschaft.mannschaft }}
</NuxtLink>
</template>
<div class="h-3 w-px shrink-0 bg-primary-700" />
<NuxtLink
to="/mannschaften/spielplaene"
class="shrink-0 whitespace-nowrap px-2.5 py-1 text-xs text-gray-300 hover:text-white hover:bg-primary-700/50 rounded transition-all"
:to="`/mannschaften/${mannschaft.slug}`"
class="px-2.5 py-1 text-xs text-gray-300 hover:text-white hover:bg-primary-700/50 rounded transition-all"
active-class="text-white bg-primary-600"
>
Spielpläne
{{ mannschaft.mannschaft }}
</NuxtLink>
<NuxtLink
to="/spielsysteme"
class="shrink-0 whitespace-nowrap px-2.5 py-1 text-xs text-gray-300 hover:text-white hover:bg-primary-700/50 rounded transition-all"
active-class="text-white bg-primary-600"
>
Spielsysteme
</NuxtLink>
</div>
<button
v-if="showMannschaftenSubmenuLeftControl"
type="button"
class="absolute inset-y-0 left-0 z-10 flex w-9 items-center justify-start bg-gradient-to-r from-primary-900 via-primary-900/90 to-transparent pl-1 text-primary-300 transition-colors hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-300"
aria-label="Vorherige Mannschaften anzeigen"
@pointerdown.stop
@click.stop.prevent="scrollMannschaftenSubmenuLeft"
</template>
<div class="h-3 w-px bg-primary-700" />
<NuxtLink
to="/mannschaften/spielplaene"
class="px-2.5 py-1 text-xs text-gray-300 hover:text-white hover:bg-primary-700/50 rounded transition-all"
active-class="text-white bg-primary-600"
>
</button>
<button
v-if="showMannschaftenSubmenuRightControl"
type="button"
class="absolute inset-y-0 right-0 z-10 flex w-9 items-center justify-end bg-gradient-to-l from-primary-900 via-primary-900/90 to-transparent pr-1 text-primary-300 transition-colors hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-300"
aria-label="Weitere Mannschaften anzeigen"
@pointerdown.stop
@click.stop.prevent="scrollMannschaftenSubmenuRight"
Spielpläne
</NuxtLink>
<NuxtLink
to="/spielsysteme"
class="px-2.5 py-1 text-xs text-gray-300 hover:text-white hover:bg-primary-700/50 rounded transition-all"
active-class="text-white bg-primary-600"
>
</button>
Spielsysteme
</NuxtLink>
</template>
<!-- Training Submenu -->
@@ -290,8 +259,7 @@
<!-- Intern Submenu -->
<template v-if="currentSubmenu === 'intern'">
<div class="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto whitespace-nowrap">
<NuxtLink
<NuxtLink
to="/mitgliederbereich"
class="px-2.5 py-1 text-xs font-semibold text-white hover:bg-primary-700/50 rounded transition-all"
active-class="bg-primary-600"
@@ -311,7 +279,7 @@
class="px-2.5 py-1 text-xs text-gray-300 hover:text-white hover:bg-primary-700/50 rounded transition-all"
active-class="text-white bg-primary-600"
>
TTR / QTTR
QTTR
</NuxtLink>
<NuxtLink
to="/mitgliederbereich/news"
@@ -355,10 +323,9 @@
Kontaktanfragen
</NuxtLink>
</template>
</div>
<template v-if="isAdmin">
<div class="h-3 w-px shrink-0 bg-primary-700" />
<div class="relative shrink-0 inline-block">
<div class="h-3 w-px bg-primary-700" />
<div class="relative inline-block">
<button
class="px-2.5 py-1 text-xs text-yellow-300 hover:text-white hover:bg-primary-700/50 rounded transition-all flex items-center"
:class="route.path.startsWith('/cms') ? 'text-white bg-primary-600' : ''"
@@ -443,13 +410,6 @@
>
Einstellungen
</NuxtLink>
<NuxtLink
to="/cms/mytischtennis"
class="block px-4 py-2 text-sm text-gray-300 hover:bg-primary-600 hover:text-white transition-colors"
@click="showCmsDropdown = false"
>
myTischtennis
</NuxtLink>
<NuxtLink
to="/cms/benutzer"
class="block px-4 py-2 text-sm text-gray-300 hover:bg-primary-600 hover:text-white transition-colors"
@@ -766,7 +726,7 @@
class="block px-4 py-2 text-sm text-gray-400 hover:text-white hover:bg-primary-700/50 rounded-lg transition-colors"
@click="isMobileMenuOpen = false"
>
TTR / QTTR
QTTR
</NuxtLink>
<NuxtLink
to="/mitgliederbereich/news"
@@ -867,13 +827,6 @@
>
Einstellungen
</NuxtLink>
<NuxtLink
to="/cms/mytischtennis"
class="block px-4 py-2 text-sm text-yellow-300 hover:text-white hover:bg-primary-700/50 rounded-lg transition-colors"
@click="isMobileMenuOpen = false"
>
myTischtennis
</NuxtLink>
<NuxtLink
v-if="canManageUsers"
to="/cms/benutzer"
@@ -900,7 +853,7 @@
</template>
<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick, watch } from 'vue'
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { Menu, X, ChevronDown } from 'lucide-vue-next'
@@ -908,9 +861,6 @@ const route = useRoute()
const isMobileMenuOpen = ref(false)
const mobileSubmenu = ref(null)
const mannschaften = ref([])
const mannschaftenSubmenuRail = ref(null)
const showMannschaftenSubmenuLeftControl = ref(false)
const showMannschaftenSubmenuRightControl = ref(false)
const hasGalleryImages = ref(false)
const showCmsDropdown = ref(false)
const authStore = useAuthStore()
@@ -948,38 +898,6 @@ const toggleMobileSubmenu = (menu) => {
mobileSubmenu.value = mobileSubmenu.value === menu ? null : menu
}
const updateMannschaftenSubmenuControls = () => {
const rail = mannschaftenSubmenuRail.value
if (!rail) return
const canScroll = rail.scrollWidth > rail.clientWidth + 1
const atStart = rail.scrollLeft <= 1
const atEnd = rail.scrollLeft + rail.clientWidth >= rail.scrollWidth - 1
showMannschaftenSubmenuLeftControl.value = canScroll && !atStart
showMannschaftenSubmenuRightControl.value = canScroll && !atEnd
}
const scrollMannschaftenSubmenuLeft = () => {
const rail = mannschaftenSubmenuRail.value
if (!rail) return
rail.scrollBy({
left: -Math.max(rail.clientWidth * 0.8, 160),
behavior: 'smooth'
})
}
const scrollMannschaftenSubmenuRight = () => {
const rail = mannschaftenSubmenuRail.value
if (!rail) return
rail.scrollBy({
left: Math.max(rail.clientWidth * 0.8, 160),
behavior: 'smooth'
})
}
const loadMannschaften = async () => {
try {
const attempt = async () => {
@@ -1064,23 +982,16 @@ onMounted(() => {
// Listen for global updates to mannschaften (e.g., CMS saved)
if (typeof window !== 'undefined') {
window.addEventListener('mannschaften:changed', loadMannschaften)
window.addEventListener('resize', updateMannschaftenSubmenuControls)
}
nextTick(updateMannschaftenSubmenuControls)
})
onUnmounted(() => {
document.removeEventListener('click', handleDocumentClick)
if (typeof window !== 'undefined') {
window.removeEventListener('mannschaften:changed', loadMannschaften)
window.removeEventListener('resize', updateMannschaftenSubmenuControls)
}
})
watch([currentSubmenu, mannschaften], () => {
nextTick(updateMannschaftenSubmenuControls)
}, { flush: 'post' })
const toggleSubmenu = (menu) => {
// Wenn wir schon im richtigen Bereich sind, nichts tun (Submenu bleibt offen)
// Wenn nicht, zur Hauptseite navigieren

View File

@@ -1,13 +1,9 @@
<template>
<section
class="bg-white"
:class="news.length === 0 && !isLoading ? 'py-8 sm:py-10' : 'py-10 sm:py-12'"
class="py-16 sm:py-20 bg-white min-h-[32rem]"
>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div
class="text-center"
:class="news.length === 0 && !isLoading ? 'mb-6 sm:mb-8' : 'mb-8 sm:mb-10'"
>
<div class="text-center mb-16">
<h2 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-4">
Aktuelles
</h2>
@@ -71,7 +67,7 @@
<div
v-else
class="max-w-xl mx-auto text-center bg-gray-50 border border-gray-200 rounded-xl p-5"
class="max-w-xl mx-auto text-center bg-gray-50 border border-gray-200 rounded-xl p-8"
>
<p class="text-gray-700 font-semibold mb-2">
Aktuell keine News
@@ -226,3 +222,4 @@ onUnmounted(() => {
opacity: 0;
}
</style>

View File

@@ -1,7 +1,7 @@
<template>
<section class="py-8 sm:py-10 bg-white">
<section class="py-16 bg-white">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="text-center mb-6 sm:mb-8">
<div class="text-center mb-12">
<h2 class="text-3xl font-bold text-gray-900 mb-4">
Nächste Spiele
</h2>
@@ -10,7 +10,7 @@
<!-- Loading State -->
<div
v-if="isLoading"
class="text-center py-4"
class="text-center py-8"
>
<svg
class="w-8 h-8 text-gray-400 mx-auto mb-4 animate-spin"
@@ -33,7 +33,7 @@
<!-- Error State -->
<div
v-else-if="error"
class="text-center py-4"
class="text-center py-8"
>
<svg
class="w-12 h-12 text-gray-400 mx-auto mb-4"
@@ -62,7 +62,7 @@
<!-- Empty State -->
<div
v-else-if="!upcomingGames || upcomingGames.length === 0"
class="text-center py-4"
class="text-center py-8"
>
<svg
class="w-12 h-12 text-gray-400 mx-auto mb-4"
@@ -146,7 +146,7 @@
Heim
</p>
<p class="font-semibold text-gray-900">
{{ formatTeamName(game.HeimMannschaft, game.HeimMannschaftAltersklasse, game.Altersklasse) }}
{{ formatTeamName(game.HeimMannschaft, game.HeimMannschaftAltersklasse) }}
</p>
</div>
<div class="text-center mx-4">
@@ -159,7 +159,7 @@
Gast
</p>
<p class="font-semibold text-gray-900">
{{ formatTeamName(game.GastMannschaft, game.GastMannschaftAltersklasse, game.Altersklasse) }}
{{ formatTeamName(game.GastMannschaft, game.GastMannschaftAltersklasse) }}
</p>
</div>
</div>
@@ -220,7 +220,6 @@
<script setup>
import { ref, onMounted, computed } from 'vue'
import { formatTeamDisplayName } from '~/utils/team-display'
const spielplanData = ref([])
const isLoading = ref(false)
@@ -356,10 +355,17 @@ const formatTime = (terminString) => {
}
}
const formatTeamName = (teamName, ageGroup, competitionAgeGroup) => {
const formatTeamName = (teamName, ageGroup) => {
if (!teamName) return 'Nicht angegeben'
return formatTeamDisplayName(teamName, ageGroup, competitionAgeGroup)
// Prüfe ob es Nachwuchs ist
const isNachwuchs = ageGroup && (
ageGroup.toLowerCase().includes('jugend') ||
teamName.toLowerCase().includes('jugend')
)
// Füge (J) für Nachwuchs hinzu
return isNachwuchs ? `(J) ${teamName}` : teamName
}
const formatRunde = (runde) => {

View File

@@ -45,7 +45,7 @@
<div
v-else
class="text-center py-4 bg-gray-50 rounded-lg"
class="text-center py-8 bg-gray-50 rounded-lg"
>
<Calendar
:size="32"
@@ -123,3 +123,4 @@ onMounted(() => {
loadTermine()
})
</script>

View File

@@ -219,10 +219,7 @@
>
<span class="text-sm text-gray-800">{{ team.label }}</span>
</label>
<p
v-if="!spielplanTeams.length"
class="px-4 py-3 text-sm text-gray-500"
>
<p v-if="!spielplanTeams.length" class="px-4 py-3 text-sm text-gray-500">
Noch keine importierten Spielplan-Teams verfügbar.
</p>
</div>

View File

@@ -56,17 +56,14 @@ has_tracked_files_under() {
install_dependencies() {
if [ -f "package-lock.json" ]; then
echo " Running: npm ci --no-audit"
# The registry audit endpoint is independent of package installation and
# can be temporarily unavailable (e.g. DNS EAI_AGAIN). Do not block a
# production rollout on that external advisory lookup.
if ! npm ci --no-audit --fund=false; then
echo " Running: npm ci"
if ! npm ci; then
echo " WARNING: npm ci fehlgeschlagen (Lockfile ggf. nicht synchron). Fallback auf npm install..."
npm install --no-audit --fund=false
npm install
fi
else
echo " WARNING: package-lock.json fehlt. Führe npm install aus..."
npm install --no-audit --fund=false
npm install
fi
}
@@ -105,18 +102,6 @@ install_dependencies_if_needed() {
printf '%s\n' "$current_lock_hash" > "$lock_hash_file"
}
install_playwright_browser() {
if [ ! -d "node_modules/playwright" ]; then
echo " Playwright ist nicht installiert; Browser-Installation wird übersprungen"
return 0
fi
# Muss mit demselben Benutzer laufen, der später den PM2-Prozess startet;
# Playwright legt den Browser im benutzerspezifischen Cache ab.
echo " Installing/verifying Playwright Chromium browser..."
npx playwright install chromium
}
use_project_node() {
export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
if [ -s "$NVM_DIR/nvm.sh" ]; then
@@ -293,16 +278,21 @@ echo "3. Installing dependencies..."
use_project_node
ensure_node_version
install_dependencies_if_needed
install_playwright_browser
# 4. Stop running apps before replacing build artifacts
echo ""
echo "4. Stopping PM2 before replacing build artifacts..."
if command -v pm2 >/dev/null 2>&1 && pm2 describe harheimertc >/dev/null 2>&1; then
pm2 stop harheimertc || true
echo " ✓ harheimertc gestoppt"
if command -v pm2 >/dev/null 2>&1; then
for instance_name in harheimertc harheimertc-3102; do
if pm2 describe "$instance_name" >/dev/null 2>&1; then
pm2 stop "$instance_name" || true
echo "$instance_name gestoppt"
else
echo " PM2-Prozess $instance_name läuft nicht"
fi
done
else
echo " PM2-Prozess harheimertc läuft nicht oder PM2 ist nicht verfügbar"
echo " PM2 ist nicht verfügbar"
fi
# 5. Remove old build (but keep data!)
@@ -569,14 +559,18 @@ restart_pm2_instance() {
fi
}
# Starte/Neustarte die Produktionsinstanz
# Starte/Neustarte beide Instanzen
INSTANCE_ERRORS=0
if ! restart_pm2_instance "harheimertc"; then
INSTANCE_ERRORS=$((INSTANCE_ERRORS + 1))
fi
# Prüfe, ob der Prozess läuft
if ! restart_pm2_instance "harheimertc-3102"; then
INSTANCE_ERRORS=$((INSTANCE_ERRORS + 1))
fi
# Prüfe, ob beide Prozesse laufen
sleep 2
echo ""
echo " Checking PM2 instances status..."
@@ -588,11 +582,19 @@ else
INSTANCE_ERRORS=$((INSTANCE_ERRORS + 1))
fi
if pm2 describe harheimertc-3102 | grep -q "online"; then
echo " ✓ PM2-Prozess 'harheimertc-3102' läuft (online)"
else
echo " WARNING: PM2-Prozess 'harheimertc-3102' ist nicht online. Prüfe Logs: pm2 logs harheimertc-3102"
INSTANCE_ERRORS=$((INSTANCE_ERRORS + 1))
fi
if [ "$INSTANCE_ERRORS" -gt 0 ]; then
echo ""
echo "WARNING: Einige PM2-Instanzen haben Probleme. Bitte manuell prüfen:"
echo " pm2 status"
echo " pm2 logs harheimertc"
echo " pm2 logs harheimertc-3102"
fi
echo ""
@@ -601,5 +603,8 @@ echo "The application is now running with the latest code and your production da
echo ""
echo "Useful commands:"
echo " pm2 logs harheimertc # View logs (Port 3100)"
echo " pm2 logs harheimertc-3102 # View logs (Port 3102)"
echo " pm2 status # View status"
echo " pm2 restart harheimertc # Restart instance on port 3100"
echo " pm2 restart harheimertc-3102 # Restart instance on port 3102"
echo " pm2 restart all # Restart all instances"

View File

@@ -69,17 +69,14 @@ has_tracked_files_under() {
install_dependencies() {
if [ -f "package-lock.json" ]; then
echo " Running: npm ci --no-audit"
# The registry audit endpoint is independent of package installation and
# can be temporarily unavailable (e.g. DNS EAI_AGAIN). Do not block a
# test rollout on that external advisory lookup.
if ! npm ci --no-audit --fund=false; then
echo " Running: npm ci"
if ! npm ci; then
echo " WARNING: npm ci fehlgeschlagen (Lockfile ggf. nicht synchron). Fallback auf npm install..."
npm install --no-audit --fund=false
npm install
fi
else
echo " WARNING: package-lock.json fehlt. Führe npm install aus..."
npm install --no-audit --fund=false
npm install
fi
}
@@ -118,18 +115,6 @@ install_dependencies_if_needed() {
printf '%s\n' "$current_lock_hash" > "$lock_hash_file"
}
install_playwright_browser() {
if [ ! -d "node_modules/playwright" ]; then
echo " Playwright ist nicht installiert; Browser-Installation wird übersprungen"
return 0
fi
# Muss mit demselben Benutzer laufen, der später den PM2-Prozess startet;
# Playwright legt den Browser im benutzerspezifischen Cache ab.
echo " Installing/verifying Playwright Chromium browser..."
npx playwright install chromium
}
use_project_node() {
export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
if [ -s "$NVM_DIR/nvm.sh" ]; then
@@ -299,7 +284,6 @@ echo "3. Installing dependencies..."
use_project_node
ensure_node_version
install_dependencies_if_needed
install_playwright_browser
# 4. Stop running app before replacing build artifacts
echo ""
@@ -583,10 +567,9 @@ restart_pm2_instance() {
# Starte/Neustarte Test-Instanz
if ! restart_pm2_instance "harheimertc.test"; then
echo ""
echo "ERROR: PM2-Instanz konnte nicht gestartet werden."
echo "WARNING: PM2-Instanz konnte nicht gestartet werden. Bitte manuell prüfen:"
echo " pm2 status"
echo " pm2 logs harheimertc.test"
exit 1
fi
# Prüfe, ob der Prozess läuft
@@ -597,16 +580,9 @@ echo " Checking PM2 instance status..."
if pm2 describe harheimertc.test | grep -q "online"; then
echo " ✓ PM2-Prozess 'harheimertc.test' läuft (online)"
else
echo " ERROR: PM2-Prozess 'harheimertc.test' ist nicht online. Prüfe Logs: pm2 logs harheimertc.test"
exit 1
echo " WARNING: PM2-Prozess 'harheimertc.test' ist nicht online. Prüfe Logs: pm2 logs harheimertc.test"
fi
if ! curl --fail --silent --show-error --max-time 15 http://127.0.0.1:3102/ >/dev/null; then
echo "ERROR: Test-Instanz antwortet nicht auf Port 3102."
exit 1
fi
echo " ✓ HTTP-Healthcheck auf Port 3102 erfolgreich"
echo ""
echo "=== Test-Instanz Deployment completed successfully! ==="
echo "The test application is now running with the latest code and your test data preserved."

View File

@@ -10,7 +10,7 @@ git pull origin main
# Dependencies installieren
echo "📦 Installing dependencies..."
npm install --no-audit --fund=false
npm install
# Website bauen (Static Generation)
echo "🔨 Building website..."

View File

@@ -61,6 +61,22 @@ module.exports = {
out_file: '/var/log/pm2/harheimertc-out.log',
log_file: '/var/log/pm2/harheimertc-combined.log',
time: true
},
{
name: 'harheimertc-3102',
// Zweite Instanz auf Port 3102
script: 'node',
args: '.output/server/index.mjs',
cwd: '/var/www/harheimertc',
instances: 1,
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: createEnv(3102),
error_file: '/var/log/pm2/harheimertc-3102-error.log',
out_file: '/var/log/pm2/harheimertc-3102-out.log',
log_file: '/var/log/pm2/harheimertc-3102-combined.log',
time: true
}
]
}

View File

@@ -58,7 +58,7 @@ module.exports = {
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: createEnv(3102),
env: createEnv(process.env.PORT || 3102),
error_file: '/var/log/pm2/harheimertc.test-error.log',
out_file: '/var/log/pm2/harheimertc.test-out.log',
log_file: '/var/log/pm2/harheimertc.test-combined.log',

3422
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "harheimertc-website",
"version": "1.8.9",
"version": "1.8.4",
"description": "Moderne Webseite für den Harheimer Tischtennis Club",
"private": true,
"type": "module",
@@ -18,7 +18,7 @@
"test": "vitest run",
"test:data-rotation": "vitest run tests/data-file-rotation.spec.ts",
"check-security": "node scripts/verify-no-public-writes.js",
"smoke-local": "BASE_URL=http://127.0.0.1:3100 node scripts/smoke-test.js",
"smoke-local": "BASE_URL=http://127.0.0.1:3100 node scripts/smoke-tests.js",
"sync-public-data": "node scripts/sync-public-data.js",
"data-backups:list": "node scripts/data-backup-restore.js list",
"data-backups:restore": "node scripts/data-backup-restore.js restore",
@@ -40,13 +40,12 @@
"jsonwebtoken": "^9.0.2",
"multer": "^2.0.2",
"nodemailer": "^9.0.1",
"nuxt": "^4.5.1",
"nuxt": "^4.1.3",
"pdf-lib": "^1.17.1",
"pdf-parse": "^2.4.5",
"pinia": "^3.0.3",
"playwright": "^1.62.1",
"quill": "2.0.2",
"sharp": "^0.35.3",
"quill": "^2.0.2",
"sharp": "^0.34.5",
"vue": "^3.5.22"
},
"devDependencies": {
@@ -68,7 +67,6 @@
},
"overrides": {
"@peculiar/x509": "1.13.0",
"esbuild": "0.28.1",
"qs": "6.16.0"
"esbuild": "0.28.1"
}
}

View File

@@ -201,20 +201,6 @@
</p>
</NuxtLink>
<NuxtLink
v-if="authStore.hasAnyRole('admin', 'vorstand')"
to="/cms/mytischtennis"
class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 hover:shadow-xl transition-all group"
>
<div class="flex items-center mb-4">
<div class="w-12 h-12 bg-teal-100 rounded-lg flex items-center justify-center group-hover:bg-teal-600 transition-colors">
<RefreshCw :size="24" class="text-teal-600 group-hover:text-white" />
</div>
<h2 class="ml-4 text-xl font-semibold text-gray-900">myTischtennis</h2>
</div>
<p class="text-gray-600">Vereinszugang und TTR-Synchronisierung</p>
</NuxtLink>
<!-- Benutzerverwaltung (Admin ODER Vorstand) -->
<NuxtLink
v-if="authStore.hasAnyRole('admin', 'vorstand')"
@@ -263,7 +249,7 @@
</template>
<script setup>
import { Newspaper, Calendar, Users, UserCog, Settings, Layout, Mail, ShieldAlert, RefreshCw } from 'lucide-vue-next'
import { Newspaper, Calendar, Users, UserCog, Settings, Layout, Mail, ShieldAlert } from 'lucide-vue-next'
import { ref, onMounted } from 'vue'
const authStore = useAuthStore()

View File

@@ -1,52 +0,0 @@
<template>
<div class="min-h-screen bg-gray-50 py-10">
<div class="max-w-2xl mx-auto px-4">
<h1 class="text-3xl font-display font-bold text-gray-900">myTischtennis-Verbindung</h1>
<p class="mt-2 text-gray-600">Vereinszugang für den geschützten Import aktueller TTR- und QTTR-Werte.</p>
<form class="mt-8 bg-white rounded-xl shadow-lg p-6 space-y-5" @submit.prevent="save">
<div class="rounded-lg bg-amber-50 border border-amber-200 p-4 text-sm text-amber-900">
Das Passwort wird verschlüsselt auf dem Server gespeichert und nie wieder angezeigt. Zugriff haben ausschließlich Admin und Vorstand.
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">myTischtennis-E-Mail</label>
<input v-model.trim="form.email" type="email" required autocomplete="username" class="w-full rounded-lg border border-gray-300 px-3 py-2">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Passwort</label>
<input v-model="form.password" type="password" required autocomplete="current-password" class="w-full rounded-lg border border-gray-300 px-3 py-2">
</div>
<div class="grid sm:grid-cols-2 gap-4">
<label class="block text-sm font-medium text-gray-700">Verband<input v-model.trim="form.association" required class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2"></label>
<label class="block text-sm font-medium text-gray-700">Vereinsnummer<input v-model.trim="form.clubId" required class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2"></label>
</div>
<p v-if="status.configured" class="text-sm text-gray-600">Hinterlegt: {{ status.email }} · letzter erfolgreicher Abruf: {{ formattedLastImport }}</p>
<p v-if="status.lastImportError" class="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
Letzter Abruf fehlgeschlagen: {{ status.lastImportError }}
</p>
<p v-if="message" class="text-sm" :class="error ? 'text-red-700' : 'text-green-700'">{{ message }}</p>
<div class="flex gap-3 flex-wrap">
<button :disabled="busy" class="rounded-lg bg-primary-600 px-4 py-2 font-semibold text-white disabled:opacity-60">Zugang speichern</button>
<button type="button" :disabled="busy || !status.configured" class="rounded-lg border border-primary-600 px-4 py-2 font-semibold text-primary-700 disabled:opacity-60" @click="runImport">Jetzt abrufen</button>
<button v-if="authStore.hasRole('admin')" type="button" :disabled="busy" class="rounded-lg border border-teal-600 px-4 py-2 font-semibold text-teal-700 disabled:opacity-60" @click="sendTestPush">Push-Test an mich senden</button>
</div>
</form>
</div>
</div>
</template>
<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useAuthStore } from '~/stores/auth'
definePageMeta({ middleware: 'auth' })
useHead({ title: 'myTischtennis-Verbindung CMS' })
const form = reactive({ email: '', password: '', association: 'HeTTV', clubId: '43030' })
const authStore = useAuthStore()
const status = ref({ configured: false })
const busy = ref(false); const message = ref(''); const error = ref(false)
const formattedLastImport = computed(() => status.value.lastSuccessfulImportAt ? new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(status.value.lastSuccessfulImportAt)) : 'noch nie')
async function load() { status.value = await $fetch('/api/cms/mytischtennis') }
async function save() { busy.value = true; message.value = ''; error.value = false; try { status.value = await $fetch('/api/cms/mytischtennis', { method: 'PUT', body: form }); form.password = ''; message.value = 'Zugang verschlüsselt gespeichert.' } catch { error.value = true; message.value = 'Zugang konnte nicht gespeichert werden.' } finally { busy.value = false } }
async function runImport() { busy.value = true; message.value = ''; error.value = false; try { const result = await $fetch('/api/cms/mytischtennis/import', { method: 'POST' }); message.value = `${result.rowCount} Werte wurden aktualisiert.`; await load() } catch (caught) { error.value = true; message.value = caught?.data?.message || 'Abruf fehlgeschlagen. Details stehen im Serverlog.'; await load().catch(() => {}) } finally { busy.value = false } }
async function sendTestPush() { busy.value = true; message.value = ''; error.value = false; try { const result = await $fetch('/api/cms/notifications/test', { method: 'POST' }); if (result.registeredTokenCount === 0) { message.value = 'Kein Android-Token für dieses Konto gespeichert.'; error.value = true } else if (result.skipped) { message.value = `${result.registeredTokenCount} Android-Gerät(e) registriert, aber der FCM-Push-Dienst ist auf dem Server nicht konfiguriert.`; error.value = true } else if (result.deliveryError) { message.value = `${result.registeredTokenCount} Android-Gerät(e) registriert, aber: ${result.deliveryError}`; error.value = true } else if (result.sent > 0) { message.value = `Push-Test wurde an ${result.sent} registrierte(s) Android-Gerät(e) gesendet.` } else { message.value = `${result.registeredTokenCount} Android-Gerät(e) registriert, Zustellung fehlgeschlagen. Bitte Serverlog prüfen.`; error.value = true } } catch (caught) { error.value = true; message.value = caught?.data?.statusMessage || caught?.data?.message || 'Push-Test konnte nicht gesendet werden.' } finally { busy.value = false } }
onMounted(load)
</script>

View File

@@ -216,7 +216,7 @@
class="relative z-30 px-4 sm:px-6 lg:px-8"
:class="hasHeroSection ? '-mt-44 sm:-mt-48 lg:-mt-52' : 'mt-8'"
>
<div class="featured-widget-shell max-w-6xl mx-auto rounded-2xl border border-gray-200 bg-white/25 backdrop-blur-md overflow-hidden">
<div class="featured-widget-shell max-w-6xl mx-auto rounded-2xl border border-gray-200 bg-white/25 backdrop-blur-md overflow-hidden min-h-[22rem] sm:min-h-[25rem]">
<HomeSpielplanTeamWidget
v-if="featuredWidgetSection.id === 'spielplan_team'"
:season="featuredWidgetSection.config?.season"
@@ -627,15 +627,9 @@ async function saveEditor() {
background-color: transparent !important;
}
.featured-widget-shell :deep(.py-8),
.featured-widget-shell :deep(.py-10),
.featured-widget-shell :deep(.py-12),
.featured-widget-shell :deep(.py-16),
.featured-widget-shell :deep(.sm\:py-10),
.featured-widget-shell :deep(.sm\:py-12),
.featured-widget-shell :deep(.sm\:py-16),
.featured-widget-shell :deep(.sm\:py-20) {
padding-top: 1.5rem !important;
padding-bottom: 1.5rem !important;
padding-bottom: 2rem !important;
}
</style>

View File

@@ -362,7 +362,7 @@
<script setup>
import { ref, computed, onMounted } from 'vue'
import { rowMatchesTeamFilter } from '~/utils/spielplan-filter.js'
import { rowMatchesTeamFilter } from '../../utils/spielplan-filter.js'
const route = useRoute()

View File

@@ -360,7 +360,7 @@
<script setup>
import { ref, onMounted } from 'vue'
import { filterSpielplanRows, toApiTeamParam } from '~/utils/spielplan-filter.js'
import { filterSpielplanRows, toApiTeamParam } from '../../utils/spielplan-filter.js'
const route = useRoute()
const router = useRouter()

View File

@@ -3,11 +3,18 @@
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
<div>
<h1 class="text-4xl sm:text-5xl font-display font-bold text-gray-900 mb-4">
TTR- und QTTR-Werte
QTTR-Werte
</h1>
<div class="w-24 h-1 bg-primary-600 mb-6" />
<p class="text-lg text-gray-700 max-w-3xl">
Aktuelle TTR- und QTTR-Werte des Harheimer TC. Der Abruf erfolgt über die geschützte Vereinsverbindung.
Aus technischen Gründen sind nur die QTTR-Werte verfügbar. Für TTR bitte auf
<a
:href="externalUrl"
target="_blank"
rel="noopener noreferrer"
class="text-primary-600 hover:text-primary-800 underline"
>myTischtennis</a>
wechseln.
</p>
</div>
@@ -30,13 +37,13 @@
v-if="pending"
class="py-12 text-center text-gray-500"
>
Lade TTR- und QTTR-Werte...
Lade QTTR-Werte...
</div>
<div
v-else-if="error"
class="rounded-lg border border-red-200 bg-red-50 p-4 text-red-800"
>
{{ error.statusMessage || error.message || 'TTR- und QTTR-Werte konnten nicht geladen werden.' }}
{{ error.statusMessage || error.message || 'QTTR-Werte konnten nicht geladen werden.' }}
</div>
<div
v-else
@@ -54,9 +61,6 @@
<th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">
Verein
</th>
<th class="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wider text-gray-500">
TTR
</th>
<th class="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wider text-gray-500">
QTTR
</th>
@@ -79,9 +83,6 @@
<td class="px-4 py-3 text-sm text-gray-700">
{{ row.clubName || 'Harheimer TC' }}
</td>
<td class="px-4 py-3 text-right text-lg font-semibold text-gray-900 tabular-nums">
{{ row.currentTtr ?? '' }}
</td>
<td class="px-4 py-3 text-right text-lg font-semibold text-gray-900 tabular-nums">
{{ row.currentQttr ?? '' }}
</td>
@@ -98,6 +99,7 @@
import { computed } from 'vue'
const authStore = useAuthStore()
const externalUrl = 'https://www.mytischtennis.de/rankings/andro-rangliste?continent=all&country=Deutschland&all-players=on&as=DE.WE.R4.07&di=DE.WE.R4.07.04&area=DE.WE.R4.07.04.43&clubnr-search=Harheimer+TC&clubnr=43030&fednickname=HeTTV&gender=all&current-ranking=yes&ttr-range=100%3B3000&birth-range=1926%3B2021'
definePageMeta({
middleware: 'auth',
@@ -124,7 +126,7 @@ function isMaleGender(value) {
function isFemaleGender(value) {
const gender = normalizeName(value)
return gender.startsWith('w') || gender.includes('weib') || gender.includes('frau') || gender.includes('female')
return gender.startsWith('w') || gender.includes('weib') || gender.includes('frau')
}
function isOwnRow(playerName) {
@@ -178,6 +180,6 @@ function formatDate(value) {
}
useHead({
title: 'TTR- und QTTR-Werte - Harheimer TC'
title: 'QTTR-Werte - Harheimer TC'
})
</script>

View File

@@ -1,10 +0,0 @@
import { getUserFromToken, hasAnyRole } from '../../utils/auth.js'
import { publicConnectionStatus, readMyTischtennisConnection } from '../../utils/mytischtennis-connection.js'
export default defineEventHandler(async (event) => {
const token = getCookie(event, 'auth_token') || getHeader(event, 'authorization')?.replace(/^Bearer\s+/i, '')
const user = token ? await getUserFromToken(token) : null
if (!user) throw createError({ statusCode: 401, statusMessage: 'Nicht authentifiziert' })
if (!hasAnyRole(user, 'admin', 'vorstand')) throw createError({ statusCode: 403, statusMessage: 'Keine Berechtigung' })
return publicConnectionStatus(await readMyTischtennisConnection())
})

View File

@@ -1,17 +0,0 @@
import { getUserFromToken, hasAnyRole } from '../../utils/auth.js'
import { readMyTischtennisConnection, saveMyTischtennisConnection, publicConnectionStatus } from '../../utils/mytischtennis-connection.js'
export default defineEventHandler(async (event) => {
const token = getCookie(event, 'auth_token') || getHeader(event, 'authorization')?.replace(/^Bearer\s+/i, '')
const user = token ? await getUserFromToken(token) : null
if (!user) throw createError({ statusCode: 401, statusMessage: 'Nicht authentifiziert' })
if (!hasAnyRole(user, 'admin', 'vorstand')) throw createError({ statusCode: 403, statusMessage: 'Keine Berechtigung' })
const body = await readBody(event)
if (!/^\S+@\S+\.\S+$/.test(String(body.email || '')) || String(body.password || '').length < 1) {
throw createError({ statusCode: 400, statusMessage: 'E-Mail und Passwort sind erforderlich.' })
}
const previous = await readMyTischtennisConnection()
const connection = { ...previous, email: body.email.trim(), password: body.password, association: String(body.association || 'HeTTV'), clubId: String(body.clubId || '43030') }
await saveMyTischtennisConnection(connection)
return publicConnectionStatus(connection)
})

View File

@@ -1,24 +0,0 @@
import { getUserFromToken, hasAnyRole } from '../../../utils/auth.js'
import { importQttrValues } from '../../../utils/qttr-import.js'
import { readMyTischtennisConnection, saveMyTischtennisConnection } from '../../../utils/mytischtennis-connection.js'
export default defineEventHandler(async (event) => {
const token = getCookie(event, 'auth_token') || getHeader(event, 'authorization')?.replace(/^Bearer\s+/i, '')
const user = token ? await getUserFromToken(token) : null
if (!user) throw createError({ statusCode: 401, statusMessage: 'Nicht authentifiziert' })
if (!hasAnyRole(user, 'admin', 'vorstand')) throw createError({ statusCode: 403, statusMessage: 'Keine Berechtigung' })
const connection = await readMyTischtennisConnection()
if (!connection) throw createError({ statusCode: 409, statusMessage: 'Keine myTischtennis-Verbindung eingerichtet.' })
try {
const result = await importQttrValues({ connection })
return { success: true, rowCount: result.rowCount, importedAt: result.importedAt }
} catch (error) {
const fullDetail = String(error.stack || error.message || error)
const detail = fullDetail.slice(0, 500)
// Vollständig nur ins serverseitige PM2-Log schreiben; im CMS wird der Fehler
// bewusst gekürzt gespeichert, damit Browser-/Systempfade nicht öffentlich werden.
console.error('[mytischtennis] TTR-Abruf fehlgeschlagen:', fullDetail)
await saveMyTischtennisConnection({ ...connection, lastImportError: detail })
throw createError({ statusCode: 502, message: 'TTR-Abruf fehlgeschlagen. Details stehen im Serverlog.' })
}
})

View File

@@ -1,22 +0,0 @@
import { getUserFromToken, hasRole } from '../../../utils/auth.js'
import { androidPushTokenCountForUser, sendTestPushToUser } from '../../../utils/push-notifications.js'
export default defineEventHandler(async (event) => {
const token = getCookie(event, 'auth_token') || getHeader(event, 'authorization')?.replace(/^Bearer\s+/i, '')
const user = token ? await getUserFromToken(token) : null
if (!user) throw createError({ statusCode: 401, statusMessage: 'Nicht authentifiziert' })
if (!hasRole(user, 'admin')) throw createError({ statusCode: 403, statusMessage: 'Nur Administratoren dürfen einen Push-Test auslösen.' })
const registeredTokenCount = await androidPushTokenCountForUser(user.id)
try {
const result = await sendTestPushToUser(user.id)
return { success: true, registeredTokenCount, ...result }
} catch (error) {
console.error('FCM Test-Push konnte nicht vorbereitet werden:', error)
return {
success: false,
registeredTokenCount,
deliveryError: 'Die FCM-Serververbindung konnte nicht aufgebaut werden. Details stehen im Serverlog.'
}
}
})

View File

@@ -1,15 +1,18 @@
import { listSpielplanSeasons, readSpielplanData, validateSeasonSlug } from '../../utils/spielplan-data.js'
import { formatTeamDisplayName } from '~/utils/team-display.js'
function teamLabel(teamName, teamAgeGroup, competitionAgeGroup) {
return formatTeamDisplayName(teamName, teamAgeGroup, competitionAgeGroup)
function teamLabel(teamName, teamAgeGroup) {
const name = String(teamName || '').trim()
const age = String(teamAgeGroup || '').trim()
if (!name) return ''
const isYouth = age.toLowerCase().includes('jugend') || name.toLowerCase().includes('jugend')
return isYouth ? `(J) ${name}` : name
}
function extractHarheimerTeams(rows) {
const seen = new Set()
const teams = []
const addTeam = (teamName, teamAgeGroup, competitionAgeGroup) => {
const addTeam = (teamName, teamAgeGroup) => {
const name = String(teamName || '').trim()
if (!name) return
const age = String(teamAgeGroup || '').trim()
@@ -18,7 +21,7 @@ function extractHarheimerTeams(rows) {
seen.add(key)
teams.push({
key,
label: teamLabel(name, age, competitionAgeGroup),
label: teamLabel(name, age),
teamName: name,
teamAgeGroup: age
})
@@ -26,10 +29,10 @@ function extractHarheimerTeams(rows) {
for (const row of rows || []) {
if (String(row.HeimVereinName || '').trim() === 'Harheimer TC') {
addTeam(row.HeimMannschaft, row.HeimMannschaftAltersklasse, row.Altersklasse)
addTeam(row.HeimMannschaft, row.HeimMannschaftAltersklasse)
}
if (String(row.GastVereinName || '').trim() === 'Harheimer TC') {
addTeam(row.GastMannschaft, row.GastMannschaftAltersklasse, row.Altersklasse)
addTeam(row.GastMannschaft, row.GastMannschaftAltersklasse)
}
}
@@ -55,4 +58,4 @@ export default defineEventHandler(async (event) => {
seasons,
teams: extractHarheimerTeams(dataResult.data)
}
})
})

View File

@@ -2,7 +2,6 @@ import fs from 'fs/promises'
import path from 'path'
import { requireUserWithAnyRole } from '../../utils/auth.js'
import { decryptObject } from '../../utils/encryption.js'
import { getServerDataPath } from '../../utils/paths.js'
export default defineEventHandler(async (event) => {
try {
@@ -18,7 +17,7 @@ export default defineEventHandler(async (event) => {
})
}
const dataDir = getServerDataPath('membership-applications')
const dataDir = path.join(process.cwd(), 'server/data/membership-applications')
// Prüfen ob Verzeichnis existiert
try {

View File

@@ -1,6 +1,5 @@
import fs from 'fs/promises'
import path from 'path'
import { createHmac, timingSafeEqual } from 'crypto'
import { getUserFromToken } from '../../../utils/auth.js'
import { getServerDataPath } from '../../../utils/paths.js'
@@ -48,27 +47,7 @@ export default defineEventHandler(async (event) => {
}
}
// Native apps cannot reliably reuse the httpOnly browser cookie that is
// set when the application is created. They receive the same short-lived
// authorization as a signed response token instead.
const signedDownloadToken = getHeader(event, 'x-membership-download-token')
if (signedDownloadToken) {
try {
const [payload, signature] = signedDownloadToken.split('.')
const secret = process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production'
const expected = createHmac('sha256', secret).update(payload).digest('base64url')
const validSignature = signature && timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
const tokenAge = Date.now() - Number(decoded.issuedAt)
if (validSignature && decoded.fileId === fileId && tokenAge >= 0 && tokenAge < 24 * 60 * 60 * 1000) {
isAuthorized = true
}
} catch (_error) {
// Invalid download tokens are treated as unauthorized.
}
}
// Browser clients continue to use the httpOnly cookie.
// Prüfen ob es sich um eine aktuelle Session handelt (innerhalb der letzten 24 Stunden)
const downloadToken = getCookie(event, 'download_token')
if (downloadToken) {

View File

@@ -1,13 +1,11 @@
import { exec } from 'child_process'
import { promisify } from 'util'
import { createHmac } from 'crypto'
import fs from 'fs/promises'
import path from 'path'
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'
import { getDownloadCookieOptionsWithMaxAge } from '../../utils/cookies.js'
import { sendMembershipEmail as sendMembershipEmailUtil } from '../../utils/email-service.js'
import { getProjectPath, getServerDataPath } from '../../utils/paths.js'
import { createMembershipApplication, removeMembershipApplication } from '../../utils/membership-applications.js'
// const require = createRequire(import.meta.url) // Nicht verwendet
const execAsync = promisify(exec)
@@ -312,18 +310,9 @@ function getDataPath(filename) {
return getServerDataPath(filename)
}
function createMembershipDownloadToken(fileId) {
const issuedAt = Date.now()
const payload = Buffer.from(JSON.stringify({ fileId, issuedAt })).toString('base64url')
const secret = process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production'
const signature = createHmac('sha256', secret).update(payload).digest('base64url')
return `${payload}.${signature}`
}
// Use central email service
export default defineEventHandler(async (event) => {
let application = null
try {
const body = await readBody(event)
@@ -349,10 +338,6 @@ export default defineEventHandler(async (event) => {
...body,
isVolljaehrig
}
// Persist the pending application before generating files or sending mail.
// This also makes repeated taps and concurrent requests idempotently fail.
application = await createMembershipApplication(data)
// Eindeutige Datei-ID generieren
const timestamp = Date.now()
@@ -645,11 +630,9 @@ export default defineEventHandler(async (event) => {
success: true,
message: 'Beitrittsformular erfolgreich aus Template erzeugt und E-Mail gesendet.',
downloadUrl: `/api/membership/download/${filename}.pdf`,
downloadToken: createMembershipDownloadToken(`${filename}.pdf`),
emailSuccess: emailResult.success,
emailMessage: emailResult.message,
usedTemplate: true,
applicationId: application.id
usedTemplate: true
}
}
@@ -707,10 +690,8 @@ export default defineEventHandler(async (event) => {
success: true,
message: 'Beitrittsformular erfolgreich erstellt und E-Mail gesendet.',
downloadUrl: `/api/membership/download/${filename}.pdf`,
downloadToken: createMembershipDownloadToken(`${filename}.pdf`),
emailSuccess: emailResult.success,
emailMessage: emailResult.message,
applicationId: application.id
}
} catch (latexError) {
@@ -745,22 +726,16 @@ export default defineEventHandler(async (event) => {
success: true,
message: 'Beitrittsformular erfolgreich erstellt und E-Mail gesendet (Fallback-Lösung).',
downloadUrl: `/api/membership/download/${fallbackFilename}`,
downloadToken: createMembershipDownloadToken(fallbackFilename),
emailSuccess: emailResult.success,
emailMessage: emailResult.message,
applicationId: application.id
}
}
} catch (error) {
// A failed generation must not leave a pending application that prevents
// the applicant from trying again.
await removeMembershipApplication(application?.id)
console.error('Fehler beim Generieren des PDFs:', error)
if (error?.statusCode) throw error
throw createError({
statusCode: 500,
statusMessage: 'Fehler beim Generieren des PDFs'
})
}
})
})

View File

@@ -1,8 +1,8 @@
import fs from 'fs/promises'
import path from 'path'
import { requireUserWithAnyRole } from '../../utils/auth.js'
import { decryptObject } from '../../utils/encryption.js'
import { saveMember } from '../../utils/members.js'
import { getServerDataPath } from '../../utils/paths.js'
export default defineEventHandler(async (event) => {
try {
@@ -43,7 +43,9 @@ export default defineEventHandler(async (event) => {
}
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
const filePath = getServerDataPath('membership-applications', `${id}.json`)
const dataDir = path.join(process.cwd(), 'server/data/membership-applications')
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
const filePath = path.join(dataDir, `${id}.json`)
// Antrag laden
const fileContent = await fs.readFile(filePath, 'utf8')
@@ -65,7 +67,6 @@ export default defineEventHandler(async (event) => {
const newMember = {
firstName: decryptedData.vorname,
lastName: decryptedData.nachname,
geburtsdatum: decryptedData.geburtsdatum,
email: decryptedData.email,
phone: decryptedData.telefon_privat || decryptedData.telefon_mobil || '',
address: `${decryptedData.strasse}, ${decryptedData.plz} ${decryptedData.ort}`,

View File

@@ -22,8 +22,7 @@ export default defineEventHandler(async (event) => {
upsertPushToken(users[userIndex], {
token: body.token,
platform: body.platform || 'android',
appVersion: body.appVersion || null,
installationId: body.installationId || null
appVersion: body.appVersion || null
})
await writeUsers(users)
return { success: true, message: 'Push-Token gespeichert.' }

View File

@@ -2,7 +2,7 @@ import fs from 'fs/promises'
import path from 'path'
import { readSpielplanData, validateSeasonSlug } from '../../utils/spielplan-data.js'
import { info as loggerInfo, error as loggerError } from '../../utils/logger.js'
import { filterSpielplanRows } from '~/utils/spielplan-filter.js'
import { filterSpielplanRows } from '../../../utils/spielplan-filter.js'
function seasonSlugToLabel(slug) {
const match = String(slug || '').match(/^(\d{2})--(\d{2})$/)

View File

@@ -221,23 +221,14 @@ export function normalizeDate(dateString) {
}
// Check for duplicate member based on firstName, lastName, and geburtsdatum
function normalizeIdentityPart(value) {
return String(value || '')
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9]+/g, ' ')
.trim()
.toLowerCase()
}
export function findDuplicateMember(members, firstName, lastName, geburtsdatum) {
const normalizedFirstName = normalizeIdentityPart(firstName)
const normalizedLastName = normalizeIdentityPart(lastName)
function findDuplicateMember(members, firstName, lastName, geburtsdatum) {
const normalizedFirstName = (firstName || '').trim().toLowerCase()
const normalizedLastName = (lastName || '').trim().toLowerCase()
const normalizedDate = normalizeDate(geburtsdatum)
return members.find(m => {
const mFirstName = normalizeIdentityPart(m.firstName)
const mLastName = normalizeIdentityPart(m.lastName)
const mFirstName = (m.firstName || '').trim().toLowerCase()
const mLastName = (m.lastName || '').trim().toLowerCase()
const mDate = normalizeDate(m.geburtsdatum)
return mFirstName === normalizedFirstName &&
@@ -316,3 +307,4 @@ export async function deleteMember(id) {
await writeMembers(filtered)
return true
}

View File

@@ -1,104 +0,0 @@
import { createHash, randomUUID } from 'crypto'
import { promises as fs } from 'fs'
import { decryptObject, encryptObject } from './encryption.js'
import { readMembers, findDuplicateMember, normalizeDate } from './members.js'
import { getServerDataPath } from './paths.js'
const APPLICATIONS_DIR = getServerDataPath('membership-applications')
const LOCKS_DIR = getServerDataPath('membership-application-locks')
function encryptionKey() {
return process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production'
}
function normalizeName(value) {
return String(value || '')
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9]+/g, ' ')
.trim()
.toLowerCase()
}
function identityHash(data) {
const identity = [normalizeName(data.vorname), normalizeName(data.nachname), normalizeDate(data.geburtsdatum)].join('|')
return createHash('sha256').update(identity).digest('hex')
}
async function withIdentityLock(hash, operation) {
await fs.mkdir(LOCKS_DIR, { recursive: true })
const lockPath = `${LOCKS_DIR}/${hash}.lock`
let handle
try {
handle = await fs.open(lockPath, 'wx')
} catch (error) {
if (error?.code === 'EEXIST') {
throw createError({ statusCode: 409, statusMessage: 'Für diese Person wird bereits ein Mitgliedschaftsantrag bearbeitet.' })
}
throw error
}
try {
return await operation()
} finally {
await handle.close().catch(() => {})
await fs.unlink(lockPath).catch(() => {})
}
}
async function findMatchingApplication(data) {
try {
const files = await fs.readdir(APPLICATIONS_DIR)
const target = identityHash(data)
for (const file of files.filter(file => file.endsWith('.json'))) {
try {
const application = JSON.parse(await fs.readFile(`${APPLICATIONS_DIR}/${file}`, 'utf8'))
if (application.identityHash === target) return application
if (application.encryptedData) {
const personalData = decryptObject(application.encryptedData, encryptionKey())
if (identityHash(personalData) === target) return application
}
} catch (error) {
console.warn('Mitgliedschaftsantrag konnte bei der Duplikatprüfung nicht gelesen werden:', { file, message: error.message })
}
}
return null
} catch (error) {
if (error?.code !== 'ENOENT') throw error
return null
}
}
export async function createMembershipApplication(data) {
const hash = identityHash(data)
if (!normalizeName(data.vorname) || !normalizeName(data.nachname) || !normalizeDate(data.geburtsdatum)) {
throw createError({ statusCode: 400, statusMessage: 'Vorname, Nachname und ein gültiges Geburtsdatum sind erforderlich.' })
}
return withIdentityLock(hash, async () => {
const members = await readMembers()
if (findDuplicateMember(members, data.vorname, data.nachname, data.geburtsdatum)) {
throw createError({ statusCode: 409, statusMessage: 'Für diese Person besteht bereits eine Mitgliedschaft.' })
}
const existing = await findMatchingApplication(data)
if (existing) {
throw createError({ statusCode: 409, statusMessage: 'Für diese Person liegt bereits ein Mitgliedschaftsantrag vor.' })
}
await fs.mkdir(APPLICATIONS_DIR, { recursive: true })
const application = {
id: randomUUID(),
timestamp: new Date().toISOString(),
status: 'pending',
identityHash: hash,
metadata: { mitgliedschaftsart: data.mitgliedschaftsart },
encryptedData: encryptObject(data, encryptionKey())
}
await fs.writeFile(`${APPLICATIONS_DIR}/${application.id}.json`, `${JSON.stringify(application, null, 2)}\n`, { encoding: 'utf8', flag: 'wx' })
return application
})
}
export async function removeMembershipApplication(applicationId) {
if (!applicationId) return
await fs.unlink(`${APPLICATIONS_DIR}/${applicationId}.json`).catch(error => {
if (error?.code !== 'ENOENT') throw error
})
}

View File

@@ -1,170 +0,0 @@
import { chromium } from 'playwright'
const BASE_URL = 'https://www.mytischtennis.de'
const HEADERS = { 'accept-language': 'de-DE,de;q=0.9', 'user-agent': 'Harheimer-TC-Vereinsverwaltung/1.0' }
function findAuthCookie(headers) {
const raw = headers.getSetCookie?.() || (headers.get('set-cookie') ? [headers.get('set-cookie')] : [])
return raw.find(value => value.startsWith('sb-10-auth-token='))?.split(';')[0] || null
}
function findEntries(value) {
if (!value || typeof value !== 'object') return null
if (Array.isArray(value.entries)) return value.entries
for (const child of Object.values(value)) {
const result = findEntries(child)
if (result) return result
}
return null
}
async function loginDirect(email, password) {
const page = await fetch(`${BASE_URL}/login?next=%2F`, { headers: HEADERS })
const html = await page.text()
if (/captcha/i.test(html)) throw new Error('CAPTCHA_REQUIRED')
const xsrf = html.match(/name=["']xsrf["'][^>]*value=["']([^"']+)/i)?.[1]
const form = new URLSearchParams({ email, password, intent: 'login' })
if (xsrf) form.set('xsrf', xsrf)
const result = await fetch(`${BASE_URL}/login?next=%2F&_data=routes%2F_auth%2B%2Flogin`, {
method: 'POST', headers: { ...HEADERS, 'content-type': 'application/x-www-form-urlencoded' }, body: form, redirect: 'manual'
})
const cookie = findAuthCookie(result.headers)
if (!cookie) throw new Error('Direkter myTischtennis-Login fehlgeschlagen.')
return cookie
}
async function loginWithBrowser(email, password) {
const browser = await chromium.launch({
headless: true,
args: ['--no-sandbox', '--disable-dev-shm-usage']
})
try {
const page = await browser.newPage()
// Das myTT-CAPTCHA wird erst nach dem Laden der Seite erzeugt. Der Ablauf
// entspricht der erprobten Integration im Trainingstagebuch.
const acceptConsentDialog = async (waitMs = 0) => {
if (waitMs) await page.waitForTimeout(waitMs)
for (const selector of [
'#onetrust-accept-btn-handler', 'button:has-text("Alle akzeptieren")',
'button:has-text("Akzeptieren")', 'button:has-text("Einverstanden")',
'button:has-text("Zustimmen")', '[data-testid="accept-button"]', '.cmp-accept-all', '.accept-all-btn'
]) {
try {
const button = page.locator(selector).first()
if (await button.count()) { await button.click({ timeout: 2_500 }); await page.waitForTimeout(800); return true }
} catch { /* try next CMP selector */ }
}
return false
}
await page.goto(BASE_URL, { waitUntil: 'domcontentloaded', timeout: 30_000 }).catch(() => {})
if (!await acceptConsentDialog()) await acceptConsentDialog(2_500)
await page.goto(`${BASE_URL}/login?next=%2F`, { waitUntil: 'domcontentloaded', timeout: 45_000 })
if (!await acceptConsentDialog()) await acceptConsentDialog(1_500)
await page.locator('input[name="email"]').fill(email)
await page.locator('input[name="password"]').fill(password)
// Exakt wie in trainingstagebuch: Das Widget wird nach dem DOM-Load
// nachgeladen; ein sofortiges count() würde es häufig übersehen.
await page.waitForSelector('private-captcha', { timeout: 8_000 }).catch(() => {})
const captchaHost = page.locator('private-captcha').first()
const hasCaptcha = await captchaHost.count() > 0
console.info('[mytischtennis] CAPTCHA widget detected:', hasCaptcha)
if (hasCaptcha) {
await page.waitForTimeout(1_200)
// Ein echter Playwright-Klick erzeugt im Gegensatz zu element.click() ein
// vertrauenswürdiges Pointer-Ereignis für das Widget.
await captchaHost.click({ timeout: 5_000, force: true }).catch(error => {
console.warn('[mytischtennis] CAPTCHA pointer click failed:', error.message)
})
await page.evaluate(() => {
const host = document.querySelector('private-captcha')
const checkbox = host?.shadowRoot?.querySelector('#pc-checkbox')
if (!checkbox) return
checkbox.click()
checkbox.dispatchEvent(new Event('input', { bubbles: true }))
checkbox.dispatchEvent(new Event('change', { bubbles: true }))
})
await page.waitForFunction(() => {
const token = document.querySelector('input[name="captcha"]')?.value?.trim() || ''
const clicked = document.querySelector('input[name="captcha_clicked"]')?.value?.toLowerCase() || ''
return token.length > 80 && (clicked === 'true' || clicked === '1')
}, { timeout: 32_000 }).catch(() => {})
const captchaState = await page.evaluate(() => {
const host = document.querySelector('private-captcha')
const checkbox = host?.shadowRoot?.querySelector('#pc-checkbox')
const token = document.querySelector('input[name="captcha"]')?.value?.trim() || ''
return {
tokenLength: token.length,
clicked: document.querySelector('input[name="captcha_clicked"]')?.value || null,
shadowRoot: Boolean(host?.shadowRoot),
checkboxFound: Boolean(checkbox),
checkboxChecked: Boolean(checkbox?.checked),
widgetState: host?.getAttribute('data-state') || null
}
})
console.info('[mytischtennis] CAPTCHA state after wait:', captchaState)
const captchaReady = captchaState.tokenLength > 80
if (!captchaReady) throw new Error('CAPTCHA konnte nicht automatisch gelöst werden.')
await page.waitForTimeout(2_500)
}
await page.evaluate(() => {
const form = document.querySelector('form[action*="/login"]')
if (!form) return
let intent = form.querySelector('input[name="intent"]')
if (!intent) {
intent = document.createElement('input')
intent.setAttribute('type', 'hidden')
intent.setAttribute('name', 'intent')
form.appendChild(intent)
}
intent.setAttribute('value', 'login')
})
const submit = page.locator('button[type="submit"][name="intent"][value="login"]').first()
const genericSubmit = page.locator('button[type="submit"], input[type="submit"]').first()
if (await submit.count()) await submit.click({ noWaitAfter: true })
else if (await genericSubmit.count()) await genericSubmit.click({ noWaitAfter: true })
else await page.locator('form').evaluate(form => form.requestSubmit())
let cookie = null
let cookieNames = []
let loginPageText = ''
for (let attempt = 0; attempt < 40; attempt += 1) {
const cookies = await page.context().cookies()
cookieNames = cookies.map(item => item.name)
cookie = cookies.find(item => item.name === 'sb-10-auth-token' || /^sb-\d+-auth-token$/.test(item.name) || item.name.includes('auth-token'))
if (cookie) break
if (attempt % 4 === 0) {
loginPageText = await page.locator('body').innerText().catch(() => '')
}
await page.waitForTimeout(500)
}
if (!cookie) {
console.warn('[mytischtennis] Login after solved CAPTCHA did not create a session', {
url: page.url(), cookieNames, pageText: loginPageText.slice(0, 1_000)
})
throw new Error('myTischtennis-Login nach gelöstem CAPTCHA fehlgeschlagen.')
}
return `${cookie.name}=${cookie.value}`
} finally { await browser.close() }
}
export async function fetchClubRankings(connection, currentRanking = 'yes') {
let cookie
try { cookie = await loginDirect(connection.email, connection.password) } catch (error) {
if (error.message !== 'CAPTCHA_REQUIRED') throw error
cookie = await loginWithBrowser(connection.email, connection.password)
}
const url = new URL('/rankings/andro-rangliste', BASE_URL)
url.search = new URLSearchParams({ 'all-players': 'on', clubnr: connection.clubId, fednickname: connection.association, 'current-ranking': currentRanking, 'results-per-page': '100', page: '0', _data: 'routes/$' })
console.info('[mytischtennis] Ranking request URL:', url.toString())
const response = await fetch(url, { headers: { ...HEADERS, cookie, accept: 'application/json', referer: `${BASE_URL}/` } })
if (!response.ok) throw new Error(`Ranglisten-Abruf fehlgeschlagen (HTTP ${response.status}).`)
const entries = findEntries(await response.json())
if (!entries) throw new Error('myTischtennis hat keine Ranglisten-Daten geliefert.')
console.info('[mytischtennis] Ranking response:', {
currentRanking,
entryCount: entries.length,
entryKeys: Object.keys(entries[0] || {})
})
return entries
}

View File

@@ -1,44 +0,0 @@
import { promises as fs } from 'fs'
import { encryptObject, decryptObject } from './encryption.js'
import { getServerDataPath } from './paths.js'
const FILE = getServerDataPath('mytischtennis-connection.json')
function encryptionKey() {
const key = process.env.ENCRYPTION_KEY
if (!key) throw new Error('ENCRYPTION_KEY ist für die myTischtennis-Verbindung erforderlich.')
return key
}
export async function readMyTischtennisConnection() {
try {
const stored = JSON.parse(await fs.readFile(FILE, 'utf8'))
return decryptObject(stored.encrypted, encryptionKey())
} catch (error) {
if (error?.code === 'ENOENT') return null
throw error
}
}
export async function saveMyTischtennisConnection(connection) {
const payload = {
version: 1,
encrypted: encryptObject(connection, encryptionKey())
}
await fs.mkdir(getServerDataPath(), { recursive: true })
await fs.writeFile(FILE, `${JSON.stringify(payload)}\n`, { encoding: 'utf8', mode: 0o600 })
}
export function publicConnectionStatus(connection) {
if (!connection) return { configured: false }
const email = String(connection.email || '')
const [name, domain] = email.split('@')
return {
configured: true,
email: name ? `${name.slice(0, 2)}${'•'.repeat(Math.max(1, name.length - 2))}${domain ? `@${domain}` : ''}` : null,
association: connection.association || null,
clubId: connection.clubId || null,
lastSuccessfulImportAt: connection.lastSuccessfulImportAt || null,
lastImportError: connection.lastImportError || null
}
}

View File

@@ -8,7 +8,6 @@ export const DEFAULT_NOTIFICATION_SETTINGS = Object.freeze({
birthdays: false,
newContactRequest: false,
newUserRegistration: false,
ownTtrChanges: false,
selectedTeamSlugs: [],
selectedTeamSeason: null,
notificationTime: '09:00'
@@ -42,7 +41,6 @@ export function sanitizeNotificationSettings(input = {}) {
birthdays: coerceBoolean(input.birthdays),
newContactRequest: coerceBoolean(input.newContactRequest),
newUserRegistration: coerceBoolean(input.newUserRegistration),
ownTtrChanges: coerceBoolean(input.ownTtrChanges),
selectedTeamSlugs: [...new Set(selectedTeamSlugs)],
selectedTeamSeason,
notificationTime

View File

@@ -85,21 +85,16 @@ function pushTokensForUser(user) {
: []
}
export function upsertPushToken(user, { token, platform = 'android', appVersion = null, installationId = null }) {
export function upsertPushToken(user, { token, platform = 'android', appVersion = null }) {
const normalizedToken = String(token || '').trim()
if (!normalizedToken) return user
const normalizedInstallationId = String(installationId || '').trim().slice(0, 200) || null
const now = new Date().toISOString()
const tokens = Array.isArray(user.pushTokens) ? user.pushTokens : []
// A Firebase token can rotate for the same app installation. Retain tokens
// from other devices, but replace the previous token of this installation.
const next = tokens.filter(entry => entry?.token !== normalizedToken &&
(!normalizedInstallationId || entry?.installationId !== normalizedInstallationId))
const next = tokens.filter(entry => entry?.token !== normalizedToken)
next.push({
token: normalizedToken,
platform: String(platform || 'android').slice(0, 30),
appVersion: appVersion ? String(appVersion).slice(0, 80) : null,
installationId: normalizedInstallationId,
updatedAt: now,
createdAt: tokens.find(entry => entry?.token === normalizedToken)?.createdAt || now
})
@@ -107,12 +102,7 @@ export function upsertPushToken(user, { token, platform = 'android', appVersion
return user
}
export async function androidPushTokenCountForUser(userId) {
const user = (await readUsers()).find(entry => entry?.id === userId)
return pushTokensForUser(user).length
}
async function sendFcmMessage({ serviceAccount, accessToken, token, data = {} }) {
async function sendFcmMessage({ serviceAccount, accessToken, token, title, body, data = {} }) {
const projectId = projectIdFromServiceAccount(serviceAccount)
if (!projectId) throw new Error('FCM project_id fehlt.')
const response = await fetch(`https://fcm.googleapis.com/v1/projects/${projectId}/messages:send`, {
@@ -124,14 +114,14 @@ async function sendFcmMessage({ serviceAccount, accessToken, token, data = {} })
body: JSON.stringify({
message: {
token,
notification: { title, body },
data,
android: {
priority: 'high',
// Keep this as a data message. With a `notification` payload FCM
// renders background messages itself, bypassing our notification
// channel and HarheimerMessagingService. Data messages use the
// same app-controlled channel while the app is foregrounded and
// backgrounded.
notification: {
channel_id: 'harheimer_tc_updates',
click_action: 'OPEN_NEWS'
}
}
}
})
@@ -160,26 +150,6 @@ function isVorstandUser(user) {
return roles.includes('admin') || roles.includes('vorstand')
}
function normalizePersonName(value) {
return String(value || '')
.trim()
.toLowerCase()
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/['`]/g, '')
.replace(/\s+/g, ' ')
}
function userMatchesPlayer(user, playerName) {
const player = normalizePersonName(playerName)
if (!player) return false
const candidates = [
user?.name,
`${user?.firstName || ''} ${user?.lastName || ''}`.trim()
].map(normalizePersonName).filter(Boolean)
return candidates.includes(player)
}
export async function sendPushToUsers({ title, body, data = {}, predicate, bodyForUser, dataForUser, failureLabel = 'FCM-Push' }) {
const serviceAccount = await readServiceAccount()
if (serviceAccount == null) {
@@ -215,7 +185,7 @@ export async function sendPushToUsers({ title, body, data = {}, predicate, bodyF
const validTokens = []
for (const entry of tokens) {
try {
await sendFcmMessage({ serviceAccount, accessToken, token: entry.token, data: payload })
await sendFcmMessage({ serviceAccount, accessToken, token: entry.token, title, body: userBody, data: payload })
sent += 1
validTokens.push(entry)
} catch (error) {
@@ -236,11 +206,7 @@ export async function sendPushToUsers({ title, body, data = {}, predicate, bodyF
}
}
if (changed) await writeUsers(users)
const result = { sent, failed, removed, recipients, tokenCount, skipped: false }
// This makes an absent registration immediately visible in the production
// log without exposing tokens or user data.
console.info('FCM Push Ergebnis:', { failureLabel, ...result })
return result
return { sent, failed, removed, recipients, tokenCount, skipped: false }
}
export async function sendNewNewsPush(news) {
@@ -305,57 +271,3 @@ export async function sendNewUserRegistrationPush(registration) {
failureLabel: 'FCM Registrierungs-Push'
})
}
export async function sendOwnTtrChangePush(changes = []) {
const byPlayer = new Map(
changes
.filter(change => change?.playerName && Number.isFinite(change?.previousTtr) && Number.isFinite(change?.currentTtr))
.map(change => [normalizePersonName(change.playerName), change])
)
if (!byPlayer.size) return { sent: 0, failed: 0, removed: 0, recipients: 0, tokenCount: 0, skipped: false }
return sendPushToUsers({
title: 'TTR-Wert geändert',
data: { type: 'ttr_change' },
predicate: (user, settings) => settings.ownTtrChanges && [...byPlayer.values()].some(change => userMatchesPlayer(user, change.playerName)),
bodyForUser: (user) => {
const change = [...byPlayer.values()].find(entry => userMatchesPlayer(user, entry.playerName))
return `Dein TTR-Wert hat sich von ${change.previousTtr} auf ${change.currentTtr} geändert.`
},
dataForUser: (user) => {
const change = [...byPlayer.values()].find(entry => userMatchesPlayer(user, entry.playerName))
return {
previousTtr: change.previousTtr,
currentTtr: change.currentTtr,
notificationId: notificationIdFor(`ttr:${change.playerName}:${change.previousTtr}:${change.currentTtr}`)
}
},
failureLabel: 'FCM TTR-Änderungs-Push'
})
}
export async function sendQttrListUpdatedPush({ importedAt, rowCount }) {
return sendPushToUsers({
title: 'QTTR-Liste aktualisiert',
body: `Die aktuelle TTR- und QTTR-Liste wurde aktualisiert (${rowCount} Einträge).`,
data: {
type: 'qttr_list_updated',
importedAt: importedAt || '',
notificationId: notificationIdFor(`qttr-list:${importedAt || Date.now()}`)
},
failureLabel: 'FCM QTTR-Listen-Push'
})
}
export async function sendTestPushToUser(userId) {
return sendPushToUsers({
title: 'Harheimer TC: Push-Test',
body: 'Diese Test-Benachrichtigung wurde erfolgreich vom CMS ausgelöst.',
data: {
type: 'test',
notificationId: notificationIdFor(`test:${userId}:${Date.now()}`)
},
predicate: user => user?.id === userId,
failureLabel: 'FCM Test-Push'
})
}

View File

@@ -1,8 +1,5 @@
import { promises as fs } from 'fs'
import { getServerDataPath } from './paths.js'
import { sendOwnTtrChangePush, sendQttrListUpdatedPush } from './push-notifications.js'
import { fetchClubRankings } from './mytischtennis-client.js'
import { readMyTischtennisConnection, saveMyTischtennisConnection } from './mytischtennis-connection.js'
const QTTR_URL = 'https://www.mytischtennis.de/rankings/andro-rangliste?continent=all&country=Deutschland&all-players=on&as=DE.WE.R4.07&di=DE.WE.R4.07.04&area=DE.WE.R4.07.04.43&clubnr-search=Harheimer+TC&clubnr=43030&fednickname=HeTTV&gender=all&current-ranking=no&ttr-range=100%3B3000&birth-range=1926%3B2021'
const OUTPUT_FILE = getServerDataPath('qttr-values.json')
@@ -62,8 +59,8 @@ function toNumberOrNull(value) {
function normalizeGender(value) {
const normalized = String(value || '').trim().toLowerCase()
if (['m', 'männlich', 'maennlich', 'male', 'man'].includes(normalized)) return 'männlich'
if (['w', 'weiblich', 'female', 'woman', 'f'].includes(normalized)) return 'weiblich'
if (normalized === 'm' || normalized === 'männlich') return 'männlich'
if (normalized === 'w' || normalized === 'weiblich') return 'weiblich'
return normalized || null
}
@@ -163,9 +160,6 @@ function deriveQttrFields(headers, cells) {
}
export async function importQttrValues(options = {}) {
const connection = options.connection ?? await readMyTischtennisConnection()
if (connection) return importAuthenticatedTtrValues(connection)
const url = options.url || QTTR_URL
const response = await fetch(url, {
headers: {
@@ -213,72 +207,4 @@ export async function importQttrValues(options = {}) {
rowCount: parsedRows.length,
...payload
}
}
async function importAuthenticatedTtrValues(connection) {
const previousPayload = await fs.readFile(OUTPUT_FILE, 'utf8')
.then(JSON.parse)
.catch(() => ({ rows: [] }))
const [ttrEntries, qttrEntries] = await Promise.all([
fetchClubRankings(connection, 'yes'),
fetchClubRankings(connection, 'no')
])
const qttrByPlayer = new Map(qttrEntries.map(entry => [
String(entry.personId || `${entry.firstname || ''}|${entry.lastname || ''}`).toLowerCase(), entry
]))
const rows = ttrEntries.map((entry, index) => {
const key = String(entry.personId || `${entry.firstname || ''}|${entry.lastname || ''}`).toLowerCase()
const qttrEntry = qttrByPlayer.get(key)
return ({
rank: toNumberOrNull(entry.rank ?? entry.ranking ?? index + 1),
playerNumber: toNumberOrNull(entry.playernr ?? entry.player_number ?? entry.nuid),
gender: normalizeGender(entry.gender ?? entry.sex ?? entry.genderCode ?? entry.gender_code),
playerName: `${entry.firstname ?? entry.first_name ?? ''} ${entry.lastname ?? entry.last_name ?? ''}`.trim() || entry.name || null,
clubName: entry.clubname ?? entry.club_name ?? 'Harheimer TC',
currentQttr: toNumberOrNull(qttrEntry?.fedRank ?? qttrEntry?.qttr ?? entry.qttr),
currentTtr: toNumberOrNull(entry.fedRank ?? entry.ttr ?? entry.current_ttr),
previousQttr: null,
valuesByHeader: entry,
rawCells: []
})
}).filter(row => row.playerName && (row.currentTtr != null || row.currentQttr != null))
if (!rows.length) throw new Error('Keine verwertbaren TTR-Werte in der myTischtennis-Rangliste gefunden.')
const previousQttrSignature = qttrListSignature(previousPayload.rows)
const nextQttrSignature = qttrListSignature(rows)
const importedAt = new Date().toISOString()
const payload = {
format: 'harheimertc.qttr.v2', importedAt,
source: { type: 'mytischtennis-authenticated', association: connection.association, clubId: connection.clubId },
title: 'Aktuelle myTischtennis-Rangliste', headerCount: 0, rowCount: rows.length, headers: [], rows
}
await fs.mkdir(getServerDataPath(), { recursive: true })
await fs.writeFile(OUTPUT_FILE, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
const previousTtrByPlayer = new Map((previousPayload.rows || []).map(row => [
String(row?.playerName || '').trim().toLowerCase(), toNumberOrNull(row?.currentTtr)
]))
const changes = rows.flatMap(row => {
const previousTtr = previousTtrByPlayer.get(String(row.playerName || '').trim().toLowerCase())
return previousTtr != null && row.currentTtr != null && previousTtr !== row.currentTtr
? [{ playerName: row.playerName, previousTtr, currentTtr: row.currentTtr }]
: []
})
await sendOwnTtrChangePush(changes)
if (previousQttrSignature && previousQttrSignature !== nextQttrSignature) {
await sendQttrListUpdatedPush({ importedAt, rowCount: rows.length })
}
await saveMyTischtennisConnection({ ...connection, lastSuccessfulImportAt: importedAt, lastImportError: null })
return { outputFile: OUTPUT_FILE, tableCount: 1, ...payload }
}
function qttrListSignature(rows) {
if (!Array.isArray(rows) || rows.length === 0) return ''
return rows
.map(row => [
String(row?.playerName || '').trim().toLocaleLowerCase('de-DE'),
row?.rank ?? '',
row?.currentQttr ?? ''
].join('|'))
.sort()
.join('\n')
}
}

View File

@@ -83,7 +83,6 @@ describe('Auth API Endpoints', () => {
afterEach(() => {
delete process.env.NODE_ENV
delete process.env.APP_ENV
delete process.env.DEBUG
delete process.env.NUXT_PUBLIC_BASE_URL
delete process.env.PASSWORD_RESET_TTL_MIN
})
@@ -283,7 +282,6 @@ describe('Auth API Endpoints', () => {
it('benachrichtigt in Testumgebung nicht die Vorstand-Empfänger', async () => {
process.env.NODE_ENV = 'production'
process.env.APP_ENV = 'test'
delete process.env.DEBUG
const event = createEvent()
mockSuccessReadBody({

View File

@@ -247,7 +247,7 @@ describe('Config & Profil Endpoints', () => {
it('speichert Android-Push-Token am Benutzer', async () => {
const event = createEvent({ headers: { authorization: 'Bearer android-token' } })
mockSuccessReadBody({ token: 'fcm-token', platform: 'android', appVersion: '1.0+1', installationId: 'firebase-installation-id' })
mockSuccessReadBody({ token: 'fcm-token', platform: 'android', appVersion: '1.0+1' })
const users = [{ id: '1', email: 'max@test.de', roles: ['mitglied'] }]
authUtils.verifyToken.mockReturnValue({ id: '1' })
authUtils.getUserFromToken.mockResolvedValue(users[0])
@@ -260,7 +260,7 @@ describe('Config & Profil Endpoints', () => {
expect(authUtils.writeUsers).toHaveBeenCalledWith([
expect.objectContaining({
id: '1',
pushTokens: [expect.objectContaining({ token: 'fcm-token', platform: 'android', appVersion: '1.0+1', installationId: 'firebase-installation-id' })]
pushTokens: [expect.objectContaining({ token: 'fcm-token', platform: 'android', appVersion: '1.0+1' })]
})
])
})

View File

@@ -1,36 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { promises as fs } from 'fs'
import os from 'os'
import path from 'path'
const originalAppRoot = process.env.APP_ROOT
const createdRoots = []
afterEach(async () => {
vi.resetModules()
if (originalAppRoot === undefined) delete process.env.APP_ROOT
else process.env.APP_ROOT = originalAppRoot
await Promise.all(createdRoots.splice(0).map(root => fs.rm(root, { recursive: true, force: true })))
})
describe('membership applications', () => {
it('rejects a second pending application with the same name and birth date', async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'harheimertc-membership-'))
createdRoots.push(root)
await fs.mkdir(path.join(root, 'server', 'data'), { recursive: true })
process.env.APP_ROOT = root
const { createMembershipApplication } = await import('../server/utils/membership-applications.js')
const data = {
vorname: 'Jörg',
nachname: 'Beispiel',
geburtsdatum: '1990-02-03',
mitgliedschaftsart: 'aktiv'
}
const application = await createMembershipApplication(data)
expect(application.status).toBe('pending')
await expect(createMembershipApplication({ ...data, vorname: ' JÖRG ' }))
.rejects.toMatchObject({ statusCode: 409 })
})
})

View File

@@ -1,30 +0,0 @@
/**
* Makes youth teams identifiable while retaining the team name supplied by
* click-TT. Age groups occur in a few forms, for example "Jugend 13",
* "Jugend 13 1. Kreisklasse", and "J13". Some imports provide the age
* only for the whole fixture, therefore `competitionAgeGroup` is considered
* as a fallback.
*/
export function youthTeamCode(teamAgeGroup, teamName = '', competitionAgeGroup = '') {
const ageGroup = [teamAgeGroup, competitionAgeGroup]
.map(value => String(value || '').trim())
.filter(Boolean)
.join(' ')
const name = String(teamName || '').trim()
const codeMatch = `${ageGroup} ${name}`.match(/\b(?:jugend\s*|j\s*\(?)(\d{1,2})\b/i)
if (codeMatch) return `J${codeMatch[1]}`
if (/\bjugend\b/i.test(ageGroup) || /\bjugend\b/i.test(name)) return 'J'
return ''
}
export function formatTeamDisplayName(teamName, teamAgeGroup, competitionAgeGroup = '') {
const rawName = String(teamName || '').trim()
if (!rawName) return ''
const youthCode = youthTeamCode(teamAgeGroup, rawName, competitionAgeGroup)
const name = youthCode
? rawName.replace(/\s*\(J\d{1,2}\)\s*$/i, '').trim()
: rawName
return youthCode ? `(${youthCode}) ${name}` : name
}