← All repositories

reportage

A life-logging app for iPhone

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


commit 32433bfb2f4d9e948abcddb5a209883ff5a7fda4
parent 3043a77d8109cb0c7b8b24ac1a2f0ebd822315db
Author: Michael Camilleri <[email protected]>
Date:   Tue, 20 Oct 2026 21:23:44 +0900

Delete unanswered questions and archive answered ones

The Questions screen had no way to remove a question. This commit adds
one at the foot of each question's screen, and what it offers depends on
whether the question has been answered. A question with no answers shows
'Delete Question', which asks for confirmation and then removes it. A
question answered in past reports can't be deleted without those answers
losing their meaning, so it shows 'Archive Question' instead, with a
note giving the number of reports that answered it.

Archived questions now have their own Archived section on the Questions
screen, after Not Asked, with a note explaining why they're kept. Not
Asked now holds only questions that are switched off in every survey and
not archived. Opening an archived question and turning on a survey asks
it again.

Skipped answers don't count as answers, so a question that was only ever
skipped can still be deleted. Deleting it removes those skipped records
and the question's tokens, and marks the affected reports as modified so
the change syncs. The store checks for answers itself and leaves a
question that has any in place, whatever the screen asks.

Archiving goes through the question's editor before the change is
committed, so the commit made when the screen disappears doesn't undo
it.

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

Diffstat

MNotes/Design.md | 15+++++++++++----
MReportage/Views/Settings/QuestionEditor.swift | 37++++++++++++++++++++++++++-----------
MReportage/Views/Settings/QuestionsView.swift | 105++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
MShared/Persistence/ReportStore.swift | 37+++++++++++++++++++++++++++++++++++++
MTests/Unit/QuestionListTests.swift | 21+++++++++++++++++++++
MTests/Unit/ReportStoreTests.swift | 23+++++++++++++++++++++++

6 files changed, 214 insertions(+), 24 deletions(-)

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

@@ -164,7 +164,7 @@ the app. A change that needs data rewritten would need a migration of its own.
 | `askOn`       | Set of report kinds the question appears in: `random`, `wake`, `bedtime`. |
 | `order`       | Sort order within a survey, one order across all surveys. Narratives read in the current order, so reordering a question changes past narratives too. |
 | `showsInTimeline` | Whether answers appear in the timeline's narratives. Hidden answers are still shown in a report's details. |
-| `archivedAt`  | Questions are archived, never deleted, so history keeps its meaning. |
+| `archivedAt`  | Questions with answers are archived, never deleted, so history keeps its meaning. One never answered can be deleted. |
 
 Reporter's `questionType` values map as: 0 → `tokens`, 1 → `choice`,
 2 → `yesNo`, 3 → `location`, 4 → `people`, 5 → `number`, 6 → `note`.
@@ -189,7 +189,7 @@ Their prompts are written in the user's language at seeding time and are
 ordinary data after that.
 
 **The Questions screen.** Settings lists the questions by survey (prompted,
-wake, bedtime), plus those not asked in any. Dragging reorders a question
+wake, bedtime), plus those not asked in any and those archived. Dragging reorders a question
 among those in the same survey, leaving the rest of the order alone. Opening
 a question edits it in place: its prompt, a choice question's answers,
 whether it shows in the timeline and how it reads there, and the surveys it's
@@ -208,8 +208,15 @@ changed after that, since answers already given wouldn't fit another type.
 Text fields sit on a faint wash of ink (`Theme.field`) so they read as
 somewhere to type, and each answer is its own field, without rules between. A
 new question goes to the end of the order, asked in the prompted survey.
-Asking an archived question brings it back in that survey alone. Removing
-questions is next.
+Asking an archived question brings it back in that survey alone.
+
+A question with no answers can be deleted, after a confirmation; the reports'
+records of it being skipped go with it, and those reports count as modified.
+A question with answers can't be deleted, since the answers would lose their
+meaning, so the screen says how many reports answered it and offers Archive
+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.
 
 **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

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

@@ -163,6 +163,11 @@ final class QuestionEditor {
         (askOn, archivedAt) = (question.askOn, question.archivedAt)
     }
 
+    /// Stops asking the question anywhere, keeping its answers.
+    func archive(now: Date = Date()) {
+        archivedAt = now
+    }
+
     /// Takes `question` as saved, tidying the answers to match it.
     func saved(_ question: Question) {
         self.question = question
@@ -187,21 +192,30 @@ extension String {
     }
 }
 
+/// The text field of a question form that has the focus.
+enum QuestionFormField: Hashable {
+    case prompt
+    case option(UUID)
+    case rule(Int)
+}
+
+extension QuestionForm where Footer == EmptyView {
+    init(editor: QuestionEditor, onCommit: @escaping () -> Void = {}) {
+        self.init(editor: editor, onCommit: onCommit) { EmptyView() }
+    }
+}
+
 /// The fields of a question being edited or added: its prompt, its type,
 /// its answers for a choice, how it shows in the timeline and the surveys
 /// it's asked in. `onCommit` runs when a field is finished, a toggle changes
 /// or an answer is moved or removed.
-struct QuestionForm: View {
+struct QuestionForm<Footer: View>: View {
     @Bindable var editor: QuestionEditor
     var onCommit: () -> Void = {}
+    /// Shown at the end of the form, such as a way to remove the question.
+    @ViewBuilder var footer: Footer
 
-    @FocusState private var focus: Field?
-
-    enum Field: Hashable {
-        case prompt
-        case option(UUID)
-        case rule(Int)
-    }
+    @FocusState private var focus: QuestionFormField?
 
     var body: some View {
         List {
@@ -252,6 +266,7 @@ struct QuestionForm: View {
             } header: {
                 SettingsHeading("Asked In")
             }
+            footer
         }
         .listStyle(.plain)
         .scrollContentBackground(.hidden)
@@ -277,7 +292,7 @@ extension View {
     /// Draws a text field on a wash of ink so it reads as somewhere to type,
     /// and focuses it from anywhere in the wash, not just its text.
     fileprivate func filledField(
-        focus: FocusState<QuestionForm.Field?>.Binding, as field: QuestionForm.Field
+        focus: FocusState<QuestionFormField?>.Binding, as field: QuestionFormField
     ) -> some View {
         padding(.horizontal, 12)
             .padding(.vertical, 9)
@@ -291,7 +306,7 @@ extension View {
 /// added to.
 private struct OptionsSection: View {
     @Bindable var editor: QuestionEditor
-    var focus: FocusState<QuestionForm.Field?>.Binding
+    var focus: FocusState<QuestionFormField?>.Binding
     let onCommit: () -> Void
 
     var body: some View {
@@ -340,7 +355,7 @@ private struct OptionsSection: View {
 /// of their own, how its answers read there, with an example.
 private struct TimelineSection: View {
     @Bindable var editor: QuestionEditor
-    var focus: FocusState<QuestionForm.Field?>.Binding
+    var focus: FocusState<QuestionFormField?>.Binding
 
     var body: some View {
         Section {

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

@@ -57,8 +57,11 @@ final class QuestionList {
         didSet { group() }
     }
     private(set) var bySurvey: [Survey: [Question]] = [:]
-    /// Questions not asked in any survey.
+    /// Questions not asked in any survey, archived ones aside.
     private(set) var notAsked: [Question] = []
+    /// Questions with answers that were removed, kept so their answers keep
+    /// their meaning.
+    private(set) var archived: [Question] = []
     private(set) var isLoaded = false
 
     private var store: ReportStore?
@@ -88,6 +91,13 @@ final class QuestionList {
         enqueue { [question] in try await $0.save(question, renamingOptions: renames) }
     }
 
+    /// Deletes a question with no answers. One that has been answered since
+    /// is left in the store; it shows again when the list next loads.
+    func delete(id: String) {
+        questions.removeAll { $0.id == id }
+        enqueue { try await $0.deleteQuestion(id: id) }
+    }
+
     /// Adds a question at the end of the order.
     func add(_ question: Question) {
         var question = question
@@ -136,8 +146,9 @@ final class QuestionList {
                 (survey, questions.filter { $0.isAsked(in: survey) })
             })
         notAsked = questions.filter { question in
-            !Survey.allCases.contains { question.isAsked(in: $0) }
+            question.archivedAt == nil && !Survey.allCases.contains { question.isAsked(in: $0) }
         }
+        archived = questions.filter { $0.archivedAt != nil }
     }
 
     private func save(_ questions: [Question]) {
@@ -200,6 +211,20 @@ struct QuestionsView: View {
                     SettingsHeading("Not Asked")
                 }
             }
+            if !list.archived.isEmpty {
+                Section {
+                    SettingsNote {
+                        Text(
+                            "These questions have answers in past reports, so they're kept rather than deleted, and their answers still show in those reports. Open one and turn on a survey to ask it again."
+                        )
+                    }
+                    ForEach(list.archived, id: \.id) { question in
+                        QuestionRow(question: question, list: list)
+                    }
+                } header: {
+                    SettingsHeading("Archived")
+                }
+            }
         }
         .listStyle(.plain)
         .scrollContentBackground(.hidden)
@@ -249,9 +274,16 @@ private struct QuestionRow: View {
 }
 
 /// One question, edited in place. Each field is saved when it's finished.
+/// A question with no answers can be deleted; one with answers can only be
+/// archived, so its answers keep their meaning.
 private struct QuestionDetailView: View {
     let list: QuestionList
     @State private var editor: QuestionEditor
+    /// `nil` until counted.
+    @State private var answerCount: Int?
+    @State private var isConfirmingDelete = false
+    @Environment(\.reportStore) private var store
+    @Environment(\.dismiss) private var dismiss
 
     init(question: Question, list: QuestionList) {
         self.list = list
@@ -259,15 +291,70 @@ private struct QuestionDetailView: View {
     }
 
     var body: some View {
-        QuestionForm(editor: editor) {
-            let (question, renames) = editor.drafted()
-            guard question != editor.question || !renames.isEmpty else { return }
-            list.update(question, renamingOptions: renames)
-            if let saved = list.question(id: question.id) {
-                editor.saved(saved)
-            }
+        QuestionForm(editor: editor, onCommit: commit) {
+            removal
         }
         .navigationBarTitleDisplayMode(.inline)
+        .task {
+            answerCount = try? await store?.answerCount(questionID: editor.question.id)
+        }
+        .confirmationDialog("Delete this question?", isPresented: $isConfirmingDelete, titleVisibility: .visible) {
+            Button("Delete Question", role: .destructive) {
+                list.delete(id: editor.question.id)
+                dismiss()
+            }
+        } message: {
+            Text("It hasn't been answered, so no reports change. This can't be undone.")
+        }
+    }
+
+    @ViewBuilder private var removal: some View {
+        if editor.archivedAt != nil {
+            Section {
+                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."
+                    )
+                }
+            }
+        } else if let answerCount {
+            Section {
+                if answerCount == 0 {
+                    removeButton("Delete Question", role: .destructive) { isConfirmingDelete = true }
+                } else {
+                    removeButton("Archive Question", role: nil) {
+                        editor.archive()
+                        commit()
+                        dismiss()
+                    }
+                    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."
+                        )
+                    }
+                }
+            }
+        }
+    }
+
+    private func removeButton(
+        _ title: LocalizedStringKey, role: ButtonRole?, action: @escaping () -> Void
+    ) -> some View {
+        Button(title, role: role, action: action)
+            .font(.body.weight(.semibold))
+            .foregroundStyle(role == .destructive ? Color.red : Theme.accent)
+            .frame(maxWidth: .infinity, minHeight: 44)
+            .listRowBackground(Theme.paper)
+            .listRowSeparator(.hidden)
+    }
+
+    private func commit() {
+        let (question, renames) = editor.drafted()
+        guard question != editor.question || !renames.isEmpty else { return }
+        list.update(question, renamingOptions: renames)
+        if let saved = list.question(id: question.id) {
+            editor.saved(saved)
+        }
     }
 }
 

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

@@ -124,6 +124,43 @@ struct ReportStore: Sendable {
         }
     }
 
+    /// How many reports answered the question with `id`. Skipped answers
+    /// don't count.
+    func answerCount(questionID id: String) async throws -> Int {
+        let context = persistence.newBackgroundContext()
+        return try await context.perform {
+            let request = ResponseEntity.fetchRequest()
+            request.predicate = NSPredicate(format: "questionID == %@ AND value != nil", id)
+            return try context.count(for: request)
+        }
+    }
+
+    /// Deletes the question with `id` if it has no answers, along with the
+    /// reports' records of it being skipped. A question with answers is left
+    /// alone, since they'd lose their meaning; it's archived instead.
+    /// Returns whether the question was deleted.
+    @discardableResult
+    func deleteQuestion(id: String, now: Date = Date()) async throws -> Bool {
+        let context = persistence.newBackgroundContext()
+        return try await context.perform {
+            let responses = ResponseEntity.fetchRequest()
+            responses.predicate = NSPredicate(format: "questionID == %@", id)
+            let skipped = try context.fetch(responses)
+            guard skipped.allSatisfy({ $0.value == nil }) else { return false }
+            let questions = QuestionEntity.fetchRequest()
+            questions.predicate = NSPredicate(format: "id == %@", id)
+            let tokens = TokenEntity.fetchRequest()
+            tokens.predicate = NSPredicate(format: "questionID == %@", id)
+            for response in skipped {
+                response.report?.modifiedAt = now
+            }
+            let objects: [NSManagedObject] = skipped + (try context.fetch(questions)) + (try context.fetch(tokens))
+            objects.forEach(context.delete)
+            try context.save()
+            return true
+        }
+    }
+
     /// 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/QuestionListTests.swift b/Tests/Unit/QuestionListTests.swift

@@ -39,4 +39,25 @@ struct QuestionListTests {
         question.setAsked(false, in: .bedtime)
         #expect(question.askOn.isEmpty)
     }
+
+    @Test("Archived questions are listed apart from those not asked")
+    func grouping() async throws {
+        let store = ReportStore(persistence: makeTestPersistence())
+        try await store.save([
+            Self.question("asked", .random),
+            Self.question("off", []),
+            Self.question("archived", .random, archived: true),
+        ])
+        let list = QuestionList()
+        await list.load(from: store)
+        #expect(list.bySurvey[.prompted]?.map(\.id) == ["asked"])
+        #expect(list.notAsked.map(\.id) == ["off"])
+        #expect(list.archived.map(\.id) == ["archived"])
+
+        var archived = try #require(list.question(id: "archived"))
+        archived.setAsked(true, in: .wake)
+        list.update(archived)
+        #expect(list.archived.isEmpty)
+        #expect(list.bySurvey[.wake]?.map(\.id) == ["archived"])
+    }
 }

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

@@ -434,4 +434,27 @@ extension ReportStoreTests {
         #expect(kept.modifiedAt == good.modifiedAt)
         #expect(try await store.allQuestions().first?.options == ["Fine", "Good"])
     }
+
+    @Test("A question is deleted only while it has no answers, skipped ones aside")
+    func deleteQuestion() async throws {
+        let now = Date(timeIntervalSince1970: 0)
+        let skipped = Question(id: "skipped", prompt: "Raining?", kind: .yesNo, askOn: .random, order: 0, modifiedAt: now)
+        let answered = Question(id: "answered", prompt: "Working?", kind: .yesNo, askOn: .random, order: 1, modifiedAt: now)
+        try await store.save([skipped, answered])
+        let report = Self.report(1, responses: [
+            Response(questionID: "skipped", prompt: "Raining?", value: nil),
+            Response(questionID: "answered", prompt: "Working?", value: .options([ResponseValue.yesOption])),
+        ])
+        try await store.insert(report)
+
+        #expect(try await store.answerCount(questionID: "skipped") == 0)
+        #expect(try await store.answerCount(questionID: "answered") == 1)
+        #expect(try await !store.deleteQuestion(id: "answered"))
+        #expect(try await store.deleteQuestion(id: "skipped", now: Date(timeIntervalSince1970: 50)))
+
+        #expect(try await store.allQuestions().map(\.id) == ["answered"])
+        let kept = try #require(try await store.report(id: report.id))
+        #expect(kept.responses.map(\.questionID) == ["answered"])
+        #expect(kept.modifiedAt == Date(timeIntervalSince1970: 50))
+    }
 }