← All repositories

reportage

A life-logging app for iPhone

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


commit b39c50b7ac8f5a631896181442cdd55592ad0526
parent 3f18b3b3895c646be97d64cdedfd158a1ba611ad
Author: Michael Camilleri <[email protected]>
Date:   Wed, 21 Oct 2026 12:33:10 +0900

Merge questions into others of the same type

Deleting everything and importing from Reporter could leave the user
with multiple copies of the same questions.

This commit adds 'Merge Into…' to the screen of any answered question
that has another of the same type. After a confirmation, its responses
are reassigned to the chosen question, with the prompt text stored on
each response unchanged, and its tokens are reassigned too; a token with
the same name as one of the chosen question's is merged into it.  The
possible answers are added to the surviving question and the merging
question is then deleted. Unlike merging tokens, this can't be undone.

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

Diffstat

MNotes/Design.md | 9+++++++++
MReportage/Views/Settings/QuestionsView.swift | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MShared/Persistence/ReportStore.swift | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MTests/Unit/ReportStoreTests.swift | 37+++++++++++++++++++++++++++++++++++++

4 files changed, 212 insertions(+), 0 deletions(-)

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

@@ -215,6 +215,15 @@ Question instead, which stops it being asked. Archived questions are listed
 in their own section with a note on why they're kept, and their answers still
 show in their reports and narratives.
 
+A question with answers can be merged into another of the same type with
+**Merge Into…**, after a confirmation. Its responses are reassigned to the
+other question; the prompt text stored with each response is unchanged. Its
+tokens are reassigned too, and a token with the same name as one of the other
+question's is merged into that one. Its choice answers join the other's,
+and the merged question is deleted. Unlike merging tokens, this can't be
+undone. An archived question with no answers, such as a default the Reporter
+import replaced, can be deleted.
+
 **Editable questions.** Every question is the user's to edit, the defaults
 included: there is no fixed built-in set. Each question stores its own
 [narrative rule](#drafts), so rewording a question or its rule never depends

diff --git a/Reportage/Views/Settings/QuestionsView.swift b/Reportage/Views/Settings/QuestionsView.swift

@@ -98,6 +98,18 @@ final class QuestionList {
         enqueue { try await $0.deleteQuestion(id: id) }
     }
 
+    /// Merges the question with `id` into `target`, then reloads, since
+    /// the merge can add choice answers to `target`.
+    func merge(_ id: String, into target: String) {
+        questions.removeAll { $0.id == id }
+        enqueue { try await $0.mergeQuestion(id, into: target) }
+        let saved = saving
+        Task {
+            await saved?.value
+            await load(from: store)
+        }
+    }
+
     /// Adds a question at the end of the order.
     func add(_ question: Question) {
         var question = question
@@ -251,6 +263,67 @@ struct QuestionsView: View {
     }
 }
 
+/// The questions one can be merged into. Choosing one asks for
+/// confirmation, since a merge can't be undone.
+private struct MergeQuestionView: View {
+    let source: Question
+    /// How many reports answered `source`.
+    let count: Int
+    let targets: [Question]
+    let onMerge: (Question) -> Void
+    @State private var chosen: Question?
+    @Environment(\.dismiss) private var dismiss
+
+    var body: some View {
+        NavigationStack {
+            List {
+                ForEach(targets, id: \.id) { question in
+                    Button {
+                        chosen = question
+                    } label: {
+                        VStack(alignment: .leading, spacing: Theme.lineGap) {
+                            Text(question.prompt)
+                                .font(Theme.serif(.body))
+                            if question.archivedAt != nil {
+                                Text("Archived")
+                                    .font(.footnote)
+                                    .foregroundStyle(Theme.muted)
+                            }
+                        }
+                        .frame(maxWidth: .infinity, alignment: .leading)
+                        .contentShape(Rectangle())
+                    }
+                    .buttonStyle(.plain)
+                    .settingsRow()
+                }
+            }
+            .listStyle(.plain)
+            .scrollContentBackground(.hidden)
+            .background(Theme.paper)
+            .foregroundStyle(Theme.ink)
+            .navigationTitle("Merge Into")
+            .navigationBarTitleDisplayMode(.inline)
+            .toolbar {
+                ToolbarItem(placement: .cancellationAction) {
+                    Button("Cancel") { dismiss() }
+                }
+            }
+            .alert(
+                "Merge into '\(chosen?.prompt ?? "")'?",
+                isPresented: Binding(get: { chosen != nil }, set: { if !$0 { chosen = nil } }),
+                presenting: chosen
+            ) { target in
+                Button("Cancel", role: .cancel) {}
+                Button("Merge") { onMerge(target) }
+            } message: { _ in
+                Text(
+                    "Answers in ^[\(count) report](inflect: true) move to that question, and '\(source.prompt)' is deleted. This can't be undone."
+                )
+            }
+        }
+    }
+}
+
 /// A question's prompt, noting when its answers are left out of the
 /// timeline.
 private struct QuestionRow: View {
@@ -284,6 +357,7 @@ private struct QuestionDetailView: View {
     /// `nil` until counted.
     @State private var answerCount: Int?
     @State private var isConfirmingDelete = false
+    @State private var isChoosingTarget = false
     @Environment(\.reportStore) private var store
     @Environment(\.dismiss) private var dismiss
 
@@ -309,6 +383,25 @@ private struct QuestionDetailView: View {
         } message: {
             Text("It hasn't been answered, so no reports change. This can't be undone.")
         }
+        .sheet(isPresented: $isChoosingTarget) {
+            MergeQuestionView(source: editor.question, count: answerCount ?? 0, targets: targets) { target in
+                isChoosingTarget = false
+                list.merge(editor.question.id, into: target.id)
+                dismiss()
+            }
+        }
+    }
+
+    /// The other questions of this kind, which this one can be merged into.
+    private var targets: [Question] {
+        list.questions.filter { $0.kind == editor.question.kind && $0.id != editor.question.id }
+    }
+
+    /// Merging, for a question with answers and another of its kind.
+    @ViewBuilder private var merge: some View {
+        if let answerCount, answerCount > 0, !targets.isEmpty {
+            removeButton("Merge Into…", role: nil) { isChoosingTarget = true }
+        }
     }
 
     @ViewBuilder private var removal: some View {
@@ -320,6 +413,7 @@ private struct QuestionDetailView: View {
             }
         } else if editor.archivedAt != nil {
             Section {
+                merge
                 SettingsNote {
                     Text(
                         "This question is archived. It has answers in past reports, so it's kept rather than deleted. Turn on a survey above to ask it again."
@@ -333,6 +427,7 @@ private struct QuestionDetailView: View {
                     commit()
                     dismiss()
                 }
+                merge
                 SettingsNote {
                     Text(
                         "This question can't be deleted because it's been answered in ^[\(answerCount) report](inflect: true). Archiving it stops it being asked and keeps those answers."

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

@@ -161,6 +161,77 @@ struct ReportStore: Sendable {
         }
     }
 
+    /// Merges the question with `id` into the question with `target`, of
+    /// the same kind, and deletes it. Its responses and tokens are
+    /// reassigned to `target`; each response's stored prompt is unchanged,
+    /// and a token named as one of `target`'s is merged into it. Its choice answers are added
+    /// to `target`'s. A report that answered both keeps one answer: the
+    /// one that wasn't skipped, both sets of tokens, or else `target`'s.
+    /// Unlike merging tokens, this can't be undone.
+    func mergeQuestion(_ id: String, into target: String, now: Date = Date()) async throws {
+        let context = persistence.newBackgroundContext()
+        try await context.perform {
+            let questions = QuestionEntity.fetchRequest()
+            questions.predicate = NSPredicate(format: "id IN %@", [id, target])
+            let entities = try context.fetch(questions)
+            guard let sourceEntity = entities.first(where: { $0.id == id }),
+                let targetEntity = entities.first(where: { $0.id == target })
+            else { return }
+            let source = try sourceEntity.question()
+            var merged = try targetEntity.question()
+            guard source.kind == merged.kind else { return }
+
+            let tokens = TokenEntity.fetchRequest()
+            tokens.predicate = NSPredicate(format: "questionID IN %@", [id, target])
+            let tokenEntities = try context.fetch(tokens)
+            var targetTokens: [String: String] = [:]
+            for entity in tokenEntities where entity.questionID == target {
+                let token = try entity.token()
+                guard token.mergedInto == nil else { continue }
+                targetTokens[token.text.lowercased()] = token.id
+            }
+            for entity in tokenEntities where entity.questionID == id {
+                var token = try entity.token()
+                token.questionID = target
+                if token.mergedInto == nil, let match = targetTokens[token.text.lowercased()] {
+                    token.mergedInto = match
+                }
+                token.modifiedAt = now
+                try entity.update(from: token)
+            }
+
+            let responses = ResponseEntity.fetchRequest()
+            responses.predicate = NSPredicate(format: "questionID == %@", id)
+            for response in try context.fetch(responses) {
+                guard let report = response.report else { continue }
+                report.modifiedAt = now
+                let existing = (report.responses as? Set<ResponseEntity>)?.first { $0.questionID == target }
+                guard let existing else {
+                    response.questionID = target
+                    continue
+                }
+                let moved = try response.response().value
+                let kept = try existing.response().value
+                switch (kept, moved) {
+                case (nil, let value?):
+                    existing.value = try ModelCoding.encode(value)
+                case (.tokens(let keptIDs)?, .tokens(let movedIDs)?):
+                    let combined = keptIDs + movedIDs.filter { !keptIDs.contains($0) }
+                    existing.value = try ModelCoding.encode(ResponseValue.tokens(combined))
+                default:
+                    break
+                }
+                context.delete(response)
+            }
+
+            merged.options += source.options.filter { !merged.options.contains($0) }
+            merged.modifiedAt = now
+            try targetEntity.update(from: merged)
+            context.delete(sourceEntity)
+            try context.save()
+        }
+    }
+
     /// The questions with `ids`, archived or not, in the order given. IDs
     /// with no question are left out.
     func questions(ids: [String]) async throws -> [Question] {

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

@@ -523,4 +523,41 @@ extension ReportStoreTests {
         #expect(kept.responses.map(\.questionID) == ["answered"])
         #expect(kept.modifiedAt == Date(timeIntervalSince1970: 50))
     }
+
+    @Test("Merging a question moves its answers and tokens to the other, then deletes it")
+    func mergeQuestion() async throws {
+        let then = Date(timeIntervalSince1970: 0)
+        let old = Question(id: "old", prompt: "Doing what?", kind: .tokens, askOn: [], order: 0, archivedAt: then, modifiedAt: then)
+        let new = Question(id: "new", prompt: "What are you doing?", kind: .tokens, askOn: .random, order: 1, modifiedAt: then)
+        try await store.save([old, new])
+        func token(_ id: String, _ question: String, _ text: String) -> Token {
+            Token(id: id, questionID: question, text: text, modifiedAt: then)
+        }
+        // One report per question, and one that answered both.
+        let onlyOld = Self.report(1, responses: [Response(questionID: "old", prompt: "Doing what?", value: .tokens(["old-reading", "old-cooking"]))])
+        let onlyNew = Self.report(2, responses: [Response(questionID: "new", prompt: "What are you doing?", value: .tokens(["new-reading"]))])
+        let both = Self.report(3, responses: [
+            Response(questionID: "new", prompt: "What are you doing?", value: .tokens(["new-reading"])),
+            Response(questionID: "old", prompt: "Doing what?", value: .tokens(["old-cooking"])),
+        ])
+        try await store.insert(onlyOld, newTokens: [token("old-reading", "old", "Reading"), token("old-cooking", "old", "Cooking")])
+        try await store.insert(onlyNew, newTokens: [token("new-reading", "new", "reading")])
+        try await store.insert(both)
+
+        let now = Date(timeIntervalSince1970: 100)
+        try await store.mergeQuestion("old", into: "new", now: now)
+
+        #expect(try await store.allQuestions().map(\.id) == ["new"])
+        let moved = try #require(try await store.report(id: onlyOld.id))
+        // Each answer keeps the prompt it was given under.
+        #expect(moved.responses.map(\.questionID) == ["new"])
+        #expect(moved.responses.first?.prompt == "Doing what?")
+        #expect(moved.modifiedAt == now)
+        let combined = try #require(try await store.report(id: both.id))
+        #expect(combined.responses.map(\.value) == [.tokens(["new-reading", "old-cooking"])])
+        // 'Reading' went into the other question's 'reading'; 'Cooking' moved as it was.
+        let tokens = try await store.tokens(for: ["new"])
+        #expect(Set(tokens.map(\.id)) == ["new-reading", "old-cooking"])
+        #expect(try await store.answerCount(questionID: "new") == 3)
+    }
 }