commit 87e87e5f6d854c9efe58e67908f05a189f41aa0c
parent f71c611e7c9bcae9ced80ea8bb8bee95c2ae77e7
Author: Michael Camilleri <[email protected]>
Date: Sat, 17 Oct 2026 06:04:10 +0900
Support instant reports
Nothing in the app could make a passive report, and one made elsewhere
could not be filled in, so recording a moment always meant answering
the whole survey.
This commit adds a quick log button that records the moment with its
context and no answers. The report is saved at once, so it appears in
the timeline straight away, and its context is added when the capture
finishes. The logging lives in Shared, ready for the notification action
and the Watch.
Instant reports sit in the timeline like any other report, since some
users will want to keep them as they are. Tapping one opens the survey
as of its original time and zone, with the location it was logged with,
and saving writes only the answers and its completion, so a capture
still under way is not overwritten. Cancelling discards the answers but
keeps the report.
The app badge counts instant reports. It shows only once the user
allows notifications, which Phase 3 asks for along with prompts.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 18 | ++++++++++++++---- |
| M | Reportage.xcodeproj/project.pbxproj | | | 8 | ++++++++ |
| A | Reportage/Services/AppBadge.swift | | | 12 | ++++++++++++ |
| M | Reportage/Views/Home/HomeView.swift | | | 119 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------ |
| M | Reportage/Views/Survey/SurveyModel.swift | | | 58 | +++++++++++++++++++++++++++++++++++++++++++++++++++------- |
| M | Reportage/Views/Survey/SurveyView.swift | | | 57 | +++++++++++++++++++++++++++++++++++++++++++++------------ |
| A | Shared/Capture/PassiveLog.swift | | | 37 | +++++++++++++++++++++++++++++++++++++ |
| M | Shared/Persistence/ReportStore.swift | | | 62 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/ReportStoreTests.swift | | | 65 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/SurveyModelTests.swift | | | 51 | +++++++++++++++++++++++++++++++++++++++++++++++++++ |
10 files changed, 446 insertions(+), 41 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -507,9 +507,19 @@ passive reports logged from a notification get no location. The app asks for
## Passive Reports and the Watch
A passive report records "this moment" with its context and nothing else. It
-appears in the iPhone app's **Unfinished** list (and as the badge count) until
-it's filled in. Filling it in answers the survey as of the report's original
-`date`.
+appears in the timeline like any other report, labelled 'Instant', rather than
+in a list of unfinished reports: some users will want to keep such reports as
+they are, and shouldn't feel pressed to fill them in. Tapping one fills it in,
+answering the survey as of the report's original `date` with the context it
+was logged with. Only the answers and its completion are saved, so a context
+capture still under way isn't overwritten.
+
+A passive report is saved as soon as it's logged, so it's in the timeline at
+once, and its context is added when the capture finishes (`PassiveLog`). The
+home screen's quick log button, a bolt beside the +, makes one without
+opening the survey. The badge counts passive reports; it shows only
+once notifications are allowed, which Phase 3 asks for, and could become a
+setting.
There's one App Intent, `LogPassiveReportIntent`, in `Shared/`. It drives every
quick-log surface:
@@ -747,7 +757,7 @@ default); when included, each is the original JSON text as a string.
tests, JSON export. This proves the model against real data before any UI
depends on it.
2. **Logging on iPhone.** Survey UI for every question type, wake, bedtime and
- manual reports, written entries, the Unfinished list, and live context
+ manual reports, written entries, passive reports, and live context
capture (location, device, safe ambient noise).
3. **Prompts.** Scheduler, notification actions, background refresh.
4. **Sync.** `CKSyncEngine`, both zones, first upload of the archive.
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -28,6 +28,7 @@
6F06CC539C4D17B343A9321C /* LegacyBlob.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */; };
770B4C77FABB2A7A0B2C5E3A /* EntryDraft.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14AD1548EA722CF1E19BCE42 /* EntryDraft.swift */; };
7ACDA81EC3D7811F891CA029 /* ReportSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BBAB5AD6266B8F6E3507AE3 /* ReportSummary.swift */; };
+ 81B485BD03549DE6E7AA94A7 /* AppBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */; };
83E954F0DAC9719D2AA02111 /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C7E4E96538BB14AD6956CA /* HomeView.swift */; };
85A36A88AB170F0EAC0DAC03 /* QuestionPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24A77AE6DE479403D1D4C9CF /* QuestionPage.swift */; };
89AC740ACEABE2AE5453E683 /* SurveyModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 844ABAD88442C143BA239374 /* SurveyModel.swift */; };
@@ -46,6 +47,7 @@
C8E02DEA2119E61D31667FFE /* ReporterImportPlanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */; };
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */; };
D0497C9835A2502936591DC1 /* DisplayRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E609FFCB918B4EF9BFCC018 /* DisplayRule.swift */; };
+ D1F2257DDB68439AF352B57D /* PassiveLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46FB42E5DB43201A13D6D141 /* PassiveLog.swift */; };
D3C3046B927DB98443E005C8 /* PlaceDirectory.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBBE80E95676BAEB53CE80E0 /* PlaceDirectory.swift */; };
D3FF67FB406DCCB78DF9D61A /* ReportSummaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */; };
D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F3237323A968FA629020DA9 /* ContextCapture.swift */; };
@@ -86,6 +88,7 @@
383FF2C73A8FBAA2AB13D653 /* ReportageApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageApp.swift; sourceTree = "<group>"; };
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RealExportVerificationTests.swift; sourceTree = "<group>"; };
3ED0CAE575381DCB86FB8EE9 /* ReporterImportVerifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportVerifier.swift; sourceTree = "<group>"; };
+ 46FB42E5DB43201A13D6D141 /* PassiveLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PassiveLog.swift; sourceTree = "<group>"; };
487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchiveTests.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>"; };
@@ -103,6 +106,7 @@
76FFC5FE874467974DD6BFA0 /* PlaceRanking.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaceRanking.swift; sourceTree = "<group>"; };
798E1DE82BD53EC5BEBA76B7 /* ReporterImportPlan.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportPlan.swift; sourceTree = "<group>"; };
7ABE75DB46245AFDE8A44A48 /* Config.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = "<group>"; };
+ 7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppBadge.swift; sourceTree = "<group>"; };
7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExportTests.swift; sourceTree = "<group>"; };
7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportPlanTests.swift; sourceTree = "<group>"; };
844ABAD88442C143BA239374 /* SurveyModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModel.swift; sourceTree = "<group>"; };
@@ -191,6 +195,7 @@
isa = PBXGroup;
children = (
9F3237323A968FA629020DA9 /* ContextCapture.swift */,
+ 46FB42E5DB43201A13D6D141 /* PassiveLog.swift */,
);
path = Capture;
sourceTree = "<group>";
@@ -217,6 +222,7 @@
60B58F5030E4A690025C51F5 /* Services */ = {
isa = PBXGroup;
children = (
+ 7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */,
AD85758A0521ED681067B90F /* Export */,
96D6D46E008E39350B203328 /* Narrative */,
580063E6A7AE05D5C6C16830 /* Places */,
@@ -456,6 +462,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ 81B485BD03549DE6E7AA94A7 /* AppBadge.swift in Sources */,
DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */,
@@ -468,6 +475,7 @@
3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */,
6F06CC539C4D17B343A9321C /* LegacyBlob.swift in Sources */,
F6F2DD23C77A981D76BE0480 /* NarrativePolisher.swift in Sources */,
+ D1F2257DDB68439AF352B57D /* PassiveLog.swift in Sources */,
C5D94FEC4507054E6497E85B /* PersistenceController.swift in Sources */,
2EE68329C383FA1C5295ACA9 /* PlaceAnswerView.swift in Sources */,
D3C3046B927DB98443E005C8 /* PlaceDirectory.swift in Sources */,
diff --git a/Reportage/Services/AppBadge.swift b/Reportage/Services/AppBadge.swift
@@ -0,0 +1,12 @@
+import UserNotifications
+
+/// The app icon's badge: the number of reports logged for later.
+enum AppBadge {
+ /// Sets the badge from the store. The badge only shows once the user
+ /// has allowed notifications, which Phase 3 asks for along with prompts;
+ /// until then this does nothing visible.
+ static func update(from store: ReportStore?) async {
+ guard let store, let count = try? await store.passiveCount() else { return }
+ try? await UNUserNotificationCenter.current().setBadgeCount(count)
+ }
+}
diff --git a/Reportage/Views/Home/HomeView.swift b/Reportage/Views/Home/HomeView.swift
@@ -1,4 +1,5 @@
import CoreData
+import OSLog
import SwiftUI
/// The app's main screen: reports by day, newest first, and the button that
@@ -8,21 +9,46 @@ struct HomeView: View {
@State private var survey: SurveyRequest?
@State private var describer = ReportDescriber()
+ private let logger = Logger(subsystem: "net.inqk.reportage", category: "Home")
+
var body: some View {
NavigationStack {
- ReportList(describer: describer) { kind in
- survey = SurveyRequest(kind: kind)
- }
+ ReportList(
+ describer: describer,
+ onStart: { kind in survey = SurveyRequest(kind: kind) },
+ onQuickLog: quickLog,
+ onFillIn: { id, kind in survey = .fillIn(id, kind: kind) }
+ )
.toolbar(.hidden, for: .navigationBar)
}
.sheet(item: $survey, onDismiss: reload) { request in
SurveySheet(request: request)
}
- .task { await describer.load(from: store) }
+ .task {
+ await describer.load(from: store)
+ await AppBadge.update(from: store)
+ }
}
private func reload() {
- Task { await describer.load(from: store) }
+ Task {
+ await describer.load(from: store)
+ await AppBadge.update(from: store)
+ }
+ }
+
+ /// Logs this moment with its context and no answers. It goes straight
+ /// into the timeline, where it can be filled in or left as it is.
+ private func quickLog() {
+ guard let store else { return }
+ Task {
+ do {
+ try await PassiveLog(store: store).log(trigger: .app)
+ } catch {
+ logger.error("Couldn't make a quick log: \(error)")
+ }
+ await AppBadge.update(from: store)
+ }
}
}
@@ -68,6 +94,9 @@ extension ReportEntity {
struct ReportList: View {
let describer: ReportDescriber
let onStart: (ReportKind) -> Void
+ let onQuickLog: () -> Void
+ /// Opens the survey for a report logged for later.
+ let onFillIn: (UUID, ReportKind) -> Void
@SectionedFetchRequest(fetchRequest: ReportList.request, sectionIdentifier: \ReportEntity.dayKey)
private var days: SectionedFetchResults<String, ReportEntity>
@@ -82,7 +111,7 @@ struct ReportList: View {
var body: some View {
List {
- HomeHeader(onStart: onStart)
+ HomeHeader(onStart: onStart, onQuickLog: onQuickLog)
.listRowInsets(EdgeInsets(top: 8, leading: 24, bottom: 20, trailing: 24))
.listRowBackground(Theme.paper)
.listRowSeparatorTint(Theme.ink)
@@ -96,7 +125,7 @@ struct ReportList: View {
ForEach(days) { day in
Section {
ForEach(day) { report in
- ReportRow(report: report, describer: describer)
+ row(for: report)
.listRowInsets(EdgeInsets(top: 18, leading: 24, bottom: 18, trailing: 24))
.listRowBackground(Theme.paper)
.listRowSeparatorTint(Theme.rule)
@@ -110,10 +139,28 @@ struct ReportList: View {
.scrollContentBackground(.hidden)
.background(Theme.paper)
}
+
+ /// A report logged for later can be tapped to fill it in.
+ @ViewBuilder
+ private func row(for report: ReportEntity) -> some View {
+ if report.state == ReportState.passive.rawValue, let id = report.id {
+ Button {
+ onFillIn(id, report.kind.flatMap(ReportKind.init) ?? .manual)
+ } label: {
+ ReportRow(report: report, describer: describer)
+ .contentShape(.rect)
+ }
+ .buttonStyle(.plain)
+ .accessibilityHint(Text("Answers the survey for this moment"))
+ } else {
+ ReportRow(report: report, describer: describer)
+ }
+ }
}
struct HomeHeader: View {
let onStart: (ReportKind) -> Void
+ let onQuickLog: () -> Void
var body: some View {
HStack(alignment: .center) {
@@ -122,11 +169,41 @@ struct HomeHeader: View {
.foregroundStyle(Theme.ink)
.accessibilityAddTraits(.isHeader)
Spacer()
- NewReportMenu(onStart: onStart)
+ HStack(spacing: 12) {
+ QuickLogButton(action: onQuickLog)
+ NewReportMenu(onStart: onStart)
+ }
}
}
}
+/// Logs the moment without a survey: a bolt, ink-outlined beside the filled
+/// + so the two read as a pair. Nothing opens, so a tap is confirmed
+/// with a haptic as the report slides into the timeline.
+struct QuickLogButton: View {
+ let action: () -> Void
+
+ @State private var taps = 0
+
+ var body: some View {
+ Button {
+ taps += 1
+ action()
+ } label: {
+ Image(systemName: "bolt.fill")
+ .font(.title3.weight(.semibold))
+ .foregroundStyle(Theme.ink)
+ .frame(width: 44, height: 44)
+ .overlay(Circle().strokeBorder(Theme.ink, lineWidth: 1.5))
+ .contentShape(.circle)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text("Quick Log"))
+ .accessibilityHint(Text("Logs this moment without a survey"))
+ .sensoryFeedback(.success, trigger: taps)
+ }
+}
+
struct NewReportMenu: View {
let onStart: (ReportKind) -> Void
@@ -204,15 +281,13 @@ struct ReportRow: View {
ReportTime(date: report.date, timeZone: report.timeZone)
.frame(width: 60, alignment: .leading)
VStack(alignment: .leading, spacing: 6) {
- ReportKindLabel(
- kind: kind,
- isUnfinished: report.state == ReportState.passive.rawValue
- )
+ ReportKindLabel(kind: kind, isLogged: isLogged)
ReportSummaryText(
entry: entry(for: summary.draft),
isWriting: isWriting,
details: summary.details,
- context: summary.context
+ context: summary.context,
+ isLogged: isLogged
)
}
}
@@ -221,6 +296,9 @@ struct ReportRow: View {
}
}
+ /// Whether the report was logged for later and has no answers yet.
+ private var isLogged: Bool { report.state == ReportState.passive.rawValue }
+
/// The stored narrative if it was made from the current draft, otherwise
/// the draft itself. A narrative from an older polishing pass is still
/// shown until it's rewritten.
@@ -298,12 +376,15 @@ struct ReportTime: View {
struct ReportKindLabel: View {
let kind: ReportKind?
- let isUnfinished: Bool
+ /// A report logged without answers is labelled as an instant rather than
+ /// as unfinished: leaving it as it is is fine.
+ let isLogged: Bool
var body: some View {
- if isUnfinished {
- Text("Unfinished", comment: "Label for a report that's been logged but not answered")
- .eyebrow(Theme.accent)
+ if isLogged {
+ Text("Instant", comment: "Label for a report logged without answers, such as a quick log")
+ .eyebrow()
+ .italic()
} else {
Text((kind ?? .manual).shortTitle)
.eyebrow(kind == .wake || kind == .bedtime ? Theme.accent : Theme.muted)
@@ -332,6 +413,8 @@ struct ReportSummaryText: View {
let isWriting: Bool
let details: [AnswerDetail]
let context: String?
+ /// A report logged for later has no answers, and doesn't say so.
+ let isLogged: Bool
/// Answers shown beneath the entry before the rest are counted.
private static let detailLimit = 2
@@ -349,7 +432,7 @@ struct ReportSummaryText: View {
WritingIndicator()
}
}
- } else if details.isEmpty {
+ } else if details.isEmpty, !isLogged {
Text("No answers", comment: "Shown for a report whose questions were all skipped")
.font(Theme.serif(.body).italic())
.foregroundStyle(Theme.muted)
diff --git a/Reportage/Views/Survey/SurveyModel.swift b/Reportage/Views/Survey/SurveyModel.swift
@@ -7,10 +7,14 @@ import Observation
@Observable
final class SurveyModel {
let kind: ReportKind
- /// The moment the report describes: when the survey was started.
+ /// The moment the report describes: when the survey was started, or
+ /// when the report being filled in was logged.
let date: Date
let timeZone: String
let questions: [Question]
+ /// The report logged for later that this survey fills in, if any. Its
+ /// context was captured when it was logged, so none is captured now.
+ let existing: Report?
/// Pickers for `tokens` and `people` questions, and for `location`
/// questions, by question ID. They're created once so each page keeps its
/// search and selection.
@@ -22,17 +26,47 @@ final class SurveyModel {
/// Live context, captured from when the survey opens.
private var contextTask: Task<Context, Never>?
- init(
+ convenience init(
kind: ReportKind,
date: Date,
timeZone: TimeZone = .current,
questions: [Question],
vocabulary: [String: [VocabularyEntry]],
directory: any PlaceDirectory = MapKitPlaceDirectory()
+ ) {
+ self.init(
+ kind: kind, date: date, timeZone: timeZone.identifier, existing: nil,
+ questions: questions, vocabulary: vocabulary, directory: directory)
+ }
+
+ /// A survey that fills in `report`, as of the moment it was logged.
+ convenience init(
+ fillingIn report: Report,
+ questions: [Question],
+ vocabulary: [String: [VocabularyEntry]],
+ directory: any PlaceDirectory = MapKitPlaceDirectory()
+ ) {
+ self.init(
+ kind: report.kind, date: report.date, timeZone: report.timeZone, existing: report,
+ questions: questions, vocabulary: vocabulary, directory: directory)
+ for picker in placePickers.values {
+ picker.setLocation(report.context.location)
+ }
+ }
+
+ private init(
+ kind: ReportKind,
+ date: Date,
+ timeZone: String,
+ existing: Report?,
+ questions: [Question],
+ vocabulary: [String: [VocabularyEntry]],
+ directory: any PlaceDirectory
) {
self.kind = kind
self.date = date
- self.timeZone = timeZone.identifier
+ self.timeZone = timeZone
+ self.existing = existing
self.questions = questions
var pickers: [String: TokenPicker] = [:]
var placePickers: [String: PlacePicker] = [:]
@@ -159,7 +193,7 @@ final class SurveyModel {
/// opens, so the context describes the moment the report is about. Place
/// pickers get the location as soon as there's a fix.
func startCapture(_ capture: ContextCapture = ContextCapture()) {
- guard contextTask == nil else { return }
+ guard contextTask == nil, existing == nil else { return }
let placePickers = Array(placePickers.values)
contextTask = Task {
let context = await capture.capture { location in
@@ -173,16 +207,19 @@ final class SurveyModel {
}
/// The captured context, waiting for the capture if it's still running.
- /// It finishes within its budget of the survey opening.
+ /// It finishes within its budget of the survey opening. A report being
+ /// filled in keeps the context it was logged with.
func capturedContext() async -> Context {
- await contextTask?.value ?? Context()
+ if let existing { return existing.context }
+ return await contextTask?.value ?? Context()
}
// MARK: Saving
/// The finished report, with a response for every question in the
/// survey (skipped questions have no value), and the tokens created
- /// while answering that the report uses.
+ /// while answering that the report uses. A report being filled in keeps
+ /// its ID, trigger and context, and gains the answers.
func makeReport(
id: UUID = UUID(),
now: Date,
@@ -202,6 +239,13 @@ final class SurveyModel {
pickers[question.id]?.usedNewTokens(now: now)
?? placePickers[question.id]?.usedNewTokens(now: now) ?? []
}
+ if var report = existing {
+ report.state = .complete
+ report.completedAt = now
+ report.responses = responses
+ report.modifiedAt = now
+ return (report, newTokens)
+ }
let report = Report(
id: id,
date: date,
diff --git a/Reportage/Views/Survey/SurveyView.swift b/Reportage/Views/Survey/SurveyView.swift
@@ -1,10 +1,18 @@
import SwiftUI
-/// What to survey: a report of `kind` describing `date`.
+/// What to survey: a new report of `kind` describing `date`, or answers for
+/// a report that was logged for later.
struct SurveyRequest: Identifiable {
let id = UUID()
var kind: ReportKind
var date = Date()
+ /// The report logged for later to fill in.
+ var reportID: UUID?
+
+ /// Fills in the report logged for later with `id`.
+ static func fillIn(_ id: UUID, kind: ReportKind) -> SurveyRequest {
+ SurveyRequest(kind: kind, reportID: id)
+ }
}
/// Loads the questions and suggestions for a survey, then presents it.
@@ -37,18 +45,31 @@ struct SurveySheet: View {
private func load() async {
guard model == nil, let store else { return }
do {
- let questions = try await store.surveyQuestions(for: request.kind)
+ var existing: Report?
+ if let id = request.reportID {
+ guard let report = try await store.report(id: id) else {
+ loadError = String(localized: "This report no longer exists.")
+ return
+ }
+ existing = report
+ }
+ let questions = try await store.surveyQuestions(for: existing?.kind ?? request.kind)
let tokenQuestions = questions.filter {
[QuestionKind.tokens, .people, .location].contains($0.kind)
}
let vocabulary = try await store.vocabulary(for: tokenQuestions.map(\.id))
- let model = SurveyModel(
- kind: request.kind,
- date: request.date,
- questions: questions,
- vocabulary: vocabulary
- )
- model.startCapture()
+ let model: SurveyModel
+ if let existing {
+ model = SurveyModel(fillingIn: existing, questions: questions, vocabulary: vocabulary)
+ } else {
+ model = SurveyModel(
+ kind: request.kind,
+ date: request.date,
+ questions: questions,
+ vocabulary: vocabulary
+ )
+ model.startCapture()
+ }
self.model = model
} catch {
loadError = error.localizedDescription
@@ -85,11 +106,19 @@ struct SurveyView: View {
onCancel: cancel
)
.confirmationDialog(
- "Discard this report?",
+ model.existing == nil ? "Discard this report?" : "Discard these answers?",
isPresented: $isConfirmingCancel,
titleVisibility: .visible
) {
- Button("Discard Report", role: .destructive) { dismiss() }
+ if model.existing == nil {
+ Button("Discard Report", role: .destructive) { dismiss() }
+ } else {
+ Button("Discard Answers", role: .destructive) { dismiss() }
+ }
+ } message: {
+ if model.existing != nil {
+ Text("The report stays logged, and can be filled in later.")
+ }
}
}
.safeAreaInset(edge: .bottom) {
@@ -145,7 +174,11 @@ struct SurveyView: View {
let context = await model.capturedContext()
let (report, newTokens) = model.makeReport(now: Date(), context: context)
do {
- try await store.insert(report, newTokens: newTokens)
+ if model.existing == nil {
+ try await store.insert(report, newTokens: newTokens)
+ } else {
+ try await store.fillIn(report, newTokens: newTokens)
+ }
dismiss()
} catch {
saveError = error.localizedDescription
diff --git a/Shared/Capture/PassiveLog.swift b/Shared/Capture/PassiveLog.swift
@@ -0,0 +1,37 @@
+import Foundation
+
+/// Logs the moment: a report with its context and no answers, from a quick
+/// log or Log for Later. It appears in the timeline straight away and can be
+/// filled in at any time, or left as it is.
+struct PassiveLog: Sendable {
+ let store: ReportStore
+ var capture: @Sendable () async -> Context = { await ContextCapture().capture() }
+
+ /// Saves the report at once, so it's in the timeline while its context
+ /// is captured, then adds the context. Returns the report's ID.
+ @discardableResult
+ func log(
+ kind: ReportKind = .manual,
+ trigger: ReportTrigger,
+ date: Date = Date(),
+ timeZone: TimeZone = .current,
+ promptedAt: Date? = nil
+ ) async throws -> UUID {
+ let report = Report(
+ id: UUID(),
+ date: date,
+ timeZone: timeZone.identifier,
+ kind: kind,
+ trigger: trigger,
+ state: .passive,
+ promptedAt: promptedAt,
+ modifiedAt: date
+ )
+ try await store.insert(report)
+ let context = await capture()
+ if context != Context() {
+ try await store.setContext(context, for: report.id)
+ }
+ return report.id
+ }
+}
diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift
@@ -49,6 +49,64 @@ struct ReportStore: Sendable {
}
}
+ func report(id: UUID) async throws -> Report? {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ try Self.entity(id: id, in: context)?.report()
+ }
+ }
+
+ /// How many reports are logged and waiting for answers.
+ func passiveCount() async throws -> Int {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let request = ReportEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "state == %@", ReportState.passive.rawValue)
+ return try context.count(for: request)
+ }
+ }
+
+ /// Sets the context of a report saved before its capture finished.
+ func setContext(_ captured: Context, for id: UUID, now: Date = Date()) async throws {
+ let context = persistence.newBackgroundContext()
+ try await context.perform {
+ guard let entity = try Self.entity(id: id, in: context) else { return }
+ entity.context = try ModelCoding.encode(captured)
+ entity.modifiedAt = now
+ try context.save()
+ }
+ }
+
+ /// Saves the answers to a report that was logged for later, together
+ /// with the tokens created while answering. Only the answers and what
+ /// marks the report complete are taken from `report`, so a context
+ /// captured meanwhile isn't overwritten.
+ func fillIn(_ report: Report, newTokens: [Token] = []) async throws {
+ let context = persistence.newBackgroundContext()
+ try await context.perform {
+ guard let entity = try Self.entity(id: report.id, in: context) else {
+ throw ReportStoreError.missingReport(report.id)
+ }
+ var stored = try entity.report()
+ stored.responses = report.responses
+ stored.state = report.state
+ stored.completedAt = report.completedAt
+ stored.modifiedAt = report.modifiedAt
+ for token in newTokens {
+ try TokenEntity(context: context).update(from: token)
+ }
+ try entity.update(from: stored)
+ try context.save()
+ }
+ }
+
+ private static func entity(id: UUID, in context: NSManagedObjectContext) throws -> ReportEntity? {
+ let request = ReportEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
+ request.fetchLimit = 1
+ return try context.fetch(request).first
+ }
+
/// Saves a new report together with the tokens created while answering
/// it, in one transaction.
func insert(_ report: Report, newTokens: [Token] = []) async throws {
@@ -62,3 +120,7 @@ struct ReportStore: Sendable {
}
}
}
+
+enum ReportStoreError: Error {
+ case missingReport(UUID)
+}
diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift
@@ -179,6 +179,71 @@ struct ReportStoreTests {
#expect(try await store.vocabulary(for: ["L"])["L"]?.first?.locality == nil)
}
+ @Test("A report logged for later appears at once, then gains its context")
+ func passiveLog() async throws {
+ var captured = Context()
+ captured.device = DeviceContext(batteryLevel: 0.5)
+ let store = self.store
+ let gate = AsyncStream<Void>.makeStream()
+ let log = PassiveLog(store: store) { [captured] in
+ for await _ in gate.stream { break }
+ return captured
+ }
+ let logging = Task {
+ try await log.log(trigger: .app, date: Date(timeIntervalSince1970: 10), promptedAt: nil)
+ }
+
+ // Before the capture finishes, the report is already saved.
+ var count = 0
+ for _ in 0..<100 where count == 0 {
+ count = try await store.passiveCount()
+ if count == 0 { try await Task.sleep(for: .milliseconds(10)) }
+ }
+ #expect(count == 1)
+
+ gate.continuation.yield()
+ let id = try await logging.value
+ let report = try #require(try await store.report(id: id))
+ #expect(report.state == .passive)
+ #expect(report.trigger == .app)
+ #expect(report.kind == .manual)
+ #expect(report.date == Date(timeIntervalSince1970: 10))
+ #expect(report.responses.isEmpty)
+ #expect(report.context == captured)
+ }
+
+ @Test("Filling in a report saves its answers and keeps its context")
+ func fillIn() async throws {
+ var logged = Self.report(1, responses: [])
+ logged.state = .passive
+ try await store.insert(logged)
+ #expect(try await store.passiveCount() == 1)
+
+ // The survey was opened before the context arrived.
+ let answered = Report(
+ id: logged.id, date: logged.date, timeZone: logged.timeZone, kind: logged.kind,
+ trigger: .watch, state: .complete, completedAt: Date(timeIntervalSince1970: 99),
+ responses: [Response(questionID: "Q", prompt: "P", value: .tokens(["N"]))],
+ modifiedAt: Date(timeIntervalSince1970: 99))
+ var captured = Context()
+ captured.device = DeviceContext(connectivity: .wifi)
+ try await store.setContext(captured, for: logged.id)
+ try await store.fillIn(answered, newTokens: [Self.token("N", "New")])
+
+ let report = try #require(try await store.report(id: logged.id))
+ #expect(report.state == .complete)
+ #expect(report.completedAt == Date(timeIntervalSince1970: 99))
+ #expect(report.responses == answered.responses)
+ #expect(report.context == captured)
+ #expect(report.trigger == logged.trigger)
+ #expect(try await store.passiveCount() == 0)
+ #expect(try await store.vocabulary(for: ["Q"])["Q"]?.map(\.id) == ["N"])
+
+ await #expect(throws: ReportStoreError.self) {
+ try await store.fillIn(Self.report(2, responses: []))
+ }
+ }
+
@Test("A report and its new tokens are saved together")
func insert() async throws {
let token = Self.token("N", "New")
diff --git a/Tests/Unit/SurveyModelTests.swift b/Tests/Unit/SurveyModelTests.swift
@@ -146,6 +146,57 @@ struct SurveyModelTests {
#expect(newTokens.first?.modifiedAt == Date(timeIntervalSince1970: 5))
}
+ @Test("Filling in a logged report keeps its moment, trigger and context")
+ func fillIn() throws {
+ var context = Context()
+ context.location = LocationContext(
+ coordinate: Coordinate(latitude: 1.5, longitude: 2.5), horizontalAccuracy: 20)
+ let logged = Report(
+ id: Fixtures.reportID(7),
+ date: Date(timeIntervalSince1970: 50),
+ timeZone: "Australia/Sydney",
+ kind: .random,
+ trigger: .notification,
+ state: .passive,
+ promptedAt: Date(timeIntervalSince1970: 40),
+ context: context,
+ modifiedAt: Date(timeIntervalSince1970: 50)
+ )
+ let model = SurveyModel(
+ fillingIn: logged, questions: Self.questions,
+ vocabulary: [
+ "place": [
+ VocabularyEntry(
+ id: "P1", text: "Home", useCount: 1,
+ coordinate: Coordinate(latitude: 1.5, longitude: 2.5))
+ ]
+ ])
+ #expect(model.date == logged.date)
+ #expect(model.timeZone == "Australia/Sydney")
+ #expect(model.kind == .random)
+ // The place picker uses the logged location, and nothing is captured.
+ let places = try #require(model.placePickers["place"])
+ #expect(places.location == context.location)
+ model.startCapture()
+
+ places.toggle(try #require(places.candidate(id: "P1")))
+ model[optionFor: "yes"] = ResponseValue.yesOption
+ let report = model.makeReport(now: Date(timeIntervalSince1970: 300), context: context).report
+
+ #expect(report.id == logged.id)
+ #expect(report.trigger == .notification)
+ #expect(report.promptedAt == logged.promptedAt)
+ #expect(report.date == logged.date)
+ #expect(report.context == context)
+ #expect(report.state == .complete)
+ #expect(report.completedAt == Date(timeIntervalSince1970: 300))
+ #expect(report.modifiedAt == Date(timeIntervalSince1970: 300))
+ #expect(report.responses.first?.value == .options(["Yes"]))
+ #expect(
+ report.responses[3].value
+ == .place(PlaceAnswer(tokenID: "P1", coordinate: context.location?.coordinate, accuracy: 20)))
+ }
+
@Test("New place tokens carry place details")
func newPlace() throws {
let model = makeModel()