Fixes some long compilation warnings

multistore
Laurent 1 year ago
parent 08c466e45f
commit 09bdae21fd
  1. 2
      PadelClub/Data/Club.swift
  2. 4
      PadelClub/Data/Event.swift
  3. 2
      PadelClub/Data/GroupStage.swift
  4. 72
      PadelClub/Data/Match.swift
  5. 23
      PadelClub/Data/MatchScheduler.swift
  6. 8
      PadelClub/Data/MockData.swift
  7. 51
      PadelClub/Data/Round.swift
  8. 59
      PadelClub/Data/TeamRegistration.swift
  9. 4
      PadelClub/Data/TeamScore.swift
  10. 117
      PadelClub/Data/Tournament.swift
  11. 4
      PadelClub/Extensions/FixedWidthInteger+Extensions.swift
  12. 5
      PadelClub/ViewModel/SearchViewModel.swift
  13. 12
      PadelClub/Views/Navigation/Agenda/ActivityView.swift
  14. 10
      PadelClub/Views/Navigation/MainView.swift
  15. 3
      PadelClub/Views/Planning/LoserRoundScheduleEditorView.swift
  16. 3
      PadelClub/Views/Planning/MatchScheduleEditorView.swift
  17. 9
      PadelClub/Views/Planning/PlanningView.swift
  18. 4
      PadelClub/Views/Round/LoserRoundsView.swift
  19. 2
      PadelClub/Views/Score/EditScoreView.swift
  20. 2
      PadelClub/Views/Shared/SelectablePlayerListView.swift
  21. 4
      PadelClub/Views/Tournament/Screen/InscriptionManagerView.swift
  22. 3
      PadelClub/Views/Tournament/Screen/TournamentCashierView.swift
  23. 8
      PadelClub/Views/Tournament/Screen/TournamentScheduleView.swift

@ -71,7 +71,7 @@ class Club : ModelObject, Storable, Hashable {
} }
override func deleteDependencies() throws { override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.customizedCourts) DataStore.shared.courts.deleteDependencies(self.customizedCourts)
} }
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {

@ -30,8 +30,8 @@ class Event: ModelObject, Storable {
} }
override func deleteDependencies() throws { override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.tournaments) DataStore.shared.tournaments.deleteDependencies(self.tournaments)
try Store.main.deleteDependencies(items: self.courtsUnavailability) DataStore.shared.dateIntervals.deleteDependencies(self.courtsUnavailability)
} }
// MARK: - Computed dependencies // MARK: - Computed dependencies

@ -359,7 +359,7 @@ class GroupStage: ModelObject, Storable {
} }
override func deleteDependencies() throws { override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self._matches()) DataStore.shared.matches.deleteDependencies(self._matches())
} }
func encode(to encoder: Encoder) throws { func encode(to encoder: Encoder) throws {

@ -60,13 +60,13 @@ class Match: ModelObject, Storable {
// MARK: - Computed dependencies // MARK: - Computed dependencies
var teamScores: [TeamScore] { var teamScores: [TeamScore] {
Store.main.filter { $0.match == self.id } return Store.main.filter { $0.match == self.id }
} }
// MARK: - // MARK: -
override func deleteDependencies() throws { override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.teamScores) DataStore.shared.teamScores.deleteDependencies(self.teamScores)
} }
func indexInRound(in matches: [Match]? = nil) -> Int { func indexInRound(in matches: [Match]? = nil) -> Int {
@ -100,7 +100,7 @@ class Match: ModelObject, Storable {
} }
func isSeedLocked(atTeamPosition teamPosition: TeamPosition) -> Bool { func isSeedLocked(atTeamPosition teamPosition: TeamPosition) -> Bool {
previousMatch(teamPosition)?.disabled == true return previousMatch(teamPosition)?.disabled == true
} }
func unlockSeedPosition(atTeamPosition teamPosition: TeamPosition) { func unlockSeedPosition(atTeamPosition teamPosition: TeamPosition) {
@ -219,11 +219,11 @@ class Match: ModelObject, Storable {
} }
func luckyLosers() -> [TeamRegistration] { func luckyLosers() -> [TeamRegistration] {
roundObject?.previousRound()?.losers() ?? [] return roundObject?.previousRound()?.losers() ?? []
} }
func isWalkOutSpot(_ teamPosition: TeamPosition) -> Bool { func isWalkOutSpot(_ teamPosition: TeamPosition) -> Bool {
teamScore(teamPosition)?.walkOut == 1 return teamScore(teamPosition)?.walkOut == 1
} }
func setLuckyLoser(team: TeamRegistration, teamPosition: TeamPosition) { func setLuckyLoser(team: TeamRegistration, teamPosition: TeamPosition) {
@ -350,7 +350,7 @@ class Match: ModelObject, Storable {
} }
func next() -> Match? { func next() -> Match? {
Store.main.filter(isIncluded: { $0.round == round && $0.index > index }).sorted(by: \.index).first return Store.main.filter(isIncluded: { $0.round == round && $0.index > index }).sorted(by: \.index).first
} }
func followingMatch() -> Match? { func followingMatch() -> Match? {
@ -377,25 +377,27 @@ class Match: ModelObject, Storable {
} }
func topPreviousRoundMatchIndex() -> Int { func topPreviousRoundMatchIndex() -> Int {
index * 2 + 1 return index * 2 + 1
} }
func bottomPreviousRoundMatchIndex() -> Int { func bottomPreviousRoundMatchIndex() -> Int {
(index + 1) * 2 return (index + 1) * 2
} }
func topPreviousRoundMatch() -> Match? { func topPreviousRoundMatch() -> Match? {
guard let roundObject else { return nil } guard let roundObject else { return nil }
return Store.main.filter { match in let matches: [Match] = Store.main.filter { match in
match.index == topPreviousRoundMatchIndex() && match.round != nil && match.round == roundObject.previousRound()?.id match.index == topPreviousRoundMatchIndex() && match.round != nil && match.round == roundObject.previousRound()?.id
}.sorted(by: \.index).first }
return matches.sorted(by: \.index).first
} }
func bottomPreviousRoundMatch() -> Match? { func bottomPreviousRoundMatch() -> Match? {
guard let roundObject else { return nil } guard let roundObject else { return nil }
return Store.main.filter { match in let matches: [Match] = Store.main.filter { match in
match.index == bottomPreviousRoundMatchIndex() && match.round != nil && match.round == roundObject.previousRound()?.id match.index == bottomPreviousRoundMatchIndex() && match.round != nil && match.round == roundObject.previousRound()?.id
}.sorted(by: \.index).first }
return matches.sorted(by: \.index).first
} }
func upperBracketMatch(_ teamPosition: TeamPosition) -> Match? { func upperBracketMatch(_ teamPosition: TeamPosition) -> Match? {
@ -568,17 +570,16 @@ class Match: ModelObject, Storable {
} }
func courtCount() -> Int { func courtCount() -> Int {
currentTournament()?.courtCount ?? 1 return currentTournament()?.courtCount ?? 1
} }
func courtIsAvailable(_ courtIndex: Int) -> Bool { func courtIsAvailable(_ courtIndex: Int) -> Bool {
let courtUsed = currentTournament()?.courtUsed() ?? [] let courtUsed = currentTournament()?.courtUsed() ?? []
return courtUsed.contains(courtIndex) == false return courtUsed.contains(courtIndex) == false
// return Set(availableCourts().map { String($0) }).subtracting(Set(courtUsed))
} }
func courtIsPreferred(_ courtIndex: Int) -> Bool { func courtIsPreferred(_ courtIndex: Int) -> Bool {
false return false
} }
func availableCourts() -> [Int] { func availableCourts() -> [Int] {
@ -604,62 +605,62 @@ class Match: ModelObject, Storable {
} }
func isTeamPlaying(_ team: TeamRegistration, inMatches matches: [Match]) -> Bool { func isTeamPlaying(_ team: TeamRegistration, inMatches matches: [Match]) -> Bool {
matches.filter({ $0.teamScores.compactMap { $0.teamRegistration }.contains(team.id) }).isEmpty == false return matches.filter({ $0.teamScores.compactMap { $0.teamRegistration }.contains(team.id) }).isEmpty == false
} }
var computedStartDateForSorting: Date { var computedStartDateForSorting: Date {
startDate ?? .distantFuture return startDate ?? .distantFuture
} }
var computedEndDateForSorting: Date { var computedEndDateForSorting: Date {
endDate ?? .distantFuture return endDate ?? .distantFuture
} }
func hasSpaceLeft() -> Bool { func hasSpaceLeft() -> Bool {
teamScores.count < 2 return teamScores.count < 2
} }
func isReady() -> Bool { func isReady() -> Bool {
teamScores.count >= 2 return teamScores.count >= 2
// teams().count == 2 // teams().count == 2
} }
func isEmpty() -> Bool { func isEmpty() -> Bool {
teamScores.isEmpty return teamScores.isEmpty
// teams().isEmpty // teams().isEmpty
} }
func hasEnded() -> Bool { func hasEnded() -> Bool {
endDate != nil return endDate != nil
} }
func isGroupStage() -> Bool { func isGroupStage() -> Bool {
groupStage != nil return groupStage != nil
} }
func isBracket() -> Bool { func isBracket() -> Bool {
round != nil return round != nil
} }
func walkoutTeam() -> [TeamRegistration] { func walkoutTeam() -> [TeamRegistration] {
//walkout 0 means real walkout, walkout 1 means lucky loser situation //walkout 0 means real walkout, walkout 1 means lucky loser situation
scores().filter({ $0.walkOut == 0 }).compactMap { $0.team } return scores().filter({ $0.walkOut == 0 }).compactMap { $0.team }
} }
func hasWalkoutTeam() -> Bool { func hasWalkoutTeam() -> Bool {
walkoutTeam().isEmpty == false return walkoutTeam().isEmpty == false
} }
func currentTournament() -> Tournament? { func currentTournament() -> Tournament? {
groupStageObject?.tournamentObject() ?? roundObject?.tournamentObject() return groupStageObject?.tournamentObject() ?? roundObject?.tournamentObject()
} }
func tournamentId() -> String? { func tournamentId() -> String? {
groupStageObject?.tournament ?? roundObject?.tournament return groupStageObject?.tournament ?? roundObject?.tournament
} }
func scores() -> [TeamScore] { func scores() -> [TeamScore] {
Store.main.filter(isIncluded: { $0.match == id }) return Store.main.filter(isIncluded: { $0.match == id })
} }
func teams() -> [TeamRegistration] { func teams() -> [TeamRegistration] {
@ -734,23 +735,23 @@ class Match: ModelObject, Storable {
} }
func teamNames(_ team: TeamRegistration?) -> [String]? { func teamNames(_ team: TeamRegistration?) -> [String]? {
team?.players().map { $0.playerLabel() } return team?.players().map { $0.playerLabel() }
} }
func teamWalkOut(_ team: TeamRegistration?) -> Bool { func teamWalkOut(_ team: TeamRegistration?) -> Bool {
teamScore(ofTeam: team)?.isWalkOut() == true return teamScore(ofTeam: team)?.isWalkOut() == true
} }
func teamScore(_ team: TeamPosition) -> TeamScore? { func teamScore(_ team: TeamPosition) -> TeamScore? {
teamScore(ofTeam: self.team(team)) return teamScore(ofTeam: self.team(team))
} }
func teamScore(ofTeam team: TeamRegistration?) -> TeamScore? { func teamScore(ofTeam team: TeamRegistration?) -> TeamScore? {
scores().first(where: { $0.teamRegistration == team?.id }) return scores().first(where: { $0.teamRegistration == team?.id })
} }
func isRunning() -> Bool { // at least a match has started func isRunning() -> Bool { // at least a match has started
confirmed && hasStarted() && hasEnded() == false return confirmed && hasStarted() && hasEnded() == false
} }
func hasStarted() -> Bool { // meaning at least one match is over func hasStarted() -> Bool { // meaning at least one match is over
@ -781,7 +782,7 @@ class Match: ModelObject, Storable {
} }
var isLoserBracket: Bool { var isLoserBracket: Bool {
roundObject?.parent != nil return roundObject?.parent != nil
} }
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {
@ -893,7 +894,6 @@ enum MatchDateSetup: Hashable, Identifiable {
var id: Int { hashValue } var id: Int { hashValue }
} }
enum MatchFieldSetup: Hashable, Identifiable { enum MatchFieldSetup: Hashable, Identifiable {
case random case random
// case firstAvailable // case firstAvailable

@ -73,20 +73,20 @@ class MatchScheduler : ModelObject, Storable {
} }
var additionalEstimationDuration : Int { var additionalEstimationDuration : Int {
tournamentObject()?.additionalEstimationDuration ?? 0 return tournamentObject()?.additionalEstimationDuration ?? 0
} }
func tournamentObject() -> Tournament? { func tournamentObject() -> Tournament? {
Store.main.findById(tournament) return Store.main.findById(tournament)
} }
@discardableResult @discardableResult
func updateGroupStageSchedule(tournament: Tournament) -> Date { func updateGroupStageSchedule(tournament: Tournament) -> Date {
let computedGroupStageChunkCount = groupStageChunkCount ?? 1 let computedGroupStageChunkCount = groupStageChunkCount ?? 1
let groupStages = tournament.groupStages() let groupStages: [GroupStage] = tournament.groupStages()
let numberOfCourtsAvailablePerRotation: Int = tournament.courtCount let numberOfCourtsAvailablePerRotation: Int = tournament.courtCount
let matches = groupStages.flatMap({ $0._matches() }) let matches = groupStages.flatMap { $0._matches() }
matches.forEach({ matches.forEach({
$0.removeCourt() $0.removeCourt()
$0.startDate = nil $0.startDate = nil
@ -232,8 +232,8 @@ class MatchScheduler : ModelObject, Storable {
var organizedSlots = [GroupStageTimeMatch]() var organizedSlots = [GroupStageTimeMatch]()
for i in 0..<rotationIndex { for i in 0..<rotationIndex {
let courtsSorted = slots.filter({ $0.rotationIndex == i }).map { $0.courtIndex }.sorted() let courtsSorted: [Int] = slots.filter({ $0.rotationIndex == i }).map { $0.courtIndex }.sorted()
let courts = randomizeCourts ? courtsSorted.shuffled() : courtsSorted let courts: [Int] = randomizeCourts ? courtsSorted.shuffled() : courtsSorted
var matches = slots.filter({ $0.rotationIndex == i }).sorted(using: .keyPath(\.groupIndex), .keyPath(\.courtIndex)) var matches = slots.filter({ $0.rotationIndex == i }).sorted(using: .keyPath(\.groupIndex), .keyPath(\.courtIndex))
for j in 0..<matches.count { for j in 0..<matches.count {
@ -541,8 +541,8 @@ class MatchScheduler : ModelObject, Storable {
func updateBracketSchedule(tournament: Tournament, fromRoundId roundId: String?, fromMatchId matchId: String?, startDate: Date) { func updateBracketSchedule(tournament: Tournament, fromRoundId roundId: String?, fromMatchId matchId: String?, startDate: Date) {
let upperRounds = tournament.rounds() let upperRounds: [Round] = tournament.rounds()
let allMatches = tournament.allMatches() let allMatches: [Match] = tournament.allMatches()
var rounds = [Round]() var rounds = [Round]()
@ -607,8 +607,9 @@ class MatchScheduler : ModelObject, Storable {
} }
let usedCourts = getAvailableCourts(from: allMatches.filter({ $0.startDate?.isEarlierThan(startDate) == true && $0.startDate?.dayInt == startDate.dayInt })) let matches: [Match] = allMatches.filter { $0.startDate?.isEarlierThan(startDate) == true && $0.startDate?.dayInt == startDate.dayInt }
let initialCourts = usedCourts.filter { (court, availableDate) in let usedCourts = getAvailableCourts(from: matches)
let initialCourts: [Int] = usedCourts.filter { (court, availableDate) in
availableDate <= startDate availableDate <= startDate
}.sorted(by: \.1).compactMap { $0.0 } }.sorted(by: \.1).compactMap { $0.0 }
@ -696,6 +697,6 @@ extension Match {
} }
func containsTeamId(_ id: String) -> Bool { func containsTeamId(_ id: String) -> Bool {
teamIds().contains(id) return teamIds().contains(id)
} }
} }

@ -43,24 +43,24 @@ extension Round {
extension Tournament { extension Tournament {
static func mock() -> Tournament { static func mock() -> Tournament {
Tournament(groupStageSortMode: .snake, teamSorting: .inscriptionDate, federalCategory: .men, federalLevelCategory: .p100, federalAgeCategory: .senior) return Tournament(groupStageSortMode: .snake, teamSorting: .inscriptionDate, federalCategory: .men, federalLevelCategory: .p100, federalAgeCategory: .senior)
} }
} }
extension Match { extension Match {
static func mock() -> Match { static func mock() -> Match {
Match(index: 0) return Match(index: 0)
} }
} }
extension TeamRegistration { extension TeamRegistration {
static func mock() -> TeamRegistration { static func mock() -> TeamRegistration {
TeamRegistration(tournament: "") return TeamRegistration(tournament: "")
} }
} }
extension PlayerRegistration { extension PlayerRegistration {
static func mock() -> PlayerRegistration { static func mock() -> PlayerRegistration {
PlayerRegistration(firstName: "Raz", lastName: "Shark", sex: .male) return PlayerRegistration(firstName: "Raz", lastName: "Shark", sex: .male)
} }
} }

@ -32,15 +32,15 @@ class Round: ModelObject, Storable {
// MARK: - Computed dependencies // MARK: - Computed dependencies
func tournamentObject() -> Tournament? { func tournamentObject() -> Tournament? {
Store.main.findById(tournament) return Store.main.findById(tournament)
} }
func _matches() -> [Match] { func _matches() -> [Match] {
Store.main.filter { $0.round == self.id } return Store.main.filter { $0.round == self.id }
} }
func getDisabledMatches() -> [Match] { func getDisabledMatches() -> [Match] {
Store.main.filter { $0.round == self.id && $0.disabled == true } return Store.main.filter { $0.round == self.id && $0.disabled == true }
} }
// MARK: - // MARK: -
@ -56,11 +56,11 @@ class Round: ModelObject, Storable {
func hasStarted() -> Bool { func hasStarted() -> Bool {
playedMatches().anySatisfy({ $0.hasStarted() }) return playedMatches().anySatisfy({ $0.hasStarted() })
} }
func hasEnded() -> Bool { func hasEnded() -> Bool {
playedMatches().anySatisfy({ $0.hasEnded() == false }) == false return playedMatches().anySatisfy({ $0.hasEnded() == false }) == false
} }
func upperMatches(ofMatch match: Match) -> [Match] { func upperMatches(ofMatch match: Match) -> [Match] {
@ -130,11 +130,11 @@ class Round: ModelObject, Storable {
} }
func losers() -> [TeamRegistration] { func losers() -> [TeamRegistration] {
_matches().compactMap { $0.losingTeamId }.compactMap { Store.main.findById($0) } return _matches().compactMap { $0.losingTeamId }.compactMap { Store.main.findById($0) }
} }
func teams() -> [TeamRegistration] { func teams() -> [TeamRegistration] {
playedMatches().flatMap({ $0.teams() }) return playedMatches().flatMap({ $0.teams() })
} }
func roundProjectedTeam(_ team: TeamPosition, inMatch match: Match) -> TeamRegistration? { func roundProjectedTeam(_ team: TeamPosition, inMatch match: Match) -> TeamRegistration? {
@ -190,18 +190,19 @@ class Round: ModelObject, Storable {
func topPreviousRoundMatch(ofMatch match: Match) -> Match? { func topPreviousRoundMatch(ofMatch match: Match) -> Match? {
guard let previousRound = previousRound() else { return nil } guard let previousRound = previousRound() else { return nil }
return Store.main.filter { let matches: [Match] = Store.main.filter {
$0.index == match.topPreviousRoundMatchIndex() && $0.round == previousRound.id $0.index == match.topPreviousRoundMatchIndex() && $0.round == previousRound.id
}.sorted(by: \.index).first }
return matches.sorted(by: \.index).first
} }
func bottomPreviousRoundMatch(ofMatch match: Match) -> Match? { func bottomPreviousRoundMatch(ofMatch match: Match) -> Match? {
guard let previousRound = previousRound() else { return nil } guard let previousRound = previousRound() else { return nil }
return Store.main.filter { let matches: [Match] = Store.main.filter {
$0.index == match.bottomPreviousRoundMatchIndex() && $0.round == previousRound.id $0.index == match.bottomPreviousRoundMatchIndex() && $0.round == previousRound.id
}.sorted(by: \.index).first
} }
return matches.sorted(by: \.index).first
}
func getMatch(atMatchIndexInRound matchIndexInRound: Int) -> Match? { func getMatch(atMatchIndexInRound matchIndexInRound: Int) -> Match? {
Store.main.filter(isIncluded: { Store.main.filter(isIncluded: {
@ -211,7 +212,7 @@ class Round: ModelObject, Storable {
} }
func enabledMatches() -> [Match] { func enabledMatches() -> [Match] {
Store.main.filter { $0.round == self.id && $0.disabled == false } return Store.main.filter { $0.round == self.id && $0.disabled == false }
} }
func displayableMatches() -> [Match] { func displayableMatches() -> [Match] {
@ -233,11 +234,11 @@ class Round: ModelObject, Storable {
} }
func previousRound() -> Round? { func previousRound() -> Round? {
Store.main.filter(isIncluded: { $0.tournament == tournament && $0.parent == parent && $0.index == index + 1 }).first return Store.main.filter(isIncluded: { $0.tournament == tournament && $0.parent == parent && $0.index == index + 1 }).first
} }
func nextRound() -> Round? { func nextRound() -> Round? {
Store.main.filter(isIncluded: { $0.tournament == tournament && $0.parent == parent && $0.index == index - 1 }).first return Store.main.filter(isIncluded: { $0.tournament == tournament && $0.parent == parent && $0.index == index - 1 }).first
} }
func loserRounds(forRoundIndex roundIndex: Int) -> [Round] { func loserRounds(forRoundIndex roundIndex: Int) -> [Round] {
@ -245,11 +246,11 @@ class Round: ModelObject, Storable {
} }
func isDisabled() -> Bool { func isDisabled() -> Bool {
_matches().allSatisfy({ $0.disabled }) return _matches().allSatisfy({ $0.disabled })
} }
func isRankDisabled() -> Bool { func isRankDisabled() -> Bool {
_matches().allSatisfy({ $0.disabled && $0.teamScores.isEmpty }) return _matches().allSatisfy({ $0.disabled && $0.teamScores.isEmpty })
} }
func resetFromRoundAllMatchesStartDate() { func resetFromRoundAllMatchesStartDate() {
@ -324,11 +325,11 @@ class Round: ModelObject, Storable {
} }
func estimatedEndDate(_ additionalEstimationDuration: Int) -> Date? { func estimatedEndDate(_ additionalEstimationDuration: Int) -> Date? {
enabledMatches().last?.estimatedEndDate(additionalEstimationDuration) return enabledMatches().last?.estimatedEndDate(additionalEstimationDuration)
} }
func getLoserRoundStartDate() -> Date? { func getLoserRoundStartDate() -> Date? {
loserRoundsAndChildren().first(where: { $0.isDisabled() == false })?.enabledMatches().first?.startDate return loserRoundsAndChildren().first(where: { $0.isDisabled() == false })?.enabledMatches().first?.startDate
} }
func estimatedLoserRoundEndDate(_ additionalEstimationDuration: Int) -> Date? { func estimatedLoserRoundEndDate(_ additionalEstimationDuration: Int) -> Date? {
@ -337,7 +338,7 @@ class Round: ModelObject, Storable {
} }
func disabledMatches() -> [Match] { func disabledMatches() -> [Match] {
_matches().filter({ $0.disabled }) return _matches().filter({ $0.disabled })
} }
var theoryCumulativeMatchCount: Int { var theoryCumulativeMatchCount: Int {
@ -362,7 +363,7 @@ class Round: ModelObject, Storable {
} }
func hasNextRound() -> Bool { func hasNextRound() -> Bool {
nextRound()?.isDisabled() == false return nextRound()?.isDisabled() == false
} }
func seedInterval() -> SeedInterval? { func seedInterval() -> SeedInterval? {
@ -427,11 +428,11 @@ class Round: ModelObject, Storable {
} }
func isUpperBracket() -> Bool { func isUpperBracket() -> Bool {
parent == nil return parent == nil
} }
func isLoserBracket() -> Bool { func isLoserBracket() -> Bool {
parent != nil return parent != nil
} }
func buildLoserBracket() { func buildLoserBracket() {
@ -505,8 +506,8 @@ class Round: ModelObject, Storable {
} }
override func deleteDependencies() throws { override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: _matches()) DataStore.shared.matches.deleteDependencies(self._matches())
try Store.main.deleteDependencies(items: loserRoundsAndChildren()) DataStore.shared.rounds.deleteDependencies(self.loserRoundsAndChildren())
} }
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {

@ -66,7 +66,7 @@ class TeamRegistration: ModelObject, Storable {
// MARK: - // MARK: -
override func deleteDependencies() throws { override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.unsortedPlayers()) DataStore.shared.playerRegistrations.deleteDependencies(self.unsortedPlayers())
} }
func hasArrived() { func hasArrived() {
@ -84,9 +84,9 @@ class TeamRegistration: ModelObject, Storable {
} }
func setSeedPosition(inSpot match: Match, slot: TeamPosition?, opposingSeeding: Bool) { func setSeedPosition(inSpot match: Match, slot: TeamPosition?, opposingSeeding: Bool) {
let seedPosition = match.lockAndGetSeedPosition(atTeamPosition: slot, opposingSeeding: opposingSeeding) let seedPosition: Int = match.lockAndGetSeedPosition(atTeamPosition: slot, opposingSeeding: opposingSeeding)
tournamentObject()?.resetTeamScores(in: bracketPosition) tournamentObject()?.resetTeamScores(in: bracketPosition)
bracketPosition = seedPosition self.bracketPosition = seedPosition
tournamentObject()?.updateTeamScores(in: bracketPosition) tournamentObject()?.updateTeamScores(in: bracketPosition)
} }
@ -100,15 +100,15 @@ class TeamRegistration: ModelObject, Storable {
} }
var initialWeight: Int { var initialWeight: Int {
lockedWeight ?? weight return lockedWeight ?? weight
} }
func called() -> Bool { func called() -> Bool {
callDate != nil return callDate != nil
} }
func confirmed() -> Bool { func confirmed() -> Bool {
confirmationDate != nil return confirmationDate != nil
} }
func getPhoneNumbers() -> [String] { func getPhoneNumbers() -> [String] {
@ -121,35 +121,35 @@ class TeamRegistration: ModelObject, Storable {
} }
func isImported() -> Bool { func isImported() -> Bool {
unsortedPlayers().allSatisfy({ $0.isImported() }) return unsortedPlayers().allSatisfy({ $0.isImported() })
} }
func isWildCard() -> Bool { func isWildCard() -> Bool {
wildCardBracket || wildCardGroupStage return wildCardBracket || wildCardGroupStage
} }
func isPlaying() -> Bool { func isPlaying() -> Bool {
currentMatch() != nil return currentMatch() != nil
} }
func currentMatch() -> Match? { func currentMatch() -> Match? {
teamScores().compactMap { $0.matchObject() }.first(where: { $0.isRunning() }) return teamScores().compactMap { $0.matchObject() }.first(where: { $0.isRunning() })
} }
func teamScores() -> [TeamScore] { func teamScores() -> [TeamScore] {
Store.main.filter(isIncluded: { $0.teamRegistration == id }) return Store.main.filter(isIncluded: { $0.teamRegistration == id })
} }
func wins() -> [Match] { func wins() -> [Match] {
Store.main.filter(isIncluded: { $0.winningTeamId == id }) return Store.main.filter(isIncluded: { $0.winningTeamId == id })
} }
func loses() -> [Match] { func loses() -> [Match] {
Store.main.filter(isIncluded: { $0.losingTeamId == id }) return Store.main.filter(isIncluded: { $0.losingTeamId == id })
} }
func matches() -> [Match] { func matches() -> [Match] {
Store.main.filter(isIncluded: { $0.losingTeamId == id || $0.winningTeamId == id }) return Store.main.filter(isIncluded: { $0.losingTeamId == id || $0.winningTeamId == id })
} }
var tournamentCategory: TournamentCategory { var tournamentCategory: TournamentCategory {
@ -169,15 +169,15 @@ class TeamRegistration: ModelObject, Storable {
} }
func updateWeight(inTournamentCategory tournamentCategory: TournamentCategory) { func updateWeight(inTournamentCategory tournamentCategory: TournamentCategory) {
setWeight(from: self.players(), inTournamentCategory: tournamentCategory) self.setWeight(from: self.players(), inTournamentCategory: tournamentCategory)
} }
func teamLabel(_ displayStyle: DisplayStyle = .wide, twoLines: Bool = false) -> String { func teamLabel(_ displayStyle: DisplayStyle = .wide, twoLines: Bool = false) -> String {
players().map { $0.playerLabel(displayStyle) }.joined(separator: twoLines ? "\n" : " & ") return players().map { $0.playerLabel(displayStyle) }.joined(separator: twoLines ? "\n" : " & ")
} }
func index(in teams: [TeamRegistration]) -> Int? { func index(in teams: [TeamRegistration]) -> Int? {
teams.firstIndex(where: { $0.id == id }) return teams.firstIndex(where: { $0.id == id })
} }
func formattedSeed(in teams: [TeamRegistration]) -> String { func formattedSeed(in teams: [TeamRegistration]) -> String {
@ -189,7 +189,7 @@ class TeamRegistration: ModelObject, Storable {
} }
func contains(_ searchField: String) -> Bool { func contains(_ searchField: String) -> Bool {
unsortedPlayers().anySatisfy({ $0.contains(searchField) }) || self.name?.localizedCaseInsensitiveContains(searchField) == true return unsortedPlayers().anySatisfy({ $0.contains(searchField) }) || self.name?.localizedCaseInsensitiveContains(searchField) == true
} }
func containsExactlyPlayerLicenses(_ playerLicenses: [String?]) -> Bool { func containsExactlyPlayerLicenses(_ playerLicenses: [String?]) -> Bool {
@ -200,31 +200,31 @@ class TeamRegistration: ModelObject, Storable {
} }
func includes(_ players: [PlayerRegistration]) -> Bool { func includes(_ players: [PlayerRegistration]) -> Bool {
players.allSatisfy { player in return players.allSatisfy { player in
includes(player) includes(player)
} }
} }
func includes(_ player: PlayerRegistration) -> Bool { func includes(_ player: PlayerRegistration) -> Bool {
unsortedPlayers().anySatisfy { _player in return unsortedPlayers().anySatisfy { _player in
_player.isSameAs(player) _player.isSameAs(player)
} }
} }
func canPlay() -> Bool { func canPlay() -> Bool {
matches().isEmpty == false || players().allSatisfy({ $0.hasPaid() || $0.hasArrived }) return matches().isEmpty == false || players().allSatisfy({ $0.hasPaid() || $0.hasArrived })
} }
func availableForSeedPick() -> Bool { func availableForSeedPick() -> Bool {
groupStage == nil && bracketPosition == nil return groupStage == nil && bracketPosition == nil
} }
func inGroupStage() -> Bool { func inGroupStage() -> Bool {
groupStagePosition != nil return groupStagePosition != nil
} }
func inRound() -> Bool { func inRound() -> Bool {
bracketPosition != nil return bracketPosition != nil
} }
func resetGroupeStagePosition() { func resetGroupeStagePosition() {
@ -253,7 +253,7 @@ class TeamRegistration: ModelObject, Storable {
} }
var computedRegistrationDate: Date { var computedRegistrationDate: Date {
registrationDate ?? .distantFuture return registrationDate ?? .distantFuture
} }
func formattedInscriptionDate() -> String? { func formattedInscriptionDate() -> String? {
@ -265,10 +265,9 @@ class TeamRegistration: ModelObject, Storable {
} }
func playersPasteData() -> String { func playersPasteData() -> String {
players().map { $0.pasteData() }.joined(separator: "\n") return players().map { $0.pasteData() }.joined(separator: "\n")
} }
func updatePlayers(_ players: Set<PlayerRegistration>, inTournamentCategory tournamentCategory: TournamentCategory) { func updatePlayers(_ players: Set<PlayerRegistration>, inTournamentCategory tournamentCategory: TournamentCategory) {
let previousPlayers = Set(unsortedPlayers()) let previousPlayers = Set(unsortedPlayers())
let playersToRemove = previousPlayers.subtracting(players) let playersToRemove = previousPlayers.subtracting(players)
@ -349,7 +348,7 @@ class TeamRegistration: ModelObject, Storable {
} }
func significantPlayerCount() -> Int { func significantPlayerCount() -> Int {
tournamentObject()?.significantPlayerCount() ?? 2 return tournamentObject()?.significantPlayerCount() ?? 2
} }
func missingPlayerType(inTournamentCategory tournamentCategory: TournamentCategory) -> [Int] { func missingPlayerType(inTournamentCategory tournamentCategory: TournamentCategory) -> [Int] {
@ -366,7 +365,7 @@ class TeamRegistration: ModelObject, Storable {
} }
func unrankValue(for malePlayer: Bool) -> Int { func unrankValue(for malePlayer: Bool) -> Int {
tournamentObject()?.unrankValue(for: malePlayer) ?? 100_000 return tournamentObject()?.unrankValue(for: malePlayer) ?? 100_000
} }
func groupStageObject() -> GroupStage? { func groupStageObject() -> GroupStage? {
@ -388,7 +387,7 @@ class TeamRegistration: ModelObject, Storable {
func tournamentObject() -> Tournament? { func tournamentObject() -> Tournament? {
Store.main.findById(tournament) return Store.main.findById(tournament)
} }
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {

@ -45,7 +45,7 @@ class TeamScore: ModelObject, Storable {
// MARK: - Computed dependencies // MARK: - Computed dependencies
func matchObject() -> Match? { func matchObject() -> Match? {
Store.main.findById(self.match) return Store.main.findById(self.match)
} }
var team: TeamRegistration? { var team: TeamRegistration? {
@ -58,7 +58,7 @@ class TeamScore: ModelObject, Storable {
// MARK: - // MARK: -
func isWalkOut() -> Bool { func isWalkOut() -> Bool {
walkOut != nil return walkOut != nil
} }
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {

@ -330,24 +330,24 @@ class Tournament : ModelObject, Storable {
} }
override func deleteDependencies() throws { override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.unsortedTeams()) DataStore.shared.teamRegistrations.deleteDependencies(self.unsortedTeams())
try Store.main.deleteDependencies(items: self.groupStages()) DataStore.shared.groupStages.deleteDependencies(self.groupStages())
try Store.main.deleteDependencies(items: self.rounds()) DataStore.shared.rounds.deleteDependencies(self.rounds())
try Store.main.deleteDependencies(items: self._matchSchedulers()) DataStore.shared.matchSchedulers.deleteDependencies(self._matchSchedulers())
} }
// MARK: - Computed Dependencies // MARK: - Computed Dependencies
func unsortedTeams() -> [TeamRegistration] { func unsortedTeams() -> [TeamRegistration] {
Store.main.filter { $0.tournament == self.id } return Store.main.filter { $0.tournament == self.id }
} }
func groupStages() -> [GroupStage] { func groupStages() -> [GroupStage] {
Store.main.filter { $0.tournament == self.id }.sorted(by: \.index) return Store.main.filter { $0.tournament == self.id }.sorted(by: \.index)
} }
func allRounds() -> [Round] { func allRounds() -> [Round] {
Store.main.filter { $0.tournament == self.id } return Store.main.filter { $0.tournament == self.id }
} }
// MARK: - // MARK: -
@ -388,7 +388,7 @@ class Tournament : ModelObject, Storable {
} }
func publishedTeamsDate() -> Date { func publishedTeamsDate() -> Date {
startDate return self.startDate
} }
func canBePublished() -> Bool { func canBePublished() -> Bool {
@ -401,19 +401,22 @@ class Tournament : ModelObject, Storable {
} }
func isTournamentPublished() -> Bool { func isTournamentPublished() -> Bool {
(Date() >= publishedTournamentDate() && canBePublished()) || publishTournament return (Date() >= publishedTournamentDate() && canBePublished()) || publishTournament
} }
func areTeamsPublished() -> Bool { func areTeamsPublished() -> Bool {
Date() >= startDate || publishTeams return Date() >= startDate || publishTeams
} }
func areSummonsPublished() -> Bool { func areSummonsPublished() -> Bool {
Date() >= startDate || publishSummons return Date() >= startDate || publishSummons
} }
func publishedGroupStagesDate() -> Date? { fileprivate func _publishedDateFromMatches(_ matches: [Match]) -> Date? {
if let first = groupStages().flatMap({ $0.playedMatches() }).compactMap({ $0.startDate }).sorted().first?.atEightAM() { let startDates: [Date] = matches.compactMap { $0.startDate }
let sortedDates: [Date] = startDates.sorted()
if let first: Date = sortedDates.first?.atEightAM() {
if first.isEarlierThan(startDate) { if first.isEarlierThan(startDate) {
return startDate return startDate
} else { } else {
@ -424,6 +427,11 @@ class Tournament : ModelObject, Storable {
} }
} }
func publishedGroupStagesDate() -> Date? {
let matches: [Match] = self.groupStages().flatMap { $0.playedMatches() }
return self._publishedDateFromMatches(matches)
}
func areGroupStagesPublished() -> Bool { func areGroupStagesPublished() -> Bool {
if publishGroupStages { return true } if publishGroupStages { return true }
if let publishedGroupStagesDate = publishedGroupStagesDate() { if let publishedGroupStagesDate = publishedGroupStagesDate() {
@ -434,15 +442,8 @@ class Tournament : ModelObject, Storable {
} }
func publishedBracketsDate() -> Date? { func publishedBracketsDate() -> Date? {
if let first = rounds().flatMap({ $0.playedMatches() }).compactMap({ $0.startDate }).sorted().first?.atEightAM() { let matches: [Match] = self.rounds().flatMap { $0.playedMatches() }
if first.isEarlierThan(startDate) { return self._publishedDateFromMatches(matches)
return startDate
} else {
return first
}
} else {
return startDate
}
} }
func areBracketsPublished() -> Bool { func areBracketsPublished() -> Bool {
@ -471,7 +472,7 @@ class Tournament : ModelObject, Storable {
} }
func hasStarted() -> Bool { func hasStarted() -> Bool {
startDate <= Date() return startDate <= Date()
} }
func eventObject() -> Event? { func eventObject() -> Event? {
@ -485,7 +486,7 @@ class Tournament : ModelObject, Storable {
} }
func club() -> Club? { func club() -> Club? {
eventObject()?.clubObject() return eventObject()?.clubObject()
} }
func locationLabel(_ displayStyle: DisplayStyle = .wide) -> String { func locationLabel(_ displayStyle: DisplayStyle = .wide) -> String {
@ -502,7 +503,7 @@ class Tournament : ModelObject, Storable {
} }
func hasEnded() -> Bool { func hasEnded() -> Bool {
endDate != nil return endDate != nil
} }
func state() -> Tournament.State { func state() -> Tournament.State {
@ -524,11 +525,11 @@ class Tournament : ModelObject, Storable {
} }
func seededTeams() -> [TeamRegistration] { func seededTeams() -> [TeamRegistration] {
selectedSortedTeams().filter({ $0.bracketPosition != nil && $0.groupStagePosition == nil }) return selectedSortedTeams().filter({ $0.bracketPosition != nil && $0.groupStagePosition == nil })
} }
func groupStageTeams() -> [TeamRegistration] { func groupStageTeams() -> [TeamRegistration] {
selectedSortedTeams().filter({ $0.groupStagePosition != nil }) return selectedSortedTeams().filter({ $0.groupStagePosition != nil })
} }
func groupStageSpots() -> Int { func groupStageSpots() -> Int {
@ -559,15 +560,15 @@ class Tournament : ModelObject, Storable {
} }
func getRound(atRoundIndex roundIndex: Int) -> Round? { func getRound(atRoundIndex roundIndex: Int) -> Round? {
Store.main.filter(isIncluded: { $0.tournament == id && $0.index == roundIndex }).first return Store.main.filter(isIncluded: { $0.tournament == id && $0.index == roundIndex }).first
} }
func availableSeedSpot(inRoundIndex roundIndex: Int) -> [Match] { func availableSeedSpot(inRoundIndex roundIndex: Int) -> [Match] {
getRound(atRoundIndex: roundIndex)?.playedMatches().filter { $0.isEmpty() } ?? [] return getRound(atRoundIndex: roundIndex)?.playedMatches().filter { $0.isEmpty() } ?? []
} }
func availableSeedOpponentSpot(inRoundIndex roundIndex: Int) -> [Match] { func availableSeedOpponentSpot(inRoundIndex roundIndex: Int) -> [Match] {
getRound(atRoundIndex: roundIndex)?.playedMatches().filter { $0.hasSpaceLeft() } ?? [] return getRound(atRoundIndex: roundIndex)?.playedMatches().filter { $0.hasSpaceLeft() } ?? []
} }
func availableSeedGroups() -> [SeedInterval] { func availableSeedGroups() -> [SeedInterval] {
@ -1143,7 +1144,8 @@ class Tournament : ModelObject, Storable {
let lastRankWoman = SourceFileManager.shared.getUnrankValue(forMale: false, rankSourceDate: rankSourceDate) let lastRankWoman = SourceFileManager.shared.getUnrankValue(forMale: false, rankSourceDate: rankSourceDate)
let lastRankMan = SourceFileManager.shared.getUnrankValue(forMale: true, rankSourceDate: rankSourceDate) let lastRankMan = SourceFileManager.shared.getUnrankValue(forMale: true, rankSourceDate: rankSourceDate)
await MainActor.run { await MainActor.run {
let monthData = MonthData(monthKey: URL.importDateFormatter.string(from: newDate)) let formatted: String = URL.importDateFormatter.string(from: newDate)
let monthData: MonthData = MonthData(monthKey: formatted)
monthData.maleUnrankedValue = lastRankMan monthData.maleUnrankedValue = lastRankMan
monthData.femaleUnrankedValue = lastRankWoman monthData.femaleUnrankedValue = lastRankWoman
do { do {
@ -1156,7 +1158,7 @@ class Tournament : ModelObject, Storable {
let lastRankMan = currentMonthData()?.maleUnrankedValue let lastRankMan = currentMonthData()?.maleUnrankedValue
let lastRankWoman = currentMonthData()?.femaleUnrankedValue let lastRankWoman = currentMonthData()?.femaleUnrankedValue
let dataURLs = SourceFileManager.shared.allFiles.filter({ $0.dateFromPath == newDate }) let dataURLs = SourceFileManager.shared.allFiles.filter { $0.dateFromPath == newDate }
let sources = dataURLs.map { CSVParser(url: $0) } let sources = dataURLs.map { CSVParser(url: $0) }
try await unsortedPlayers().concurrentForEach { player in try await unsortedPlayers().concurrentForEach { player in
@ -1165,23 +1167,23 @@ class Tournament : ModelObject, Storable {
} }
func missingUnrankedValue() -> Bool { func missingUnrankedValue() -> Bool {
maleUnrankedValue == nil || femaleUnrankedValue == nil return maleUnrankedValue == nil || femaleUnrankedValue == nil
} }
func findTeam(_ players: [PlayerRegistration]) -> TeamRegistration? { func findTeam(_ players: [PlayerRegistration]) -> TeamRegistration? {
unsortedTeams().first(where: { $0.includes(players) }) return unsortedTeams().first(where: { $0.includes(players) })
} }
func tournamentTitle(_ displayStyle: DisplayStyle = .wide) -> String { func tournamentTitle(_ displayStyle: DisplayStyle = .wide) -> String {
[tournamentLevel.localizedLabel(displayStyle) + " " + tournamentCategory.localizedLabel(displayStyle), displayStyle == .wide ? name : nil].compactMap({ $0 }).joined(separator: " - ") return [tournamentLevel.localizedLabel(displayStyle) + " " + tournamentCategory.localizedLabel(displayStyle), displayStyle == .wide ? name : nil].compactMap({ $0 }).joined(separator: " - ")
} }
func hideWeight() -> Bool { func hideWeight() -> Bool {
tournamentLevel.hideWeight() return tournamentLevel.hideWeight()
} }
func subtitle(_ displayStyle: DisplayStyle = .wide) -> String { func subtitle(_ displayStyle: DisplayStyle = .wide) -> String {
name ?? "" return name ?? ""
} }
func formattedDate(_ displayStyle: DisplayStyle = .wide) -> String { func formattedDate(_ displayStyle: DisplayStyle = .wide) -> String {
@ -1194,20 +1196,20 @@ class Tournament : ModelObject, Storable {
} }
func qualifiedFromGroupStage() -> Int { func qualifiedFromGroupStage() -> Int {
groupStageCount * qualifiedPerGroupStage return groupStageCount * qualifiedPerGroupStage
} }
func availableQualifiedTeams() -> [TeamRegistration] { func availableQualifiedTeams() -> [TeamRegistration] {
unsortedTeams().filter({ $0.qualified && $0.bracketPosition == nil }) return unsortedTeams().filter({ $0.qualified && $0.bracketPosition == nil })
} }
func qualifiedTeams() -> [TeamRegistration] { func qualifiedTeams() -> [TeamRegistration] {
unsortedTeams().filter({ $0.qualifiedFromGroupStage() }) return unsortedTeams().filter({ $0.qualifiedFromGroupStage() })
} }
func moreQualifiedToDraw() -> Int { func moreQualifiedToDraw() -> Int {
max(qualifiedTeams().count - (qualifiedFromGroupStage() + groupStageAdditionalQualified), 0) return max(qualifiedTeams().count - (qualifiedFromGroupStage() + groupStageAdditionalQualified), 0)
} }
func missingQualifiedFromGroupStages() -> [TeamRegistration] { func missingQualifiedFromGroupStages() -> [TeamRegistration] {
@ -1231,7 +1233,7 @@ class Tournament : ModelObject, Storable {
} }
func paymentMethodMessage() -> String? { func paymentMethodMessage() -> String? {
DataStore.shared.user.summonsAvailablePaymentMethods ?? ContactType.defaultAvailablePaymentMethods return DataStore.shared.user.summonsAvailablePaymentMethods ?? ContactType.defaultAvailablePaymentMethods
} }
var entryFeeMessage: String { var entryFeeMessage: String {
@ -1264,7 +1266,8 @@ class Tournament : ModelObject, Storable {
func cashierStatus() async -> TournamentStatus { func cashierStatus() async -> TournamentStatus {
let selectedPlayers = selectedPlayers() let selectedPlayers = selectedPlayers()
let paid = selectedPlayers.filter({ $0.hasPaid() }) let paid = selectedPlayers.filter({ $0.hasPaid() })
let label = paid.count.formatted() + " / " + selectedPlayers.count.formatted() + " joueurs encaissés" // let label = paid.count.formatted() + " / " + selectedPlayers.count.formatted() + " joueurs encaissés"
let label = "\(paid.count.formatted()) / \(selectedPlayers.count.formatted()) joueurs encaissés"
let completion = (Double(paid.count) / Double(selectedPlayers.count)) let completion = (Double(paid.count) / Double(selectedPlayers.count))
let completionLabel = completion.isNaN ? "" : completion.formatted(.percent.precision(.fractionLength(0))) let completionLabel = completion.isNaN ? "" : completion.formatted(.percent.precision(.fractionLength(0)))
return TournamentStatus(label: label, completion: completionLabel) return TournamentStatus(label: label, completion: completionLabel)
@ -1273,7 +1276,8 @@ class Tournament : ModelObject, Storable {
func scheduleStatus() async -> TournamentStatus { func scheduleStatus() async -> TournamentStatus {
let allMatches = allMatches() let allMatches = allMatches()
let ready = allMatches.filter({ $0.startDate != nil }) let ready = allMatches.filter({ $0.startDate != nil })
let label = ready.count.formatted() + " / " + allMatches.count.formatted() + " matchs programmés" // let label = ready.count.formatted() + " / " + allMatches.count.formatted() + " matchs programmés"
let label = "\(ready.count.formatted()) / \(allMatches.count.formatted()) matchs programmés"
let completion = (Double(ready.count) / Double(allMatches.count)) let completion = (Double(ready.count) / Double(allMatches.count))
let completionLabel = completion.isNaN ? "" : completion.formatted(.percent.precision(.fractionLength(0))) let completionLabel = completion.isNaN ? "" : completion.formatted(.percent.precision(.fractionLength(0)))
return TournamentStatus(label: label, completion: completionLabel) return TournamentStatus(label: label, completion: completionLabel)
@ -1282,7 +1286,7 @@ class Tournament : ModelObject, Storable {
func callStatus() async -> TournamentStatus { func callStatus() async -> TournamentStatus {
let selectedSortedTeams = selectedSortedTeams() let selectedSortedTeams = selectedSortedTeams()
let called = selectedSortedTeams.filter { isStartDateIsDifferentThanCallDate($0) == false } let called = selectedSortedTeams.filter { isStartDateIsDifferentThanCallDate($0) == false }
let label = called.count.formatted() + " / " + selectedSortedTeams.count.formatted() + " convoquées au bon horaire" let label = "\(called.count.formatted()) / \(selectedSortedTeams.count.formatted()) convoquées au bon horaire"
let completion = (Double(called.count) / Double(selectedSortedTeams.count)) let completion = (Double(called.count) / Double(selectedSortedTeams.count))
let completionLabel = completion.isNaN ? "" : completion.formatted(.percent.precision(.fractionLength(0))) let completionLabel = completion.isNaN ? "" : completion.formatted(.percent.precision(.fractionLength(0)))
return TournamentStatus(label: label, completion: completionLabel) return TournamentStatus(label: label, completion: completionLabel)
@ -1291,7 +1295,7 @@ class Tournament : ModelObject, Storable {
func confirmedSummonStatus() async -> TournamentStatus { func confirmedSummonStatus() async -> TournamentStatus {
let selectedSortedTeams = selectedSortedTeams() let selectedSortedTeams = selectedSortedTeams()
let called = selectedSortedTeams.filter { $0.confirmationDate != nil } let called = selectedSortedTeams.filter { $0.confirmationDate != nil }
let label = called.count.formatted() + " / " + selectedSortedTeams.count.formatted() + " confirmées" let label = "\(called.count.formatted()) / \(selectedSortedTeams.count.formatted()) confirmées"
let completion = (Double(called.count) / Double(selectedSortedTeams.count)) let completion = (Double(called.count) / Double(selectedSortedTeams.count))
let completionLabel = completion.isNaN ? "" : completion.formatted(.percent.precision(.fractionLength(0))) let completionLabel = completion.isNaN ? "" : completion.formatted(.percent.precision(.fractionLength(0)))
return TournamentStatus(label: label, completion: completionLabel) return TournamentStatus(label: label, completion: completionLabel)
@ -1519,11 +1523,11 @@ class Tournament : ModelObject, Storable {
func isFree() -> Bool { func isFree() -> Bool {
entryFee == nil || entryFee == 0 return entryFee == nil || entryFee == 0
} }
func indexOf(team: TeamRegistration) -> Int? { func indexOf(team: TeamRegistration) -> Int? {
selectedSortedTeams().firstIndex(where: { $0.id == team.id }) return selectedSortedTeams().firstIndex(where: { $0.id == team.id })
} }
func labelIndexOf(team: TeamRegistration) -> String? { func labelIndexOf(team: TeamRegistration) -> String? {
@ -1670,11 +1674,11 @@ class Tournament : ModelObject, Storable {
private let _currentSelectionSorting : [MySortDescriptor<TeamRegistration>] = [.keyPath(\.weight), .keyPath(\.registrationDate!)] private let _currentSelectionSorting : [MySortDescriptor<TeamRegistration>] = [.keyPath(\.weight), .keyPath(\.registrationDate!)]
private func _matchSchedulers() -> [MatchScheduler] { private func _matchSchedulers() -> [MatchScheduler] {
Store.main.filter(isIncluded: { $0.tournament == self.id }) return Store.main.filter(isIncluded: { $0.tournament == self.id })
} }
func matchScheduler() -> MatchScheduler? { func matchScheduler() -> MatchScheduler? {
_matchSchedulers().first return self._matchSchedulers().first
} }
func currentMonthData() -> MonthData? { func currentMonthData() -> MonthData? {
@ -1684,24 +1688,25 @@ class Tournament : ModelObject, Storable {
} }
var maleUnrankedValue: Int? { var maleUnrankedValue: Int? {
currentMonthData()?.maleUnrankedValue return currentMonthData()?.maleUnrankedValue
} }
var femaleUnrankedValue: Int? { var femaleUnrankedValue: Int? {
currentMonthData()?.femaleUnrankedValue return currentMonthData()?.femaleUnrankedValue
} }
func courtNameIfAvailable(atIndex courtIndex: Int) -> String? { func courtNameIfAvailable(atIndex courtIndex: Int) -> String? {
club()?.customizedCourts.first(where: { $0.index == courtIndex })?.name return club()?.customizedCourts.first(where: { $0.index == courtIndex })?.name
} }
func courtName(atIndex courtIndex: Int) -> String { func courtName(atIndex courtIndex: Int) -> String {
courtNameIfAvailable(atIndex: courtIndex) ?? Court.courtIndexedTitle(atIndex: courtIndex) return courtNameIfAvailable(atIndex: courtIndex) ?? Court.courtIndexedTitle(atIndex: courtIndex)
} }
func tournamentWinner() -> TeamRegistration? { func tournamentWinner() -> TeamRegistration? {
let final : Round? = Store.main.filter(isIncluded: { $0.index == 0 && $0.tournament == id && $0.parent == nil }).first let rounds: [Round] = Store.main.filter(isIncluded: { $0.index == 0 && $0.tournament == id && $0.parent == nil })
return final?.playedMatches().first?.winner() // let final: Round? = .first
return rounds.first?.playedMatches().first?.winner()
} }
func getGroupStageChunkValue() -> Int { func getGroupStageChunkValue() -> Int {

@ -16,10 +16,10 @@ public extension FixedWidthInteger {
} }
func ordinalFormatted() -> String { func ordinalFormatted() -> String {
self.formatted() + self.ordinalFormattedSuffix() return self.formatted() + self.ordinalFormattedSuffix()
} }
var pluralSuffix: String { var pluralSuffix: String {
self > 1 ? "s" : "" return self > 1 ? "s" : ""
} }
} }

@ -73,7 +73,8 @@ class SearchViewModel: ObservableObject, Identifiable {
} }
func codeClubs() -> [String] { func codeClubs() -> [String] {
DataStore.shared.user.clubsObjects().compactMap { $0.code } let clubs: [Club] = DataStore.shared.user.clubsObjects()
return clubs.compactMap { $0.code }
} }
func getCodeClub() -> String? { func getCodeClub() -> String? {
@ -127,7 +128,7 @@ class SearchViewModel: ObservableObject, Identifiable {
} }
func words() -> [String] { func words() -> [String] {
searchText.canonicalVersion.trimmed.components(separatedBy: .whitespaces) return searchText.canonicalVersion.trimmed.components(separatedBy: .whitespaces)
} }
func wordsPredicates() -> NSPredicate? { func wordsPredicates() -> NSPredicate? {

@ -35,17 +35,17 @@ struct ActivityView: View {
} }
var runningTournaments: [FederalTournamentHolder] { var runningTournaments: [FederalTournamentHolder] {
dataStore.tournaments.filter({ $0.endDate == nil }) return dataStore.tournaments.filter({ $0.endDate == nil })
.filter({ federalDataViewModel.isTournamentValidForFilters($0) }) .filter({ federalDataViewModel.isTournamentValidForFilters($0) })
} }
func getRunningTournaments() -> [Tournament] { func getRunningTournaments() -> [Tournament] {
dataStore.tournaments.filter({ $0.endDate == nil }) return dataStore.tournaments.filter({ $0.endDate == nil })
.filter({ federalDataViewModel.isTournamentValidForFilters($0) }) .filter({ federalDataViewModel.isTournamentValidForFilters($0) })
} }
var endedTournaments: [Tournament] { var endedTournaments: [Tournament] {
dataStore.tournaments.filter({ $0.endDate != nil }) return dataStore.tournaments.filter({ $0.endDate != nil })
.filter({ federalDataViewModel.isTournamentValidForFilters($0) }) .filter({ federalDataViewModel.isTournamentValidForFilters($0) })
} }
// //
@ -62,11 +62,11 @@ struct ActivityView: View {
var tournaments: [FederalTournamentHolder] { var tournaments: [FederalTournamentHolder] {
switch navigation.agendaDestination! { switch navigation.agendaDestination! {
case .activity: case .activity:
runningTournaments return runningTournaments
case .history: case .history:
endedTournaments return endedTournaments
case .tenup: case .tenup:
federalDataViewModel.filteredFederalTournaments return federalDataViewModel.filteredFederalTournaments
} }
} }

@ -45,15 +45,15 @@ struct MainView: View {
)} )}
var matches: [Match] { var matches: [Match] {
dataStore.matches.filter({ $0.confirmed && $0.startDate != nil && $0.endDate == nil && $0.courtIndex != nil }) return dataStore.matches.filter { $0.confirmed && $0.startDate != nil && $0.endDate == nil && $0.courtIndex != nil }
} }
private func _isConnected() -> Bool { private func _isConnected() -> Bool {
Store.main.hasToken() && Store.main.userId != nil return Store.main.hasToken() && Store.main.userId != nil
} }
var badgeText: Text? { var badgeText: Text? {
_isConnected() == false ? Text("!").font(.headline) : nil return _isConnected() == false ? Text("!").font(.headline) : nil
} }
var body: some View { var body: some View {
@ -104,7 +104,7 @@ struct MainView: View {
} }
func _activityStatusBoxView() -> some View { func _activityStatusBoxView() -> some View {
_activityStatus() return _activityStatus()
.toastFormatted() .toastFormatted()
} }

@ -67,7 +67,8 @@ struct LoserRoundScheduleEditorView: View {
// _save() // _save()
let loserRounds = upperRound.loserRounds().filter { $0.isDisabled() == false } let loserRounds = upperRound.loserRounds().filter { $0.isDisabled() == false }
tournament.matchScheduler()?.updateBracketSchedule(tournament: tournament, fromRoundId: loserRounds.first?.id, fromMatchId: nil, startDate: startDate) let scheduler: MatchScheduler? = tournament.matchScheduler()
scheduler?.updateBracketSchedule(tournament: self.tournament, fromRoundId: loserRounds.first?.id, fromMatchId: nil, startDate: self.startDate)
loserRounds.first?.startDate = startDate loserRounds.first?.startDate = startDate
_save() _save()
} }

@ -33,7 +33,8 @@ struct MatchScheduleEditorView: View {
} }
private func _updateSchedule() async { private func _updateSchedule() async {
tournament.matchScheduler()?.updateBracketSchedule(tournament: tournament, fromRoundId: match.round, fromMatchId: match.id, startDate: startDate) let scheduler: MatchScheduler? = tournament.matchScheduler()
scheduler?.updateBracketSchedule(tournament: tournament, fromRoundId: match.round, fromMatchId: match.id, startDate: startDate)
} }
} }

@ -62,7 +62,7 @@ struct PlanningView: View {
Text(day.formatted(.dateTime.day().weekday().month())) Text(day.formatted(.dateTime.day().weekday().month()))
Spacer() Spacer()
let count = _matchesCount(inDayInt: day.dayInt) let count = _matchesCount(inDayInt: day.dayInt)
Text(count.formatted() + " match" + count.pluralSuffix) Text(self._formattedMatchCount(count))
} }
} }
.headerProminence(.increased) .headerProminence(.increased)
@ -90,12 +90,17 @@ struct PlanningView: View {
private func _timeSlotView(key: Date, matches: [Match]) -> some View { private func _timeSlotView(key: Date, matches: [Match]) -> some View {
LabeledContent { LabeledContent {
Text(matches.count.formatted() + " match" + matches.count.pluralSuffix) Text(self._formattedMatchCount(self.matches.count))
} label: { } label: {
Text(key.formatted(date: .omitted, time: .shortened)).font(.title).fontWeight(.semibold) Text(key.formatted(date: .omitted, time: .shortened)).font(.title).fontWeight(.semibold)
Text(Set(matches.compactMap { $0.roundTitle() }).joined(separator: ", ")) Text(Set(matches.compactMap { $0.roundTitle() }).joined(separator: ", "))
} }
} }
fileprivate func _formattedMatchCount(_ count: Int) -> String {
return "\(count.formatted()) match\(count.pluralSuffix)"
}
} }
//#Preview { //#Preview {

@ -45,7 +45,9 @@ extension LoserRound: Equatable {
} }
func badgeValue() -> Int? { func badgeValue() -> Int? {
return rounds.flatMap { $0.playedMatches() }.filter({ $0.isRunning() }).count let playedMatches: [Match] = self.rounds.flatMap { $0.playedMatches() }
let runningMatches: [Match] = playedMatches.filter { $0.isRunning() }
return runningMatches.count
} }
func badgeValueColor() -> Color? { func badgeValueColor() -> Color? {

@ -14,7 +14,7 @@ struct EditScoreView: View {
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
func walkout(_ team: TeamPosition) { func walkout(_ team: TeamPosition) {
matchDescriptor.match?.setWalkOut(team) self.matchDescriptor.match?.setWalkOut(team)
save() save()
dismiss() dismiss()
} }

@ -381,7 +381,7 @@ struct MySearchView: View {
private func headerView() -> some View { private func headerView() -> some View {
HStack { HStack {
Text(players.count.formatted() + " " + searchViewModel.filterOption.localizedPlayerLabel + players.count.pluralSuffix) Text("\(players.count.formatted()) \( searchViewModel.filterOption.localizedPlayerLabel)\( players.count.pluralSuffix)")
Spacer() Spacer()
Menu { Menu {
Section { Section {

@ -804,7 +804,9 @@ struct InscriptionManagerView: View {
static private func _pastePredicate(pasteField: String, mostRecentDate: Date?, filterOption: PlayerFilterOption) -> NSPredicate? { static private func _pastePredicate(pasteField: String, mostRecentDate: Date?, filterOption: PlayerFilterOption) -> NSPredicate? {
let text = pasteField.canonicalVersion let text = pasteField.canonicalVersion
let nameComponents = text.components(separatedBy: .whitespacesAndNewlines).compactMap { $0.isEmpty ? nil : $0 }.filter({ $0 != "de" && $0 != "la" && $0 != "le" && $0.count > 1 }) let textStrings: [String] = text.components(separatedBy: .whitespacesAndNewlines)
let nonEmptyStrings: [String] = textStrings.compactMap { $0.isEmpty ? nil : $0 }
let nameComponents = nonEmptyStrings.filter({ $0 != "de" && $0 != "la" && $0 != "le" && $0.count > 1 })
var andPredicates = [NSPredicate]() var andPredicates = [NSPredicate]()
var orPredicates = [NSPredicate]() var orPredicates = [NSPredicate]()
//self.wordsCount = nameComponents.count //self.wordsCount = nameComponents.count

@ -56,7 +56,8 @@ enum CashierDestination: Identifiable, Selectable, Equatable {
case .groupStage(let groupStage): case .groupStage(let groupStage):
return groupStage.unsortedPlayers().filter({ $0.hasPaid() == false }).count return groupStage.unsortedPlayers().filter({ $0.hasPaid() == false }).count
case .bracket(let round): case .bracket(let round):
return round.seeds().flatMap { $0.unsortedPlayers() }.filter({ $0.hasPaid() == false }).count let playerRegistrations: [PlayerRegistration] = round.seeds().flatMap { $0.unsortedPlayers() }
return playerRegistrations.filter({ $0.hasPaid() == false }).count
case .all(let tournament): case .all(let tournament):
return nil return nil
} }

@ -16,10 +16,10 @@ protocol Schedulable: Identifiable {
extension Schedulable { extension Schedulable {
func getStartDate() -> Date? { func getStartDate() -> Date? {
startDate ?? playedMatches().first?.startDate return startDate ?? playedMatches().first?.startDate
} }
} }
enum ScheduleDestination: String, Identifiable, Selectable, Equatable { enum ScheduleDestination: String, Identifiable, Selectable, Equatable {
static func == (lhs: ScheduleDestination, rhs: ScheduleDestination) -> Bool { static func == (lhs: ScheduleDestination, rhs: ScheduleDestination) -> Bool {
return lhs.id == rhs.id return lhs.id == rhs.id
@ -43,7 +43,7 @@ enum ScheduleDestination: String, Identifiable, Selectable, Equatable {
} }
func badgeValue() -> Int? { func badgeValue() -> Int? {
nil return nil
} }
func badgeValueColor() -> Color? { func badgeValueColor() -> Color? {
@ -51,7 +51,7 @@ enum ScheduleDestination: String, Identifiable, Selectable, Equatable {
} }
func badgeImage() -> Badge? { func badgeImage() -> Badge? {
nil return nil
} }
} }

Loading…
Cancel
Save