Shared/Persistence/ReportStore.swift (23896B)
1import CoreData
2import Foundation
3
4
5
6struct ReportStore: Sendable {
7 let persistence: PersistenceController
8
9
10
11
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
28
29
30
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
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
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
80 func save(_ questions: [Question]) async throws {
81 try await save(questions, renaming: [:])
82 }
83
84
85
86
87
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
128
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
139
140
141
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
165
166
167
168
169
170
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
236
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
250
251
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
258
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
288
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
299
300
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
314
315
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
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
347
348
349
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
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
375
376
377
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
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
404
405
406
407
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
428
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
439
440 func deleteAll() async throws {
441 let context = persistence.newBackgroundContext()
442 let viewContext = persistence.viewContext
443
444
445 let entities = ["ReportEntity", "HealthEntity", "TokenEntity", "QuestionEntity"]
446 let deleted = try await context.perform {
447
448
449 let isSQLite = context.persistentStoreCoordinator?.persistentStores
450 .allSatisfy { $0.type == NSSQLiteStoreType } ?? false
451 var deleted: [NSManagedObjectID] = []
452 if isSQLite {
453
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
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
492
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}