← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Services/Charts/AnswerSummary.swift (9998B)

1import CoreData
2import Foundation
3
4/// The span of reports the charts cover, ending now.
5enum ChartPeriod: String, CaseIterable, Sendable {
6    case week
7    case month
8    case year
9    case all
10
11    var title: String {
12        switch self {
13        case .week: String(localized: "Past Week", comment: "A chart period")
14        case .month: String(localized: "Past Month", comment: "A chart period")
15        case .year: String(localized: "Past Year", comment: "A chart period")
16        case .all: String(localized: "All Time", comment: "A chart period")
17        }
18    }
19
20    /// When the period starts, or `nil` for all time.
21    func start(endingAt now: Date, calendar: Calendar = .current) -> Date? {
22        switch self {
23        case .week: calendar.date(byAdding: .day, value: -7, to: now)
24        case .month: calendar.date(byAdding: .month, value: -1, to: now)
25        case .year: calendar.date(byAdding: .year, value: -1, to: now)
26        case .all: nil
27        }
28    }
29
30    /// The span each point of a trend covers: days for a week or a month,
31    /// weeks for a year, and months for all time.
32    var bucket: Calendar.Component {
33        switch self {
34        case .week, .month: .day
35        case .year: .weekOfYear
36        case .all: .month
37        }
38    }
39}
40
41extension Calendar {
42    /// The start of the `component` that `date` falls in.
43    func start(of component: Calendar.Component, for date: Date) -> Date {
44        dateInterval(of: component, for: date)?.start ?? date
45    }
46}
47
48/// A value for one span of a trend, such as a day or a month, with its range
49/// where it has one.
50struct TrendPoint: Identifiable, Equatable, Sendable {
51    /// The start of the span.
52    var date: Date
53    var value: Double
54    var low: Double?
55    var high: Double?
56
57    var id: Date { date }
58}
59
60/// One answer to a question, with when its report was made.
61struct AnswerRecord: Sendable {
62    var questionID: String
63    var date: Date
64    var value: ResponseValue
65}
66
67/// How often one answer was given: a token, a choice, or yes or no.
68struct Tally: Identifiable, Equatable, Sendable {
69    /// The token's ID, after merges, or the option.
70    var id: String
71    var label: String
72    var count: Int
73}
74
75/// The spread of a number question's answers.
76struct NumberSummary: Equatable, Sendable {
77    var mean: Double
78    var lowest: Double
79    var highest: Double
80}
81
82/// What a question's answers came to over a period.
83struct QuestionSummary: Identifiable, Equatable, Sendable {
84    var question: Question
85    /// How many reports answered the question.
86    var answered: Int
87    /// For token, choice and yes/no questions: each answer and how many
88    /// reports gave it. Yes/no and choice answers keep the question's order;
89    /// tokens are most used first.
90    var tallies: [Tally] = []
91    var numbers: NumberSummary?
92    /// For note questions: the notes, newest first.
93    var notes: [Note] = []
94    /// For yes/no questions, the share answering yes in each span; for
95    /// number questions, the average.
96    var trend: [TrendPoint] = []
97    /// For token and choice questions: how many reports gave each answer in
98    /// each span, by the tally's ID.
99    var tallyTrends: [String: [TrendPoint]] = [:]
100
101    var id: String { question.id }
102
103    struct Note: Equatable, Sendable {
104        var date: Date
105        var text: String
106    }
107
108    /// The share of the reports answering the question that gave `tally`.
109    func share(of tally: Tally) -> Double {
110        answered == 0 ? 0 : Double(tally.count) / Double(answered)
111    }
112}
113
114enum AnswerSummary {
115    /// Summaries of the questions answered in `rows`: unarchived questions
116    /// in survey order, then archived ones. Questions without answers are
117    /// left out. A token merged into another counts as that token, and once
118    /// per answer.
119    /// Trends are split into spans of `bucket` in `calendar`.
120    static func summarise(
121        _ rows: [AnswerRecord], questions: [Question], lookup: SummaryLookup,
122        bucket: Calendar.Component = .day, calendar: Calendar = .current
123    ) -> [QuestionSummary] {
124        let byQuestion = Dictionary(grouping: rows, by: \.questionID)
125        let ordered = questions.filter { $0.archivedAt == nil } + questions.filter { $0.archivedAt != nil }
126        return ordered.compactMap { question in
127            guard let rows = byQuestion[question.id], !rows.isEmpty else { return nil }
128            return summary(of: question, rows: rows, lookup: lookup, bucket: bucket, calendar: calendar)
129        }
130    }
131
132    private static func summary(
133        of question: Question, rows: [AnswerRecord], lookup: SummaryLookup,
134        bucket: Calendar.Component, calendar: Calendar
135    ) -> QuestionSummary {
136        var summary = QuestionSummary(question: question, answered: rows.count)
137        var counts: [String: Int] = [:]
138        var numbers: [Double] = []
139        // By the start of each span: how many reports answered, and gave
140        // each answer, and the numbers given.
141        var answeredBySpan: [Date: Int] = [:]
142        var countsBySpan: [String: [Date: Int]] = [:]
143        var numbersBySpan: [Date: [Double]] = [:]
144        for row in rows {
145            let span = calendar.start(of: bucket, for: row.date)
146            answeredBySpan[span, default: 0] += 1
147            func count(_ ids: Set<String>) {
148                for id in ids {
149                    counts[id, default: 0] += 1
150                    countsBySpan[id, default: [:]][span, default: 0] += 1
151                }
152            }
153            switch row.value {
154            case .tokens(let ids):
155                count(Set(ids.map { lookup.mergedIDs[$0] ?? $0 }))
156            case .place(let place):
157                count([lookup.mergedIDs[place.tokenID] ?? place.tokenID])
158            case .options(let options):
159                count(Set(options))
160            case .number(let number):
161                let number = NSDecimalNumber(decimal: number).doubleValue
162                numbers.append(number)
163                numbersBySpan[span, default: []].append(number)
164            case .text(let text):
165                let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
166                if !text.isEmpty { summary.notes.append(.init(date: row.date, text: text)) }
167            }
168        }
169        if let lowest = numbers.min(), let highest = numbers.max() {
170            summary.numbers = NumberSummary(
171                mean: numbers.reduce(0, +) / Double(numbers.count), lowest: lowest, highest: highest)
172        }
173        summary.notes.sort { $0.date > $1.date }
174
175        switch question.kind {
176        case .yesNo:
177            let yes = countsBySpan[ResponseValue.yesOption] ?? [:]
178            summary.trend = answeredBySpan.map { span, answered in
179                TrendPoint(date: span, value: Double(yes[span] ?? 0) / Double(answered))
180            }
181            .sorted { $0.date < $1.date }
182        case .number:
183            summary.trend = numbersBySpan.map { span, numbers in
184                TrendPoint(
185                    date: span, value: numbers.reduce(0, +) / Double(numbers.count),
186                    low: numbers.min(), high: numbers.max())
187            }
188            .sorted { $0.date < $1.date }
189        default:
190            summary.tallyTrends = countsBySpan.mapValues { counts in
191                counts.map { TrendPoint(date: $0.key, value: Double($0.value)) }.sorted { $0.date < $1.date }
192            }
193        }
194
195        switch question.kind {
196        case .yesNo, .choice:
197            let fixed = question.kind == .yesNo ? [ResponseValue.yesOption, ResponseValue.noOption] : question.options
198            // Answers since renamed or removed from the options follow them.
199            let others = counts.keys.filter { !fixed.contains($0) }.sorted { counts[$0]! > counts[$1]! }
200            summary.tallies = (fixed + others).compactMap { option in
201                counts[option].map { Tally(id: option, label: label(of: option), count: $0) }
202            }
203        default:
204            summary.tallies = counts.compactMap { id, count in
205                lookup.tokenTexts[id].map { Tally(id: id, label: $0, count: count) }
206            }
207            .sorted { lhs, rhs in
208                lhs.count != rhs.count
209                    ? lhs.count > rhs.count
210                    : lhs.label.localizedStandardCompare(rhs.label) == .orderedAscending
211            }
212        }
213        return summary
214    }
215
216    private static func label(of option: String) -> String {
217        switch option {
218        case ResponseValue.yesOption: String(localized: "Yes", comment: "Answer to a yes/no question")
219        case ResponseValue.noOption: String(localized: "No", comment: "Answer to a yes/no question")
220        default: option
221        }
222    }
223}
224
225extension ReportStore {
226    /// Every answer given since `start`, or ever when it's `nil`. Skipped
227    /// questions are left out.
228    func answers(since start: Date?) async throws -> [AnswerRecord] {
229        let context = persistence.newBackgroundContext()
230        return try await context.perform {
231            let request = NSFetchRequest<NSDictionary>(entityName: "ResponseEntity")
232            request.resultType = .dictionaryResultType
233            request.predicate =
234                if let start {
235                    NSPredicate(format: "value != nil AND report.date >= %@", start as NSDate)
236                } else {
237                    NSPredicate(format: "value != nil")
238                }
239            request.propertiesToFetch = ["questionID", "value", "report.date"]
240            return try context.fetch(request).compactMap { row in
241                guard let questionID = row["questionID"] as? String,
242                    let data = row["value"] as? Data,
243                    let date = row["report.date"] as? Date
244                else { return nil }
245                return AnswerRecord(
246                    questionID: questionID, date: date,
247                    value: try ModelCoding.decode(ResponseValue.self, from: data))
248            }
249        }
250    }
251}