wip
This commit is contained in:
@@ -1,137 +0,0 @@
|
||||
//
|
||||
// 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: true)
|
||||
}
|
||||
|
||||
public var viewContext: NSManagedObjectContext {
|
||||
return PersistenceController.shared.container.viewContext
|
||||
}
|
||||
|
||||
public lazy var childContext: NSManagedObjectContext = {
|
||||
NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
|
||||
}()
|
||||
|
||||
public var switchContainerListeners = [(() -> Void)]()
|
||||
|
||||
private var editedDataClosure = [() -> 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()
|
||||
}
|
||||
}
|
||||
|
||||
public func addNewDataListener(closure: @escaping (() -> Void)) {
|
||||
editedDataClosure.append(closure)
|
||||
}
|
||||
|
||||
public func saveAndRunDataListerners() {
|
||||
do {
|
||||
try viewContext.save()
|
||||
|
||||
for closure in editedDataClosure {
|
||||
closure()
|
||||
}
|
||||
} catch {
|
||||
print(error)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
#if DEBUG
|
||||
if let storeURLDebug = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.groupShareIdDebug) {
|
||||
return storeURLDebug.appendingPathComponent("Feels-Debug.sqlite")
|
||||
}
|
||||
// Fallback to default location if App Group not available
|
||||
print("⚠️ App Group not available, using default Core Data location")
|
||||
return super.defaultDirectoryURL()
|
||||
#else
|
||||
if let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.groupShareId) {
|
||||
return storeURL.appendingPathComponent("Feels.sqlite")
|
||||
}
|
||||
// Fallback to default location if App Group not available
|
||||
print("⚠️ App Group not available, using default Core Data location")
|
||||
return super.defaultDirectoryURL()
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
//
|
||||
// PersistenceADD.swift
|
||||
// Feels
|
||||
//
|
||||
// Created by Trey Tartt on 2/17/22.
|
||||
//
|
||||
|
||||
import CoreData
|
||||
|
||||
extension PersistenceController {
|
||||
public func fixWrongWeekdays() {
|
||||
let data = PersistenceController.shared.getData(startDate: Date(timeIntervalSince1970: 0),
|
||||
endDate: Date(),
|
||||
includedDays: []).sorted(by: {
|
||||
$0.forDate! < $1.forDate!
|
||||
})
|
||||
|
||||
data.forEach({
|
||||
$0.weekDay = Int16(Calendar.current.component(.weekday, from: $0.forDate!))
|
||||
})
|
||||
try? viewContext.save()
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
EventLogger.log(event: "add_entry", withData: ["entry_type": entryType.rawValue])
|
||||
|
||||
saveAndRunDataListerners()
|
||||
}
|
||||
|
||||
func fillInMissingDates() {
|
||||
let currentOnboarding = UserDefaultsStore.getOnboarding()
|
||||
var endDate = ShowBasedOnVoteLogics.getCurrentVotingDate(onboardingData: currentOnboarding)
|
||||
// since its for views take away the last date so vote is enabled
|
||||
endDate = Calendar.current.date(byAdding: .day, value: -1, to: endDate)!
|
||||
|
||||
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, toDate: endDate, includingToDate: true).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 12 hours, if you enter a things right at 12:00.00 it wont show .... mabye
|
||||
// due to utc offset?
|
||||
let adjustedDate = Calendar.current.date(byAdding: .hour, value: 12, to: date)!
|
||||
add(mood: .missing, forDate: adjustedDate, entryType: .filledInMissing)
|
||||
}
|
||||
|
||||
if !missing.isEmpty {
|
||||
EventLogger.log(event: "filled_in_missing_entries", withData: ["count": missing.count])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeNoForDates() {
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: false)]
|
||||
let entries = try! viewContext.fetch(fetchRequest)
|
||||
|
||||
for entry in entries {
|
||||
guard let _ = entry.forDate else {
|
||||
viewContext.delete(entry)
|
||||
try? viewContext.save()
|
||||
return
|
||||
}
|
||||
}
|
||||
EventLogger.log(event: "removed_entry_no_for_date", withData: ["count": entries.count])
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
//
|
||||
// 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)
|
||||
saveAndRunDataListerners()
|
||||
} catch let error as NSError {
|
||||
fatalError("Unresolved error \(error), \(error.userInfo)")
|
||||
}
|
||||
}
|
||||
|
||||
func deleteLast(numberOfEntries: Int) {
|
||||
let entries = PersistenceController.shared.getData(startDate: Calendar.current.date(byAdding: .day, value: -numberOfEntries, to: Date())!,
|
||||
endDate: Date(),
|
||||
includedDays: [])
|
||||
for entry in entries {
|
||||
viewContext.delete(entry)
|
||||
}
|
||||
try! viewContext.save()
|
||||
}
|
||||
|
||||
func deleteRandomFromLast(numberOfEntries: Int) {
|
||||
let entries = PersistenceController.shared.getData(startDate: Calendar.current.date(byAdding: .day, value: -numberOfEntries, to: Date())!,
|
||||
endDate: Date(),
|
||||
includedDays: [])
|
||||
for entry in entries {
|
||||
if Bool.random() {
|
||||
viewContext.delete(entry)
|
||||
}
|
||||
}
|
||||
try! viewContext.save()
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
//
|
||||
// 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(includedDays: [Int]) -> [Int: [Int: [MoodEntry]]] {
|
||||
let data = PersistenceController.shared.getData(startDate: Date(timeIntervalSince1970: 0),
|
||||
endDate: Date(),
|
||||
includedDays: includedDays).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
|
||||
components.day = 1
|
||||
let startDateOfMonth = Calendar.current.date(from: components)!
|
||||
|
||||
let items = PersistenceController.shared.getData(startDate: startDateOfMonth,
|
||||
endDate: startDateOfMonth.endOfMonth,
|
||||
includedDays: [1,2,3,4,5,6,7])
|
||||
|
||||
if !items.isEmpty {
|
||||
allMonths[month] = items
|
||||
}
|
||||
}
|
||||
returnData[year] = allMonths
|
||||
}
|
||||
}
|
||||
return returnData
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
//
|
||||
// PersistenceHelper.swift
|
||||
// Feels (iOS)
|
||||
//
|
||||
// Created by Trey Tartt on 2/17/22.
|
||||
//
|
||||
|
||||
import CoreData
|
||||
|
||||
extension PersistenceController {
|
||||
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() {
|
||||
#if debug
|
||||
for idx in 1..<255 {
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
newItem.moodValue = Int16.random(in: 2 ... 4)
|
||||
if idx % 5 == 0 {
|
||||
newItem.moodValue = Int16.random(in: 0 ... 4)
|
||||
}
|
||||
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)")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
func generateObjectNotInArray(forDate date: Date = Date(), withMood mood: Mood = .placeholder) -> MoodEntry {
|
||||
let newItem = MoodEntry(context: childContext)
|
||||
newItem.timestamp = Date()
|
||||
newItem.moodValue = Int16.random(in: 2 ... 4)
|
||||
if Int16.random(in: 0 ... 400) % 5 == 0 {
|
||||
newItem.moodValue = Int16.random(in: 0 ... 4)
|
||||
}
|
||||
newItem.forDate = date
|
||||
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: Date()))
|
||||
newItem.canEdit = false
|
||||
newItem.canDelete = false
|
||||
return newItem
|
||||
}
|
||||
|
||||
func populateTestData() {
|
||||
do {
|
||||
self.clearDB()
|
||||
try viewContext.save()
|
||||
|
||||
for idx in 1..<1000 {
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Date()
|
||||
newItem.moodValue = Int16.random(in: 3 ... 4)
|
||||
if Int16.random(in: 0 ... 400) % 5 == 0 {
|
||||
newItem.moodValue = Int16.random(in: 0 ... 4)
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
saveAndRunDataListerners()
|
||||
} 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
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
//
|
||||
// PersistenceUPDATE.swift
|
||||
// Feels
|
||||
//
|
||||
// Created by Trey Tartt on 2/18/22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension PersistenceController {
|
||||
@discardableResult
|
||||
public func update(entryDate: Date, withModd mood: Mood) -> Bool {
|
||||
guard let existingEntry = getEntry(byDate: entryDate) else {
|
||||
return false
|
||||
}
|
||||
|
||||
existingEntry.setValue(mood.rawValue, forKey: "moodValue")
|
||||
saveAndRunDataListerners()
|
||||
|
||||
EventLogger.log(event: "update_entry")
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user