fix issue with two votes on the same date

fix issue with header not showing correct vote date
split logic for Persistence into different files
create class that deals with voting time, existing votes, and what should be shown based on that
This commit is contained in:
Trey t
2022-02-17 14:46:11 -06:00
parent f0ed56fe94
commit 675e44bca9
12 changed files with 547 additions and 427 deletions

View File

@@ -0,0 +1,104 @@
//
// Persistence.swift
// Shared
//
// Created by Trey Tartt on 1/5/22.
//
import CoreData
import SwiftUI
class PersistenceController {
@AppStorage(UserDefaultsStore.Keys.useCloudKit.rawValue, store: GroupUserDefaults.groupDefaults) private var useCloudKit = false
static let shared = PersistenceController.persistenceController
private static var persistenceController: PersistenceController {
return PersistenceController(inMemory: false)
}
public var viewContext: NSManagedObjectContext {
return PersistenceController.shared.container.viewContext
}
public var switchContainerListeners = [(() -> Void)]()
public var earliestEntry: MoodEntry? {
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
let first = try! viewContext.fetch(fetchRequest).first
return first ?? nil
}
public var latestEntry: MoodEntry? {
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
let last = try! viewContext.fetch(fetchRequest).last
return last ?? nil
}
lazy var container: NSPersistentContainer = {
setupContainer()
}()
func switchContainer() {
try? viewContext.save()
container = setupContainer()
for item in switchContainerListeners {
item()
}
}
private func setupContainer() -> NSPersistentContainer {
if useCloudKit {
container = NSPersistentCloudKitContainer(name: "Feels")
} else {
container = NSCustomPersistentContainer(name: "Feels")
}
for description in container.persistentStoreDescriptions {
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption)
description.setOption(true as NSNumber, forKey: NSInferMappingModelAutomaticallyOption)
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
self.container.viewContext.automaticallyMergesChangesFromParent = true
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}
init(inMemory: Bool = false) {
container = setupContainer()
}
}
extension NSManagedObjectContext {
/// Executes the given `NSBatchDeleteRequest` and directly merges the changes to bring the given managed object context up to date.
///
/// - Parameter batchDeleteRequest: The `NSBatchDeleteRequest` to execute.
/// - Throws: An error if anything went wrong executing the batch deletion.
public func executeAndMergeChanges(using batchDeleteRequest: NSBatchDeleteRequest) throws {
batchDeleteRequest.resultType = .resultTypeObjectIDs
let result = try execute(batchDeleteRequest) as? NSBatchDeleteResult
let changes: [AnyHashable: Any] = [NSDeletedObjectsKey: result?.result as? [NSManagedObjectID] ?? []]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
}
}
class NSCustomPersistentContainer: NSPersistentContainer {
override open class func defaultDirectoryURL() -> URL {
var storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.groupShareId)
storeURL = storeURL?.appendingPathComponent("Feels.sqlite")
#if DEBUG
storeURL = storeURL?.appendingPathComponent("Feels-Debug.sqlite")
#endif
return storeURL!
}
}

View File

@@ -0,0 +1,63 @@
//
// PersistenceADD.swift
// Feels
//
// Created by Trey Tartt on 2/17/22.
//
import CoreData
extension PersistenceController {
public func add(mood: Mood, forDate date: Date, entryType: EntryType) {
if let existingEntry = getEntry(byDate: date) {
viewContext.delete(existingEntry)
try? viewContext.save()
}
let newItem = MoodEntry(context: viewContext)
newItem.timestamp = Date()
newItem.moodValue = Int16(mood.rawValue)
newItem.forDate = date
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
newItem.canEdit = true
newItem.canDelete = true
newItem.entryType = Int16(entryType.rawValue)
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
func fillInMissingDates() {
let endDate = ShowBasedOnVoteLogics.getLastDateVoteShouldExist()
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: false)]
let entries = try! viewContext.fetch(fetchRequest)
if let firstEntry = entries.last?.forDate {
let allDates: [Date] = Date.dates(from: firstEntry, to: endDate).map({
let zeroDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: $0)!
return zeroDate
})
let existingEntries: [Date] = entries.compactMap({
if let date = $0.forDate {
let zeroDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: date)!
return zeroDate
}
return nil
})
let allDatesSet = Set(allDates)
let existingEntriesSet = Set(existingEntries)
let missing = Array(allDatesSet.subtracting(existingEntriesSet)).sorted(by: >)
for date in missing {
add(mood: .missing, forDate: date, entryType: .listView)
}
}
}
}

View File

@@ -0,0 +1,29 @@
//
// PersistenceDELETE.swift
// Feels
//
// Created by Trey Tartt on 2/17/22.
//
import CoreData
extension PersistenceController {
func clearDB() {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "MoodEntry")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try viewContext.executeAndMergeChanges(using: deleteRequest)
try viewContext.save()
} catch let error as NSError {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
func delete(forDate: Date) {
if let entry = PersistenceController.shared.getEntry(byDate: forDate) {
viewContext.delete(entry)
try! viewContext.save()
}
}
}

View File

@@ -0,0 +1,92 @@
//
// PersistenceGET.swift
// Feels
//
// Created by Trey Tartt on 2/17/22.
//
import CoreData
extension PersistenceController {
public func getEntry(byDate date: Date) -> MoodEntry? {
let startDate = Calendar.current.startOfDay(for: date)
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)!
let predicate = NSPredicate(format: "forDate >= %@ && forDate <= %@ ",
startDate as NSDate,
endDate as NSDate)
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
let data = try! viewContext.fetch(fetchRequest)
return data.first
}
public func getData(startDate: Date, endDate: Date, includedDays: [Int]) -> [MoodEntry] {
try! viewContext.setQueryGenerationFrom(.current)
viewContext.refreshAllObjects()
var includedDays16 = [Int16]()
if includedDays.isEmpty {
includedDays16 = [Int16(1), Int16(2), Int16(3), Int16(4), Int16(5), Int16(6), Int16(7)]
} else {
includedDays16 = includedDays.map({
Int16($0)
})
}
let predicate = NSPredicate(format: "forDate >= %@ && forDate <= %@ && weekDay IN %@",
startDate as NSDate,
endDate as NSDate,
includedDays16)
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
let data = try! viewContext.fetch(fetchRequest)
return data
}
public func splitIntoYearMonth() -> [Int: [Int: [MoodEntry]]] {
let data = PersistenceController.shared.getData(startDate: Date(timeIntervalSince1970: 0),
endDate: Date(),
includedDays: [1,2,3,4,5,6,7]).sorted(by: {
$0.forDate! < $1.forDate!
})
var returnData = [Int: [Int: [MoodEntry]]]()
if let earliestEntry = data.first,
let lastEntry = data.last {
let calendar = Calendar.current
let components = calendar.dateComponents([.year], from: earliestEntry.forDate!)
let earliestYear = components.year!
let latestComponents = calendar.dateComponents([.year], from: lastEntry.forDate!)
let latestYear = latestComponents.year!
for year in earliestYear...latestYear {
var allMonths = [Int: [MoodEntry]]()
for month in (1...12) {
var components = DateComponents()
components.month = month
components.year = year
let startDateOfMonth = Calendar.current.date(from: components)!
let items = data.filter({ entry in
let components = calendar.dateComponents([.month, .year], from: startDateOfMonth)
let entryComponents = calendar.dateComponents([.month, .year], from: entry.forDate!)
return (components.month == entryComponents.month && components.year == entryComponents.year)
})
if !items.isEmpty {
allMonths[month] = items
}
}
returnData[year] = allMonths
}
}
return returnData
}
}

View File

@@ -0,0 +1,85 @@
//
// PersistenceHelper.swift
// Feels (iOS)
//
// Created by Trey Tartt on 2/17/22.
//
import CoreData
extension PersistenceController {
private var childContext: NSManagedObjectContext {
return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
}
public func randomEntries(count: Int) -> [MoodEntry] {
var entries = [MoodEntry]()
for idx in 0..<count {
let newItem = MoodEntry(context: childContext)
newItem.timestamp = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
newItem.moodValue = Int16(Mood.allValues.randomElement()!.rawValue)
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
newItem.forDate = date
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
newItem.canEdit = true
newItem.canDelete = true
entries.append(newItem)
}
return entries
}
func populateMemory() {
for idx in 1..<25 {
let newItem = MoodEntry(context: viewContext)
newItem.timestamp = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
newItem.moodValue = Int16(Mood.allValues.randomElement()!.rawValue)
newItem.canEdit = true
newItem.canDelete = true
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
newItem.forDate = date
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
}
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
func populateTestData() {
for idx in 1..<120 {
let newItem = MoodEntry(context: viewContext)
newItem.timestamp = Date()
newItem.moodValue = Int16(Mood.allValues.randomElement()!.rawValue)
newItem.canEdit = true
newItem.canDelete = true
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
newItem.forDate = date
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
}
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
func longestStreak() -> [MoodEntry] {
// let predicate = NSPredicate(format: "forDate == %@", date as NSDate)
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
// fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
let data = try! viewContext.fetch(fetchRequest)
return data
}
}