commit e5fbb7611e980c5ff112f8154828cfda180bb6b7
parent 503ad68418678e224e2a1a54d91a13435e40a551
Author: Michael Camilleri <[email protected]>
Date: Wed, 21 Oct 2026 19:29:01 +0900
Import Reportage's own JSON exports
Import Reports could only read Reporter's exports, so a Reportage export
could not be used to restore the user's data onto a fresh install.
This commit lets Import Reports read both, telling them apart by the
top-level format member, which only Reportage's exports have. Records
are matched by ID: one missing from the store is added, and one already
there is replaced only if the export's modifiedAt is later, so an older
export never undoes newer edits and importing the same file twice
changes nothing. Reports are decoded one at a time, and one that can't
be read is skipped and counted. The timeline and Charts tab now reload
after any import.
Default questions are now seeded with a modifiedAt at the Unix epoch, so
an edited copy from an export, or later from another device, always
wins over a freshly seeded one. Demo reports also have fixed IDs, so an
export from one demo launch imports into another without duplicates.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 11 | +++++++++++ |
| M | Reportage.xcodeproj/project.pbxproj | | | 20 | ++++++++++++++++++++ |
| M | Reportage/Services/DemoSeed.swift | | | 12 | ++++++++++-- |
| M | Reportage/Services/Export/ReportageExport.swift | | | 16 | +++++++++++----- |
| A | Reportage/Services/ReportageImport/ArchiveFormat.swift | | | 27 | +++++++++++++++++++++++++++ |
| A | Reportage/Services/ReportageImport/ReportageImporter.swift | | | 207 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Settings/DataSection.swift | | | 104 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------- |
| M | Shared/Models/DefaultQuestions.swift | | | 9 | +++++++-- |
| M | Shared/Persistence/ReportStore.swift | | | 4 | ++-- |
| M | Tests/Unit/ImportMessageTests.swift | | | 17 | +++++++++++++++++ |
| M | Tests/Unit/ReportStoreTests.swift | | | 6 | +++--- |
| A | Tests/Unit/ReportageImporterTests.swift | | | 181 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/ReporterImporterTests.swift | | | 4 | ++-- |
13 files changed, 586 insertions(+), 32 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -182,6 +182,8 @@ never mix with an imported archive in the surveys; answers already given to them keep their meaning. They have fixed IDs (`reportage-default-` plus a name), so seeding is idempotent and two devices that both seed them end up with the same questions after syncing. +They're seeded with `modifiedAt` at the Unix epoch, so an edited copy from +an export or another device is always newer and wins over a fresh seed. Their prompts are written in the user's language at seeding time and are ordinary data after that. @@ -975,6 +977,15 @@ written one per line, in batches, so the archive is never held in memory as a whole. The schema is documented in `Notes/ExportFormat.md` and covered by round-trip tests. +**Import Reports** reads these exports as well as Reporter's, telling them +apart by the top-level `format` member, which only Reportage's exports have. +Records are matched by ID: one missing from the store is added, and one +already there is replaced only if the export's `modifiedAt` is later, so an +older export never undoes newer edits and re-importing changes nothing. The +export doesn't record deletions, so anything deleted since it was made comes +back. Reports are decoded one at a time, and one that can't be read is +skipped and counted. This restores a backup onto a fresh install. + **Delete All Data**, also in the Data section, asks first, then deletes every report, question and token and seeds the default questions again, leaving the app as a fresh install has it. Prompt settings are kept.
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -11,6 +11,7 @@
047D3797389624E8B4AF44B4 /* ReportageExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD433A98973E8B13E42230A1 /* ReportageExporter.swift */; };
06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */ = {isa = PBXBuildFile; fileRef = B03734F91822E7F161432075 /* Report.swift */; };
06BD386D5CA144F8D5053A39 /* NotificationsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */; };
+ 0AFAC8D04793CD85CFEE7329 /* ArchiveFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7117B46D7B8EE8E2510F806D /* ArchiveFormat.swift */; };
0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E55C093BA98D8700F406AE /* ReportStoreTests.swift */; };
123470F9E3205890526D3A89 /* EventLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFF717BC324925C231BD3378 /* EventLog.swift */; };
141F97BD7B695424E7ED30D6 /* ContextCharts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 996F5818A958E305371F4BE3 /* ContextCharts.swift */; };
@@ -90,6 +91,7 @@
C71E99843CC3D9DE4468B36B /* Environment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 878CE0FF7A2598F4197E8E61 /* Environment.swift */; };
C87E1C0465FE7B2917F92846 /* PromptSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */; };
C8E02DEA2119E61D31667FFE /* ReporterImportPlanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */; };
+ C9FD2FE13F80F1F064A0DEC2 /* ReportageImporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83C5FB4631405F1706BB2C94 /* ReportageImporter.swift */; };
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */; };
D1F2257DDB68439AF352B57D /* PassiveLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46FB42E5DB43201A13D6D141 /* PassiveLog.swift */; };
D1FFB84FFDF0F659D8D78AEB /* ReportageWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EDD39E85D86AFF45B5672F3 /* ReportageWidgets.swift */; };
@@ -112,6 +114,7 @@
EA730F4FD060F5843CC5B422 /* SurveyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7998F9826B899741323C0C7 /* SurveyView.swift */; };
EFF44121C9ECBFBCAC1D7730 /* ReportageModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = A49FBFD55992A79B9A6492C4 /* ReportageModel.xcdatamodeld */; };
F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */ = {isa = PBXBuildFile; fileRef = B007E6BACAA214C7332EF77C /* Question.swift */; };
+ F7EBA038A8409CC922DE3EE1 /* ReportageImporterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F814788097E33F94C704E5B /* ReportageImporterTests.swift */; };
FBE598AB29E0297BC232ED75 /* ReportDetailsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */; };
FD41318BC8EEAF3208CD59B7 /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A70B6E5B7C07D2CE13E9E771 /* RootView.swift */; };
/* End PBXBuildFile section */
@@ -179,6 +182,7 @@
48ACB0E76C4E2271EA59B8E9 /* QuestionEditorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionEditorTests.swift; sourceTree = "<group>"; };
48D44876FDE4293FA0460595 /* ReporterImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImporter.swift; sourceTree = "<group>"; };
4C40E7F6C3A90E317C8CB5B1 /* PlacePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePicker.swift; sourceTree = "<group>"; };
+ 4F814788097E33F94C704E5B /* ReportageImporterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageImporterTests.swift; sourceTree = "<group>"; };
50FA891F300310E4E378EB09 /* ReportCalendar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportCalendar.swift; sourceTree = "<group>"; };
5591E042089D038B59B26E9F /* ReportKind+Title.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ReportKind+Title.swift"; sourceTree = "<group>"; };
577EC17EF58F65207B7EA15D /* PlacePhrase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePhrase.swift; sourceTree = "<group>"; };
@@ -193,6 +197,7 @@
662E31DC0006681643DD0A8D /* VocabularyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VocabularyView.swift; sourceTree = "<group>"; };
695CB01E79016592A3823541 /* HealthTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthTests.swift; sourceTree = "<group>"; };
6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModelTests.swift; sourceTree = "<group>"; };
+ 7117B46D7B8EE8E2510F806D /* ArchiveFormat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArchiveFormat.swift; sourceTree = "<group>"; };
7196D553D769071DB876B606 /* ReporterTimeZones.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterTimeZones.swift; sourceTree = "<group>"; };
729C291798F29C69029E7DB7 /* InstantReportLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InstantReportLogger.swift; sourceTree = "<group>"; };
74FF461F6E8A0241C18357B2 /* Vocabulary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Vocabulary.swift; sourceTree = "<group>"; };
@@ -206,6 +211,7 @@
7F9A0A87A54F3E96E079F52D /* QuestionsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionsView.swift; sourceTree = "<group>"; };
7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportPlanTests.swift; sourceTree = "<group>"; };
81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
+ 83C5FB4631405F1706BB2C94 /* ReportageImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageImporter.swift; sourceTree = "<group>"; };
844ABAD88442C143BA239374 /* SurveyModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModel.swift; sourceTree = "<group>"; };
84E55C093BA98D8700F406AE /* ReportStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportStoreTests.swift; sourceTree = "<group>"; };
86069F79CD8FA24FC6C26650 /* HealthContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthContext.swift; sourceTree = "<group>"; };
@@ -332,6 +338,15 @@
path = Health;
sourceTree = "<group>";
};
+ 40C0504858C23EDB12EC4962 /* ReportageImport */ = {
+ isa = PBXGroup;
+ children = (
+ 7117B46D7B8EE8E2510F806D /* ArchiveFormat.swift */,
+ 83C5FB4631405F1706BB2C94 /* ReportageImporter.swift */,
+ );
+ path = ReportageImport;
+ sourceTree = "<group>";
+ };
40C7D2F3410CAC897AFD7083 /* Charts */ = {
isa = PBXGroup;
children = (
@@ -417,6 +432,7 @@
96D6D46E008E39350B203328 /* Narrative */,
580063E6A7AE05D5C6C16830 /* Places */,
0CECB181B29E96DE98FDF293 /* Prompts */,
+ 40C0504858C23EDB12EC4962 /* ReportageImport */,
F7B8E02FFC282DCD163E25FE /* ReporterImport */,
);
path = Services;
@@ -469,6 +485,7 @@
0E6B536B922A8468136815CD /* QuestionListTests.swift */,
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */,
7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */,
+ 4F814788097E33F94C704E5B /* ReportageImporterTests.swift */,
BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */,
487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */,
917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */,
@@ -753,6 +770,7 @@
0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */,
D3FF67FB406DCCB78DF9D61A /* ReportSummaryTests.swift in Sources */,
B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */,
+ F7EBA038A8409CC922DE3EE1 /* ReportageImporterTests.swift in Sources */,
28D2CDAAB0777233D4465A83 /* ReporterArchiveTests.swift in Sources */,
C8E02DEA2119E61D31667FFE /* ReporterImportPlanTests.swift in Sources */,
E68EF6274FD2F6D54D49F5BD /* ReporterImporterTests.swift in Sources */,
@@ -771,6 +789,7 @@
E3C74ABCE348FFF05890690E /* AnswerSummary.swift in Sources */,
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */,
E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */,
+ 0AFAC8D04793CD85CFEE7329 /* ArchiveFormat.swift in Sources */,
811704907EE199CC627F0CE5 /* BackgroundLocation.swift in Sources */,
3BDDC4FD8CE13B29BCDE3ADC /* ChartsView.swift in Sources */,
DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
@@ -825,6 +844,7 @@
961848A8D899BC67FA43F475 /* ReportageApp.swift in Sources */,
E0137FEEBF13F5D14C07656F /* ReportageExport.swift in Sources */,
047D3797389624E8B4AF44B4 /* ReportageExporter.swift in Sources */,
+ C9FD2FE13F80F1F064A0DEC2 /* ReportageImporter.swift in Sources */,
EFF44121C9ECBFBCAC1D7730 /* ReportageModel.xcdatamodeld in Sources */,
9EF3CB3707CD6B5AFFD3B767 /* ReporterArchive.swift in Sources */,
68DDAB8BB2E679EB7EC1E9C1 /* ReporterImportPlan.swift in Sources */,
diff --git a/Reportage/Services/DemoSeed.swift b/Reportage/Services/DemoSeed.swift
@@ -61,12 +61,20 @@ enum DemoSeed {
func answer(_ question: String, _ value: ResponseValue?) -> Response {
Response(questionID: p + question, prompt: "", value: value)
}
+ // Report IDs are fixed, in the order the reports are made, so every
+ // launch seeds the same reports and an export from one launch
+ // imports into another without duplicates.
+ var reportCount = 0
+ func reportID() -> UUID {
+ reportCount += 1
+ return UUID(uuidString: String(format: "DE000000-0000-4000-8000-%012d", reportCount))!
+ }
// Prompted reports come from a notification; the rest are started
// in the app.
func report(_ date: Date, _ kind: ReportKind, _ responses: [Response], _ context: Context) -> Report {
let isPrompted = kind == .random
return Report(
- id: UUID(), date: date, timeZone: TimeZone.current.identifier, kind: kind,
+ id: reportID(), date: date, timeZone: TimeZone.current.identifier, kind: kind,
trigger: isPrompted ? .notification : .app, state: .complete, promptedAt: isPrompted ? date : nil,
completedAt: date.addingTimeInterval(40), context: context, responses: responses, modifiedAt: now)
}
@@ -119,7 +127,7 @@ enum DemoSeed {
// An Instant Report from a prompt: context and no answers.
(
Report(
- id: UUID(), date: at(0, 13, 4), timeZone: TimeZone.current.identifier, kind: .random,
+ id: reportID(), date: at(0, 13, 4), timeZone: TimeZone.current.identifier, kind: .random,
trigger: .notification, state: .passive, promptedAt: at(0, 13, 4),
context: context(park, 19, "Partly Cloudy"), modifiedAt: now),
steps(6_318)
diff --git a/Reportage/Services/Export/ReportageExport.swift b/Reportage/Services/Export/ReportageExport.swift
@@ -20,13 +20,18 @@ struct ReportageExport: Decodable, Sendable {
/// Decodes an export, rejecting other formats and newer versions.
static func decode(_ data: Data) throws -> ReportageExport {
let header = try ExportDates.decoder.decode(Header.self, from: data)
- guard header.format == format else {
- throw ReportageExportError.unknownFormat(header.format)
+ try check(format: header.format, version: header.version)
+ return try ExportDates.decoder.decode(ReportageExport.self, from: data)
+ }
+
+ /// Throws unless a file with this header can be read.
+ static func check(format: String, version: Int) throws {
+ guard format == self.format else {
+ throw ReportageExportError.unknownFormat(format)
}
- guard header.version <= version else {
- throw ReportageExportError.unsupportedVersion(header.version)
+ guard version <= self.version else {
+ throw ReportageExportError.unsupportedVersion(version)
}
- return try ExportDates.decoder.decode(ReportageExport.self, from: data)
}
private struct Header: Decodable {
@@ -39,6 +44,7 @@ enum ReportageExportError: Error, Equatable {
case unknownFormat(String)
case unsupportedVersion(Int)
case unknownSurvey(String)
+ case missingMember(String)
}
/// Dates are ISO 8601 with a numeric offset. Dates inside a report use the
diff --git a/Reportage/Services/ReportageImport/ArchiveFormat.swift b/Reportage/Services/ReportageImport/ArchiveFormat.swift
@@ -0,0 +1,27 @@
+import Foundation
+
+/// The two kinds of JSON export **Import Reports** reads.
+enum ArchiveFormat: Equatable, Sendable {
+ case reporter
+ case reportage
+
+ enum Error: Swift.Error, Equatable {
+ case noJSONObject
+ }
+
+ /// Reportage's exports have a top-level `format` member and Reporter's
+ /// don't. Only the top level is scanned, so nothing is decoded.
+ init(data: Data) throws {
+ let members = try Self.members(of: data)
+ self = members.contains { $0.key == "format" } ? .reportage : .reporter
+ }
+
+ /// The members of the file's top-level object. Reporter's exports start
+ /// with junk before the opening brace, so it's skipped.
+ static func members(of data: Data) throws -> [(key: String, range: Range<Int>)] {
+ guard let start = data.firstIndex(of: UInt8(ascii: "{")) else {
+ throw Error.noJSONObject
+ }
+ return try JSONSlicer.objectMembers(in: data, at: start)
+ }
+}
diff --git a/Reportage/Services/ReportageImport/ReportageImporter.swift b/Reportage/Services/ReportageImport/ReportageImporter.swift
@@ -0,0 +1,207 @@
+import CoreData
+import Foundation
+
+struct ReportageImportSummary: Equatable, Sendable {
+ struct Counts: Equatable, Sendable {
+ var inserted = 0
+ var updated = 0
+ var unchanged = 0
+
+ var changed: Int { inserted + updated }
+ }
+
+ /// A report the export holds but that couldn't be decoded.
+ struct Failure: Equatable, Sendable {
+ var index: Int
+ var message: String
+ }
+
+ var questions = Counts()
+ var tokens = Counts()
+ var reports = Counts()
+ var failures: [Failure] = []
+}
+
+/// Imports a Reportage JSON export (`Notes/ExportFormat.md`) into the store,
+/// to restore a backup or to merge in another store's records.
+///
+/// Records are matched by ID. One missing from the store is added; one
+/// already there is replaced only if the export's `modifiedAt` is later, so
+/// importing an older export never undoes newer edits and importing the
+/// same export twice changes nothing. Records deleted from the store since
+/// the export was made come back, as nothing in the export marks deletions.
+struct ReportageImporter: Sendable {
+ static let batchSize = 500
+
+ let persistence: PersistenceController
+
+ @concurrent
+ func importArchive(at url: URL) async throws -> ReportageImportSummary {
+ try await importArchive(Data(contentsOf: url, options: .mappedIfSafe))
+ }
+
+ @concurrent
+ func importArchive(_ data: Data) async throws -> ReportageImportSummary {
+ let archive = try Archive(data: data)
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ try Self.write(archive, into: context)
+ }
+ }
+
+ /// The export's questions and tokens, decoded, and its reports as byte
+ /// ranges, decoded a batch at a time while they're written.
+ private struct Archive {
+ var data: Data
+ var questions: [Question]
+ var tokens: [Token]
+ var reports: [Range<Int>]
+
+ init(data: Data) throws {
+ let members = try ArchiveFormat.members(of: data)
+ func range(of key: String) throws -> Range<Int> {
+ guard let member = members.first(where: { $0.key == key }) else {
+ throw ReportageExportError.missingMember(key)
+ }
+ return member.range
+ }
+ func value(_ key: String) throws -> Data { data[try range(of: key)] }
+
+ let decoder = ExportDates.decoder
+ try ReportageExport.check(
+ format: try decoder.decode(String.self, from: value("format")),
+ version: try decoder.decode(Int.self, from: value("version")))
+ self.data = data
+ questions = try decoder.decode([ExportedQuestion].self, from: value("questions"))
+ .map { try $0.question() }
+ tokens = try decoder.decode([ExportedToken].self, from: value("tokens"))
+ .map { $0.token() }
+ reports = try JSONSlicer.arrayElements(in: data, range: try range(of: "reports"))
+ }
+ }
+
+ /// When each stored record of `entityName` was last modified, by ID.
+ private static func modifiedDates<ID: Hashable>(
+ of entityName: String,
+ as type: ID.Type,
+ in context: NSManagedObjectContext
+ ) throws -> [ID: Date] {
+ let request = NSFetchRequest<NSDictionary>(entityName: entityName)
+ request.resultType = .dictionaryResultType
+ request.propertiesToFetch = ["id", "modifiedAt"]
+ var dates: [ID: Date] = [:]
+ for row in try context.fetch(request) {
+ guard let id = row["id"] as? ID, let date = row["modifiedAt"] as? Date else { continue }
+ dates[id] = date
+ }
+ return dates
+ }
+
+ /// Splits `records` into those to insert and those to replace, counting
+ /// the rest as unchanged.
+ private static func classify<Record, ID: Hashable>(
+ _ records: [Record],
+ id: (Record) -> ID,
+ modifiedAt: (Record) -> Date,
+ against stored: [ID: Date],
+ counts: inout ReportageImportSummary.Counts
+ ) -> (inserts: [Record], updates: [ID: Record]) {
+ var inserts: [Record] = []
+ var updates: [ID: Record] = [:]
+ for record in records {
+ if let date = stored[id(record)] {
+ if modifiedAt(record) > date {
+ updates[id(record)] = record
+ } else {
+ counts.unchanged += 1
+ }
+ } else {
+ inserts.append(record)
+ }
+ }
+ counts.inserted += inserts.count
+ counts.updated += updates.count
+ return (inserts, updates)
+ }
+
+ private static func write(
+ _ archive: Archive,
+ into context: NSManagedObjectContext
+ ) throws -> ReportageImportSummary {
+ var summary = ReportageImportSummary()
+
+ let questions = classify(
+ archive.questions, id: \.id, modifiedAt: \.modifiedAt,
+ against: try modifiedDates(of: "QuestionEntity", as: String.self, in: context),
+ counts: &summary.questions)
+ for question in questions.inserts {
+ try QuestionEntity(context: context).update(from: question)
+ }
+ if !questions.updates.isEmpty {
+ let request = QuestionEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id IN %@", Array(questions.updates.keys))
+ for entity in try context.fetch(request) {
+ guard let id = entity.id, let question = questions.updates[id] else { continue }
+ try entity.update(from: question)
+ }
+ }
+ try context.save()
+ context.reset()
+
+ let tokens = classify(
+ archive.tokens, id: \.id, modifiedAt: \.modifiedAt,
+ against: try modifiedDates(of: "TokenEntity", as: String.self, in: context),
+ counts: &summary.tokens)
+ for token in tokens.inserts {
+ try TokenEntity(context: context).update(from: token)
+ }
+ if !tokens.updates.isEmpty {
+ let request = TokenEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id IN %@", Array(tokens.updates.keys))
+ for entity in try context.fetch(request) {
+ guard let id = entity.id, let token = tokens.updates[id] else { continue }
+ try entity.update(from: token)
+ }
+ }
+ try context.save()
+ context.reset()
+
+ let storedReports = try modifiedDates(of: "ReportEntity", as: UUID.self, in: context)
+ let decoder = ExportDates.decoder
+ var start = 0
+ while start < archive.reports.count {
+ let end = min(start + batchSize, archive.reports.count)
+ var batch: [Report] = []
+ for index in start..<end {
+ do {
+ batch.append(
+ try decoder.decode(ExportedReport.self, from: archive.data[archive.reports[index]])
+ .report())
+ } catch {
+ summary.failures.append(.init(index: index, message: String(describing: error)))
+ }
+ }
+ let reports = classify(
+ batch, id: \.id, modifiedAt: \.modifiedAt,
+ against: storedReports, counts: &summary.reports)
+ for report in reports.inserts {
+ try ReportEntity(context: context).update(from: report)
+ }
+ if !reports.updates.isEmpty {
+ let request = ReportEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id IN %@", Array(reports.updates.keys))
+ request.relationshipKeyPathsForPrefetching = ["responses"]
+ for entity in try context.fetch(request) {
+ guard let id = entity.id, let report = reports.updates[id] else { continue }
+ try entity.update(from: report)
+ }
+ }
+ if context.hasChanges {
+ try context.save()
+ }
+ context.reset()
+ start = end
+ }
+ return summary
+ }
+}
diff --git a/Reportage/Views/Settings/DataSection.swift b/Reportage/Views/Settings/DataSection.swift
@@ -3,7 +3,7 @@ import OSLog
import SwiftUI
import UniformTypeIdentifiers
-/// Importing a Reporter export, exporting the store as JSON, improving
+/// Importing a Reporter or Reportage export, exporting the store as JSON, improving
/// earlier reports on the Historical Data screen, and deleting everything.
struct DataSection: View {
@Environment(\.reportStore) private var store
@@ -15,8 +15,6 @@ struct DataSection: View {
@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
@@ -122,13 +120,34 @@ struct DataSection: View {
let isScoped = url.startAccessingSecurityScopedResource()
defer { if isScoped { url.stopAccessingSecurityScopedResource() } }
do {
- let summary = try await ReporterImporter(persistence: store.persistence).importArchive(at: url)
- log(summary)
- outcome = Outcome(title: "Import Finished", message: Self.message(for: summary))
+ let message = try await Self.importArchive(at: url, persistence: store.persistence)
+ outcome = Outcome(title: "Import Finished", message: message)
} catch {
- logger.error("Couldn't import a Reporter export: \(error)")
+ Self.logger.error("Couldn't import: \(error)")
outcome = Outcome(title: "Couldn't Import", message: error.localizedDescription)
}
+ // Imported questions and vocabulary change how reports read.
+ NotificationCenter.default.post(name: .summaryLookupChanged, object: nil)
+ }
+
+ /// Imports either kind of export, telling them apart by their contents,
+ /// and returns what to tell the user.
+ @concurrent
+ private static func importArchive(
+ at url: URL,
+ persistence: PersistenceController
+ ) async throws -> String {
+ let data = try Data(contentsOf: url, options: .mappedIfSafe)
+ switch try ArchiveFormat(data: data) {
+ case .reporter:
+ let summary = try await ReporterImporter(persistence: persistence).importArchive(data)
+ log(summary)
+ return message(for: summary)
+ case .reportage:
+ let summary = try await ReportageImporter(persistence: persistence).importArchive(data)
+ log(summary)
+ return message(for: summary)
+ }
}
private func export() async {
@@ -140,10 +159,10 @@ struct DataSection: View {
do {
let summary = try await ReportageExporter(persistence: store.persistence)
.export(to: url)
- logger.info("Exported \(summary.reports) reports, \(summary.questions) questions, \(summary.tokens) tokens")
+ Self.logger.info("Exported \(summary.reports) reports, \(summary.questions) questions, \(summary.tokens) tokens")
exported = ExportFile(url: url)
} catch {
- logger.error("Couldn't export: \(error)")
+ Self.logger.error("Couldn't export: \(error)")
outcome = Outcome(title: "Couldn't Export", message: error.localizedDescription)
}
}
@@ -155,9 +174,9 @@ struct DataSection: View {
do {
try await store.deleteAll()
try await store.seedDefaultQuestionsIfNeeded()
- logger.info("Deleted all data")
+ Self.logger.info("Deleted all data")
} catch {
- logger.error("Couldn't delete all data: \(error)")
+ Self.logger.error("Couldn't delete all data: \(error)")
outcome = Outcome(title: "Couldn't Delete", message: error.localizedDescription)
}
}
@@ -169,8 +188,10 @@ struct DataSection: View {
self.exported = nil
}
+ nonisolated private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Data")
+
/// Counts and fallbacks only: IDs, never the contents of reports.
- private func log(_ summary: ReporterImportSummary) {
+ nonisolated private static func log(_ summary: ReporterImportSummary) {
logger.info(
"""
Imported \(summary.reportsInserted) reports (\(summary.reportsAlreadyPresent) already present), \
@@ -180,14 +201,14 @@ struct DataSection: View {
\(summary.fallbacks.count) fallbacks, \(summary.failures.count) failures
""")
for warning in summary.warnings {
- logger.notice("Import warning: \(warning)")
+ Self.logger.notice("Import warning: \(warning)")
}
for failure in summary.failures {
- logger.error("Snapshot \(failure.index) (\(failure.reportID ?? "no ID")) failed: \(failure.message)")
+ Self.logger.error("Snapshot \(failure.index) (\(failure.reportID ?? "no ID")) failed: \(failure.message)")
}
}
- static func message(for summary: ReporterImportSummary) -> String {
+ nonisolated static func message(for summary: ReporterImportSummary) -> String {
var lines: [String] = []
if summary.reportsInserted == 0 {
lines.append(String(localized: "No new reports. Everything in this export was already imported."))
@@ -209,9 +230,60 @@ struct DataSection: View {
return lines.joined(separator: "\n\n")
}
+ /// Counts only, never the contents of reports.
+ nonisolated private static func log(_ summary: ReportageImportSummary) {
+ func counts(_ counts: ReportageImportSummary.Counts) -> String {
+ "\(counts.inserted) added, \(counts.updated) updated, \(counts.unchanged) unchanged"
+ }
+ logger.info(
+ """
+ Imported a Reportage export: reports \(counts(summary.reports)); \
+ questions \(counts(summary.questions)); tokens \(counts(summary.tokens)); \
+ \(summary.failures.count) failures
+ """)
+ for failure in summary.failures {
+ Self.logger.error("Report \(failure.index) failed: \(failure.message)")
+ }
+ }
+
+ nonisolated static func message(for summary: ReportageImportSummary) -> String {
+ var lines: [String] = []
+ let reports = summary.reports
+ if reports.changed == 0 && summary.questions.changed == 0 && summary.tokens.changed == 0 {
+ lines.append(String(localized: "No changes. Everything in this export is already in Reportage."))
+ } else {
+ if reports.inserted > 0 {
+ lines.append(inflected("Added ^[\(reports.inserted) report](inflect: true)."))
+ }
+ if reports.updated > 0 {
+ lines.append(
+ inflected("Updated ^[\(reports.updated) report](inflect: true) with a newer version from the export."))
+ }
+ let questions = summary.questions.changed
+ let names = summary.tokens.changed
+ if questions > 0 && names > 0 {
+ lines.append(
+ inflected(
+ "Added or updated ^[\(questions) question](inflect: true) and ^[\(names) name](inflect: true)."
+ ))
+ } else if questions > 0 {
+ lines.append(inflected("Added or updated ^[\(questions) question](inflect: true)."))
+ } else if names > 0 {
+ lines.append(inflected("Added or updated ^[\(names) name](inflect: true)."))
+ }
+ if reports.unchanged > 0 {
+ lines.append(inflected("^[\(reports.unchanged) report](inflect: true) had no newer changes."))
+ }
+ }
+ if !summary.failures.isEmpty {
+ lines.append(inflected("Skipped ^[\(summary.failures.count) report](inflect: true) that couldn't be read."))
+ }
+ return lines.joined(separator: "\n\n")
+ }
+
/// `resource` with its counted words inflected. A plain `String` keeps
/// the inflection markup as written; an attributed string applies it.
- private static func inflected(_ resource: String.LocalizationValue) -> String {
+ nonisolated private static func inflected(_ resource: String.LocalizationValue) -> String {
String(AttributedString(localized: resource).characters)
}
}
diff --git a/Shared/Models/DefaultQuestions.swift b/Shared/Models/DefaultQuestions.swift
@@ -10,7 +10,12 @@ enum DefaultQuestions {
/// The start of every default question's ID.
static let idPrefix = "reportage-default-"
- static func make(now: Date) -> [Question] {
+ /// When every default question was last modified, before any edit. An
+ /// export or another device holding an edited copy is always newer, so
+ /// its edits win over a freshly seeded question.
+ static let seededAt = Date(timeIntervalSince1970: 0)
+
+ static func make() -> [Question] {
func question(
_ id: String,
_ prompt: String,
@@ -25,7 +30,7 @@ enum DefaultQuestions {
options: options,
askOn: askOn,
order: 0,
- modifiedAt: now
+ modifiedAt: seededAt
)
}
diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift
@@ -10,13 +10,13 @@ struct ReportStore: Sendable {
/// fresh install has a survey to show. A store with imported or edited
/// questions is left alone.
@discardableResult
- func seedDefaultQuestionsIfNeeded(now: Date = Date()) async throws -> Bool {
+ func seedDefaultQuestionsIfNeeded() async throws -> Bool {
let context = persistence.newBackgroundContext()
return try await context.perform {
let request = QuestionEntity.fetchRequest()
request.fetchLimit = 1
guard try context.count(for: request) == 0 else { return false }
- for question in DefaultQuestions.make(now: now) {
+ for question in DefaultQuestions.make() {
try QuestionEntity(context: context).update(from: question)
}
try context.save()
diff --git a/Tests/Unit/ImportMessageTests.swift b/Tests/Unit/ImportMessageTests.swift
@@ -18,4 +18,21 @@ struct ImportMessageTests {
#expect(message.contains("1 question."))
#expect(message.contains("2 reports had"))
}
+
+ @Test("A Reportage import counts what changed, with counts inflected")
+ func reportage() {
+ var summary = ReportageImportSummary()
+ summary.reports = .init(inserted: 1, updated: 2, unchanged: 1)
+ summary.tokens = .init(inserted: 3)
+ let message = DataSection.message(for: summary)
+ #expect(!message.contains("^["))
+ #expect(message.contains("Added 1 report."))
+ #expect(message.contains("Updated 2 reports"))
+ #expect(message.contains("Added or updated 3 names."))
+ #expect(message.contains("1 report had no newer changes."))
+
+ summary = ReportageImportSummary()
+ summary.reports.unchanged = 5
+ #expect(DataSection.message(for: summary).hasPrefix("No changes."))
+ }
}
diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift
@@ -44,7 +44,7 @@ struct ReportStoreTests {
#expect(try await store.seedDefaultQuestionsIfNeeded())
#expect(try await !store.seedDefaultQuestionsIfNeeded())
- let defaults = DefaultQuestions.make(now: Date())
+ let defaults = DefaultQuestions.make()
#expect(try await questionCount() == defaults.count)
#expect(Set(defaults.map(\.kind)) == Set(QuestionKind.allCases))
#expect(defaults.map(\.order) == Array(defaults.indices))
@@ -437,7 +437,7 @@ struct ReportStoreTests {
extension ReportStoreTests {
@Test("Edited questions are saved, and every question is listed in order")
func saveQuestions() async throws {
- try await store.seedDefaultQuestionsIfNeeded(now: Date(timeIntervalSince1970: 0))
+ try await store.seedDefaultQuestionsIfNeeded()
var questions = try await store.allQuestions()
#expect(questions.map(\.order) == Array(questions.indices))
questions[0].showsInTimeline = false
@@ -451,7 +451,7 @@ extension ReportStoreTests {
@Test("Narrative rules are stored with questions, and missing built-in rules are filled once")
func narrativeRules() async throws {
- try await store.seedDefaultQuestionsIfNeeded(now: Date(timeIntervalSince1970: 0))
+ try await store.seedDefaultQuestionsIfNeeded()
var questions = try await store.allQuestions()
let mood = try #require(questions.firstIndex { $0.id == DefaultQuestions.idPrefix + "mood" })
let working = try #require(questions.firstIndex { $0.id == DefaultQuestions.idPrefix + "working" })
diff --git a/Tests/Unit/ReportageImporterTests.swift b/Tests/Unit/ReportageImporterTests.swift
@@ -0,0 +1,181 @@
+import CoreData
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@Suite("ReportageImporter")
+struct ReportageImporterTests {
+
+ private static let report = Report(
+ id: UUID(uuidString: "E0000002-0000-4000-8000-000000000000")!,
+ date: Date(timeIntervalSince1970: 1_736_893_800),
+ timeZone: "Australia/Sydney",
+ kind: .manual,
+ trigger: .app,
+ state: .complete,
+ completedAt: Date(timeIntervalSince1970: 1_736_893_860),
+ responses: [Response(questionID: "Q1", prompt: "How many?", value: .number(2))],
+ modifiedAt: Date(timeIntervalSince1970: 1_736_893_860)
+ )
+
+ private static func edited(_ report: Report, value: Decimal, at seconds: TimeInterval) -> Report {
+ var report = report
+ report.responses = [Response(questionID: "Q1", prompt: "How many?", value: .number(value))]
+ report.modifiedAt = report.modifiedAt.addingTimeInterval(seconds)
+ return report
+ }
+
+ private static func export(_ persistence: PersistenceController) async throws -> Data {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("reportage-import-\(UUID().uuidString).json")
+ defer { try? FileManager.default.removeItem(at: url) }
+ _ = try await ReportageExporter(persistence: persistence).export(to: url)
+ return try Data(contentsOf: url)
+ }
+
+ private static func insert(_ report: Report, into persistence: PersistenceController) async throws {
+ let context = persistence.newBackgroundContext()
+ try await context.perform {
+ try ReportEntity(context: context).update(from: report)
+ try context.save()
+ }
+ }
+
+ private static func stored(
+ _ persistence: PersistenceController
+ ) async throws -> (questions: Set<Question>, tokens: Set<Token>, reports: [Report]) {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let reports = ReportEntity.fetchRequest()
+ reports.sortDescriptors = [
+ NSSortDescriptor(key: "date", ascending: true),
+ NSSortDescriptor(key: "id", ascending: true),
+ ]
+ return (
+ Set(try context.fetch(QuestionEntity.fetchRequest()).map { try $0.question() }),
+ Set(try context.fetch(TokenEntity.fetchRequest()).map { try $0.token() }),
+ try context.fetch(reports).map { try $0.report() }
+ )
+ }
+ }
+
+ /// An export of the Reporter fixture, as made by another store.
+ private static func fixtureExport() async throws -> (data: Data, source: PersistenceController) {
+ let source = makeTestPersistence()
+ _ = try await ReporterImporter(persistence: source)
+ .importArchive(try Fixtures.reporterExport(), now: Date(timeIntervalSince1970: 0))
+ return (try await export(source), source)
+ }
+
+ @Test("Importing an export into an empty store restores it exactly")
+ func restore() async throws {
+ let (data, source) = try await Self.fixtureExport()
+ let target = makeTestPersistence()
+ let summary = try await ReportageImporter(persistence: target).importArchive(data)
+
+ #expect(summary.questions == .init(inserted: 9))
+ #expect(summary.tokens == .init(inserted: 11))
+ #expect(summary.reports == .init(inserted: 14))
+ #expect(summary.failures.isEmpty)
+ let expected = try await Self.stored(source)
+ let restored = try await Self.stored(target)
+ #expect(restored.questions == expected.questions)
+ #expect(restored.tokens == expected.tokens)
+ #expect(restored.reports == expected.reports)
+ }
+
+ @Test("Importing the same export again changes nothing")
+ func idempotent() async throws {
+ let (data, _) = try await Self.fixtureExport()
+ let target = makeTestPersistence()
+ let importer = ReportageImporter(persistence: target)
+ _ = try await importer.importArchive(data)
+ let before = try await Self.stored(target)
+
+ let again = try await importer.importArchive(data)
+ #expect(again.questions == .init(unchanged: 9))
+ #expect(again.tokens == .init(unchanged: 11))
+ #expect(again.reports == .init(unchanged: 14))
+ let after = try await Self.stored(target)
+ #expect(after.questions == before.questions)
+ #expect(after.reports == before.reports)
+ }
+
+ @Test("A record is replaced only when the export's copy is newer")
+ func newerWins() async throws {
+ let source = makeTestPersistence()
+ try await Self.insert(Self.report, into: source)
+ let data = try await Self.export(source)
+
+ let newer = makeTestPersistence()
+ let edited = Self.edited(Self.report, value: 3, at: 60)
+ try await Self.insert(edited, into: newer)
+ let kept = try await ReportageImporter(persistence: newer).importArchive(data)
+ #expect(kept.reports == .init(unchanged: 1))
+ #expect(try await Self.stored(newer).reports == [edited])
+
+ let older = makeTestPersistence()
+ try await Self.insert(Self.edited(Self.report, value: 3, at: -60), into: older)
+ let replaced = try await ReportageImporter(persistence: older).importArchive(data)
+ #expect(replaced.reports == .init(updated: 1))
+ #expect(try await Self.stored(older).reports == [Self.report])
+ let context = older.newBackgroundContext()
+ let responses = try await context.perform {
+ try context.count(for: ResponseEntity.fetchRequest())
+ }
+ #expect(responses == 1)
+ }
+
+ @Test("Edits to default questions win over a fresh install's defaults")
+ func editedDefaults() async throws {
+ let source = makeTestPersistence()
+ let store = ReportStore(persistence: source)
+ try await store.seedDefaultQuestionsIfNeeded()
+ var question = try #require(try await store.allQuestions().first)
+ question.prompt = "Reworded?"
+ question.archivedAt = Date(timeIntervalSince1970: 100)
+ question.modifiedAt = Date(timeIntervalSince1970: 100)
+ try await store.save([question])
+ let data = try await Self.export(source)
+
+ let fresh = makeTestPersistence()
+ try await ReportStore(persistence: fresh).seedDefaultQuestionsIfNeeded()
+ let summary = try await ReportageImporter(persistence: fresh).importArchive(data)
+ #expect(summary.questions.updated == 1)
+ #expect(summary.questions.unchanged == DefaultQuestions.make().count - 1)
+ #expect(try await Self.stored(fresh).questions.contains(question))
+ }
+
+ @Test("A report that can't be read is skipped and the rest are imported")
+ func unreadableReport() async throws {
+ let (data, _) = try await Self.fixtureExport()
+ var lines = String(decoding: data, as: UTF8.self).components(separatedBy: "\n")
+ let first = try #require(lines.firstIndex(of: "\"reports\":[")) + 1
+ lines[first] = #"{"id":"not a report"},"#
+ let damaged = Data(lines.joined(separator: "\n").utf8)
+
+ let summary = try await ReportageImporter(persistence: makeTestPersistence())
+ .importArchive(damaged)
+ #expect(summary.reports == .init(inserted: 13))
+ #expect(summary.failures.map(\.index) == [0])
+ }
+
+ @Test("Newer versions of the format are rejected")
+ func newerVersion() async throws {
+ let data = Data(#"{"format":"reportage","version":2,"questions":[],"tokens":[],"reports":[]}"#.utf8)
+ await #expect(throws: ReportageExportError.unsupportedVersion(2)) {
+ try await ReportageImporter(persistence: makeTestPersistence()).importArchive(data)
+ }
+ }
+
+ @Test("Reporter and Reportage exports are told apart")
+ func format() async throws {
+ #expect(try ArchiveFormat(data: Fixtures.reporterExport()) == .reporter)
+ let export = try await Self.fixtureExport().data
+ #expect(try ArchiveFormat(data: export) == .reportage)
+ #expect(throws: ArchiveFormat.Error.noJSONObject) {
+ try ArchiveFormat(data: Data("[]".utf8))
+ }
+ }
+}
diff --git a/Tests/Unit/ReporterImporterTests.swift b/Tests/Unit/ReporterImporterTests.swift
@@ -126,8 +126,8 @@ struct ReporterImporterTests {
@Test("Importing archives the default questions, so the surveys ask Reporter's")
func defaultsArchived() async throws {
let now = Date(timeIntervalSince1970: 0)
- try await ReportStore(persistence: persistence).seedDefaultQuestionsIfNeeded(now: now)
- let defaults = DefaultQuestions.make(now: now).count
+ try await ReportStore(persistence: persistence).seedDefaultQuestionsIfNeeded()
+ let defaults = DefaultQuestions.make().count
let summary = try await importer.importArchive(try Fixtures.reporterExport(), now: now)
#expect(summary.defaultQuestionsArchived == defaults)