sync2
Laurent 8 months ago
commit a16b104757
  1. 12
      PadelClub.xcodeproj/project.pbxproj
  2. 2
      PadelClub/AppDelegate.swift
  3. 17
      PadelClub/Data/DataStore.swift
  4. 12
      PadelClub/Data/Federal/FederalTournament.swift
  5. 24
      PadelClub/Data/GroupStage.swift
  6. 25
      PadelClub/Data/Match.swift
  7. 27
      PadelClub/Data/PlayerRegistration.swift
  8. 23
      PadelClub/Data/TeamRegistration.swift
  9. 162
      PadelClub/Data/Tournament.swift
  10. 26
      PadelClub/Extensions/Sequence+Extensions.swift
  11. 2
      PadelClub/InscriptionLegendView.swift
  12. 60
      PadelClub/OnlineRegistrationWarningView.swift
  13. 4
      PadelClub/Utils/Network/NetworkManager.swift
  14. 71
      PadelClub/Utils/SwiftParser.swift
  15. 12
      PadelClub/Views/Calling/CallView.swift
  16. 29
      PadelClub/Views/GroupStage/GroupStagesSettingsView.swift
  17. 81
      PadelClub/Views/GroupStage/GroupStagesView.swift
  18. 2
      PadelClub/Views/Match/Components/MatchDateView.swift
  19. 2
      PadelClub/Views/Match/Components/PlayerBlockView.swift
  20. 2
      PadelClub/Views/Match/MatchDetailView.swift
  21. 6
      PadelClub/Views/Navigation/Agenda/ActivityView.swift
  22. 66
      PadelClub/Views/Navigation/Agenda/EventListView.swift
  23. 2
      PadelClub/Views/Player/Components/EditablePlayerView.swift
  24. 2
      PadelClub/Views/Player/PlayerView.swift
  25. 2
      PadelClub/Views/Round/RoundSettingsView.swift
  26. 5
      PadelClub/Views/Score/FollowUpMatchView.swift
  27. 2
      PadelClub/Views/Shared/SelectablePlayerListView.swift
  28. 132
      PadelClub/Views/Team/EditingTeamView.swift
  29. 12
      PadelClub/Views/Team/TeamPickerView.swift
  30. 6
      PadelClub/Views/Team/TeamRowView.swift
  31. 35
      PadelClub/Views/Tournament/FileImportView.swift
  32. 12
      PadelClub/Views/Tournament/Screen/AddTeamView.swift
  33. 19
      PadelClub/Views/Tournament/Screen/Components/UpdateSourceRankDateView.swift
  34. 73
      PadelClub/Views/Tournament/Screen/InscriptionManagerView.swift
  35. 12
      PadelClub/Views/Tournament/Screen/RegistrationSetupView.swift
  36. 23
      PadelClub/Views/Tournament/Screen/TableStructureView.swift
  37. 20
      PadelClub/Views/Tournament/Shared/TournamentCellView.swift
  38. 10
      PadelClub/Views/Tournament/TournamentBuildView.swift
  39. 8
      PadelClub/Views/Tournament/TournamentView.swift

@ -3624,7 +3624,7 @@
CODE_SIGN_ENTITLEMENTS = PadelClub/PadelClub.entitlements; CODE_SIGN_ENTITLEMENTS = PadelClub/PadelClub.entitlements;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 2;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEFINES_MODULE = YES; DEFINES_MODULE = YES;
DEVELOPMENT_ASSET_PATHS = "\"PadelClub/Preview Content\""; DEVELOPMENT_ASSET_PATHS = "\"PadelClub/Preview Content\"";
@ -3650,7 +3650,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 1.1.13; MARKETING_VERSION = 1.1.20;
PRODUCT_BUNDLE_IDENTIFIER = app.padelclub; PRODUCT_BUNDLE_IDENTIFIER = app.padelclub;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
@ -3670,7 +3670,7 @@
CODE_SIGN_ENTITLEMENTS = PadelClub/PadelClub.entitlements; CODE_SIGN_ENTITLEMENTS = PadelClub/PadelClub.entitlements;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 2;
DEFINES_MODULE = YES; DEFINES_MODULE = YES;
DEVELOPMENT_ASSET_PATHS = "\"PadelClub/Preview Content\""; DEVELOPMENT_ASSET_PATHS = "\"PadelClub/Preview Content\"";
DEVELOPMENT_TEAM = BQ3Y44M3Q6; DEVELOPMENT_TEAM = BQ3Y44M3Q6;
@ -3695,7 +3695,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 1.1.13; MARKETING_VERSION = 1.1.20;
PRODUCT_BUNDLE_IDENTIFIER = app.padelclub; PRODUCT_BUNDLE_IDENTIFIER = app.padelclub;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
@ -3792,7 +3792,6 @@
DEFINES_MODULE = YES; DEFINES_MODULE = YES;
DEVELOPMENT_ASSET_PATHS = "\"PadelClub/Preview Content\""; DEVELOPMENT_ASSET_PATHS = "\"PadelClub/Preview Content\"";
DEVELOPMENT_TEAM = BQ3Y44M3Q6; DEVELOPMENT_TEAM = BQ3Y44M3Q6;
GCC_OPTIMIZATION_LEVEL = 0;
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = PadelClub/Info.plist; INFOPLIST_FILE = PadelClub/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "Padel Club (ProdTest)"; INFOPLIST_KEY_CFBundleDisplayName = "Padel Club (ProdTest)";
@ -3821,7 +3820,6 @@
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SUPPORTS_MACCATALYST = NO; SUPPORTS_MACCATALYST = NO;
SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
}; };
@ -3839,7 +3837,6 @@
DEFINES_MODULE = YES; DEFINES_MODULE = YES;
DEVELOPMENT_ASSET_PATHS = "\"PadelClub/Preview Content\""; DEVELOPMENT_ASSET_PATHS = "\"PadelClub/Preview Content\"";
DEVELOPMENT_TEAM = BQ3Y44M3Q6; DEVELOPMENT_TEAM = BQ3Y44M3Q6;
GCC_OPTIMIZATION_LEVEL = 0;
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = PadelClub/Info.plist; INFOPLIST_FILE = PadelClub/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = "Padel Club (ProdTest)"; INFOPLIST_KEY_CFBundleDisplayName = "Padel Club (ProdTest)";
@ -3869,7 +3866,6 @@
SUPPORTS_MACCATALYST = NO; SUPPORTS_MACCATALYST = NO;
SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = PRODTEST; SWIFT_ACTIVE_COMPILATION_CONDITIONS = PRODTEST;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
}; };

@ -23,6 +23,8 @@ class AppDelegate : NSObject, UIApplicationDelegate, UNUserNotificationCenterDel
return true return true
} }
// MARK: - Remote Notifications
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
if StoreCenter.main.hasToken() { if StoreCenter.main.hasToken() {

@ -103,6 +103,11 @@ class DataStore: ObservableObject {
NotificationCenter.default.addObserver(self, selector: #selector(collectionDidLoad), name: NSNotification.Name.CollectionDidLoad, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(collectionDidLoad), name: NSNotification.Name.CollectionDidLoad, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(collectionDidUpdate), name: NSNotification.Name.CollectionDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(collectionDidUpdate), name: NSNotification.Name.CollectionDidChange, object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(_willEnterForegroundNotification),
name: UIScene.willEnterForegroundNotification,
object: nil)
} }
@ -119,11 +124,7 @@ class DataStore: ObservableObject {
} }
@objc func collectionDidLoad(notification: Notification) { @objc func collectionDidLoad(notification: Notification) {
DispatchQueue.main.async {
self.objectWillChange.send()
}
if let userSingleton: StoredSingleton<CustomUser> = notification.object as? StoredSingleton<CustomUser> { if let userSingleton: StoredSingleton<CustomUser> = notification.object as? StoredSingleton<CustomUser> {
self.user = userSingleton.item() ?? self._temporaryLocalUser.item ?? CustomUser.placeHolder() self.user = userSingleton.item() ?? self._temporaryLocalUser.item ?? CustomUser.placeHolder()
} else if let clubsCollection: StoredCollection<Club> = notification.object as? StoredCollection<Club> { } else if let clubsCollection: StoredCollection<Club> = notification.object as? StoredCollection<Club> {
@ -166,6 +167,12 @@ class DataStore: ObservableObject {
self.objectWillChange.send() self.objectWillChange.send()
} }
@objc func _willEnterForegroundNotification() {
Task {
try await self.purchases.loadDataFromServerIfAllowed(clear: true)
}
}
func disconnect() { func disconnect() {
Task { Task {

@ -236,12 +236,12 @@ struct CategorieAge: Codable {
var tournamentAge: FederalTournamentAge? { var tournamentAge: FederalTournamentAge? {
if let id { if let id {
return FederalTournamentAge(rawValue: id) return FederalTournamentAge(rawValue: id) ?? .senior
} }
if let libelle { if let libelle {
return FederalTournamentAge.allCases.first(where: { $0.localizedFederalAgeLabel().localizedCaseInsensitiveContains(libelle) }) return FederalTournamentAge.allCases.first(where: { $0.localizedFederalAgeLabel().localizedCaseInsensitiveContains(libelle) }) ?? .senior
} }
return nil return .senior
} }
} }
@ -295,7 +295,7 @@ struct Serie: Codable {
var sexe: String? var sexe: String?
var tournamentCategory: TournamentCategory? { var tournamentCategory: TournamentCategory? {
TournamentCategory.allCases.first(where: { $0.requestLabel == code }) TournamentCategory.allCases.first(where: { $0.requestLabel == code }) ?? .men
} }
} }
@ -348,9 +348,9 @@ struct TypeEpreuve: Codable {
var tournamentLevel: TournamentLevel? { var tournamentLevel: TournamentLevel? {
if let code, let value = Int(code.removingFirstCharacter) { if let code, let value = Int(code.removingFirstCharacter) {
return TournamentLevel(rawValue: value) return TournamentLevel(rawValue: value) ?? .p100
} }
return nil return .p100
} }
} }

@ -402,7 +402,7 @@ final class GroupStage: BaseGroupStage, SideStorable {
unsortedTeams().flatMap({ $0.unsortedPlayers() }) unsortedTeams().flatMap({ $0.unsortedPlayers() })
} }
fileprivate typealias TeamScoreAreInIncreasingOrder = (TeamGroupStageScore, TeamGroupStageScore) -> Bool typealias TeamScoreAreInIncreasingOrder = (TeamGroupStageScore, TeamGroupStageScore) -> Bool
typealias TeamGroupStageScore = (team: TeamRegistration, wins: Int, loses: Int, setDifference: Int, gameDifference: Int) typealias TeamGroupStageScore = (team: TeamRegistration, wins: Int, loses: Int, setDifference: Int, gameDifference: Int)
@ -457,20 +457,24 @@ final class GroupStage: BaseGroupStage, SideStorable {
var scoreCache: [Int: TeamGroupStageScore] = [:] var scoreCache: [Int: TeamGroupStageScore] = [:]
func computedScore(forTeam team: TeamRegistration, step: Int = 0) -> TeamGroupStageScore? {
if let cachedScore = scoreCache[team.groupStagePositionAtStep(step)!] {
return cachedScore
} else {
let score = _score(forGroupStagePosition: team.groupStagePositionAtStep(step)!)
if let score = score {
scoreCache[team.groupStagePositionAtStep(step)!] = score
}
return score
}
}
func teams(_ sortedByScore: Bool = false, scores: [TeamGroupStageScore]? = nil) -> [TeamRegistration] { func teams(_ sortedByScore: Bool = false, scores: [TeamGroupStageScore]? = nil) -> [TeamRegistration] {
if sortedByScore { if sortedByScore {
return unsortedTeams().compactMap({ team in return unsortedTeams().compactMap({ team in
// Check cache or use provided scores, otherwise calculate and store in cache // Check cache or use provided scores, otherwise calculate and store in cache
scores?.first(where: { $0.team.id == team.id }) ?? { scores?.first(where: { $0.team.id == team.id }) ?? {
if let cachedScore = scoreCache[team.groupStagePositionAtStep(step)!] { return computedScore(forTeam: team, step: step)
return cachedScore
} else {
let score = _score(forGroupStagePosition: team.groupStagePositionAtStep(step)!)
if let score = score {
scoreCache[team.groupStagePositionAtStep(step)!] = score
}
return score
}
}() }()
}).sorted { (lhs, rhs) in }).sorted { (lhs, rhs) in
let predicates: [TeamScoreAreInIncreasingOrder] = [ let predicates: [TeamScoreAreInIncreasingOrder] = [

@ -354,12 +354,15 @@ defer {
} }
} }
//byeState = false //byeState = false
roundObject?._cachedSeedInterval = nil
name = nil if state != currentState {
do { roundObject?._cachedSeedInterval = nil
try self.tournamentStore?.matches.addOrUpdate(instance: self) name = nil
} catch { do {
Logger.error(error) try self.tournamentStore?.matches.addOrUpdate(instance: self)
} catch {
Logger.error(error)
}
} }
if single == false { if single == false {
@ -459,7 +462,7 @@ defer {
return (groupStageObject.index + 1) * 100 + groupStageObject.indexOf(index) return (groupStageObject.index + 1) * 100 + groupStageObject.indexOf(index)
} }
guard let roundObject else { return index } guard let roundObject else { return index }
return roundObject.isLoserBracket() ? (roundObject.index + 1) * 10000 + indexInRound() : (roundObject.index + 1) * 1000 + indexInRound() return (300 - (roundObject.theoryCumulativeMatchCount * 10 + roundObject.index * 22)) * 10 + indexInRound()
} }
func previousMatches() -> [Match] { func previousMatches() -> [Match] {
@ -484,9 +487,15 @@ defer {
func setWalkOut(_ teamPosition: TeamPosition) { func setWalkOut(_ teamPosition: TeamPosition) {
let teamScoreWalkout = teamScore(teamPosition) ?? TeamScore(match: id, team: team(teamPosition)) let teamScoreWalkout = teamScore(teamPosition) ?? TeamScore(match: id, team: team(teamPosition))
teamScoreWalkout.walkOut = 0 teamScoreWalkout.walkOut = 0
teamScoreWalkout.score = matchFormat.defaultWalkOutScore(true).compactMap({ String($0) }).joined(separator: ",")
let teamScoreWinning = teamScore(teamPosition.otherTeam) ?? TeamScore(match: id, team: team(teamPosition.otherTeam)) let teamScoreWinning = teamScore(teamPosition.otherTeam) ?? TeamScore(match: id, team: team(teamPosition.otherTeam))
teamScoreWinning.walkOut = nil teamScoreWinning.walkOut = nil
self.tournamentStore?.teamScores.addOrUpdate(contentOfs: [teamScoreWalkout, teamScoreWinning]) teamScoreWinning.score = matchFormat.defaultWalkOutScore(false).compactMap({ String($0) }).joined(separator: ",")
do {
try self.tournamentStore?.teamScores.addOrUpdate(contentOfs: [teamScoreWalkout, teamScoreWinning])
} catch {
Logger.error(error)
}
if endDate == nil { if endDate == nil {
endDate = Date() endDate = Date()

@ -276,21 +276,23 @@ final class PlayerRegistration: BasePlayerRegistration, SideStorable {
return await withTaskGroup(of: Line?.self) { group in return await withTaskGroup(of: Line?.self) { group in
for source in filteredSources { for source in filteredSources {
group.addTask { group.addTask {
guard !Task.isCancelled else { print("Cancelled"); return nil } guard !Task.isCancelled else { return nil }
return try? await source.first { $0.rawValue.contains(";\(license);") } return try? await source.first { $0.rawValue.contains(";\(license);") }
} }
} }
if let first = await group.first(where: { $0 != nil }) { for await result in group {
group.cancelAll() if let result {
return first group.cancelAll() // Stop other tasks as soon as we find a match
return result
}
} }
return nil return nil
} }
} }
func historyFromName(from sources: [CSVParser]) async throws -> Line? { func historyFromName(from sources: [CSVParser]) async throws -> Line? {
#if DEBUG_TIME #if DEBUG
let start = Date() let start = Date()
defer { defer {
let duration = Duration.milliseconds(Date().timeIntervalSince(start) * 1_000) let duration = Duration.milliseconds(Date().timeIntervalSince(start) * 1_000)
@ -313,20 +315,17 @@ final class PlayerRegistration: BasePlayerRegistration, SideStorable {
} }
} }
if let first = await group.first(where: { $0 != nil }) { for await result in group {
group.cancelAll() if let result {
return first group.cancelAll() // Stop other tasks as soon as we find a match
return result
}
} }
return nil return nil
} }
} }
func setComputedRank(in tournament: Tournament) { func setComputedRank(in tournament: Tournament) {
if tournament.isAnimation() {
computedRank = rank ?? 0
return
}
let currentRank = rank ?? tournament.unrankValue(for: isMalePlayer()) ?? 90_000 let currentRank = rank ?? tournament.unrankValue(for: isMalePlayer()) ?? 90_000
switch tournament.tournamentCategory { switch tournament.tournamentCategory {
case .men: case .men:

@ -369,11 +369,11 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
func initialRoundColor() -> Color? { func initialRoundColor() -> Color? {
if walkOut { return Color.logoRed } if walkOut { return Color.logoRed }
if groupStagePosition != nil { return Color.blue } if groupStagePosition != nil || wildCardGroupStage { return Color.blue }
if let initialRound = initialRound(), if let initialRound = initialRound(), let colorHex = RoundRule.colors[safe: initialRound.index] {
let colorHex = RoundRule.colors[safe: initialRound.index]
{
return Color(uiColor: .init(fromHex: colorHex)) return Color(uiColor: .init(fromHex: colorHex))
} else if wildCardBracket {
return Color.mint
} else { } else {
return nil return nil
} }
@ -582,11 +582,8 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
inTournamentCategory tournamentCategory: TournamentCategory inTournamentCategory tournamentCategory: TournamentCategory
) { ) {
let significantPlayerCount = significantPlayerCount() let significantPlayerCount = significantPlayerCount()
weight = let sortedPlayers = players.sorted(by: \.computedRank, order: .ascending)
(players.prefix(significantPlayerCount).map { $0.computedRank } weight = (sortedPlayers.prefix(significantPlayerCount).map { $0.computedRank } + missingPlayerType(inTournamentCategory: tournamentCategory).map { unrankValue(for: $0 == 1 ? true : false ) }).prefix(significantPlayerCount).reduce(0,+)
+ missingPlayerType(inTournamentCategory: tournamentCategory).map {
unrankValue(for: $0 == 1 ? true : false)
}).prefix(significantPlayerCount).reduce(0, +)
} }
func significantPlayerCount() -> Int { func significantPlayerCount() -> Int {
@ -702,6 +699,14 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
func shouldDisplayRankAndWeight() -> Bool { func shouldDisplayRankAndWeight() -> Bool {
unsortedPlayers().count > 0 unsortedPlayers().count > 0
} }
func bracketMatchTitleAndQualifiedStatus() -> String? {
let values = [qualified ? "Qualifié" : nil, initialMatch()?.roundAndMatchTitle()].compactMap({ $0 })
if values.isEmpty {
return nil
}
return values.joined(separator: " -> ")
}
func insertOnServer() { func insertOnServer() {
self.tournamentStore?.teamRegistrations.writeChangeAndInsertOnServer(instance: self) self.tournamentStore?.teamRegistrations.writeChangeAndInsertOnServer(instance: self)

@ -12,6 +12,16 @@ import SwiftUI
@Observable @Observable
final class Tournament: BaseTournament { final class Tournament: BaseTournament {
//local variable
var refreshInProgress: Bool = false
var lastTeamRefresh: Date?
var refreshRanking: Bool = false
func shouldRefreshTeams() -> Bool {
guard let lastTeamRefresh else { return true }
return lastTeamRefresh.timeIntervalSinceNow < -60
}
@ObservationIgnored @ObservationIgnored
var navigationPath: [Screen] = [] var navigationPath: [Screen] = []
@ -620,7 +630,7 @@ defer {
let wcBracket = _teams.filter { $0.wildCardBracket }.sorted(using: _currentSelectionSorting, order: .ascending) let wcBracket = _teams.filter { $0.wildCardBracket }.sorted(using: _currentSelectionSorting, order: .ascending)
let groupStageSpots: Int = self.groupStageSpots() let groupStageSpots: Int = self.groupStageSpots()
var bracketSeeds: Int = min(teamCount, _teams.count) - groupStageSpots - wcBracket.count var bracketSeeds: Int = teamCount - groupStageSpots - wcBracket.count
var groupStageTeamCount: Int = groupStageSpots - wcGroupStage.count var groupStageTeamCount: Int = groupStageSpots - wcGroupStage.count
if groupStageTeamCount < 0 { groupStageTeamCount = 0 } if groupStageTeamCount < 0 { groupStageTeamCount = 0 }
if bracketSeeds < 0 { bracketSeeds = 0 } if bracketSeeds < 0 { bracketSeeds = 0 }
@ -663,9 +673,9 @@ defer {
return waitings return waitings
} }
} }
func bracketCut(teamCount: Int) -> Int { func bracketCut(teamCount: Int, groupStageCut: Int) -> Int {
return max(0, teamCount - groupStageCut()) return self.teamCount - groupStageCut
} }
func groupStageCut() -> Int { func groupStageCut() -> Int {
@ -674,10 +684,12 @@ defer {
func cutLabel(index: Int, teamCount: Int?) -> String { func cutLabel(index: Int, teamCount: Int?) -> String {
let _teamCount = teamCount ?? selectedSortedTeams().count let _teamCount = teamCount ?? selectedSortedTeams().count
let bracketCut = bracketCut(teamCount: _teamCount) let groupStageCut = groupStageCut()
let bracketCut = bracketCut(teamCount: _teamCount, groupStageCut: groupStageCut)
if index < bracketCut { if index < bracketCut {
return "Tableau" return "Tableau"
} else if index - bracketCut < groupStageCut() && _teamCount > 0 { } else if index - bracketCut < groupStageCut && _teamCount > 0 {
return "Poule" return "Poule"
} else { } else {
return "Attente" return "Attente"
@ -687,11 +699,12 @@ defer {
func cutLabelColor(index: Int?, teamCount: Int?) -> Color { func cutLabelColor(index: Int?, teamCount: Int?) -> Color {
guard let index else { return Color.gray } guard let index else { return Color.gray }
let _teamCount = teamCount ?? selectedSortedTeams().count let _teamCount = teamCount ?? selectedSortedTeams().count
let bracketCut = bracketCut(teamCount: _teamCount) let groupStageCut = groupStageCut()
let bracketCut = bracketCut(teamCount: _teamCount, groupStageCut: groupStageCut)
if index < bracketCut { if index < bracketCut {
return Color.mint return Color.mint
} else if index - bracketCut < groupStageCut() && _teamCount > 0 { } else if index - bracketCut < groupStageCut && _teamCount > 0 {
return Color.cyan return Color.indigo
} else { } else {
return Color.gray return Color.gray
} }
@ -881,8 +894,8 @@ defer {
return max(1, courtCount) return max(1, courtCount)
} }
} }
func registrationIssues(selectedTeams: [TeamRegistration]) -> Int { func registrationIssues(selectedTeams: [TeamRegistration]) async -> Int {
let players : [PlayerRegistration] = unsortedPlayers() let players : [PlayerRegistration] = unsortedPlayers()
let callDateIssue : [TeamRegistration] = selectedTeams.filter { $0.callDate != nil && isStartDateIsDifferentThanCallDate($0) } let callDateIssue : [TeamRegistration] = selectedTeams.filter { $0.callDate != nil && isStartDateIsDifferentThanCallDate($0) }
let duplicates : [PlayerRegistration] = duplicates(in: players) let duplicates : [PlayerRegistration] = duplicates(in: players)
@ -1187,9 +1200,9 @@ defer {
} }
self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams) self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} }
func updateRank(to newDate: Date?) async throws { func updateRank(to newDate: Date?, forceRefreshLockWeight: Bool, providedSources: [CSVParser]?) async throws {
refreshRanking = true
#if DEBUG_TIME #if DEBUG_TIME
let start = Date() let start = Date()
defer { defer {
@ -1225,16 +1238,42 @@ defer {
let lastRankMan = monthData?.maleUnrankedValue ?? 0 let lastRankMan = monthData?.maleUnrankedValue ?? 0
let lastRankWoman = monthData?.femaleUnrankedValue ?? 0 let lastRankWoman = monthData?.femaleUnrankedValue ?? 0
// Fetch only the required files var chunkedParsers: [CSVParser] = []
let dataURLs = SourceFileManager.shared.allFiles.filter { $0.dateFromPath == newDate } if let providedSources {
guard !dataURLs.isEmpty else { return } // Early return if no files found chunkedParsers = providedSources
} else {
// Fetch only the required files
let dataURLs = SourceFileManager.shared.allFiles.filter { $0.dateFromPath == newDate }
guard !dataURLs.isEmpty else { return } // Early return if no files found
let sources = dataURLs.map { CSVParser(url: $0) } let sources = dataURLs.map { CSVParser(url: $0) }
chunkedParsers = try await chunkAllSources(sources: sources, size: 10000)
}
let players = unsortedPlayers() let players = unsortedPlayers()
try await players.concurrentForEach { player in try await players.concurrentForEach { player in
let lastRank = (player.sex == .female) ? lastRankWoman : lastRankMan let lastRank = (player.sex == .female) ? lastRankWoman : lastRankMan
try await player.updateRank(from: sources, lastRank: lastRank) try await player.updateRank(from: chunkedParsers, lastRank: lastRank)
player.setComputedRank(in: self)
}
if providedSources == nil {
try chunkedParsers.forEach { chunk in
try FileManager.default.removeItem(at: chunk.url)
}
}
try tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: players)
let unsortedTeams = unsortedTeams()
unsortedTeams.forEach { team in
team.setWeight(from: team.players(), inTournamentCategory: tournamentCategory)
if forceRefreshLockWeight {
team.lockedWeight = team.weight
}
} }
try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: unsortedTeams)
refreshRanking = false
} }
@ -1278,7 +1317,7 @@ defer {
} }
func hideWeight() -> Bool { func hideWeight() -> Bool {
return hideTeamsWeight || tournamentLevel.hideWeight() return hideTeamsWeight
} }
func isAnimation() -> Bool { func isAnimation() -> Bool {
@ -1537,6 +1576,7 @@ defer {
} }
team.setWeight(from: [], inTournamentCategory: self.tournamentCategory) team.setWeight(from: [], inTournamentCategory: self.tournamentCategory)
team.weight += 200_000
return team return team
} }
@ -1584,9 +1624,10 @@ defer {
return bracketTeamCount return bracketTeamCount
} }
func buildBracket() { func buildBracket(minimalBracketTeamCount: Int? = nil) {
guard rounds().isEmpty else { return } guard rounds().isEmpty else { return }
let roundCount = RoundRule.numberOfRounds(forTeams: bracketTeamCount()) let roundCount = RoundRule.numberOfRounds(forTeams: minimalBracketTeamCount ?? bracketTeamCount())
let matchCount = RoundRule.numberOfMatches(forTeams: minimalBracketTeamCount ?? bracketTeamCount())
let rounds = (0..<roundCount).map { //index 0 is the final let rounds = (0..<roundCount).map { //index 0 is the final
return Round(tournament: id, index: $0, matchFormat: roundSmartMatchFormat($0), loserBracketMode: loserBracketMode) return Round(tournament: id, index: $0, matchFormat: roundSmartMatchFormat($0), loserBracketMode: loserBracketMode)
@ -1601,7 +1642,6 @@ defer {
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
let matchCount = RoundRule.numberOfMatches(forTeams: bracketTeamCount())
let matches = (0..<matchCount).map { //0 is final match let matches = (0..<matchCount).map { //0 is final match
let roundIndex = RoundRule.roundIndex(fromMatchIndex: $0) let roundIndex = RoundRule.roundIndex(fromMatchIndex: $0)
@ -2079,12 +2119,15 @@ defer {
func updateSeedsBracketPosition() async { func updateSeedsBracketPosition() async {
await removeAllSeeds() await removeAllSeeds(saveTeamsAtTheEnd: false)
let drawLogs = drawLogs().reversed() let drawLogs = drawLogs().reversed()
let seeds = seeds() let seeds = seeds()
for (index, seed) in seeds.enumerated() {
if let drawLog = drawLogs.first(where: { $0.drawSeed == index }) { await MainActor.run {
drawLog.updateTeamBracketPosition(seed) for (index, seed) in seeds.enumerated() {
if let drawLog = drawLogs.first(where: { $0.drawSeed == index }) {
drawLog.updateTeamBracketPosition(seed)
}
} }
} }
@ -2094,12 +2137,14 @@ defer {
Logger.error(error) Logger.error(error)
} }
} }
func removeAllSeeds() async { func removeAllSeeds(saveTeamsAtTheEnd: Bool) async {
let teams = unsortedTeams() let teams = unsortedTeams()
teams.forEach({ team in teams.forEach({ team in
team.bracketPosition = nil team.bracketPosition = nil
team._cachedRestingTime = nil team._cachedRestingTime = nil
team.finalRanking = nil
team.pointsEarned = nil
}) })
let allMatches = allRoundMatches() let allMatches = allRoundMatches()
let ts = allMatches.flatMap { match in let ts = allMatches.flatMap { match in
@ -2120,18 +2165,13 @@ defer {
Logger.error(error) Logger.error(error)
} }
do { if saveTeamsAtTheEnd {
try tournamentStore?.matches.addOrUpdate(contentOfs: allMatches) do {
} catch { try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
Logger.error(error) } catch {
} Logger.error(error)
}
do {
try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} catch {
Logger.error(error)
} }
updateTournamentState()
} }
func addNewRound(_ roundIndex: Int) async { func addNewRound(_ roundIndex: Int) async {
@ -2238,8 +2278,7 @@ defer {
} }
// MARK: - Status // MARK: - Status
func shouldTournamentBeOver() async -> Bool {
func shouldTournamentBeOver() -> Bool {
#if _DEBUGING_TIME //DEBUGING TIME #if _DEBUGING_TIME //DEBUGING TIME
let start = Date() let start = Date()
defer { defer {
@ -2263,6 +2302,45 @@ defer {
return false return false
} }
func rankSourceShouldBeRefreshed() -> Date? {
if let mostRecentDate = SourceFileManager.shared.lastDataSourceDate(), let currentRankSourceDate = rankSourceDate, currentRankSourceDate < mostRecentDate, hasEnded() == false {
return mostRecentDate
} else {
return nil
}
}
func onlineTeams() -> [TeamRegistration] {
unsortedTeams().filter({ $0.hasRegisteredOnline() })
}
func shouldWarnOnlineRegistrationUpdates() -> Bool {
enableOnlineRegistration && onlineTeams().isEmpty == false && hasEnded() == false && hasStarted() == false
}
func refreshTeamList() async {
guard StoreCenter.main.hasToken() else { return }
guard shouldRefreshTeams(), refreshInProgress == false, enableOnlineRegistration, hasEnded() == false else { return }
await MainActor.run {
refreshInProgress = true
}
do {
try await self.tournamentStore?.playerRegistrations.loadDataFromServerIfAllowed(clear: true)
try await self.tournamentStore?.teamScores.loadDataFromServerIfAllowed(clear: true)
try await self.tournamentStore?.teamRegistrations.loadDataFromServerIfAllowed(clear: true)
await MainActor.run {
refreshInProgress = false
lastTeamRefresh = Date()
}
} catch {
Logger.error(error)
await MainActor.run {
refreshInProgress = false
lastTeamRefresh = Date()
}
}
}
// MARK: - // MARK: -
func insertOnServer() throws { func insertOnServer() throws {

@ -32,19 +32,35 @@ extension Sequence {
func concurrentForEach( func concurrentForEach(
_ operation: @escaping (Element) async throws -> Void _ operation: @escaping (Element) async throws -> Void
) async throws { ) async throws {
// A task group automatically waits for all of its
// sub-tasks to complete, while also performing those
// tasks in parallel:
try await withThrowingTaskGroup(of: Void.self) { group in try await withThrowingTaskGroup(of: Void.self) { group in
// First, create all tasks
for element in self { for element in self {
group.addTask { group.addTask {
try await operation(element) try await operation(element)
} }
for try await _ in group {}
} }
// Then wait for all tasks to complete
for try await _ in group {}
} }
} }
func concurrentForEach(
_ operation: @escaping (Element) async -> Void
) async {
await withTaskGroup(of: Void.self) { group in
// First, add all tasks
for element in self {
group.addTask {
await operation(element)
}
}
// Then wait for all tasks to complete
for await _ in group {}
}
}
} }
enum SortOrder { enum SortOrder {

@ -36,7 +36,7 @@ struct InscriptionLegendView: View {
Text("Équipe estimée en tableau") Text("Équipe estimée en tableau")
.listRowView(isActive: true, color: .mint, hideColorVariation: true, alignment: .leading) .listRowView(isActive: true, color: .mint, hideColorVariation: true, alignment: .leading)
Text("Équipe estimée en poule") Text("Équipe estimée en poule")
.listRowView(isActive: true, color: .cyan, hideColorVariation: true, alignment: .leading) .listRowView(isActive: true, color: .indigo, hideColorVariation: true, alignment: .leading)
} }

@ -0,0 +1,60 @@
//
// WaitingListView.swift
// PadelClub
//
// Created by razmig on 26/02/2025.
//
import SwiftUI
struct WaitingListView: View {
@Environment(Tournament.self) var tournament: Tournament
let teamCount: Int
@ViewBuilder
var body: some View {
Text("Attention, l'inscription en ligne est activée et vous avez des équipes inscrites en ligne, en modifiant la structure ces équipes seront intégrées ou retirées de votre sélection d'équipes. Pour l'instant Padel Club ne saura pas les prévenir automatiquement, vous devrez les contacter via l'écran de gestion des inscriptions.")
.foregroundStyle(.logoRed)
let selection = tournament.selectedSortedTeams()
if teamCount > tournament.teamCount {
Section {
let teams = tournament.waitingListSortedTeams(selectedSortedTeams: selection)
.prefix(teamCount - tournament.teamCount)
.filter { $0.hasRegisteredOnline() }
ForEach(teams) { team in
NavigationLink {
EditingTeamView(team: team)
.environment(tournament)
} label: {
TeamRowView(team: team)
}
}
} header: {
Text("Équipes entrantes dans la sélection")
} footer: {
Text("Équipes inscrites en ligne à prévenir rentrant dans votre liste")
}
}
if teamCount < tournament.teamCount {
Section {
let teams = selection.suffix(tournament.teamCount - teamCount)
.filter { $0.hasRegisteredOnline() }
ForEach(teams) { team in
NavigationLink {
EditingTeamView(team: team)
.environment(tournament)
} label: {
TeamRowView(team: team)
}
}
} header: {
Text("Équipes sortantes de la sélection")
} footer: {
Text("Équipes inscrites en ligne à prévenir retirées de votre liste")
}
}
}
}

@ -51,9 +51,9 @@ class NetworkManager {
let documentsUrl: URL = SourceFileManager.shared.rankingSourceDirectory let documentsUrl: URL = SourceFileManager.shared.rankingSourceDirectory
let destinationFileUrl = documentsUrl.appendingPathComponent("\(dateString)") let destinationFileUrl = documentsUrl.appendingPathComponent("\(dateString)")
let fileURL = URL(string: "https://xlr.alwaysdata.net/static/rankings/\(dateString)") let fileURL = URLs.main.extend(path: "static/rankings/\(dateString)")
var request = URLRequest(url:fileURL!) var request = URLRequest(url:fileURL)
request.addValue("attachment;filename=\(dateString)", forHTTPHeaderField:"Content-Disposition") request.addValue("attachment;filename=\(dateString)", forHTTPHeaderField:"Content-Disposition")
if FileManager.default.fileExists(atPath: destinationFileUrl.path()), let modificationDate = destinationFileUrl.creationDate() { if FileManager.default.fileExists(atPath: destinationFileUrl.path()), let modificationDate = destinationFileUrl.creationDate() {
request.addValue(formatDateForHTTPHeader(modificationDate), forHTTPHeaderField: "If-Modified-Since") request.addValue(formatDateForHTTPHeader(modificationDate), forHTTPHeaderField: "If-Modified-Since")

@ -70,18 +70,18 @@ struct Line: Identifiable {
struct CSVParser: AsyncSequence, AsyncIteratorProtocol { struct CSVParser: AsyncSequence, AsyncIteratorProtocol {
typealias Element = Line typealias Element = Line
private let url: URL let url: URL
private var lineIterator: LineIterator private var lineIterator: LineIterator
private let seperator: Character private let separator: Character
private let quoteCharacter: Character = "\"" private let quoteCharacter: Character = "\""
private var lineNumber = 0 private var lineNumber = 0
private let date: Date private let date: Date
let maleData: Bool let maleData: Bool
init(url: URL, seperator: Character = ";") { init(url: URL, separator: Character = ";") {
self.date = url.dateFromPath self.date = url.dateFromPath
self.url = url self.url = url
self.seperator = seperator self.separator = separator
self.lineIterator = url.lines.makeAsyncIterator() self.lineIterator = url.lines.makeAsyncIterator()
self.maleData = url.path().contains(SourceFile.messieurs.rawValue) self.maleData = url.path().contains(SourceFile.messieurs.rawValue)
} }
@ -127,7 +127,7 @@ struct CSVParser: AsyncSequence, AsyncIteratorProtocol {
func makeAsyncIterator() -> CSVParser { func makeAsyncIterator() -> CSVParser {
return self return self
} }
private func split(line: String) -> [String?] { private func split(line: String) -> [String?] {
var data = [String?]() var data = [String?]()
var inQuote = false var inQuote = false
@ -139,7 +139,7 @@ struct CSVParser: AsyncSequence, AsyncIteratorProtocol {
inQuote = !inQuote inQuote = !inQuote
continue continue
case seperator: case separator:
if !inQuote { if !inQuote {
data.append(currentString.isEmpty ? nil : currentString) data.append(currentString.isEmpty ? nil : currentString)
currentString = "" currentString = ""
@ -157,4 +157,63 @@ struct CSVParser: AsyncSequence, AsyncIteratorProtocol {
return data return data
} }
/// Splits the CSV file into multiple temporary CSV files, each containing `size` lines.
/// Returns an array of new `CSVParser` instances pointing to these chunked files.
func getChunkedParser(size: Int) async throws -> [CSVParser] {
var chunkedParsers: [CSVParser] = []
var currentChunk: [String] = []
var iterator = self.makeAsyncIterator()
var chunkIndex = 0
while let line = try await iterator.next()?.rawValue {
currentChunk.append(line)
// When the chunk reaches the desired size, write it to a file
if currentChunk.count == size {
let chunkURL = try writeChunkToFile(chunk: currentChunk, index: chunkIndex)
chunkedParsers.append(CSVParser(url: chunkURL, separator: self.separator))
chunkIndex += 1
currentChunk.removeAll()
}
}
// Handle remaining lines (if any)
if !currentChunk.isEmpty {
let chunkURL = try writeChunkToFile(chunk: currentChunk, index: chunkIndex)
chunkedParsers.append(CSVParser(url: chunkURL, separator: self.separator))
}
return chunkedParsers
}
/// Writes a chunk of CSV lines to a temporary file and returns its URL.
private func writeChunkToFile(chunk: [String], index: Int) throws -> URL {
let tempDirectory = FileManager.default.temporaryDirectory
let chunkURL = tempDirectory.appendingPathComponent("\(url.lastPathComponent)-\(index).csv")
let chunkData = chunk.joined(separator: "\n")
try chunkData.write(to: chunkURL, atomically: true, encoding: .utf8)
return chunkURL
}
}
/// Process all large CSV files concurrently and gather all mini CSVs.
func chunkAllSources(sources: [CSVParser], size: Int) async throws -> [CSVParser] {
var allChunks: [CSVParser] = []
await withTaskGroup(of: [CSVParser].self) { group in
for source in sources {
group.addTask {
return (try? await source.getChunkedParser(size: size)) ?? []
}
}
for await miniCSVs in group {
allChunks.append(contentsOf: miniCSVs)
}
}
return allChunks
} }

@ -199,14 +199,16 @@ struct CallView: View {
let uncalledTeams = teams.filter { $0.getPhoneNumbers().isEmpty } let uncalledTeams = teams.filter { $0.getPhoneNumbers().isEmpty }
if networkMonitor.connected == false { if networkMonitor.connected == false {
if uncalledTeams.isEmpty == false { if uncalledTeams.isEmpty == false, calledTeams.isEmpty == false {
self.sentError = .uncalledTeams(uncalledTeams) self.sentError = .uncalledTeams(uncalledTeams)
} else { } else {
self.sentError = .messageNotSent self.sentError = .messageNotSent
} }
} else { } else {
if uncalledTeams.isEmpty == false { if uncalledTeams.isEmpty == false, calledTeams.isEmpty == false {
self.sentError = .uncalledTeams(uncalledTeams) self.sentError = .uncalledTeams(uncalledTeams)
} else if uncalledTeams.isEmpty == false, calledTeams.isEmpty {
self._called(uncalledTeams, true)
} }
self._called(calledTeams, true) self._called(calledTeams, true)
} }
@ -228,14 +230,16 @@ struct CallView: View {
if networkMonitor.connected == false { if networkMonitor.connected == false {
self.contactType = nil self.contactType = nil
if uncalledTeams.isEmpty == false { if uncalledTeams.isEmpty == false, calledTeams.isEmpty == false {
self.sentError = .uncalledTeams(uncalledTeams) self.sentError = .uncalledTeams(uncalledTeams)
} else { } else {
self.sentError = .mailNotSent self.sentError = .mailNotSent
} }
} else { } else {
if uncalledTeams.isEmpty == false { if uncalledTeams.isEmpty == false, calledTeams.isEmpty == false {
self.sentError = .uncalledTeams(uncalledTeams) self.sentError = .uncalledTeams(uncalledTeams)
} else if uncalledTeams.isEmpty == false, calledTeams.isEmpty {
self._called(uncalledTeams, true)
} }
self._called(calledTeams, true) self._called(calledTeams, true)
} }

@ -128,6 +128,18 @@ struct GroupStagesSettingsView: View {
} }
} }
#endif #endif
Section {
menuGenerateGroupStage(.random)
} footer: {
Text("Redistribue les équipes par tirage au sort par chapeau")
}
Section {
menuGenerateGroupStage(.snake)
} footer: {
Text("Redistribue les équipes par la méthode du serpentin")
}
Section { Section {
RowButtonView("Retirer tous les horaires", role: .destructive) { RowButtonView("Retirer tous les horaires", role: .destructive) {
@ -144,30 +156,17 @@ struct GroupStagesSettingsView: View {
} }
} }
} footer: { } footer: {
Text("Retire les horaires pré-définis des matchs. Utile si vous avez convoqué mais que l'ordre des matchs à lancer n'est pas important.") Text("Retire les horaires pré-définis des matchs. Utile si vous avez convoqué mais que l'ordre des matchs à lancer n'est pas important.").foregroundStyle(.logoRed).bold()
} }
if tournament.unsortedTeams().filter({ $0.groupStagePosition != nil }).isEmpty == false { if tournament.unsortedTeams().filter({ $0.groupStagePosition != nil }).isEmpty == false {
Section { Section {
menuBuildAllGroupStages menuBuildAllGroupStages
} footer: { } footer: {
Text("Efface et recréé les poules, les horaires et les résultats existants seront perdus") Text("Efface et recréé les poules, les horaires et les résultats existants seront perdus").foregroundStyle(.logoRed).bold()
} }
} }
Section {
menuGenerateGroupStage(.random)
} footer: {
Text("Redistribue les équipes par tirage au sort par chapeau")
}
Section {
menuGenerateGroupStage(.snake)
} footer: {
Text("Redistribue les équipes par la méthode du serpentin")
}
let groupStages = tournament.groupStages() let groupStages = tournament.groupStages()
Section { Section {

@ -105,6 +105,80 @@ struct GroupStagesView: View {
allDestinations.append(contentsOf: groupStageDestinations) allDestinations.append(contentsOf: groupStageDestinations)
return allDestinations return allDestinations
} }
func sortedTeams(missingQualifiedFromGroupStages: [TeamRegistration]) -> [GroupStage.TeamGroupStageScore] {
let sortedTeams = missingQualifiedFromGroupStages.compactMap({ team in
team.groupStageObject()?.computedScore(forTeam: team)
}).sorted { (lhs, rhs) in
let predicates: [GroupStage.TeamScoreAreInIncreasingOrder] = [
{ $0.wins < $1.wins },
{ $0.setDifference < $1.setDifference },
{ $0.gameDifference < $1.gameDifference},
]
for predicate in predicates {
if !predicate(lhs, rhs) && !predicate(rhs, lhs) {
continue
}
return predicate(lhs, rhs)
}
return false
}
return sortedTeams
}
func _sortedAdditionnalTeams(missingQualifiedFromGroupStages: [TeamRegistration]) -> some View {
Section {
let teamGroupStageScores = self.sortedTeams(missingQualifiedFromGroupStages: missingQualifiedFromGroupStages).reversed()
ForEach(teamGroupStageScores, id: \.team.id) { teamGroupStageScore in
let team = teamGroupStageScore.team
let groupStage = team.groupStageObject()!
let groupStagePosition = team.groupStagePosition!
NavigationLink {
GroupStageTeamView(groupStage: groupStage, team: team)
.environment(self.tournament)
} label: {
HStack {
VStack(alignment: .leading) {
if let teamName = team.name, teamName.isEmpty == false {
Text(teamName).foregroundStyle(.secondary).font(.footnote)
}
ForEach(team.players()) { player in
Text(player.playerLabel()).lineLimit(1)
}
}
Spacer()
if let score = groupStage.scoreLabel(forGroupStagePosition: groupStagePosition, score: teamGroupStageScore) {
VStack(alignment: .trailing) {
HStack(spacing: 0.0) {
Text(score.wins)
Text("/")
Text(score.losses)
}.font(.headline).monospacedDigit()
if let setsDifference = score.setsDifference {
HStack(spacing: 4.0) {
Text(setsDifference)
}.font(.footnote)
}
if let gamesDifference = score.gamesDifference {
HStack(spacing: 4.0) {
Text(gamesDifference)
}.font(.footnote)
}
}
}
}
}
}
} header: {
let name = "\((tournament.qualifiedPerGroupStage + 1).ordinalFormatted())"
Text("Meilleurs \(name) de poule")
}
}
var body: some View { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
@ -116,9 +190,8 @@ struct GroupStagesView: View {
List { List {
if tournament.groupStageAdditionalQualified > 0 { if tournament.groupStageAdditionalQualified > 0 {
let missingQualifiedFromGroupStages = tournament.missingQualifiedFromGroupStages() let missingQualifiedFromGroupStages = tournament.missingQualifiedFromGroupStages()
let name = "\((tournament.qualifiedPerGroupStage + 1).ordinalFormatted())"
Section { Section {
let name = "\((tournament.qualifiedPerGroupStage + 1).ordinalFormatted())"
NavigationLink { NavigationLink {
SpinDrawView(drawees: ["Qualification d'un \(name) de poule"], segments: missingQualifiedFromGroupStages) { results in SpinDrawView(drawees: ["Qualification d'un \(name) de poule"], segments: missingQualifiedFromGroupStages) { results in
results.forEach { drawResult in results.forEach { drawResult in
@ -134,6 +207,8 @@ struct GroupStagesView: View {
Text("Qualifier un \(name) de poule par tirage au sort") Text("Qualifier un \(name) de poule par tirage au sort")
} }
.disabled(tournament.moreQualifiedToDraw() == 0 || missingQualifiedFromGroupStages.isEmpty) .disabled(tournament.moreQualifiedToDraw() == 0 || missingQualifiedFromGroupStages.isEmpty)
} header: {
Text("Tirage au sort d'un \(name) de poule")
} footer: { } footer: {
if tournament.moreQualifiedToDraw() == 0 { if tournament.moreQualifiedToDraw() == 0 {
Text("Aucune équipe supplémentaire à qualifier. Vous pouvez en rajouter en modifier le paramètre dans structure.") Text("Aucune équipe supplémentaire à qualifier. Vous pouvez en rajouter en modifier le paramètre dans structure.")
@ -141,6 +216,8 @@ struct GroupStagesView: View {
Text("Aucune équipe supplémentaire à tirer au sort. Attendez la fin des poules.") Text("Aucune équipe supplémentaire à tirer au sort. Attendez la fin des poules.")
} }
} }
_sortedAdditionnalTeams(missingQualifiedFromGroupStages: missingQualifiedFromGroupStages)
} }
let runningMatches = Tournament.runningMatches(allMatches) let runningMatches = Tournament.runningMatches(allMatches)

@ -30,7 +30,7 @@ struct MatchDateView: View {
} }
var currentDate: Date { var currentDate: Date {
Date().withoutSeconds() Date()
} }
var body: some View { var body: some View {

@ -151,7 +151,7 @@ struct PlayerBlockView: View {
} }
} }
} }
} else if let team { } else if let team, hasWon == false, isWalkOut == false {
TeamWeightView(team: team, teamPosition: teamPosition) TeamWeightView(team: team, teamPosition: teamPosition)
} }
} }

@ -501,7 +501,7 @@ struct MatchDetailView: View {
Text("Horaire") Text("Horaire")
} }
.onChange(of: startDateSetup) { .onChange(of: startDateSetup) {
let date = Date().withoutSeconds() let date = Date()
switch startDateSetup { switch startDateSetup {
case .customDate: case .customDate:
break break

@ -178,6 +178,12 @@ struct ActivityView: View {
federalDataViewModel.federalTournaments.removeAll() federalDataViewModel.federalTournaments.removeAll()
NetworkFederalService.shared.formId = "" NetworkFederalService.shared.formId = ""
_gatherFederalTournaments() _gatherFederalTournaments()
} else if navigation.agendaDestination == .activity {
runningTournaments.forEach { t in
if let tournament = t as? Tournament {
tournament.lastTeamRefresh = nil
}
}
} }
} }
.task { .task {

@ -19,6 +19,11 @@ struct EventListView: View {
@State var showUserSearch: Bool = false @State var showUserSearch: Bool = false
var lastDataSource: Date? {
guard let _lastDataSource = dataStore.appSettings.lastDataSource else { return nil }
return URL.importDateFormatter.date(from: _lastDataSource)
}
var body: some View { var body: some View {
let groupedTournamentsByDate = Dictionary(grouping: federalDataViewModel.filteredFederalTournaments(from: tournaments)) { $0.startDate.startOfMonth } let groupedTournamentsByDate = Dictionary(grouping: federalDataViewModel.filteredFederalTournaments(from: tournaments)) { $0.startDate.startOfMonth }
switch viewStyle { switch viewStyle {
@ -103,6 +108,41 @@ struct EventListView: View {
@ViewBuilder @ViewBuilder
private func _options(_ pcTournaments: [Tournament]) -> some View { private func _options(_ pcTournaments: [Tournament]) -> some View {
if let lastDataSource, pcTournaments.anySatisfy({ $0.rankSourceShouldBeRefreshed() != nil && $0.hasEnded() == false }) {
Section {
Button {
Task {
do {
let dataURLs = SourceFileManager.shared.allFiles.filter { $0.dateFromPath == lastDataSource }
guard !dataURLs.isEmpty else { return } // Early return if no files found
let sources = dataURLs.map { CSVParser(url: $0) }
let chunkedParsers = try await chunkAllSources(sources: sources, size: 10000)
try await pcTournaments.concurrentForEach { tournament in
if let mostRecentDate = tournament.rankSourceShouldBeRefreshed() {
try await tournament.updateRank(to: mostRecentDate, forceRefreshLockWeight: false, providedSources: chunkedParsers)
}
}
try chunkedParsers.forEach { chunk in
try FileManager.default.removeItem(at: chunk.url)
}
try dataStore.tournaments.addOrUpdate(contentOfs: pcTournaments)
} catch {
Logger.error(error)
}
}
} label: {
Text("Rafraîchir les classements")
}
} header: {
Text("Source disponible : \(lastDataSource.monthYearFormatted)")
}
Divider()
}
Section { Section {
if pcTournaments.anySatisfy({ $0.isPrivate == true }) { if pcTournaments.anySatisfy({ $0.isPrivate == true }) {
Button { Button {
@ -137,7 +177,7 @@ struct EventListView: View {
Text("Visibilité sur Padel Club") Text("Visibilité sur Padel Club")
} }
Divider() Divider()
if pcTournaments.anySatisfy({ $0.hasEnded() == false && $0.enableOnlineRegistration == false && $0.onlineRegistrationCanBeEnabled() }) || pcTournaments.anySatisfy({ $0.enableOnlineRegistration == true }) { if pcTournaments.anySatisfy({ $0.hasEnded() == false && $0.enableOnlineRegistration == false && $0.onlineRegistrationCanBeEnabled() }) || pcTournaments.anySatisfy({ $0.enableOnlineRegistration == true && $0.hasEnded() == false }) {
Section { Section {
if pcTournaments.anySatisfy({ $0.hasEnded() == false && $0.enableOnlineRegistration == false && $0.onlineRegistrationCanBeEnabled() }) { if pcTournaments.anySatisfy({ $0.hasEnded() == false && $0.enableOnlineRegistration == false && $0.onlineRegistrationCanBeEnabled() }) {
Button { Button {
@ -154,7 +194,19 @@ struct EventListView: View {
} }
} }
if pcTournaments.anySatisfy({ $0.enableOnlineRegistration == true }) { if pcTournaments.anySatisfy({ $0.enableOnlineRegistration == true && $0.hasEnded() == false }) {
Button {
Task {
await pcTournaments.concurrentForEach { tournament in
await tournament.refreshTeamList()
}
}
} label: {
Text("Rafraîchir la liste des équipes inscrites en ligne")
}
Button { Button {
pcTournaments.forEach { tournament in pcTournaments.forEach { tournament in
tournament.enableOnlineRegistration = false tournament.enableOnlineRegistration = false
@ -208,11 +260,11 @@ struct EventListView: View {
private func _tournamentView(_ tournament: Tournament) -> some View { private func _tournamentView(_ tournament: Tournament) -> some View {
NavigationLink(value: tournament) { NavigationLink(value: tournament) {
TournamentCellView(tournament: tournament)
TournamentCellView(tournament: tournament, shouldTournamentBeOver: tournament.shouldTournamentBeOver()) .id(tournament.lastTeamRefresh)
.popover(isPresented: self.$showUserSearch) { .task(priority: .background) {
ShareModelView(instance: tournament) await tournament.refreshTeamList()
} }
} }
.listRowView(isActive: tournament.enableOnlineRegistration, color: .green, hideColorVariation: true) .listRowView(isActive: tournament.enableOnlineRegistration, color: .green, hideColorVariation: true)
.contextMenu { .contextMenu {

@ -97,7 +97,7 @@ struct EditablePlayerView: View {
@ViewBuilder @ViewBuilder
func computedPlayerView(_ player: PlayerRegistration) -> some View { func computedPlayerView(_ player: PlayerRegistration) -> some View {
VStack(alignment: .leading, spacing: 0.0) { VStack(alignment: .leading, spacing: 0.0) {
ImportedPlayerView(player: player) ImportedPlayerView(player: player, showFemaleInMaleAssimilation: player.tournament()?.tournamentCategory.showFemaleInMaleAssimilation ?? false)
// HStack { // HStack {
// Text(player.isImported() ? "importé via beach padel" : "") // Text(player.isImported() ? "importé via beach padel" : "")
// Text(player.formattedLicense().isLicenseNumber ? "licence valide" : "non valide") // Text(player.formattedLicense().isLicenseNumber ? "licence valide" : "non valide")

@ -20,7 +20,7 @@ struct PlayerView: View {
} }
var body: some View { var body: some View {
ImportedPlayerView(player: player) ImportedPlayerView(player: player, showFemaleInMaleAssimilation: tournament.tournamentCategory.showFemaleInMaleAssimilation)
.swipeActions(edge: .trailing, allowsFullSwipe: true) { .swipeActions(edge: .trailing, allowsFullSwipe: true) {
Button(role: .destructive) { Button(role: .destructive) {
do { do {

@ -150,7 +150,7 @@ struct RoundSettingsView: View {
private func _removeAllSeeds() async { private func _removeAllSeeds() async {
await tournament.removeAllSeeds() await tournament.removeAllSeeds(saveTeamsAtTheEnd: true)
self.isEditingTournamentSeed.wrappedValue = true self.isEditingTournamentSeed.wrappedValue = true
} }

@ -217,6 +217,11 @@ struct FollowUpMatchView: View {
} }
#if DEBUG #if DEBUG
Spacer() Spacer()
if let roundObject = match.roundObject {
Text(roundObject.index.formatted())
Text(roundObject.theoryCumulativeMatchCount.formatted())
}
Text(match.computedOrder.formatted())
FooterButtonView("copier l'id") { FooterButtonView("copier l'id") {
let pasteboard = UIPasteboard.general let pasteboard = UIPasteboard.general
pasteboard.string = match.id pasteboard.string = match.id

@ -427,7 +427,9 @@ struct MySearchView: View {
searchViewModel.selectedPlayers.insert(player) searchViewModel.selectedPlayers.insert(player)
} label: { } label: {
ImportedPlayerView(player: player, showFemaleInMaleAssimilation: searchViewModel.showFemaleInMaleAssimilation, showProgression: true) ImportedPlayerView(player: player, showFemaleInMaleAssimilation: searchViewModel.showFemaleInMaleAssimilation, showProgression: true)
.contentShape(Rectangle())
} }
.frame(maxWidth: .infinity)
.buttonStyle(.plain) .buttonStyle(.plain)
} }
} header: { } header: {

@ -20,11 +20,11 @@ struct EditingTeamView: View {
@State private var sentError: ContactManagerError? = nil @State private var sentError: ContactManagerError? = nil
@State private var showSubscriptionView: Bool = false @State private var showSubscriptionView: Bool = false
@State private var registrationDate : Date @State private var registrationDate : Date
@State private var walkOut : Bool
@State private var wildCardBracket : Bool
@State private var wildCardGroupStage : Bool
@State private var name: String @State private var name: String
@FocusState private var focusedField: TeamRegistration.CodingKeys? @FocusState private var focusedField: TeamRegistration.CodingKeys?
@State private var presentOnlineRegistrationWarning: Bool = false
@State private var currentWaitingList: TeamRegistration?
@State private var presentTeamToWarn: Bool = false
var messageSentFailed: Binding<Bool> { var messageSentFailed: Binding<Bool> {
Binding { Binding {
@ -36,6 +36,22 @@ struct EditingTeamView: View {
} }
} }
var hasChanged: Binding<Bool> {
Binding {
if canSaveWithoutWarning() {
return false
}
return
registrationDate != team.registrationDate
|| walkOut != team.walkOut
|| wildCardBracket != team.wildCardBracket
|| wildCardGroupStage != team.wildCardGroupStage
} set: { _ in
}
}
var tournamentStore: TournamentStore? { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -44,25 +60,19 @@ struct EditingTeamView: View {
self.team = team self.team = team
_name = .init(wrappedValue: team.name ?? "") _name = .init(wrappedValue: team.name ?? "")
_registrationDate = State(wrappedValue: team.registrationDate ?? Date()) _registrationDate = State(wrappedValue: team.registrationDate ?? Date())
_walkOut = State(wrappedValue: team.walkOut)
_wildCardBracket = State(wrappedValue: team.wildCardBracket)
_wildCardGroupStage = State(wrappedValue: team.wildCardGroupStage)
} }
private func _resetTeam() { private func _resetTeam() {
let selectedSortedTeams = tournament.selectedSortedTeams()
self.currentWaitingList = tournament.waitingListSortedTeams(selectedSortedTeams: selectedSortedTeams).filter({ $0.hasRegisteredOnline() }).first
team.resetPositions() team.resetPositions()
team.qualified = false
team.wildCardGroupStage = false team.wildCardGroupStage = false
team.walkOut = false team.walkOut = false
team.wildCardBracket = false team.wildCardBracket = false
} }
private func _checkOnlineRegistrationWarning() {
guard let currentWaitingList else { return }
let selectedSortedTeams = tournament.selectedSortedTeams().map({ $0.id })
if selectedSortedTeams.contains(currentWaitingList.id) {
presentOnlineRegistrationWarning = true
}
}
var body: some View { var body: some View {
List { List {
Section { Section {
@ -92,10 +102,6 @@ struct EditingTeamView: View {
.headerProminence(.increased) .headerProminence(.increased)
Section { Section {
DatePicker(selection: $registrationDate) {
Text("Inscription")
Text(registrationDate.localizedWeekDay().capitalized)
}
if let callDate = team.callDate { if let callDate = team.callDate {
LabeledContent() { LabeledContent() {
Text(callDate.localizedDate()) Text(callDate.localizedDate())
@ -117,36 +123,23 @@ struct EditingTeamView: View {
Text("Équipe sur place") Text("Équipe sur place")
} }
} }
}
Section {
DatePicker(selection: $registrationDate) {
Text("Inscription")
Text(registrationDate.localizedWeekDay().capitalized)
}
Toggle(isOn: .init(get: { Toggle(isOn: $wildCardBracket) {
return team.wildCardBracket
}, set: { value in
_resetTeam()
team.wildCardBracket = value
_save()
})) {
Text("Wildcard Tableau") Text("Wildcard Tableau")
} }
Toggle(isOn: .init(get: { Toggle(isOn: $wildCardGroupStage) {
return team.wildCardGroupStage
}, set: { value in
_resetTeam()
team.wildCardGroupStage = value
_save()
})) {
Text("Wildcard Poule") Text("Wildcard Poule")
} }.disabled(tournament.groupStageCount == 0)
Toggle(isOn: .init(get: { Toggle(isOn: $walkOut) {
return team.walkOut
}, set: { value in
_resetTeam()
team.walkOut = value
_save()
})) {
Text("Forfait") Text("Forfait")
} }
} }
@ -218,30 +211,24 @@ struct EditingTeamView: View {
} }
} }
} }
.sheet(isPresented: $presentTeamToWarn) { .alert("Attention", isPresented: hasChanged, actions: {
if let currentWaitingList { Button("Confirmer") {
NavigationStack { _resetTeam()
EditingTeamView(team: currentWaitingList) team.registrationDate = registrationDate
} team.wildCardBracket = wildCardBracket
.tint(.master) team.wildCardGroupStage = wildCardGroupStage
team.walkOut = walkOut
_save()
} }
}
.alert("Attention", isPresented: $presentOnlineRegistrationWarning, actions: { Button("Annuler", role: .cancel) {
if currentWaitingList != nil { registrationDate = team.registrationDate ?? Date()
walkOut = team.walkOut
Button("Voir l'équipe") { wildCardBracket = team.wildCardBracket
self.presentTeamToWarn = true wildCardGroupStage = team.wildCardGroupStage
}
Button("OK") {
self.currentWaitingList = nil
self.presentOnlineRegistrationWarning = false
}
} }
}, message: { }, message: {
if let currentWaitingList { Text("Ce changement peut entraîner l'entrée ou la sortie d'une équipe de votre sélection. Padel Club préviendra automatiquement une équipe inscrite en ligne de son nouveau statut.")
Text("L'équipe \(currentWaitingList.teamLabel(separator: "/")), inscrite en ligne, rentre dans votre sélection suite à la modification que vous venez de faire, voulez-vous les prévenir ?")
}
}) })
.navigationBarBackButtonHidden(focusedField != nil) .navigationBarBackButtonHidden(focusedField != nil)
.toolbar(content: { .toolbar(content: {
@ -329,14 +316,29 @@ struct EditingTeamView: View {
} }
} }
.onChange(of: registrationDate) { .onChange(of: registrationDate) {
team.registrationDate = registrationDate if canSaveWithoutWarning() {
_save() team.registrationDate = registrationDate
_save()
}
}
.onChange(of: [walkOut, wildCardBracket, wildCardGroupStage]) {
if canSaveWithoutWarning() {
_resetTeam()
team.walkOut = walkOut
team.wildCardBracket = wildCardBracket
team.wildCardGroupStage = wildCardGroupStage
_save()
}
} }
.toolbarBackground(.visible, for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar)
.navigationTitle("Édition de l'équipe") .navigationTitle("Édition de l'équipe")
.navigationBarTitleDisplayMode(.inline) .navigationBarTitleDisplayMode(.inline)
} }
func canSaveWithoutWarning() -> Bool {
(tournament.shouldWarnOnlineRegistrationUpdates() && tournament.teamCount <= tournament.unsortedTeamsCount()) == false
}
private var confirmationReceived: Binding<Bool> { private var confirmationReceived: Binding<Bool> {
Binding { Binding {
team.confirmed() team.confirmed()
@ -371,8 +373,6 @@ struct EditingTeamView: View {
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
_checkOnlineRegistrationWarning()
} }
private var _networkErrorMessage: String { private var _networkErrorMessage: String {

@ -134,11 +134,19 @@ struct TeamPickerView: View {
// presentTeamPickerView = false // presentTeamPickerView = false
// } // }
} label: { } label: {
TeamRowView(team: team) VStack(alignment: .leading) {
.contentShape(Rectangle()) if let roundAndMatchTitle = team.bracketMatchTitleAndQualifiedStatus() {
Text(roundAndMatchTitle)
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
}
TeamRowView(team: team)
}
.contentShape(Rectangle())
} }
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
.buttonStyle(.plain) .buttonStyle(.plain)
.id(team.id)
.listRowView(isActive: matchTypeContext == .loserBracket && round?.teams().map({ $0.id }).contains(team.id) == true, color: .green, hideColorVariation: true) .listRowView(isActive: matchTypeContext == .loserBracket && round?.teams().map({ $0.id }).contains(team.id) == true, color: .green, hideColorVariation: true)
// .confirmationDialog("Attention", isPresented: confirmationRequest, titleVisibility: .visible) { // .confirmationDialog("Attention", isPresented: confirmationRequest, titleVisibility: .visible) {
// Button("Retirer du tableau", role: .destructive) { // Button("Retirer du tableau", role: .destructive) {

@ -9,6 +9,8 @@ import SwiftUI
struct TeamRowView: View { struct TeamRowView: View {
@EnvironmentObject var dataStore: DataStore @EnvironmentObject var dataStore: DataStore
@Environment(\.isEditingTournamentSeed) private var isEditingTournamentSeed
var team: TeamRegistration var team: TeamRegistration
var teamPosition: TeamPosition? = nil var teamPosition: TeamPosition? = nil
var displayCallDate: Bool = false var displayCallDate: Bool = false
@ -20,7 +22,9 @@ struct TeamRowView: View {
TeamWeightView(team: team, teamPosition: teamPosition, teamIndex: teamIndex) TeamWeightView(team: team, teamPosition: teamPosition, teamIndex: teamIndex)
} label: { } label: {
VStack(alignment: .leading) { VStack(alignment: .leading) {
TeamHeadlineView(team: team) if isEditingTournamentSeed.wrappedValue == false {
TeamHeadlineView(team: team)
}
TeamView(team: team) TeamView(team: team)
} }
if displayCallDate { if displayCallDate {

@ -120,10 +120,10 @@ struct FileImportView: View {
return teams.filter { $0.tournamentCategory == tournament.tournamentCategory && $0.tournamentAgeCategory == tournament.federalTournamentAge }.sorted(by: \.weight) return teams.filter { $0.tournamentCategory == tournament.tournamentCategory && $0.tournamentAgeCategory == tournament.federalTournamentAge }.sorted(by: \.weight)
} }
private func _deleteTeams() async { private func _deleteTeams(teams: [TeamRegistration]) async {
await MainActor.run { await MainActor.run {
do { do {
try tournamentStore?.teamRegistrations.delete(contentOfs: tournament.unsortedTeams()) try tournamentStore?.teamRegistrations.delete(contentOfs: teams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -140,9 +140,18 @@ struct FileImportView: View {
} }
} }
if tournament.unsortedTeams().count > 0, tournament.enableOnlineRegistration == false { let unsortedTeams = tournament.unsortedTeams()
RowButtonView("Effacer les équipes déjà inscrites", role: .destructive) { let onlineTeams = unsortedTeams.filter({ $0.hasRegisteredOnline() })
await _deleteTeams() if unsortedTeams.count > 0 {
Section {
RowButtonView("Effacer les équipes déjà inscrites", role: .destructive) {
await _deleteTeams(teams: unsortedTeams)
}
.disabled(onlineTeams.isEmpty == false)
} footer: {
if onlineTeams.isEmpty == false {
Text("Ce tournoi contient des inscriptions en ligne, vous ne pouvez pas effacer toute votre liste d'inscription d'un coup.")
}
} }
} }
@ -499,21 +508,7 @@ struct FileImportView: View {
private func _validate(tournament: Tournament) async { private func _validate(tournament: Tournament) async {
let filteredTeams = filteredTeams(tournament: tournament) let filteredTeams = filteredTeams(tournament: tournament)
let unfound = _getUnfound(tournament: tournament, fromTeams: filteredTeams)
unfound.forEach { team in
if team.isWildCard() == false {
team.resetPositions()
team.walkOut = true
}
}
do {
try tournament.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: unfound)
} catch {
Logger.error(error)
}
tournament.importTeams(filteredTeams) tournament.importTeams(filteredTeams)
validatedTournamentIds.insert(tournament.id) validatedTournamentIds.insert(tournament.id)

@ -80,7 +80,15 @@ struct AddTeamView: View {
fetchRequest = FetchRequest(fetchRequest: request, animation: .default) fetchRequest = FetchRequest(fetchRequest: request, animation: .default)
} }
var selectionLimit: Int {
if tournament.isAnimation() {
return -1
} else {
return tournament.significantPlayerCount() - _currentSelectionIds().count
}
}
var body: some View { var body: some View {
if let pasteString, pasteString.isEmpty == false, fetchPlayers.isEmpty == false { if let pasteString, pasteString.isEmpty == false, fetchPlayers.isEmpty == false {
computedBody computedBody
@ -163,7 +171,7 @@ struct AddTeamView: View {
} }
.sheet(isPresented: $presentPlayerSearch) { .sheet(isPresented: $presentPlayerSearch) {
NavigationStack { NavigationStack {
SelectablePlayerListView(allowSelection: 2 - _currentSelectionIds().count, isPresented: true, searchField: searchField, filterOption: _filterOption(), showFemaleInMaleAssimilation: tournament.tournamentCategory.showFemaleInMaleAssimilation) { players in SelectablePlayerListView(allowSelection: selectionLimit, isPresented: true, searchField: searchField, filterOption: _filterOption(), showFemaleInMaleAssimilation: tournament.tournamentCategory.showFemaleInMaleAssimilation) { players in
players.forEach { player in players.forEach { player in
let newPlayer = PlayerRegistration(importedPlayer: player) let newPlayer = PlayerRegistration(importedPlayer: player)
newPlayer.setComputedRank(in: tournament) newPlayer.setComputedRank(in: tournament)

@ -42,25 +42,8 @@ struct UpdateSourceRankDateView: View {
updatingRank = true updatingRank = true
Task { Task {
do { do {
try await tournament.updateRank(to: currentRankSourceDate)
let unsortedPlayers = tournament.unsortedPlayers()
tournament.unsortedPlayers().forEach { player in
player.setComputedRank(in: tournament)
}
try tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: unsortedPlayers)
let unsortedTeams = tournament.unsortedTeams()
unsortedTeams.forEach { team in
team.setWeight(from: team.players(), inTournamentCategory: tournament.tournamentCategory)
if forceRefreshLockWeight {
team.lockedWeight = team.weight
}
}
try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: unsortedTeams)
try await tournament.updateRank(to: currentRankSourceDate, forceRefreshLockWeight: forceRefreshLockWeight, providedSources: nil)
try dataStore.tournaments.addOrUpdate(instance: tournament) try dataStore.tournaments.addOrUpdate(instance: tournament)
} catch { } catch {
Logger.error(error) Logger.error(error)

@ -51,7 +51,6 @@ struct InscriptionManagerView: View {
@State private var pasteString: String? @State private var pasteString: String?
@State private var registrationIssues: Int? = nil @State private var registrationIssues: Int? = nil
@State private var refreshResult: String? = nil @State private var refreshResult: String? = nil
@State private var refreshInProgress: Bool = false
@State private var refreshStatus: Bool? @State private var refreshStatus: Bool?
@State private var showLegendView: Bool = false @State private var showLegendView: Bool = false
@ -193,8 +192,8 @@ struct InscriptionManagerView: View {
self.teamsHash = _simpleHash(ids: selectedSortedTeams.map { $0.id }) self.teamsHash = _simpleHash(ids: selectedSortedTeams.map { $0.id })
} }
self.registrationIssues = nil self.registrationIssues = nil
DispatchQueue.main.async { Task {
self.registrationIssues = tournament.registrationIssues(selectedTeams: selectedSortedTeams) self.registrationIssues = await tournament.registrationIssues(selectedTeams: selectedSortedTeams)
} }
} }
@ -248,7 +247,7 @@ struct InscriptionManagerView: View {
if tournament.enableOnlineRegistration { if tournament.enableOnlineRegistration {
RowButtonView("Rafraîchir la liste", cornerRadius: 20) { RowButtonView("Rafraîchir la liste", cornerRadius: 20) {
await _refreshList() await _refreshList(forced: true)
} }
} else if tournament.onlineRegistrationCanBeEnabled() { } else if tournament.onlineRegistrationCanBeEnabled() {
RowButtonView("Inscription en ligne") { RowButtonView("Inscription en ligne") {
@ -259,11 +258,16 @@ struct InscriptionManagerView: View {
} }
} }
} }
.task(priority: .background) {
await _refreshList(forced: false)
}
.refreshable { .refreshable {
await _refreshList() await _refreshList(forced: true)
} }
.onAppear { .onAppear {
_setHash(currentSelectedSortedTeams: selectedSortedTeams) if tournament.enableOnlineRegistration == false || refreshStatus == true {
_setHash(currentSelectedSortedTeams: selectedSortedTeams)
}
} }
.onDisappear { .onDisappear {
_handleHashDiff(selectedSortedTeams: selectedSortedTeams) _handleHashDiff(selectedSortedTeams: selectedSortedTeams)
@ -542,29 +546,29 @@ struct InscriptionManagerView: View {
// try? tournamentStore.playerRegistrations.addOrUpdate(contentOfs: players) // try? tournamentStore.playerRegistrations.addOrUpdate(contentOfs: players)
// } // }
// //
private func _refreshList() async { private func _refreshList(forced: Bool) async {
if refreshInProgress { return } if refreshStatus == true, forced == false { return }
if tournament.enableOnlineRegistration == false { return }
if tournament.hasEnded() { return }
if tournament.refreshInProgress { return }
refreshResult = nil refreshResult = nil
refreshStatus = nil refreshStatus = nil
refreshInProgress = true
do { do {
try await self.tournamentStore?.playerRegistrations.loadDataFromServerIfAllowed(clear: true) await self.tournament.refreshTeamList()
try await self.tournamentStore?.teamScores.loadDataFromServerIfAllowed(clear: true)
try await self.tournamentStore?.teamRegistrations.loadDataFromServerIfAllowed(clear: true)
_setHash() _setHash()
if let lastTeamRefresh = self.tournament.lastTeamRefresh?.formatted(date: .abbreviated, time: .shortened) {
self.refreshResult = "la synchronization a réussi" self.refreshResult = "Dernière m-à-j : \(lastTeamRefresh)"
} else {
self.refreshResult = "La synchronization a réussi"
}
self.refreshStatus = true self.refreshStatus = true
refreshInProgress = false
} catch { } catch {
Logger.error(error) Logger.error(error)
self.refreshResult = "La synchronization a échoué"
self.refreshResult = "la synchronization a échoué"
self.refreshStatus = false self.refreshStatus = false
refreshInProgress = false
} }
} }
@ -717,7 +721,7 @@ struct InscriptionManagerView: View {
@ViewBuilder @ViewBuilder
private func _rankHandlerView() -> some View { private func _rankHandlerView() -> some View {
if let mostRecentDate = SourceFileManager.shared.lastDataSourceDate(), let currentRankSourceDate, currentRankSourceDate < mostRecentDate, tournament.hasEnded() == false { if let mostRecentDate = tournament.rankSourceShouldBeRefreshed() {
Section { Section {
TipView(rankUpdateTip) { action in TipView(rankUpdateTip) { action in
self.currentRankSourceDate = mostRecentDate self.currentRankSourceDate = mostRecentDate
@ -839,28 +843,21 @@ struct InscriptionManagerView: View {
// } // }
if tournament.enableOnlineRegistration { if tournament.enableOnlineRegistration {
Button { LabeledContent {
Task { Text(tournament.unsortedTeams().filter({ $0.hasRegisteredOnline() }).count.formatted())
await _refreshList() .font(.largeTitle)
}
} label: { } label: {
LabeledContent { Text("Inscriptions en ligne")
if refreshInProgress { if let refreshResult {
ProgressView() Text(refreshResult).foregroundStyle(.secondary)
} else if let refreshStatus { } else {
if refreshStatus { Text(" ")
Image(systemName: "checkmark").foregroundStyle(.green).font(.headline)
} else {
Image(systemName: "xmark").foregroundStyle(.logoRed).font(.headline)
}
}
} label: {
Text("Récupérer les inscriptions en ligne")
if let refreshResult {
Text(refreshResult)
}
} }
} }
RowButtonView("Rafraîchir les inscriptions en ligne") {
await _refreshList(forced: true)
}
} }
} header: { } header: {
HStack { HStack {

@ -27,7 +27,7 @@ struct RegistrationSetupView: View {
@State private var showMoreInfos: Bool = false @State private var showMoreInfos: Bool = false
@State private var hasChanges: Bool = false @State private var hasChanges: Bool = false
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
init(tournament: Tournament) { init(tournament: Tournament) {
@ -72,8 +72,18 @@ struct RegistrationSetupView: View {
} }
func displayWarning() -> Bool {
let unsortedTeamsCount = tournament.unsortedTeamsCount()
return tournament.shouldWarnOnlineRegistrationUpdates() && targetTeamCount != tournament.teamCount && (tournament.teamCount <= unsortedTeamsCount || targetTeamCount <= unsortedTeamsCount)
}
var body: some View { var body: some View {
List { List {
if displayWarning() {
Text("Attention, l'inscription en ligne est activée et vous avez des équipes inscrites en ligne, en modifiant la structure ces équipes seront intégrées ou retirées de votre sélection d'équipes. Padel Club saura prévenir les équipes inscrites en ligne automatiquement.")
.foregroundStyle(.logoRed)
}
Section { Section {
Toggle(isOn: $enableOnlineRegistration) { Toggle(isOn: $enableOnlineRegistration) {
Text("Activer") Text("Activer")

@ -23,6 +23,11 @@ struct TableStructureView: View {
@State private var buildWildcards: Bool = true @State private var buildWildcards: Bool = true
@FocusState private var stepperFieldIsFocused: Bool @FocusState private var stepperFieldIsFocused: Bool
func displayWarning() -> Bool {
let unsortedTeamsCount = tournament.unsortedTeamsCount()
return tournament.shouldWarnOnlineRegistrationUpdates() && teamCount != tournament.teamCount && (tournament.teamCount <= unsortedTeamsCount || teamCount <= unsortedTeamsCount)
}
var qualifiedFromGroupStage: Int { var qualifiedFromGroupStage: Int {
groupStageCount * qualifiedPerGroupStage groupStageCount * qualifiedPerGroupStage
} }
@ -43,7 +48,7 @@ struct TableStructureView: View {
var moreQualifiedLabel: String { var moreQualifiedLabel: String {
if groupStageAdditionalQualified == 0 { return "Aucun" } if groupStageAdditionalQualified == 0 { return "Aucun" }
return (groupStageAdditionalQualified > 1 ? "les \(groupStageAdditionalQualified)" : "le") + " meilleur\(groupStageAdditionalQualified.pluralSuffix) " + (qualifiedPerGroupStage + 1).ordinalFormatted() return (groupStageAdditionalQualified > 1 ? "les \(groupStageAdditionalQualified)" : "le") + " " + (qualifiedPerGroupStage + 1).ordinalFormatted()
} }
var maxGroupStages: Int { var maxGroupStages: Int {
@ -58,7 +63,11 @@ struct TableStructureView: View {
@ViewBuilder @ViewBuilder
var body: some View { var body: some View {
List { List {
if displayWarning() {
Text("Attention, l'inscription en ligne est activée et vous avez des équipes inscrites en ligne, en modifiant la structure ces équipes seront intégrées ou retirées de votre sélection d'équipes. Padel Club saura prévenir les équipes inscrites en ligne automatiquement.")
.foregroundStyle(.logoRed)
}
if tournament.state() != .build { if tournament.state() != .build {
Section { Section {
Picker(selection: $structurePreset) { Picker(selection: $structurePreset) {
@ -252,6 +261,16 @@ struct TableStructureView: View {
} }
} }
if tournament.rounds().isEmpty, tournament.state() == .build {
Section {
RowButtonView("Ajouter un tableau", role: .destructive) {
tournament.buildBracket(minimalBracketTeamCount: 4)
}
} footer: {
Text("Vous pourrez ensuite modifier le nombre de tour dans l'écran de réglages du tableau.")
}
}
if tournament.state() != .initial { if tournament.state() != .initial {
Section { Section {

@ -15,7 +15,7 @@ struct TournamentCellView: View {
let tournament: FederalTournamentHolder let tournament: FederalTournamentHolder
// let color: Color = .black // let color: Color = .black
var displayStyle: DisplayStyle = .wide var displayStyle: DisplayStyle = .wide
var shouldTournamentBeOver: Bool = false @State var shouldTournamentBeOver: Bool = false
var event: Event? { var event: Event? {
guard let federalTournament = tournament as? FederalTournament else { return nil } guard let federalTournament = tournament as? FederalTournament else { return nil }
@ -114,7 +114,9 @@ struct TournamentCellView: View {
} }
Spacer() Spacer()
if let tournament = tournament as? Tournament, displayStyle == .wide { if let tournament = tournament as? Tournament, displayStyle == .wide {
if tournament.isCanceled { if tournament.refreshInProgress || tournament.refreshRanking {
ProgressView()
} else if tournament.isCanceled {
Text("Annulé".uppercased()) Text("Annulé".uppercased())
.capsule(foreground: .white, background: .logoRed) .capsule(foreground: .white, background: .logoRed)
} else if shouldTournamentBeOver { } else if shouldTournamentBeOver {
@ -157,6 +159,9 @@ struct TournamentCellView: View {
let hasStarted = tournament.inscriptionClosed() || tournament.hasStarted() let hasStarted = tournament.inscriptionClosed() || tournament.hasStarted()
let word = hasStarted ? "équipe" : "inscription" let word = hasStarted ? "équipe" : "inscription"
Text(word + teamCount.pluralSuffix) Text(word + teamCount.pluralSuffix)
.task(priority: .background) {
self.shouldTournamentBeOver = await tournament.shouldTournamentBeOver()
}
} }
} }
} }
@ -164,6 +169,17 @@ struct TournamentCellView: View {
Text(build.category.localizedLabel()) Text(build.category.localizedLabel())
Text(build.age.localizedFederalAgeLabel()) Text(build.age.localizedFederalAgeLabel())
} }
if displayStyle == .wide, let tournament = tournament as? Tournament {
if tournament.enableOnlineRegistration {
let value: Int = tournament.onlineTeams().count
HStack {
Spacer()
if value > 0 {
Text("(dont " + value.formatted() + " inscrite\(value.pluralSuffix) en ligne)")
}
}
}
}
} }
} }
.font(.caption) .font(.caption)

@ -54,7 +54,7 @@ struct TournamentBuildView: View {
} }
} }
} }
.task { .task(priority: .background) {
groupStageStatus = await tournament.groupStageStatus() groupStageStatus = await tournament.groupStageStatus()
} }
} }
@ -105,7 +105,7 @@ struct TournamentBuildView: View {
} }
} }
} }
.task { .task(priority: .background) {
bracketStatus = await tournament.bracketStatus() bracketStatus = await tournament.bracketStatus()
} }
} }
@ -157,7 +157,7 @@ struct TournamentBuildView: View {
} }
} }
} }
.task { .task(priority: .background) {
scheduleStatus = await tournament.scheduleStatus() scheduleStatus = await tournament.scheduleStatus()
} }
@ -178,7 +178,7 @@ struct TournamentBuildView: View {
} }
} }
} }
.task { .task(priority: .background) {
callStatus = await tournament.callStatus() callStatus = await tournament.callStatus()
} }
@ -199,7 +199,7 @@ struct TournamentBuildView: View {
} }
} }
} }
.task { .task(priority: .background) {
cashierStatus = await tournament.cashierStatus() cashierStatus = await tournament.cashierStatus()
} }
} }

@ -15,7 +15,8 @@ struct TournamentView: View {
@Environment(NavigationViewModel.self) var navigation: NavigationViewModel @Environment(NavigationViewModel.self) var navigation: NavigationViewModel
@State var tournament: Tournament @State var tournament: Tournament
@State private var showMoreInfos: Bool = false @State private var showMoreInfos: Bool = false
@State var shouldTournamentBeOver: Bool = false
var presentationContext: PresentationContext = .agenda var presentationContext: PresentationContext = .agenda
let tournamentSelectionTip: TournamentSelectionTip = TournamentSelectionTip() let tournamentSelectionTip: TournamentSelectionTip = TournamentSelectionTip()
@ -106,7 +107,7 @@ struct TournamentView: View {
TournamentBuildView(tournament: tournament) TournamentBuildView(tournament: tournament)
TournamentInitView(tournament: tournament) TournamentInitView(tournament: tournament)
case .running: case .running:
if tournament.shouldTournamentBeOver() { if shouldTournamentBeOver {
Section { Section {
TipView(shouldTournamentBeOverTip) { actions in TipView(shouldTournamentBeOverTip) { actions in
navigation.path.append(Screen.stateSettings) navigation.path.append(Screen.stateSettings)
@ -125,6 +126,9 @@ struct TournamentView: View {
RegistrationInfoSheetView() RegistrationInfoSheetView()
} }
} }
.task(priority: .background) {
self.shouldTournamentBeOver = await tournament.shouldTournamentBeOver()
}
.environment(tournament) .environment(tournament)
.id(tournament.id) .id(tournament.id)
.toolbarBackground(.visible, for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar)

Loading…
Cancel
Save