fix issue with disconnection by making TournamentStore optional

sync2
Laurent 9 months ago
parent 5795a3b62f
commit edc00f0515
  1. 24
      PadelClub/Data/DataStore.swift
  2. 4
      PadelClub/Data/DrawLog.swift
  3. 32
      PadelClub/Data/GroupStage.swift
  4. 62
      PadelClub/Data/Match.swift
  5. 8
      PadelClub/Data/MatchScheduler.swift
  6. 6
      PadelClub/Data/PlayerRegistration.swift
  7. 82
      PadelClub/Data/Round.swift
  8. 58
      PadelClub/Data/TeamRegistration.swift
  9. 8
      PadelClub/Data/TeamScore.swift
  10. 146
      PadelClub/Data/Tournament.swift
  11. 4
      PadelClub/Data/TournamentLibrary.swift
  12. 2
      PadelClub/Utils/Patcher.swift
  13. 6
      PadelClub/Views/Calling/CallSettingsView.swift
  14. 4
      PadelClub/Views/Calling/CallView.swift
  15. 8
      PadelClub/Views/Calling/SendToAllView.swift
  16. 6
      PadelClub/Views/Calling/TeamsCallingView.swift
  17. 2
      PadelClub/Views/Cashier/CashierSettingsView.swift
  18. 12
      PadelClub/Views/GroupStage/Components/GroupStageSettingsView.swift
  19. 4
      PadelClub/Views/GroupStage/Components/GroupStageTeamView.swift
  20. 10
      PadelClub/Views/GroupStage/GroupStageView.swift
  21. 22
      PadelClub/Views/GroupStage/GroupStagesSettingsView.swift
  22. 2
      PadelClub/Views/GroupStage/GroupStagesView.swift
  23. 12
      PadelClub/Views/GroupStage/LoserBracketFromGroupStageView.swift
  24. 2
      PadelClub/Views/Match/Components/MatchDateView.swift
  25. 22
      PadelClub/Views/Match/MatchDetailView.swift
  26. 2
      PadelClub/Views/Match/MatchRowView.swift
  27. 34
      PadelClub/Views/Match/MatchSetupView.swift
  28. 53
      PadelClub/Views/Navigation/Toolbox/ToolboxView.swift
  29. 4
      PadelClub/Views/Planning/GroupStageScheduleEditorView.swift
  30. 4
      PadelClub/Views/Planning/LoserRoundScheduleEditorView.swift
  31. 4
      PadelClub/Views/Planning/LoserRoundStepScheduleEditorView.swift
  32. 4
      PadelClub/Views/Planning/MatchScheduleEditorView.swift
  33. 24
      PadelClub/Views/Planning/PlanningSettingsView.swift
  34. 4
      PadelClub/Views/Planning/PlanningView.swift
  35. 4
      PadelClub/Views/Planning/RoundScheduleEditorView.swift
  36. 10
      PadelClub/Views/Planning/SchedulerView.swift
  37. 6
      PadelClub/Views/Player/Components/PlayerSexPickerView.swift
  38. 6
      PadelClub/Views/Player/PlayerDetailView.swift
  39. 4
      PadelClub/Views/Player/PlayerView.swift
  40. 2
      PadelClub/Views/Round/DrawLogsView.swift
  41. 8
      PadelClub/Views/Round/LoserRoundSettingsView.swift
  42. 2
      PadelClub/Views/Round/LoserRoundView.swift
  43. 14
      PadelClub/Views/Round/RoundSettingsView.swift
  44. 8
      PadelClub/Views/Round/RoundView.swift
  45. 2
      PadelClub/Views/Score/EditScoreView.swift
  46. 2
      PadelClub/Views/Team/CoachListView.swift
  47. 16
      PadelClub/Views/Team/EditingTeamView.swift
  48. 6
      PadelClub/Views/Tournament/FileImportView.swift
  49. 10
      PadelClub/Views/Tournament/Screen/AddTeamView.swift
  50. 16
      PadelClub/Views/Tournament/Screen/Components/InscriptionInfoView.swift
  51. 4
      PadelClub/Views/Tournament/Screen/Components/TournamentGeneralSettingsView.swift
  52. 6
      PadelClub/Views/Tournament/Screen/Components/TournamentMatchFormatsSettingsView.swift
  53. 6
      PadelClub/Views/Tournament/Screen/Components/UpdateSourceRankDateView.swift
  54. 6
      PadelClub/Views/Tournament/Screen/InscriptionManagerView.swift
  55. 2
      PadelClub/Views/Tournament/Screen/TableStructureView.swift
  56. 52
      PadelClub/Views/Tournament/Screen/TournamentCashierView.swift
  57. 12
      PadelClub/Views/Tournament/Screen/TournamentRankView.swift

@ -302,10 +302,12 @@ class DataStore: ObservableObject {
var runningMatches: [Match] = [] var runningMatches: [Match] = []
for tournament in lastTournaments { for tournament in lastTournaments {
let matches = tournament.tournamentStore.matches.filter { match in if let store = tournament.tournamentStore {
match.disabled == false && match.isRunning() let matches = store.matches.filter { match in
match.disabled == false && match.isRunning()
}
runningMatches.append(contentsOf: matches)
} }
runningMatches.append(contentsOf: matches)
} }
return runningMatches return runningMatches
} }
@ -317,9 +319,11 @@ class DataStore: ObservableObject {
var runningMatches: [Match] = [] var runningMatches: [Match] = []
for tournament in lastTournaments { for tournament in lastTournaments {
let matches = tournament.tournamentStore.matches.filter { match in if let store = tournament.tournamentStore {
match.disabled == false && match.startDate != nil && match.endDate == nil } let matches = store.matches.filter { match in
runningMatches.append(contentsOf: matches) match.disabled == false && match.startDate != nil && match.endDate == nil }
runningMatches.append(contentsOf: matches)
}
} }
return runningMatches return runningMatches
} }
@ -330,9 +334,11 @@ class DataStore: ObservableObject {
var runningMatches: [Match] = [] var runningMatches: [Match] = []
for tournament in lastTournaments { for tournament in lastTournaments {
let matches = tournament.tournamentStore.matches.filter { match in if let store = tournament.tournamentStore {
match.disabled == false && match.hasEnded() } let matches = store.matches.filter { match in
runningMatches.append(contentsOf: matches) match.disabled == false && match.hasEnded() }
runningMatches.append(contentsOf: matches)
}
} }
return runningMatches.sorted(by: \.endDate!, order: .descending) return runningMatches.sorted(by: \.endDate!, order: .descending)
} }

@ -52,7 +52,7 @@ final class DrawLog: BaseDrawLog, SideStorable {
switch drawType { switch drawType {
case .seed: case .seed:
let roundIndex = RoundRule.roundIndex(fromMatchIndex: drawMatchIndex) let roundIndex = RoundRule.roundIndex(fromMatchIndex: drawMatchIndex)
return tournamentStore.rounds.first(where: { $0.parent == nil && $0.index == roundIndex })?._matches().first(where: { $0.index == drawMatchIndex }) return tournamentStore?.rounds.first(where: { $0.parent == nil && $0.index == roundIndex })?._matches().first(where: { $0.index == drawMatchIndex })
default: default:
return nil return nil
} }
@ -70,7 +70,7 @@ final class DrawLog: BaseDrawLog, SideStorable {
return drawMatch()?.matchTitle() ?? "" return drawMatch()?.matchTitle() ?? ""
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return TournamentLibrary.shared.store(tournamentId: self.tournament) return TournamentLibrary.shared.store(tournamentId: self.tournament)
} }

@ -22,14 +22,15 @@ final class GroupStage: BaseGroupStage, SideStorable {
} }
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return TournamentLibrary.shared.store(tournamentId: self.tournament) return TournamentLibrary.shared.store(tournamentId: self.tournament)
} }
// MARK: - Computed dependencies // MARK: - Computed dependencies
func _matches() -> [Match] { func _matches() -> [Match] {
return self.tournamentStore.matches.filter { $0.groupStage == self.id }.sorted(by: \.index) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.matches.filter { $0.groupStage == self.id }.sorted(by: \.index)
// Store.main.filter { $0.groupStage == self.id } // Store.main.filter { $0.groupStage == self.id }
} }
@ -101,7 +102,7 @@ final class GroupStage: BaseGroupStage, SideStorable {
returnMatches = returnMatches.filter({ $0.index >= matchCount * matchPhaseCount }) returnMatches = returnMatches.filter({ $0.index >= matchCount * matchPhaseCount })
} }
do { do {
try self.tournamentStore.matches.delete(contentOfs: returnMatches) try self.tournamentStore?.matches.delete(contentOfs: returnMatches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -127,8 +128,8 @@ final class GroupStage: BaseGroupStage, SideStorable {
matches.append(newMatch) matches.append(newMatch)
} }
self.tournamentStore.matches.addOrUpdate(contentOfs: matches) self.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
self.tournamentStore.teamScores.addOrUpdate(contentOfs: teamScores) self.tournamentStore?.teamScores.addOrUpdate(contentOfs: teamScores)
} }
func buildMatches(keepExistingMatches: Bool = false) { func buildMatches(keepExistingMatches: Bool = false) {
@ -153,8 +154,8 @@ final class GroupStage: BaseGroupStage, SideStorable {
} }
do { do {
try self.tournamentStore.matches.addOrUpdate(contentOfs: matches) try self.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
try self.tournamentStore.teamScores.addOrUpdate(contentOfs: teamScores) try self.tournamentStore?.teamScores.addOrUpdate(contentOfs: teamScores)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -192,11 +193,11 @@ final class GroupStage: BaseGroupStage, SideStorable {
tournamentObject()?.shouldVerifyBracket = true tournamentObject()?.shouldVerifyBracket = true
} }
} }
try self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
if let tournamentObject = tournamentObject() { if let tournamentObject = tournamentObject() {
try DataStore.shared.tournaments.addOrUpdate(instance: tournamentObject) try DataStore.shared.tournaments.addOrUpdate(instance: tournamentObject)
} }
self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
let groupStagesAreOverAtFirstStep = tournament.groupStagesAreOver(atStep: 0) let groupStagesAreOverAtFirstStep = tournament.groupStagesAreOver(atStep: 0)
let nextStepGroupStages = tournament.groupStages(atStep: 1) let nextStepGroupStages = tournament.groupStages(atStep: 1)
@ -388,7 +389,7 @@ final class GroupStage: BaseGroupStage, SideStorable {
} }
private func _removeMatches() { private func _removeMatches() {
self.tournamentStore.matches.delete(contentOfs: _matches()) self.tournamentStore?.matches.delete(contentOfs: _matches())
} }
private func _numberOfMatchesToBuild() -> Int { private func _numberOfMatchesToBuild() -> Int {
@ -444,10 +445,11 @@ final class GroupStage: BaseGroupStage, SideStorable {
} }
func unsortedTeams() -> [TeamRegistration] { func unsortedTeams() -> [TeamRegistration] {
guard let tournamentStore = self.tournamentStore else { return [] }
if step > 0 { if step > 0 {
return self.tournamentStore.groupStages.filter({ $0.step == step - 1 }).compactMap({ $0.teams(true)[safe: index] }) return tournamentStore.groupStages.filter({ $0.step == step - 1 }).compactMap({ $0.teams(true)[safe: index] })
} }
return self.tournamentStore.teamRegistrations.filter { $0.groupStage == self.id && $0.groupStagePosition != nil } return tournamentStore.teamRegistrations.filter { $0.groupStage == self.id && $0.groupStagePosition != nil }
} }
@ -570,7 +572,7 @@ final class GroupStage: BaseGroupStage, SideStorable {
playedMatches.forEach { match in playedMatches.forEach { match in
match.matchFormat = matchFormat match.matchFormat = matchFormat
} }
self.tournamentStore.matches.addOrUpdate(contentOfs: playedMatches) self.tournamentStore?.matches.addOrUpdate(contentOfs: playedMatches)
} }
func pasteData() -> String { func pasteData() -> String {
@ -593,7 +595,7 @@ final class GroupStage: BaseGroupStage, SideStorable {
for match in matches { for match in matches {
match.deleteDependencies() match.deleteDependencies()
} }
self.tournamentStore.matches.deleteDependencies(matches) self.tournamentStore?.matches.deleteDependencies(matches)
} }
// init(from decoder: Decoder) throws { // init(from decoder: Decoder) throws {
@ -627,7 +629,7 @@ final class GroupStage: BaseGroupStage, SideStorable {
// } // }
func insertOnServer() { func insertOnServer() {
self.tournamentStore.groupStages.writeChangeAndInsertOnServer(instance: self) self.tournamentStore?.groupStages.writeChangeAndInsertOnServer(instance: self)
for match in self._matches() { for match in self._matches() {
match.insertOnServer() match.insertOnServer()
} }

@ -46,7 +46,7 @@ final class Match: BaseMatch, SideStorable {
} }
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
if let id = self.store?.identifier { if let id = self.store?.identifier {
return TournamentLibrary.shared.store(tournamentId: id) return TournamentLibrary.shared.store(tournamentId: id)
} }
@ -60,7 +60,8 @@ final class Match: BaseMatch, SideStorable {
// MARK: - Computed dependencies // MARK: - Computed dependencies
var teamScores: [TeamScore] { var teamScores: [TeamScore] {
return self.tournamentStore.teamScores.filter { $0.match == self.id } guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.teamScores.filter { $0.match == self.id }
} }
// MARK: - // MARK: -
@ -70,7 +71,7 @@ final class Match: BaseMatch, SideStorable {
for teamScore in teamScores { for teamScore in teamScores {
teamScore.deleteDependencies() teamScore.deleteDependencies()
} }
self.tournamentStore.teamScores.deleteDependencies(teamScores) self.tournamentStore?.teamScores.deleteDependencies(teamScores)
} }
func indexInRound(in matches: [Match]? = nil) -> Int { func indexInRound(in matches: [Match]? = nil) -> Int {
@ -149,12 +150,12 @@ defer {
func winner() -> TeamRegistration? { func winner() -> TeamRegistration? {
guard let winningTeamId else { return nil } guard let winningTeamId else { return nil }
return self.tournamentStore.teamRegistrations.findById(winningTeamId) return self.tournamentStore?.teamRegistrations.findById(winningTeamId)
} }
func loser() -> TeamRegistration? { func loser() -> TeamRegistration? {
guard let losingTeamId else { return nil } guard let losingTeamId else { return nil }
return self.tournamentStore.teamRegistrations.findById(losingTeamId) return self.tournamentStore?.teamRegistrations.findById(losingTeamId)
} }
@ -183,7 +184,7 @@ defer {
endDate = nil endDate = nil
followingMatch()?.cleanScheduleAndSave(nil) followingMatch()?.cleanScheduleAndSave(nil)
_loserMatch()?.cleanScheduleAndSave(nil) _loserMatch()?.cleanScheduleAndSave(nil)
self.tournamentStore.matches.addOrUpdate(instance: self) self.tournamentStore?.matches.addOrUpdate(instance: self)
} }
func resetMatch() { func resetMatch() {
@ -200,14 +201,14 @@ defer {
func resetScores() { func resetScores() {
teamScores.forEach({ $0.score = nil }) teamScores.forEach({ $0.score = nil })
self.tournamentStore.teamScores.addOrUpdate(contentOfs: teamScores) self.tournamentStore?.teamScores.addOrUpdate(contentOfs: teamScores)
} }
func teamWillBeWalkOut(_ team: TeamRegistration) { func teamWillBeWalkOut(_ team: TeamRegistration) {
resetMatch() resetMatch()
let existingTeamScore = teamScore(ofTeam: team) ?? TeamScore(match: id, team: team) let existingTeamScore = teamScore(ofTeam: team) ?? TeamScore(match: id, team: team)
existingTeamScore.walkOut = 1 existingTeamScore.walkOut = 1
self.tournamentStore.teamScores.addOrUpdate(instance: existingTeamScore) self.tournamentStore?.teamScores.addOrUpdate(instance: existingTeamScore)
} }
func luckyLosers() -> [TeamRegistration] { func luckyLosers() -> [TeamRegistration] {
@ -225,11 +226,11 @@ defer {
let position = matchIndex * 2 + teamPosition.rawValue let position = matchIndex * 2 + teamPosition.rawValue
let previousScores = teamScores.filter({ $0.luckyLoser == position }) let previousScores = teamScores.filter({ $0.luckyLoser == position })
self.tournamentStore.teamScores.delete(contentOfs: previousScores) self.tournamentStore?.teamScores.delete(contentOfs: previousScores)
let teamScoreLuckyLoser = teamScore(ofTeam: team) ?? TeamScore(match: id, team: team) let teamScoreLuckyLoser = teamScore(ofTeam: team) ?? TeamScore(match: id, team: team)
teamScoreLuckyLoser.luckyLoser = position teamScoreLuckyLoser.luckyLoser = position
self.tournamentStore.teamScores.addOrUpdate(instance: teamScoreLuckyLoser) self.tournamentStore?.teamScores.addOrUpdate(instance: teamScoreLuckyLoser)
} }
func disableMatch() { func disableMatch() {
@ -264,14 +265,14 @@ defer {
let isTopMatch = topMatchIndex + 1 == index let isTopMatch = topMatchIndex + 1 == index
let lookingForIndex = isTopMatch ? topMatchIndex : bottomMatchIndex let lookingForIndex = isTopMatch ? topMatchIndex : bottomMatchIndex
return self.tournamentStore.matches.first(where: { $0.round == round && $0.index == lookingForIndex }) return self.tournamentStore?.matches.first(where: { $0.round == round && $0.index == lookingForIndex })
} }
private func _forwardMatch(inRound round: Round) -> Match? { private func _forwardMatch(inRound round: Round) -> Match? {
guard let roundObjectNextRound = round.nextRound() else { return nil } guard let roundObjectNextRound = round.nextRound() else { return nil }
let nextIndex = (index - 1) / 2 let nextIndex = (index - 1) / 2
return self.tournamentStore.matches.first(where: { $0.round == roundObjectNextRound.id && $0.index == nextIndex }) return self.tournamentStore?.matches.first(where: { $0.round == roundObjectNextRound.id && $0.index == nextIndex })
} }
func _toggleForwardMatchDisableState(_ state: Bool) { func _toggleForwardMatchDisableState(_ state: Bool) {
@ -339,7 +340,7 @@ defer {
if disabled != currentState { if disabled != currentState {
do { do {
try self.tournamentStore.teamScores.delete(contentOfs: teamScores) try self.tournamentStore?.teamScores.delete(contentOfs: teamScores)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -349,7 +350,7 @@ defer {
for team in teams { for team in teams {
if isSeededBy(team: team) { if isSeededBy(team: team) {
team.bracketPosition = nil team.bracketPosition = nil
self.tournamentStore.teamRegistrations.addOrUpdate(instance: team) self.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} }
} }
} }
@ -357,7 +358,7 @@ defer {
roundObject?._cachedSeedInterval = nil roundObject?._cachedSeedInterval = nil
name = nil name = nil
do { do {
try self.tournamentStore.matches.addOrUpdate(instance: self) try self.tournamentStore?.matches.addOrUpdate(instance: self)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -374,7 +375,8 @@ defer {
} }
func next() -> Match? { func next() -> Match? {
let matches: [Match] = self.tournamentStore.matches.filter { $0.round == round && $0.index > index && $0.disabled == false } guard let tournamentStore = self.tournamentStore else { return nil }
let matches: [Match] = tournamentStore.matches.filter { $0.round == round && $0.index > index && $0.disabled == false }
return matches.sorted(by: \.index).first return matches.sorted(by: \.index).first
} }
@ -384,7 +386,7 @@ defer {
} }
func getFollowingMatch(fromNextRoundId nextRoundId: String) -> Match? { func getFollowingMatch(fromNextRoundId nextRoundId: String) -> Match? {
return self.tournamentStore.matches.first(where: { $0.round == nextRoundId && $0.index == (index - 1) / 2 }) return self.tournamentStore?.matches.first(where: { $0.round == nextRoundId && $0.index == (index - 1) / 2 })
} }
func getDuration() -> Int { func getDuration() -> Int {
@ -417,7 +419,7 @@ defer {
guard let roundObject else { return nil } guard let roundObject else { return nil }
let topPreviousRoundMatchIndex = topPreviousRoundMatchIndex() let topPreviousRoundMatchIndex = topPreviousRoundMatchIndex()
let roundObjectPreviousRoundId = roundObject.previousRound()?.id let roundObjectPreviousRoundId = roundObject.previousRound()?.id
return self.tournamentStore.matches.first(where: { match in return self.tournamentStore?.matches.first(where: { match in
match.round != nil && match.round == roundObjectPreviousRoundId && match.index == topPreviousRoundMatchIndex match.round != nil && match.round == roundObjectPreviousRoundId && match.index == topPreviousRoundMatchIndex
}) })
} }
@ -426,7 +428,7 @@ defer {
guard let roundObject else { return nil } guard let roundObject else { return nil }
let bottomPreviousRoundMatchIndex = bottomPreviousRoundMatchIndex() let bottomPreviousRoundMatchIndex = bottomPreviousRoundMatchIndex()
let roundObjectPreviousRoundId = roundObject.previousRound()?.id let roundObjectPreviousRoundId = roundObject.previousRound()?.id
return self.tournamentStore.matches.first(where: { match in return self.tournamentStore?.matches.first(where: { match in
match.round != nil && match.round == roundObjectPreviousRoundId && match.index == bottomPreviousRoundMatchIndex match.round != nil && match.round == roundObjectPreviousRoundId && match.index == bottomPreviousRoundMatchIndex
}) })
} }
@ -463,8 +465,10 @@ defer {
func previousMatches() -> [Match] { func previousMatches() -> [Match] {
guard let roundObject else { return [] } guard let roundObject else { return [] }
guard let tournamentStore = self.tournamentStore else { return [] }
let roundObjectPreviousRoundId = roundObject.previousRound()?.id let roundObjectPreviousRoundId = roundObject.previousRound()?.id
return self.tournamentStore.matches.filter { match in return tournamentStore.matches.filter { match in
match.round == roundObjectPreviousRoundId && (match.index == topPreviousRoundMatchIndex() || match.index == bottomPreviousRoundMatchIndex()) match.round == roundObjectPreviousRoundId && (match.index == topPreviousRoundMatchIndex() || match.index == bottomPreviousRoundMatchIndex())
}.sorted(by: \.index) }.sorted(by: \.index)
} }
@ -483,7 +487,7 @@ defer {
teamScoreWalkout.walkOut = 0 teamScoreWalkout.walkOut = 0
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]) self.tournamentStore?.teamScores.addOrUpdate(contentOfs: [teamScoreWalkout, teamScoreWinning])
if endDate == nil { if endDate == nil {
endDate = Date() endDate = Date()
@ -542,7 +546,7 @@ defer {
teamScoreOne.score = matchDescriptor.teamOneScores.joined(separator: ",") teamScoreOne.score = matchDescriptor.teamOneScores.joined(separator: ",")
let teamScoreTwo = teamScore(.two) ?? TeamScore(match: id, team: team(.two)) let teamScoreTwo = teamScore(.two) ?? TeamScore(match: id, team: team(.two))
teamScoreTwo.score = matchDescriptor.teamTwoScores.joined(separator: ",") teamScoreTwo.score = matchDescriptor.teamTwoScores.joined(separator: ",")
self.tournamentStore.teamScores.addOrUpdate(contentOfs: [teamScoreOne, teamScoreTwo]) self.tournamentStore?.teamScores.addOrUpdate(contentOfs: [teamScoreOne, teamScoreTwo])
matchFormat = matchDescriptor.matchFormat matchFormat = matchDescriptor.matchFormat
} }
@ -555,7 +559,7 @@ defer {
let ids = newTeamScores.map { $0.id } let ids = newTeamScores.map { $0.id }
let teamScores = teamScores.filter({ ids.contains($0.id) == false }) let teamScores = teamScores.filter({ ids.contains($0.id) == false })
if teamScores.isEmpty == false { if teamScores.isEmpty == false {
self.tournamentStore.teamScores.delete(contentOfs: teamScores) self.tournamentStore?.teamScores.delete(contentOfs: teamScores)
followingMatch()?.resetTeamScores(outsideOf: []) followingMatch()?.resetTeamScores(outsideOf: [])
_loserMatch()?.resetTeamScores(outsideOf: []) _loserMatch()?.resetTeamScores(outsideOf: [])
} }
@ -578,7 +582,7 @@ defer {
func updateTeamScores() { func updateTeamScores() {
let teams = getOrCreateTeamScores() let teams = getOrCreateTeamScores()
self.tournamentStore.teamScores.addOrUpdate(contentOfs: teams) self.tournamentStore?.teamScores.addOrUpdate(contentOfs: teams)
resetTeamScores(outsideOf: teams) resetTeamScores(outsideOf: teams)
if teams.isEmpty == false { if teams.isEmpty == false {
updateFollowingMatchTeamScore() updateFollowingMatchTeamScore()
@ -732,7 +736,8 @@ defer {
} }
func scores() -> [TeamScore] { func scores() -> [TeamScore] {
return self.tournamentStore.teamScores.filter { $0.match == id } guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.teamScores.filter { $0.match == id }
} }
func teams() -> [TeamRegistration] { func teams() -> [TeamRegistration] {
@ -864,13 +869,12 @@ defer {
var roundObject: Round? { var roundObject: Round? {
guard let round else { return nil } guard let round else { return nil }
return self.tournamentStore.rounds.findById(round) return self.tournamentStore?.rounds.findById(round)
} }
var groupStageObject: GroupStage? { var groupStageObject: GroupStage? {
guard let groupStage else { return nil } guard let groupStage else { return nil }
return self.tournamentStore.groupStages.findById(groupStage) return self.tournamentStore?.groupStages.findById(groupStage)
// self.store?.findById(group)
} }
var isLoserBracket: Bool { var isLoserBracket: Bool {
@ -999,7 +1003,7 @@ defer {
} }
func insertOnServer() { func insertOnServer() {
self.tournamentStore.matches.writeChangeAndInsertOnServer(instance: self) self.tournamentStore?.matches.writeChangeAndInsertOnServer(instance: self)
for teamScore in self.teamScores { for teamScore in self.teamScores {
teamScore.insertOnServer() teamScore.insertOnServer()
} }

@ -58,7 +58,7 @@ final class MatchScheduler: BaseMatchScheduler, SideStorable {
return tournamentObject()?.additionalEstimationDuration ?? 0 return tournamentObject()?.additionalEstimationDuration ?? 0
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return TournamentLibrary.shared.store(tournamentId: self.tournament) return TournamentLibrary.shared.store(tournamentId: self.tournament)
// TournamentStore.instance(tournamentId: self.tournament) // TournamentStore.instance(tournamentId: self.tournament)
} }
@ -120,7 +120,7 @@ final class MatchScheduler: BaseMatchScheduler, SideStorable {
groupStages.filter({ $0.startDate == nil || times.contains($0.startDate!) == false }).chunked(into: computedGroupStageChunkCount).forEach { groups in groupStages.filter({ $0.startDate == nil || times.contains($0.startDate!) == false }).chunked(into: computedGroupStageChunkCount).forEach { groups in
groups.forEach({ $0.startDate = lastDate }) groups.forEach({ $0.startDate = lastDate })
do { do {
try self.tournamentStore.groupStages.addOrUpdate(contentOfs: groups) try self.tournamentStore?.groupStages.addOrUpdate(contentOfs: groups)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -141,7 +141,7 @@ final class MatchScheduler: BaseMatchScheduler, SideStorable {
} }
} }
do { do {
try self.tournamentStore.matches.addOrUpdate(contentOfs: matches) try self.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -739,7 +739,7 @@ final class MatchScheduler: BaseMatchScheduler, SideStorable {
} }
do { do {
try self.tournamentStore.matches.addOrUpdate(contentOfs: allMatches) try self.tournamentStore?.matches.addOrUpdate(contentOfs: allMatches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -124,7 +124,7 @@ final class PlayerRegistration: BasePlayerRegistration, SideStorable {
try super.init(from: decoder) try super.init(from: decoder)
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
guard let storeId else { guard let storeId else {
fatalError("missing store id for \(String(describing: type(of: self)))") fatalError("missing store id for \(String(describing: type(of: self)))")
} }
@ -198,7 +198,7 @@ final class PlayerRegistration: BasePlayerRegistration, SideStorable {
func team() -> TeamRegistration? { func team() -> TeamRegistration? {
guard let teamRegistration else { return nil } guard let teamRegistration else { return nil }
return self.tournamentStore.teamRegistrations.findById(teamRegistration) return self.tournamentStore?.teamRegistrations.findById(teamRegistration)
} }
func isHere() -> Bool { func isHere() -> Bool {
@ -417,7 +417,7 @@ final class PlayerRegistration: BasePlayerRegistration, SideStorable {
} }
func insertOnServer() { func insertOnServer() {
self.tournamentStore.playerRegistrations.writeChangeAndInsertOnServer(instance: self) self.tournamentStore?.playerRegistrations.writeChangeAndInsertOnServer(instance: self)
} }
} }

@ -34,7 +34,7 @@ final class Round: BaseRound, SideStorable {
// MARK: - Computed dependencies // MARK: - Computed dependencies
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return TournamentLibrary.shared.store(tournamentId: self.tournament) return TournamentLibrary.shared.store(tournamentId: self.tournament)
} }
@ -43,13 +43,13 @@ final class Round: BaseRound, SideStorable {
} }
func _matches() -> [Match] { func _matches() -> [Match] {
return self.tournamentStore.matches.filter { $0.round == self.id }.sorted(by: \.index) guard let tournamentStore = self.tournamentStore else { return [] }
// return Store.main.filter { $0.round == self.id } return tournamentStore.matches.filter { $0.round == self.id }.sorted(by: \.index)
} }
func getDisabledMatches() -> [Match] { func getDisabledMatches() -> [Match] {
return self.tournamentStore.matches.filter { $0.round == self.id && $0.disabled == true } guard let tournamentStore = self.tournamentStore else { return [] }
// return Store.main.filter { $0.round == self.id && $0.disabled == true } return tournamentStore.matches.filter { $0.round == self.id && $0.disabled == true }
} }
// MARK: - // MARK: -
@ -86,8 +86,9 @@ final class Round: BaseRound, SideStorable {
func previousMatches(ofMatch match: Match) -> [Match] { func previousMatches(ofMatch match: Match) -> [Match] {
guard let previousRound = previousRound() else { return [] } guard let previousRound = previousRound() else { return [] }
guard let tournamentStore = self.tournamentStore else { return [] }
return self.tournamentStore.matches.filter { return tournamentStore.matches.filter {
$0.round == previousRound.id && ($0.index == match.topPreviousRoundMatchIndex() || $0.index == match.bottomPreviousRoundMatchIndex()) $0.round == previousRound.id && ($0.index == match.topPreviousRoundMatchIndex() || $0.index == match.bottomPreviousRoundMatchIndex())
} }
@ -114,7 +115,7 @@ final class Round: BaseRound, SideStorable {
} }
func seed(_ team: TeamPosition, inMatchIndex matchIndex: Int) -> TeamRegistration? { func seed(_ team: TeamPosition, inMatchIndex matchIndex: Int) -> TeamRegistration? {
return self.tournamentStore.teamRegistrations.first(where: { return self.tournamentStore?.teamRegistrations.first(where: {
$0.bracketPosition != nil $0.bracketPosition != nil
&& ($0.bracketPosition! / 2) == matchIndex && ($0.bracketPosition! / 2) == matchIndex
&& ($0.bracketPosition! % 2) == team.rawValue && ($0.bracketPosition! % 2) == team.rawValue
@ -122,7 +123,8 @@ final class Round: BaseRound, SideStorable {
} }
func seeds(inMatchIndex matchIndex: Int) -> [TeamRegistration] { func seeds(inMatchIndex matchIndex: Int) -> [TeamRegistration] {
return self.tournamentStore.teamRegistrations.filter { guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.teamRegistrations.filter {
$0.tournament == tournament $0.tournament == tournament
&& $0.bracketPosition != nil && $0.bracketPosition != nil
@ -137,9 +139,10 @@ final class Round: BaseRound, SideStorable {
} }
func seeds() -> [TeamRegistration] { func seeds() -> [TeamRegistration] {
guard let tournamentStore = self.tournamentStore else { return [] }
let initialMatchIndex = RoundRule.matchIndex(fromRoundIndex: index) let initialMatchIndex = RoundRule.matchIndex(fromRoundIndex: index)
let numberOfMatches = RoundRule.numberOfMatches(forRoundIndex: index) let numberOfMatches = RoundRule.numberOfMatches(forRoundIndex: index)
return self.tournamentStore.teamRegistrations.filter { return tournamentStore.teamRegistrations.filter {
$0.bracketPosition != nil $0.bracketPosition != nil
&& ($0.bracketPosition! / 2) >= initialMatchIndex && ($0.bracketPosition! / 2) >= initialMatchIndex
&& ($0.bracketPosition! / 2) < initialMatchIndex + numberOfMatches && ($0.bracketPosition! / 2) < initialMatchIndex + numberOfMatches
@ -158,12 +161,12 @@ final class Round: BaseRound, SideStorable {
func losers() -> [TeamRegistration] { func losers() -> [TeamRegistration] {
let teamIds: [String] = self._matches().compactMap { $0.losingTeamId } let teamIds: [String] = self._matches().compactMap { $0.losingTeamId }
return teamIds.compactMap { self.tournamentStore.teamRegistrations.findById($0) } return teamIds.compactMap { self.tournamentStore?.teamRegistrations.findById($0) }
} }
func winners() -> [TeamRegistration] { func winners() -> [TeamRegistration] {
let teamIds: [String] = self._matches().compactMap { $0.winningTeamId } let teamIds: [String] = self._matches().compactMap { $0.winningTeamId }
return teamIds.compactMap { self.tournamentStore.teamRegistrations.findById($0) } return teamIds.compactMap { self.tournamentStore?.teamRegistrations.findById($0) }
} }
func teams() -> [TeamRegistration] { func teams() -> [TeamRegistration] {
@ -188,7 +191,7 @@ defer {
return luckyLoser.team return luckyLoser.team
} else if let previousMatch = topPreviousRoundMatch(ofMatch: match, previousRound: previousRound) { } else if let previousMatch = topPreviousRoundMatch(ofMatch: match, previousRound: previousRound) {
if let teamId = previousMatch.winningTeamId { if let teamId = previousMatch.winningTeamId {
return self.tournamentStore.teamRegistrations.findById(teamId) return self.tournamentStore?.teamRegistrations.findById(teamId)
} else if previousMatch.disabled { } else if previousMatch.disabled {
return previousMatch.teams().first return previousMatch.teams().first
} }
@ -200,7 +203,7 @@ defer {
return luckyLoser.team return luckyLoser.team
} else if let previousMatch = bottomPreviousRoundMatch(ofMatch: match, previousRound: previousRound) { } else if let previousMatch = bottomPreviousRoundMatch(ofMatch: match, previousRound: previousRound) {
if let teamId = previousMatch.winningTeamId { if let teamId = previousMatch.winningTeamId {
return self.tournamentStore.teamRegistrations.findById(teamId) return self.tournamentStore?.teamRegistrations.findById(teamId)
} else if previousMatch.disabled { } else if previousMatch.disabled {
return previousMatch.teams().first return previousMatch.teams().first
} }
@ -265,7 +268,7 @@ defer {
guard let previousRound else { return nil } guard let previousRound else { return nil }
let topPreviousRoundMatchIndex = match.topPreviousRoundMatchIndex() let topPreviousRoundMatchIndex = match.topPreviousRoundMatchIndex()
return self.tournamentStore.matches.first(where: { return self.tournamentStore?.matches.first(where: {
$0.round == previousRound.id && $0.index == topPreviousRoundMatchIndex $0.round == previousRound.id && $0.index == topPreviousRoundMatchIndex
}) })
} }
@ -281,20 +284,21 @@ defer {
guard let previousRound else { return nil } guard let previousRound else { return nil }
let bottomPreviousRoundMatchIndex = match.bottomPreviousRoundMatchIndex() let bottomPreviousRoundMatchIndex = match.bottomPreviousRoundMatchIndex()
return self.tournamentStore.matches.first(where: { return self.tournamentStore?.matches.first(where: {
$0.round == previousRound.id && $0.index == bottomPreviousRoundMatchIndex $0.round == previousRound.id && $0.index == bottomPreviousRoundMatchIndex
}) })
} }
func getMatch(atMatchIndexInRound matchIndexInRound: Int) -> Match? { func getMatch(atMatchIndexInRound matchIndexInRound: Int) -> Match? {
self.tournamentStore.matches.first(where: { self.tournamentStore?.matches.first(where: {
let index = RoundRule.matchIndexWithinRound(fromMatchIndex: $0.index) let index = RoundRule.matchIndexWithinRound(fromMatchIndex: $0.index)
return $0.round == id && index == matchIndexInRound return $0.round == id && index == matchIndexInRound
}) })
} }
func enabledMatches() -> [Match] { func enabledMatches() -> [Match] {
return self.tournamentStore.matches.filter { $0.round == self.id && $0.disabled == false }.sorted(by: \.index) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.matches.filter { $0.round == self.id && $0.disabled == false }.sorted(by: \.index)
} }
// func displayableMatches() -> [Match] { // func displayableMatches() -> [Match] {
@ -331,11 +335,11 @@ defer {
print("func previousRound of: ", id, duration.formatted(.units(allowed: [.seconds, .milliseconds]))) print("func previousRound of: ", id, duration.formatted(.units(allowed: [.seconds, .milliseconds])))
} }
#endif #endif
return self.tournamentStore.rounds.first(where: { $0.parent == parent && $0.index == index + 1 }) return self.tournamentStore?.rounds.first(where: { $0.parent == parent && $0.index == index + 1 })
} }
func nextRound() -> Round? { func nextRound() -> Round? {
return self.tournamentStore.rounds.first(where: { $0.parent == parent && $0.index == index - 1 }) return self.tournamentStore?.rounds.first(where: { $0.parent == parent && $0.index == index - 1 })
} }
func loserRounds(forRoundIndex roundIndex: Int) -> [Round] { func loserRounds(forRoundIndex roundIndex: Int) -> [Round] {
@ -402,7 +406,7 @@ defer {
// Logger.error(error) // Logger.error(error)
// } // }
} }
self.tournamentStore.matches.addOrUpdate(contentOfs: _matches) self.tournamentStore?.matches.addOrUpdate(contentOfs: _matches)
} }
var cumulativeMatchCount: Int { var cumulativeMatchCount: Int {
@ -462,9 +466,12 @@ defer {
} }
#endif #endif
let initialMatchIndexFromRoundIndex = RoundRule.matchIndex(fromRoundIndex: index) let initialMatchIndexFromRoundIndex = RoundRule.matchIndex(fromRoundIndex: index)
let seedsAfterThisRound: [TeamRegistration] = self.tournamentStore.teamRegistrations.filter { var seedsAfterThisRound: [TeamRegistration] = []
$0.bracketPosition != nil if let tournamentStore = tournamentStore {
&& ($0.bracketPosition! / 2) < initialMatchIndexFromRoundIndex seedsAfterThisRound = tournamentStore.teamRegistrations.filter {
$0.bracketPosition != nil
&& ($0.bracketPosition! / 2) < initialMatchIndexFromRoundIndex
}
} }
// let seedsAfterThisRound : [TeamRegistration] = Store.main.filter(isIncluded: { // let seedsAfterThisRound : [TeamRegistration] = Store.main.filter(isIncluded: {
@ -523,9 +530,12 @@ defer {
//print(seedInterval.localizedLabel()) //print(seedInterval.localizedLabel())
return seedInterval return seedInterval
} else { } else {
let seedsAfterThisRound : [TeamRegistration] = self.tournamentStore.teamRegistrations.filter { var seedsAfterThisRound : [TeamRegistration] = []
$0.bracketPosition != nil if let tournamentStore = self.tournamentStore {
&& ($0.bracketPosition! / 2) < initialMatchIndexFromRoundIndex seedsAfterThisRound = tournamentStore.teamRegistrations.filter {
$0.bracketPosition != nil
&& ($0.bracketPosition! / 2) < initialMatchIndexFromRoundIndex
}
} }
var seedsCount = seedsAfterThisRound.count var seedsCount = seedsAfterThisRound.count
@ -594,7 +604,7 @@ defer {
} }
func loserRounds() -> [Round] { func loserRounds() -> [Round] {
guard let tournamentStore = self.tournamentStore else { return [] }
#if _DEBUG_TIME //DEBUGING TIME #if _DEBUG_TIME //DEBUGING TIME
let start = Date() let start = Date()
defer { defer {
@ -603,7 +613,7 @@ defer {
} }
#endif #endif
return self.tournamentStore.rounds.filter( { $0.parent == id }).sorted(by: \.index).reversed() return tournamentStore.rounds.filter( { $0.parent == id }).sorted(by: \.index).reversed()
} }
func loserRoundsAndChildren() -> [Round] { func loserRoundsAndChildren() -> [Round] {
@ -621,7 +631,7 @@ defer {
func deleteLoserBracket() { func deleteLoserBracket() {
let loserRounds = loserRounds() let loserRounds = loserRounds()
self.tournamentStore.rounds.delete(contentOfs: loserRounds) self.tournamentStore?.rounds.delete(contentOfs: loserRounds)
} }
func buildLoserBracket() { func buildLoserBracket() {
@ -640,7 +650,7 @@ defer {
round.parent = id //parent round.parent = id //parent
return round return round
} }
self.tournamentStore.rounds.addOrUpdate(contentOfs: rounds) self.tournamentStore?.rounds.addOrUpdate(contentOfs: rounds)
let matchCount = RoundRule.numberOfMatches(forTeams: currentRoundMatchCount) let matchCount = RoundRule.numberOfMatches(forTeams: currentRoundMatchCount)
let matches = (0..<matchCount).map { //0 is final match let matches = (0..<matchCount).map { //0 is final match
@ -650,7 +660,7 @@ defer {
//initial mode let the roundTitle give a name without considering the playable match //initial mode let the roundTitle give a name without considering the playable match
} }
self.tournamentStore.matches.addOrUpdate(contentOfs: matches) self.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
loserRounds().forEach { round in loserRounds().forEach { round in
round.buildLoserBracket() round.buildLoserBracket()
@ -659,7 +669,7 @@ defer {
var parentRound: Round? { var parentRound: Round? {
guard let parent = parent else { return nil } guard let parent = parent else { return nil }
return self.tournamentStore.rounds.findById(parent) return self.tournamentStore?.rounds.findById(parent)
} }
func nextRoundsDisableMatches() -> Int { func nextRoundsDisableMatches() -> Int {
@ -691,7 +701,7 @@ defer {
playedMatches.forEach { match in playedMatches.forEach { match in
match.matchFormat = updatedMatchFormat match.matchFormat = updatedMatchFormat
} }
self.tournamentStore.matches.addOrUpdate(contentOfs: playedMatches) self.tournamentStore?.matches.addOrUpdate(contentOfs: playedMatches)
} }
override func deleteDependencies() { override func deleteDependencies() {
@ -700,14 +710,14 @@ defer {
match.deleteDependencies() match.deleteDependencies()
} }
self.tournamentStore.matches.deleteDependencies(matches) self.tournamentStore?.matches.deleteDependencies(matches)
let loserRounds = self.loserRounds() let loserRounds = self.loserRounds()
for round in loserRounds { for round in loserRounds {
round.deleteDependencies() round.deleteDependencies()
} }
self.tournamentStore.rounds.deleteDependencies(loserRounds) self.tournamentStore?.rounds.deleteDependencies(loserRounds)
} }
// enum CodingKeys: String, CodingKey { // enum CodingKeys: String, CodingKey {
@ -755,7 +765,7 @@ defer {
// } // }
func insertOnServer() { func insertOnServer() {
self.tournamentStore.rounds.writeChangeAndInsertOnServer(instance: self) self.tournamentStore?.rounds.writeChangeAndInsertOnServer(instance: self)
for match in self._matches() { for match in self._matches() {
match.insertOnServer() match.insertOnServer()
} }

@ -72,21 +72,23 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
try super.init(from: decoder) try super.init(from: decoder)
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return TournamentLibrary.shared.store(tournamentId: self.tournament) return TournamentLibrary.shared.store(tournamentId: self.tournament)
} }
// MARK: - Computed dependencies // MARK: - Computed dependencies
func unsortedPlayers() -> [PlayerRegistration] { func unsortedPlayers() -> [PlayerRegistration] {
return self.tournamentStore.playerRegistrations.filter { $0.teamRegistration == self.id } guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.playerRegistrations.filter { $0.teamRegistration == self.id }
} }
// MARK: - // MARK: -
func deleteTeamScores() { func deleteTeamScores() {
let ts = self.tournamentStore.teamScores.filter({ $0.teamRegistration == id }) guard let tournamentStore = self.tournamentStore else { return }
self.tournamentStore.teamScores.delete(contentOfs: ts) let ts = tournamentStore.teamScores.filter({ $0.teamRegistration == id })
tournamentStore.teamScores.delete(contentOfs: ts)
} }
override func deleteDependencies() { override func deleteDependencies() {
@ -94,19 +96,19 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
for player in unsortedPlayers { for player in unsortedPlayers {
player.deleteDependencies() player.deleteDependencies()
} }
self.tournamentStore.playerRegistrations.deleteDependencies(unsortedPlayers) self.tournamentStore?.playerRegistrations.deleteDependencies(unsortedPlayers)
let teamScores = teamScores() let teamScores = teamScores()
for teamScore in teamScores { for teamScore in teamScores {
teamScore.deleteDependencies() teamScore.deleteDependencies()
} }
self.tournamentStore.teamScores.deleteDependencies(teamScores) self.tournamentStore?.teamScores.deleteDependencies(teamScores)
} }
func hasArrived(isHere: Bool = false) { func hasArrived(isHere: Bool = false) {
let unsortedPlayers = unsortedPlayers() let unsortedPlayers = unsortedPlayers()
unsortedPlayers.forEach({ $0.hasArrived = !isHere }) unsortedPlayers.forEach({ $0.hasArrived = !isHere })
self.tournamentStore.playerRegistrations.addOrUpdate(contentOfs: unsortedPlayers) self.tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: unsortedPlayers)
} }
func isHere() -> Bool { func isHere() -> Bool {
@ -146,7 +148,7 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
if let index = index(in: tournament.selectedSortedTeams()) { if let index = index(in: tournament.selectedSortedTeams()) {
let drawLog = DrawLog(tournament: tournament.id, drawSeed: index, drawMatchIndex: match.index, drawTeamPosition: teamPosition, drawType: .seed) let drawLog = DrawLog(tournament: tournament.id, drawSeed: index, drawMatchIndex: match.index, drawTeamPosition: teamPosition, drawType: .seed)
do { do {
try tournamentStore.drawLogs.addOrUpdate(instance: drawLog) try tournamentStore?.drawLogs.addOrUpdate(instance: drawLog)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -202,19 +204,23 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
} }
func teamScores() -> [TeamScore] { func teamScores() -> [TeamScore] {
return self.tournamentStore.teamScores.filter({ $0.teamRegistration == id }) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.teamScores.filter({ $0.teamRegistration == id })
} }
func wins() -> [Match] { func wins() -> [Match] {
return self.tournamentStore.matches.filter({ $0.winningTeamId == id }) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.matches.filter({ $0.winningTeamId == id })
} }
func loses() -> [Match] { func loses() -> [Match] {
return self.tournamentStore.matches.filter({ $0.losingTeamId == id }) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.matches.filter({ $0.losingTeamId == id })
} }
func matches() -> [Match] { func matches() -> [Match] {
return self.tournamentStore.matches.filter({ $0.losingTeamId == id || $0.winningTeamId == id }) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.matches.filter({ $0.losingTeamId == id || $0.winningTeamId == id })
} }
var tournamentCategory: TournamentCategory { var tournamentCategory: TournamentCategory {
@ -328,10 +334,11 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
} }
func resetGroupeStagePosition() { func resetGroupeStagePosition() {
guard let tournamentStore = self.tournamentStore else { return }
if let groupStage { if let groupStage {
let matches = self.tournamentStore.matches.filter({ $0.groupStage == groupStage }).map { $0.id } let matches = tournamentStore.matches.filter({ $0.groupStage == groupStage }).map { $0.id }
let teamScores = self.tournamentStore.teamScores.filter({ $0.teamRegistration == id && matches.contains($0.match) }) let teamScores = tournamentStore.teamScores.filter({ $0.teamRegistration == id && matches.contains($0.match) })
self.tournamentStore.teamScores.delete(contentOfs: teamScores) tournamentStore.teamScores.delete(contentOfs: teamScores)
} }
//groupStageObject()?._matches().forEach({ $0.updateTeamScores() }) //groupStageObject()?._matches().forEach({ $0.updateTeamScores() })
groupStage = nil groupStage = nil
@ -339,9 +346,10 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
} }
func resetBracketPosition() { func resetBracketPosition() {
let matches = self.tournamentStore.matches.filter({ $0.groupStage == nil }).map { $0.id } guard let tournamentStore = self.tournamentStore else { return }
let teamScores = self.tournamentStore.teamScores.filter({ $0.teamRegistration == id && matches.contains($0.match) }) let matches = tournamentStore.matches.filter({ $0.groupStage == nil }).map { $0.id }
self.tournamentStore.teamScores.delete(contentOfs: teamScores) let teamScores = tournamentStore.teamScores.filter({ $0.teamRegistration == id && matches.contains($0.match) })
tournamentStore.teamScores.delete(contentOfs: teamScores)
self.bracketPosition = nil self.bracketPosition = nil
} }
@ -411,7 +419,7 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
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)
self.tournamentStore.playerRegistrations.delete(contentOfs: playersToRemove) self.tournamentStore?.playerRegistrations.delete(contentOfs: playersToRemove)
setWeight(from: Array(players), inTournamentCategory: tournamentCategory) setWeight(from: Array(players), inTournamentCategory: tournamentCategory)
players.forEach { player in players.forEach { player in
@ -454,8 +462,8 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
typealias AreInIncreasingOrder = (PlayerRegistration, PlayerRegistration) -> Bool typealias AreInIncreasingOrder = (PlayerRegistration, PlayerRegistration) -> Bool
func players() -> [PlayerRegistration] { func players() -> [PlayerRegistration] {
guard let tournamentStore = self.tournamentStore else { return [] }
self.tournamentStore.playerRegistrations.filter { $0.teamRegistration == self.id }.sorted { (lhs, rhs) in return tournamentStore.playerRegistrations.filter { $0.teamRegistration == self.id }.sorted { (lhs, rhs) in
let predicates: [AreInIncreasingOrder] = [ let predicates: [AreInIncreasingOrder] = [
{ $0.sex?.rawValue ?? 0 < $1.sex?.rawValue ?? 0 }, { $0.sex?.rawValue ?? 0 < $1.sex?.rawValue ?? 0 },
{ $0.rank ?? Int.max < $1.rank ?? Int.max }, { $0.rank ?? Int.max < $1.rank ?? Int.max },
@ -503,19 +511,19 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
func groupStageObject() -> GroupStage? { func groupStageObject() -> GroupStage? {
guard let groupStage else { return nil } guard let groupStage else { return nil }
return self.tournamentStore.groupStages.findById(groupStage) return self.tournamentStore?.groupStages.findById(groupStage)
} }
func initialRound() -> Round? { func initialRound() -> Round? {
guard let bracketPosition else { return nil } guard let bracketPosition else { return nil }
let roundIndex = RoundRule.roundIndex(fromMatchIndex: bracketPosition / 2) let roundIndex = RoundRule.roundIndex(fromMatchIndex: bracketPosition / 2)
return self.tournamentStore.rounds.first(where: { $0.index == roundIndex }) return self.tournamentStore?.rounds.first(where: { $0.index == roundIndex })
} }
func initialMatch() -> Match? { func initialMatch() -> Match? {
guard let bracketPosition else { return nil } guard let bracketPosition else { return nil }
guard let initialRoundObject = initialRound() else { return nil } guard let initialRoundObject = initialRound() else { return nil }
return self.tournamentStore.matches.first(where: { $0.round == initialRoundObject.id && $0.index == bracketPosition / 2 }) return self.tournamentStore?.matches.first(where: { $0.round == initialRoundObject.id && $0.index == bracketPosition / 2 })
} }
func toggleSummonConfirmation() { func toggleSummonConfirmation() {
@ -587,7 +595,7 @@ final class TeamRegistration: BaseTeamRegistration, SideStorable {
} }
func insertOnServer() { func insertOnServer() {
self.tournamentStore.teamRegistrations.writeChangeAndInsertOnServer(instance: self) self.tournamentStore?.teamRegistrations.writeChangeAndInsertOnServer(instance: self)
for playerRegistration in self.unsortedPlayers() { for playerRegistration in self.unsortedPlayers() {
playerRegistration.insertOnServer() playerRegistration.insertOnServer()
} }

@ -50,7 +50,7 @@ final class TeamScore: BaseTeamScore, SideStorable {
try super.init(from: decoder) try super.init(from: decoder)
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
guard let storeId else { guard let storeId else {
fatalError("missing store id for \(String(describing: type(of: self)))") fatalError("missing store id for \(String(describing: type(of: self)))")
} }
@ -65,14 +65,14 @@ final class TeamScore: BaseTeamScore, SideStorable {
// MARK: - Computed dependencies // MARK: - Computed dependencies
func matchObject() -> Match? { func matchObject() -> Match? {
return self.tournamentStore.matches.findById(self.match) return self.tournamentStore?.matches.findById(self.match)
} }
var team: TeamRegistration? { var team: TeamRegistration? {
guard let teamRegistration else { guard let teamRegistration else {
return nil return nil
} }
return self.tournamentStore.teamRegistrations.findById(teamRegistration) return self.tournamentStore?.teamRegistrations.findById(teamRegistration)
} }
// MARK: - // MARK: -
@ -107,7 +107,7 @@ final class TeamScore: BaseTeamScore, SideStorable {
// } // }
func insertOnServer() { func insertOnServer() {
self.tournamentStore.teamScores.writeChangeAndInsertOnServer(instance: self) self.tournamentStore?.teamScores.writeChangeAndInsertOnServer(instance: self)
} }
} }

@ -77,31 +77,31 @@ final class Tournament: BaseTournament {
try super.init(from: decoder) try super.init(from: decoder)
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return TournamentLibrary.shared.store(tournamentId: self.id) return TournamentLibrary.shared.store(tournamentId: self.id)
} }
override func deleteDependencies() { override func deleteDependencies() {
let store = self.tournamentStore guard let store = self.tournamentStore else { return }
let drawLogs = Array(self.tournamentStore.drawLogs) let drawLogs = Array(store.drawLogs)
for drawLog in drawLogs { for drawLog in drawLogs {
drawLog.deleteDependencies() drawLog.deleteDependencies()
} }
store.drawLogs.deleteDependencies(drawLogs) store.drawLogs.deleteDependencies(drawLogs)
let teams = self.tournamentStore.teamRegistrations let teams = store.teamRegistrations
for team in Array(teams) { for team in Array(teams) {
team.deleteDependencies() team.deleteDependencies()
} }
store.teamRegistrations.deleteDependencies(teams) store.teamRegistrations.deleteDependencies(teams)
let groups = Array(self.tournamentStore.groupStages) let groups = Array(store.groupStages)
for group in groups { for group in groups {
group.deleteDependencies() group.deleteDependencies()
} }
store.groupStages.deleteDependencies(groups) store.groupStages.deleteDependencies(groups)
let rounds = Array(self.tournamentStore.rounds) let rounds = Array(store.rounds)
for round in rounds { for round in rounds {
round.deleteDependencies() round.deleteDependencies()
} }
@ -120,20 +120,24 @@ final class Tournament: BaseTournament {
// MARK: - Computed Dependencies // MARK: - Computed Dependencies
func unsortedTeams() -> [TeamRegistration] { func unsortedTeams() -> [TeamRegistration] {
return Array(self.tournamentStore.teamRegistrations) guard let tournamentStore = self.tournamentStore else { return [] }
return Array(tournamentStore.teamRegistrations)
} }
func groupStages(atStep step: Int = 0) -> [GroupStage] { func groupStages(atStep step: Int = 0) -> [GroupStage] {
let groupStages: [GroupStage] = self.tournamentStore.groupStages.filter { $0.tournament == self.id && $0.step == step } guard let tournamentStore = self.tournamentStore else { return [] }
let groupStages: [GroupStage] = tournamentStore.groupStages.filter { $0.tournament == self.id && $0.step == step }
return groupStages.sorted(by: \.index) return groupStages.sorted(by: \.index)
} }
func allGroupStages() -> [GroupStage] { func allGroupStages() -> [GroupStage] {
return self.tournamentStore.groupStages.sorted(by: \GroupStage.computedOrder) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.groupStages.sorted(by: \GroupStage.computedOrder)
} }
func allRounds() -> [Round] { func allRounds() -> [Round] {
return Array(self.tournamentStore.rounds) guard let tournamentStore = self.tournamentStore else { return [] }
return Array(tournamentStore.rounds)
} }
// MARK: - // MARK: -
@ -354,7 +358,7 @@ defer {
} }
func getRound(atRoundIndex roundIndex: Int) -> Round? { func getRound(atRoundIndex roundIndex: Int) -> Round? {
return self.tournamentStore.rounds.first(where: { $0.index == roundIndex }) return self.tournamentStore?.rounds.first(where: { $0.index == roundIndex })
// return Store.main.filter(isIncluded: { $0.tournament == id && $0.index == roundIndex }).first // return Store.main.filter(isIncluded: { $0.tournament == id && $0.index == roundIndex }).first
} }
@ -546,15 +550,18 @@ defer {
} }
func allMatches() -> [Match] { func allMatches() -> [Match] {
return self.tournamentStore.matches.filter { $0.disabled == false } guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.matches.filter { $0.disabled == false }
} }
func _allMatchesIncludingDisabled() -> [Match] { func _allMatchesIncludingDisabled() -> [Match] {
return Array(self.tournamentStore.matches) guard let tournamentStore = self.tournamentStore else { return [] }
return Array(tournamentStore.matches)
} }
func rounds() -> [Round] { func rounds() -> [Round] {
let rounds: [Round] = self.tournamentStore.rounds.filter { $0.isUpperBracket() } guard let tournamentStore = self.tournamentStore else { return [] }
let rounds: [Round] = tournamentStore.rounds.filter { $0.isUpperBracket() }
return rounds.sorted(by: \.index).reversed() return rounds.sorted(by: \.index).reversed()
} }
@ -677,12 +684,14 @@ defer {
} }
func unsortedTeamsWithoutWO() -> [TeamRegistration] { func unsortedTeamsWithoutWO() -> [TeamRegistration] {
return self.tournamentStore.teamRegistrations.filter { $0.walkOut == false } guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.teamRegistrations.filter { $0.walkOut == false }
// return Store.main.filter { $0.tournament == self.id && $0.walkOut == false } // return Store.main.filter { $0.tournament == self.id && $0.walkOut == false }
} }
func walkoutTeams() -> [TeamRegistration] { func walkoutTeams() -> [TeamRegistration] {
return self.tournamentStore.teamRegistrations.filter { $0.walkOut == true } guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.teamRegistrations.filter { $0.walkOut == true }
// return Store.main.filter { $0.tournament == self.id && $0.walkOut == true } // return Store.main.filter { $0.tournament == self.id && $0.walkOut == true }
} }
@ -702,7 +711,8 @@ defer {
} }
func unsortedPlayers() -> [PlayerRegistration] { func unsortedPlayers() -> [PlayerRegistration] {
return Array(self.tournamentStore.playerRegistrations) guard let tournamentStore = self.tournamentStore else { return [] }
return Array(tournamentStore.playerRegistrations)
} }
func selectedPlayers() -> [PlayerRegistration] { func selectedPlayers() -> [PlayerRegistration] {
@ -718,7 +728,8 @@ defer {
} }
func players() -> [PlayerRegistration] { func players() -> [PlayerRegistration] {
return self.tournamentStore.playerRegistrations.sorted(by: \.computedRank) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.playerRegistrations.sorted(by: \.computedRank)
} }
func unrankValue(for malePlayer: Bool) -> Int? { func unrankValue(for malePlayer: Bool) -> Int? {
@ -838,8 +849,10 @@ defer {
} }
} }
self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teamsToImport) if let tournamentStore = self.tournamentStore {
self.tournamentStore.playerRegistrations.addOrUpdate(contentOfs: teams.flatMap { $0.players }) tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teamsToImport)
tournamentStore.playerRegistrations.addOrUpdate(contentOfs: teams.flatMap { $0.players })
}
if state() == .build && groupStageCount > 0 && groupStageTeams().isEmpty { if state() == .build && groupStageCount > 0 && groupStageTeams().isEmpty {
setGroupStage(randomize: groupStageSortMode == .random) setGroupStage(randomize: groupStageSortMode == .random)
@ -1020,7 +1033,7 @@ defer {
_removeStrings(from: &teams, stringsToRemove: disabledIds) _removeStrings(from: &teams, stringsToRemove: disabledIds)
teams[interval.last] = disabledIds teams[interval.last] = disabledIds
let teamNames : [String] = disabledIds.compactMap { let teamNames : [String] = disabledIds.compactMap {
let t : TeamRegistration? = tournamentStore.teamRegistrations.findById($0) let t : TeamRegistration? = self.tournamentStore?.teamRegistrations.findById($0)
return t return t
}.map { $0.canonicalName } }.map { $0.canonicalName }
print("winners.isEmpty", "\(interval.last) : ", teamNames) print("winners.isEmpty", "\(interval.last) : ", teamNames)
@ -1033,7 +1046,7 @@ defer {
_removeStrings(from: &teams, stringsToRemove: winners) _removeStrings(from: &teams, stringsToRemove: winners)
teams[interval.first + winners.count - 1] = winners teams[interval.first + winners.count - 1] = winners
let teamNames : [String] = winners.compactMap { let teamNames : [String] = winners.compactMap {
let t: TeamRegistration? = tournamentStore.teamRegistrations.findById($0) let t: TeamRegistration? = tournamentStore?.teamRegistrations.findById($0)
return t return t
}.map { $0.canonicalName } }.map { $0.canonicalName }
print("winners", "\(interval.last + winners.count - 1) : ", teamNames) print("winners", "\(interval.last + winners.count - 1) : ", teamNames)
@ -1044,7 +1057,7 @@ defer {
_removeStrings(from: &teams, stringsToRemove: losers) _removeStrings(from: &teams, stringsToRemove: losers)
teams[interval.first + winners.count] = losers teams[interval.first + winners.count] = losers
let loserTeamNames : [String] = losers.compactMap { let loserTeamNames : [String] = losers.compactMap {
let t: TeamRegistration? = tournamentStore.teamRegistrations.findById($0) let t: TeamRegistration? = tournamentStore?.teamRegistrations.findById($0)
return t return t
}.map { $0.canonicalName } }.map { $0.canonicalName }
print("losers", "\(interval.first + winners.count) : ", loserTeamNames) print("losers", "\(interval.first + winners.count) : ", loserTeamNames)
@ -1088,11 +1101,13 @@ defer {
} }
func setRankings(finalRanks: [Int: [String]]) async -> [Int: [TeamRegistration]] { func setRankings(finalRanks: [Int: [String]]) async -> [Int: [TeamRegistration]] {
guard let tournamentStore = self.tournamentStore else { return [:] }
var rankings: [Int: [TeamRegistration]] = [:] var rankings: [Int: [TeamRegistration]] = [:]
finalRanks.keys.sorted().forEach { rank in finalRanks.keys.sorted().forEach { rank in
if let rankedTeamIds = finalRanks[rank] { if let rankedTeamIds = finalRanks[rank] {
let teams: [TeamRegistration] = rankedTeamIds.compactMap { self.tournamentStore.teamRegistrations.findById($0) } let teams: [TeamRegistration] = rankedTeamIds.compactMap { tournamentStore.teamRegistrations.findById($0) }
rankings[rank] = teams rankings[rank] = teams
} }
} }
@ -1106,7 +1121,7 @@ defer {
} }
} }
self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: unsortedTeams()) tournamentStore.teamRegistrations.addOrUpdate(contentOfs: unsortedTeams())
return rankings return rankings
} }
@ -1121,7 +1136,7 @@ defer {
teams.forEach { team in teams.forEach { team in
team.lockedWeight = team.weight team.lockedWeight = team.weight
} }
self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} }
func unlockRegistration() { func unlockRegistration() {
@ -1130,7 +1145,7 @@ defer {
teams.forEach { team in teams.forEach { team in
team.lockedWeight = nil team.lockedWeight = nil
} }
self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} }
func updateWeights() { func updateWeights() {
@ -1139,9 +1154,9 @@ defer {
let players = team.unsortedPlayers() let players = team.unsortedPlayers()
players.forEach { $0.setComputedRank(in: self) } players.forEach { $0.setComputedRank(in: self) }
team.setWeight(from: players, inTournamentCategory: tournamentCategory) team.setWeight(from: players, inTournamentCategory: tournamentCategory)
self.tournamentStore.playerRegistrations.addOrUpdate(contentOfs: players) self.tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: players)
} }
self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} }
func updateRank(to newDate: Date?) async throws { func updateRank(to newDate: Date?) async throws {
@ -1472,27 +1487,30 @@ defer {
} }
do { do {
try self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: wcs) try self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: wcs)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
} }
func addEmptyTeamRegistration(_ count: Int) { func addEmptyTeamRegistration(_ count: Int) {
guard let tournamentStore = self.tournamentStore else { return }
let teams = (0..<count).map { _ in let teams = (0..<count).map { _ in
let team = TeamRegistration(tournament: id) let team = TeamRegistration(tournament: id)
return team return team
} }
do { do {
try self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
} }
func buildGroupStages() { func buildGroupStages() {
guard groupStages().isEmpty else { guard groupStages().isEmpty, let tournamentStore = self.tournamentStore else {
return return
} }
@ -1502,7 +1520,7 @@ defer {
_groupStages.append(groupStage) _groupStages.append(groupStage)
} }
self.tournamentStore.groupStages.addOrUpdate(contentOfs: _groupStages) tournamentStore.groupStages.addOrUpdate(contentOfs: _groupStages)
refreshGroupStages() refreshGroupStages()
} }
@ -1524,7 +1542,7 @@ defer {
} }
do { do {
try self.tournamentStore.rounds.addOrUpdate(contentOfs: rounds) try self.tournamentStore?.rounds.addOrUpdate(contentOfs: rounds)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -1540,7 +1558,7 @@ defer {
(RoundRule.roundName(fromMatchIndex: $0.index), RoundRule.matchIndexWithinRound(fromMatchIndex: $0.index)) (RoundRule.roundName(fromMatchIndex: $0.index), RoundRule.matchIndexWithinRound(fromMatchIndex: $0.index))
}) })
self.tournamentStore.matches.addOrUpdate(contentOfs: matches) self.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
rounds.forEach { round in rounds.forEach { round in
round.buildLoserBracket() round.buildLoserBracket()
@ -1552,7 +1570,7 @@ defer {
let matchIndex = bracketPosition / 2 let matchIndex = bracketPosition / 2
let roundIndex = RoundRule.roundIndex(fromMatchIndex: matchIndex) let roundIndex = RoundRule.roundIndex(fromMatchIndex: matchIndex)
if let round: Round = self.getRound(atRoundIndex: roundIndex) { if let round: Round = self.getRound(atRoundIndex: roundIndex) {
return self.tournamentStore.matches.first(where: { $0.round == round.id && $0.index == matchIndex }) return self.tournamentStore?.matches.first(where: { $0.round == round.id && $0.index == matchIndex })
// return Store.main.filter(isIncluded: { $0.round == round.id && $0.index == matchIndex }).first // return Store.main.filter(isIncluded: { $0.round == round.id && $0.index == matchIndex }).first
} }
@ -1570,7 +1588,7 @@ defer {
} }
func deleteStructure() { func deleteStructure() {
self.tournamentStore.rounds.delete(contentOfs: rounds()) self.tournamentStore?.rounds.delete(contentOfs: rounds())
} }
func resetBracketPosition() { func resetBracketPosition() {
@ -1578,7 +1596,7 @@ defer {
} }
func deleteGroupStages() { func deleteGroupStages() {
self.tournamentStore.groupStages.delete(contentOfs: allGroupStages()) self.tournamentStore?.groupStages.delete(contentOfs: allGroupStages())
} }
func refreshGroupStages(keepExistingMatches: Bool = false) { func refreshGroupStages(keepExistingMatches: Bool = false) {
@ -1631,7 +1649,7 @@ defer {
} }
} }
self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: unsortedTeams()) self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: unsortedTeams())
} }
func isFree() -> Bool { func isFree() -> Bool {
@ -1792,7 +1810,8 @@ defer {
private let _currentSelectionSorting : [MySortDescriptor<TeamRegistration>] = [.keyPath(\.weight), .keyPath(\.id)] private let _currentSelectionSorting : [MySortDescriptor<TeamRegistration>] = [.keyPath(\.weight), .keyPath(\.id)]
private func _matchSchedulers() -> [MatchScheduler] { private func _matchSchedulers() -> [MatchScheduler] {
return self.tournamentStore.matchSchedulers.filter { $0.tournament == self.id } guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.matchSchedulers.filter { $0.tournament == self.id }
// DataStore.shared.matchSchedulers.filter(isIncluded: { $0.tournament == self.id }) // DataStore.shared.matchSchedulers.filter(isIncluded: { $0.tournament == self.id })
} }
@ -1827,7 +1846,7 @@ defer {
} }
func tournamentWinner() -> TeamRegistration? { func tournamentWinner() -> TeamRegistration? {
let finals: Round? = self.tournamentStore.rounds.first(where: { $0.index == 0 && $0.isUpperBracket() }) let finals: Round? = self.tournamentStore?.rounds.first(where: { $0.index == 0 && $0.isUpperBracket() })
return finals?.playedMatches().first?.winner() return finals?.playedMatches().first?.winner()
} }
@ -1890,7 +1909,7 @@ defer {
} }
func groupStageLoserBracket() -> Round? { func groupStageLoserBracket() -> Round? {
tournamentStore.rounds.first(where: { $0.groupStageLoserBracket }) self.tournamentStore?.rounds.first(where: { $0.groupStageLoserBracket })
} }
func groupStageLoserBracketsInitialPlace() -> Int { func groupStageLoserBracketsInitialPlace() -> Int {
@ -1901,14 +1920,14 @@ defer {
let lastStep = lastStep() + 1 let lastStep = lastStep() + 1
for i in 0..<teamsPerGroupStage { for i in 0..<teamsPerGroupStage {
let gs = GroupStage(tournament: id, index: i, size: groupStageCount, step: lastStep) let gs = GroupStage(tournament: id, index: i, size: groupStageCount, step: lastStep)
tournamentStore.groupStages.addOrUpdate(instance: gs) self.tournamentStore?.groupStages.addOrUpdate(instance: gs)
} }
groupStages(atStep: 1).forEach { $0.buildMatches() } groupStages(atStep: 1).forEach { $0.buildMatches() }
} }
func lastStep() -> Int { func lastStep() -> Int {
self.tournamentStore.groupStages.sorted(by: \.step).last?.step ?? 0 self.tournamentStore?.groupStages.sorted(by: \.step).last?.step ?? 0
} }
func generateSmartLoserGroupStageBracket() { func generateSmartLoserGroupStageBracket() {
@ -1919,7 +1938,7 @@ defer {
let match = Match(round: groupStageLoserBracket.id, index: placeCount, format: groupStageLoserBracket.matchFormat) let match = Match(round: groupStageLoserBracket.id, index: placeCount, format: groupStageLoserBracket.matchFormat)
match.setMatchName("\(placeCount)\(placeCount.ordinalFormattedSuffix(feminine: true)) place") match.setMatchName("\(placeCount)\(placeCount.ordinalFormattedSuffix(feminine: true)) place")
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -1958,7 +1977,8 @@ defer {
} }
func drawLogs() -> [DrawLog] { func drawLogs() -> [DrawLog] {
self.tournamentStore.drawLogs.sorted(by: \.drawDate) guard let tournamentStore = self.tournamentStore else { return [] }
return tournamentStore.drawLogs.sorted(by: \.drawDate)
} }
func seedSpotsLeft() -> Bool { func seedSpotsLeft() -> Bool {
@ -1989,7 +2009,7 @@ defer {
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: seeds) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: seeds)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -2004,12 +2024,12 @@ defer {
} }
do { do {
try tournamentStore.teamScores.delete(contentOfs: ts) try tournamentStore?.teamScores.delete(contentOfs: ts)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: unsortedTeams()) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: unsortedTeams())
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -2028,7 +2048,7 @@ defer {
let matches = (0..<matchCount).map { index in //0 is final match let matches = (0..<matchCount).map { index in //0 is final match
let computedIndex = index + matchStartIndex let computedIndex = index + matchStartIndex
let match = Match(round: round.id, index: computedIndex, format: round.matchFormat) let match = Match(round: round.id, index: computedIndex, format: round.matchFormat)
if let nextRound, let followingMatch = self.tournamentStore.matches.first(where: { $0.round == nextRound.id && $0.index == (computedIndex - 1) / 2 }) { if let nextRound, let followingMatch = self.tournamentStore?.matches.first(where: { $0.round == nextRound.id && $0.index == (computedIndex - 1) / 2 }) {
if followingMatch.disabled { if followingMatch.disabled {
match.disabled = true match.disabled = true
} else if computedIndex%2 == 1 && followingMatch.team(.one) != nil { } else if computedIndex%2 == 1 && followingMatch.team(.one) != nil {
@ -2049,12 +2069,12 @@ defer {
return match return match
} }
do { do {
try tournamentStore.rounds.addOrUpdate(instance: round) try tournamentStore?.rounds.addOrUpdate(instance: round)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
do { do {
try tournamentStore.matches.addOrUpdate(contentOfs: matches) try tournamentStore?.matches.addOrUpdate(contentOfs: matches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -2085,17 +2105,17 @@ defer {
func insertOnServer() throws { func insertOnServer() throws {
DataStore.shared.tournaments.writeChangeAndInsertOnServer(instance: self) // DataStore.shared.tournaments.writeChangeAndInsertOnServer(instance: self)
//
for teamRegistration in self.tournamentStore.teamRegistrations { // for teamRegistration in self.tournamentStore?.teamRegistrations {
teamRegistration.insertOnServer() // teamRegistration.insertOnServer()
} // }
for groupStage in self.tournamentStore.groupStages { // for groupStage in self.tournamentStore?.groupStages {
groupStage.insertOnServer() // groupStage.insertOnServer()
} // }
for round in self.tournamentStore.rounds { // for round in self.tournamentStore.rounds {
round.insertOnServer() // round.insertOnServer()
} // }
} }

@ -14,7 +14,9 @@ class TournamentLibrary {
fileprivate var _stores: [String : TournamentStore] = [:] fileprivate var _stores: [String : TournamentStore] = [:]
func store(tournamentId: String) -> TournamentStore { func store(tournamentId: String) -> TournamentStore? {
guard let tournament = DataStore.shared.tournaments.first(where: { $0.id == tournamentId }) else { return nil }
if let store = self._stores[tournamentId] { if let store = self._stores[tournamentId] {
return store return store
} }

@ -56,7 +56,7 @@ class Patcher {
for tournament in DataStore.shared.tournaments { for tournament in DataStore.shared.tournaments {
let id = tournament.id let id = tournament.id
let store = TournamentLibrary.shared.store(tournamentId: tournament.id) guard let store = TournamentLibrary.shared.store(tournamentId: tournament.id) else { continue }
for round in store.rounds { for round in store.rounds {
round.storeId = id round.storeId = id

@ -15,7 +15,7 @@ struct CallSettingsView: View {
@State private var showSendToAllView: Bool = false @State private var showSendToAllView: Bool = false
@State private var addLink: Bool = false @State private var addLink: Bool = false
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -64,7 +64,7 @@ struct CallSettingsView: View {
team.callDate = nil team.callDate = nil
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -82,7 +82,7 @@ struct CallSettingsView: View {
} }
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -104,7 +104,7 @@ struct CallView: View {
} }
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -130,7 +130,7 @@ struct CallView: View {
} }
} }
do { do {
try self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: calledTeams) try self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: calledTeams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -32,7 +32,7 @@ struct SendToAllView: View {
@State var summonParamByMessage: Bool = false @State var summonParamByMessage: Bool = false
@State var summonParamReSummon: Bool = false @State var summonParamReSummon: Bool = false
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -233,12 +233,14 @@ struct SendToAllView: View {
} }
func _roundTeams() -> [TeamRegistration] { func _roundTeams() -> [TeamRegistration] {
let rounds: [Round] = contactRecipients.compactMap { self.tournamentStore.rounds.findById($0) } guard let tournamentStore = self.tournamentStore else { return [] }
let rounds: [Round] = contactRecipients.compactMap { tournamentStore.rounds.findById($0) }
return rounds.flatMap { $0.teams() } return rounds.flatMap { $0.teams() }
} }
func _groupStagesTeams() -> [TeamRegistration] { func _groupStagesTeams() -> [TeamRegistration] {
let groupStages : [GroupStage] = contactRecipients.compactMap { self.tournamentStore.groupStages.findById($0) } guard let tournamentStore = self.tournamentStore else { return [] }
let groupStages : [GroupStage] = contactRecipients.compactMap { tournamentStore.groupStages.findById($0) }
return groupStages.flatMap { $0.teams() } return groupStages.flatMap { $0.teams() }
} }

@ -117,7 +117,7 @@ struct CallMenuOptionsView: View {
} set: { _ in } set: { _ in
team.toggleSummonConfirmation() team.toggleSummonConfirmation()
do { do {
try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -152,7 +152,7 @@ struct CallMenuOptionsView: View {
RowButtonView("Effacer la date de convocation", role: .destructive) { RowButtonView("Effacer la date de convocation", role: .destructive) {
team.callDate = nil team.callDate = nil
do { do {
try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -165,7 +165,7 @@ struct CallMenuOptionsView: View {
RowButtonView("Indiquer comme convoquée", role: .destructive) { RowButtonView("Indiquer comme convoquée", role: .destructive) {
team.callDate = team.initialMatch()?.startDate ?? tournament.startDate team.callDate = team.initialMatch()?.startDate ?? tournament.startDate
do { do {
try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -137,7 +137,7 @@ struct CashierSettingsView: View {
} }
private func _save(players: [PlayerRegistration]) { private func _save(players: [PlayerRegistration]) {
tournament.tournamentStore.playerRegistrations.addOrUpdate(contentOfs: players) tournament.tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: players)
} }
private func _save() { private func _save() {

@ -29,7 +29,7 @@ struct GroupStageSettingsView: View {
_courtIndex = .init(wrappedValue: groupStage._matches().first?.courtIndex ?? 0) _courtIndex = .init(wrappedValue: groupStage._matches().first?.courtIndex ?? 0)
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -70,7 +70,7 @@ struct GroupStageSettingsView: View {
} }
do { do {
try tournamentStore.matches.addOrUpdate(contentOfs: groupStage._matches()) try tournamentStore?.matches.addOrUpdate(contentOfs: groupStage._matches())
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -93,7 +93,7 @@ struct GroupStageSettingsView: View {
groupStage._matches().forEach({ $0.updateTeamScores() }) groupStage._matches().forEach({ $0.updateTeamScores() })
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -116,7 +116,7 @@ struct GroupStageSettingsView: View {
} }
do { do {
try tournamentStore.matches.addOrUpdate(contentOfs: groupStage._matches()) try tournamentStore?.matches.addOrUpdate(contentOfs: groupStage._matches())
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -132,7 +132,7 @@ struct GroupStageSettingsView: View {
groupStage._matches().forEach({ $0.updateTeamScores() }) groupStage._matches().forEach({ $0.updateTeamScores() })
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -243,7 +243,7 @@ struct GroupStageSettingsView: View {
private func _save() { private func _save() {
do { do {
try tournamentStore.groupStages.addOrUpdate(instance: groupStage) try tournamentStore?.groupStages.addOrUpdate(instance: groupStage)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -23,7 +23,7 @@ struct GroupStageTeamView: View {
let groupStage: GroupStage let groupStage: GroupStage
var team: TeamRegistration var team: TeamRegistration
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -189,7 +189,7 @@ struct GroupStageTeamView: View {
private func _save() { private func _save() {
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -22,7 +22,7 @@ struct GroupStageView: View {
_sortingMode = .init(wrappedValue: groupStage.hasEnded() ? .score : .weight) _sortingMode = .init(wrappedValue: groupStage.hasEnded() ? .score : .weight)
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -118,7 +118,7 @@ struct GroupStageView: View {
let scores: [GroupStage.TeamGroupStageScore]? let scores: [GroupStage.TeamGroupStageScore]?
let teams: [TeamRegistration] let teams: [TeamRegistration]
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -207,7 +207,7 @@ struct GroupStageView: View {
Button { Button {
player.hasArrived.toggle() player.hasArrived.toggle()
do { do {
try self.tournamentStore.playerRegistrations.addOrUpdate(instance: player) try self.tournamentStore?.playerRegistrations.addOrUpdate(instance: player)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -236,7 +236,7 @@ struct GroupStageView: View {
team.groupStagePosition = index team.groupStagePosition = index
groupStage._matches().forEach({ $0.updateTeamScores() }) groupStage._matches().forEach({ $0.updateTeamScores() })
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -266,7 +266,7 @@ struct GroupStageView: View {
private func _save() { private func _save() {
do { do {
try tournamentStore.groupStages.addOrUpdate(instance: groupStage) try tournamentStore?.groupStages.addOrUpdate(instance: groupStage)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -15,7 +15,7 @@ struct GroupStagesSettingsView: View {
@State private var generationDoneMessage: String? @State private var generationDoneMessage: String?
let step: Int let step: Int
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -26,7 +26,7 @@ struct GroupStagesSettingsView: View {
let issues = tournament.groupStageTeamPlacementIssue() let issues = tournament.groupStageTeamPlacementIssue()
DisclosureGroup { DisclosureGroup {
ForEach(issues.shouldBeInIt, id: \.self) { id in ForEach(issues.shouldBeInIt, id: \.self) { id in
if let team: TeamRegistration = self.tournamentStore.teamRegistrations.findById(id) { if let team: TeamRegistration = self.tournamentStore?.teamRegistrations.findById(id) {
TeamRowView(team: team) TeamRowView(team: team)
} }
} }
@ -39,12 +39,12 @@ struct GroupStagesSettingsView: View {
} }
DisclosureGroup { DisclosureGroup {
ForEach(issues.shouldNotBeInIt, id: \.self) { id in ForEach(issues.shouldNotBeInIt, id: \.self) { id in
if let team = self.tournamentStore.teamRegistrations.findById(id) { if let team = self.tournamentStore?.teamRegistrations.findById(id) {
Menu { Menu {
Button("Retirer de sa poule") { Button("Retirer de sa poule") {
team.resetGroupeStagePosition() team.resetGroupeStagePosition()
do { do {
try self.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -80,7 +80,7 @@ struct GroupStagesSettingsView: View {
let round = Round(tournament: tournament.id, index: 0, matchFormat: tournament.loserRoundFormat, groupStageLoserBracket: true) let round = Round(tournament: tournament.id, index: 0, matchFormat: tournament.loserRoundFormat, groupStageLoserBracket: true)
do { do {
try tournamentStore.rounds.addOrUpdate(instance: round) try tournamentStore?.rounds.addOrUpdate(instance: round)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -89,7 +89,7 @@ struct GroupStagesSettingsView: View {
} else if let groupStageLoserBracket = tournament.groupStageLoserBracket() { } else if let groupStageLoserBracket = tournament.groupStageLoserBracket() {
RowButtonView("Supprimer les matchs de classements", role: .destructive) { RowButtonView("Supprimer les matchs de classements", role: .destructive) {
do { do {
try tournamentStore.rounds.delete(instance: groupStageLoserBracket) try tournamentStore?.rounds.delete(instance: groupStageLoserBracket)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -110,7 +110,7 @@ struct GroupStagesSettingsView: View {
RowButtonView("Supprimer cette phase de poule", role: .destructive) { RowButtonView("Supprimer cette phase de poule", role: .destructive) {
let groupStages = tournament.groupStages(atStep: tournament.lastStep()) let groupStages = tournament.groupStages(atStep: tournament.lastStep())
do { do {
try tournament.tournamentStore.groupStages.delete(contentOfs: groupStages) try self.tournamentStore?.groupStages.delete(contentOfs: groupStages)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -138,7 +138,7 @@ struct GroupStagesSettingsView: View {
} }
do { do {
try tournamentStore.matches.addOrUpdate(contentOfs: matches) try tournamentStore?.matches.addOrUpdate(contentOfs: matches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -211,7 +211,7 @@ struct GroupStagesSettingsView: View {
} }
} }
do { do {
try self.tournament.tournamentStore.groupStages.addOrUpdate(contentOfs: groupStages) try self.tournament.tournamentStore?.groupStages.addOrUpdate(contentOfs: groupStages)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -225,7 +225,7 @@ struct GroupStagesSettingsView: View {
groupStage.name = nil groupStage.name = nil
} }
do { do {
try self.tournament.tournamentStore.groupStages.addOrUpdate(contentOfs: groupStages) try self.tournament.tournamentStore?.groupStages.addOrUpdate(contentOfs: groupStages)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -242,7 +242,7 @@ struct GroupStagesSettingsView: View {
groupStage._matches().forEach({ $0.updateTeamScores() }) groupStage._matches().forEach({ $0.updateTeamScores() })
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -124,7 +124,7 @@ struct GroupStagesView: View {
results.forEach { drawResult in results.forEach { drawResult in
missingQualifiedFromGroupStages[drawResult.drawIndex].qualified = true missingQualifiedFromGroupStages[drawResult.drawIndex].qualified = true
do { do {
try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: missingQualifiedFromGroupStages[drawResult.drawIndex]) try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: missingQualifiedFromGroupStages[drawResult.drawIndex])
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -21,7 +21,7 @@ struct LoserBracketFromGroupStageView: View {
_isEditingLoserBracketGroupStage = .init(wrappedValue: loserBracket._matches().isEmpty) _isEditingLoserBracketGroupStage = .init(wrappedValue: loserBracket._matches().isEmpty)
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -110,13 +110,13 @@ struct LoserBracketFromGroupStageView: View {
let match = Match(round: loserBracket.id, index: placeCount, format: loserBracket.matchFormat) let match = Match(round: loserBracket.id, index: placeCount, format: loserBracket.matchFormat)
match.setMatchName("\(placeCount)\(placeCount.ordinalFormattedSuffix()) place") match.setMatchName("\(placeCount)\(placeCount.ordinalFormattedSuffix()) place")
tournamentStore.matches.addOrUpdate(instance: match) tournamentStore?.matches.addOrUpdate(instance: match)
} }
private func _deleteAllMatches() { private func _deleteAllMatches() {
let displayableMatches = loserBracket.playedMatches().sorted(by: \.index) let displayableMatches = loserBracket.playedMatches().sorted(by: \.index)
tournamentStore.matches.delete(contentOfs: displayableMatches) tournamentStore?.matches.delete(contentOfs: displayableMatches)
} }
@ -164,7 +164,7 @@ struct GroupStageLoserBracketMatchFooterView: View {
Spacer() Spacer()
FooterButtonView("Effacer", role: .destructive) { FooterButtonView("Effacer", role: .destructive) {
do { do {
try match.tournamentStore.matches.delete(instance: match) try match.tournamentStore?.matches.delete(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -199,7 +199,7 @@ struct GroupStageLoserBracketMatchFooterView: View {
match.setMatchName("\(newIndexValidated)\(newIndexValidated.ordinalFormattedSuffix()) place") match.setMatchName("\(newIndexValidated)\(newIndexValidated.ordinalFormattedSuffix()) place")
match.tournamentStore.teamScores.addOrUpdate(contentOfs: teamScores) match.tournamentStore?.teamScores.addOrUpdate(contentOfs: teamScores)
match.tournamentStore.matches.addOrUpdate(instance: match) match.tournamentStore?.matches.addOrUpdate(instance: match)
} }
} }

@ -191,7 +191,7 @@ struct MatchDateView: View {
} }
do { do {
try self.match.tournamentStore.matches.addOrUpdate(instance: match) try self.match.tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -38,7 +38,7 @@ struct MatchDetailView: View {
@State private var presentRanking: Bool = false @State private var presentRanking: Bool = false
@State private var confirmScoreEdition: Bool = false @State private var confirmScoreEdition: Bool = false
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return match.tournamentStore return match.tournamentStore
} }
@ -121,8 +121,10 @@ struct MatchDetailView: View {
DisclosureGroup { DisclosureGroup {
ForEach(unpaid) { player in ForEach(unpaid) { player in
LabeledContent { LabeledContent {
PlayerPayView(player: player) if let store = self.tournamentStore {
.environmentObject(tournamentStore) PlayerPayView(player: player)
.environmentObject(store)
}
} label: { } label: {
Text(player.playerLabel()) Text(player.playerLabel())
} }
@ -140,8 +142,12 @@ struct MatchDetailView: View {
menuView menuView
} }
.sheet(isPresented: $showDetails) { .sheet(isPresented: $showDetails) {
MatchTeamDetailView(match: match).tint(.master) if let store = self.tournamentStore {
.environmentObject(tournamentStore) MatchTeamDetailView(match: match).tint(.master)
.environmentObject(store)
} else {
Text("no store")
}
} }
.sheet(isPresented: self.$showSubscriptionView, content: { .sheet(isPresented: self.$showSubscriptionView, content: {
NavigationStack { NavigationStack {
@ -364,7 +370,7 @@ struct MatchDetailView: View {
ForEach(match.teamScores) { teamScore in ForEach(match.teamScores) { teamScore in
Button(role: .destructive) { Button(role: .destructive) {
do { do {
try tournamentStore.teamScores.delete(instance: teamScore) try tournamentStore?.teamScores.delete(instance: teamScore)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -566,7 +572,7 @@ struct MatchDetailView: View {
if match.isReady() == false && match.teams().count == 2 { if match.isReady() == false && match.teams().count == 2 {
let teamsScores = match.getOrCreateTeamScores() let teamsScores = match.getOrCreateTeamScores()
do { do {
try tournamentStore.teamScores.addOrUpdate(contentOfs: teamsScores) try tournamentStore?.teamScores.addOrUpdate(contentOfs: teamsScores)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -615,7 +621,7 @@ struct MatchDetailView: View {
private func _saveMatch() { private func _saveMatch() {
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -69,7 +69,7 @@ struct MatchRowView: View {
Button { Button {
player.hasArrived.toggle() player.hasArrived.toggle()
do { do {
try player.tournamentStore.playerRegistrations.addOrUpdate(instance: player) try player.tournamentStore?.playerRegistrations.addOrUpdate(instance: player)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -16,7 +16,7 @@ struct MatchSetupView: View {
@State var match: Match @State var match: Match
@State private var seedGroup: SeedInterval? @State private var seedGroup: SeedInterval?
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return match.tournamentStore return match.tournamentStore
} }
@ -68,19 +68,19 @@ struct MatchSetupView: View {
if walkOutSpot || team.bracketPosition != nil || matchTypeContext == .loserBracket { if walkOutSpot || team.bracketPosition != nil || matchTypeContext == .loserBracket {
match.setLuckyLoser(team: team, teamPosition: teamPosition) match.setLuckyLoser(team: team, teamPosition: teamPosition)
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
} else if team.bracketPosition == nil { } else if team.bracketPosition == nil {
team.setSeedPosition(inSpot: match, slot: teamPosition, opposingSeeding: false) team.setSeedPosition(inSpot: match, slot: teamPosition, opposingSeeding: false)
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -97,7 +97,7 @@ struct MatchSetupView: View {
if let randomTeam = luckyLosers.randomElement() { if let randomTeam = luckyLosers.randomElement() {
match.setLuckyLoser(team: randomTeam, teamPosition: teamPosition) match.setLuckyLoser(team: randomTeam, teamPosition: teamPosition)
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -112,12 +112,12 @@ struct MatchSetupView: View {
if let randomTeam = availableQualifiedTeams.randomElement() { if let randomTeam = availableQualifiedTeams.randomElement() {
randomTeam.setSeedPosition(inSpot: match, slot: teamPosition, opposingSeeding: false) randomTeam.setSeedPosition(inSpot: match, slot: teamPosition, opposingSeeding: false)
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: randomTeam) try tournamentStore?.teamRegistrations.addOrUpdate(instance: randomTeam)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -132,12 +132,12 @@ struct MatchSetupView: View {
if let randomTeam = tournament.randomSeed(fromSeedGroup: seedGroup) { if let randomTeam = tournament.randomSeed(fromSeedGroup: seedGroup) {
randomTeam.setSeedPosition(inSpot: match, slot: teamPosition, opposingSeeding: false) randomTeam.setSeedPosition(inSpot: match, slot: teamPosition, opposingSeeding: false)
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: randomTeam) try tournamentStore?.teamRegistrations.addOrUpdate(instance: randomTeam)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -158,7 +158,7 @@ struct MatchSetupView: View {
Button { Button {
match.unlockSeedPosition(atTeamPosition: teamPosition) match.unlockSeedPosition(atTeamPosition: teamPosition)
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -170,7 +170,7 @@ struct MatchSetupView: View {
ConfirmButtonView(shouldConfirm: shouldConfirm, message: MatchSetupView.confirmationMessage) { ConfirmButtonView(shouldConfirm: shouldConfirm, message: MatchSetupView.confirmationMessage) {
_ = match.lockAndGetSeedPosition(atTeamPosition: teamPosition) _ = match.lockAndGetSeedPosition(atTeamPosition: teamPosition)
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -193,7 +193,7 @@ struct MatchSetupView: View {
if match.isSeededBy(team: team, inTeamPosition: teamPosition) { if match.isSeededBy(team: team, inTeamPosition: teamPosition) {
if let score = match.teamScore(ofTeam: team) { if let score = match.teamScore(ofTeam: team) {
do { do {
try tournamentStore.teamScores.delete(instance: score) try tournamentStore?.teamScores.delete(instance: score)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -201,7 +201,7 @@ struct MatchSetupView: View {
team.bracketPosition = nil team.bracketPosition = nil
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -209,7 +209,7 @@ struct MatchSetupView: View {
if previousMatch.disabled { if previousMatch.disabled {
previousMatch.enableMatch() previousMatch.enableMatch()
do { do {
try tournamentStore.matches.addOrUpdate(instance: previousMatch) try tournamentStore?.matches.addOrUpdate(instance: previousMatch)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -217,14 +217,14 @@ struct MatchSetupView: View {
} }
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
} else if match.isLoserBracket { } else if match.isLoserBracket {
if let score = match.teamScore(ofTeam: team) { if let score = match.teamScore(ofTeam: team) {
do { do {
try tournamentStore.teamScores.delete(instance: score) try tournamentStore?.teamScores.delete(instance: score)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -232,7 +232,7 @@ struct MatchSetupView: View {
} else { } else {
match.teamWillBeWalkOut(team) match.teamWillBeWalkOut(team)
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -73,17 +73,18 @@ struct ToolboxView: View {
for tournament in dataStore.tournaments { for tournament in dataStore.tournaments {
let store = tournament.tournamentStore if let store = tournament.tournamentStore {
let playerRegistrations = store.playerRegistrations let playerRegistrations = store.playerRegistrations
playerRegistrations.forEach { player in playerRegistrations.forEach { player in
player.firstName = player.firstName.trimmed.capitalized player.firstName = player.firstName.trimmed.capitalized
player.lastName = player.lastName.trimmed.uppercased() player.lastName = player.lastName.trimmed.uppercased()
} }
do { do {
try store.playerRegistrations.addOrUpdate(contentOfs: playerRegistrations) try store.playerRegistrations.addOrUpdate(contentOfs: playerRegistrations)
} catch { } catch {
Logger.error(error) Logger.error(error)
}
} }
} }
@ -95,13 +96,14 @@ struct ToolboxView: View {
for tournament in DataStore.shared.tournaments { for tournament in DataStore.shared.tournaments {
let store: TournamentStore = tournament.tournamentStore if let store: TournamentStore = tournament.tournamentStore {
let teamRegistrations = store.teamRegistrations.filter({ $0.tournamentObject() == nil }) let teamRegistrations = store.teamRegistrations.filter({ $0.tournamentObject() == nil })
do { do {
try store.teamRegistrations.delete(contentOfs: teamRegistrations) try store.teamRegistrations.delete(contentOfs: teamRegistrations)
} catch { } catch {
Logger.error(error) Logger.error(error)
}
} }
} }
} }
@ -112,13 +114,14 @@ struct ToolboxView: View {
RowButtonView("Delete players") { RowButtonView("Delete players") {
for tournament in DataStore.shared.tournaments { for tournament in DataStore.shared.tournaments {
let store: TournamentStore = tournament.tournamentStore if let store: TournamentStore = tournament.tournamentStore {
let playersRegistrations = store.playerRegistrations.filter({ $0.team() == nil }) let playersRegistrations = store.playerRegistrations.filter({ $0.team() == nil })
do { do {
try store.playerRegistrations.delete(contentOfs: playersRegistrations) try store.playerRegistrations.delete(contentOfs: playersRegistrations)
} catch { } catch {
Logger.error(error) Logger.error(error)
}
} }
} }

@ -17,7 +17,7 @@ struct GroupStageScheduleEditorView: View {
@State private var startDate: Date @State private var startDate: Date
@State private var currentDate: Date? @State private var currentDate: Date?
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -42,7 +42,7 @@ struct GroupStageScheduleEditorView: View {
private func _save() { private func _save() {
do { do {
try tournamentStore.groupStages.addOrUpdate(instance: groupStage) try tournamentStore?.groupStages.addOrUpdate(instance: groupStage)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -19,7 +19,7 @@ struct LoserRoundScheduleEditorView: View {
@State private var matchFormat: MatchFormat @State private var matchFormat: MatchFormat
@State private var currentDate: Date? @State private var currentDate: Date?
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -92,7 +92,7 @@ struct LoserRoundScheduleEditorView: View {
private func _save() { private func _save() {
do { do {
try self.tournamentStore.rounds.addOrUpdate(contentOfs: upperRound.loserRounds()) try self.tournamentStore?.rounds.addOrUpdate(contentOfs: upperRound.loserRounds())
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -20,7 +20,7 @@ struct LoserRoundStepScheduleEditorView: View {
@State private var startDate: Date @State private var startDate: Date
//@State private var matchFormat: MatchFormat //@State private var matchFormat: MatchFormat
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -79,7 +79,7 @@ struct LoserRoundStepScheduleEditorView: View {
private func _save() { private func _save() {
do { do {
try tournamentStore.rounds.addOrUpdate(contentOfs: upperRound.loserRounds(forRoundIndex: round.index)) try tournamentStore?.rounds.addOrUpdate(contentOfs: upperRound.loserRounds(forRoundIndex: round.index))
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -14,7 +14,7 @@ struct MatchScheduleEditorView: View {
@State private var startDate: Date @State private var startDate: Date
@State private var currentDate: Date? @State private var currentDate: Date?
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -54,7 +54,7 @@ struct MatchScheduleEditorView: View {
private func _save() { private func _save() {
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -24,7 +24,7 @@ struct PlanningSettingsView: View {
@State private var deletingDateMatchesDone: Bool = false @State private var deletingDateMatchesDone: Bool = false
@State private var deletingDone: Bool = false @State private var deletingDone: Bool = false
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -148,7 +148,7 @@ struct PlanningSettingsView: View {
.headerProminence(.increased) .headerProminence(.increased)
.onAppear { .onAppear {
do { do {
try self.tournamentStore.matchSchedulers.addOrUpdate(instance: matchScheduler) try self.tournamentStore?.matchSchedulers.addOrUpdate(instance: matchScheduler)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -228,7 +228,7 @@ struct PlanningSettingsView: View {
$0.startDate = nil $0.startDate = nil
$0.confirmed = false $0.confirmed = false
}) })
try self.tournamentStore.matches.addOrUpdate(contentOfs: allMatches) try self.tournamentStore?.matches.addOrUpdate(contentOfs: allMatches)
deletingDateMatchesDone = true deletingDateMatchesDone = true
} catch { } catch {
Logger.error(error) Logger.error(error)
@ -245,7 +245,7 @@ struct PlanningSettingsView: View {
do { do {
deletingDone = false deletingDone = false
allGroupStages.forEach({ $0.startDate = nil }) allGroupStages.forEach({ $0.startDate = nil })
try self.tournamentStore.groupStages.addOrUpdate(contentOfs: allGroupStages) try self.tournamentStore?.groupStages.addOrUpdate(contentOfs: allGroupStages)
deletingDone = true deletingDone = true
} catch { } catch {
@ -261,7 +261,7 @@ struct PlanningSettingsView: View {
do { do {
deletingDone = false deletingDone = false
allRounds.forEach({ $0.startDate = nil }) allRounds.forEach({ $0.startDate = nil })
try self.tournamentStore.rounds.addOrUpdate(contentOfs: allRounds) try self.tournamentStore?.rounds.addOrUpdate(contentOfs: allRounds)
deletingDone = true deletingDone = true
} catch { } catch {
Logger.error(error) Logger.error(error)
@ -281,13 +281,13 @@ struct PlanningSettingsView: View {
$0.startDate = nil $0.startDate = nil
$0.confirmed = false $0.confirmed = false
}) })
try self.tournamentStore.matches.addOrUpdate(contentOfs: allMatches) try self.tournamentStore?.matches.addOrUpdate(contentOfs: allMatches)
allGroupStages.forEach({ $0.startDate = nil }) allGroupStages.forEach({ $0.startDate = nil })
try self.tournamentStore.groupStages.addOrUpdate(contentOfs: allGroupStages) try self.tournamentStore?.groupStages.addOrUpdate(contentOfs: allGroupStages)
allRounds.forEach({ $0.startDate = nil }) allRounds.forEach({ $0.startDate = nil })
try self.tournamentStore.rounds.addOrUpdate(contentOfs: allRounds) try self.tournamentStore?.rounds.addOrUpdate(contentOfs: allRounds)
deletingDone = true deletingDone = true
} catch { } catch {
Logger.error(error) Logger.error(error)
@ -308,13 +308,13 @@ struct PlanningSettingsView: View {
$0.endDate = nil $0.endDate = nil
$0.confirmed = false $0.confirmed = false
}) })
try self.tournamentStore.matches.addOrUpdate(contentOfs: tournament.allMatches()) try self.tournamentStore?.matches.addOrUpdate(contentOfs: tournament.allMatches())
allGroupStages.forEach({ $0.startDate = nil }) allGroupStages.forEach({ $0.startDate = nil })
try self.tournamentStore.groupStages.addOrUpdate(contentOfs: allGroupStages) try self.tournamentStore?.groupStages.addOrUpdate(contentOfs: allGroupStages)
allRounds.forEach({ $0.startDate = nil }) allRounds.forEach({ $0.startDate = nil })
try self.tournamentStore.rounds.addOrUpdate(contentOfs: allRounds) try self.tournamentStore?.rounds.addOrUpdate(contentOfs: allRounds)
deletingDone = true deletingDone = true
} catch { } catch {
Logger.error(error) Logger.error(error)
@ -485,7 +485,7 @@ struct PlanningSettingsView: View {
private func _save() { private func _save() {
do { do {
try self.tournamentStore.matchSchedulers.addOrUpdate(instance: matchScheduler) try self.tournamentStore?.matchSchedulers.addOrUpdate(instance: matchScheduler)
try dataStore.tournaments.addOrUpdate(instance: tournament) try dataStore.tournaments.addOrUpdate(instance: tournament)
} catch { } catch {
Logger.error(error) Logger.error(error)

@ -97,7 +97,7 @@ struct PlanningView: View {
ToolbarItem(placement: .topBarTrailing) { ToolbarItem(placement: .topBarTrailing) {
Button("Sauver") { Button("Sauver") {
do { do {
try self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: allMatches) try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: allMatches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -503,7 +503,7 @@ struct PlanningView: View {
// } // }
// } // }
// //
// try? self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: matches) // try? self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
// } // }
// //
// //

@ -16,7 +16,7 @@ struct RoundScheduleEditorView: View {
@State private var startDate: Date @State private var startDate: Date
@State private var currentDate: Date? @State private var currentDate: Date?
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -71,7 +71,7 @@ struct RoundScheduleEditorView: View {
private func _save() { private func _save() {
do { do {
try tournamentStore.rounds.addOrUpdate(instance: round) try tournamentStore?.rounds.addOrUpdate(instance: round)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -26,7 +26,7 @@ struct SchedulerView: View {
var tournament: Tournament var tournament: Tournament
var destination: ScheduleDestination var destination: ScheduleDestination
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -49,7 +49,7 @@ struct SchedulerView: View {
} }
do { do {
try dataStore.tournaments.addOrUpdate(instance: tournament) try dataStore.tournaments.addOrUpdate(instance: tournament)
try self.tournamentStore.groupStages.addOrUpdate(contentOfs: groupStages) try self.tournamentStore?.groupStages.addOrUpdate(contentOfs: groupStages)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -90,7 +90,7 @@ struct SchedulerView: View {
do { do {
try dataStore.tournaments.addOrUpdate(instance: tournament) try dataStore.tournaments.addOrUpdate(instance: tournament)
try self.tournamentStore.groupStages.addOrUpdate(contentOfs: groupStages) try self.tournamentStore?.groupStages.addOrUpdate(contentOfs: groupStages)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -131,7 +131,7 @@ struct SchedulerView: View {
Button { Button {
round.updateMatchFormatAndAllMatches(federalFormat) round.updateMatchFormatAndAllMatches(federalFormat)
do { do {
try self.tournamentStore.rounds.addOrUpdate(instance: round) try self.tournamentStore?.rounds.addOrUpdate(instance: round)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -176,7 +176,7 @@ struct SchedulerView: View {
Button { Button {
round.updateMatchFormatAndAllMatches(federalFormat) round.updateMatchFormatAndAllMatches(federalFormat)
do { do {
try self.tournamentStore.rounds.addOrUpdate(instance: round) try self.tournamentStore?.rounds.addOrUpdate(instance: round)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -14,7 +14,7 @@ struct PlayerSexPickerView: View {
@Environment(Tournament.self) var tournament: Tournament @Environment(Tournament.self) var tournament: Tournament
@Bindable var player: PlayerRegistration @Bindable var player: PlayerRegistration
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -38,10 +38,10 @@ struct PlayerSexPickerView: View {
private func _save() { private func _save() {
player.setComputedRank(in: tournament) player.setComputedRank(in: tournament)
tournamentStore.playerRegistrations.addOrUpdate(instance: player) tournamentStore?.playerRegistrations.addOrUpdate(instance: player)
if let team = player.team() { if let team = player.team() {
team.updateWeight(inTournamentCategory: tournament.tournamentCategory) team.updateWeight(inTournamentCategory: tournament.tournamentCategory)
tournamentStore.teamRegistrations.addOrUpdate(instance: team) tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} }
} }

@ -19,7 +19,7 @@ struct PlayerDetailView: View {
@State private var email: String @State private var email: String
@FocusState var focusedField: PlayerRegistration.CodingKeys? @FocusState var focusedField: PlayerRegistration.CodingKeys?
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -257,13 +257,13 @@ struct PlayerDetailView: View {
private func _save() { private func _save() {
do { do {
try self.tournamentStore.playerRegistrations.addOrUpdate(instance: player) try self.tournamentStore?.playerRegistrations.addOrUpdate(instance: player)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
if let team = player.team() { if let team = player.team() {
do { do {
try self.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -15,7 +15,7 @@ struct PlayerView: View {
let player: PlayerRegistration let player: PlayerRegistration
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -24,7 +24,7 @@ struct PlayerView: View {
.swipeActions(edge: .trailing, allowsFullSwipe: true) { .swipeActions(edge: .trailing, allowsFullSwipe: true) {
Button(role: .destructive) { Button(role: .destructive) {
do { do {
try self.tournamentStore.playerRegistrations.delete(instance: player) try self.tournamentStore?.playerRegistrations.delete(instance: player)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -52,7 +52,7 @@ struct DrawLogsView: View {
Button("Tout effacer", role: .destructive) { Button("Tout effacer", role: .destructive) {
do { do {
try tournament.tournamentStore.drawLogs.deleteAll() try tournament.tournamentStore?.drawLogs.deleteAll()
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -64,7 +64,7 @@ struct LoserRoundSettingsView: View {
}) })
allRoundMatches.forEach({ $0.setMatchName($0.roundTitle()) }) allRoundMatches.forEach({ $0.setMatchName($0.roundTitle()) })
do { do {
try self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: allRoundMatches) try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: allRoundMatches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -121,13 +121,13 @@ struct LoserRoundSettingsView: View {
} }
do { do {
try self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: matches) try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
do { do {
try self.tournament.tournamentStore.rounds.addOrUpdate(instance: upperBracketRound.round) try self.tournament.tournamentStore?.rounds.addOrUpdate(instance: upperBracketRound.round)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -145,7 +145,7 @@ struct LoserRoundSettingsView: View {
match._toggleLoserMatchDisableState(true) match._toggleLoserMatchDisableState(true)
} }
do { do {
try self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: upperBracketRound.round.allLoserRoundMatches()) try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: upperBracketRound.round.allLoserRoundMatches())
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -133,7 +133,7 @@ struct LoserRoundView: View {
let allRoundMatches = loserBracket.allMatches.filter({ $0.name == nil }) let allRoundMatches = loserBracket.allMatches.filter({ $0.name == nil })
allRoundMatches.forEach({ $0.setMatchName($0.roundTitle()) }) allRoundMatches.forEach({ $0.setMatchName($0.roundTitle()) })
do { do {
try self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: allRoundMatches) try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: allRoundMatches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -14,7 +14,7 @@ struct RoundSettingsView: View {
@Environment(\.isEditingTournamentSeed) private var isEditingTournamentSeed @Environment(\.isEditingTournamentSeed) private var isEditingTournamentSeed
@Environment(Tournament.self) var tournament: Tournament @Environment(Tournament.self) var tournament: Tournament
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -25,7 +25,7 @@ struct RoundSettingsView: View {
let issues = tournament.bracketTeamPlacementIssue() let issues = tournament.bracketTeamPlacementIssue()
DisclosureGroup { DisclosureGroup {
ForEach(issues.shouldBeInIt, id: \.self) { id in ForEach(issues.shouldBeInIt, id: \.self) { id in
if let team: TeamRegistration = self.tournamentStore.teamRegistrations.findById(id) { if let team: TeamRegistration = self.tournamentStore?.teamRegistrations.findById(id) {
TeamRowView(team: team) TeamRowView(team: team)
} }
} }
@ -38,11 +38,11 @@ struct RoundSettingsView: View {
} }
DisclosureGroup { DisclosureGroup {
ForEach(issues.shouldNotBeInIt, id: \.self) { id in ForEach(issues.shouldNotBeInIt, id: \.self) { id in
if let team = self.tournamentStore.teamRegistrations.findById(id) { if let team = self.tournamentStore?.teamRegistrations.findById(id) {
Menu { Menu {
Button("Retirer du tableau") { Button("Retirer du tableau") {
team.resetBracketPosition() team.resetBracketPosition()
self.tournamentStore.teamRegistrations.addOrUpdate(instance: team) self.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} }
} label: { } label: {
TeamRowView(team: team) TeamRowView(team: team)
@ -128,7 +128,7 @@ struct RoundSettingsView: View {
let allRoundMatches = tournament.allLoserRoundMatches() let allRoundMatches = tournament.allLoserRoundMatches()
allRoundMatches.forEach({ $0.setMatchName($0.roundTitle()) }) allRoundMatches.forEach({ $0.setMatchName($0.roundTitle()) })
do { do {
try self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: allRoundMatches) try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: allRoundMatches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -164,8 +164,8 @@ struct RoundSettingsView: View {
teams.forEach { team in teams.forEach { team in
team.resetBracketPosition() team.resetBracketPosition()
} }
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
try tournamentStore.rounds.delete(instance: lastRound) try tournamentStore?.rounds.delete(instance: lastRound)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -30,7 +30,7 @@ struct RoundView: View {
BracketEditTip.matchesHidden = upperRound.round.getDisabledMatches().count BracketEditTip.matchesHidden = upperRound.round.getDisabledMatches().count
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -242,7 +242,7 @@ struct RoundView: View {
FooterButtonView("Désactiver", role: .destructive) { FooterButtonView("Désactiver", role: .destructive) {
match.disableMatch() match.disableMatch()
do { do {
try tournamentStore.matches.addOrUpdate(instance: match) try tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -327,7 +327,7 @@ struct RoundView: View {
private func _save(seeds: [TeamRegistration]) { private func _save(seeds: [TeamRegistration]) {
do { do {
try self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: seeds) try self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: seeds)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -365,7 +365,7 @@ struct RoundView: View {
} }
do { do {
try tournament.tournamentStore.matches.addOrUpdate(contentOfs: matchesToUpdate + loserMatches) try tournament.tournamentStore?.matches.addOrUpdate(contentOfs: matchesToUpdate + loserMatches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -207,7 +207,7 @@ struct EditScoreView: View {
self.confirmScoreEdition = true self.confirmScoreEdition = true
if let match = matchDescriptor.match { if let match = matchDescriptor.match {
do { do {
try match.tournamentStore.matches.addOrUpdate(instance: match) try match.tournamentStore?.matches.addOrUpdate(instance: match)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -50,7 +50,7 @@ struct CoachListView: View {
private func _save() { private func _save() {
do { do {
try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -33,7 +33,7 @@ struct EditingTeamView: View {
} }
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -100,7 +100,7 @@ struct EditingTeamView: View {
team.walkOut = false team.walkOut = false
team.wildCardBracket = value team.wildCardBracket = value
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -116,7 +116,7 @@ struct EditingTeamView: View {
team.walkOut = false team.walkOut = false
team.wildCardGroupStage = value team.wildCardGroupStage = value
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -132,7 +132,7 @@ struct EditingTeamView: View {
team.wildCardGroupStage = false team.wildCardGroupStage = false
team.walkOut = value team.walkOut = value
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -195,7 +195,7 @@ struct EditingTeamView: View {
RowButtonView("Effacer l'équipe", role: .destructive, systemImage: "trash") { RowButtonView("Effacer l'équipe", role: .destructive, systemImage: "trash") {
team.deleteTeamScores() team.deleteTeamScores()
do { do {
try tournamentStore.teamRegistrations.delete(instance: team) try tournamentStore?.teamRegistrations.delete(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -303,7 +303,7 @@ struct EditingTeamView: View {
} set: { confirmed in } set: { confirmed in
team.confirmationDate = confirmed ? Date() : nil team.confirmationDate = confirmed ? Date() : nil
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -318,7 +318,7 @@ struct EditingTeamView: View {
$0.hasArrived = hasArrived $0.hasArrived = hasArrived
} }
do { do {
try tournamentStore.playerRegistrations.addOrUpdate(contentOfs: team.unsortedPlayers()) try tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: team.unsortedPlayers())
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -327,7 +327,7 @@ struct EditingTeamView: View {
} }
private func _save() { private func _save() {
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(instance: team) try tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -105,7 +105,7 @@ struct FileImportView: View {
_fileProvider = .init(wrappedValue: defaultFileProvider) _fileProvider = .init(wrappedValue: defaultFileProvider)
} }
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -123,7 +123,7 @@ struct FileImportView: View {
private func _deleteTeams() async { private func _deleteTeams() async {
await MainActor.run { await MainActor.run {
do { do {
try tournamentStore.teamRegistrations.delete(contentOfs: tournament.unsortedTeams()) try tournamentStore?.teamRegistrations.delete(contentOfs: tournament.unsortedTeams())
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -509,7 +509,7 @@ struct FileImportView: View {
} }
do { do {
try tournament.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: unfound) try tournament.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: unfound)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -46,7 +46,7 @@ struct AddTeamView: View {
@State private var testMessageIndex: Int = 0 @State private var testMessageIndex: Int = 0
@State private var presentLocalMultiplayerSearch: Bool = false @State private var presentLocalMultiplayerSearch: Bool = false
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -361,8 +361,8 @@ struct AddTeamView: View {
} }
let team = tournament.addTeam(players) let team = tournament.addTeam(players)
self.tournamentStore.teamRegistrations.addOrUpdate(instance: team) self.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
self.tournamentStore.playerRegistrations.addOrUpdate(contentOfs: players) self.tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: players)
pasteString = nil pasteString = nil
editableTextField = "" editableTextField = ""
@ -389,8 +389,8 @@ struct AddTeamView: View {
let players = _currentSelection() let players = _currentSelection()
editedTeam.updatePlayers(players, inTournamentCategory: tournament.tournamentCategory) editedTeam.updatePlayers(players, inTournamentCategory: tournament.tournamentCategory)
self.tournamentStore.teamRegistrations.addOrUpdate(instance: editedTeam) self.tournamentStore?.teamRegistrations.addOrUpdate(instance: editedTeam)
self.tournamentStore.playerRegistrations.addOrUpdate(contentOfs: players) self.tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: players)
pasteString = nil pasteString = nil
editableTextField = "" editableTextField = ""

@ -224,13 +224,15 @@ struct InscriptionInfoView: View {
Section { Section {
DisclosureGroup { DisclosureGroup {
ForEach(playersWithoutValidLicense) { ForEach(playersWithoutValidLicense) {
EditablePlayerView(player: $0, editingOptions: [.licenceId]) if let store = tournament.tournamentStore {
.environmentObject(tournament.tournamentStore) EditablePlayerView(player: $0, editingOptions: [.licenceId])
.onChange(of: $0.licenceId) { .environmentObject(store)
players = tournament.unsortedPlayers() .onChange(of: $0.licenceId) {
let isImported = players.anySatisfy({ $0.isImported() }) players = tournament.unsortedPlayers()
playersWithoutValidLicense = tournament.playersWithoutValidLicense(in: players, isImported: isImported) let isImported = players.anySatisfy({ $0.isImported() })
} playersWithoutValidLicense = tournament.playersWithoutValidLicense(in: players, isImported: isImported)
}
}
} }
} label: { } label: {
LabeledContent { LabeledContent {

@ -225,14 +225,14 @@ struct TournamentGeneralSettingsView: View {
} }
do { do {
try self.tournament.tournamentStore.matches.addOrUpdate(contentOfs: matches) try self.tournament.tournamentStore?.matches.addOrUpdate(contentOfs: matches)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
} }
do { do {
try self.tournament.tournamentStore.rounds.addOrUpdate(contentOfs: rounds) try self.tournament.tournamentStore?.rounds.addOrUpdate(contentOfs: rounds)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -17,7 +17,7 @@ struct TournamentMatchFormatsSettingsView: View {
@State private var confirmUpdate: Bool = false @State private var confirmUpdate: Bool = false
@State private var updateCompleted: Bool = false @State private var updateCompleted: Bool = false
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -99,12 +99,12 @@ struct TournamentMatchFormatsSettingsView: View {
} }
} }
do { do {
try tournamentStore.groupStages.addOrUpdate(contentOfs: groupStages) try tournamentStore?.groupStages.addOrUpdate(contentOfs: groupStages)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
do { do {
try tournamentStore.rounds.addOrUpdate(contentOfs: allRounds) try tournamentStore?.rounds.addOrUpdate(contentOfs: allRounds)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -17,7 +17,7 @@ struct UpdateSourceRankDateView: View {
@State private var updatingRank = false @State private var updatingRank = false
var tournament: Tournament var tournament: Tournament
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -48,7 +48,7 @@ struct UpdateSourceRankDateView: View {
player.setComputedRank(in: tournament) player.setComputedRank(in: tournament)
} }
try tournamentStore.playerRegistrations.addOrUpdate(contentOfs: tournament.unsortedPlayers()) try tournamentStore?.playerRegistrations.addOrUpdate(contentOfs: tournament.unsortedPlayers())
tournament.unsortedTeams().forEach { team in tournament.unsortedTeams().forEach { team in
team.setWeight(from: team.players(), inTournamentCategory: tournament.tournamentCategory) team.setWeight(from: team.players(), inTournamentCategory: tournament.tournamentCategory)
@ -57,7 +57,7 @@ struct UpdateSourceRankDateView: View {
} }
} }
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: tournament.unsortedTeams()) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: tournament.unsortedTeams())
try dataStore.tournaments.addOrUpdate(instance: tournament) try dataStore.tournaments.addOrUpdate(instance: tournament)

@ -50,7 +50,7 @@ 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
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -195,7 +195,7 @@ struct InscriptionManagerView: View {
} }
do { do {
try tournamentStore.teamRegistrations.addOrUpdate(contentOfs: waitingList) try tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: waitingList)
try dataStore.tournaments.addOrUpdate(instance: tournament) try dataStore.tournaments.addOrUpdate(instance: tournament)
} catch { } catch {
Logger.error(error) Logger.error(error)
@ -979,7 +979,7 @@ struct InscriptionManagerView: View {
Button(role: .destructive) { Button(role: .destructive) {
team.deleteTeamScores() team.deleteTeamScores()
do { do {
try tournamentStore.teamRegistrations.delete(instance: team) try tournamentStore?.teamRegistrations.delete(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -388,7 +388,7 @@ struct TableStructureView: View {
team.groupStage = nil team.groupStage = nil
} }
do { do {
try tournament.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: teams) try tournament.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: teams)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

@ -137,33 +137,37 @@ struct TournamentCashierView: View {
} }
var body: some View { var body: some View {
VStack(spacing: 0) { if let store = self.tournament.tournamentStore {
GenericDestinationPickerView(selectedDestination: $selectedDestination, destinations: allDestinations, nilDestinationIsValid: true) VStack(spacing: 0) {
switch selectedDestination { GenericDestinationPickerView(selectedDestination: $selectedDestination, destinations: allDestinations, nilDestinationIsValid: true)
case .none: switch selectedDestination {
CashierSettingsView(tournament: tournament) case .none:
case .some(let selectedCall): CashierSettingsView(tournament: tournament)
switch selectedCall { case .some(let selectedCall):
case .summary: switch selectedCall {
CashierDetailView(tournament: tournament).id(selectedCall.id) case .summary:
case .groupStage(let groupStage): CashierDetailView(tournament: tournament).id(selectedCall.id)
CashierView(tournament: tournament, teams: groupStage.teams()).id(selectedCall.id) case .groupStage(let groupStage):
.searchable(text: $cashierViewModel.searchText, isPresented: $cashierViewModel.isSearching, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Chercher un joueur")) CashierView(tournament: tournament, teams: groupStage.teams()).id(selectedCall.id)
case .bracket(let round): .searchable(text: $cashierViewModel.searchText, isPresented: $cashierViewModel.isSearching, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Chercher un joueur"))
CashierView(tournament: tournament, teams: round.seeds()).id(selectedCall.id) case .bracket(let round):
.searchable(text: $cashierViewModel.searchText, isPresented: $cashierViewModel.isSearching, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Chercher un joueur")) CashierView(tournament: tournament, teams: round.seeds()).id(selectedCall.id)
case .all(let tournament): .searchable(text: $cashierViewModel.searchText, isPresented: $cashierViewModel.isSearching, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Chercher un joueur"))
CashierView(tournament: tournament, teams: tournament.selectedSortedTeams()).id(selectedCall.id) case .all(let tournament):
.searchable(text: $cashierViewModel.searchText, isPresented: $cashierViewModel.isSearching, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Chercher un joueur")) CashierView(tournament: tournament, teams: tournament.selectedSortedTeams()).id(selectedCall.id)
.searchable(text: $cashierViewModel.searchText, isPresented: $cashierViewModel.isSearching, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Chercher un joueur"))
}
} }
} }
.environment(tournament)
.environmentObject(store)
.environmentObject(cashierViewModel)
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.visible, for: .navigationBar)
.navigationTitle(tournament.isFree() ? "Présence" : "Encaissement")
} else {
Text("no store")
} }
.environment(tournament)
.environmentObject(tournament.tournamentStore)
.environmentObject(cashierViewModel)
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.visible, for: .navigationBar)
.navigationTitle(tournament.isFree() ? "Présence" : "Encaissement")
} }
} }

@ -17,7 +17,7 @@ struct TournamentRankView: View {
@State private var calculating = false @State private var calculating = false
@State private var selectedTeam: TeamRegistration? @State private var selectedTeam: TeamRegistration?
var tournamentStore: TournamentStore { var tournamentStore: TournamentStore? {
return self.tournament.tournamentStore return self.tournament.tournamentStore
} }
@ -118,7 +118,7 @@ struct TournamentRankView: View {
Button("Valider") { Button("Valider") {
selectedTeam.pointsEarned = tournament.isAnimation() ? nil : tournament.tournamentLevel.points(for: selectedTeam.finalRanking! - 1, count: tournament.teamCount) selectedTeam.pointsEarned = tournament.isAnimation() ? nil : tournament.tournamentLevel.points(for: selectedTeam.finalRanking! - 1, count: tournament.teamCount)
do { do {
try self.tournamentStore.teamRegistrations.addOrUpdate(instance: selectedTeam) try self.tournamentStore?.teamRegistrations.addOrUpdate(instance: selectedTeam)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -171,7 +171,7 @@ struct TournamentRankView: View {
team.finalRanking = key team.finalRanking = key
team.pointsEarned = tournament.isAnimation() ? nil : tournament.tournamentLevel.points(for: key - 1, count: tournament.teamCount) team.pointsEarned = tournament.isAnimation() ? nil : tournament.tournamentLevel.points(for: key - 1, count: tournament.teamCount)
do { do {
try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -273,7 +273,7 @@ struct TournamentRankView: View {
team.pointsEarned = tournament.isAnimation() ? nil : tournament.tournamentLevel.points(for: key - 1, count: tournament.teamCount) team.pointsEarned = tournament.isAnimation() ? nil : tournament.tournamentLevel.points(for: key - 1, count: tournament.teamCount)
do { do {
try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -289,7 +289,7 @@ struct TournamentRankView: View {
Button("Valider") { Button("Valider") {
team.pointsEarned = tournament.isAnimation() ? nil : tournament.tournamentLevel.points(for: key - 1, count: tournament.teamCount) team.pointsEarned = tournament.isAnimation() ? nil : tournament.tournamentLevel.points(for: key - 1, count: tournament.teamCount)
do { do {
try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: team) try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
} catch { } catch {
Logger.error(error) Logger.error(error)
} }
@ -317,7 +317,7 @@ struct TournamentRankView: View {
private func _save() { private func _save() {
do { do {
try self.tournamentStore.teamRegistrations.addOrUpdate(contentOfs: tournament.unsortedTeams()) try self.tournamentStore?.teamRegistrations.addOrUpdate(contentOfs: tournament.unsortedTeams())
} catch { } catch {
Logger.error(error) Logger.error(error)
} }

Loading…
Cancel
Save