Make insert method to send events on the server when a creator has been set

multistore
Laurent 1 year ago
parent fc1ea85c7c
commit f3f2ebd032
  1. 4
      PadelClub/Data/DateInterval.swift
  2. 5
      PadelClub/Data/Event.swift
  3. 27
      PadelClub/Data/GroupStage.swift
  4. 29
      PadelClub/Data/Match.swift
  5. 5
      PadelClub/Data/PlayerRegistration.swift
  6. 29
      PadelClub/Data/Round.swift
  7. 27
      PadelClub/Data/TeamRegistration.swift
  8. 16
      PadelClub/Data/TeamScore.swift
  9. 135
      PadelClub/Data/Tournament.swift

@ -54,4 +54,8 @@ class DateInterval: ModelObject, Storable {
case _endDate = "endDate" case _endDate = "endDate"
} }
func insertOnServer() throws {
try DataStore.shared.dateIntervals.writeChangeAndInsertOnServer(instance: self)
}
} }

@ -84,7 +84,10 @@ class Event: ModelObject, Storable {
func insertOnServer() throws { func insertOnServer() throws {
try DataStore.shared.events.writeChangeAndInsertOnServer(instance: self) try DataStore.shared.events.writeChangeAndInsertOnServer(instance: self)
for tournament in self.tournaments { for tournament in self.tournaments {
// try tournament.insertOnServer() try tournament.insertOnServer()
}
for dataInterval in self.courtsUnavailability {
try dataInterval.insertOnServer()
} }
} }

@ -1,5 +1,5 @@
// //
// GroupStage_v2.swift // GroupStage.swift
// Padel Tournament // Padel Tournament
// //
// Created by razmig on 10/03/2024. // Created by razmig on 10/03/2024.
@ -41,12 +41,20 @@ class GroupStage: ModelObject, Storable {
self.name = name self.name = name
} }
func teamAt(groupStagePosition: Int) -> TeamRegistration? { // MARK: - Computed dependencies
teams().first(where: { $0.groupStagePosition == groupStagePosition })
func _matches() -> [Match] {
Store.main.filter { $0.groupStage == self.id }
} }
func tournamentObject() -> Tournament? { func tournamentObject() -> Tournament? {
Store.main.findById(tournament) Store.main.findById(self.tournament)
}
// MARK: -
func teamAt(groupStagePosition: Int) -> TeamRegistration? {
teams().first(where: { $0.groupStagePosition == groupStagePosition })
} }
func groupStageTitle(_ displayStyle: DisplayStyle = .wide) -> String { func groupStageTitle(_ displayStyle: DisplayStyle = .wide) -> String {
@ -244,10 +252,6 @@ class GroupStage: ModelObject, Storable {
(size * (size - 1)) / 2 (size * (size - 1)) / 2
} }
func _matches() -> [Match] {
Store.main.filter { $0.groupStage == self.id }
}
func unsortedPlayers() -> [PlayerRegistration] { func unsortedPlayers() -> [PlayerRegistration] {
unsortedTeams().flatMap({ $0.unsortedPlayers() }) unsortedTeams().flatMap({ $0.unsortedPlayers() })
} }
@ -346,6 +350,13 @@ class GroupStage: ModelObject, Storable {
} }
} }
func insertOnServer() throws {
try DataStore.shared.groupStages.writeChangeAndInsertOnServer(instance: self)
for match in self._matches() {
try match.insertOnServer()
}
}
} }
extension GroupStage { extension GroupStage {

@ -1,5 +1,5 @@
// //
// Match_v2.swift // Match.swift
// Padel Tournament // Padel Tournament
// //
// Created by razmig on 10/03/2024. // Created by razmig on 10/03/2024.
@ -55,6 +55,18 @@ class Match: ModelObject, Storable {
// self.order = order // self.order = order
} }
// MARK: - Computed dependencies
var teamScores: [TeamScore] {
Store.main.filter { $0.match == self.id }
}
// MARK: -
override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.teamScores)
}
func indexInRound() -> Int { func indexInRound() -> Int {
if groupStage != nil { if groupStage != nil {
return index return index
@ -756,14 +768,6 @@ class Match: ModelObject, Storable {
roundObject?.parent != nil roundObject?.parent != nil
} }
var teamScores: [TeamScore] {
Store.main.filter { $0.match == self.id }
}
override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.teamScores)
}
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {
case _id = "id" case _id = "id"
case _round = "round" case _round = "round"
@ -853,6 +857,13 @@ class Match: ModelObject, Storable {
} }
} }
func insertOnServer() throws {
try DataStore.shared.matches.writeChangeAndInsertOnServer(instance: self)
for teamScore in self.teamScores {
try teamScore.insertOnServer()
}
}
} }
enum MatchDateSetup: Hashable, Identifiable { enum MatchDateSetup: Hashable, Identifiable {

@ -471,6 +471,11 @@ class PlayerRegistration: ModelObject, Storable {
return 15000 return 15000
} }
} }
func insertOnServer() throws {
try DataStore.shared.playerRegistrations.writeChangeAndInsertOnServer(instance: self)
}
} }
extension PlayerRegistration: Hashable { extension PlayerRegistration: Hashable {

@ -1,5 +1,5 @@
// //
// Round_v2.swift // Round.swift
// Padel Tournament // Padel Tournament
// //
// Created by razmig on 10/03/2024. // Created by razmig on 10/03/2024.
@ -29,6 +29,18 @@ class Round: ModelObject, Storable {
self.startDate = startDate self.startDate = startDate
} }
// MARK: - Computed dependencies
func tournamentObject() -> Tournament? {
Store.main.findById(tournament)
}
func _matches() -> [Match] {
Store.main.filter { $0.round == self.id }
}
// MARK: -
var matchFormat: MatchFormat { var matchFormat: MatchFormat {
get { get {
format ?? .defaultFormatForMatchType(.bracket) format ?? .defaultFormatForMatchType(.bracket)
@ -47,14 +59,6 @@ class Round: ModelObject, Storable {
playedMatches().allSatisfy({ $0.hasEnded() }) playedMatches().allSatisfy({ $0.hasEnded() })
} }
func tournamentObject() -> Tournament? {
Store.main.findById(tournament)
}
func _matches() -> [Match] {
Store.main.filter { $0.round == self.id }
}
func upperMatches(ofMatch match: Match) -> [Match] { func upperMatches(ofMatch match: Match) -> [Match] {
if parent != nil, previousRound() == nil, let parentRound { if parent != nil, previousRound() == nil, let parentRound {
let matchIndex = match.index let matchIndex = match.index
@ -530,6 +534,13 @@ class Round: ModelObject, Storable {
} }
} }
func insertOnServer() throws {
try DataStore.shared.rounds.writeChangeAndInsertOnServer(instance: self)
for match in self._matches() {
try match.insertOnServer()
}
}
} }
extension Round: Selectable { extension Round: Selectable {

@ -57,6 +57,18 @@ class TeamRegistration: ModelObject, Storable {
self.qualified = qualified self.qualified = qualified
} }
// MARK: - Computed dependencies
func unsortedPlayers() -> [PlayerRegistration] {
Store.main.filter { $0.teamRegistration == self.id }
}
// MARK: -
override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.unsortedPlayers())
}
func isSeedable() -> Bool { func isSeedable() -> Bool {
bracketPosition == nil && groupStage == nil bracketPosition == nil && groupStage == nil
} }
@ -301,10 +313,6 @@ class TeamRegistration: ModelObject, Storable {
} }
} }
func unsortedPlayers() -> [PlayerRegistration] {
Store.main.filter { $0.teamRegistration == self.id }
}
func setWeight(from players: [PlayerRegistration], inTournamentCategory tournamentCategory: TournamentCategory) { func setWeight(from players: [PlayerRegistration], inTournamentCategory tournamentCategory: TournamentCategory) {
let significantPlayerCount = significantPlayerCount() let significantPlayerCount = significantPlayerCount()
weight = (players.prefix(significantPlayerCount).map { $0.computedRank } + missingPlayerType(inTournamentCategory: tournamentCategory).map { unrankValue(for: $0 == 1 ? true : false ) }).prefix(significantPlayerCount).reduce(0,+) weight = (players.prefix(significantPlayerCount).map { $0.computedRank } + missingPlayerType(inTournamentCategory: tournamentCategory).map { unrankValue(for: $0 == 1 ? true : false ) }).prefix(significantPlayerCount).reduce(0,+)
@ -353,10 +361,6 @@ class TeamRegistration: ModelObject, Storable {
Store.main.findById(tournament) Store.main.findById(tournament)
} }
override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.unsortedPlayers())
}
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {
case _id = "id" case _id = "id"
case _tournament = "tournament" case _tournament = "tournament"
@ -479,6 +483,13 @@ class TeamRegistration: ModelObject, Storable {
} }
} }
func insertOnServer() throws {
try DataStore.shared.teamRegistrations.writeChangeAndInsertOnServer(instance: self)
for playerRegistration in self.unsortedPlayers() {
try playerRegistration.insertOnServer()
}
}
} }
extension TeamRegistration: Hashable { extension TeamRegistration: Hashable {

@ -42,12 +42,10 @@ class TeamScore: ModelObject, Storable {
self.luckyLoser = nil self.luckyLoser = nil
} }
func isWalkOut() -> Bool { // MARK: - Computed dependencies
walkOut != nil
}
func matchObject() -> Match? { func matchObject() -> Match? {
Store.main.findById(match) Store.main.findById(self.match)
} }
var team: TeamRegistration? { var team: TeamRegistration? {
@ -57,6 +55,12 @@ class TeamScore: ModelObject, Storable {
return DataStore.shared.teamRegistrations.findById(teamRegistration) return DataStore.shared.teamRegistrations.findById(teamRegistration)
} }
// MARK: -
func isWalkOut() -> Bool {
walkOut != nil
}
enum CodingKeys: String, CodingKey { enum CodingKeys: String, CodingKey {
case _id = "id" case _id = "id"
case _match = "match" case _match = "match"
@ -100,4 +104,8 @@ class TeamScore: ModelObject, Storable {
} }
} }
func insertOnServer() throws {
try DataStore.shared.teamScores.writeChangeAndInsertOnServer(instance: self)
}
} }

@ -319,6 +319,28 @@ class Tournament : ModelObject, Storable {
} }
} }
override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.unsortedTeams())
try Store.main.deleteDependencies(items: self.groupStages())
try Store.main.deleteDependencies(items: self.rounds())
try Store.main.deleteDependencies(items: self._matchSchedulers())
}
// MARK: - Computed Dependencies
func unsortedTeams() -> [TeamRegistration] {
Store.main.filter { $0.tournament == self.id }
}
func groupStages() -> [GroupStage] {
Store.main.filter { $0.tournament == self.id }.sorted(by: \.index)
}
func allRounds() -> [Round] {
Store.main.filter { $0.tournament == self.id }
}
// MARK: -
/// Warning: if the enum has more than 10 cases, the payment algo is broken /// Warning: if the enum has more than 10 cases, the payment algo is broken
enum TournamentPayment: Int, CaseIterable { enum TournamentPayment: Int, CaseIterable {
@ -632,10 +654,6 @@ class Tournament : ModelObject, Storable {
closedRegistrationDate != nil closedRegistrationDate != nil
} }
func groupStages() -> [GroupStage] {
Store.main.filter { $0.tournament == self.id }.sorted(by: \.index)
}
func getActiveGroupStage() -> GroupStage? { func getActiveGroupStage() -> GroupStage? {
let groupStages = groupStages() let groupStages = groupStages()
return groupStages.filter({ $0.hasStarted() && $0.hasEnded() == false }).sorted(by: \.index).first ?? groupStages.first return groupStages.filter({ $0.hasStarted() && $0.hasEnded() == false }).sorted(by: \.index).first ?? groupStages.first
@ -681,10 +699,6 @@ class Tournament : ModelObject, Storable {
return unsortedGroupStages.flatMap { $0._matches() } + allRounds().flatMap { $0._matches() } return unsortedGroupStages.flatMap { $0._matches() } + allRounds().flatMap { $0._matches() }
} }
func allRounds() -> [Round] {
Store.main.filter { $0.tournament == self.id }
}
func rounds() -> [Round] { func rounds() -> [Round] {
Store.main.filter { $0.tournament == self.id && $0.parent == nil }.sorted(by: \.index).reversed() Store.main.filter { $0.tournament == self.id && $0.parent == nil }.sorted(by: \.index).reversed()
} }
@ -754,10 +768,6 @@ class Tournament : ModelObject, Storable {
} }
} }
func unsortedTeams() -> [TeamRegistration] {
Store.main.filter { $0.tournament == self.id }
}
func unsortedTeamsWithoutWO() -> [TeamRegistration] { func unsortedTeamsWithoutWO() -> [TeamRegistration] {
Store.main.filter { $0.tournament == self.id && $0.walkOut == false } Store.main.filter { $0.tournament == self.id && $0.walkOut == false }
} }
@ -1559,13 +1569,6 @@ class Tournament : ModelObject, Storable {
private let _currentSelectionSorting : [MySortDescriptor<TeamRegistration>] = [.keyPath(\.weight), .keyPath(\.registrationDate!)] private let _currentSelectionSorting : [MySortDescriptor<TeamRegistration>] = [.keyPath(\.weight), .keyPath(\.registrationDate!)]
override func deleteDependencies() throws {
try Store.main.deleteDependencies(items: self.unsortedTeams())
try Store.main.deleteDependencies(items: self.groupStages())
try Store.main.deleteDependencies(items: self.rounds())
try Store.main.deleteDependencies(items: self._matchSchedulers())
}
private func _matchSchedulers() -> [MatchScheduler] { private func _matchSchedulers() -> [MatchScheduler] {
Store.main.filter(isIncluded: { $0.tournament == self.id }) Store.main.filter(isIncluded: { $0.tournament == self.id })
} }
@ -1601,91 +1604,25 @@ class Tournament : ModelObject, Storable {
return final?.playedMatches().first?.winner() return final?.playedMatches().first?.winner()
} }
// MARK: - Payments & Crypto // MARK: -
fileprivate var _currentPayment: TournamentPayment? = nil
fileprivate var _currentCanceled: Bool? = nil
func insertOnServer() throws {
// func setPayment(_ payment: TournamentPayment) { try DataStore.shared.tournaments.writeChangeAndInsertOnServer(instance: self)
//
// let max: Int = TournamentPayment.allCases.count
// self._currentPayment = payment
// var sequence = (1...18).map { _ in Int.random(in: (0..<max)) }
// sequence.append(payment.rawValue)
// sequence.append(contentsOf: (1...13).map { _ in Int.random(in: (0..<max ))} )
//
// let stringCombo: [String] = sequence.map { $0.formatted() }
// let joined: String = stringCombo.joined(separator: "")
// if let data = joined.data(using: .utf8) {
// do {
// self.payment = try data.encrypt(pass: Key.pass.rawValue)
// } catch {
// Logger.error(error)
// }
// }
// }
// var currentPayment: TournamentPayment? { for teamRegistration in self.unsortedTeams() {
// if let current = self._currentPayment { try teamRegistration.insertOnServer()
// return current }
// } for groupStage in self.groupStages() {
// self._currentPayment = self.decryptPayment() try groupStage.insertOnServer()
// return self._currentPayment }
// } for round in self.allRounds() {
try round.insertOnServer()
// func decryptPayment() -> TournamentPayment? { }
// if let payment {
// do {
// let decoded: String = try payment.decryptData(pass: Key.pass.rawValue)
// let sequence = decoded.compactMap { _numberFormatter.number(from: String($0))?.intValue }
// return TournamentPayment(rawValue: sequence[18])
// } catch {
// Logger.error(error)
// }
// }
// return nil
// }
// func setCanceled(_ canceled: Bool) {
//
// let max: Int = 9
// self._currentCanceled = canceled
// var sequence = (1...18).map { _ in Int.random(in: (0..<max)) }
// sequence.append(canceled.encodedValue)
// sequence.append(contentsOf: (1...13).map { _ in Int.random(in: (0..<max ))} )
//
// let stringCombo: [String] = sequence.map { $0.formatted() }
// let joined: String = stringCombo.joined(separator: "")
// if let data = joined.data(using: .utf8) {
// do {
// self.isCanceled = try data.encrypt(pass: Key.pass.rawValue)
// } catch {
// Logger.error(error)
// }
// }
// }
// var currentCanceled: Bool? { }
// if let current = self._currentCanceled {
// return current
// }
// self._currentCanceled = self.decryptCanceled()
// return self._currentCanceled
// }
// func decryptCanceled() -> Bool? { // MARK: - Payments & Crypto
// if let isCanceled {
// do {
// let decoded: String = try isCanceled.decryptData(pass: Key.pass.rawValue)
// let sequence = decoded.compactMap { _numberFormatter.number(from: String($0))?.intValue }
// return Bool.decodeInt(sequence[18])
// } catch {
// Logger.error(error)
// }
// }
// return nil
// }
enum PaymentError: Error { enum PaymentError: Error {
case cantPayTournament case cantPayTournament

Loading…
Cancel
Save