Jul 27 - Update for scheduled task instruction

This commit is contained in:
Nguyen Ngo
2026-07-27 12:57:13 -04:00
parent 5999871f77
commit ad91a92ff1
10 changed files with 424 additions and 28 deletions
@@ -40,6 +40,14 @@ struct ExecuteInspectionView: View {
@State private var isSubmitting = false
@State private var submitResult: SubmitResult?
// Schedule instructions
// Snapshotted into @State in onAppear rather than read from SwiftData on
// every body pass: resolveAndFulfillSchedule() DELETES the cached
// LocalScheduledInspection row at submit time, while this view is still on
// screen showing the success banner. Reading a deleted PersistentModel traps.
@State private var scheduleInstructions: String? = nil
@State private var instructionsExpanded = true
// Location manager created on view init. requestLocation() is called in
// onAppear so the permission prompt (and GPS fix acquisition) starts as
// soon as the inspector opens the inspection, maximising the chance of
@@ -158,6 +166,7 @@ struct ExecuteInspectionView: View {
}
.onAppear {
formValues = inspection.formData.compactMapValues { "\($0)" }
loadScheduleInstructions()
// Request Location permission (and start acquiring a fix) the moment
// the inspector opens the inspection gives GPS the entire duration
// of the inspection to get a fix, rather than only the few seconds
@@ -260,6 +269,15 @@ struct ExecuteInspectionView: View {
headerCard
.padding(.bottom, 16)
// Instructions from the schedule this inspection fulfils. Sits directly
// above the form so the inspector can re-read it mid-inspection without
// leaving the screen. Collapsible because long instructions would
// otherwise push the first form field below the fold.
if let instructions = scheduleInstructions {
instructionsBanner(instructions)
.padding(.bottom, 16)
}
// CHANGED: grid-based form rendering (replaces card-grouped linear list)
if formSchema.isEmpty {
emptyFormPlaceholder
@@ -297,6 +315,60 @@ struct ExecuteInspectionView: View {
.clipShape(RoundedRectangle(cornerRadius: 10))
}
// Instructions Banner
/// Manager-authored instructions for the schedule this inspection fulfils.
/// Wire/DB field is `notes`; "Instructions" is the user-facing wording.
private func instructionsBanner(_ text: String) -> some View {
VStack(alignment: .leading, spacing: 8) {
Button {
withAnimation(.easeInOut(duration: 0.2)) {
instructionsExpanded.toggle()
}
} label: {
HStack(spacing: 8) {
Image(systemName: "info.circle.fill")
.foregroundStyle(.blue)
Text("Instructions")
.font(.callout.bold())
.foregroundStyle(.blue)
Spacer()
Image(systemName: instructionsExpanded ? "chevron.up" : "chevron.down")
.font(.caption.bold())
.foregroundStyle(.blue)
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
if instructionsExpanded {
Text(text)
.font(.callout)
.foregroundStyle(.primary)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.blue.opacity(0.10))
.clipShape(RoundedRectangle(cornerRadius: 10))
}
/// Copy the schedule's instructions into `@State` once, at appear.
///
/// Deliberately a snapshot, not a computed lookup: the cached
/// `LocalScheduledInspection` is deleted by `resolveAndFulfillSchedule()`
/// the instant Submit is tapped, and this view stays on screen for another
/// 2.5 s afterwards. A computed property would re-read a deleted
/// `PersistentModel` during that window and trap.
private func loadScheduleInstructions() {
guard let schedId = inspection.scheduledInspectionServerId else { return }
// Fetch-all then filter in Swift no #Predicate (CLAUDE.md rule 3).
let all = (try? context.fetch(FetchDescriptor<LocalScheduledInspection>())) ?? []
scheduleInstructions = all.first(where: { $0.serverId == schedId })?.instructions
}
// Header Card
private var headerCard: some View {
@@ -576,6 +648,15 @@ struct ExecuteInspectionView: View {
// regardless of connectivity or sync timing.
clearParentFollowUpFlag()
// Fulfil the originating scheduled inspection
// Two jobs, both mirroring the web app's execute route:
// 1. Make sure the submission carries scheduled_inspection_id, even
// when the inspector reached this form via "+" instead of the
// Scheduled row the server cannot fulfil an unlinked inspection.
// 2. Drop the cached schedule row so the SCHEDULED card clears the
// moment Submit is tapped, online or offline.
resolveAndFulfillSchedule()
try? context.save()
isSubmitting = false
@@ -638,6 +719,84 @@ struct ExecuteInspectionView: View {
}
}
// Scheduled inspection fulfilment
/// Link this submission to the schedule it satisfies, then drop the cached
/// schedule row.
///
/// **Why the fallback link exists.** On the web, `scheduled_inspections.start`
/// is the *only* way to open a scheduled inspection, so the link is always
/// present. On the iPad the Scheduled row merely pre-selects facility +
/// template the inspector can reach the identical form through the "+"
/// button, and that path leaves `scheduledInspectionServerId` nil. The
/// server then stores `scheduled_inspection_id = NULL`, never calls
/// `_fulfill_schedule()`, and the schedule stays **Active** on the web.
/// Matching facility + template here restores parity of outcome between the
/// two entry points.
///
/// **Why the match is narrow.** Only schedules already due (due date on or
/// before today) are eligible, so an ad-hoc inspection today cannot silently
/// close out an occurrence planned for next month. Assignment must also fit:
/// unassigned schedules, or ones assigned to this inspector. When several
/// qualify, the earliest due date wins that is the occurrence being worked.
///
/// **Why the row is deleted rather than rolled forward.** `LocalScheduledInspection`
/// is a read-only cache and does not carry the phase43 recurrence detail
/// (weekdays / month_mode / day_of_month / nth_week / nth_weekday), so the
/// next due date cannot be computed correctly on device. Deleting invalidates
/// the cache instead: `pullScheduledInspections()` re-inserts recurring
/// schedules with the server-authoritative `next_due_date` on the next pull,
/// and a one-time schedule stays gone because the server has deactivated it.
/// The same pull also restores the row if the submission never lands, so a
/// failed sync self-heals.
private func resolveAndFulfillSchedule() {
// Fetch-all then filter in Swift no #Predicate (CLAUDE.md rule 3).
let all = (try? context.fetch(FetchDescriptor<LocalScheduledInspection>())) ?? []
guard !all.isEmpty else { return }
// Fallback link for inspections not started from a Scheduled row.
// Re-inspections are excluded: a follow-up shares its parent's facility
// and template, so it would otherwise close out an unrelated planned
// occurrence. The web app keeps the two workflows separate the same way.
let isReInspection = inspection.parentServerId != nil || inspection.parentLocalId != nil
if inspection.scheduledInspectionServerId == nil && !isReInspection {
let tid = inspection.templateServerId
let fid = inspection.facilityServerId
let uid = inspection.inspectorUserId
let today = Self.dueDateFormatter.string(from: Date())
let candidate = all
.filter {
$0.templateServerId == tid &&
$0.facilityServerId == fid &&
($0.inspectorId == nil || $0.inspectorId == uid) &&
!$0.dueDateString.isEmpty &&
$0.dueDateString <= today // ISO strings sort chronologically
}
.sorted { $0.dueDateString < $1.dueDateString }
.first
if let candidate {
inspection.scheduledInspectionServerId = candidate.serverId
}
}
// Clear the cached row for whichever schedule this submission fulfils.
guard let schedId = inspection.scheduledInspectionServerId,
let sched = all.first(where: { $0.serverId == schedId })
else { return }
context.delete(sched)
}
/// "yyyy-MM-dd", matching `LocalScheduledInspection.dueDateString`.
private static let dueDateFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = Locale(identifier: "en_US_POSIX")
f.dateFormat = "yyyy-MM-dd"
return f
}()
// Photo Handling
private func handlePhotoSelected(localPath: String, field: [String: Any]) {