← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Shared/Persistence/ReportStore.swift (23896B)

1import CoreData
2import Foundation
3
4/// Reads and writes the store for the app's screens. Each call runs on its
5/// own background context and returns value types.
6struct ReportStore: Sendable {
7    let persistence: PersistenceController
8
9    /// Adds the default questions if the store has no questions at all, so a
10    /// fresh install has a survey to show. A store with imported or edited
11    /// questions is left alone.
12    @discardableResult
13    func seedDefaultQuestionsIfNeeded() async throws -> Bool {
14        let context = persistence.newBackgroundContext()
15        return try await context.perform {
16            let request = QuestionEntity.fetchRequest()
17            request.fetchLimit = 1
18            guard try context.count(for: request) == 0 else { return false }
19            for question in DefaultQuestions.make() {
20                try QuestionEntity(context: context).update(from: question)
21            }
22            try context.save()
23            return true
24        }
25    }
26
27    /// Gives the default questions and Reporter's built-in questions their
28    /// rules from `NarrativeRule.builtIn` if they have none, as in stores made
29    /// before questions stored their rules. A rule the user cleared is
30    /// stored blank, so it isn't filled again.
31    func fillMissingNarrativeRules(now: Date = Date()) async throws {
32        let context = persistence.newBackgroundContext()
33        try await context.perform {
34            let request = QuestionEntity.fetchRequest()
35            request.predicate = NSPredicate(
36                format: "narrativeRule == nil AND id IN %@", Array(NarrativeRule.builtIn.keys))
37            let entities = try context.fetch(request)
38            guard !entities.isEmpty else { return }
39            for entity in entities {
40                var question = try entity.question()
41                question.narrativeRule = NarrativeRule.builtIn[question.id]
42                question.modifiedAt = now
43                try entity.update(from: question)
44            }
45            try context.save()
46        }
47    }
48
49    /// The questions a report of `kind` asks, in survey order.
50    func surveyQuestions(for kind: ReportKind) async throws -> [Question] {
51        let survey = SurveyKinds(surveyFor: kind)
52        let context = persistence.newBackgroundContext()
53        return try await context.perform {
54            let request = QuestionEntity.fetchRequest()
55            request.predicate = NSPredicate(format: "archivedAt == nil")
56            request.sortDescriptors = [
57                NSSortDescriptor(key: "order", ascending: true),
58                NSSortDescriptor(key: "id", ascending: true),
59            ]
60            return try context.fetch(request)
61                .map { try $0.question() }
62                .filter { $0.askOn.contains(survey) }
63        }
64    }
65
66    /// Every question, archived or not, in survey order.
67    func allQuestions() async throws -> [Question] {
68        let context = persistence.newBackgroundContext()
69        return try await context.perform {
70            let request = QuestionEntity.fetchRequest()
71            request.sortDescriptors = [
72                NSSortDescriptor(key: "order", ascending: true),
73                NSSortDescriptor(key: "id", ascending: true),
74            ]
75            return try context.fetch(request).map { try $0.question() }
76        }
77    }
78
79    /// Saves questions, adding those not yet in the store.
80    func save(_ questions: [Question]) async throws {
81        try await save(questions, renaming: [:])
82    }
83
84    /// Saves a choice question along with renamed options, by old text.
85    /// Past answers given with an old option are rewritten to the new one,
86    /// as renaming a token renames it throughout history, and their reports
87    /// count as modified.
88    func save(_ question: Question, renamingOptions renames: [String: String]) async throws {
89        try await save([question], renaming: [question.id: renames])
90    }
91
92    private func save(_ questions: [Question], renaming: [String: [String: String]]) async throws {
93        let context = persistence.newBackgroundContext()
94        try await context.perform {
95            let request = QuestionEntity.fetchRequest()
96            request.predicate = NSPredicate(format: "id IN %@", questions.map(\.id))
97            let entities = Dictionary(
98                try context.fetch(request).compactMap { entity in entity.id.map { ($0, entity) } },
99                uniquingKeysWith: { first, _ in first })
100            for question in questions {
101                try (entities[question.id] ?? QuestionEntity(context: context)).update(from: question)
102            }
103            for question in questions {
104                guard let renames = renaming[question.id], !renames.isEmpty else { continue }
105                try Self.renameOptions(renames, of: question.id, at: question.modifiedAt, in: context)
106            }
107            try context.save()
108        }
109    }
110
111    private static func renameOptions(
112        _ renames: [String: String], of questionID: String, at now: Date, in context: NSManagedObjectContext
113    ) throws {
114        let request = ResponseEntity.fetchRequest()
115        request.predicate = NSPredicate(format: "questionID == %@", questionID)
116        for entity in try context.fetch(request) {
117            guard let data = entity.value,
118                case .options(let options) = try ModelCoding.decode(ResponseValue.self, from: data)
119            else { continue }
120            let renamed = options.map { renames[$0] ?? $0 }
121            guard renamed != options else { continue }
122            entity.value = try ModelCoding.encode(ResponseValue.options(renamed))
123            entity.report?.modifiedAt = now
124        }
125    }
126
127    /// How many reports answered the question with `id`. Skipped answers
128    /// don't count.
129    func answerCount(questionID id: String) async throws -> Int {
130        let context = persistence.newBackgroundContext()
131        return try await context.perform {
132            let request = ResponseEntity.fetchRequest()
133            request.predicate = NSPredicate(format: "questionID == %@ AND value != nil", id)
134            return try context.count(for: request)
135        }
136    }
137
138    /// Deletes the question with `id` if it has no answers, along with the
139    /// reports' records of it being skipped. A question with answers is left
140    /// alone, since they'd lose their meaning; it's archived instead.
141    /// Returns whether the question was deleted.
142    @discardableResult
143    func deleteQuestion(id: String, now: Date = Date()) async throws -> Bool {
144        let context = persistence.newBackgroundContext()
145        return try await context.perform {
146            let responses = ResponseEntity.fetchRequest()
147            responses.predicate = NSPredicate(format: "questionID == %@", id)
148            let skipped = try context.fetch(responses)
149            guard skipped.allSatisfy({ $0.value == nil }) else { return false }
150            let questions = QuestionEntity.fetchRequest()
151            questions.predicate = NSPredicate(format: "id == %@", id)
152            let tokens = TokenEntity.fetchRequest()
153            tokens.predicate = NSPredicate(format: "questionID == %@", id)
154            for response in skipped {
155                response.report?.modifiedAt = now
156            }
157            let objects: [NSManagedObject] = skipped + (try context.fetch(questions)) + (try context.fetch(tokens))
158            objects.forEach(context.delete)
159            try context.save()
160            return true
161        }
162    }
163
164    /// Merges the question with `id` into the question with `target`, of
165    /// the same kind, and deletes it. Its responses and tokens are
166    /// reassigned to `target`; each response's stored prompt is unchanged,
167    /// and a token named as one of `target`'s is merged into it. Its choice answers are added
168    /// to `target`'s. A report that answered both keeps one answer: the
169    /// one that wasn't skipped, both sets of tokens, or else `target`'s.
170    /// Unlike merging tokens, this can't be undone.
171    func mergeQuestion(_ id: String, into target: String, now: Date = Date()) async throws {
172        let context = persistence.newBackgroundContext()
173        try await context.perform {
174            let questions = QuestionEntity.fetchRequest()
175            questions.predicate = NSPredicate(format: "id IN %@", [id, target])
176            let entities = try context.fetch(questions)
177            guard let sourceEntity = entities.first(where: { $0.id == id }),
178                let targetEntity = entities.first(where: { $0.id == target })
179            else { return }
180            let source = try sourceEntity.question()
181            var merged = try targetEntity.question()
182            guard source.kind == merged.kind else { return }
183
184            let tokens = TokenEntity.fetchRequest()
185            tokens.predicate = NSPredicate(format: "questionID IN %@", [id, target])
186            let tokenEntities = try context.fetch(tokens)
187            var targetTokens: [String: String] = [:]
188            for entity in tokenEntities where entity.questionID == target {
189                let token = try entity.token()
190                guard token.mergedInto == nil else { continue }
191                targetTokens[token.text.lowercased()] = token.id
192            }
193            for entity in tokenEntities where entity.questionID == id {
194                var token = try entity.token()
195                token.questionID = target
196                if token.mergedInto == nil, let match = targetTokens[token.text.lowercased()] {
197                    token.mergedInto = match
198                }
199                token.modifiedAt = now
200                try entity.update(from: token)
201            }
202
203            let responses = ResponseEntity.fetchRequest()
204            responses.predicate = NSPredicate(format: "questionID == %@", id)
205            for response in try context.fetch(responses) {
206                guard let report = response.report else { continue }
207                report.modifiedAt = now
208                let existing = (report.responses as? Set<ResponseEntity>)?.first { $0.questionID == target }
209                guard let existing else {
210                    response.questionID = target
211                    continue
212                }
213                let moved = try response.response().value
214                let kept = try existing.response().value
215                switch (kept, moved) {
216                case (nil, let value?):
217                    existing.value = try ModelCoding.encode(value)
218                case (.tokens(let keptIDs)?, .tokens(let movedIDs)?):
219                    let combined = keptIDs + movedIDs.filter { !keptIDs.contains($0) }
220                    existing.value = try ModelCoding.encode(ResponseValue.tokens(combined))
221                default:
222                    break
223                }
224                context.delete(response)
225            }
226
227            merged.options += source.options.filter { !merged.options.contains($0) }
228            merged.modifiedAt = now
229            try targetEntity.update(from: merged)
230            context.delete(sourceEntity)
231            try context.save()
232        }
233    }
234
235    /// The questions with `ids`, archived or not, in the order given. IDs
236    /// with no question are left out.
237    func questions(ids: [String]) async throws -> [Question] {
238        let context = persistence.newBackgroundContext()
239        return try await context.perform {
240            let request = QuestionEntity.fetchRequest()
241            request.predicate = NSPredicate(format: "id IN %@", ids)
242            let byID = Dictionary(
243                try context.fetch(request).map { try $0.question() }.map { ($0.id, $0) },
244                uniquingKeysWith: { first, _ in first })
245            return ids.compactMap { byID[$0] }
246        }
247    }
248
249    /// Entries for the tokens with `ids`, archived or not, by ID. A token
250    /// merged into another shows that token's name and place, but keeps its
251    /// own ID, so an answer that uses it is unchanged.
252    func tokenEntries(ids: [String]) async throws -> [String: VocabularyEntry] {
253        let context = persistence.newBackgroundContext()
254        return try await context.perform {
255            var tokens: [String: Token] = [:]
256            var wanted = Set(ids)
257            // Fetch the tokens, then the tokens they were merged into, and so
258            // on along each chain.
259            while !wanted.isEmpty {
260                let request = TokenEntity.fetchRequest()
261                request.predicate = NSPredicate(format: "id IN %@", Array(wanted))
262                let found = try context.fetch(request).map { try $0.token() }
263                for token in found { tokens[token.id] = token }
264                wanted = Set(found.compactMap(\.mergedInto)).subtracting(tokens.keys)
265            }
266            var entries: [String: VocabularyEntry] = [:]
267            for id in ids {
268                guard var token = tokens[id] else { continue }
269                var seen: Set<String> = [id]
270                while let next = token.mergedInto.flatMap({ tokens[$0] }), seen.insert(next.id).inserted {
271                    token = next
272                }
273                entries[id] = VocabularyEntry(
274                    id: id,
275                    text: token.text,
276                    useCount: 0,
277                    coordinate: token.place?.coordinate,
278                    externalID: token.place?.externalID,
279                    narrativeForm: token.narrativeForm,
280                    isRenamed: token.place?.externalID != nil && !token.isNamedByDirectory
281                )
282            }
283            return entries
284        }
285    }
286
287    /// The tokens of `questionIDs` that haven't been merged into another,
288    /// archived or not.
289    func tokens(for questionIDs: [String]) async throws -> [Token] {
290        let context = persistence.newBackgroundContext()
291        return try await context.perform {
292            let request = TokenEntity.fetchRequest()
293            request.predicate = NSPredicate(format: "questionID IN %@ AND mergedInto == nil", questionIDs)
294            return try context.fetch(request).map { try $0.token() }
295        }
296    }
297
298    /// Saves an edited token. A new text renames it throughout history,
299    /// since answers refer to it by ID. A token not in the store is left
300    /// out: tokens are added with the reports that first use them.
301    func save(_ token: Token) async throws {
302        let context = persistence.newBackgroundContext()
303        try await context.perform {
304            let request = TokenEntity.fetchRequest()
305            request.predicate = NSPredicate(format: "id == %@", token.id)
306            request.fetchLimit = 1
307            guard let entity = try context.fetch(request).first else { return }
308            try entity.update(from: token)
309            try context.save()
310        }
311    }
312
313    /// Merges the token with `id` into the token with `target`, so answers
314    /// that use it read as using that token, or separates it again when
315    /// `target` is `nil`. No answer is rewritten, so a merge can be undone.
316    func merge(_ id: String, into target: String?) async throws {
317        let context = persistence.newBackgroundContext()
318        try await context.perform {
319            let request = TokenEntity.fetchRequest()
320            request.predicate = NSPredicate(format: "id == %@", id)
321            request.fetchLimit = 1
322            guard let entity = try context.fetch(request).first else { return }
323            var token = try entity.token()
324            token.mergedInto = target
325            token.modifiedAt = Date()
326            try entity.update(from: token)
327            try context.save()
328        }
329    }
330
331    /// Ranked suggestions for each of `questionIDs`. See `Vocabulary`.
332    func vocabulary(for questionIDs: [String]) async throws -> [String: [VocabularyEntry]] {
333        let context = persistence.newBackgroundContext()
334        return try await context.perform {
335            try Vocabulary.entries(for: questionIDs, in: context)
336        }
337    }
338
339    func report(id: UUID) async throws -> Report? {
340        let context = persistence.newBackgroundContext()
341        return try await context.perform {
342            try Self.entity(id: id, in: context)?.report()
343        }
344    }
345
346    /// The most recent answered report before `date`, if it's no more than
347    /// `interval` earlier. Instant Reports still waiting for answers are
348    /// passed over. A new report carries its people forward: see
349    /// `SurveyModel`.
350    func previousReport(before date: Date, within interval: TimeInterval) async throws -> Report? {
351        let context = persistence.newBackgroundContext()
352        return try await context.perform {
353            let request = ReportEntity.fetchRequest()
354            request.predicate = NSPredicate(
355                format: "date < %@ AND date >= %@ AND state == %@",
356                date as NSDate, date.addingTimeInterval(-interval) as NSDate,
357                ReportState.complete.rawValue)
358            request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
359            request.fetchLimit = 1
360            return try context.fetch(request).first?.report()
361        }
362    }
363
364    /// How many reports are logged and waiting for answers.
365    func passiveCount() async throws -> Int {
366        let context = persistence.newBackgroundContext()
367        return try await context.perform {
368            let request = ReportEntity.fetchRequest()
369            request.predicate = NSPredicate(format: "state == %@", ReportState.passive.rawValue)
370            return try context.count(for: request)
371        }
372    }
373
374    /// Where a list of the newest `count` reports should start: the start of
375    /// the day, in `calendar`, of the first report beyond them, so the list
376    /// holds at least `count` reports and no day is cut short. `nil` when
377    /// there are no more than `count` reports, so the list holds them all.
378    func listStart(covering count: Int, calendar: Calendar = .current) async throws -> Date? {
379        let context = persistence.newBackgroundContext()
380        return try await context.perform {
381            let request = NSFetchRequest<NSDictionary>(entityName: "ReportEntity")
382            request.resultType = .dictionaryResultType
383            request.propertiesToFetch = ["date"]
384            request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
385            request.fetchOffset = count
386            request.fetchLimit = 1
387            guard let date = try context.fetch(request).first?["date"] as? Date else { return nil }
388            return calendar.startOfDay(for: date)
389        }
390    }
391
392    /// Sets the context of a report saved before its capture finished.
393    func setContext(_ captured: Context, for id: UUID, now: Date = Date()) async throws {
394        let context = persistence.newBackgroundContext()
395        try await context.perform {
396            guard let entity = try Self.entity(id: id, in: context) else { return }
397            entity.context = try ModelCoding.encode(captured)
398            entity.modifiedAt = now
399            try context.save()
400        }
401    }
402
403    /// Saves new answers to an existing report, whether filling in an instant
404    /// report or editing a finished one, together with the tokens created
405    /// while answering. Only the answers and what marks the report complete
406    /// are taken from `report`, so a context captured meanwhile isn't
407    /// overwritten.
408    func saveAnswers(_ report: Report, newTokens: [Token] = []) async throws {
409        let context = persistence.newBackgroundContext()
410        try await context.perform {
411            guard let entity = try Self.entity(id: report.id, in: context) else {
412                throw ReportStoreError.missingReport(report.id)
413            }
414            var stored = try entity.report()
415            stored.responses = report.responses
416            stored.state = report.state
417            stored.completedAt = report.completedAt
418            stored.modifiedAt = report.modifiedAt
419            for token in newTokens {
420                try TokenEntity(context: context).update(from: token)
421            }
422            try entity.update(from: stored)
423            try context.save()
424        }
425    }
426
427    /// Deletes a report and its responses. The tokens its answers used are
428    /// kept: other reports may use them, and they're never deleted.
429    func delete(id: UUID) async throws {
430        let context = persistence.newBackgroundContext()
431        try await context.perform {
432            guard let entity = try Self.entity(id: id, in: context) else { return }
433            context.delete(entity)
434            try context.save()
435        }
436    }
437
438    /// Deletes every report, question and token, leaving the store as a
439    /// fresh install has it before the default questions are added.
440    func deleteAll() async throws {
441        let context = persistence.newBackgroundContext()
442        let viewContext = persistence.viewContext
443        // Responses go with their reports, by the cascade. Health entries
444        // are named, so their deletions are reported like the rest.
445        let entities = ["ReportEntity", "HealthEntity", "TokenEntity", "QuestionEntity"]
446        let deleted = try await context.perform {
447            // Batch deletes run in SQLite without loading each object; the
448            // in-memory stores tests use don't support them.
449            let isSQLite = context.persistentStoreCoordinator?.persistentStores
450                .allSatisfy { $0.type == NSSQLiteStoreType } ?? false
451            var deleted: [NSManagedObjectID] = []
452            if isSQLite {
453                // A batch delete reports only the objects it was asked for.
454                let responses = NSFetchRequest<NSManagedObjectID>(entityName: "ResponseEntity")
455                responses.resultType = .managedObjectIDResultType
456                deleted += try context.fetch(responses)
457            }
458            for name in entities {
459                let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: name)
460                if isSQLite {
461                    let request = NSBatchDeleteRequest(fetchRequest: fetch)
462                    request.resultType = .resultTypeObjectIDs
463                    let result = try context.execute(request) as? NSBatchDeleteResult
464                    deleted += result?.result as? [NSManagedObjectID] ?? []
465                } else {
466                    fetch.includesPropertyValues = false
467                    for case let object as NSManagedObject in try context.fetch(fetch) {
468                        context.delete(object)
469                    }
470                }
471            }
472            try context.save()
473            return deleted
474        }
475        // A batch delete bypasses the contexts, so the screens are told.
476        if !deleted.isEmpty {
477            await viewContext.perform {
478                NSManagedObjectContext.mergeChanges(
479                    fromRemoteContextSave: [NSDeletedObjectsKey: deleted], into: [viewContext])
480            }
481        }
482    }
483
484    private static func entity(id: UUID, in context: NSManagedObjectContext) throws -> ReportEntity? {
485        let request = ReportEntity.fetchRequest()
486        request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
487        request.fetchLimit = 1
488        return try context.fetch(request).first
489    }
490
491    /// Saves a new report together with the tokens created while answering
492    /// it, in one transaction.
493    func insert(_ report: Report, newTokens: [Token] = []) async throws {
494        let context = persistence.newBackgroundContext()
495        try await context.perform {
496            for token in newTokens {
497                try TokenEntity(context: context).update(from: token)
498            }
499            try ReportEntity(context: context).update(from: report)
500            try context.save()
501        }
502    }
503}
504
505enum ReportStoreError: Error {
506    case missingReport(UUID)
507}