← All repositories

reportage

A life-logging app for iPhone

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


commit 3286b548f26c1e3bbe46be672db24d617366c4d7
parent 254867909e70e71fb6b716c4cfb9456a2454d00c
Author: Michael Camilleri <[email protected]>
Date:   Wed,  4 Nov 2026 08:31:51 +0900

Carry the previous report's people forward at the same place

When the user files reports in quick succession at the same place, they
are usually with the same people, but each new report started with an
empty people answer that had to be filled in again.

This commit pre-selects the people of the previous report when a new
report's place is the same as that report's place. The previous report
is the latest answered one no more than 2 hours earlier; an Instant
Report still waiting for answers is passed over. The place counts
whether the user chose it or it was pre-filled from the location, and
places and people are compared as the tokens they were merged into.
The people follow the place: choosing a different place takes them
away and choosing the same place again brings them back, until the user
changes the people answer, after which it is left alone. As with the
place pre-fill, this applies to new reports only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Diffstat

MNotes/Design.md | 19+++++++++++++++++++
MReportage/Views/Survey/PlacePicker.swift | 8+++++++-
MReportage/Views/Survey/SurveyModel.swift | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MReportage/Views/Survey/SurveyView.swift | 5++++-
MShared/Persistence/ReportStore.swift | 18++++++++++++++++++
MTests/Unit/ReportStoreTests.swift | 16++++++++++++++++
MTests/Unit/SurveyModelTests.swift | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

7 files changed, 282 insertions(+), 2 deletions(-)

diff --git a/Notes/Design.md b/Notes/Design.md

@@ -319,6 +319,25 @@ coordinate centroid for places. It is rebuilt from responses and never synced.
 Token identity and text are not part of the index: they live in the synced
 `Token` records.
 
+### Carrying people forward
+
+In a new report, the people of the previous report are chosen already when
+the place is the same as that report's place: being in the same place
+shortly after is good evidence of being with the same people. The previous
+report is the latest answered one before this report, if it's no more than
+2 hours earlier. Instant Reports still waiting for answers are passed over.
+The place counts whether the user chose it or it was pre-filled from the
+location. Places and people are compared as the tokens they were merged
+into, and people no longer suggested are left out.
+
+The people follow the place: choosing a different place, or none, takes
+them away, and choosing the same place again brings them back. Once the
+user changes the people answer, it's left alone. Activities aren't carried
+forward: they change more often than company, and copying them would
+undercut a random prompt. As with the place pre-fill, this applies to new
+reports only, not to reports being edited or Instant Reports being filled
+in.
+
 ### Place names
 
 A place has one name: the one MapKit gave when it was chosen, in the app's

diff --git a/Reportage/Views/Survey/PlacePicker.swift b/Reportage/Views/Survey/PlacePicker.swift

@@ -70,7 +70,13 @@ final class PlacePicker {
     private(set) var sections: [PlaceSection] = []
     /// Whether `query` names none of the user's places, so it can be added.
     private(set) var canAddQuery = false
-    private(set) var selection: PlaceCandidate?
+    private(set) var selection: PlaceCandidate? {
+        didSet {
+            if selection?.id != oldValue?.id { onSelectionChange?() }
+        }
+    }
+    /// Called when a different place is chosen, or none.
+    @ObservationIgnored var onSelectionChange: (() -> Void)?
     /// Whether a directory search is under way.
     private(set) var isSearching = false
     /// Whether the place the report is at may be chosen when the location

diff --git a/Reportage/Views/Survey/SurveyModel.swift b/Reportage/Views/Survey/SurveyModel.swift

@@ -31,6 +31,16 @@ final class SurveyModel {
     private let originalResponses: [String: Response]
     /// Live context, captured from when the survey opens.
     private var contextTask: Task<Context, Never>?
+    /// What a new report carries forward from the previous one: its place
+    /// answers and its people answers, by question ID.
+    private var carried: (places: [String: String], people: [String: [String]])?
+    /// For each place question, the ID each place reads as: see
+    /// `survivorIDs(_:)`.
+    private var placeIDs: [String: [String: String]] = [:]
+
+    /// How long after a report its people are carried into the next one
+    /// at the same place.
+    static let carryInterval: TimeInterval = 2 * 60 * 60
 
     convenience init(
         kind: ReportKind,
@@ -40,12 +50,14 @@ final class SurveyModel {
         promptedAt: Date? = nil,
         questions: [Question],
         vocabulary: [String: [VocabularyEntry]],
+        previous: Report? = nil,
         directory: any PlaceDirectory = MapKitPlaceDirectory()
     ) {
         self.init(
             kind: kind, date: date, timeZone: timeZone.identifier, trigger: trigger,
             promptedAt: promptedAt, existing: nil, questions: questions, vocabulary: vocabulary,
             directory: directory)
+        if let previous { carry(from: previous, vocabulary: vocabulary) }
     }
 
     /// A survey that edits `report`, as of the moment it describes, starting
@@ -126,6 +138,70 @@ final class SurveyModel {
         self.placePickers = placePickers
     }
 
+    // MARK: Carrying forward
+
+    /// Sets up the people of `previous`, the last report, to be chosen
+    /// whenever this report's place is the same as its place. Tokens are
+    /// compared as the tokens they were merged into, and people that are
+    /// no longer suggested are left out.
+    private func carry(from previous: Report, vocabulary: [String: [VocabularyEntry]]) {
+        var places: [String: String] = [:]
+        var people: [String: [String]] = [:]
+        for response in previous.responses {
+            let id = Self.survivorIDs(vocabulary[response.questionID] ?? [])
+            switch response.value {
+            case .place(let answer) where placePickers[response.questionID] != nil:
+                places[response.questionID] = id[answer.tokenID] ?? answer.tokenID
+            case .tokens(let ids) where peopleQuestionIDs.contains(response.questionID):
+                var seen: Set<String> = []
+                let ids = ids.compactMap { id[$0] }.filter { seen.insert($0).inserted }
+                if !ids.isEmpty { people[response.questionID] = ids }
+            default:
+                continue
+            }
+        }
+        guard !places.isEmpty, !people.isEmpty else { return }
+        carried = (places, people)
+        for (questionID, picker) in placePickers {
+            placeIDs[questionID] = Self.survivorIDs(vocabulary[questionID] ?? [])
+            picker.onSelectionChange = { [weak self] in self?.placeChanged() }
+        }
+    }
+
+    private var peopleQuestionIDs: Set<String> {
+        Set(questions.filter { $0.kind == .people }.map(\.id))
+    }
+
+    /// Chooses the carried people when a place chosen is the previous
+    /// report's, or takes them away again when it changes, unless the user
+    /// has changed them.
+    private func placeChanged() {
+        guard let carried else { return }
+        let isSame = placePickers.contains { questionID, picker in
+            guard let chosen = picker.selectedTokenID else { return false }
+            return (placeIDs[questionID]?[chosen] ?? chosen) == carried.places[questionID]
+        }
+        for (questionID, ids) in carried.people {
+            guard let picker = pickers[questionID] else { continue }
+            if isSame {
+                picker.prefill(ids)
+            } else if picker.isPrefilled {
+                picker.prefill([])
+            }
+        }
+    }
+
+    /// The ID each of `entries` reads as, by its own ID and the IDs of the
+    /// tokens merged into it.
+    private static func survivorIDs(_ entries: [VocabularyEntry]) -> [String: String] {
+        var ids: [String: String] = [:]
+        for entry in entries {
+            ids[entry.id] = entry.id
+            for merged in entry.merged { ids[merged.id] = entry.id }
+        }
+        return ids
+    }
+
     var currentQuestion: Question? {
         questions.indices.contains(index) ? questions[index] : nil
     }
@@ -376,8 +452,15 @@ final class TokenPicker {
 
     func isSelected(_ id: String) -> Bool { selection.contains(id) }
 
+    /// Whether the user has changed the selection, after which it's never
+    /// pre-filled.
+    private(set) var isEdited = false
+    /// Whether the selection is a pre-fill the user hasn't changed.
+    private(set) var isPrefilled = false
+
     /// Selects or deselects `id`. Selecting clears the query.
     func toggle(_ id: String) {
+        markEdited()
         if let position = selection.firstIndex(of: id) {
             selection.remove(at: position)
             return
@@ -395,6 +478,7 @@ final class TokenPicker {
     func addQuery() {
         let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
         guard !text.isEmpty else { return }
+        markEdited()
         if let existing = entry(named: text) {
             if !isSelected(existing.id) { toggle(existing.id) }
         } else {
@@ -407,10 +491,25 @@ final class TokenPicker {
     }
 
     func clear() {
+        markEdited()
         selection = []
         query = ""
     }
 
+    /// Selects `ids` as a guess the user can change, or clears an earlier
+    /// guess when `ids` is empty. Does nothing once the user has changed
+    /// the selection.
+    func prefill(_ ids: [String]) {
+        guard !isEdited, isPrefilled || selection.isEmpty else { return }
+        selection = ids
+        isPrefilled = !ids.isEmpty
+    }
+
+    private func markEdited() {
+        isEdited = true
+        isPrefilled = false
+    }
+
     /// Selects `ids`, as an existing answer does, adding `entries` for any
     /// the suggestions leave out so each selected token shows.
     func preselect(_ ids: [String], entries extra: [VocabularyEntry]) {

diff --git a/Reportage/Views/Survey/SurveyView.swift b/Reportage/Views/Survey/SurveyView.swift

@@ -77,13 +77,16 @@ struct SurveySheet: View {
                 model = SurveyModel(
                     editing: existing, questions: questions, vocabulary: vocabulary, tokens: tokens)
             } else {
+                let previous = try await store.previousReport(
+                    before: request.date, within: SurveyModel.carryInterval)
                 model = SurveyModel(
                     kind: request.kind,
                     date: request.date,
                     trigger: request.trigger,
                     promptedAt: request.promptedAt,
                     questions: questions,
-                    vocabulary: vocabulary
+                    vocabulary: vocabulary,
+                    previous: previous
                 )
                 model.startCapture()
             }

diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift

@@ -342,6 +342,24 @@ struct ReportStore: Sendable {
         }
     }
 
+    /// The most recent answered report before `date`, if it's no more than
+    /// `interval` earlier. Instant Reports still waiting for answers are
+    /// passed over. A new report carries its people forward: see
+    /// `SurveyModel`.
+    func previousReport(before date: Date, within interval: TimeInterval) async throws -> Report? {
+        let context = persistence.newBackgroundContext()
+        return try await context.perform {
+            let request = ReportEntity.fetchRequest()
+            request.predicate = NSPredicate(
+                format: "date < %@ AND date >= %@ AND state == %@",
+                date as NSDate, date.addingTimeInterval(-interval) as NSDate,
+                ReportState.complete.rawValue)
+            request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
+            request.fetchLimit = 1
+            return try context.fetch(request).first?.report()
+        }
+    }
+
     /// How many reports are logged and waiting for answers.
     func passiveCount() async throws -> Int {
         let context = persistence.newBackgroundContext()

diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift

@@ -39,6 +39,22 @@ struct ReportStoreTests {
             modifiedAt: Date(timeIntervalSince1970: 0))
     }
 
+    @Test("The previous report is the latest answered one within the interval")
+    func previousReport() async throws {
+        // Reports at 1, 2 and 3 hours; the one at 3 hours is still waiting.
+        try await store.insert(Self.report(1, responses: []))
+        try await store.insert(Self.report(2, responses: []))
+        var waiting = Self.report(3, responses: [])
+        waiting.state = .passive
+        try await store.insert(waiting)
+
+        let at = Date(timeIntervalSince1970: 3.5 * 3600)
+        #expect(try await store.previousReport(before: at, within: 2 * 3600)?.id == Fixtures.reportID(2))
+        #expect(try await store.previousReport(before: at, within: 3600) == nil)
+        let first = Date(timeIntervalSince1970: 3600)
+        #expect(try await store.previousReport(before: first, within: 2 * 3600) == nil)
+    }
+
     @Test("Default questions are seeded once, covering every question kind")
     func seeding() async throws {
         #expect(try await store.seedDefaultQuestionsIfNeeded())

diff --git a/Tests/Unit/SurveyModelTests.swift b/Tests/Unit/SurveyModelTests.swift

@@ -280,6 +280,125 @@ struct SurveyModelTests {
         #expect(newTokens.first?.place == PlaceDetails())
         #expect(newTokens.first?.modifiedAt == Date(timeIntervalSince1970: 5))
     }
+
+    // MARK: Carrying people forward
+
+    private static let carryQuestions = [
+        question("place", .location, order: 0),
+        question("people", .people, order: 1),
+        question("tokens", .tokens, order: 2),
+    ]
+
+    private static let home = Coordinate(latitude: 35, longitude: 139)
+
+    /// The previous report: at Home with Sam and Kai, reading.
+    private static func previous(people: [String] = ["S", "K"]) -> Report {
+        Report(
+            id: Fixtures.reportID(9),
+            date: Date(timeIntervalSince1970: 0),
+            timeZone: "Asia/Tokyo",
+            kind: .random,
+            trigger: .notification,
+            state: .complete,
+            responses: [
+                Response(questionID: "place", prompt: "Where?", value: .place(PlaceAnswer(tokenID: "P1"))),
+                Response(questionID: "people", prompt: "With?", value: .tokens(people)),
+                Response(questionID: "tokens", prompt: "Doing?", value: .tokens(["T1"])),
+            ],
+            modifiedAt: Date(timeIntervalSince1970: 0)
+        )
+    }
+
+    private func makeCarryingModel(
+        previous: Report = previous(), people: [VocabularyEntry]? = nil
+    ) -> SurveyModel {
+        SurveyModel(
+            kind: .random,
+            date: Date(timeIntervalSince1970: 100),
+            questions: Self.carryQuestions,
+            vocabulary: [
+                "place": [
+                    VocabularyEntry(id: "P1", text: "Home", useCount: 5, coordinate: Self.home),
+                    Self.entry("P2", "Café"),
+                ],
+                "people": people ?? [Self.entry("S", "Sam"), Self.entry("K", "Kai"), Self.entry("A", "Ada")],
+                "tokens": [Self.entry("T1", "Reading")],
+            ],
+            previous: previous,
+            directory: EmptyDirectory()
+        )
+    }
+
+    @Test("The previous report's people are chosen while the place is the same")
+    func carriesPeople() throws {
+        let model = makeCarryingModel()
+        let places = try #require(model.placePickers["place"])
+        let people = try #require(model.pickers["people"])
+        #expect(people.selection.isEmpty)
+
+        places.toggle(try #require(places.candidate(id: "P1")))
+        #expect(people.selection == ["S", "K"])
+        #expect(people.isPrefilled)
+        // Activities aren't carried.
+        #expect(model.pickers["tokens"]?.selection.isEmpty == true)
+
+        // A different place takes them away, and the same place brings them back.
+        places.toggle(try #require(places.candidate(id: "P2")))
+        #expect(people.selection.isEmpty)
+        places.toggle(try #require(places.candidate(id: "P1")))
+        #expect(people.selection == ["S", "K"])
+        places.toggle(try #require(places.candidate(id: "P1")))
+        #expect(people.selection.isEmpty)
+    }
+
+    @Test("The place pre-filled from the location carries the people too")
+    func carriesWithPrefilledPlace() throws {
+        let model = makeCarryingModel()
+        model.placePickers["place"]?.setLocation(LocationContext(coordinate: Self.home, horizontalAccuracy: 10))
+        #expect(model.placePickers["place"]?.selectedTokenID == "P1")
+        #expect(model.pickers["people"]?.selection == ["S", "K"])
+    }
+
+    @Test("People the user has changed are left alone when the place changes")
+    func userChangesWin() throws {
+        let model = makeCarryingModel()
+        let places = try #require(model.placePickers["place"])
+        let people = try #require(model.pickers["people"])
+
+        places.toggle(try #require(places.candidate(id: "P1")))
+        people.toggle("A")
+        places.toggle(try #require(places.candidate(id: "P2")))
+        #expect(people.selection == ["S", "K", "A"])
+
+        // Clearing the people before the place is chosen counts as a change.
+        let other = makeCarryingModel()
+        let otherPeople = try #require(other.pickers["people"])
+        otherPeople.toggle("A")
+        otherPeople.toggle("A")
+        let otherPlaces = try #require(other.placePickers["place"])
+        otherPlaces.toggle(try #require(otherPlaces.candidate(id: "P1")))
+        #expect(otherPeople.selection.isEmpty)
+    }
+
+    @Test("Carried people read as the tokens they were merged into, without those no longer suggested")
+    func carriesMergedPeople() throws {
+        let model = makeCarryingModel(
+            previous: Self.previous(people: ["OLD", "S", "GONE"]),
+            people: [
+                VocabularyEntry(
+                    id: "S", text: "Sam", useCount: 2,
+                    merged: [MergedToken(id: "OLD", text: "Samuel", useCount: 1)])
+            ])
+        let places = try #require(model.placePickers["place"])
+        places.toggle(try #require(places.candidate(id: "P1")))
+        #expect(model.pickers["people"]?.selection == ["S"])
+    }
+}
+
+/// A directory with no places.
+private struct EmptyDirectory: PlaceDirectory {
+    func places(near coordinate: Coordinate) async throws -> [DirectoryPlace] { [] }
+    func search(_ query: String, near coordinate: Coordinate?) async throws -> [DirectoryPlace] { [] }
 }
 
 @MainActor