From 41823ec8968f8eed3028d779dda7a6f072f4f9e3 Mon Sep 17 00:00:00 2001 From: Razmig Sarkissian Date: Sun, 5 May 2024 11:25:31 +0200 Subject: [PATCH] fix stuff for syncing --- PadelClub/Data/DataStore.swift | 6 ++-- PadelClub/Data/User.swift | 12 +++++++ PadelClub/Extensions/String+Extensions.swift | 6 ++-- PadelClub/Utils/Network/NetworkManager.swift | 2 +- PadelClub/Utils/SourceFileManager.swift | 35 +++++++++++++++---- PadelClub/Views/Club/ClubDetailView.swift | 8 ++--- PadelClub/Views/Club/ClubsView.swift | 2 +- .../Navigation/Agenda/ActivityView.swift | 14 +++++--- .../Navigation/Agenda/EventListView.swift | 2 +- .../Views/Navigation/Umpire/UmpireView.swift | 22 ++++++------ 10 files changed, 73 insertions(+), 36 deletions(-) diff --git a/PadelClub/Data/DataStore.swift b/PadelClub/Data/DataStore.swift index 4a8f346..42d62fb 100644 --- a/PadelClub/Data/DataStore.swift +++ b/PadelClub/Data/DataStore.swift @@ -77,7 +77,7 @@ class DataStore: ObservableObject { // store.addMigration(Migration(version: 3)) let indexed : Bool = true - let synchronized : Bool = false + let synchronized : Bool = true self.clubs = store.registerCollection(synchronized: synchronized, indexed: indexed) self.courts = store.registerCollection(synchronized: synchronized, indexed: indexed) self.tournaments = store.registerCollection(synchronized: synchronized, indexed: indexed) @@ -88,10 +88,10 @@ class DataStore: ObservableObject { self.playerRegistrations = store.registerCollection(synchronized: synchronized, indexed: indexed) self.rounds = store.registerCollection(synchronized: synchronized, indexed: indexed) self.matches = store.registerCollection(synchronized: synchronized, indexed: indexed) - self.monthData = store.registerCollection(synchronized: synchronized, indexed: indexed) + self.monthData = store.registerCollection(synchronized: false, indexed: indexed) self.dateIntervals = store.registerCollection(synchronized: synchronized, indexed: indexed) - self.userStorage = store.registerObject(synchronized: synchronized) + self.userStorage = store.registerObject(synchronized: false) NotificationCenter.default.addObserver(self, selector: #selector(collectionWasUpdated), name: NSNotification.Name.CollectionDidLoad, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(collectionWasUpdated), name: NSNotification.Name.CollectionDidChange, object: nil) diff --git a/PadelClub/Data/User.swift b/PadelClub/Data/User.swift index b2604ef..51571b4 100644 --- a/PadelClub/Data/User.swift +++ b/PadelClub/Data/User.swift @@ -61,6 +61,18 @@ class User: UserBase, Storable { clubs?.isEmpty == false } + func hasFavoriteClubsAndCreatedClubs() -> Bool { + clubsObjects(includeCreated: true).isEmpty == false + } + + func setUserClub(_ userClub: Club) { + if clubs == nil { + clubs = [userClub.id] + } else { + clubs!.insert(userClub.id, at: 0) + } + } + func clubsObjects(includeCreated: Bool = false) -> [Club] { guard let clubs else { return [] } return Store.main.filter(isIncluded: { (includeCreated && $0.creator == id) || clubs.contains($0.id) }) diff --git a/PadelClub/Extensions/String+Extensions.swift b/PadelClub/Extensions/String+Extensions.swift index f0afc3a..2a54554 100644 --- a/PadelClub/Extensions/String+Extensions.swift +++ b/PadelClub/Extensions/String+Extensions.swift @@ -52,8 +52,10 @@ extension String { // Extract the first character of each sentence let firstLetters = sentences.compactMap { sentence -> Character? in let trimmedSentence = sentence.trimmingCharacters(in: .whitespacesAndNewlines) - if let firstCharacter = trimmedSentence.first { - return firstCharacter + if trimmedSentence.count > 2 { + if let firstCharacter = trimmedSentence.first { + return firstCharacter + } } return nil } diff --git a/PadelClub/Utils/Network/NetworkManager.swift b/PadelClub/Utils/Network/NetworkManager.swift index dc2ef7b..6da1982 100644 --- a/PadelClub/Utils/Network/NetworkManager.swift +++ b/PadelClub/Utils/Network/NetworkManager.swift @@ -22,7 +22,7 @@ class NetworkManager { let dateString = ["CLASSEMENT-PADEL", fileName, lastDateString].joined(separator: "-") + ".csv" - let documentsUrl:URL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)! + let documentsUrl: URL = SourceFileManager.shared.rankingSourceDirectory let destinationFileUrl = documentsUrl.appendingPathComponent("\(dateString)") let fileURL = URL(string: "https://padelclub.app/static/\(dateString)") diff --git a/PadelClub/Utils/SourceFileManager.swift b/PadelClub/Utils/SourceFileManager.swift index fab3def..0c1b68a 100644 --- a/PadelClub/Utils/SourceFileManager.swift +++ b/PadelClub/Utils/SourceFileManager.swift @@ -9,7 +9,32 @@ import Foundation class SourceFileManager { static let shared = SourceFileManager() + + init() { + createDirectoryIfNeeded() + } + + let rankingSourceDirectory : URL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appending(path: "rankings") + func createDirectoryIfNeeded() { + let fileManager = FileManager.default + do { + let directoryURL = rankingSourceDirectory + + // Check if the directory exists + if !fileManager.fileExists(atPath: directoryURL.path) { + // Directory does not exist, create it + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + print("Directory created at: \(directoryURL)") + } else { + print("Directory already exists at: \(directoryURL)") + } + } catch { + print("Error: \(error)") + } + } + + var lastDataSource: String? { DataStore.shared.appSettings.lastDataSource } @@ -117,16 +142,14 @@ class SourceFileManager { } func removeAllFilesFromServer() { - let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) - let allFiles = try! FileManager.default.contentsOfDirectory(at: docDir, includingPropertiesForKeys: nil) + let allFiles = try! FileManager.default.contentsOfDirectory(at: rankingSourceDirectory, includingPropertiesForKeys: nil) allFiles.filter { $0.pathExtension == "csv" }.forEach { url in try? FileManager.default.removeItem(at: url) } } var allFiles: [URL] { - let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) - let allFiles = try! FileManager.default.contentsOfDirectory(at: docDir, includingPropertiesForKeys: nil).filter({ url in + let allFiles = try! FileManager.default.contentsOfDirectory(at: rankingSourceDirectory, includingPropertiesForKeys: nil).filter({ url in url.pathExtension == "csv" }) @@ -149,8 +172,8 @@ enum SourceFile: String, CaseIterable { case messieurs = "MESSIEURS" var filesFromServer: [URL] { - let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) - let allFiles = try! FileManager.default.contentsOfDirectory(at: docDir, includingPropertiesForKeys: nil) + let rankingSourceDirectory = SourceFileManager.shared.rankingSourceDirectory + let allFiles = try! FileManager.default.contentsOfDirectory(at: rankingSourceDirectory, includingPropertiesForKeys: nil) return allFiles.filter{$0.pathExtension == "csv" && $0.path().contains(rawValue)} } diff --git a/PadelClub/Views/Club/ClubDetailView.swift b/PadelClub/Views/Club/ClubDetailView.swift index acaa1aa..73b3a30 100644 --- a/PadelClub/Views/Club/ClubDetailView.swift +++ b/PadelClub/Views/Club/ClubDetailView.swift @@ -142,9 +142,6 @@ struct ClubDetailView: View { LabeledContent("Ville") { Text(club.city ?? "") } - LabeledContent("Code Postal") { - Text(club.zipCode ?? "") - } Link(destination: federalLink) { Text("Fiche du club sur tenup") } @@ -168,7 +165,7 @@ struct ClubDetailView: View { .keyboardType(.alphabet) .autocorrectionDisabled() .defaultFocus($focusedField, ._name, priority: .automatic) - .navigationTitle(displayContext == .addition ? "Nouveau club" : club.name) + .navigationTitle(displayContext == .addition ? "Nouveau club" : "Détail du club") .navigationBarTitleDisplayMode(.inline) .toolbar(.visible, for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) @@ -176,7 +173,7 @@ struct ClubDetailView: View { if displayContext == .edition || displayContext == .lockedForEditing { let isFavorite = club.isFavorite() ToolbarItem(placement: .topBarTrailing) { - BarButtonView("Favori", icon: isFavorite ? "start" : "star.fill") { + BarButtonView("Favori", icon: isFavorite ? "star.fill" : "star") { do { if isFavorite { dataStore.user?.clubs?.removeAll(where: { $0 == club.id }) @@ -188,6 +185,7 @@ struct ClubDetailView: View { Logger.error(error) } } + .tint(isFavorite ? .green : .logoRed) } } } diff --git a/PadelClub/Views/Club/ClubsView.swift b/PadelClub/Views/Club/ClubsView.swift index c5786f5..ec2830f 100644 --- a/PadelClub/Views/Club/ClubsView.swift +++ b/PadelClub/Views/Club/ClubsView.swift @@ -55,7 +55,7 @@ struct ClubsView: View { } } .overlay { - if dataStore.user == nil || dataStore.user?.hasClubs() == true { + if dataStore.user?.hasFavoriteClubsAndCreatedClubs() == false { ContentUnavailableView { Label("Aucun club", systemImage: "house.and.flag.fill") } description: { diff --git a/PadelClub/Views/Navigation/Agenda/ActivityView.swift b/PadelClub/Views/Navigation/Agenda/ActivityView.swift index 26cee95..b4fe287 100644 --- a/PadelClub/Views/Navigation/Agenda/ActivityView.swift +++ b/PadelClub/Views/Navigation/Agenda/ActivityView.swift @@ -122,14 +122,14 @@ struct ActivityView: View { // } .task { if navigation.agendaDestination == .tenup - && dataStore.user?.hasClubs() == false + && dataStore.user?.hasClubs() == true && federalDataViewModel.federalTournaments.isEmpty { _gatherFederalTournaments() } } .onChange(of: navigation.agendaDestination) { if navigation.agendaDestination == .tenup - && dataStore.user?.hasClubs() == false + && dataStore.user?.hasClubs() == true && federalDataViewModel.federalTournaments.isEmpty { _gatherFederalTournaments() } @@ -202,7 +202,11 @@ struct ActivityView: View { .environment(navigation) .tint(.master) } - .sheet(isPresented: $presentClubSearchView) { + .sheet(isPresented: $presentClubSearchView, onDismiss: { + if dataStore.user?.hasClubs() == true { + navigation.agendaDestination = .tenup + } + }) { ClubImportView() .tint(.master) } @@ -253,7 +257,7 @@ struct ActivityView: View { RowButtonView("Créer un nouvel événement") { newTournament = Tournament.newEmptyInstance() } - if dataStore.user == nil || dataStore.user?.hasClubs() == true { + if dataStore.user?.hasClubs() == false { RowButtonView("Chercher l'un de vos clubs") { presentClubSearchView = true } @@ -274,7 +278,7 @@ struct ActivityView: View { } private func _tenupEmptyView() -> some View { - if dataStore.user == nil || dataStore.user?.hasClubs() == true { + if dataStore.user?.hasClubs() == false { ContentUnavailableView { Label("Aucun tournoi", systemImage: "shield.slash") } description: { diff --git a/PadelClub/Views/Navigation/Agenda/EventListView.swift b/PadelClub/Views/Navigation/Agenda/EventListView.swift index bc0f872..dab5805 100644 --- a/PadelClub/Views/Navigation/Agenda/EventListView.swift +++ b/PadelClub/Views/Navigation/Agenda/EventListView.swift @@ -51,7 +51,7 @@ struct EventListView: View { .headerProminence(.increased) .task { if navigation.agendaDestination == .tenup - && dataStore.user?.hasClubs() == false + && dataStore.user?.hasClubs() == true && _tournaments.isEmpty { _gatherFederalTournaments(startDate: section) } diff --git a/PadelClub/Views/Navigation/Umpire/UmpireView.swift b/PadelClub/Views/Navigation/Umpire/UmpireView.swift index 5fe8e34..67952e7 100644 --- a/PadelClub/Views/Navigation/Umpire/UmpireView.swift +++ b/PadelClub/Views/Navigation/Umpire/UmpireView.swift @@ -57,24 +57,22 @@ struct UmpireView: View { } } else { NavigationLink { - SelectablePlayerListView(allowSelection: 1, playerSelectionAction: { players in + SelectablePlayerListView(allowSelection: 1, searchField: user.firstName + " " + user.lastName, playerSelectionAction: { players in if let player = players.first { user.licenceId = player.license - let userClub = Club.findOrCreate(name: player.clubName!, code: player.clubCode) - do { - try dataStore.clubs.addOrUpdate(instance: userClub) - - if user.clubs == nil { - user.clubs = [userClub.id] - } else { - user.clubs!.insert(userClub.id, at: 0) + if user.clubsObjects().contains(where: { $0.code == player.clubCode }) == false { + let userClub = Club.findOrCreate(name: player.clubName!, code: player.clubCode) + do { + try dataStore.clubs.addOrUpdate(instance: userClub) + user.setUserClub(userClub) + try dataStore.userStorage.update() + } catch { + Logger.error(error) } - try dataStore.userStorage.update() - } catch { - Logger.error(error) } } }) + .id(UUID()) } label: { Label("Ma fiche joueur", systemImage: "person.bust.circle.fill") }