commit 0ddad8208818d31a641ecc432ead42a7267a837f
parent a69db0dd12eb1f829d4d423834b11c18d138d379
Author: Michael Camilleri <[email protected]>
Date: Sat, 17 Oct 2026 21:56:57 +0900
Add Delete All Data and phrase imported reports like new ones
Imported reports looked unlike new ones in the timeline. Answers to
Reporter's yes/no and choice questions, such as 'Are you working?',
were listed beneath the entry as question and answer rather than read
into it, because display rules were keyed to the default questions'
IDs and imported answers keep Reporter's. The context line also gave
only the bare locality, since Reporter's placemarks lack the city with
its region that new reports store.
This commit gives Reporter's seven built-in questions the rules of the
defaults that ask the same things, so their answers read as 'Working',
'Slept ok' or '2 coffees', and their entries are rewritten the next time
they're shown. Imported placemarks now put together the city and its
region as Apple Maps writes it for new reports, without repeating a
region that is the city itself.
Settings' Data section also gains 'Delete All Data', which asks first,
then deletes every report, question and token and seeds the default
questions again, so the archive can be re-imported from scratch. Prompt
settings are kept. On the app's SQLite store it uses batch deletes,
removing reports and letting their responses go with them by the
cascade, then merges the deletions into the view context so the
timeline empties.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 17 | ++++++++++++++--- |
| M | Reportage/Services/Narrative/DisplayRule.swift | | | 47 | ++++++++++++++++++++++++++++++++++------------- |
| M | Reportage/Views/Settings/DataSection.swift | | | 38 | ++++++++++++++++++++++++++++++++++++++ |
| M | Shared/Models/Context.swift | | | 12 | ++++++++---- |
| M | Shared/Persistence/ReportStore.swift | | | 45 | +++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/ReportStoreTests.swift | | | 37 | +++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/ReportSummaryTests.swift | | | 29 | ++++++++++++++++++++++++----- |
7 files changed, 200 insertions(+), 25 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -94,7 +94,9 @@ The look is called Almanac: ink on paper, like a printed journal.
- **Home screen:** reports grouped under day headings, newest first. Each
shows its own local time (the period beneath on a 12-hour clock, so times
fit one column), its kind, its entry, any answers the entry doesn't cover,
- and a line of context (locality and weather). Days are grouped in the
+ and a line of context: the city with its region ('Suginami, Tokyo', put
+ together from the locality and region for imported placemarks) and the
+ weather. Days are grouped in the
device's time zone: grouping by each report's own zone would put reports out
of order around midnight after a change of zone, which a sectioned fetch
can't show. Grouping by a computed day loads every report the fetch
@@ -177,7 +179,11 @@ or off and moved between surveys, plus custom questions the user writes with
their own display rule. The built-in set should reuse Reporter's built-in
question IDs, so imported answers map onto it directly: 7 of the 8 questions
in the real export are Reporter's own. Today the default questions get their
-rules from `DisplayRule.builtIn`, keyed by ID.
+rules from `DisplayRule.builtIn`, keyed by ID, and Reporter's seven built-in
+questions (`default-question-1` to `-7`) share the rules of the defaults that
+ask the same things, so imported answers read as entries too. This assumes
+an ID keeps its meaning: a Reporter user who reworded a built-in question
+would get the wrong phrasing until the built-in set is settled.
### Report
@@ -807,7 +813,12 @@ Source: Reporter's JSON export, which has two top-level arrays, `questions` and
- Runs on the iPhone only, off the main actor, inserting in batches. It's
started from **Import from Reporter** in Settings' Data section, which picks
the export with `fileImporter` and shows the counts when it's done; the full
- summary goes to the log, as counts and IDs only.
+ summary goes to the log, as counts and IDs only. **Delete All Data**, in
+ the same section, asks first, then deletes every report, question and
+ token and seeds the default questions again, so the archive can be
+ re-imported from scratch. Prompt settings are kept. Once sync exists, it
+ has to clear the CloudKit zones too, or the next fetch brings everything
+ back.
- **Idempotent and repeatable.** Reports, questions and tokens keep their
Reporter IDs, so importing a newer export adds only what's new. The user can
keep using Reporter while Reportage is under development and re-import at
diff --git a/Reportage/Services/Narrative/DisplayRule.swift b/Reportage/Services/Narrative/DisplayRule.swift
@@ -35,18 +35,39 @@ enum DisplayRule: Equatable, Sendable {
}
}
- /// Rules for the default questions, by ID.
- static let builtIn: [String: DisplayRule] = [
- "reportage-default-working": .phrases([
- ResponseValue.yesOption: "Working",
- ResponseValue.noOption: "Not working",
- ]),
- "reportage-default-activity": .activities,
- "reportage-default-location": .place,
- "reportage-default-people": .people,
- "reportage-default-mood": .template("Feeling %@"),
- "reportage-default-sleep-quality": .template("Slept %@"),
- "reportage-default-coffee": .count(singular: "coffee", plural: "coffees"),
- "reportage-default-learned": .quote(lead: "Learned"),
+ /// Rules for the default questions, by ID, and for Reporter's built-in
+ /// questions, which ask the same things. Imported answers keep
+ /// Reporter's question IDs.
+ static let builtIn: [String: DisplayRule] = {
+ var rules: [String: DisplayRule] = [
+ "working": .phrases([
+ ResponseValue.yesOption: "Working",
+ ResponseValue.noOption: "Not working",
+ ]),
+ "activity": .activities,
+ "location": .place,
+ "people": .people,
+ "mood": .template("Feeling %@"),
+ "sleep-quality": .template("Slept %@"),
+ "coffee": .count(singular: "coffee", plural: "coffees"),
+ "learned": .quote(lead: "Learned"),
+ ]
+ rules = Dictionary(uniqueKeysWithValues: rules.map { (DefaultQuestions.idPrefix + $0.key, $0.value) })
+ for (reporterID, name) in reporterQuestions {
+ rules[reporterID] = rules[DefaultQuestions.idPrefix + name]
+ }
+ return rules
+ }()
+
+ /// Reporter's built-in questions, by the default question that asks the
+ /// same thing.
+ private static let reporterQuestions = [
+ "default-question-1": "sleep-quality",
+ "default-question-2": "working",
+ "default-question-3": "activity",
+ "default-question-4": "location",
+ "default-question-5": "people",
+ "default-question-6": "coffee",
+ "default-question-7": "learned",
]
}
diff --git a/Reportage/Views/Settings/DataSection.swift b/Reportage/Views/Settings/DataSection.swift
@@ -11,12 +11,14 @@ struct DataSection: View {
@State private var includeLegacy = false
@State private var exported: ExportFile?
@State private var outcome: Outcome?
+ @State private var isConfirmingDelete = false
private let logger = Logger(subsystem: "net.inqk.reportage", category: "Data")
private enum DataTask {
case importing
case exporting
+ case deleting
}
/// What's shown in an alert once a task finishes.
@@ -53,6 +55,18 @@ struct DataSection: View {
"Saves every question, answer and report as a JSON file. Reporter snapshots are the original records of imported reports, kept exactly as Reporter exported them."
)
}
+ Button(role: .destructive) {
+ isConfirmingDelete = true
+ } label: {
+ TaskLabel("Delete All Data", isRunning: task == .deleting)
+ }
+ .disabled(task != nil || store == nil)
+ .settingsRow()
+ SettingsNote {
+ Text(
+ "Deletes every report, question, place and person, and starts again with the default questions. Prompt settings are kept."
+ )
+ }
} header: {
SettingsHeading("Data")
}
@@ -77,6 +91,15 @@ struct DataSection: View {
} onCancellation: {
finishExport()
}
+ .confirmationDialog(
+ "Delete All Data?", isPresented: $isConfirmingDelete, titleVisibility: .visible
+ ) {
+ Button("Delete All Data", role: .destructive) {
+ Task { await deleteAll() }
+ }
+ } message: {
+ Text("Every report, question, place and person in Reportage will be deleted. This can't be undone, so export first to keep a copy.")
+ }
.alert(outcome?.title ?? "", isPresented: isShowingOutcome, presenting: outcome) { _ in
Button("OK") {}
} message: { outcome in
@@ -130,6 +153,21 @@ struct DataSection: View {
}
}
+ private func deleteAll() async {
+ guard let store else { return }
+ task = .deleting
+ defer { task = nil }
+ do {
+ try await store.deleteAll()
+ try await store.seedDefaultQuestionsIfNeeded()
+ logger.info("Deleted all data")
+ } catch {
+ logger.error("Couldn't delete all data: \(error)")
+ outcome = Outcome(title: "Couldn't Delete", message: error.localizedDescription)
+ }
+ await AppBadge.update(from: store)
+ }
+
/// Removes the temporary copy once it's been saved or the save cancelled.
private func finishExport() {
guard let exported else { return }
diff --git a/Shared/Models/Context.swift b/Shared/Models/Context.swift
@@ -59,11 +59,15 @@ struct Placemark: Codable, Hashable, Sendable {
}
extension Placemark {
- /// Where this is, in a few words: the city with its region, or else the
- /// most specific locality there is. Imported placemarks have no city
- /// with its region.
+ /// Where this is, in a few words: the city with its region, as Apple
+ /// Maps writes it ('Suginami, Tokyo'). Imported placemarks don't have
+ /// that, so it's put together from their locality and region, or else
+ /// the most specific place there is.
var displayLocality: String? {
- cityWithContext ?? subLocality ?? locality ?? name
+ if let cityWithContext { return cityWithContext }
+ guard let locality else { return subLocality ?? name }
+ guard let administrativeArea, administrativeArea != locality else { return locality }
+ return "\(locality), \(administrativeArea)"
}
}
diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift
@@ -180,6 +180,51 @@ struct ReportStore: Sendable {
}
}
+ /// Deletes every report, question and token, leaving the store as a
+ /// fresh install has it before the default questions are added.
+ func deleteAll() async throws {
+ let context = persistence.newBackgroundContext()
+ let viewContext = persistence.viewContext
+ // Responses go with their reports, by the cascade.
+ let entities = ["ReportEntity", "TokenEntity", "QuestionEntity"]
+ let deleted = try await context.perform {
+ // Batch deletes run in SQLite without loading each object; the
+ // in-memory stores tests use don't support them.
+ let isSQLite = context.persistentStoreCoordinator?.persistentStores
+ .allSatisfy { $0.type == NSSQLiteStoreType } ?? false
+ var deleted: [NSManagedObjectID] = []
+ if isSQLite {
+ // A batch delete reports only the objects it was asked for.
+ let responses = NSFetchRequest<NSManagedObjectID>(entityName: "ResponseEntity")
+ responses.resultType = .managedObjectIDResultType
+ deleted += try context.fetch(responses)
+ }
+ for name in entities {
+ let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: name)
+ if isSQLite {
+ let request = NSBatchDeleteRequest(fetchRequest: fetch)
+ request.resultType = .resultTypeObjectIDs
+ let result = try context.execute(request) as? NSBatchDeleteResult
+ deleted += result?.result as? [NSManagedObjectID] ?? []
+ } else {
+ fetch.includesPropertyValues = false
+ for case let object as NSManagedObject in try context.fetch(fetch) {
+ context.delete(object)
+ }
+ }
+ }
+ try context.save()
+ return deleted
+ }
+ // A batch delete bypasses the contexts, so the screens are told.
+ if !deleted.isEmpty {
+ await viewContext.perform {
+ NSManagedObjectContext.mergeChanges(
+ fromRemoteContextSave: [NSDeletedObjectsKey: deleted], into: [viewContext])
+ }
+ }
+ }
+
private static func entity(id: UUID, in context: NSManagedObjectContext) throws -> ReportEntity? {
let request = ReportEntity.fetchRequest()
request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift
@@ -329,4 +329,41 @@ struct ReportStoreTests {
#expect(try await store.listStart(covering: 4, calendar: calendar) == day(0))
#expect(try await store.listStart(covering: 5, calendar: calendar) == nil)
}
+
+ @Test("Deleting all data empties the store, and the defaults can be seeded again")
+ func deleteAll() async throws {
+ _ = try await ReporterImporter(persistence: persistence)
+ .importArchive(try Fixtures.reporterExport())
+ try await store.deleteAll()
+
+ let context = persistence.newBackgroundContext()
+ let counts = try await context.perform {
+ try ["ResponseEntity", "ReportEntity", "TokenEntity", "QuestionEntity"].map {
+ try context.count(for: NSFetchRequest<NSFetchRequestResult>(entityName: $0))
+ }
+ }
+ #expect(counts == [0, 0, 0, 0])
+ #expect(try await store.seedDefaultQuestionsIfNeeded())
+ }
+
+ @Test("Deleting all data from an SQLite store reaches the view context")
+ @MainActor
+ func deleteAllSQLite() async throws {
+ let directory = URL.temporaryDirectory.appending(path: UUID().uuidString)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let persistence = PersistenceController(storeURL: directory.appending(path: "Store.sqlite"))
+ let store = ReportStore(persistence: persistence)
+ _ = try await ReporterImporter(persistence: persistence)
+ .importArchive(try Fixtures.reporterExport())
+
+ let shown = try persistence.viewContext.fetch(ReportEntity.fetchRequest())
+ #expect(!shown.isEmpty)
+ try await store.deleteAll()
+
+ #expect(shown.allSatisfy { $0.isDeleted || $0.managedObjectContext == nil })
+ #expect(try persistence.viewContext.count(for: ReportEntity.fetchRequest()) == 0)
+ #expect(try persistence.viewContext.count(for: ResponseEntity.fetchRequest()) == 0)
+ #expect(try persistence.viewContext.count(for: QuestionEntity.fetchRequest()) == 0)
+ }
}
diff --git a/Tests/Unit/ReportSummaryTests.swift b/Tests/Unit/ReportSummaryTests.swift
@@ -56,6 +56,17 @@ struct EntryBuilderTests {
== "Not working. Reading. Feeling great. 1 coffee. Learned: 'The neighbours are nice people.'")
}
+ @Test("Reporter's built-in questions read like the defaults that ask the same things")
+ func reporterRules() {
+ let (draft, details) = Self.build([
+ Self.response("default-question-1", .options(["Poorly"])),
+ Self.response("default-question-2", .options([ResponseValue.yesOption])),
+ Self.response("default-question-6", .number(2)),
+ ])
+ #expect(draft?.text == "Slept poorly. Working. 2 coffees.")
+ #expect(details.isEmpty)
+ }
+
@Test("Counts use the plural noun for anything but one")
func counts() {
let draft = Self.build([Self.response("reportage-default-coffee", .number(2))]).draft
@@ -167,17 +178,25 @@ struct InlineCasingTests {
@Suite("ReportSummary")
struct ReportSummaryTests {
- @Test("The context line names the locality")
+ @Test("The context line names the city with its region")
func contextLine() {
var context = Context()
context.location = LocationContext(
coordinate: Coordinate(latitude: 35.7, longitude: 139.58),
- placemark: Placemark(name: "1-2-3", locality: "Musashino")
+ placemark: Placemark(name: "1-2-3", subLocality: "Kichijōji")
)
+ #expect(ReportSummary.contextLine(context) == "Kichijōji")
+
+ context.location?.placemark?.locality = "Musashino"
#expect(ReportSummary.contextLine(context) == "Musashino")
- context.location?.placemark?.subLocality = "Kichijōji"
- #expect(ReportSummary.contextLine(context) == "Kichijōji")
+ // Imported placemarks have no city with its region, so it's put
+ // together, without repeating a region that is the city.
+ context.location?.placemark?.administrativeArea = "Tokyo"
+ #expect(ReportSummary.contextLine(context) == "Musashino, Tokyo")
+ context.location?.placemark?.administrativeArea = "Musashino"
+ #expect(ReportSummary.contextLine(context) == "Musashino")
+ context.location?.placemark?.administrativeArea = "Tokyo"
context.location?.placemark?.cityWithContext = "Suginami, Tokyo"
#expect(ReportSummary.contextLine(context) == "Suginami, Tokyo")
@@ -185,7 +204,7 @@ struct ReportSummaryTests {
context.weather = WeatherContext(source: .darkSky, condition: "Cloudy", temperature: 18.2)
let line = ReportSummary.contextLine(context)
- #expect(line?.hasPrefix("Kichijōji · ") == true)
+ #expect(line?.hasPrefix("Musashino, Tokyo · ") == true)
#expect(line?.hasSuffix(" Cloudy") == true)
}
}