Native SwiftUI redesign, restored recognition photos and optional prescription metadata with profile-scoped correction.
Native light/dark purpose surfaces, Today recording actions, searchable medications, grouped editors, routine progress and profile navigation retain existing care flows.
Optional civil prescription date, prescriber, one-supply duration and repeats left support explicit decrement and revision-guarded Undo without recording a dose.
The historical synthetic migration fixture preserves identifiers and opaque history bytes; live personal-store and CloudKit migration are not established.
Recognition photos are visible in medication rows and Today; detail, editor and dose logging bring existing images and draft controls forward. Storage/import/ownership rules remain unchanged.
Ready to push
Four source-review perspectives and follow-up review completed. Missing foreground snooze and recognition-photo surfaces were restored. The full native gate passed 201 phone domain, 14 Watch and all 16 phone UI scenarios. Actual photo-bearing screenshots were inspected in both appearances.
6a385ad docs: record photo restoration publication verification abf67e3 test: allow visible end-of-form dosage controls 3110683 docs: record focused photo restoration verification cc8bed7 test: wait for rebuilt medication library in photo journeys cf40672 fix: restore recognition photos in redesigned medication screens 3debb59 [test]: tap the leading native timing-menu label ce50b4c [test]: find timing cue across native accessibility roles 9c870d9 [test]: verify enabled follow-up through its conditional fields a88dada [test]: allow reachable follow-up controls near form end e22d53e [test]: target follow-up fields with bounded form navigation da53431 [test]: locate dose-limit fields without form overshoot 2ebd0f7 [fix]: restore foreground medication snooze before publication 27e03cf [doc]: record verified prescription details implementation 6f4fba4 [test]: target native timing menu by its visible label 1b59fee [fix]: invalidate stale repeat actions across medication archive cdd1d40 [test]: keep prescription UI helpers within lint limits 421b37f [test]: verify prescription editing and profile-safe repeat controls f9b28a1 [feat]: add profile-scoped prescription details and repeat correction 36cfcf2 [doc]: propose medication prescription details plan 1201a8d [doc]: record completed Meddy redesign verification cf21e68 [bug]: handle hidden native bars in redesign UI checks e10e654 [bug]: stabilize redesigned native UI selectors and scrolling 815a869 [feat]: implement native Meddy visual redesign Meddy’s screens use consistent native cards, colors and controls. You can save prescription information and lower the remaining repeats by one, then Undo a mistaken change.
Today highlights recorded care and available actions; prescription details stay with the selected person’s medication.
Optional means blank is unknown, while zero repeats means none recorded as remaining. A prescription date is a calendar day rather than an instant.
The restoration reuses the existing aspect-preserving view and bounded cache. Detail opens the same medication editor; Add/Replace/Remove remain unsaved until Save. The preview does not embed images in history, exports or Watch payloads.
Shared presentation tokens and extracted feature views drive the redesign. Medication gains four nullable entered fields plus a nullable revision token. The editor merges untouched fields with current values and rejects conflicting edits; export reuses existing Markdown escaping.
Repeat mutations reuse canonical profile/lifecycle validation and a single SwiftData save. Transient Undo receipts require the exact post-save revision and count. Archive/reactivate invalidates captured actions.
A current-details model avoids introducing prescription history or refill inference. Explicit known-value restoration handles reproduced SwiftData rollback behavior without broad persistence changes.
The restoration reuses the existing aspect-preserving view and bounded cache. Detail opens the same medication editor; Add/Replace/Remove remain unsaved until Save. The preview does not embed images in history, exports or Watch payloads.
The prescription day round-trips through Gregorian UTC YYYY-MM-DD; local today is converted only when the user explicitly enables the date. Captures retain canonical owner/lifecycle and revisions; stale receipts cannot overwrite later edits or another lifecycle. Failed saves roll back and restore realized count/revision values for a retry.
Presentation-only redesign retains shared domain rules. Five optional fields preserve missing-value compatibility; Watch DTOs and account/capability configuration remain unchanged.
Historical synthetic store upgrade/reopen is tested, while exact installed personal-store and live CloudKit acceptance are not. Existing background-publication/accessibility and baseline compiler warnings remain. Parameterized tests retain native declaration counts in converted JUnit.
The restoration reuses the existing aspect-preserving view and bounded cache. Detail opens the same medication editor; Add/Replace/Remove remain unsaved until Save. The preview does not embed images in history, exports or Watch payloads.
Meddy/Meddy/Design/MeddyStyle.swift
Why it matters. Consistent light/dark contrast and native accessibility scaling.
What to look at. MeddyStyle and PurposePalette
Meddy/Meddy/Features/TodayMedicationAction.swift
Why it matters. Quick actions retain existing transaction and profile checks.
What to look at. TodayMedicationAction.take
Meddy/Meddy/Features/PrescriptionFields.swift
Why it matters. Avoid stale editors overwriting newer recorded metadata.
What to look at. PrescriptionDraft.apply
Meddy/Meddy/Services/PrescriptionService.swift
Why it matters. A quick correction must not write to another owner/lifecycle or overwrite a later change.
What to look at. PrescriptionService.decrement, undo and change
Meddy/Meddy/Features/MedicationDetailView.swift
Why it matters. The redesign had removed the only in-app medication snooze action.
What to look at. Scheduled detail Remind me later callback
Meddy/Meddy/ContentView.swift
Why it matters. Owner recognition photos should remain visible after a presentation redesign.
What to look at. MedicationRow, Today cards, MedicationEditor and AdministrationEditor; MedicationDetailView header
Store YYYY-MM-DD and format with the same Gregorian UTC calendar so travel does not shift the recorded day.
Entered supply duration does not change schedules, stock, treatment course or safety status.
Undo restores only the current matching repeat mutation. A later editor change or archive invalidates old receipts.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Recognition-photo presentation | Redesign removed main medication-row and dose-log images and relegated detail/editor photos. Storage and import remained. | Restored images through existing MedicationPhotoView, moved editor controls near identity fields and added a detail editor shortcut. Preserved original combined VoiceOver care labels. Focused nine-domain/two-UI tests and full publication gate passed; 12 photo screenshots inspected. |
| minor | Photo UI navigation | New UI journey assumed immediate library selection during profile navigation rebuild and a Back control after retapping the active tab. | Native accessibility evidence guided waiting for actual medicationSearch arrival and removing redundant Back. All photo/profile assertions retained. Earlier failed run remains recorded separately. |
| minor | Dose-limit UI viewport | The existing helper required dose-limit fields in the upper half of a longer form, though native evidence showed them visible and hittable near the end. | Accept the reachable viewport while retaining top/bottom navigation clearance, hittability and every saved quantity/allowance/time/Taken/Undo assertion. The focused scenario and fresh full UI suite pass. |
| minor | Medication editor UI navigation | Page-sized and one-direction scrolling overshot newly enabled dose-limit and follow-up fields in the longer medication form. | Test-only bounded bidirectional form navigation retains dosage, allowance, timing, saved follow-up and Undo assertions. End-of-form controls use reachable viewport bounds; conditional fields verify enabled follow-up state after layout changes. The timing cue uses a role-independent lookup and a leading-label tap for the observed wide native button. Reviewed and focused-verified before final full UI gate. |
| major | Foreground reminder action | Redesign removed in-app Remind me later. | Restored the existing callback for active standalone scheduled medication with reminders enabled; synthetic foreground regression checks 900-second deferral and zero dose records. Quality/spec re-review clean. |
| minor | Prescription date formatting reuse | Civil-date formatting duplicates ScheduleCalendar.civilDate. | Deferred optional helper consolidation; current explicit Gregorian UTC implementation is correct. |
| minor | Timer presentation formatting | Small duplicate progress/fallback presentation helpers. | Deferred optional consolidation; running countdowns already reuse PhoneTimerControl. |
| minor | Today schedule calculation | Computed future occurrences can be regenerated inside filtering. | Deferred optimization at personal-app scale; no observed lag or correctness defect. |
| minor | Medication detail dose checks | Dose-limit check is eager and repeated for PRN. | Deferred presentation optimization; no behavior blocker. |
| minor | Medication row closure | Unused taken closure remains. | Deferred unrelated cleanup. |
| minor | Prescription timezone coverage | No dedicated timezone-boundary test beyond UTC civil-date round-trip. | Optional coverage improvement; code consistently uses Gregorian UTC and no defect demonstrated. |
Source: local run at 2026-10-09T02:07:42.454019+11:00 · snapshot abf67e3bcfaa2819ba1794736b0df7fd71d2c7bc
Baseline: none
Execution: passed · JUnit: 3 files · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 231 passed · 0 failed · 0 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 70f79a8a453c5e8cacf3d2f2a7ff18b729421ed5.
88 files: 83 code · 5 docs. Click to expand.
diff --git a/Meddy/Meddy/App/AppRootView.swift b/Meddy/Meddy/App/AppRootView.swiftindex 617dfc2..885550d 100644--- a/Meddy/Meddy/App/AppRootView.swift+++ b/Meddy/Meddy/App/AppRootView.swift@@ -18,17 +18,18 @@ struct AppRootView: View { _cloud = State(initialValue: CloudSyncMonitor(isolated: AppEnvironment.isTesting)) _roundAlerts = State(initialValue: PhoneRoundAlertService(context: container.mainContext)) }+ private var referenceAppearance: ColorScheme? {+ switch ProcessInfo.processInfo.environment["MEDDY_TEST_APPEARANCE"] {+ case "dark": .dark+ case "light": .light+ default: nil+ }+ } var body: some View { VStack(spacing: 0) {- ProfilePicker(selection: $selectedProfileID)- if !AppEnvironment.isTesting {- HStack {- Text(cloud.message).font(.caption).foregroundStyle(.secondary)- if cloud.needsAttention { Button("Retry") { cloud.refresh() }.font(.caption) }- }.padding(.horizontal)- } TimelineView(.everyMinute) { timeline in- ContentView().id(selectedProfileID).environment(\.careProfileID, selectedProfileID)+ ContentView(profileSelection: $selectedProfileID, cloud: cloud)+ .environment(\.careProfileID, selectedProfileID) .environment(\.logicalDayNow, timeline.date) .environment(\.snoozeMedication) { reminders?.snoozeMedication($0) } .onChange(of: ScheduleCalendar.localDate(timeline.date, calendar: .current)) { _, _ in@@ -37,6 +38,8 @@ struct AppRootView: View { } } }+ .meddyScreen()+ .preferredColorScheme(AppEnvironment.isTesting ? referenceAppearance : nil) .environment(navigation) .environment(\.careProfileID, selectedProfileID) .onChange(of: selectedProfileID) { _, new in@@ -45,6 +48,9 @@ struct AppRootView: View { } .task { guard reminders == nil else { return }+ #if DEBUG+ do { try RedesignReferenceFixture.seed(context: container.mainContext) } catch { navigation.error = error.localizedDescription }+ #endif let manager = ReminderService(context: container.mainContext) manager.onError = { navigation.error = $0 } manager.openRun = { run in
diff --git a/Meddy/Meddy/Assets.xcassets/AccentColor.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/AccentColor.colorset/Contents.jsonindex eb87897..55dd76c 100644--- a/Meddy/Meddy/Assets.xcassets/AccentColor.colorset/Contents.json+++ b/Meddy/Meddy/Assets.xcassets/AccentColor.colorset/Contents.json@@ -1,11 +1,44 @@ {- "colors" : [+ "colors": [ {- "idiom" : "universal"+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.419608",+ "green": "0.352941",+ "blue": "0.878431",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.741176",+ "green": "0.682353",+ "blue": "0.968627",+ "alpha": "1.000000"+ }+ } } ],- "info" : {- "author" : "xcode",- "version" : 1+ "info": {+ "author": "xcode",+ "version": 1 } }
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyAccent.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyAccent.colorset/Contents.jsonnew file mode 100644index 0000000..55dd76c--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyAccent.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.419608",+ "green": "0.352941",+ "blue": "0.878431",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.741176",+ "green": "0.682353",+ "blue": "0.968627",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyBackground.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyBackground.colorset/Contents.jsonnew file mode 100644index 0000000..649895e--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyBackground.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.956863",+ "green": "0.945098",+ "blue": "0.988235",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.109804",+ "green": "0.090196",+ "blue": "0.188235",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyBorder.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyBorder.colorset/Contents.jsonnew file mode 100644index 0000000..40b4dc3--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyBorder.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.866667",+ "green": "0.839216",+ "blue": "0.941176",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.207843",+ "green": "0.180392",+ "blue": "0.321569",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyControl.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyControl.colorset/Contents.jsonnew file mode 100644index 0000000..3f2891b--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyControl.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.925490",+ "green": "0.905882",+ "blue": "0.984314",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.227451",+ "green": "0.196078",+ "blue": "0.376471",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyDestructive.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyDestructive.colorset/Contents.jsonnew file mode 100644index 0000000..6df7c0b--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyDestructive.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.721569",+ "green": "0.203922",+ "blue": "0.309804",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.949020",+ "green": "0.654902",+ "blue": "0.709804",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyDivider.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyDivider.colorset/Contents.jsonnew file mode 100644index 0000000..9a85568--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyDivider.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.901961",+ "green": "0.882353",+ "blue": "0.952941",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.172549",+ "green": "0.145098",+ "blue": "0.278431",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyLink.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyLink.colorset/Contents.jsonnew file mode 100644index 0000000..b1d6658--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyLink.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.356863",+ "green": "0.294118",+ "blue": "0.815686",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.741176",+ "green": "0.682353",+ "blue": "0.968627",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyOnAccent.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyOnAccent.colorset/Contents.jsonnew file mode 100644index 0000000..7c5fa31--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyOnAccent.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.109804",+ "green": "0.090196",+ "blue": "0.188235",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddySecondary.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddySecondary.colorset/Contents.jsonnew file mode 100644index 0000000..fc1f854--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddySecondary.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.431373",+ "green": "0.403922",+ "blue": "0.564706",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.647059",+ "green": "0.619608",+ "blue": "0.776471",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyStrongBorder.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyStrongBorder.colorset/Contents.jsonnew file mode 100644index 0000000..7e60f3c--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyStrongBorder.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.811765",+ "green": "0.776471",+ "blue": "0.925490",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.290196",+ "green": "0.254902",+ "blue": "0.439216",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddySuccess.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddySuccess.colorset/Contents.jsonnew file mode 100644index 0000000..1c00e8b--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddySuccess.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.180392",+ "green": "0.603922",+ "blue": "0.447059",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.623529",+ "green": "0.890196",+ "blue": "0.784314",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddySuccessSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddySuccessSurface.colorset/Contents.jsonnew file mode 100644index 0000000..8dd1c8b--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddySuccessSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.866667",+ "green": "0.952941",+ "blue": "0.917647",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.133333",+ "green": "0.219608",+ "blue": "0.227451",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddySurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddySurface.colorset/Contents.jsonnew file mode 100644index 0000000..f2af386--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddySurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.164706",+ "green": "0.141176",+ "blue": "0.258824",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyText.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyText.colorset/Contents.jsonnew file mode 100644index 0000000..cba31f8--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyText.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.121569",+ "green": "0.101961",+ "blue": "0.200000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.945098",+ "green": "0.933333",+ "blue": "0.984314",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/MeddyWarning.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/MeddyWarning.colorset/Contents.jsonnew file mode 100644index 0000000..9654a1e--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/MeddyWarning.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.603922",+ "green": "0.356863",+ "blue": "0.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.960784",+ "green": "0.780392",+ "blue": "0.494118",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeDiabetesDot.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeDiabetesDot.colorset/Contents.jsonnew file mode 100644index 0000000..a25c9a2--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeDiabetesDot.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.298003",+ "green": "0.690151",+ "blue": "0.896917",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.298003",+ "green": "0.690151",+ "blue": "0.896917",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeDiabetesInk.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeDiabetesInk.colorset/Contents.jsonnew file mode 100644index 0000000..3a79adb--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeDiabetesInk.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.000000",+ "green": "0.307609",+ "blue": "0.459701",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.616261",+ "green": "0.855450",+ "blue": "0.997453",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeDiabetesSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeDiabetesSurface.colorset/Contents.jsonnew file mode 100644index 0000000..aabe917--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeDiabetesSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.837868",+ "green": "0.939700",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.084987",+ "green": "0.214718",+ "blue": "0.284892",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeDiabetesTrack.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeDiabetesTrack.colorset/Contents.jsonnew file mode 100644index 0000000..af29117--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeDiabetesTrack.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.072849",+ "green": "0.141094",+ "blue": "0.180379",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeEyesDot.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeEyesDot.colorset/Contents.jsonnew file mode 100644index 0000000..afb6862--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeEyesDot.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.077177",+ "green": "0.731958",+ "blue": "0.761136",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.077177",+ "green": "0.731958",+ "blue": "0.761136",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeEyesInk.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeEyesInk.colorset/Contents.jsonnew file mode 100644index 0000000..c956569--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeEyesInk.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.000000",+ "green": "0.339043",+ "blue": "0.363775",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.563058",+ "green": "0.883771",+ "blue": "0.900493",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeEyesSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeEyesSurface.colorset/Contents.jsonnew file mode 100644index 0000000..b153cb3--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeEyesSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.820276",+ "green": "0.952201",+ "blue": "0.958307",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.032097",+ "green": "0.228874",+ "blue": "0.238564",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeEyesTrack.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeEyesTrack.colorset/Contents.jsonnew file mode 100644index 0000000..ab6220e--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeEyesTrack.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.054703",+ "green": "0.148964",+ "blue": "0.153947",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeFallbackDot.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeFallbackDot.colorset/Contents.jsonnew file mode 100644index 0000000..8035d43--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeFallbackDot.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.641822",+ "green": "0.592170",+ "blue": "0.919408",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.641822",+ "green": "0.592170",+ "blue": "0.919408",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeFallbackInk.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeFallbackInk.colorset/Contents.jsonnew file mode 100644index 0000000..3b2f903--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeFallbackInk.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.281961",+ "green": "0.235754",+ "blue": "0.475050",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.813912",+ "green": "0.787192",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeFallbackSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeFallbackSurface.colorset/Contents.jsonnew file mode 100644index 0000000..1850ab4--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeFallbackSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.918422",+ "green": "0.908897",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.197736",+ "green": "0.181415",+ "blue": "0.292605",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeFallbackTrack.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeFallbackTrack.colorset/Contents.jsonnew file mode 100644index 0000000..0edd7f5--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeFallbackTrack.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.130452",+ "green": "0.122327",+ "blue": "0.184868",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeInfectionDot.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeInfectionDot.colorset/Contents.jsonnew file mode 100644index 0000000..af98b9c--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeInfectionDot.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.901870",+ "green": "0.519398",+ "blue": "0.522166",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.901870",+ "green": "0.519398",+ "blue": "0.522166",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeInfectionInk.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeInfectionInk.colorset/Contents.jsonnew file mode 100644index 0000000..12ba072--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeInfectionInk.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.455296",+ "green": "0.177458",+ "blue": "0.190370",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "0.739451",+ "blue": "0.734662",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeInfectionSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeInfectionSurface.colorset/Contents.jsonnew file mode 100644index 0000000..1a624ac--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeInfectionSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "0.888241",+ "blue": "0.884242",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.287119",+ "green": "0.156905",+ "blue": "0.157328",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeInfectionTrack.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeInfectionTrack.colorset/Contents.jsonnew file mode 100644index 0000000..72f9061--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeInfectionTrack.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.182793",+ "green": "0.108921",+ "blue": "0.108227",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposePainDot.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposePainDot.colorset/Contents.jsonnew file mode 100644index 0000000..58248d5--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposePainDot.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.880162",+ "green": "0.553208",+ "blue": "0.364186",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.880162",+ "green": "0.553208",+ "blue": "0.364186",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposePainInk.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposePainInk.colorset/Contents.jsonnew file mode 100644index 0000000..2527ec1--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposePainInk.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.442098",+ "green": "0.204402",+ "blue": "0.031349",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.991607",+ "green": "0.762164",+ "blue": "0.636433",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposePainSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposePainSurface.colorset/Contents.jsonnew file mode 100644index 0000000..36fbddf--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposePainSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "0.898322",+ "blue": "0.842582",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.279559",+ "green": "0.168321",+ "blue": "0.104691",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposePainTrack.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposePainTrack.colorset/Contents.jsonnew file mode 100644index 0000000..21c5319--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposePainTrack.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.178140",+ "green": "0.115235",+ "blue": "0.080239",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeSkinDot.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeSkinDot.colorset/Contents.jsonnew file mode 100644index 0000000..a3d9fa0--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeSkinDot.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.875141",+ "green": "0.516194",+ "blue": "0.660122",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.875141",+ "green": "0.516194",+ "blue": "0.660122",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeSkinInk.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeSkinInk.colorset/Contents.jsonnew file mode 100644index 0000000..2c09d8a--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeSkinInk.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.437137",+ "green": "0.176806",+ "blue": "0.291556",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.989681",+ "green": "0.736190",+ "blue": "0.829589",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeSkinSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeSkinSurface.colorset/Contents.jsonnew file mode 100644index 0000000..d702230--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeSkinSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "0.886490",+ "blue": "0.926379",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.277945",+ "green": "0.155737",+ "blue": "0.204168",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeSkinTrack.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeSkinTrack.colorset/Contents.jsonnew file mode 100644index 0000000..b7fcd0d--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeSkinTrack.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.177434",+ "green": "0.108120",+ "blue": "0.134478",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeSupplementsDot.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeSupplementsDot.colorset/Contents.jsonnew file mode 100644index 0000000..2826a26--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeSupplementsDot.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.376383",+ "green": "0.732122",+ "blue": "0.514188",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.376383",+ "green": "0.732122",+ "blue": "0.514188",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeSupplementsInk.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeSupplementsInk.colorset/Contents.jsonnew file mode 100644index 0000000..1cb389f--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeSupplementsInk.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.000000",+ "green": "0.340234",+ "blue": "0.182300",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.656171",+ "green": "0.882840",+ "blue": "0.730571",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeSupplementsSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeSupplementsSurface.colorset/Contents.jsonnew file mode 100644index 0000000..5754f97--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeSupplementsSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.853930",+ "green": "0.951382",+ "blue": "0.882817",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.109850",+ "green": "0.228862",+ "blue": "0.154727",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeSupplementsTrack.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeSupplementsTrack.colorset/Contents.jsonnew file mode 100644index 0000000..b583592--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeSupplementsTrack.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.084740",+ "green": "0.148818",+ "blue": "0.106964",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeThyroidDot.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeThyroidDot.colorset/Contents.jsonnew file mode 100644index 0000000..d0af422--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeThyroidDot.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.691049",+ "green": "0.575266",+ "blue": "0.896228",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.691049",+ "green": "0.575266",+ "blue": "0.896228",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeThyroidInk.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeThyroidInk.colorset/Contents.jsonnew file mode 100644index 0000000..038088e--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeThyroidInk.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.315592",+ "green": "0.223463",+ "blue": "0.458546",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.849585",+ "green": "0.775368",+ "blue": "0.997699",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeThyroidSurface.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeThyroidSurface.colorset/Contents.jsonnew file mode 100644index 0000000..57cfffb--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeThyroidSurface.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.934789",+ "green": "0.903566",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.214582",+ "green": "0.175665",+ "blue": "0.284702",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/Assets.xcassets/PurposeThyroidTrack.colorset/Contents.json b/Meddy/Meddy/Assets.xcassets/PurposeThyroidTrack.colorset/Contents.jsonnew file mode 100644index 0000000..7d2b895--- /dev/null+++ b/Meddy/Meddy/Assets.xcassets/PurposeThyroidTrack.colorset/Contents.json@@ -0,0 +1,44 @@+{+ "colors": [+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "1.000000",+ "green": "1.000000",+ "blue": "1.000000",+ "alpha": "1.000000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0.140142",+ "green": "0.119079",+ "blue": "0.180368",+ "alpha": "1.000000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}
diff --git a/Meddy/Meddy/ContentView.swift b/Meddy/Meddy/ContentView.swiftindex ec54ece..0036493 100644--- a/Meddy/Meddy/ContentView.swift+++ b/Meddy/Meddy/ContentView.swift@@ -5,362 +5,388 @@ struct ContentView: View { @Environment(\.careProfileID) private var selectedProfileID @Environment(\.modelContext) private var context @Environment(\.logicalDayNow) private var logicalTick- private var logicalNow: Date {- _ = logicalTick- return Date()- } @Query(sort: \Medication.name) private var allMedications: [Medication]- private var medications: [Medication] {- allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }- } @Query(sort: \Administration.timestamp, order: .reverse) private var allEvents: [Administration]- private var events: [Administration] {- allEvents.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }- }+ @Binding var profileSelection: UUID+ var cloud: CloudSyncMonitor? @State private var addingMedication = false @State private var showArchived = false- @State private var error: String?- @Environment(\.snoozeMedication) private var snoozeMedication+ @State private var search = ""+ @FocusState private var searchFocused: Bool @State private var editingTodayEvent: Administration?- @State private var undoEvent: Administration?+ @State private var loggingMedication: Medication?+ @State private var undoEvents: [Administration] = []+ @State private var toastID = UUID()+ @State private var error: String? - private var service: MedicationService { MedicationService(context: context) }+ init(+ profileSelection: Binding<UUID> = .constant(ProfileIdentity.me), cloud: CloudSyncMonitor? = nil+ ) {+ _profileSelection = profileSelection+ self.cloud = cloud+ }+ private var now: Date {+ _ = logicalTick+ return Date()+ }+ private var medications: [Medication] {+ allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+ } private var active: [Medication] { medications.filter(\.isActive) }- private var scheduled: [Medication] {- active.filter { !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw) }.sorted { left, right in- let leftNext =- (try? MedicationPresentation.result(left, now: logicalNow, context: context).next)- ?? .distantFuture- let rightNext =- (try? MedicationPresentation.result(right, now: logicalNow, context: context).next)- ?? .distantFuture- if leftNext != rightNext { return leftNext < rightNext }- return left.name.localizedCaseInsensitiveCompare(right.name) == .orderedAscending+ private var todayEvents: [Administration] {+ allEvents.filter {+ !$0.isDeleted && ProfileAccess.visible($0, for: selectedProfileID, context: context)+ && ScheduleCalendar.sameDay($0.timestamp, now, calendar: .current) } }+ private var scheduled: [(Medication, Date)] {+ active.filter { !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw) }.compactMap { medication in+ guard+ let next = try? MedicationPresentation.result(medication, now: now, context: context).next+ else { return nil }+ return (medication, next)+ }.sorted { $0.1 == $1.1 ? $0.0.name < $1.0.name : $0.1 < $1.1 }+ }+ private var due: [Medication] {+ scheduled.filter { $0.1 <= now.addingTimeInterval(1800) }.map(\.0)+ } var body: some View { TabView {- NavigationStack {- List {- Section("Scheduled medications") {- ForEach(scheduled) { medication in- VStack(alignment: .leading) {- MedicationRow(medication: medication) { record(medication) }- if !medication.requirements.isEmpty {- Text("Requirements").font(.caption)- Text(medication.requirements).font(.caption)- }- if !medication.administrationMethod.isEmpty {- Text(medication.administrationMethod).font(.caption)- }- if medication.remindersEnabled {- Button("Remind me later") { snoozeMedication(medication.id) }- }- if let result = try? MedicationPresentation.result(- medication, now: logicalNow, context: context) {- if result.cannotFitInWindow {- Text("Remaining administrations cannot fit in today's window").font(.caption)- } else if let next = result.next {- Text("Next \(next.formatted(date: .abbreviated, time: .shortened))").font(- .caption)- }- if let remaining = result.remainingToday {- Text(- remaining == 0- ? "Completed for today"- : "\(result.takenToday) recorded · \(remaining) remaining today"- ).font(.caption)- }- }- }- }+ NavigationStack { today }.tabItem { Label("Today", systemImage: "sun.max") }+ NavigationStack { library }.id("medications-" + selectedProfileID.uuidString).tabItem {+ Label("Medications", systemImage: "pills")+ }+ NavigationStack { RoutinesView() }.id("routines-" + selectedProfileID.uuidString).tabItem {+ Label("Routines", systemImage: "list.bullet.clipboard")+ }+ }.tint(MeddyStyle.accent)+ .onChange(of: selectedProfileID) { _, _ in+ undoEvents = []+ editingTodayEvent = nil+ loggingMedication = nil+ search = ""+ showArchived = false+ }+ .sheet(isPresented: $addingMedication) { MedicationEditor(profileID: selectedProfileID) }+ .sheet(item: $loggingMedication) { AdministrationEditor(medication: $0, onSaved: showUndo) }+ .sheet(item: $editingTodayEvent) { event in+ if let medication = event.medication {+ AdministrationEditor(medication: medication, event: event)+ } else {+ ContentUnavailableView("Medication unavailable", systemImage: "pills")+ }+ }+ .alert(+ "Could not save",+ isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+ ) {+ Button("OK") { error = nil }+ } message: {+ Text(error ?? "")+ }+ }++ private var today: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: 12) {+ MeddyScreenHeader(+ title: "Today",+ subtitle:+ "\(now.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))) · \(todayEvents.count) recorded"+ ) {+ ProfilePicker(selection: $profileSelection, cloud: cloud)+ }+ if let cloud, cloud.needsAttention {+ HStack {+ Text(cloud.message).font(.caption)+ Button("Retry") { cloud.refresh() }+ }+ .foregroundStyle(MeddyStyle.warning).meddyCard(radius: 20, padding: 16)+ }+ dueHero+ scheduleAttention+ TodayRoutineSections()+ if scheduled.contains(where: { $0.1 > now.addingTimeInterval(1800) }) {+ MeddySectionLabel(text: "Later").padding(.horizontal, 8)+ ForEach(scheduled.filter { $0.1 > now.addingTimeInterval(1800) }, id: \.0.id) { medication, date in+ NavigationLink {+ MedicationDetailView(medication: medication)+ } label: {+ HStack(spacing: 12) {+ Text(date, style: .time).monospacedDigit().frame(width: 66, alignment: .leading)+ MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name, size: 32)+ Text(medication.name).fontWeight(.semibold)+ Spacer(minLength: 4)+ Text(medication.defaultDose == .unknown ? "" : medication.defaultDose.displayText)+ .font(.subheadline).foregroundStyle(MeddyStyle.secondary)+ }.padding(.vertical, 12).padding(.horizontal, 8)+ }.buttonStyle(.plain)+ Rectangle().fill(MeddyStyle.divider).frame(height: 0.5) }- TodayRoutineSections()- Section("As needed") {- ForEach(- active.filter { $0.scheduleTypeRaw == MedicationScheduleType.asNeeded.rawValue }- ) { medication in- MedicationRow(medication: medication) { record(medication) }+ }+ TodayRoutineSections(+ later: true,+ hasMedicationLater: scheduled.contains { $0.1 > now.addingTimeInterval(1800) })+ MeddySectionLabel(text: "As needed").padding(.horizontal, 8)+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 12)], spacing: 12) {+ ForEach(active.filter { $0.scheduleTypeRaw == "asNeeded" }) { medication in+ Button {+ loggingMedication = medication+ } label: {+ AsNeededTile(medication: medication) }- Button("Add as-needed medication", systemImage: "plus") { addingMedication = true }+ .buttonStyle(.plain).accessibilityLabel("Log dose for \(medication.name)")+ .accessibilityValue(medication.recognitionPhotoData == nil ? "" : "Recognition photo attached") }- Section("Taken today") {- ForEach(- events.filter {- !$0.isDeleted- && ScheduleCalendar.sameDay($0.timestamp, logicalNow, calendar: .current)- }- ) { event in+ }+ if !todayEvents.isEmpty {+ MeddySectionLabel(text: "Taken").padding(.horizontal, 8)+ MeddyWrap {+ ForEach(todayEvents) { event in Button { editingTodayEvent = event } label: {- VStack(alignment: .leading) {+ HStack(spacing: 5) {+ Image(systemName: "checkmark").foregroundStyle(MeddyStyle.success)+ MedicationPhotoView(data: event.medication?.recognitionPhotoData, name: event.medication?.name ?? "Medication", size: 24) Text(event.medication?.name ?? "Medication")- Text(event.timestamp, style: .time).font(.caption)- Text(event.recordedDose.displayText).font(.caption).foregroundStyle(.secondary)- if event.routineRunID != nil {- Text("Routine-linked administration").font(.caption)- }- }- }+ Text("· " + event.timestamp.formatted(date: .omitted, time: .shortened))+ }.font(.caption).padding(.horizontal, 12).padding(.vertical, 9)+ .background(MeddyStyle.surface, in: Capsule())+ }.buttonStyle(.plain) } } }- .navigationTitle("Today")- .toolbar {- if let event = undoEvent, !event.isDeleted {- Button("Undo Taken") {- perform {- try service.delete(event)- undoEvent = nil+ }.padding(.horizontal, 16).padding(.bottom, 120)+ }.meddyScreen().toolbar(.hidden, for: .navigationBar)+ .overlay(alignment: .bottom) { undoToast }+ }++ private var scheduleAttention: some View {+ ForEach(active.filter { !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw) }) { medication in+ if let result = try? MedicationPresentation.result(medication, now: now, context: context),+ result.next == nil {+ if result.cannotFitInWindow+ || medication.scheduleTypeRaw == "afterWaking" && result.takenToday == 0 {+ NavigationLink {+ MedicationDetailView(medication: medication)+ } label: {+ HStack(spacing: 12) {+ MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)+ VStack(alignment: .leading, spacing: 5) {+ Text(medication.name).font(.headline)+ Text(+ result.cannotFitInWindow+ ? "Remaining doses cannot fit in today's window" : "Waiting for recorded wake"+ )+ .font(.caption).foregroundStyle(MeddyStyle.secondary) }- }- }+ }.meddyCard(radius: 22, padding: 16)+ }.buttonStyle(.plain)+ .accessibilityValue(medication.recognitionPhotoData == nil ? "" : "Recognition photo attached") } }- .tabItem { Label("Today", systemImage: "sun.max") }- NavigationStack {- List {- Picker("Show", selection: $showArchived) {- Text("Active").tag(false)- Text("Archived").tag(true)- }.pickerStyle(.segmented)- let displayed = medications.filter { $0.isActive != showArchived }- let groups = Dictionary(grouping: displayed) { $0.purpose?.name ?? "Ungrouped" }- ForEach(groups.keys.sorted(), id: \.self) { purpose in- Section(purpose) {- ForEach(groups[purpose] ?? []) { medication in- MedicationRow(medication: medication) { record(medication) }+ }+ }++ private var dueHero: some View {+ VStack(alignment: .leading, spacing: 16) {+ if due.isEmpty {+ Text("All caught up").font(.system(.title2, weight: .bold))+ if let next = scheduled.first {+ Text("Next \(next.0.name) at \(next.1.formatted(date: .omitted, time: .shortened))")+ .font(.subheadline).foregroundStyle(MeddyStyle.secondary)+ } else {+ Text("Your next care will appear here.").font(.subheadline).foregroundStyle(+ MeddyStyle.secondary)+ }+ } else {+ Text(+ ((scheduled.first?.1 ?? Date()) > Date() ? "UP NEXT · " : "DUE NOW · ")+ + (scheduled.first?.1.formatted(date: .omitted, time: .shortened) ?? "")+ )+ .font(.system(.caption, weight: .bold)).tracking(1.44).foregroundStyle(MeddyStyle.accent)+ ForEach(due) { medication in+ NavigationLink {+ MedicationDetailView(medication: medication)+ } label: {+ HStack(alignment: .top, spacing: 12) {+ MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)+ VStack(alignment: .leading, spacing: 5) {+ HStack(alignment: .firstTextBaseline) {+ Text(medication.name).font(.system(.title2, weight: .bold))+ Spacer(minLength: 8)+ Text(medication.defaultDose == .unknown ? "" : medication.defaultDose.displayText)+ .font(.subheadline).foregroundStyle(MeddyStyle.secondary)+ }+ if !medication.requirements.isEmpty {+ Text(medication.requirements).font(.subheadline).foregroundStyle(+ MeddyStyle.secondary+ ).lineLimit(1)+ } else if !medication.administrationMethod.isEmpty {+ Text(medication.administrationMethod).font(.subheadline).foregroundStyle(+ MeddyStyle.secondary+ ).lineLimit(1)+ } } }+ }.buttonStyle(.plain)+ .accessibilityValue(medication.recognitionPhotoData == nil ? "" : "Recognition photo attached")+ }+ Button(due.count == 1 ? "Take" : due.count == 2 ? "Take both" : "Take all \(due.count)") {+ do { showUndo(try TodayMedicationAction.take(due, at: Date(), context: context)) } catch {+ self.error = error.localizedDescription }+ }.buttonStyle(MeddyPrimaryButtonStyle()).accessibilityIdentifier("takeDueMedications")+ }+ }.meddyCard()+ }++ private var library: some View {+ let displayed = medications.filter {+ $0.isActive != showArchived+ && (search.isEmpty+ || $0.name.localizedCaseInsensitiveContains(search)+ || ($0.purpose?.name.localizedCaseInsensitiveContains(search) ?? false))+ }+ return ScrollView {+ VStack(alignment: .leading, spacing: 12) {+ MeddyScreenHeader(title: "Medications") {+ Button {+ addingMedication = true+ } label: {+ Image(systemName: "plus").font(.title3.bold()).frame(width: 40, height: 40)+ .foregroundStyle(MeddyStyle.onAccent).background(MeddyStyle.accent, in: Circle())+ }.accessibilityLabel("Add medication")+ }+ HStack {+ Image(systemName: "magnifyingglass")+ TextField("Search \(medications.filter(\.isActive).count) medications", text: $search)+ .accessibilityIdentifier("medicationSearch")+ .focused($searchFocused).submitLabel(.search).onSubmit { searchFocused = false }+ }.padding(13).background(MeddyStyle.surface, in: RoundedRectangle(cornerRadius: 14))+ ForEach(displayed) { medication in+ MedicationRow(medication: medication) {}+ Rectangle().fill(MeddyStyle.divider).frame(height: 0.5)+ }+ if displayed.isEmpty {+ VStack(alignment: .leading, spacing: 8) {+ Text(search.isEmpty ? "No medications yet" : "No matching medications").font(+ .title2.bold())+ Text(+ search.isEmpty+ ? "Add a medication to begin tracking." : "Try another name or purpose."+ )+ .foregroundStyle(MeddyStyle.secondary)+ }.meddyCard() }- .navigationTitle("Medications")- .toolbar {- Button("Add medication", systemImage: "plus") { addingMedication = true }+ HStack(alignment: .top, spacing: 8) {+ Button(+ showArchived+ ? "Show active" : "Show archived (\(medications.filter { !$0.isActive }.count))"+ ) {+ showArchived.toggle()+ }.buttonStyle(MeddyOutlineButtonStyle()) NavigationLink { CurrentMedicationsView() } label: {- Label("Current Medications", systemImage: "list.bullet.rectangle")+ Text("Share for appointment") }- }- }- .tabItem { Label("Medications", systemImage: "pills") }- NavigationStack {- RoutinesView()- }- .tabItem { Label("Routines", systemImage: "list.bullet.clipboard") }- }- .sheet(isPresented: $addingMedication) { MedicationEditor(profileID: selectedProfileID) }- .sheet(item: $editingTodayEvent) { event in- if let medication = event.medication {- AdministrationEditor(medication: medication, event: event)- } else {- ContentUnavailableView("Medication unavailable", systemImage: "pills")- }- }- .alert(- "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })- ) {- Button("OK") { error = nil }- } message: {- Text(error ?? "")- }+ .buttonStyle(MeddyOutlineButtonStyle())+ }.padding(.top, 16)+ }.padding(.horizontal, 16).padding(.bottom, 120)+ }.meddyScreen().toolbar(.hidden, for: .navigationBar) } - private func record(_ medication: Medication) {- perform {- undoEvent = try service.record(- ProfileAccess.stamp(- AdministrationAction(- eventID: UUID(), medicationID: medication.id, timestamp: Date(),- source: .phone, dose: medication.defaultDose,- scheduleTypeAtRecording: MedicationScheduleType(rawValue: medication.scheduleTypeRaw)- ?? .asNeeded,- scheduleGenerationID: medication.scheduleGenerationID- ), target: medication, context: context))+ @ViewBuilder private var undoToast: some View {+ if !undoEvents.isEmpty {+ HStack {+ Text(+ "\(undoEvents.count == 1 ? undoEvents[0].medication?.name ?? "Medication" : "\(undoEvents.count) medications") taken"+ )+ .font(.subheadline.weight(.semibold))+ Spacer()+ Button("Undo") {+ do {+ try TodayMedicationAction.undo(undoEvents, context: context)+ undoEvents = []+ } catch { self.error = error.localizedDescription }+ }.buttonStyle(MeddyOutlineButtonStyle(ink: MeddyStyle.onAccent)).accessibilityLabel(+ "Undo Taken")+ }.padding(16).foregroundStyle(MeddyStyle.onAccent)+ .background(MeddyStyle.accent, in: RoundedRectangle(cornerRadius: 18)).padding(16)+ .task(id: toastID) {+ let captured = toastID+ try? await Task.sleep(for: .seconds(5))+ if !Task.isCancelled && captured == toastID { undoEvents = [] }+ } } }-- private func perform(_ work: () throws -> Void) {- do { try work() } catch { self.error = error.localizedDescription }+ private func showUndo(_ events: [Administration]) {+ undoEvents = events+ toastID = UUID() } } struct MedicationRow: View { @Environment(\.careProfileID) private var selectedProfileID @Environment(\.modelContext) private var context- @Environment(PhoneNavigation.self) private var navigation @Query(sort: \Routine.name) private var allRoutines: [Routine]- private var routines: [Routine] {- allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }- } let medication: Medication let taken: () -> Void- var body: some View {- HStack {- NavigationLink {- MedicationDetailView(medication: medication)- } label: {- HStack(alignment: .top) {- MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)- VStack(alignment: .leading, spacing: 4) {- Text(medication.name).font(.headline)- Text(MedicationPresentation.scheduleLabel(medication, routines: routines)).font(- .caption- ).foregroundStyle(.secondary)- if medication.defaultDose != .unknown {- Text(medication.defaultDose.displayText).font(.caption)- }- if let last = medication.visibleAdministrations.first {- Text("Last taken \(last.timestamp.formatted(date: .abbreviated, time: .shortened))")- .font(.caption).foregroundStyle(.secondary)- } else {- Text("Not logged yet").font(.caption).foregroundStyle(.secondary)- }- }- }- }- if medication.isActive {- if let ownerID = medication.managedByRoutineID,- let owner = routines.first(where: { $0.id == ownerID }) {- NavigationLink("Open routine") {- RoutineDetailView(- routine: owner, onStart: { navigation.start($0, occurrence: $1) },- onOpen: navigation.open)- }- } else {- Button("Taken", action: taken).buttonStyle(.bordered)- .accessibilityLabel("Mark \(medication.name) taken")+ NavigationLink {+ MedicationDetailView(medication: medication)+ } label: {+ HStack(spacing: 10) {+ MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)+ VStack(alignment: .leading, spacing: 5) {+ Text(medication.name).font(.system(.body, weight: .semibold))+ Text(+ [+ medication.defaultDose == .unknown ? nil : medication.defaultDose.displayText,+ MedicationPresentation.scheduleLabel(+ medication,+ routines: allRoutines.filter {+ ProfileAccess.visible($0, for: selectedProfileID, context: context)+ })+ ].compactMap { $0 }.joined(separator: " · ")+ )+ .font(.caption).foregroundStyle(MeddyStyle.secondary) }- }- }- if medication.scheduleTypeRaw == "asNeeded", medication.asNeededDoseLimitsData != nil {- AsNeededLimitStatus(medication: medication)- }+ Spacer(minLength: 0)+ PurposeTag(name: medication.purpose?.name)+ }.padding(.horizontal, 8).padding(.vertical, 14).contentShape(Rectangle())+ }.buttonStyle(.plain).accessibilityLabel(medication.name)+ .accessibilityValue(medication.recognitionPhotoData == nil ? "" : "Recognition photo attached") } } -struct MedicationDetailView: View {+struct AsNeededTile: View { @Environment(\.modelContext) private var context let medication: Medication- @State private var editing = false- @State private var logDetails = false- @State private var editingEvent: Administration?- @State private var error: String?- @State private var lastSaved: Administration?-- private var service: MedicationService { MedicationService(context: context) }-+ private var check: DoseLimitCheck? { AsNeededLimitService(context: context).check(medication) } var body: some View {- List {- if medication.scheduleTypeRaw == "asNeeded" {- Section("Dose check") { AsNeededLimitStatus(medication: medication) }- }- if medication.recognitionPhotoData != nil {- Section("Recognition photo") {- MedicationPhotoView(- data: medication.recognitionPhotoData, name: medication.name, size: 220)- }+ let check = self.check+ VStack(alignment: .leading, spacing: 10) {+ MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)+ HStack(alignment: .top) {+ Text(medication.name).font(.system(.body, weight: .bold))+ Spacer(minLength: 2)+ Image(systemName: "plus").font(.subheadline.bold()).frame(width: 28, height: 28)+ .background(MeddyStyle.control, in: Circle()).foregroundStyle(MeddyStyle.accent) }- Section {- Text(medication.purpose?.name ?? "Ungrouped")- Text((MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded).title)- .foregroundStyle(.secondary)- if medication.defaultDose != .unknown { Text(medication.defaultDose.displayText) }- if !medication.administrationMethod.isEmpty { Text(medication.administrationMethod) }- if !medication.requirements.isEmpty {- VStack(alignment: .leading) {- Text("Requirements").font(.headline)- Text(medication.requirements)- }- }- if !medication.notes.isEmpty { Text(medication.notes) }- }- if let followup = try? MedicationFollowupService.configuration(medication) {- Section("Follow-up notification") {- Text(followup.message)- Text("\((followup.delaySeconds / 60).formatted()) minutes after the recorded taken time")- .foregroundStyle(.secondary)- }- }- Section {- if medication.isActive {- Button(medication.managedByRoutineID == nil ? "Taken" : "Log outside routine") {- perform {- lastSaved = try service.record(- ProfileAccess.stamp(- AdministrationAction(- eventID: UUID(), medicationID: medication.id, timestamp: Date(),- source: .phone, dose: medication.defaultDose,- scheduleTypeAtRecording: MedicationScheduleType(- rawValue: medication.scheduleTypeRaw) ?? .asNeeded,- scheduleGenerationID: medication.scheduleGenerationID- ), target: medication, context: context))- }- }- }- Button("Log details…") { logDetails = true }- if let event = lastSaved, !event.isDeleted {- Text("Saved").foregroundStyle(.secondary)- Button("Undo Taken") {- perform {- try service.delete(event)- lastSaved = nil- }- }- }- }- let history = Dictionary(grouping: medication.visibleAdministrations) {- ScheduleCalendar.localDate($0.timestamp, calendar: .current)- }- ForEach(history.keys.sorted(by: >), id: \.self) { day in- Section("Administration history · \(day)") {- ForEach(history[day] ?? []) { event in- Button {- editingEvent = event- } label: {- VStack(alignment: .leading) {- Text(event.timestamp.formatted(date: .abbreviated, time: .shortened))- Text(event.recordedDose.displayText)- .font(.caption).foregroundStyle(.secondary)- }- }- .swipeActions {- Button("Delete", role: .destructive) {- perform {- try RoutineSessionService(context: context).correct(- event, timestamp: event.timestamp, dose: event.recordedDose, delete: true)- }- }- }- }- }- }- Section {- Button(medication.isActive ? "Archive" : "Reactivate") {- perform { try service.setActive(medication, !medication.isActive) }- }+ if let check, let amount = check.knownAmount, let max = check.maximumAmount {+ Text("\(amount.formatted()) of \(max.formatted()) \(check.unit) · configured window")+ .font(.caption).foregroundStyle(MeddyStyle.secondary)+ } else {+ Text(medication.visibleAdministrations.isEmpty ? "None logged" : "Tap to log a dose")+ .font(.caption).foregroundStyle(MeddyStyle.secondary) }- }- .navigationTitle(medication.name)- .toolbar { Button("Edit") { editing = true } }- .sheet(isPresented: $editing) { MedicationEditor(medication: medication) }- .sheet(isPresented: $logDetails) { AdministrationEditor(medication: medication) }- .sheet(item: $editingEvent) { AdministrationEditor(medication: medication, event: $0) }- .alert(- "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })- ) {- Button("OK") { error = nil }- } message: {- Text(error ?? "")- }- }-- private func perform(_ work: () throws -> Void) {- do { try work() } catch { self.error = error.localizedDescription }+ Text(check?.title ?? "Log a dose").font(.caption.weight(.semibold)).foregroundStyle(+ MeddyStyle.accent)+ }.meddyCard(radius: 22, padding: 16) } } @@ -377,6 +403,7 @@ struct MedicationEditor: View { @State private var photo: MedicationPhotoDraft @State private var limits: AsNeededLimitDraft @State private var followup: MedicationFollowupDraft+ @State private var prescription: PrescriptionDraft @State private var name: String @State private var description: String @State private var amount: String@@ -405,6 +432,7 @@ struct MedicationEditor: View { _photo = State(initialValue: MedicationPhotoDraft(data: medication?.recognitionPhotoData)) _limits = State(initialValue: AsNeededLimitDraft(medication: medication)) _followup = State(initialValue: MedicationFollowupDraft(medication: medication))+ _prescription = State(initialValue: PrescriptionDraft(medication: medication)) _name = State(initialValue: medication?.name ?? "") _description = State(initialValue: medication?.doseDescription ?? "") _amount = State(initialValue: medication?.defaultDoseAmount.map { String($0) } ?? "")@@ -436,7 +464,7 @@ struct MedicationEditor: View { var body: some View { NavigationStack { Form {- Section {+ MeddySection("Medication") { TextField("Name", text: $name) Picker("Purpose", selection: $purpose) { Text("None").tag(nil as Purpose?)@@ -445,14 +473,15 @@ struct MedicationEditor: View { } } Button("Add Purpose…") { addingPurpose = true }- }+ }.listRowBackground(MeddyStyle.surface) MedicationPhotoEditor(draft: photo, name: name)- Section("Optional recording defaults") {+ MeddySection("Optional recording defaults") { TextField("Dose description", text: $description) TextField(scheduleMode == .asNeeded ? "Quantity per dose" : "Amount", text: $amount) .keyboardType(.decimalPad) TextField("Unit", text: $unit)- }+ }.listRowBackground(MeddyStyle.surface)+ PrescriptionFields(draft: prescription) Section { TextField("How to take / apply", text: $method, axis: .vertical) TextField("Requirements", text: $requirements, axis: .vertical).accessibilityIdentifier(@@ -465,20 +494,35 @@ struct MedicationEditor: View { Text("Before sleeping is a cue, without a fixed clock reminder.").font(.caption) .foregroundStyle(.secondary) TextField("Notes", text: $notes, axis: .vertical)- }+ }.listRowBackground(MeddyStyle.surface) if medication?.managedByRoutineID == nil { scheduleFields if scheduleMode == .asNeeded { AsNeededLimitFields(draft: limits) } } else {- Section("Schedule") {+ MeddySection("Schedule") { Text("Managed by its ordered routine. Change ownership from the routine editor.")- }+ }.listRowBackground(MeddyStyle.surface) } MedicationFollowupFields(draft: followup)- if let error { Section { Text(error).foregroundStyle(.red) } }+ if let medication {+ Section {+ Button(medication.isActive ? "Archive medication" : "Reactivate medication") {+ do {+ try MedicationService(context: context).setActive(medication, !medication.isActive)+ dismiss()+ } catch { self.error = error.localizedDescription }+ }.foregroundStyle(Color("MeddyDestructive"))+ }.listRowBackground(MeddyStyle.surface)+ }+ if let error {+ Section { Text(error).foregroundStyle(.red) }.listRowBackground(MeddyStyle.surface)+ } }+ .meddyScreen()+ .accessibilityIdentifier("medicationEditorForm") .scrollDismissesKeyboard(.immediately) .navigationTitle(medication == nil ? "Add medication" : "Edit medication")+ .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) {@@ -520,13 +564,16 @@ struct MedicationEditor: View { let draft = medication?.managedByRoutineID == nil ? try scheduleFields.draft() : nil if scheduleMode == .asNeeded { _ = try limits.rules(doseUnit: doseUnit) } _ = try followup.value()+ _ = try prescription.value() _ = try EditorTransaction.save(context: context) { let service = MedicationService(context: context, deferSave: true) let saved: Medication if let medication { try service.update(- medication, edit: MedicationEdit(name: name, dose: dose, purpose: purpose,- method: method, requirements: requirements, notes: notes))+ medication,+ edit: MedicationEdit(+ name: name, dose: dose, purpose: purpose,+ method: method, requirements: requirements, notes: notes)) saved = medication } else { saved = try service.createAsNeededMedication(@@ -537,6 +584,7 @@ struct MedicationEditor: View { try ScheduleService(context: context, deferSave: true).configure( saved, draft: draft, reminders: reminders) }+ try prescription.apply(to: saved, context: context) try photo.apply(to: saved, context: context) try followup.apply(to: saved) if scheduleMode == .asNeeded {@@ -554,6 +602,9 @@ struct AdministrationEditor: View { @Environment(\.dismiss) private var dismiss let medication: Medication let event: Administration?+ var onSaved: (([Administration]) -> Void)?+ @State private var quickOffset: Int?+ @State private var customDose = false @State private var timestamp: Date @State private var description: String @State private var amount: String@@ -561,71 +612,148 @@ struct AdministrationEditor: View { @State private var error: String? @State private var eventID = UUID() - init(medication: Medication, event: Administration? = nil) {+ init(+ medication: Medication, event: Administration? = nil,+ onSaved: (([Administration]) -> Void)? = nil+ ) { self.medication = medication self.event = event+ self.onSaved = onSaved let dose = event?.recordedDose ?? medication.defaultDose+ _quickOffset = State(initialValue: event == nil ? 0 : nil)+ _customDose = State(initialValue: dose.amount == nil || dose.unit == nil) _timestamp = State(initialValue: event?.timestamp ?? Date()) _description = State(initialValue: dose.description) _amount = State(initialValue: dose.amount.map { String($0) } ?? "") _unit = State(initialValue: dose.unit ?? "") } + private var proposedDose: RecordedDoseSnapshot {+ (try? enteredDose(description: description, amount: amount, unit: unit)) ?? .unknown+ } var body: some View { NavigationStack {- Form {- MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name, size: 160)- DatePicker("Taken", selection: $timestamp, in: ...Date())- TextField("Recorded dose description", text: $description)- TextField("Amount", text: $amount).keyboardType(.decimalPad)- .onChange(of: amount) { _, _ in description = "" }- TextField("Unit", text: $unit)- .onChange(of: unit) { _, _ in description = "" }- Button("Dose not recorded") {- description = ""- amount = ""- unit = ""- }- if medication.scheduleTypeRaw == "asNeeded" {- AsNeededLimitStatus(- medication: medication,- proposedDose: (try? enteredDose(description: description, amount: amount, unit: unit))- ?? .unknown)- Text(- "Log doses actually taken even if they exceed entered limits; records are needed for an accurate check."- ).font(.caption)- }- Text("Recording details leaves medication defaults unchanged.").font(.caption)- if let error { Text(error).foregroundStyle(.red) }- }- .navigationTitle(event == nil ? "Log details" : "Correct entry")- .toolbar {- ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }- ToolbarItem(placement: .confirmationAction) {- Button("Save") {- do {- let dose = try enteredDose(description: description, amount: amount, unit: unit)- let service = MedicationService(context: context)- if let event {- try RoutineSessionService(context: context).correct(- event, timestamp: timestamp, dose: dose)- } else {- _ = try service.record(- ProfileAccess.stamp(- AdministrationAction(- eventID: eventID, medicationID: medication.id,- timestamp: timestamp, source: .manualHistory, dose: dose,- scheduleTypeAtRecording: MedicationScheduleType(- rawValue: medication.scheduleTypeRaw) ?? .asNeeded,- scheduleGenerationID: medication.scheduleGenerationID- ), target: medication, context: context))+ ScrollView {+ VStack(alignment: .leading, spacing: 12) {+ MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name, size: 160)+ .frame(maxWidth: .infinity)+ MeddySectionLabel(text: "Dose")+ VStack(spacing: 16) {+ HStack {+ Button {+ changeAmount(-1)+ } label: {+ Image(systemName: "minus").frame(width: 44, height: 44).background(+ MeddyStyle.control, in: Circle()) }- dismiss()- } catch { self.error = error.localizedDescription }+ .accessibilityLabel("Decrease recorded quantity").disabled((Double(amount) ?? 0) <= 1)+ Spacer()+ VStack {+ Text(amount.isEmpty ? "Unknown" : amount).font(.system(.title2, weight: .bold))+ .monospacedDigit()+ Text(unit).font(.subheadline).foregroundStyle(MeddyStyle.secondary)+ }+ Spacer()+ Button {+ changeAmount(1)+ } label: {+ Image(systemName: "plus").frame(width: 44, height: 44).background(+ MeddyStyle.control, in: Circle())+ }+ .accessibilityLabel("Increase recorded quantity").disabled(+ unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ DisclosureGroup("Custom dose", isExpanded: $customDose) {+ TextField("Recorded dose description", text: $description)+ HStack {+ TextField("Amount", text: $amount).keyboardType(.decimalPad).onChange(of: amount) { _, _ in+ description = ""+ }+ TextField("Unit", text: $unit).onChange(of: unit) { _, _ in description = "" }+ }+ Button("Dose not recorded") {+ description = ""+ amount = ""+ unit = ""+ }+ }+ }.meddyCard(radius: 22, padding: 18)+ MeddySectionLabel(text: "Taken")+ LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 10) {+ ForEach([0, 15, 30, 60], id: \.self) { minutes in+ Button(minutes == 0 ? "Now" : minutes == 60 ? "1 hour ago" : "\(minutes) min ago") {+ timestamp = Date().addingTimeInterval(-Double(minutes * 60))+ quickOffset = minutes+ }.buttonStyle(MeddyTimeChipStyle(selected: quickOffset == minutes)).frame(+ maxWidth: .infinity)+ } }- }+ DatePicker(+ "Custom time",+ selection: Binding(+ get: { timestamp },+ set: {+ timestamp = $0+ quickOffset = nil+ }),+ in: ...Date()+ ).meddyCard(+ radius: 22, padding: 16)+ VStack(alignment: .leading, spacing: 10) {+ Text(+ proposedDose.displayText + " at "+ + timestamp.formatted(date: .omitted, time: .shortened)+ ).font(.headline)+ if medication.scheduleTypeRaw == "asNeeded" {+ Text("Current dose check").font(.caption.bold()).foregroundStyle(MeddyStyle.secondary)+ AsNeededLimitStatus(medication: medication, proposedDose: proposedDose)+ if quickOffset != 0 {+ Text("This check uses now, rather than the earlier recorded time.").font(.caption)+ .foregroundStyle(MeddyStyle.secondary)+ }+ Text("Record doses actually taken, including doses outside entered limits.").font(+ .caption+ ).foregroundStyle(MeddyStyle.warning)+ }+ }.meddyCard(radius: 22, padding: 18)+ Button("Save", action: save).buttonStyle(MeddyPrimaryButtonStyle())+ Text("Recording details leaves medication defaults unchanged.").font(.caption)+ .foregroundStyle(MeddyStyle.secondary)+ if let error { Text(error).foregroundStyle(Color("MeddyDestructive")) }+ }.padding(24)+ }.scrollDismissesKeyboard(.immediately).meddyScreen().navigationTitle(+ event == nil ? "Log " + medication.name : "Correct entry"+ )+ .navigationBarTitleDisplayMode(.inline)+ .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }+ }.presentationDragIndicator(.visible).presentationCornerRadius(28)+ }+ private func changeAmount(_ delta: Double) {+ guard let current = Double(amount), current.isFinite else { return }+ amount = String(max(0, current + delta))+ description = ""+ }+ private func save() {+ do {+ let dose = try enteredDose(description: description, amount: amount, unit: unit)+ let service = MedicationService(context: context)+ if let event {+ try RoutineSessionService(context: context).correct(+ event, timestamp: timestamp, dose: dose)+ } else {+ let saved = try service.record(+ ProfileAccess.stamp(+ AdministrationAction(+ eventID: eventID, medicationID: medication.id,+ timestamp: timestamp, source: .manualHistory, dose: dose,+ scheduleTypeAtRecording: MedicationScheduleType(+ rawValue: medication.scheduleTypeRaw) ?? .asNeeded,+ scheduleGenerationID: medication.scheduleGenerationID+ ), target: medication, context: context))+ onSaved?([saved]) }- }+ dismiss()+ } catch { self.error = error.localizedDescription } } } @@ -643,6 +771,7 @@ private func enteredDose(description: String, amount: String, unit: String) thro #Preview { if let container = try? AppEnvironment.makeContainer(isolated: true) {- ContentView().modelContainer(container)+ ContentView().modelContainer(container).environment(+ PhoneNavigation(context: container.mainContext)) } }
diff --git a/Meddy/Meddy/Design/DoseQuantityProgress.swift b/Meddy/Meddy/Design/DoseQuantityProgress.swiftnew file mode 100644index 0000000..81b174b--- /dev/null+++ b/Meddy/Meddy/Design/DoseQuantityProgress.swift@@ -0,0 +1,28 @@+import SwiftUI++struct DoseQuantityProgress: View {+ let amount: Double+ let maximum: Double+ let palette: PurposePalette+ private var fraction: Double { min(1, max(0, amount / maximum)) }+ var body: some View {+ if maximum > 0, maximum.isFinite {+ if maximum.rounded() == maximum && maximum <= 12 {+ HStack(spacing: 4) {+ ForEach(0..<Int(maximum), id: \.self) { index in+ GeometryReader { geometry in+ Capsule().fill(palette.track)+ Capsule().fill(palette.ink).frame(+ width: geometry.size.width * min(1, max(0, amount - Double(index))))+ }.frame(height: 8)+ }+ }.accessibilityHidden(true)+ } else {+ GeometryReader { geometry in+ Capsule().fill(palette.track)+ Capsule().fill(palette.ink).frame(width: geometry.size.width * fraction)+ }.frame(height: 8).accessibilityHidden(true)+ }+ }+ }+}
diff --git a/Meddy/Meddy/Design/MeddyStyle.swift b/Meddy/Meddy/Design/MeddyStyle.swiftnew file mode 100644index 0000000..d35e354--- /dev/null+++ b/Meddy/Meddy/Design/MeddyStyle.swift@@ -0,0 +1,191 @@+import SwiftUI++// Shared native components for the dark/light handoff; purpose is always user supplied.+enum MeddyStyle {+ static let background = Color("MeddyBackground")+ static let surface = Color("MeddySurface")+ static let control = Color("MeddyControl")+ static let divider = Color("MeddyDivider")+ static let border = Color("MeddyBorder")+ static let text = Color("MeddyText")+ static let secondary = Color("MeddySecondary")+ static let accent = Color("MeddyAccent")+ static let onAccent = Color("MeddyOnAccent")+ static let success = Color("MeddySuccess")+ static let warning = Color("MeddyWarning")+}++struct PurposePalette {+ private let token: String+ init(_ name: String?) {+ switch name?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() {+ case "thyroid": token = "Thyroid"+ case "diabetes": token = "Diabetes"+ case "supplements": token = "Supplements"+ case "pain & allergy": token = "Pain"+ case "skin": token = "Skin"+ case "eyes": token = "Eyes"+ case "infection": token = "Infection"+ default: token = "Fallback"+ }+ }+ var surface: Color { Color("Purpose" + token + "Surface") }+ var ink: Color { Color("Purpose" + token + "Ink") }+ var dot: Color { Color("Purpose" + token + "Dot") }+ var track: Color { Color("Purpose" + token + "Track") }+}++struct MeddySectionLabel: View {+ let text: String+ var body: some View {+ Text(text.uppercased()).font(.system(.caption, design: .default, weight: .bold))+ .tracking(1.44).foregroundStyle(MeddyStyle.secondary)+ .frame(maxWidth: .infinity, alignment: .leading).padding(.top, 16)+ }+}++struct PurposeTag: View {+ let name: String?+ var body: some View {+ if let name, !name.isEmpty {+ Text(name.uppercased()).font(.system(.caption2, weight: .bold)).tracking(0.66)+ .foregroundStyle(PurposePalette(name).ink).padding(.horizontal, 8).padding(.vertical, 4)+ .background(PurposePalette(name).surface, in: RoundedRectangle(cornerRadius: 8))+ }+ }+}++struct MeddyPrimaryButtonStyle: ButtonStyle {+ var fill = MeddyStyle.accent+ var ink = MeddyStyle.onAccent+ func makeBody(configuration: Configuration) -> some View {+ configuration.label.font(.system(.body, weight: .bold))+ .frame(maxWidth: .infinity).padding(.vertical, 17).foregroundStyle(ink)+ .background(fill, in: RoundedRectangle(cornerRadius: 18))+ .scaleEffect(configuration.isPressed ? 0.98 : 1)+ }+}++struct MeddyOutlineButtonStyle: ButtonStyle {+ var ink = MeddyStyle.accent+ func makeBody(configuration: Configuration) -> some View {+ configuration.label.font(.system(.subheadline, weight: .semibold))+ .padding(.horizontal, 16).padding(.vertical, 10).foregroundStyle(ink)+ .background(ink.opacity(configuration.isPressed ? 0.12 : 0), in: Capsule())+ .overlay(Capsule().stroke(ink.opacity(0.6), lineWidth: 1.5))+ }+}++extension View {+ func meddyCard(fill: Color = MeddyStyle.surface, radius: CGFloat = 28, padding: CGFloat = 22)+ -> some View {+ self.padding(padding).frame(maxWidth: .infinity, alignment: .leading)+ .background(fill, in: RoundedRectangle(cornerRadius: radius))+ }+ func meddyScreen() -> some View {+ self.scrollContentBackground(.hidden).background(MeddyStyle.background)+ .foregroundStyle(MeddyStyle.text).tint(MeddyStyle.accent)+ }+}++struct MeddyScreenHeader<Accessory: View>: View {+ let title: String+ @ScaledMetric(relativeTo: .largeTitle) private var titleSize = 30+ var subtitle: String?+ @ViewBuilder var accessory: Accessory+ var body: some View {+ HStack(alignment: .center) {+ VStack(alignment: .leading, spacing: 5) {+ Text(title).font(.system(size: titleSize, weight: .bold)).tracking(-0.6)+ if let subtitle { Text(subtitle).font(.subheadline).foregroundStyle(MeddyStyle.secondary) }+ }+ Spacer(minLength: 8)+ accessory+ }.padding(.horizontal, 8).padding(.top, 10).padding(.bottom, 8)+ }+}++// Intrinsic wrapping keeps chips usable with Dynamic Type instead of truncating a fixed row.+struct MeddyWrap: Layout {+ var spacing: CGFloat = 8+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {+ arrange(subviews, width: proposal.width ?? 390).size+ }+ func placeSubviews(+ in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()+ ) {+ let result = arrange(subviews, width: bounds.width)+ for (index, point) in result.points.enumerated() {+ subviews[index].place(+ at: CGPoint(x: bounds.minX + point.x, y: bounds.minY + point.y), anchor: .topLeading,+ proposal: ProposedViewSize(+ width: min(subviews[index].sizeThatFits(.unspecified).width, bounds.width), height: nil))+ }+ }+ private func arrange(_ subviews: Subviews, width: CGFloat) -> (size: CGSize, points: [CGPoint]) {+ var points: [CGPoint] = []+ var x: CGFloat = 0+ var y: CGFloat = 0+ var rowHeight: CGFloat = 0+ for subview in subviews {+ let size = subview.sizeThatFits(ProposedViewSize(width: width, height: nil))+ if x > 0 && x + size.width > width {+ x = 0+ y += rowHeight + spacing+ rowHeight = 0+ }+ points.append(CGPoint(x: x, y: y))+ x += size.width + spacing+ rowHeight = max(rowHeight, size.height)+ }+ return (CGSize(width: width, height: y + rowHeight), points)+ }+}++struct MeddyProgressRing<Content: View>: View {+ let progress: Double+ let palette: PurposePalette+ var lineWidth: CGFloat = 10+ @ViewBuilder var content: Content+ var body: some View {+ ZStack {+ Circle().stroke(palette.track, lineWidth: lineWidth)+ Circle().trim(from: 0, to: min(1, max(0, progress)))+ .stroke(palette.ink, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))+ .rotationEffect(.degrees(-90))+ content+ }.padding(lineWidth / 2)+ }+}++struct MeddyTimeChipStyle: ButtonStyle {+ let selected: Bool+ func makeBody(configuration: Configuration) -> some View {+ configuration.label.font(.system(.subheadline, weight: .semibold))+ .frame(maxWidth: .infinity).padding(.vertical, 13)+ .foregroundStyle(selected ? MeddyStyle.onAccent : MeddyStyle.accent)+ .background(+ selected ? MeddyStyle.accent : MeddyStyle.control, in: RoundedRectangle(cornerRadius: 14)+ )+ .scaleEffect(configuration.isPressed ? 0.98 : 1)+ }+}++struct MeddySection<Content: View>: View {+ let title: String+ let fill: Color+ let content: Content+ init(_ title: String, fill: Color = MeddyStyle.surface, @ViewBuilder content: () -> Content) {+ self.title = title+ self.fill = fill+ self.content = content()+ }+ var body: some View {+ Section {+ content+ } header: {+ Text(title.uppercased()).font(.caption.weight(.bold)).tracking(1.44)+ .foregroundStyle(MeddyStyle.secondary)+ }.listRowBackground(fill)+ }+}
diff --git a/Meddy/Meddy/Design/RedesignReferenceFixture.swift b/Meddy/Meddy/Design/RedesignReferenceFixture.swiftnew file mode 100644index 0000000..a7e6d41--- /dev/null+++ b/Meddy/Meddy/Design/RedesignReferenceFixture.swift@@ -0,0 +1,90 @@+#if DEBUG+ import SwiftData+ import SwiftUI+ import UIKit++ // Only installed into AppEnvironment's in-memory test container, never a live store.+ @MainActor+ enum RedesignReferenceFixture {+ static func seed(context: ModelContext) throws {+ guard AppEnvironment.isTesting,+ ProcessInfo.processInfo.environment["MEDDY_TEST_REDESIGN_REFERENCE"] == "1"+ else { return }+ let medicationService = MedicationService(context: context)+ let purposes = try ["Thyroid", "Diabetes", "Supplements", "Pain & allergy", "Skin", "Eyes"]+ .map {+ try medicationService.createPurpose(name: $0)+ }+ let pain = try medicationService.createAsNeededMedication(+ name: "Paracetamol",+ dose: .init(description: "1 tablet", amount: 1, unit: "tablets"), purpose: purposes[3],+ method: "Synthetic reference instructions")+ try AsNeededLimitService(context: context).configure(+ pain,+ limits: .init(+ minimumIntervalSeconds: 14400, maximumAmount: 8, windowSeconds: 86400, unit: "tablets"))+ _ = try medicationService.createAsNeededMedication(+ name: "Cetirizine",+ dose: .init(description: "1 tablet", amount: 1, unit: "tablets"), purpose: purposes[3])+ let vitamin = try medicationService.createAsNeededMedication(+ name: "Vitamin D3",+ dose: .init(description: "1000 IU", amount: 1000, unit: "IU"), purpose: purposes[2],+ requirements: "With breakfast")+ let metformin = try medicationService.createAsNeededMedication(+ name: "Metformin",+ dose: .init(description: "500 mg", amount: 500, unit: "mg"), purpose: purposes[1],+ requirements: "With breakfast")+ let minute =+ Calendar.current.component(.hour, from: Date()) * 60+ + Calendar.current.component(.minute, from: Date())+ for medication in [vitamin, metformin] {+ try ScheduleService(context: context).configure(+ medication,+ draft: .init(mode: .interval, intervalMinutes: 1440, firstReminderMinute: minute),+ reminders: false)+ }+ _ = try medicationService.createAsNeededMedication(+ name: "Levothyroxine",+ dose: .init(description: "50 mcg", amount: 50, unit: "mcg"), purpose: purposes[0])+ let skinMedication = try medicationService.createAsNeededMedication(+ name: "Hydrocortisone 1%",+ dose: .init(description: "Thin layer", amount: nil, unit: nil), purpose: purposes[4])+ let routineService = RoutineService(context: context)+ _ = try routineService.createTimed(+ name: "Eye drops", rounds: 3, durationSeconds: 60,+ instructions: "Synthetic reference: one step per round", purpose: purposes[5])+ let treatmentService = TreatmentService(context: context)+ let cleanse = try treatmentService.create(+ name: "Cleanse", instructions: "Synthetic reference care", purpose: purposes[4])+ let moisturise = try treatmentService.create(name: "Moisturiser", purpose: purposes[4])+ _ = try routineService.createOrdered(+ name: "Evening skin care",+ steps: [+ .init(kind: .treatment, targetID: cleanse.id),+ .init(kind: .medication, targetID: skinMedication.id),+ .init(kind: .treatment, targetID: moisturise.id)+ ],+ purpose: purposes[4], confirmedMedicationIDs: [skinMedication.id])+ let alex = try ProfileService(context: context).create(displayName: "Alex")+ if ProcessInfo.processInfo.environment["MEDDY_TEST_RECOGNITION_PHOTOS"] == "1" {+ let bytes = try recognitionPhoto()+ let service = MedicationPhotoService(context: context)+ for medication in [pain, vitamin, skinMedication] {+ try service.setPhoto(bytes, for: medication)+ }+ _ = try medicationService.createAsNeededMedication(name: pain.name, profileID: alex.id)+ }+ }++ private static func recognitionPhoto() throws -> Data {+ let renderer = UIGraphicsImageRenderer(size: CGSize(width: 80, height: 60))+ let bytes = renderer.jpegData(withCompressionQuality: 0.8) { context in+ UIColor.systemPurple.setFill()+ context.fill(CGRect(x: 0, y: 0, width: 80, height: 60))+ UIColor.white.setFill()+ context.cgContext.fillEllipse(in: CGRect(x: 20, y: 10, width: 40, height: 40))+ }+ return try MedicationPhotoProcessor.prepare(bytes)+ }+ }+#endif
diff --git a/Meddy/Meddy/Features/AsNeededLimitViews.swift b/Meddy/Meddy/Features/AsNeededLimitViews.swiftindex 1855fd5..83a74dc 100644--- a/Meddy/Meddy/Features/AsNeededLimitViews.swift+++ b/Meddy/Meddy/Features/AsNeededLimitViews.swift@@ -71,7 +71,7 @@ final class AsNeededLimitDraft { struct AsNeededLimitFields: View { @Bindable var draft: AsNeededLimitDraft var body: some View {- Section("As-needed limits") {+ MeddySection("As-needed limits") { Toggle("Use dose limits", isOn: $draft.enabled).accessibilityIdentifier("doseLimitsEnabled") if draft.enabled { TextField("Minimum interval (hours)", text: $draft.intervalHours).accessibilityIdentifier(@@ -91,7 +91,7 @@ struct AsNeededLimitFields: View { .caption) } }- }+ }.listRowBackground(MeddyStyle.surface) } } @@ -114,8 +114,8 @@ struct AsNeededLimitStatus: View { let result = AsNeededLimitService(context: context).check( medication, proposedDose: proposedDose, now: Date()) VStack(alignment: .leading, spacing: 4) {- Text(result.title).font(.headline).foregroundStyle(- result.state == .wait ? Color.orange : Color.primary)+ Text(result.title).font(.system(.title2, weight: .bold)).foregroundStyle(+ result.state == .wait ? MeddyStyle.warning : MeddyStyle.text) if let remaining = result.remainingAmount, result.issues.isEmpty { Text( "Remaining: \(remaining.formatted()) \(result.unit) in the last \(((result.windowSeconds ?? 86400) / 3600).formatted()) hours"
diff --git a/Meddy/Meddy/Features/CareEditors.swift b/Meddy/Meddy/Features/CareEditors.swiftindex c8227ba..8fc9659 100644--- a/Meddy/Meddy/Features/CareEditors.swift+++ b/Meddy/Meddy/Features/CareEditors.swift@@ -78,15 +78,15 @@ struct TreatmentEditor: View { Section { TextField("Name", text: $name) PurposeField(purpose: $purpose).environment(\.careProfileID, profileID)- }+ }.listRowBackground(MeddyStyle.surface) Section { TextField("Instructions", text: $instructions, axis: .vertical) TextField("Notes", text: $notes, axis: .vertical)- }+ }.listRowBackground(MeddyStyle.surface) if let error { Text(error).foregroundStyle(.red) } } .scrollDismissesKeyboard(.immediately)- .navigationTitle(treatment == nil ? "Add treatment" : "Edit treatment")+ .meddyScreen().navigationTitle(treatment == nil ? "Add treatment" : "Edit treatment") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("Save") { save() } }@@ -145,25 +145,25 @@ struct TimedRoutineEditor: View { Section { TextField("Name", text: $name) PurposeField(purpose: $purpose).environment(\.careProfileID, profileID)- }- Section("Timer") {+ }.listRowBackground(MeddyStyle.surface)+ MeddySection("Timer") { TextField("Number of rounds", text: $rounds).keyboardType(.numberPad) TextField("Seconds per round", text: $seconds).keyboardType(.numberPad) Text("Each round starts only when you choose Start or Start next round.").font(.caption) .foregroundStyle(.secondary)- }+ }.listRowBackground(MeddyStyle.surface) Section { TextField("Instructions", text: $instructions, axis: .vertical) TextField("Between-round instructions", text: $between, axis: .vertical)- }+ }.listRowBackground(MeddyStyle.surface) Section { Text("Existing sessions keep their saved timer settings.").font(.caption).foregroundStyle( .secondary)- }+ }.listRowBackground(MeddyStyle.surface) if let error { Text(error).foregroundStyle(.red) } } .scrollDismissesKeyboard(.immediately)- .navigationTitle(routine == nil ? "Add timed routine" : "Edit timed routine")+ .meddyScreen().navigationTitle(routine == nil ? "Add timed routine" : "Edit timed routine") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("Save", action: save) }@@ -294,8 +294,8 @@ struct OrderedRoutineEditor: View { TextField("Name", text: $name) PurposeField(purpose: $purpose).environment(\.careProfileID, profileID) TextField("Instructions", text: $instructions, axis: .vertical)- }- Section("Ordered steps") {+ }.listRowBackground(MeddyStyle.surface)+ MeddySection("Ordered steps") { ForEach(Array(steps.enumerated()), id: \.element.id) { index, step in VStack(alignment: .leading) { Text("\(index + 1). \(targetName(step))")@@ -313,17 +313,17 @@ struct OrderedRoutineEditor: View { }.onMove { indices, destination in steps.move(fromOffsets: indices, toOffset: destination) } Menu("Add existing step", systemImage: "plus") {- Section("Treatment items") {+ MeddySection("Treatment items") { ForEach(treatments.filter(\.isActive)) { item in Button(item.name) { steps.append(.init(kind: .treatment, targetID: item.id)) } }- }- Section("Timed routines") {+ }.listRowBackground(MeddyStyle.surface)+ MeddySection("Timed routines") { ForEach(routines.filter { $0.isActive && $0.kindRaw == "timedRounds" }) { item in Button(item.name) { steps.append(.init(kind: .timedRoutine, targetID: item.id)) } }- }- Section("Medications") {+ }.listRowBackground(MeddyStyle.surface)+ MeddySection("Medications") { ForEach(medications.filter(\.isActive)) { item in Button { steps.append(.init(kind: .medication, targetID: item.id))@@ -335,16 +335,16 @@ struct OrderedRoutineEditor: View { } .disabled(medicationIDs.contains(item.id)) }- }+ }.listRowBackground(MeddyStyle.surface) } Menu("Create an item") { Button("Treatment item") { addingTreatment = true } Button("Timed routine") { addingTimed = true } Button("Medication") { addingMedication = true } }- }+ }.listRowBackground(MeddyStyle.surface) if !addedMedicationIDs.isEmpty {- Section("Medication reminder ownership") {+ MeddySection("Medication reminder ownership") { ForEach(medications.filter { addedMedicationIDs.contains($0.id) }) { Text($0.name) } Text( "Saving will cancel their standalone reminders and snoozes. History is preserved; this routine will own their reminders."@@ -368,10 +368,10 @@ struct OrderedRoutineEditor: View { })) } Toggle("Confirm ownership change", isOn: $ownershipConfirmed)- }+ }.listRowBackground(MeddyStyle.surface) } if !removedMedicationIDs.isEmpty {- Section("Removed medications") {+ MeddySection("Removed medications") { ForEach(medications.filter { removedMedicationIDs.contains($0.id) }) { item in Toggle( "Return \(item.name) to As needed",@@ -388,9 +388,9 @@ struct OrderedRoutineEditor: View { Text( "No old schedule or reminders are restored. Unfinished saved medication steps need explicit resolution first." ).font(.caption)- }+ }.listRowBackground(MeddyStyle.surface) }- Section("Group schedule") {+ MeddySection("Group schedule") { Toggle("Daily sessions", isOn: $scheduled) if scheduled { TextField("Daily session count", text: $slotCount).keyboardType(.numberPad)@@ -438,11 +438,11 @@ struct OrderedRoutineEditor: View { """ ).font(.caption).foregroundStyle(.secondary) }- }+ }.listRowBackground(MeddyStyle.surface) if let error { Text(error).foregroundStyle(.red) } } .scrollDismissesKeyboard(.immediately)- .navigationTitle(routine == nil ? "Add ordered routine" : "Edit ordered routine")+ .meddyScreen().navigationTitle(routine == nil ? "Add ordered routine" : "Edit ordered routine") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("Save", action: save) }
diff --git a/Meddy/Meddy/Features/ConsultationMarkdown.swift b/Meddy/Meddy/Features/ConsultationMarkdown.swiftindex af06cbd..ca5cf13 100644--- a/Meddy/Meddy/Features/ConsultationMarkdown.swift+++ b/Meddy/Meddy/Features/ConsultationMarkdown.swift@@ -10,6 +10,7 @@ nonisolated struct ConsultationMedication: Sendable { var method: String var requirements: String var schedule: String+ var prescription: PrescriptionDetails? } nonisolated struct ConsultationMarkdownExport: Transferable {@@ -61,6 +62,12 @@ nonisolated enum ConsultationMarkdown { lines.append("- **Requirements:** \(inline(medication.requirements))") } lines.append("- **Schedule:** \(inline(medication.schedule))")+ if let prescription = medication.prescription {+ if let date = prescription.prescribedOn { lines.append("- **Prescribed on:** \(inline(date))") }+ if let prescriber = prescription.prescribedBy { lines.append("- **Prescribed by:** \(inline(prescriber))") }+ if let days = prescription.supplyDurationDays { lines.append("- **Supply lasts (days):** \(days)") }+ if let repeats = prescription.repeatsLeft { lines.append("- **Repeats left:** \(repeats)") }+ } lines.append("") } if ordered.isEmpty { lines += ["No active medications recorded.", ""] }
diff --git a/Meddy/Meddy/Features/MedicationDetailView.swift b/Meddy/Meddy/Features/MedicationDetailView.swiftnew file mode 100644index 0000000..e90a41f--- /dev/null+++ b/Meddy/Meddy/Features/MedicationDetailView.swift@@ -0,0 +1,173 @@+import SwiftData+import SwiftUI++struct MedicationDetailView: View {+ @Environment(\.modelContext) private var context+ @Environment(\.snoozeMedication) private var snoozeMedication+ let medication: Medication+ @State private var editing = false+ @State private var logDetails = false+ @State private var editingEvent: Administration?+ @State private var error: String?+ @State private var lastSaved: Administration?+ @ScaledMetric(relativeTo: .largeTitle) private var titleSize = 30++ private var service: MedicationService { MedicationService(context: context) }++ private var palette: PurposePalette { PurposePalette(medication.purpose?.name) }+ private var check: DoseLimitCheck { AsNeededLimitService(context: context).check(medication) }+ var body: some View {+ let check = self.check+ List {+ VStack(alignment: .leading, spacing: 10) {+ Text(medication.name).font(.system(size: titleSize, weight: .bold))+ HStack {+ Text(medication.defaultDose.displayText).font(.subheadline).foregroundStyle(+ MeddyStyle.secondary)+ PurposeTag(name: medication.purpose?.name)+ }+ MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name, size: 220)+ .frame(maxWidth: .infinity)+ Button(medication.recognitionPhotoData == nil ? "Add recognition photo" : "Change recognition photo") {+ editing = true+ }+ }.listRowBackground(Color.clear).listRowSeparator(.hidden)+ VStack(alignment: .leading, spacing: 16) {+ if medication.scheduleTypeRaw == "asNeeded" {+ Text("DOSE CHECK").font(.caption.bold()).tracking(1.44).foregroundStyle(palette.ink)+ AsNeededLimitStatus(medication: medication)+ if let max = check.maximumAmount, let amount = check.knownAmount, max > 0 {+ DoseQuantityProgress(amount: amount, maximum: max, palette: palette)+ Text(+ "\(amount.formatted()) of \(max.formatted()) \(check.unit) in the configured window"+ )+ .font(.caption).foregroundStyle(palette.ink)+ }+ Button(check.state == .wait ? "Log dose anyway" : "Log dose") { logDetails = true }+ .buttonStyle(MeddyPrimaryButtonStyle(fill: palette.ink, ink: palette.surface))+ } else {+ Text("NEXT DOSE").font(.caption.bold()).tracking(1.44).foregroundStyle(palette.ink)+ if let result = try? MedicationPresentation.result(medication, context: context),+ let next = result.next {+ Text(+ next <= Date()+ ? "Due now" : "Next dose " + next.formatted(date: .omitted, time: .shortened)+ )+ .font(.system(.title2, weight: .bold))+ } else {+ Text(medication.managedByRoutineID == nil ? "Your recorded care" : "Managed by routine")+ .font(.title2.bold())+ }+ if medication.isActive {+ Button(medication.managedByRoutineID == nil ? "Take" : "Log outside routine") { take() }+ .buttonStyle(MeddyPrimaryButtonStyle(fill: palette.ink, ink: palette.surface))+ }+ Button("Log details…") { logDetails = true }+ if medication.isActive, medication.remindersEnabled, medication.managedByRoutineID == nil {+ Button("Remind me later") { snoozeMedication(medication.id) }+ }+ }+ if let event = lastSaved, !event.isDeleted {+ Button("Undo Taken") {+ perform {+ try service.delete(event)+ lastSaved = nil+ }+ }+ }+ }.meddyCard(fill: palette.surface).listRowInsets(+ EdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0)+ )+ .listRowBackground(Color.clear).listRowSeparator(.hidden)+ MeddySection("How to take", fill: .clear) {+ if !medication.administrationMethod.isEmpty { Text(medication.administrationMethod) }+ if !medication.requirements.isEmpty { Text(medication.requirements) }+ if !medication.notes.isEmpty { Text(medication.notes) }+ }+ PrescriptionSection(medication: medication)+ MeddySection("Today", fill: .clear) {+ if medication.visibleAdministrations.isEmpty {+ Text("Not logged yet").foregroundStyle(MeddyStyle.secondary)+ }+ ForEach(+ medication.visibleAdministrations.filter {+ ScheduleCalendar.sameDay($0.timestamp, Date(), calendar: .current)+ }+ ) { event in+ historyRow(event)+ }+ NavigationLink("Full history") {+ List {+ let history = Dictionary(grouping: medication.visibleAdministrations) {+ ScheduleCalendar.localDate($0.timestamp, calendar: .current)+ }+ ForEach(history.keys.sorted(by: >), id: \.self) { day in+ Section(day) { ForEach(history[day] ?? []) { event in historyRow(event) } }+ }+ }.meddyScreen().navigationTitle("Administration history")+ }+ }+ MeddySection("Settings") {+ HStack {+ Text("Schedule")+ Spacer()+ Text((MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded).title)+ .foregroundStyle(MeddyStyle.secondary)+ }+ if let followup = try? MedicationFollowupService.configuration(medication) {+ VStack(alignment: .leading, spacing: 6) {+ Text("Follow-up")+ Text(followup.message).foregroundStyle(MeddyStyle.secondary)+ Text(+ "\((followup.delaySeconds / 60).formatted()) minutes after the recorded taken time"+ ).font(.caption)+ }+ }+ Button(medication.isActive ? "Archive" : "Reactivate") {+ perform { try service.setActive(medication, !medication.isActive) }+ }.foregroundStyle(Color("MeddyDestructive"))+ }+ }.meddyScreen()+ .navigationTitle(medication.name)+ .navigationBarTitleDisplayMode(.inline)+ .toolbar(.visible, for: .navigationBar)+ .toolbar { Button("Edit") { editing = true } }+ .sheet(isPresented: $editing) { MedicationEditor(medication: medication) }+ .sheet(isPresented: $logDetails) {+ AdministrationEditor(medication: medication, onSaved: { lastSaved = $0.first })+ }+ .sheet(item: $editingEvent) { AdministrationEditor(medication: medication, event: $0) }+ .alert(+ "Could not save",+ isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+ ) {+ Button("OK") { error = nil }+ } message: {+ Text(error ?? "")+ }+ }++ private func take() {+ perform {+ lastSaved = try TodayMedicationAction.take([medication], at: Date(), context: context).first+ }+ }+ private func historyRow(_ event: Administration) -> some View {+ HStack(spacing: 16) {+ Text(event.timestamp, style: .time).monospacedDigit().frame(width: 66, alignment: .leading)+ Text(event.recordedDose.displayText).font(.subheadline)+ Spacer()+ Button("Edit") { editingEvent = event }.buttonStyle(.borderless)+ }.swipeActions {+ Button("Delete", role: .destructive) {+ perform {+ try RoutineSessionService(context: context).correct(+ event, timestamp: event.timestamp, dose: event.recordedDose, delete: true)+ }+ }+ }+ }+ private func perform(_ work: () throws -> Void) {+ do { try work() } catch { self.error = error.localizedDescription }+ }+}
diff --git a/Meddy/Meddy/Features/MedicationFollowupFields.swift b/Meddy/Meddy/Features/MedicationFollowupFields.swiftindex 05c6fa3..8f1538f 100644--- a/Meddy/Meddy/Features/MedicationFollowupFields.swift+++ b/Meddy/Meddy/Features/MedicationFollowupFields.swift@@ -44,7 +44,7 @@ struct MedicationFollowupFields: View { @Bindable var draft: MedicationFollowupDraft @State private var permissionMessage: String? var body: some View {- Section("After recording taken") {+ MeddySection("After recording taken") { Toggle("Follow-up notification", isOn: $draft.enabled).accessibilityIdentifier( "followupEnabled" )@@ -72,6 +72,6 @@ struct MedicationFollowupFields: View { ).font(.caption).foregroundStyle(.secondary) } if let permissionMessage { Text(permissionMessage).font(.caption) }- }+ }.listRowBackground(MeddyStyle.surface) } }
diff --git a/Meddy/Meddy/Features/MedicationPhoto.swift b/Meddy/Meddy/Features/MedicationPhoto.swiftindex c9eb690..61c8c7e 100644--- a/Meddy/Meddy/Features/MedicationPhoto.swift+++ b/Meddy/Meddy/Features/MedicationPhoto.swift@@ -112,10 +112,11 @@ struct MedicationPhotoEditor: View { let name: String var body: some View { let pickerTitle = draft.data == nil ? "Add photo" : "Replace photo"- Section("Recognition photo") {+ MeddySection("Recognition photo") { if draft.data != nil { MedicationPhotoView(data: draft.data, name: name, size: 160) } PhotosPicker(selection: $selection, matching: .images, preferredItemEncoding: .current) {- Label(pickerTitle, systemImage: "photo")+ Label(pickerTitle, systemImage: "photo").frame(maxWidth: .infinity).padding(.vertical, 20)+ .overlay(RoundedRectangle(cornerRadius: 16).stroke(MeddyStyle.border, style: StrokeStyle(lineWidth: 1.5, dash: [5]))) } if draft.data != nil { Button("Remove photo", role: .destructive) {@@ -127,7 +128,7 @@ struct MedicationPhotoEditor: View { if let error = draft.error { Text(error).foregroundStyle(.red) } Text("Optional photo for recognition. Changes are kept when you save.").font(.caption) .foregroundStyle(.secondary)- }+ }.listRowBackground(MeddyStyle.surface) .task(id: selection) { guard let selection else { return } await draft.load { try await selection.loadTransferable(type: Data.self) }
diff --git a/Meddy/Meddy/Features/MedicationScheduleFields.swift b/Meddy/Meddy/Features/MedicationScheduleFields.swiftindex 940d514..875a051 100644--- a/Meddy/Meddy/Features/MedicationScheduleFields.swift+++ b/Meddy/Meddy/Features/MedicationScheduleFields.swift@@ -29,14 +29,18 @@ struct MedicationScheduleFields: View { @State private var permissionMessage: String? var body: some View {- Section("Schedule") {- Picker("Schedule", selection: $mode) {- ForEach(MedicationScheduleType.allCases.filter { $0 != .routineManaged }, id: \.self) {- Text($0.title).tag($0)+ MeddySection("Schedule") {+ MeddyWrap {+ ForEach(MedicationScheduleType.allCases.filter { $0 != .routineManaged }, id: \.self) { item in+ Button(item.title) { mode = item }.font(.subheadline.weight(.semibold))+ .padding(.horizontal, 12).padding(.vertical, 9)+ .foregroundStyle(mode == item ? MeddyStyle.onAccent : MeddyStyle.accent)+ .background(mode == item ? MeddyStyle.accent : MeddyStyle.control, in: Capsule())+ .accessibilityAddTraits(mode == item ? .isSelected : [])+ .accessibilityIdentifier("scheduleType_" + item.rawValue) }- }.accessibilityIdentifier("medicationSchedulePicker").onChange(of: mode) { _, value in- if value == .asNeeded { reminders = false }- }+ }.buttonStyle(.plain)+ .onChange(of: mode) { _, value in if value == .asNeeded { reminders = false } } switch mode { case .spreadThroughDay: TextField("Doses per day", text: $doses).keyboardType(.numberPad)@@ -87,7 +91,7 @@ struct MedicationScheduleFields: View { ).font(.caption).foregroundStyle(.secondary) } if let permissionMessage { Text(permissionMessage).font(.caption) }- }+ }.listRowBackground(MeddyStyle.surface) } func draft() throws -> MedicationScheduleDraft {@@ -180,7 +184,7 @@ enum MedicationPresentation { id: item.id, purpose: item.purpose?.name ?? "Ungrouped", name: item.name, dose: item.defaultDose == .unknown ? nil : item.defaultDose.displayText, method: item.administrationMethod, requirements: item.requirements,- schedule: scheduleLabel(item, routines: routines))+ schedule: scheduleLabel(item, routines: routines), prescription: PrescriptionService.details(item)) } return ConsultationMarkdown.make( active, preparedAt: preparedAt, timeZone: timeZone, profileID: profileID,
diff --git a/Meddy/Meddy/Features/PhoneTimerControl.swift b/Meddy/Meddy/Features/PhoneTimerControl.swiftindex 0014b2d..2b04f50 100644--- a/Meddy/Meddy/Features/PhoneTimerControl.swift+++ b/Meddy/Meddy/Features/PhoneTimerControl.swift@@ -3,6 +3,7 @@ import Foundation /// Presentation only: the session service owns all timer transitions and deadlines. nonisolated struct PhoneTimerControl { let phase: TimerPhase+ let round: Int let title: String let countdown: String? let instruction: String@@ -11,7 +12,7 @@ nonisolated struct PhoneTimerControl { init(checkpoint: TimerCheckpoint, clock: ClockSample) { phase = checkpoint.phase- let round = min(checkpoint.roundIndex + (phase == .waiting ? 2 : 1), checkpoint.roundCount)+ round = min(checkpoint.roundIndex + (phase == .waiting ? 2 : 1), checkpoint.roundCount) let remaining = ceil(checkpoint.remaining(at: clock)) let time = String( format: "%02.0f:%02.0f", floor(remaining / 60), remaining.truncatingRemainder(dividingBy: 60))
diff --git a/Meddy/Meddy/Features/PrescriptionFields.swift b/Meddy/Meddy/Features/PrescriptionFields.swiftnew file mode 100644index 0000000..c606316--- /dev/null+++ b/Meddy/Meddy/Features/PrescriptionFields.swift@@ -0,0 +1,143 @@+import SwiftData+import SwiftUI++@MainActor @Observable final class PrescriptionDraft {+ var hasDate: Bool+ var date: Date+ var prescriber: String+ var days: String+ var repeats: String+ private let original: PrescriptionDetails+ private let capture: PrescriptionCapture?+ private let editingExisting: Bool+ init(medication: Medication?) {+ editingExisting = medication != nil+ original = medication.map(PrescriptionService.details) ?? .init()+ hasDate = original.prescribedOn != nil+ date = original.prescribedOn.flatMap(PrescriptionDate.date) ?? PrescriptionDate.today+ prescriber = original.prescribedBy ?? ""+ days = original.supplyDurationDays.map(String.init) ?? ""+ repeats = original.repeatsLeft.map(String.init) ?? ""+ capture = medication.flatMap { item in+ item.modelContext.flatMap { try? PrescriptionService(context: $0).capture(item) }+ }+ }+ func value() throws -> PrescriptionDetails {+ func number(_ input: String, error: PrescriptionError) throws -> Int? {+ let clean = input.trimmingCharacters(in: .whitespacesAndNewlines)+ if clean.isEmpty { return nil }+ guard clean.allSatisfy({ $0.isASCII && $0.isNumber }), let value = Int(clean) else { throw error }+ return value+ }+ let text = prescriber.trimmingCharacters(in: .whitespacesAndNewlines)+ let result = try PrescriptionDetails(+ prescribedOn: hasDate ? PrescriptionDate.string(date) : nil,+ prescribedBy: text.isEmpty ? nil : text,+ supplyDurationDays: number(days, error: .invalidDays),+ repeatsLeft: number(repeats, error: .invalidRepeats))+ try result.validate()+ return result+ }+ func apply(to medication: Medication, context: ModelContext) throws {+ _ = try ProfileAccess.owner(medication, context: context)+ if let capture {+ guard capture.medicationID == medication.id else { throw ProfileError.conflictingOwnership }+ try ProfileAccess.action(+ capture.profileID, version: ProfileIdentity.ownershipVersion, lifecycle: capture.lifecycleID,+ target: medication, context: context)+ } else if editingExisting {+ throw ProfileError.unknownOwner+ }+ let entered = try value()+ let current = PrescriptionService.details(medication)+ func merge<T: Equatable>(_ old: T, _ next: T, _ saved: T) throws -> T {+ guard next != old else { return saved }+ guard saved == old || saved == next else { throw PrescriptionError.changed }+ return next+ }+ let result = try PrescriptionDetails(+ prescribedOn: merge(original.prescribedOn, entered.prescribedOn, current.prescribedOn),+ prescribedBy: merge(original.prescribedBy, entered.prescribedBy, current.prescribedBy),+ supplyDurationDays: merge(original.supplyDurationDays, entered.supplyDurationDays, current.supplyDurationDays),+ repeatsLeft: merge(original.repeatsLeft, entered.repeatsLeft, current.repeatsLeft))+ guard result != current else { return }+ medication.prescribedOn = result.prescribedOn+ medication.prescribedBy = result.prescribedBy+ medication.supplyDurationDays = result.supplyDurationDays+ medication.repeatsLeft = result.repeatsLeft+ medication.prescriptionRevision = UUID()+ }+}++struct PrescriptionFields: View {+ @Bindable var draft: PrescriptionDraft+ var body: some View {+ MeddySection("Prescription") {+ Toggle("Record prescription date", isOn: $draft.hasDate)+ .accessibilityIdentifier("prescriptionHasDate")+ if draft.hasDate {+ DatePicker("Prescribed on", selection: $draft.date, displayedComponents: .date)+ .environment(\.calendar, PrescriptionDate.calendar)+ .environment(\.timeZone, PrescriptionDate.calendar.timeZone)+ .accessibilityIdentifier("prescriptionDate")+ }+ TextField("Prescribed by (doctor or clinic)", text: $draft.prescriber)+ .accessibilityIdentifier("prescriptionPrescriber")+ TextField("Supply lasts (days)", text: $draft.days).keyboardType(.numberPad)+ .accessibilityIdentifier("prescriptionDays")+ TextField("Repeats left", text: $draft.repeats).keyboardType(.numberPad)+ .accessibilityIdentifier("prescriptionRepeats")+ Text("Optional. Supply duration is your entered information; it does not change dose schedules.")+ .font(.caption).foregroundStyle(MeddyStyle.secondary)+ }.listRowBackground(MeddyStyle.surface)+ }+}++struct PrescriptionSection: View {+ @Environment(\.modelContext) private var context+ let medication: Medication+ @State private var undo: PrescriptionUndo?+ @State private var error: String?+ @State private var saving = false+ var body: some View {+ let details = PrescriptionService.details(medication)+ if !details.isEmpty {+ MeddySection("Prescription", fill: .clear) {+ if let date = details.prescribedOn.flatMap(PrescriptionDate.date) {+ LabeledContent("Prescribed on", value: date.formatted(+ Date.FormatStyle(date: .abbreviated, time: .omitted, calendar: PrescriptionDate.calendar,+ timeZone: PrescriptionDate.calendar.timeZone)))+ }+ if let prescriber = details.prescribedBy { LabeledContent("Prescribed by", value: prescriber) }+ if let days = details.supplyDurationDays { LabeledContent("Supply lasts", value: "\(days) days") }+ if let repeats = details.repeatsLeft {+ LabeledContent("Repeats left", value: String(repeats)).accessibilityIdentifier("repeatsLeftValue")+ if medication.isActive {+ Button("−1 repeat") {+ perform {+ let service = PrescriptionService(context: context)+ undo = try service.decrement(service.capture(medication))+ }+ }.disabled(repeats <= 0 || saving)+ .accessibilityLabel("Lower repeats left by one").accessibilityIdentifier("lowerRepeats")+ }+ }+ if let undo, medication.isActive, medication.prescriptionRevision == undo.savedRevision {+ Button("Undo repeat change") {+ perform {+ try PrescriptionService(context: context).undo(undo)+ self.undo = nil+ }+ }.disabled(saving).accessibilityIdentifier("undoRepeatChange")+ }+ if let error { Text(error).foregroundStyle(Color("MeddyDestructive")) }+ }+ }+ }+ private func perform(_ work: () throws -> Void) {+ guard !saving else { return }+ saving = true+ defer { saving = false }+ do { try work(); error = nil } catch { self.error = error.localizedDescription }+ }+}
diff --git a/Meddy/Meddy/Features/ProfileViews.swift b/Meddy/Meddy/Features/ProfileViews.swiftindex f9c5ef6..500358f 100644--- a/Meddy/Meddy/Features/ProfileViews.swift+++ b/Meddy/Meddy/Features/ProfileViews.swift@@ -13,36 +13,108 @@ struct ProfilePicker: View { @Environment(\.modelContext) private var context @Query private var profiles: [CareProfile] @Binding var selection: UUID- @State private var managing = false- private var active: [CareProfile] {- profiles.filter { $0.archivedAt == nil }.sorted { left, right in- left.id != right.id- && (left.id == ProfileIdentity.me- || right.id != ProfileIdentity.me && (left.label, left.id.uuidString) < (right.label, right.id.uuidString))- }- }+ var cloud: CloudSyncMonitor?+ @State private var showing = false+ private var active: [CareProfile] { profiles.filter { $0.archivedAt == nil } } var body: some View {- HStack {- Menu {- Picker("Care profile", selection: $selection) {- ForEach(active) { Text($0.label).tag($0.id) }- }- Button("Manage profiles…") { managing = true }- } label: {- Label(- "Profile: " + (active.first { $0.id == selection }?.label ?? "Me"),- systemImage: "person.crop.circle")- }- .accessibilityIdentifier("careProfilePicker")- Spacer()- }.padding(.horizontal).padding(.vertical, 6)- .sheet(isPresented: $managing) { ProfileManagement(selection: $selection) }+ let label = active.first { $0.id == selection }?.label ?? "Me"+ Button {+ showing = true+ } label: {+ Text(String(label.prefix(2)).uppercased()).font(.subheadline.bold()).frame(+ width: 40, height: 40+ )+ .foregroundStyle(MeddyStyle.accent).background(MeddyStyle.control, in: Circle())+ .overlay(Circle().stroke(MeddyStyle.border, lineWidth: 1.5))+ }.accessibilityIdentifier("careProfilePicker").accessibilityLabel("Profile: " + label)+ .sheet(isPresented: $showing) { ProfilesSheet(selection: $selection, cloud: cloud) } .onChange(of: profiles.map { $0.id.uuidString + String($0.archivedAt != nil) }) { _, _ in if !active.contains(where: { $0.id == selection }) { selection = ProfileIdentity.me } } } } +struct ProfilesSheet: View {+ @Environment(\.modelContext) private var context+ @Environment(\.dismiss) private var dismiss+ @Query private var profiles: [CareProfile]+ @Query private var medications: [Medication]+ @Query private var routines: [Routine]+ @Binding var selection: UUID+ var cloud: CloudSyncMonitor?+ @State private var adding = false+ @State private var managing = false+ var body: some View {+ NavigationStack {+ ScrollView {+ VStack(alignment: .leading, spacing: 12) {+ MeddySectionLabel(text: "Tracking for")+ ForEach(+ profiles.filter { $0.archivedAt == nil }.sorted {+ $0.id == ProfileIdentity.me && $1.id != ProfileIdentity.me+ || $0.id != ProfileIdentity.me && $1.id != ProfileIdentity.me && $0.label < $1.label+ }+ ) { profile in+ Button {+ selection = profile.id+ dismiss()+ } label: {+ HStack(spacing: 12) {+ Text(String(profile.label.prefix(2)).uppercased()).font(.headline)+ .frame(width: 44, height: 44).background(MeddyStyle.control, in: Circle())+ VStack(alignment: .leading, spacing: 4) {+ Text(profile.label).font(.headline)+ Text(+ "\(medications.filter { $0.isActive && ProfileAccess.visible($0, for: profile.id, context: context) }.count) medications · \(routines.filter { $0.isActive && ProfileAccess.visible($0, for: profile.id, context: context) }.count) routines"+ )+ .font(.caption).foregroundStyle(MeddyStyle.secondary)+ }+ Spacer()+ if profile.id == selection {+ Image(systemName: "checkmark.circle.fill").foregroundStyle(MeddyStyle.accent)+ }+ }.meddyCard(radius: 22, padding: 16)+ .overlay(+ RoundedRectangle(cornerRadius: 22).stroke(+ profile.id == selection ? MeddyStyle.accent : .clear, lineWidth: 2))+ }.buttonStyle(.plain).accessibilityLabel(profile.label).accessibilityIdentifier(+ "careProfile_" + profile.id.uuidString)+ }+ Button {+ adding = true+ } label: {+ Label("Add profile", systemImage: "plus").frame(maxWidth: .infinity).padding(18)+ .overlay(+ RoundedRectangle(cornerRadius: 18).stroke(+ MeddyStyle.border, style: StrokeStyle(lineWidth: 1.5, dash: [5])))+ }.accessibilityIdentifier("addProfileFromPicker")+ MeddySectionLabel(text: "Sync")+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Circle().fill(cloud?.needsAttention == true ? MeddyStyle.warning : MeddyStyle.success)+ .frame(width: 8, height: 8)+ Text(cloud?.message ?? "Isolated preview store").font(.subheadline)+ }+ if let date = cloud?.lastSuccessfulSync {+ Text(date, style: .relative).font(.caption).foregroundStyle(MeddyStyle.secondary)+ }+ if cloud?.needsAttention == true { Button("Retry") { cloud?.refresh() } }+ }.meddyCard(radius: 22, padding: 16)+ MeddySectionLabel(text: "More")+ VStack(alignment: .leading, spacing: 18) {+ NavigationLink("Share list for appointment") { CurrentMedicationsView() }+ Divider()+ Button("Manage profiles…") { managing = true }+ }.meddyCard(radius: 22, padding: 18)+ }.padding(24)+ }.meddyScreen().navigationTitle("Profiles").navigationBarTitleDisplayMode(.inline)+ .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }+ .sheet(isPresented: $adding) { ProfileNameEditor { selection = $0.id } }+ .sheet(isPresented: $managing) { ProfileManagement(selection: $selection) }+ }.presentationDragIndicator(.visible).presentationCornerRadius(28)+ }+}+ struct ProfileManagement: View { @Environment(\.modelContext) private var context @Environment(\.dismiss) private var dismiss@@ -58,7 +130,7 @@ struct ProfileManagement: View { Text( "Each profile keeps separate care and history. Update all active Meddy copies before using dependants." ).font(.caption)- }+ }.listRowBackground(MeddyStyle.surface) ForEach( profiles.sorted { $0.id != $1.id@@ -90,7 +162,7 @@ struct ProfileManagement: View { Button("Add dependant", systemImage: "plus") { adding = true }.accessibilityIdentifier( "addDependant") if let error { Text(error).foregroundStyle(.red) }- }.navigationTitle("Care profiles")+ }.meddyScreen().navigationTitle("Care profiles") .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } } .sheet(isPresented: $adding) { ProfileNameEditor { selection = $0.id } } .sheet(item: $editing) { profile in ProfileNameEditor(profile: profile) { _ in } }@@ -117,6 +189,7 @@ struct ProfileNameEditor: View { "profileDisplayName") if let error { Text(error).foregroundStyle(.red) } }+ .meddyScreen() .navigationTitle(profile == nil ? "Add dependant" : "Rename profile") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
diff --git a/Meddy/Meddy/Features/RoutineHeroCard.swift b/Meddy/Meddy/Features/RoutineHeroCard.swiftnew file mode 100644index 0000000..a6050a9--- /dev/null+++ b/Meddy/Meddy/Features/RoutineHeroCard.swift@@ -0,0 +1,94 @@+import SwiftData+import SwiftUI++struct RoutineHeroCard: View {+ @Environment(\.modelContext) private var context+ let routine: Routine+ let run: RoutineRun?+ var actionTitle: String?+ var start: (() -> Void)?+ private var palette: PurposePalette { PurposePalette(routine.purpose?.name) }+ private var savedDefinition: FrozenRoutineDefinition? {+ if let run { return try? RoutineSessionService(context: context).definition(run) }+ return try? RoutineService(context: context).freeze(routine)+ }+ var body: some View {+ let definition = savedDefinition+ let timed = definition?.kind == .timedRounds || run == nil && routine.kindRaw == "timedRounds"+ let checkpoint =+ timed ? run.flatMap { try? RoutineSessionService(context: context).timer($0) } : nil+ let progress =+ timed ? nil : run.flatMap { try? RoutineSessionService(context: context).progress($0) }+ VStack(alignment: .leading, spacing: 14) {+ HStack(spacing: 20) {+ if timed {+ if checkpoint?.phase == .running {+ TimelineView(.periodic(from: .now, by: 1)) { _ in+ timerSummary(checkpoint, definition: definition)+ }+ } else {+ timerSummary(checkpoint, definition: definition)+ }+ }+ VStack(alignment: .leading, spacing: 10) {+ Text(timed ? "TIMED" : "ORDERED").font(.caption.bold()).tracking(1.44).foregroundStyle(+ palette.ink)+ Text(definition?.name ?? (run == nil ? routine.name : "Saved plan needs review")).font(+ .system(.title3, weight: .bold))+ if let instruction = definition?.instructions, !instruction.isEmpty {+ Text(instruction).font(.subheadline).foregroundStyle(palette.ink).lineLimit(1)+ }+ if timed, let start {+ Button(actionTitle ?? (run == nil ? "Start" : "Open saved timer"), action: start)+ .buttonStyle(MeddyOutlineButtonStyle(ink: palette.ink))+ }+ }+ }+ if !timed {+ MeddyWrap {+ ForEach(definition?.steps ?? []) { step in+ let state = progress?.steps.first { $0.id == step.id }+ Text(step.name).font(.subheadline.weight(.semibold)).strikethrough(+ state?.state == .completed+ )+ .padding(.horizontal, 12).padding(.vertical, 7)+ .foregroundStyle(progress?.nextReadyStepID == step.id ? palette.surface : palette.ink)+ .background(+ progress?.nextReadyStepID == step.id ? palette.ink : palette.track, in: Capsule()+ )+ .opacity(state?.state == .completed ? 0.7 : 1)+ }+ }+ if let start {+ Button(actionTitle ?? (run == nil ? "Start session" : "Continue session"), action: start)+ .buttonStyle(MeddyOutlineButtonStyle(ink: palette.ink))+ }+ }+ }.meddyCard(fill: palette.surface, padding: 20)+ }+ private func timerSummary(_ checkpoint: TimerCheckpoint?, definition: FrozenRoutineDefinition?)+ -> some View {+ let clock = ExecutionClock.sample()+ let presentation = checkpoint.map { PhoneTimerControl(checkpoint: $0, clock: clock) }+ let duration = checkpoint?.durationSeconds ?? Double(definition?.roundDurationSeconds ?? 0)+ let remaining = checkpoint?.remaining(at: clock) ?? duration+ return MeddyProgressRing(+ progress: checkpoint?.phase == .completed ? 1 : 1 - remaining / max(1, duration),+ palette: palette+ ) {+ VStack(spacing: 4) {+ Text(+ presentation?.countdown+ ?? String(+ format: "%02.0f:%02.0f", floor(duration / 60),+ duration.truncatingRemainder(dividingBy: 60))+ )+ .font(.system(.title2, weight: .bold)).monospacedDigit()+ Text(+ presentation.map { "round \($0.round)/\(checkpoint?.roundCount ?? 0)" }+ ?? "round 1/\(definition?.roundCount ?? 0)"+ ).font(.caption2)+ }.foregroundStyle(palette.ink)+ }.frame(width: 108, height: 108)+ }+}
diff --git a/Meddy/Meddy/Features/RoutineRunView.swift b/Meddy/Meddy/Features/RoutineRunView.swiftindex 03ad899..6c1a36a 100644--- a/Meddy/Meddy/Features/RoutineRunView.swift+++ b/Meddy/Meddy/Features/RoutineRunView.swift@@ -64,6 +64,7 @@ struct RoutineRunView: View { } } .navigationTitle(definition?.name ?? "Saved session")+ .navigationBarTitleDisplayMode(.inline) .navigationDestination(item: $timerDestination) { TimerRunView(run: $0) } .onAppear { perform { try service.reconcile(run) } } .sheet(item: $correctingTreatment) { TreatmentCompletionEditor(event: $0) }@@ -94,107 +95,193 @@ struct RoutineRunView: View { @ViewBuilder private func orderedContent(_ definition: FrozenRoutineDefinition) -> some View { if let progress {- List {- sessionHeading(definition, progress: progress)- ForEach(definition.steps) { step in- if let state = progress.steps.first(where: { $0.id == step.id }) {- Section("\(step.position + 1). \(step.name)") {+ let palette = PurposePalette(run.routine?.purpose?.name)+ ScrollView {+ VStack(alignment: .leading, spacing: 16) {+ HStack(spacing: 5) {+ ForEach(progress.steps) { state in+ Capsule().fill(+ state.state == .completed+ ? palette.ink : state.id == progress.nextReadyStepID ? palette.dot : palette.track+ ).frame(height: 6)+ }+ }.accessibilityLabel(+ "\(progress.steps.filter { $0.state == .completed }.count) of \(progress.steps.count) steps completed"+ )+ if let step = currentStep(definition, progress: progress),+ let state = progress.steps.first(where: { $0.id == step.id }) {+ VStack(alignment: .leading, spacing: 16) {+ Text("STEP \(step.position + 1) OF \(definition.steps.count)").font(.caption.bold())+ .tracking(1.44).foregroundStyle(palette.ink)+ Text(step.name).font(.system(.title, weight: .bold))+ if !step.instructions.isEmpty {+ Text(step.instructions).font(.body).foregroundStyle(palette.ink)+ }+ if !step.requirements.isEmpty { Text(step.requirements).foregroundStyle(palette.ink) }+ if let dose = step.dose { Text(dose.displayText).font(.subheadline) } if step.kind == .medication,- let medication = medications.first(where: { $0.id == step.targetID }) {+ let medication = medications.first(where: { $0.id == step.targetID }),+ medication.recognitionPhotoData != nil { MedicationPhotoView(data: medication.recognitionPhotoData, name: step.name) }- Text(stepState(state)).font(.caption).foregroundStyle(- state.state == .needsReview ? Color.orange : Color.secondary)- if !step.instructions.isEmpty { Text(step.instructions) }- if !step.requirements.isEmpty { Text(step.requirements) }- if let dose = step.dose { Text(dose.displayText) }- if state.state == .needsReview {- Text(- "Later real actions are kept. Review the original log or explicitly skip this unresolved step."- ).font(.caption)- Button("Use an existing log") { linkingStep = step }- Button("Accept reviewed log") {- perform {- try service.resolveReview(- run, stepID: step.id, resolution: .acceptCanonical, actionID: UUID())- }- }- Button("Skip unresolved step") {- perform {- try service.resolveReview(- run, stepID: step.id, resolution: .skip, actionID: UUID())- }- }- } else if state.state == .skipped && !state.skipConfirmed && canExecute {- Button("Continue with skipped step") {- perform { try service.continueAfterSkip(run, stepID: step.id, actionID: UUID()) }- }- } else if progress.nextReadyStepID == step.id && canExecute {- stepAction(step, state: state)- Button("Use an existing log") { linkingStep = step }- Button("Skip step") {- perform {- try service.skip(- run, stepID: step.id, actionID: UUID(), reason: "Explicit user skip")- }- }+ currentActions(step, state: state, progress: progress)+ }.meddyCard(fill: palette.surface)+ } else {+ VStack(alignment: .leading, spacing: 10) {+ Label(+ SessionLabels.text(run.statusRaw),+ systemImage: progress.phase == .completed ? "checkmark.circle.fill" : "pause.circle"+ )+ .font(.title2.bold()).foregroundStyle(MeddyStyle.success)+ if let completedAt = run.completedAt {+ Text("Finished at " + completedAt.formatted(date: .omitted, time: .shortened)) }- if let eventID = state.canonicalEventID {- canonicalLink(eventID, kind: step.kind)+ }.meddyCard(fill: Color("MeddySuccessSurface"))+ }+ MeddySectionLabel(text: "All steps")+ allSteps(definition, progress: progress, palette: palette)+ VStack(alignment: .leading, spacing: 16) {+ if progress.phase == .active {+ Button("Pause session") { perform { try service.pause(run, actionID: UUID()) } }+ }+ if progress.phase == .paused {+ Button("Resume session") { perform { try service.resume(run, actionID: UUID()) } }+ }+ if progress.phase == .endedIncomplete {+ Button("Reopen session") { perform { try service.reopen(run, actionID: UUID()) } }+ }+ if [.active, .paused, .needsReview].contains(progress.phase) {+ Button("End session", role: .destructive) { endConfirmation = true }+ }+ }.disabled(!canExecute)+ DisclosureGroup("Saved plan and session") {+ sessionHeading(definition, progress: progress)+ }.font(.subheadline)+ }.padding(24)+ }.meddyScreen()+ } else {+ ContentUnavailableView("Checkpoint needs review", systemImage: "exclamationmark.triangle")+ }+ }+ @ViewBuilder private func allSteps(+ _ definition: FrozenRoutineDefinition, progress: OrderedCheckpoint, palette: PurposePalette+ ) -> some View {+ ForEach(definition.steps) { step in+ if let state = progress.steps.first(where: { $0.id == step.id }) {+ VStack(alignment: .leading, spacing: 10) {+ HStack(spacing: 12) {+ ZStack {+ Circle().stroke(+ state.state == .completed ? palette.ink : MeddyStyle.border, lineWidth: 1.5+ ).frame(width: 28, height: 28)+ if state.state == .completed {+ Image(systemName: "checkmark").foregroundStyle(palette.ink)+ } else {+ Text("\(step.position + 1)").font(.caption.bold()) }+ }+ if step.kind == .medication,+ let medication = medications.first(where: { $0.id == step.targetID }) {+ MedicationPhotoView(data: medication.recognitionPhotoData, name: step.name, size: 32)+ }+ VStack(alignment: .leading, spacing: 4) {+ Text(step.name).font(.body.weight(.semibold))+ Text(+ step.kind == .medication+ ? "Medication" : step.kind == .treatment ? "Treatment" : "Timed routine"+ )+ .font(.caption).foregroundStyle(MeddyStyle.secondary)+ }+ Spacer(minLength: 4)+ Text(stepState(state)).font(.caption).foregroundStyle(+ state.state == .needsReview ? MeddyStyle.warning : MeddyStyle.secondary)+ }+ if let eventID = state.canonicalEventID {+ DisclosureGroup("Recorded details") { canonicalLink(eventID, kind: step.kind) }+ .font(.caption)+ }+ if !state.audit.isEmpty {+ DisclosureGroup("Review history") { ForEach(Array(state.audit.enumerated()), id: \.offset) { _, audit in- VStack(alignment: .leading) {+ HStack(alignment: .top, spacing: 12) {+ Text(audit.timestamp, style: .time).monospacedDigit() Text(audit.reason)- Text(audit.timestamp.formatted(date: .abbreviated, time: .shortened))- }.font(.caption).foregroundStyle(.secondary)+ }.font(.caption).foregroundStyle(MeddyStyle.secondary) }- }+ }.font(.caption) }+ }.padding(.vertical, 12)+ Rectangle().fill(MeddyStyle.divider).frame(height: 0.5)+ }+ }+ }+ private func currentStep(_ definition: FrozenRoutineDefinition, progress: OrderedCheckpoint)+ -> FrozenRoutineStep? {+ let unresolved = progress.steps.first {+ $0.state == .needsReview || $0.state == .skipped && !$0.skipConfirmed+ }+ let id = unresolved?.id ?? progress.nextReadyStepID+ return definition.steps.first { $0.id == id }+ }+ @ViewBuilder private func currentActions(+ _ step: FrozenRoutineStep, state: StepProgress, progress: OrderedCheckpoint+ ) -> some View {+ if state.state == .needsReview {+ Text("Review the original log or explicitly skip this unresolved step.").font(.caption)+ Button("Use an existing log") { linkingStep = step }+ Button("Accept reviewed log") {+ perform {+ try service.resolveReview(+ run, stepID: step.id, resolution: .acceptCanonical, actionID: UUID())+ }+ }+ Button("Skip unresolved step") {+ perform {+ try service.resolveReview(run, stepID: step.id, resolution: .skip, actionID: UUID())+ }+ }+ } else if state.state == .skipped && !state.skipConfirmed && canExecute {+ Button("Continue with skipped step") {+ perform { try service.continueAfterSkip(run, stepID: step.id, actionID: UUID()) }+ }.buttonStyle(+ MeddyPrimaryButtonStyle(+ fill: PurposePalette(run.routine?.purpose?.name).ink,+ ink: PurposePalette(run.routine?.purpose?.name).surface))+ } else if progress.nextReadyStepID == step.id && canExecute {+ stepAction(step, state: state)+ Button("Use an existing log") { linkingStep = step }+ Button("Skip step") {+ perform {+ try service.skip(run, stepID: step.id, actionID: UUID(), reason: "Explicit user skip") }- Section {- if progress.phase == .active {- Button("Pause session") { perform { try service.pause(run, actionID: UUID()) } }- }- if progress.phase == .paused {- Button("Resume session") { perform { try service.resume(run, actionID: UUID()) } }- }- if progress.phase == .endedIncomplete {- Button("Reopen session") { perform { try service.reopen(run, actionID: UUID()) } }- }- if [.active, .paused, .needsReview].contains(progress.phase) {- Button("End session", role: .destructive) { endConfirmation = true }- }- }.disabled(!canExecute) }- } else {- ContentUnavailableView("Checkpoint needs review", systemImage: "exclamationmark.triangle") } } @ViewBuilder private func sessionHeading( _ definition: FrozenRoutineDefinition, progress: OrderedCheckpoint ) -> some View {- Section {- Text(SessionLabels.text(run.statusRaw)).font(.headline)- if let occurrence = definition.occurrence {- Text("Saved session: \(run.logicalDayLabel ?? occurrence.localDate)")- if let time = occurrence.scheduledAt {- Text(time.formatted(date: .abbreviated, time: .shortened))- }- Text(occurrence.timeZoneID).font(.caption).foregroundStyle(.secondary)- }- if !definition.instructions.isEmpty { Text(definition.instructions) }- if run.routine?.definitionRevision != definition.revision {- Text("The plan has changed. This session keeps its saved plan.").font(.caption)- .foregroundStyle(.secondary)- }- if run.routine?.isActive == false {- Text("This routine is archived. Its saved session and history are preserved.").font(- .caption)- }- Text(- "\(progress.steps.filter { $0.state == .completed }.count) of \(progress.steps.count) steps completed"- ).font(.caption)+ Section {+ Text(SessionLabels.text(run.statusRaw)).font(.headline)+ if let occurrence = definition.occurrence {+ Text("Saved session: \(run.logicalDayLabel ?? occurrence.localDate)")+ if let time = occurrence.scheduledAt {+ Text(time.formatted(date: .abbreviated, time: .shortened)) }+ Text(occurrence.timeZoneID).font(.caption).foregroundStyle(.secondary)+ }+ if !definition.instructions.isEmpty { Text(definition.instructions) }+ if run.routine?.definitionRevision != definition.revision {+ Text("The plan has changed. This session keeps its saved plan.").font(.caption)+ .foregroundStyle(.secondary)+ }+ if run.routine?.isActive == false {+ Text("This routine is archived. Its saved session and history are preserved.").font(+ .caption)+ }+ Text(+ "\(progress.steps.filter { $0.state == .completed }.count) of \(progress.steps.count) steps completed"+ ).font(.caption)+ } } @ViewBuilder private func stepAction(_ step: FrozenRoutineStep, state: StepProgress) -> some View {@@ -213,7 +300,10 @@ struct RoutineRunView: View { _ = try service.recordTreatment(action, in: run, stepID: step.id) pendingTreatment = nil }- }.buttonStyle(.borderedProminent)+ }.buttonStyle(+ MeddyPrimaryButtonStyle(+ fill: PurposePalette(run.routine?.purpose?.name).ink,+ ink: PurposePalette(run.routine?.purpose?.name).surface)) case .medication: Button("Taken / Applied") { perform {@@ -228,7 +318,10 @@ struct RoutineRunView: View { _ = try service.recordMedication(action, in: run, stepID: step.id) pendingMedication = nil }- }.buttonStyle(.borderedProminent)+ }.buttonStyle(+ MeddyPrimaryButtonStyle(+ fill: PurposePalette(run.routine?.purpose?.name).ink,+ ink: PurposePalette(run.routine?.purpose?.name).surface)) case .timedRoutine: if let childID = state.canonicalEventID, let child = runs.first(where: { $0.id == childID }) { NavigationLink("Open saved timer") { TimerRunView(run: child) }@@ -236,7 +329,10 @@ struct RoutineRunView: View { Button("Start timer") { perform { timerDestination = try service.beginTimedStep(run, stepID: step.id) } }- .buttonStyle(.borderedProminent)+ .buttonStyle(+ MeddyPrimaryButtonStyle(+ fill: PurposePalette(run.routine?.purpose?.name).ink,+ ink: PurposePalette(run.routine?.purpose?.name).surface)) } } }@@ -287,7 +383,8 @@ struct TimerRunView: View { @Environment(PhoneNavigation.self) private var navigation @Environment(\.modelContext) private var context let run: RoutineRun- @ScaledMetric(relativeTo: .largeTitle) private var countdownFontSize = 52+ @ScaledMetric(relativeTo: .largeTitle) private var countdownFontSize = 66+ @ScaledMetric(relativeTo: .largeTitle) private var timerTitleSize = 28 @State private var actionID = UUID() @State private var error: String? private var service: RoutineSessionService { RoutineSessionService(context: context) }@@ -305,17 +402,29 @@ struct TimerRunView: View { VStack(spacing: 20) { VStack(spacing: 8) { PhoneHandoffControls(run: run)- if !definition.instructions.isEmpty { Text(definition.instructions) }- Text("\(checkpoint.completedRounds) rounds completed").font(.subheadline)- .foregroundStyle(.secondary)+ Text("TIMED ROUTINE").font(.caption.bold()).tracking(1.44).foregroundStyle(+ PurposePalette(run.routine?.purpose?.name).ink)+ Text(definition.name).font(.system(size: timerTitleSize, weight: .bold)) }- Spacer(minLength: 0) TimelineView(.periodic(from: .now, by: 1)) { _ in- let presentation = PhoneTimerControl(- checkpoint: checkpoint, clock: ExecutionClock.sample())- timerCircle(presentation, diameter: min(geometry.size.width - 32, 340))+ let clock = ExecutionClock.sample()+ let presentation = PhoneTimerControl(checkpoint: checkpoint, clock: clock)+ VStack(spacing: 20) {+ timerCircle(+ presentation, checkpoint: checkpoint, clock: clock,+ diameter: min(geometry.size.width - 48, 280))+ if !definition.instructions.isEmpty {+ VStack(alignment: .leading, spacing: 8) {+ Text("EACH ROUND").font(.caption.bold()).tracking(1.44)+ Text(definition.instructions)+ }.foregroundStyle(PurposePalette(run.routine?.purpose?.name).ink)+ .meddyCard(+ fill: PurposePalette(run.routine?.purpose?.name).surface, radius: 22,+ padding: 18)+ }+ timerPrimaryAction(presentation)+ } }- Spacer(minLength: 0) VStack(spacing: 12) { if checkpoint.phase == .waiting { if !definition.betweenRoundInstructions.isEmpty {@@ -355,56 +464,78 @@ struct TimerRunView: View { } .multilineTextAlignment(.center) .padding(16)- .frame(maxWidth: .infinity, minHeight: max(0, geometry.size.height))+ .frame(maxWidth: .infinity) } else { ContentUnavailableView( "Saved timer needs review", systemImage: "exclamationmark.triangle") }- }+ }.meddyScreen() } .navigationTitle(definition?.name ?? "Saved timer") .navigationBarTitleDisplayMode(.inline) }- private func timerCircle(_ presentation: PhoneTimerControl, diameter: CGFloat) -> some View {- VStack(spacing: 12) {+ private func timerCircle(+ _ presentation: PhoneTimerControl, checkpoint: TimerCheckpoint, clock: ClockSample,+ diameter: CGFloat+ ) -> some View {+ let palette = PurposePalette(run.routine?.purpose?.name)+ let remaining = checkpoint.remaining(at: clock)+ let duration = checkpoint.durationSeconds+ let fraction = presentation.phase == .completed ? 1 : 1 - remaining / max(1, duration)+ return VStack(spacing: 20) { Button { if let operation = presentation.operation { transition(operation) } } label: {- VStack(spacing: 12) {- Text(presentation.title).font(.title3.weight(.semibold)).multilineTextAlignment(.center)- .contentTransition(.identity)- if let countdown = presentation.countdown {- Text(countdown).font(.system(size: countdownFontSize, weight: .bold, design: .rounded))- .monospacedDigit().lineLimit(1).minimumScaleFactor(0.6).contentTransition(.identity)- }- }- .padding(24)- .frame(width: max(180, diameter), height: max(180, diameter))- .foregroundStyle(.white)- .background(- !canExecute- ? Color(red: 0.35, green: 0.35, blue: 0.35)- : presentation.phase == .completed- ? Color(red: 0.05, green: 0.40, blue: 0.24)- : presentation.phase == .running- ? Color(red: 0.65, green: 0.25, blue: 0.02)- : Color(red: 0.04, green: 0.28, blue: 0.62), in: Circle()+ MeddyProgressRing(progress: fraction, palette: palette, lineWidth: 16) {+ VStack(spacing: 8) {+ Text(+ presentation.countdown+ ?? String(format: "%02d:%02d", Int(duration) / 60, Int(duration) % 60)+ )+ .font(.system(size: countdownFontSize, weight: .bold)).monospacedDigit()+ .lineLimit(1).minimumScaleFactor(0.6).contentTransition(.identity)+ Text(presentation.title).font(.subheadline.weight(.semibold)).multilineTextAlignment(+ .center)+ Text(+ presentation.operation == .pause+ ? "Tap to pause"+ : presentation.operation == .resume ? "Tap to resume" : "Tap to continue"+ )+ .font(.caption).foregroundStyle(MeddyStyle.secondary)+ }.padding(24)+ }.frame(width: max(180, diameter), height: max(180, diameter)).contentShape(Circle())+ }.buttonStyle(.plain).disabled(!canExecute || presentation.operation == nil)+ .accessibilityIdentifier("phoneTimerCircle").accessibilityLabel(+ presentation.accessibilityLabel )- .contentShape(Circle())- }- .buttonStyle(.plain)- .disabled(!canExecute || presentation.operation == nil)- .accessibilityIdentifier("phoneTimerCircle")- .accessibilityLabel(presentation.accessibilityLabel)- .accessibilityValue(presentation.countdown.map { "\($0) remaining" } ?? "")- .accessibilityHint(presentation.instruction)- Text(presentation.instruction).font(.subheadline).multilineTextAlignment(.center)- }- .transaction {+ .accessibilityValue(presentation.countdown.map { "\($0) remaining" } ?? "")+ .accessibilityHint(presentation.instruction)+ HStack(spacing: 8) {+ ForEach(0..<min(checkpoint.roundCount, 30), id: \.self) { index in+ Capsule().fill(index < (checkpoint.completedRounds) ? palette.ink : palette.track)+ .frame(width: 18, height: 6)+ }+ }.accessibilityHidden(true)+ }.transaction { $0.animation = nil $0.disablesAnimations = true } }+ private func timerPrimaryAction(_ presentation: PhoneTimerControl) -> some View {+ let palette = PurposePalette(run.routine?.purpose?.name)+ return VStack(spacing: 12) {+ if let operation = presentation.operation {+ Button(presentation.title) { transition(operation) }+ .buttonStyle(MeddyPrimaryButtonStyle(fill: palette.ink, ink: palette.surface)).disabled(+ !canExecute)+ } else if presentation.phase == .completed {+ Label("All rounds done", systemImage: "checkmark.circle.fill").font(.title3.bold())+ .foregroundStyle(MeddyStyle.success)+ }+ Text(presentation.instruction).font(.subheadline).foregroundStyle(MeddyStyle.secondary)+ .multilineTextAlignment(.center)+ }+ } private func transition(_ operation: TimerOperation) { do { try service.changeTimer(@@ -465,50 +596,58 @@ struct ExistingLogPicker: View { var body: some View { NavigationStack { List {- Text(- """- Choose a real matching log. Its original time and details are preserved. Moving an associated log marks its \- earlier session for review.- """- ).font(.caption)- switch step.kind {- case .medication:- ForEach(- administrations.filter {- !$0.isDeleted && $0.medicationID == step.targetID- && ["asNeeded", "routineManaged"].contains($0.scheduleTypeAtRecordingRaw)- }- ) { event in- Button {- confirmation = event.id- } label: {- logLabel(- event.timestamp, detail: event.recordedDose.displayText,- linked: event.routineRunID != nil)+ Section {+ Text(+ """+ Choose a real matching log. Its original time and details are preserved. Moving an associated log marks its \+ earlier session for review.+ """+ ).font(.caption)+ }.listRowBackground(MeddyStyle.surface)+ Section("Matching logs") {+ switch step.kind {+ case .medication:+ ForEach(+ administrations.filter {+ !$0.isDeleted && $0.medicationID == step.targetID+ && ["asNeeded", "routineManaged"].contains($0.scheduleTypeAtRecordingRaw)+ }+ ) { event in+ Button {+ confirmation = event.id+ } label: {+ logLabel(+ event.timestamp, detail: event.recordedDose.displayText,+ linked: event.routineRunID != nil)+ } }- }- case .treatment:- ForEach(completions.filter { !$0.isDeleted && $0.treatmentID == step.targetID }) { event in- Button {- confirmation = event.id- } label: {- logLabel(- event.timestamp, detail: event.instructionsSnapshot,- linked: event.routineRunID != nil)+ case .treatment:+ ForEach(completions.filter { !$0.isDeleted && $0.treatmentID == step.targetID }) { event in+ Button {+ confirmation = event.id+ } label: {+ logLabel(+ event.timestamp, detail: event.instructionsSnapshot,+ linked: event.routineRunID != nil)+ } }- }- case .timedRoutine:- ForEach(runs.filter { !$0.isDeleted && $0.wasCompleted && $0.routineID == step.targetID }) { event in- Button {- confirmation = event.id- } label: {- RunSummaryRow(run: event)+ case .timedRoutine:+ ForEach(+ runs.filter { !$0.isDeleted && $0.wasCompleted && $0.routineID == step.targetID }+ ) { event in+ Button {+ confirmation = event.id+ } label: {+ RunSummaryRow(run: event)+ } } }- }+ }.listRowBackground(MeddyStyle.surface) if let error { Text(error).foregroundStyle(.red) } }+ .meddyScreen() .navigationTitle("Use an existing log")+ .presentationDragIndicator(.visible).presentationCornerRadius(28) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } } .confirmationDialog( "Use this original log for the selected step?",
diff --git a/Meddy/Meddy/Features/RoutinesView.swift b/Meddy/Meddy/Features/RoutinesView.swiftindex 097d0d0..3b07168 100644--- a/Meddy/Meddy/Features/RoutinesView.swift+++ b/Meddy/Meddy/Features/RoutinesView.swift@@ -38,94 +38,117 @@ struct RoutinesView: View { } @State private var archived = false @State private var creation: CareCreation?+ @State private var selectingRoutine: Routine? @State private var error: String? var body: some View {- List {- Picker("Show", selection: $archived) {- Text("Active").tag(false)- Text("Archived").tag(true)- }.pickerStyle(.segmented)- Section("Ordered routines") {- ForEach(routines.filter { $0.isActive != archived && $0.kindRaw == "ordered" }) { routine in- NavigationLink {- RoutineDetailView(routine: routine, onStart: requestStart, onOpen: navigation.open)+ ScrollView {+ VStack(alignment: .leading, spacing: 12) {+ MeddyScreenHeader(title: "Routines") {+ Menu {+ Button("Treatment item") { creation = .treatment }+ Button("Timed routine") { creation = .timed }+ Button("Ordered routine") { creation = .ordered } } label: {- VStack(alignment: .leading) {- Text(routine.name)- Text("\((routine.steps ?? []).count) ordered steps").font(.caption).foregroundStyle(- .secondary)- }- }.accessibilityLabel(routine.name)+ Image(systemName: "plus").font(.title3.bold()).frame(width: 40, height: 40)+ .foregroundStyle(MeddyStyle.onAccent).background(MeddyStyle.accent, in: Circle())+ }.accessibilityLabel("Add care item") }- }- Section("Timed routines") {- ForEach(routines.filter { $0.isActive != archived && $0.kindRaw == "timedRounds" }) { routine in- HStack {- NavigationLink {- RoutineDetailView(routine: routine, onStart: requestStart, onOpen: navigation.open)- } label: {- VStack(alignment: .leading) {- Text(routine.name)- Text(- "\(routine.roundCount ?? 0) rounds · \(routine.roundDurationSeconds ?? 0) seconds each"- ).font(.caption).foregroundStyle(.secondary)- }- }- if routine.isActive {- Button(incomplete(for: routine) == nil ? "Start" : "Resume") {+ if !archived {+ ForEach(routines.filter { $0.isActive }) { routine in+ RoutineHeroCard(+ routine: routine, run: incomplete(for: routine),+ actionTitle: routine.scheduleTypeRaw != "none" && incomplete(for: routine) == nil+ ? "Choose session" : nil+ ) {+ if let run = incomplete(for: routine) {+ navigation.open(run)+ } else if routine.scheduleTypeRaw != "none" {+ selectingRoutine = routine+ } else { requestStart(routine, nil)- }.buttonStyle(.bordered)+ } } } }- }- Section("Treatment items") {+ MeddySectionLabel(text: "Ordered")+ ForEach(routines.filter { $0.isActive != archived && $0.kindRaw == "ordered" }) { routine in+ routineRow(routine, metadata: "\((routine.steps ?? []).count) ordered steps")+ }+ MeddySectionLabel(text: "Timed")+ ForEach(routines.filter { $0.isActive != archived && $0.kindRaw == "timedRounds" }) { routine in+ routineRow(+ routine,+ metadata:+ "\(routine.roundCount ?? 0) rounds · \(routine.roundDurationSeconds ?? 0) seconds each"+ )+ }+ MeddySectionLabel(text: "Treatments") ForEach(treatments.filter { $0.isActive != archived }) { treatment in NavigationLink { TreatmentDetailView(treatment: treatment) } label: {- Text(treatment.name)- }+ careRow(+ treatment.name, metadata: treatment.instructions, purpose: treatment.purpose?.name)+ }.buttonStyle(.plain) }- }- let previous = runs.filter {- !$0.isDeleted && $0.parentRoutineRunID == nil- && ["active", "paused", "needsReview"].contains($0.statusRaw)- }- if !previous.isEmpty {- Section("Unfinished sessions") {+ let previous = runs.filter {+ !$0.isDeleted && $0.parentRoutineRunID == nil+ && ["active", "paused", "needsReview"].contains($0.statusRaw)+ }+ if !previous.isEmpty {+ MeddySectionLabel(text: "Unfinished sessions") ForEach(previous) { run in Button { navigation.open(run) } label: {- RunSummaryRow(run: run)- }+ RunSummaryRow(run: run).meddyCard(radius: 22, padding: 16)+ }.buttonStyle(.plain) } }+ Button(archived ? "Show active" : "Show archived") { archived.toggle() }.buttonStyle(+ MeddyOutlineButtonStyle()+ ).padding(.top, 16)+ }.padding(.horizontal, 16).padding(.bottom, 120)+ }.meddyScreen().toolbar(.hidden, for: .navigationBar)+ .navigationDestination(item: $selectingRoutine) { routine in+ RoutineDetailView(routine: routine, onStart: requestStart, onOpen: navigation.open) }- }- .navigationTitle("Routines")- .toolbar {- Menu("Add care item", systemImage: "plus") {- Button("Treatment item") { creation = .treatment }- Button("Timed routine") { creation = .timed }- Button("Ordered routine") { creation = .ordered }+ .sheet(item: $creation) { kind in+ switch kind {+ case .treatment: TreatmentEditor(profileID: selectedProfileID)+ case .timed: TimedRoutineEditor(profileID: selectedProfileID)+ case .ordered: OrderedRoutineEditor(profileID: selectedProfileID)+ } }- }- .sheet(item: $creation) { kind in- switch kind {- case .treatment: TreatmentEditor(profileID: selectedProfileID)- case .timed: TimedRoutineEditor(profileID: selectedProfileID)- case .ordered: OrderedRoutineEditor(profileID: selectedProfileID)+ .alert(+ "Could not save",+ isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+ ) {+ Button("OK") { error = nil }+ } message: {+ Text(error ?? "") }- }- .alert(- "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })- ) {- Button("OK") { error = nil }- } message: {- Text(error ?? "")+ }+ private func routineRow(_ routine: Routine, metadata: String) -> some View {+ NavigationLink {+ RoutineDetailView(routine: routine, onStart: requestStart, onOpen: navigation.open)+ } label: {+ careRow(routine.name, metadata: metadata, purpose: routine.purpose?.name)+ }.buttonStyle(.plain).accessibilityLabel(routine.name)+ }+ private func careRow(_ name: String, metadata: String, purpose: String?) -> some View {+ VStack(spacing: 0) {+ HStack(spacing: 12) {+ Circle().fill(PurposePalette(purpose).dot).frame(width: 10, height: 10)+ VStack(alignment: .leading, spacing: 4) {+ Text(name).font(.body.weight(.semibold))+ Text(metadata).font(.caption).foregroundStyle(MeddyStyle.secondary).lineLimit(1)+ }+ Spacer()+ Image(systemName: "chevron.right").font(.caption).foregroundStyle(MeddyStyle.secondary)+ }.padding(.horizontal, 8).padding(.vertical, 14).contentShape(Rectangle())+ Rectangle().fill(MeddyStyle.divider).frame(height: 0.5) } } private func incomplete(for routine: Routine) -> RoutineRun? {@@ -191,9 +214,21 @@ struct RoutineDetailView: View { return RoutineScheduleEngine().occurrences( snapshot, runs: values, day: logicalNow, now: logicalNow, calendar: .current) }+ private var canStartUnscheduled: Bool {+ guard routine.isActive, routine.scheduleTypeRaw == "none", let snapshot else { return false }+ return snapshot.current == nil && snapshot.pending == nil+ } var body: some View { List {- Section {+ RoutineHeroCard(+ routine: routine, run: nil,+ start: canStartUnscheduled+ ? { onStart(routine, nil) } : nil+ )+ .listRowInsets(EdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0)).listRowBackground(+ Color.clear+ ).listRowSeparator(.hidden)+ MeddySection("Saved plan") { if let purpose = routine.purpose { Text(purpose.name) } if !routine.instructions.isEmpty { Text(routine.instructions) } if routine.kindRaw == "timedRounds" {@@ -208,7 +243,7 @@ struct RoutineDetailView: View { } } if routine.isActive {- Section("Sessions") {+ MeddySection("Sessions") { if let snapshot { if snapshot.current == nil && snapshot.pending == nil { Button("Start") { onStart(routine, nil) }@@ -242,7 +277,7 @@ struct RoutineDetailView: View { } } }- Section("History") {+ MeddySection("History") { ForEach(runs.filter { $0.routineID == routine.id && !$0.isDeleted }) { run in Button { onOpen(run)@@ -257,7 +292,7 @@ struct RoutineDetailView: View { } } }- .navigationTitle(routine.name)+ .meddyScreen().navigationTitle(routine.name).toolbar(.visible, for: .navigationBar) .toolbar { Button("Edit") { editing = true } } .sheet(isPresented: $editing) { if routine.kindRaw == "timedRounds" {@@ -297,34 +332,47 @@ struct TreatmentDetailView: View { var body: some View { List { Section {- if let purpose = treatment.purpose { Text(purpose.name) }- if !treatment.instructions.isEmpty { Text(treatment.instructions) }- if !treatment.notes.isEmpty { Text(treatment.notes) }- if treatment.isActive {- Button("Done") {- perform {- let action =- try pending- ?? ProfileAccess.stamp(- TreatmentAction(- eventID: UUID(), treatmentID: treatment.id, timestamp: Date(),- instructionsSnapshot: treatment.instructions, source: .phone),- target: treatment, context: context)- pending = action- lastSaved = try TreatmentService(context: context).record(action)- pending = nil- }+ VStack(alignment: .leading, spacing: 14) {+ Text(treatment.name).font(.title.bold())+ if let last = completions.first(where: { $0.treatmentID == treatment.id && !$0.isDeleted }+ ) {+ Text("Last done " + last.timestamp.formatted(date: .abbreviated, time: .shortened))+ .font(.subheadline).foregroundStyle(MeddyStyle.secondary) }- }- if let lastSaved, !lastSaved.isDeleted {- Text("Saved").foregroundStyle(.secondary)- Button("Undo Done") {- perform {- try RoutineSessionService(context: context).correct(- lastSaved, timestamp: lastSaved.timestamp, delete: true)+ if let purpose = treatment.purpose { Text(purpose.name) }+ if !treatment.instructions.isEmpty { Text(treatment.instructions) }+ if !treatment.notes.isEmpty { Text(treatment.notes) }+ if treatment.isActive {+ Button("Done") {+ perform {+ let action =+ try pending+ ?? ProfileAccess.stamp(+ TreatmentAction(+ eventID: UUID(), treatmentID: treatment.id, timestamp: Date(),+ instructionsSnapshot: treatment.instructions, source: .phone),+ target: treatment, context: context)+ pending = action+ lastSaved = try TreatmentService(context: context).record(action)+ pending = nil+ }+ }.buttonStyle(+ MeddyPrimaryButtonStyle(+ fill: PurposePalette(treatment.purpose?.name).ink,+ ink: PurposePalette(treatment.purpose?.name).surface))+ }+ if let lastSaved, !lastSaved.isDeleted {+ Text("Saved").foregroundStyle(.secondary)+ Button("Undo Done") {+ perform {+ try RoutineSessionService(context: context).correct(+ lastSaved, timestamp: lastSaved.timestamp, delete: true)+ } } }- }+ }.meddyCard(fill: PurposePalette(treatment.purpose?.name).surface)+ .listRowInsets(EdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0)).listRowBackground(+ Color.clear) } let history = Dictionary( grouping: completions.filter { $0.treatmentID == treatment.id && !$0.isDeleted }@@ -332,21 +380,25 @@ struct TreatmentDetailView: View { ForEach(history.keys.sorted(by: >), id: \.self) { day in Section("Completion history · \(day)") { ForEach(history[day] ?? []) { completion in- Button {- correcting = completion- } label: {- VStack(alignment: .leading) {- Text(completion.timestamp.formatted(date: .abbreviated, time: .shortened))+ HStack(alignment: .top, spacing: 12) {+ Text(completion.timestamp, style: .time).monospacedDigit().frame(+ width: 66, alignment: .leading)+ VStack(alignment: .leading, spacing: 5) {+ Text(treatment.name).font(.subheadline.weight(.semibold)) if completion.routineRunID != nil {- Text("Linked to a saved routine session").font(.caption)+ Text("Linked to a saved session").font(.caption).foregroundStyle(+ MeddyStyle.secondary) } if completion.hasClockMismatch {- Text("Reported device time needs review").font(.caption).foregroundStyle(.orange)+ Text("Reported device time needs review").font(.caption).foregroundStyle(+ MeddyStyle.warning) } }+ Spacer()+ Button("Edit") { correcting = completion }.buttonStyle(.borderless) } }- }+ }.listRowBackground(MeddyStyle.surface) } Section { Button(treatment.isActive ? "Archive" : "Reactivate") {@@ -356,7 +408,7 @@ struct TreatmentDetailView: View { } } }- .navigationTitle(treatment.name)+ .meddyScreen().navigationTitle(treatment.name).toolbar(.visible, for: .navigationBar) .toolbar { Button("Edit") { editing = true } } .sheet(isPresented: $editing) { TreatmentEditor(treatment: treatment) } .sheet(item: $correcting) { TreatmentCompletionEditor(event: $0) }@@ -396,7 +448,7 @@ struct TreatmentCompletionEditor: View { Button("Undo completion", role: .destructive) { save(delete: true) } if let error { Text(error).foregroundStyle(.red) } }- .navigationTitle("Completion details")+ .meddyScreen().navigationTitle("Completion details") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("Save") { save(delete: false) } }
diff --git a/Meddy/Meddy/Features/TodayMedicationAction.swift b/Meddy/Meddy/Features/TodayMedicationAction.swiftnew file mode 100644index 0000000..bc4df1d--- /dev/null+++ b/Meddy/Meddy/Features/TodayMedicationAction.swift@@ -0,0 +1,29 @@+import Foundation+import SwiftData++@MainActor+enum TodayMedicationAction {+ static func take(_ medications: [Medication], at timestamp: Date, context: ModelContext) throws+ -> [Administration] {+ try EditorTransaction.save(context: context) {+ let service = MedicationService(context: context, deferSave: true)+ return try medications.map { medication in+ try service.record(+ ProfileAccess.stamp(+ AdministrationAction(+ eventID: UUID(), medicationID: medication.id, timestamp: timestamp,+ source: .phone, dose: medication.defaultDose,+ scheduleTypeAtRecording: MedicationScheduleType(rawValue: medication.scheduleTypeRaw)+ ?? .asNeeded,+ scheduleGenerationID: medication.scheduleGenerationID), target: medication,+ context: context))+ }+ }+ }+ static func undo(_ events: [Administration], context: ModelContext) throws {+ try EditorTransaction.save(context: context) {+ let service = MedicationService(context: context, deferSave: true)+ for event in events where !event.isDeleted { try service.delete(event) }+ }+ }+}
diff --git a/Meddy/Meddy/Features/TodayRoutineSections.swift b/Meddy/Meddy/Features/TodayRoutineSections.swiftindex 7f74404..7caca5f 100644--- a/Meddy/Meddy/Features/TodayRoutineSections.swift+++ b/Meddy/Meddy/Features/TodayRoutineSections.swift@@ -2,6 +2,8 @@ import SwiftData import SwiftUI struct TodayRoutineSections: View {+ var later = false+ var hasMedicationLater = false @Environment(\.careProfileID) private var selectedProfileID @Environment(\.modelContext) private var context @Environment(\.logicalDayNow) private var logicalTick@@ -41,57 +43,115 @@ struct TodayRoutineSections: View { return (left.1.scheduledAt ?? .distantFuture) < (right.1.scheduledAt ?? .distantFuture) } }- var body: some View {- Section("Today's routines") {- ForEach(cards, id: \.1.id) { routine, occurrence in- Button {- navigation.start(routine, occurrence: occurrence)- } label: {- VStack(alignment: .leading, spacing: 4) {- Text("\(routine.name) · \(occurrence.label)").font(.headline)- if let date = occurrence.scheduledAt {- Text(- date <= logicalNow- ? "Due \(date.formatted(date: .omitted, time: .shortened))"- : "Next \(date.formatted(date: .omitted, time: .shortened))"- ).font(.caption)- }- if let id = occurrence.existingRunID, let run = runs.first(where: { $0.id == id }),- let progress = try? RoutineSessionService(context: context).progress(run) {- Text(- "\(progress.steps.filter { $0.state == .completed }.count) of \(progress.steps.count) steps · \(SessionLabels.text(run.statusRaw))"- ).font(.caption)- if let stepID = progress.nextReadyStepID,- let definition = try? RoutineSessionService(context: context).definition(run),- let step = definition.steps.first(where: { $0.id == stepID }) {- Text(step.name).font(.caption)- }- } else {- Text("Start").font(.caption)- }- }- }- }+ private var unfinished: [(Routine, RoutineOccurrence)] {+ cards.filter {+ ![SessionPhase.completed, .finishedWithSkips, .endedIncomplete].contains(+ $0.1.status ?? .active)+ }+ }+ private var future: [(Routine, RoutineOccurrence)] {+ unfinished.filter {+ $0.1.existingRunID == nil+ && ($0.1.scheduledAt ?? .distantPast) > logicalNow.addingTimeInterval(1800) }- let earlier = runs.filter {- !$0.isDeleted && $0.parentRoutineRunID == nil+ }+ private var currentTimers: [RoutineRun] {+ runs.filter {+ !$0.isDeleted && $0.parentRoutineRunID == nil && $0.routine?.kindRaw == "timedRounds" && ["active", "paused", "needsReview"].contains($0.statusRaw)- && ($0.logicalDayLabel.map {- $0 != ScheduleCalendar.localDate(logicalNow, calendar: .current)- } ?? true)+ && $0.startedAt.map { ScheduleCalendar.sameDay($0, logicalNow, calendar: .current) } == true }- if !earlier.isEmpty {- Section("Earlier unfinished sessions") {- ForEach(earlier) { run in+ }+ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ if later {+ if !future.isEmpty && !hasMedicationLater {+ MeddySectionLabel(text: "Later").padding(.horizontal, 8)+ }+ ForEach(future, id: \.1.id) { routine, occurrence in+ Button {+ navigation.start(routine, occurrence: occurrence)+ } label: {+ HStack(spacing: 12) {+ Text(occurrence.scheduledAt ?? logicalNow, style: .time).monospacedDigit().frame(+ width: 66, alignment: .leading)+ Text(routine.name).font(.body.weight(.semibold))+ Spacer()+ Text("\((routine.steps ?? []).count) steps").font(.subheadline).foregroundStyle(+ MeddyStyle.secondary)+ }.padding(.vertical, 12).padding(.horizontal, 8)+ }.buttonStyle(.plain)+ Rectangle().fill(MeddyStyle.divider).frame(height: 0.5)+ }+ } else {+ ForEach(unfinished.filter { item in !future.contains { $0.1.id == item.1.id } }, id: \.1.id) { routine, occurrence in+ Button {+ navigation.start(routine, occurrence: occurrence)+ } label: {+ HStack(spacing: 12) {+ VStack(alignment: .leading, spacing: 5) {+ Text(routine.name).font(.body.bold())+ Text(+ occurrence.label+ + (occurrence.scheduledAt.map {+ " · " + $0.formatted(date: .omitted, time: .shortened)+ } ?? "")+ )+ .font(.caption).foregroundStyle(MeddyStyle.secondary)+ }+ Spacer()+ Text(occurrence.existingRunID == nil ? "Start" : "Open").font(.subheadline.bold())+ .padding(.horizontal, 16).padding(.vertical, 9)+ .overlay(Capsule().stroke(MeddyStyle.border, lineWidth: 1.5)).foregroundStyle(+ MeddyStyle.accent)+ }.meddyCard(radius: 22, padding: 18)+ }.buttonStyle(.plain)+ }+ ForEach(currentTimers) { run in Button { navigation.open(run) } label: {- RunSummaryRow(run: run)+ HStack {+ VStack(alignment: .leading, spacing: 5) {+ Text(+ (try? RoutineSessionService(context: context).definition(run).name)+ ?? "Saved timer"+ ).font(.body.bold())+ if let checkpoint = try? RoutineSessionService(context: context).timer(run) {+ Text(+ PhoneTimerControl(checkpoint: checkpoint, clock: ExecutionClock.sample())+ .accessibilityLabel+ )+ .font(.caption).foregroundStyle(MeddyStyle.secondary)+ }+ }+ Spacer()+ Text("Open").foregroundStyle(MeddyStyle.accent)+ }.meddyCard(radius: 22, padding: 18)+ }.buttonStyle(.plain)+ }+ let earlier = runs.filter { run in+ !run.isDeleted && run.parentRoutineRunID == nil+ && ["active", "paused", "needsReview"].contains(run.statusRaw)+ && !currentTimers.contains { $0.id == run.id }+ && (run.logicalDayLabel.map {+ $0 != ScheduleCalendar.localDate(logicalNow, calendar: .current)+ } ?? true)+ }+ if !earlier.isEmpty {+ MeddySectionLabel(text: "Earlier unfinished sessions")+ ForEach(earlier) { run in+ Button {+ navigation.open(run)+ } label: {+ RunSummaryRow(run: run).meddyCard(radius: 22, padding: 16)+ }.buttonStyle(.plain) } } } } }+ } struct CurrentMedicationsView: View {@@ -127,7 +187,7 @@ struct CurrentMedicationsView: View { } } }- }.navigationTitle("Current Medications")+ }.meddyScreen().navigationTitle("Current Medications") .toolbar { ShareLink( item: MedicationPresentation.consultationExport(
diff --git a/Meddy/Meddy/Models/Models.swift b/Meddy/Meddy/Models/Models.swiftindex b882fc0..dfd172c 100644--- a/Meddy/Meddy/Models/Models.swift+++ b/Meddy/Meddy/Models/Models.swift@@ -37,6 +37,11 @@ final class Medication { var asNeededDoseLimitsData: Data? var followupNotificationData: Data? var recognitionPhotoData: Data?+ var prescribedOn: String?+ var prescribedBy: String?+ var supplyDurationDays: Int?+ var repeatsLeft: Int?+ var prescriptionRevision: UUID? var administrationMethod: String = "" var requirements: String = "" var notes: String = ""
diff --git a/Meddy/Meddy/Services/MedicationService.swift b/Meddy/Meddy/Services/MedicationService.swiftindex d9d62f4..713e65f 100644--- a/Meddy/Meddy/Services/MedicationService.swift+++ b/Meddy/Meddy/Services/MedicationService.swift@@ -131,6 +131,7 @@ final class MedicationService { func setActive(_ medication: Medication, _ active: Bool) throws { _ = try ProfileAccess.owner(medication, context: context)+ if medication.isActive != active { medication.prescriptionRevision = UUID() } medication.isActive = active medication.archivedAt = active ? nil : Date() try save()
diff --git a/Meddy/Meddy/Services/PrescriptionService.swift b/Meddy/Meddy/Services/PrescriptionService.swiftnew file mode 100644index 0000000..35ba949--- /dev/null+++ b/Meddy/Meddy/Services/PrescriptionService.swift@@ -0,0 +1,132 @@+import Foundation+import SwiftData++nonisolated enum PrescriptionError: LocalizedError {+ case invalidDate, invalidDays, invalidRepeats, changed+ var errorDescription: String? {+ switch self {+ case .invalidDate: "Enter a valid prescription date."+ case .invalidDays: "Supply duration must be a positive whole number of days."+ case .invalidRepeats: "Repeats left must be a whole number of zero or more."+ case .changed: "Prescription details changed. Reopen the editor or try the current repeat count."+ }+ }+}++nonisolated struct PrescriptionDetails: Equatable, Sendable {+ var prescribedOn: String?+ var prescribedBy: String?+ var supplyDurationDays: Int?+ var repeatsLeft: Int?+ var isEmpty: Bool {+ prescribedOn == nil && prescribedBy == nil && supplyDurationDays == nil && repeatsLeft == nil+ }+ func validate() throws {+ if let prescribedOn, PrescriptionDate.date(prescribedOn) == nil {+ throw PrescriptionError.invalidDate+ }+ if let supplyDurationDays, supplyDurationDays <= 0 { throw PrescriptionError.invalidDays }+ if let repeatsLeft, repeatsLeft < 0 { throw PrescriptionError.invalidRepeats }+ }+}++nonisolated enum PrescriptionDate {+ static var calendar: Calendar {+ var value = Calendar(identifier: .gregorian)+ value.timeZone = TimeZone(secondsFromGMT: 0)!+ return value+ }+ static var today: Date {+ let local = Calendar(identifier: .gregorian)+ let parts = local.dateComponents([.year, .month, .day], from: Date())+ return calendar.date(from: parts) ?? Date()+ }+ static func string(_ date: Date) -> String {+ let parts = calendar.dateComponents([.year, .month, .day], from: date)+ return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)+ }+ static func date(_ value: String) -> Date? {+ let parts = value.split(separator: "-", omittingEmptySubsequences: false)+ guard parts.count == 3, value.count == 10,+ let year = Int(parts[0]), (1...9999).contains(year),+ let month = Int(parts[1]), let day = Int(parts[2]),+ let result = calendar.date(from: DateComponents(year: year, month: month, day: day)),+ string(result) == value+ else { return nil }+ return result+ }+}++@MainActor struct PrescriptionCapture {+ let medicationID: UUID+ let profileID: UUID+ let lifecycleID: UUID+ let revision: UUID?+}++@MainActor struct PrescriptionUndo {+ let capture: PrescriptionCapture+ let previousCount: Int+ let savedRevision: UUID+}++@MainActor final class PrescriptionService {+ private let context: ModelContext+ init(context: ModelContext) { self.context = context }+ static func details(_ medication: Medication) -> PrescriptionDetails {+ .init(+ prescribedOn: medication.prescribedOn, prescribedBy: medication.prescribedBy,+ supplyDurationDays: medication.supplyDurationDays, repeatsLeft: medication.repeatsLeft)+ }+ func capture(_ medication: Medication) throws -> PrescriptionCapture {+ _ = try ProfileAccess.canonical(Medication.self, id: medication.id, context: context)+ return try .init(+ medicationID: medication.id, profileID: ProfileAccess.owner(medication, context: context),+ lifecycleID: ProfileAccess.lifecycle(medication, context: context),+ revision: medication.prescriptionRevision)+ }+ private func target(_ capture: PrescriptionCapture) throws -> Medication {+ let medication = try ProfileAccess.canonical(+ Medication.self, id: capture.medicationID, context: context)+ try ProfileAccess.action(+ capture.profileID, version: ProfileIdentity.ownershipVersion, lifecycle: capture.lifecycleID,+ target: medication, context: context)+ guard medication.isActive else { throw DefinitionError.invalidTarget }+ return medication+ }+ func decrement(_ capture: PrescriptionCapture, save: (() throws -> Void)? = nil) throws+ -> PrescriptionUndo {+ let medication = try target(capture)+ guard medication.prescriptionRevision == capture.revision else { throw PrescriptionError.changed }+ guard let count = medication.repeatsLeft, count > 0 else { throw PrescriptionError.invalidRepeats }+ let revision = UUID()+ try change(medication, count: count - 1, revision: revision, save: save)+ return .init(capture: capture, previousCount: count, savedRevision: revision)+ }+ func undo(_ receipt: PrescriptionUndo, save: (() throws -> Void)? = nil) throws {+ let medication = try target(receipt.capture)+ guard receipt.previousCount > 0, medication.prescriptionRevision == receipt.savedRevision,+ medication.repeatsLeft == receipt.previousCount - 1+ else { throw PrescriptionError.changed }+ try change(medication, count: receipt.previousCount, revision: UUID(), save: save)+ }+ private func change(+ _ medication: Medication, count: Int, revision: UUID, save: (() throws -> Void)?+ ) throws {+ context.autosaveEnabled = false+ let previous = medication.repeatsLeft+ let previousRevision = medication.prescriptionRevision+ do {+ medication.repeatsLeft = count+ medication.prescriptionRevision = revision+ try (save ?? { try self.context.save() })()+ MutationEffects.saved(context)+ } catch {+ context.rollback()+ // Restore these known values too: rollback alone can leave realized SwiftData properties stale.+ medication.repeatsLeft = previous+ medication.prescriptionRevision = previousRevision+ throw RecordingError.saveFailed+ }+ }+}
diff --git a/Meddy/MeddyTests/MeddyPrescriptionTests.swift b/Meddy/MeddyTests/MeddyPrescriptionTests.swiftnew file mode 100644index 0000000..c4b6ccd--- /dev/null+++ b/Meddy/MeddyTests/MeddyPrescriptionTests.swift@@ -0,0 +1,223 @@+import Foundation+import SwiftData+import Testing++@testable import Meddy++@MainActor struct MeddyPrescriptionTests {+ private func setup() throws -> (ModelContainer, Medication) {+ let store = try AppEnvironment.makeContainer(isolated: true)+ return (store, try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic medicine"))+ }+ private func set(_ item: Medication, context: ModelContext, repeats: String = "3") throws {+ let draft = PrescriptionDraft(medication: item)+ draft.hasDate = true+ draft.date = try #require(PrescriptionDate.date("2026-10-08"))+ draft.prescriber = " Synthetic doctor / clinic "+ draft.days = "30"+ draft.repeats = repeats+ try EditorTransaction.save(context: context) { try draft.apply(to: item, context: context) }+ }+ @Test func optionalDefaultsValidationAndCivilDateDoNotChangeCare() throws {+ let (store, item) = try setup()+ #expect(PrescriptionService.details(item).isEmpty)+ #expect(try PrescriptionDraft(medication: item).value() == PrescriptionDetails())+ let generation = item.scheduleGenerationID+ try set(item, context: store.mainContext, repeats: "0")+ #expect(item.prescribedOn == "2026-10-08" && item.prescribedBy == "Synthetic doctor / clinic")+ #expect(item.supplyDurationDays == 30 && item.repeatsLeft == 0)+ #expect(item.scheduleGenerationID == generation && !item.remindersEnabled)+ #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+ for date in ["2026-02-29", "2026-13-01", "2026-1-01", "0000-01-01"] {+ #expect(PrescriptionDate.date(date) == nil)+ }+ #expect(PrescriptionDate.string(try #require(PrescriptionDate.date("2024-02-29"))) == "2024-02-29")+ let draft = PrescriptionDraft(medication: item)+ for invalid in ["-1", "1.5", "abc", "999999999999999999999999999999"] {+ draft.repeats = invalid+ #expect(throws: PrescriptionError.self) { try draft.value() }+ }+ draft.repeats = "0"+ draft.days = "0"+ #expect(throws: PrescriptionError.self) { try draft.value() }+ }+ @Test func untouchedFieldsMergeNewerValuesAndConflictingEditedFieldFails() throws {+ let (store, item) = try setup()+ let context = store.mainContext+ try set(item, context: context)+ let stale = PrescriptionDraft(medication: item)+ let current = PrescriptionDraft(medication: item)+ current.repeats = "7"+ try EditorTransaction.save(context: context) { try current.apply(to: item, context: context) }+ stale.prescriber = "Synthetic second doctor"+ try EditorTransaction.save(context: context) { try stale.apply(to: item, context: context) }+ #expect(item.repeatsLeft == 7 && item.prescribedBy == "Synthetic second doctor")+ stale.repeats = "4"+ #expect(throws: PrescriptionError.self) { try stale.apply(to: item, context: context) }+ #expect(item.repeatsLeft == 7)+ let cleared = PrescriptionDraft(medication: item)+ cleared.hasDate = false+ cleared.prescriber = " "+ cleared.days = ""+ cleared.repeats = ""+ try EditorTransaction.save(context: context) { try cleared.apply(to: item, context: context) }+ #expect(PrescriptionService.details(item).isEmpty)+ }+ @Test func cancelledDraftAndCombinedEditorFailureLeavePersistedPrescriptionIntact() throws {+ let (store, item) = try setup()+ let context = store.mainContext+ try set(item, context: context)+ let before = PrescriptionService.details(item)+ let cancelled = PrescriptionDraft(medication: item)+ cancelled.repeats = "99"+ #expect(PrescriptionService.details(item) == before)+ #expect(throws: RecordingError.self) {+ try EditorTransaction.save(context: context) {+ try cancelled.apply(to: item, context: context)+ item.name = "Unsaved change"+ throw RecordingError.saveFailed+ }+ }+ let reloaded = try #require(try ModelContext(store).fetch(FetchDescriptor<Medication>()).first)+ #expect(PrescriptionService.details(reloaded) == before)+ #expect(reloaded.name == "Synthetic medicine")+ }++ @Test func decrementZeroFloorUndoAndRepeatedOrStaleActionsAreGuarded() throws {+ let (store, item) = try setup()+ let context = store.mainContext+ try set(item, context: context, repeats: "2")+ let service = PrescriptionService(context: context)+ let captured = try service.capture(item)+ let first = try service.decrement(captured)+ #expect(item.repeatsLeft == 1)+ #expect(throws: PrescriptionError.self) { try service.decrement(captured) }+ let second = try service.decrement(service.capture(item))+ #expect(item.repeatsLeft == 0)+ #expect(throws: PrescriptionError.self) { try service.decrement(service.capture(item)) }+ #expect(throws: PrescriptionError.self) { try service.undo(first) }+ try service.undo(second)+ #expect(item.repeatsLeft == 1)+ #expect(throws: PrescriptionError.self) { try service.undo(second) }+ let next = try service.decrement(service.capture(item))+ let edit = PrescriptionDraft(medication: item)+ edit.prescriber = "Updated clinic"+ try EditorTransaction.save(context: context) { try edit.apply(to: item, context: context) }+ #expect(throws: PrescriptionError.self) { try service.undo(next) }+ #expect(item.repeatsLeft == 0)+ }+ @Test func medicationArchiveRestoreInvalidatesCapturedRepeatActions() throws {+ let (store, item) = try setup()+ let context = store.mainContext+ try set(item, context: context)+ let service = PrescriptionService(context: context)+ let captured = try service.capture(item)+ let receipt = try service.decrement(captured)+ let records = MedicationService(context: context)+ try records.setActive(item, false)+ #expect(throws: DefinitionError.self) { try service.undo(receipt) }+ try records.setActive(item, true)+ #expect(throws: PrescriptionError.self) { try service.undo(receipt) }+ #expect(throws: PrescriptionError.self) { try service.decrement(captured) }+ #expect(item.repeatsLeft == 2)+ }++ @Test func unknownCountAndSaveFailureLeaveCountUnchangedAndRetryWorks() throws {+ let (store, item) = try setup()+ let context = store.mainContext+ let service = PrescriptionService(context: context)+ #expect(throws: PrescriptionError.self) { try service.decrement(service.capture(item)) }+ try set(item, context: context)+ let original = item.prescriptionRevision+ let capture = try service.capture(item)+ #expect(throws: RecordingError.self) {+ try service.decrement(capture, save: { throw RecordingError.saveFailed })+ }+ #expect(item.repeatsLeft == 3 && item.prescriptionRevision == original)+ let fresh = ModelContext(store)+ #expect(try fresh.fetch(FetchDescriptor<Medication>()).first?.repeatsLeft == 3)+ let receipt = try service.decrement(capture)+ #expect(throws: RecordingError.self) {+ try service.undo(receipt, save: { throw RecordingError.saveFailed })+ }+ #expect(item.repeatsLeft == 2 && item.prescriptionRevision == receipt.savedRevision)+ try service.undo(receipt)+ #expect(item.repeatsLeft == 3)+ }+ @Test func capturedOwnerSurvivesSelectionButRejectsForeignAndArchivedLifecycle() throws {+ let (store, me) = try setup()+ let context = store.mainContext+ let profiles = ProfileService(context: context)+ let one = try profiles.create(displayName: "Same name")+ let two = try profiles.create(displayName: "Same name")+ let medication = try MedicationService(context: context).createAsNeededMedication(name: me.name, profileID: one.id)+ let other = try MedicationService(context: context).createAsNeededMedication(name: me.name, profileID: two.id)+ for item in [me, medication, other] { try set(item, context: context) }+ let service = PrescriptionService(context: context)+ let capture = try service.capture(medication)+ let receipt = try service.decrement(capture)+ #expect(medication.repeatsLeft == 2 && me.repeatsLeft == 3 && other.repeatsLeft == 3)+ let forged = PrescriptionCapture(+ medicationID: medication.id, profileID: two.id, lifecycleID: two.lifecycleID!, revision: medication.prescriptionRevision)+ #expect(throws: ProfileError.self) { try service.decrement(forged) }+ try profiles.setArchived(one, true)+ #expect(throws: ProfileError.self) { try service.undo(receipt) }+ try profiles.setArchived(one, false)+ #expect(throws: ProfileError.self) { try service.undo(receipt) }+ #expect(throws: ProfileError.self) { try service.decrement(capture) }+ #expect(medication.repeatsLeft == 2)+ }+ @Test func historicalSyntheticDiskStoreUpgradesAndPrescriptionSurvivesRelaunch() throws {+ let bundle = Bundle(for: PrescriptionFixtureMarker.self)+ let source = try #require(bundle.url(forResource: "pre-prescription", withExtension: "store"))+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let file = directory.appendingPathComponent("synthetic.store")+ try FileManager.default.copyItem(at: source, to: file)+ let schema = AppEnvironment.schema+ func open() throws -> ModelContainer {+ try ModelContainer(for: schema, configurations: [+ ModelConfiguration(schema: schema, url: file, cloudKitDatabase: .none)+ ])+ }+ let store = try open()+ let context = store.mainContext+ try ProfileMigration.bootstrap(context)+ let item = try #require(try context.fetch(FetchDescriptor<Medication>()).first)+ #expect(item.id.uuidString == "9B4A0A43-D3B0-4A90-9674-4CF7F6C02502")+ #expect(PrescriptionService.details(item).isEmpty && item.prescriptionRevision == nil)+ #expect(item.defaultDoseAmount == 2 && item.recognitionPhotoData == Data([1, 2, 3, 4]))+ #expect(item.fixedTimesData == Data([9, 8, 7]))+ let event = try #require(try context.fetch(FetchDescriptor<Administration>()).first)+ #expect(event.isDeleted && event.medicationID == item.id)+ let run = try #require(try context.fetch(FetchDescriptor<RoutineRun>()).first)+ #expect(run.definitionSnapshotData == Data("frozen synthetic bytes".utf8))+ try set(item, context: context)+ let reopened = try open()+ let reloaded = try #require(try reopened.mainContext.fetch(FetchDescriptor<Medication>()).first)+ #expect(PrescriptionService.details(reloaded) == PrescriptionService.details(item))+ #expect(reloaded.prescriptionRevision == item.prescriptionRevision)+ #expect(try reopened.mainContext.fetch(FetchDescriptor<Administration>()).first?.isDeleted == true)+ }++ @Test func exportIncludesOnlySelectedOwnerEscapesPrescriberAndRetainsZero() throws {+ let (store, me) = try setup()+ let context = store.mainContext+ let profile = try ProfileService(context: context).create(displayName: "Synthetic dependant")+ let item = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic dependant medicine", profileID: profile.id)+ try set(item, context: context, repeats: "0")+ let draft = PrescriptionDraft(medication: item)+ draft.prescriber = "# clinic <script>"+ try EditorTransaction.save(context: context) { try draft.apply(to: item, context: context) }+ let export = MedicationPresentation.consultationExport([me, item], profileID: profile.id)+ #expect(export.markdown.contains("**Prescribed on:** 2026\\-10\\-08"))+ #expect(export.markdown.contains("**Prescribed by:** \\# clinic \\<script\\>"))+ #expect(export.markdown.contains("**Supply lasts (days):** 30"))+ #expect(export.markdown.contains("**Repeats left:** 0"))+ let empty = MedicationPresentation.consultationExport([me], profileID: ProfileIdentity.me)+ #expect(!empty.markdown.contains("Prescribed") && !empty.markdown.contains("Repeats left"))+ }+}++private final class PrescriptionFixtureMarker: NSObject {}
diff --git a/Meddy/MeddyTests/MeddySnoozeTests.swift b/Meddy/MeddyTests/MeddySnoozeTests.swiftindex c439576..ebae125 100644--- a/Meddy/MeddyTests/MeddySnoozeTests.swift+++ b/Meddy/MeddyTests/MeddySnoozeTests.swift@@ -22,6 +22,17 @@ struct MeddySnoozeTests { try JSONDecoder().decode( PlannedReminder.self, from: #require(request.content.userInfo["meddy.payload"] as? Data)) }+ @Test func foregroundMedicationSnoozeDefersReminderWithoutRecordingDose() async throws {+ let clock = Date()+ let (store, medication) = try setup(at: clock)+ let client = SnoozeNotifications()+ let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+ service.snoozeMedication(medication.id)+ await service.waitForRefresh()+ let reminder = try decoded(#require(client.requests.first))+ #expect(reminder.deliveryAt == clock.addingTimeInterval(900))+ #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+ } @Test func snoozeAnchorsToActionClockAndRefreshNeverRecreatesOriginalOverdueRequest() async throws { var clock = Date() let (store, _) = try setup(at: clock)
diff --git a/Meddy/MeddyTests/MeddyTodayActionTests.swift b/Meddy/MeddyTests/MeddyTodayActionTests.swiftnew file mode 100644index 0000000..6e830e2--- /dev/null+++ b/Meddy/MeddyTests/MeddyTodayActionTests.swift@@ -0,0 +1,53 @@+import Foundation+import SwiftData+import Testing++@testable import Meddy++@MainActor+struct MeddyTodayActionTests {+ @Test func batchTakeAndUndoPreserveQuantitySnapshotsAndSeparateProfileHistory() throws {+ let store = try AppEnvironment.makeContainer(isolated: true)+ let context = store.mainContext+ let service = MedicationService(context: context)+ let first = try service.createAsNeededMedication(+ name: "Synthetic first", dose: .init(description: "", amount: 1.5, unit: "measure"))+ let second = try service.createAsNeededMedication(name: "Synthetic second")+ let otherProfile = try ProfileService(context: context).create(displayName: "Synthetic other")+ let other = try service.createAsNeededMedication(+ name: "Synthetic first", profileID: otherProfile.id)+ let otherEvent = try TodayMedicationAction.take([other], at: Date(), context: context)[0]+ let timestamp = Date()+ let events = try TodayMedicationAction.take([first, second], at: timestamp, context: context)+ #expect(events.count == 2)+ #expect(events.allSatisfy { $0.profileID == ProfileIdentity.me && $0.timestamp == timestamp })+ #expect(events[0].recordedDose.amount == 1.5 && events[1].recordedDose == .unknown)+ try TodayMedicationAction.undo(events, context: context)+ let ids = Set(events.map(\.id))+ let durableContext = ModelContext(store)+ let durableRows = try durableContext.fetch(FetchDescriptor<Administration>())+ let undone = durableRows.filter { ids.contains($0.id) }+ #expect(undone.count == 2)+ #expect(undone.allSatisfy { $0.isDeleted })+ #expect(durableRows.first { $0.id == otherEvent.id }?.isDeleted == false)+ #expect(!otherEvent.isDeleted)+ #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 3)+ try TodayMedicationAction.undo(events, context: context)+ #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 3)+ }++ @Test func invalidMemberRollsBackWholeBatchInsteadOfLeavingPartialDose() throws {+ let store = try AppEnvironment.makeContainer(isolated: true)+ let context = store.mainContext+ let first = try MedicationService(context: context).createAsNeededMedication(+ name: "Synthetic first")+ let profile = try ProfileService(context: context).create(displayName: "Synthetic archived")+ let second = try MedicationService(context: context).createAsNeededMedication(+ name: "Synthetic second", profileID: profile.id)+ try ProfileService(context: context).setArchived(profile, true)+ #expect(throws: (any Error).self) {+ try TodayMedicationAction.take([first, second], at: Date(), context: context)+ }+ #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 0)+ }+}
diff --git a/Meddy/MeddyTests/PrescriptionFixtures/pre-prescription.store b/Meddy/MeddyTests/PrescriptionFixtures/pre-prescription.storenew file mode 100644index 0000000..3931f77Binary files /dev/null and b/Meddy/MeddyTests/PrescriptionFixtures/pre-prescription.store differ
diff --git a/Meddy/MeddyUITests/MeddyEditorUITests.swift b/Meddy/MeddyUITests/MeddyEditorUITests.swiftindex 5e73a55..14a873f 100644--- a/Meddy/MeddyUITests/MeddyEditorUITests.swift+++ b/Meddy/MeddyUITests/MeddyEditorUITests.swift@@ -7,12 +7,12 @@ final class MeddyEditorUITests: XCTestCase { let app = XCUIApplication() app.launchEnvironment["MEDDY_TESTING"] = "1" app.launch()- XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 8))+ XCTAssertTrue(app.tabBars.buttons["Medications"].waitForExistence(timeout: 8)) for kind in ["Medication", "Treatment item", "Timed routine", "Ordered routine"] { if kind == "Medication" {- app.tabBars.buttons["Today"].tap()- app.buttons["Add as-needed medication"].tap()+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Add medication"].tap() } else { app.tabBars.buttons["Routines"].tap() app.buttons["Add care item"].tap()
diff --git a/Meddy/MeddyUITests/MeddyFirstSliceUITests.swift b/Meddy/MeddyUITests/MeddyFirstSliceUITests.swiftindex 371c182..7a5cb54 100644--- a/Meddy/MeddyUITests/MeddyFirstSliceUITests.swift+++ b/Meddy/MeddyUITests/MeddyFirstSliceUITests.swift@@ -3,77 +3,142 @@ import XCTest @MainActor final class MeddyFirstSliceUITests: XCTestCase { func testNameOnlyCreationTakenAndUndoWithoutNotificationPermission() {+ continueAfterFailure = false let app = XCUIApplication() app.launchEnvironment["MEDDY_TESTING"] = "1" app.launch() XCTAssertTrue(app.tabBars.buttons["Today"].waitForExistence(timeout: 10)) XCTAssertTrue(app.tabBars.buttons["Medications"].exists) XCTAssertTrue(app.tabBars.buttons["Routines"].exists)- app.buttons["Add as-needed medication"].tap()+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Add medication"].tap()+ let form = app.descendants(matching: .any)["medicationEditorForm"].firstMatch+ func scroll(_ down: Bool) {+ let upper = form.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.15))+ let lower = form.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.45))+ if down { upper.press(forDuration: 0.05, thenDragTo: lower) } else { lower.press(forDuration: 0.05, thenDragTo: upper) }+ }+ func reveal(_ element: XCUIElement, requireHit: Bool = true) {+ for attempt in 0..<16 {+ if element.exists {+ let vertical = element.frame.midY+ if (!requireHit || element.isHittable) && vertical > 160 && vertical < app.frame.height * 0.55 { return }+ scroll(vertical < 160)+ } else {+ scroll(attempt >= 8)+ }+ }+ if !element.exists || (requireHit && !element.isHittable) {+ let attachment = XCTAttachment(screenshot: app.screenshot())+ attachment.name = "Medication editor navigation failure"+ attachment.lifetime = .keepAlways+ add(attachment)+ print("Unreachable \(element): \(app.debugDescription)")+ }+ XCTAssertTrue(element.exists && (!requireHit || element.isHittable))+ } let name = app.textFields["Name"] XCTAssertTrue(name.waitForExistence(timeout: 5))+ reveal(app.buttons["Add photo"]) XCTAssertTrue(app.buttons["Add photo"].exists) XCTAssertFalse(app.buttons["Remove photo"].exists)+ reveal(name) name.tap() name.typeText("Synthetic UI item")- if app.keyboards.firstMatch.exists { app.swipeUp() }- // Tap the menu label; the Form accessibility row extends beyond its control.- app.staticTexts["Timing option"].tap()- XCTAssertTrue(app.buttons["Before sleeping"].waitForExistence(timeout: 5))+ if app.keyboards.firstMatch.exists { scroll(false) }+ // Optional prescription rows make the form longer; reveal the actual menu label.+ let timing = app.descendants(matching: .any)["Timing option"].firstMatch+ reveal(timing, requireHit: false)+ // The native menu can expose a full-row button; tap its leading label rather than empty row space.+ print("Timing control frame: \(timing.frame); form: \(form.frame)")+ timing.coordinate(withNormalizedOffset: CGVector(dx: 0.15, dy: 0.5)).tap()+ let option = app.buttons["Before sleeping"]+ let opened = option.waitForExistence(timeout: 5)+ if !opened {+ let attachment = XCTAttachment(screenshot: app.screenshot())+ attachment.name = "Timing menu did not open"+ attachment.lifetime = .keepAlways+ add(attachment)+ print(app.debugDescription)+ }+ XCTAssertTrue(opened) app.buttons["Before sleeping"].tap() let requirements = app.descendants(matching: .any)["medicationRequirements"]+ reveal(requirements, requireHit: false) XCTAssertEqual(requirements.value as? String, "Before sleeping") app.buttons["Save"].tap()- let taken = app.buttons["Mark Synthetic UI item taken"]+ app.buttons["Synthetic UI item"].tap()+ let taken = app.buttons["Log dose"] XCTAssertTrue(taken.waitForExistence(timeout: 5)) taken.tap()+ let logSave = app.buttons["Save"]+ for _ in 0..<6 where !logSave.isHittable { app.swipeUp() }+ logSave.tap() let undo = app.buttons["Undo Taken"] XCTAssertTrue(undo.waitForExistence(timeout: 5))- XCTAssertTrue(app.staticTexts["Dose not recorded"].exists)+ XCTAssertTrue(app.staticTexts["Dose not recorded"].firstMatch.exists) undo.tap() XCTAssertTrue(app.staticTexts["Not logged yet"].waitForExistence(timeout: 5)) XCTAssertTrue(taken.exists) XCTAssertFalse(app.alerts.firstMatch.exists) } func testUserFollowupMessageAndDelaySaveWithoutSystemPermissionAndUndoStillWorks() {+ continueAfterFailure = false let app = XCUIApplication() app.launchEnvironment["MEDDY_TESTING"] = "1" app.launch()- XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))- app.buttons["Add as-needed medication"].tap()+ XCTAssertTrue(app.tabBars.buttons["Medications"].waitForExistence(timeout: 10))+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Add medication"].tap()+ let form = app.descendants(matching: .any)["medicationEditorForm"].firstMatch+ func scroll(_ down: Bool) {+ let upper = form.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.15))+ let lower = form.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.45))+ if down { upper.press(forDuration: 0.05, thenDragTo: lower) } else { lower.press(forDuration: 0.05, thenDragTo: upper) }+ }+ // End-of-form rows cannot scroll to the center; native focus scrolls entered fields above the keyboard.+ func reveal(_ element: XCUIElement) {+ for attempt in 0..<16 {+ if element.exists {+ let vertical = element.frame.midY+ if element.isHittable && vertical > 160 && vertical < app.frame.height - 70 { break }+ scroll(vertical < 160)+ } else {+ scroll(attempt >= 8)+ }+ }+ XCTAssertTrue(+ element.exists && element.isHittable && element.frame.midY > 160+ && element.frame.midY < app.frame.height - 70,+ "\(element.identifier): \(element.frame)")+ } func fill(_ id: String, _ value: String) { let field = app.descendants(matching: .any)[id].firstMatch- for _ in 0..<10 {- if field.exists && field.isHittable { break }- app.swipeUp()- }- XCTAssertTrue(field.isHittable, id)+ reveal(field) field.tap() field.typeText(value)- if app.keyboards.firstMatch.exists { app.swipeUp() }+ if app.keyboards.firstMatch.exists { scroll(false) } } fill("Name", "Synthetic follow-up UI") let toggle = app.switches["followupEnabled"]- for _ in 0..<10 {- if toggle.exists && toggle.isHittable { break }- app.swipeUp()- }- XCTAssertTrue(toggle.isHittable)+ reveal(toggle) toggle.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()- app.swipeUp()+ // Revealing the conditional message field verifies enabled state after the form rearranges. fill("followupMessage", "Synthetic later reminder") fill("followupMinutes", "17") app.buttons["Save"].tap()- let taken = app.buttons["Mark Synthetic follow-up UI taken"]+ app.buttons["Synthetic follow-up UI"].tap()+ let taken = app.buttons["Log dose"] XCTAssertTrue(taken.waitForExistence(timeout: 5)) taken.tap()+ let logSave = app.buttons["Save"]+ for _ in 0..<6 where !logSave.isHittable { app.swipeUp() }+ logSave.tap() let undo = app.buttons["Undo Taken"] XCTAssertTrue(undo.waitForExistence(timeout: 5)) undo.tap() XCTAssertTrue(app.staticTexts["Not logged yet"].waitForExistence(timeout: 5))- app.tabBars.buttons["Medications"].tap()- app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic follow-up UI"))- .firstMatch.tap()+ let message = app.descendants(matching: .any).matching( NSPredicate(format: "label CONTAINS %@", "Synthetic later reminder") ).firstMatch@@ -90,27 +155,32 @@ final class MeddyFirstSliceUITests: XCTestCase { let app = XCUIApplication() app.launchEnvironment["MEDDY_TESTING"] = "1" app.launch()- XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))- app.buttons["Add as-needed medication"].tap()+ XCTAssertTrue(app.tabBars.buttons["Medications"].waitForExistence(timeout: 10))+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Add medication"].tap()+ let form = app.descendants(matching: .any)["medicationEditorForm"].firstMatch+ func scroll(_ down: Bool) {+ let upper = form.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.15))+ let lower = form.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.45))+ if down { upper.press(forDuration: 0.05, thenDragTo: lower) } else { lower.press(forDuration: 0.05, thenDragTo: upper) }+ } func fill(_ id: String, _ value: String) { let field = app.textFields[id]- let form =- app.collectionViews.allElementsBoundByIndex.first { $0.textFields[id].exists }- ?? app.collectionViews.firstMatch- let bar = app.buttons["Save"]- // The simulator can report a clipped field as hittable behind the navigation bar.- for _ in 0..<10 {- if field.exists && field.isHittable && field.frame.minY > bar.frame.maxY { break }- if field.exists && field.frame.minY <= bar.frame.maxY {- form.swipeDown()+ for attempt in 0..<16 {+ if field.exists {+ let vertical = field.frame.midY+ if field.isHittable && vertical > 160 && vertical < app.frame.height - 70 { break }+ scroll(vertical < 160) } else {- form.swipeUp()+ scroll(attempt >= 8) } }- XCTAssertTrue(field.isHittable && field.frame.minY > bar.frame.maxY, id)+ XCTAssertTrue(+ field.exists && field.isHittable && field.frame.midY > 160+ && field.frame.midY < app.frame.height - 70, "\(id): \(field.frame)") field.tap() field.typeText(value)- if app.keyboards.firstMatch.exists { form.swipeUp() }+ if app.keyboards.firstMatch.exists { scroll(false) } } func expectStatus(_ text: String) { // SwiftUI Form/List can combine status text into one accessibility row.@@ -129,7 +199,7 @@ final class MeddyFirstSliceUITests: XCTestCase { } XCTAssertTrue(toggle.isHittable) toggle.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()- app.swipeUp() // Form materializes the newly enabled rows as they enter view.+ // The bounded fill helper locates adjacent new rows without a page-sized overshoot. fill("doseLimitintervalHours", "3") fill("doseLimitmaximum", "7.5") XCTAssertFalse(app.textFields["doseLimitwindowHours"].exists)@@ -137,14 +207,18 @@ final class MeddyFirstSliceUITests: XCTestCase { XCTAssertFalse(app.textFields["doseLimitingredients"].exists) XCTAssertFalse(app.textFields["doseLimitsource"].exists) app.buttons["Save"].tap()+ app.buttons["Synthetic interval UI"].tap() expectStatus("Fits your entered limits") expectStatus("Remaining: 7.5 measure in the last 24 hours")- let taken = app.buttons["Mark Synthetic interval UI taken"]+ let taken = app.buttons["Log dose"] for _ in 0..<8 { if taken.isHittable { break } app.swipeDown() } taken.tap()+ let logSave = app.buttons["Save"]+ for _ in 0..<6 where !logSave.isHittable { app.swipeUp() }+ logSave.tap() expectStatus("Wait before another dose") expectStatus("Remaining: 6.5 measure in the last 24 hours") expectStatus("Next dose:")@@ -161,22 +235,28 @@ final class MeddyFirstSliceUITests: XCTestCase { let app = XCUIApplication() app.launchEnvironment["MEDDY_TESTING"] = "1" app.launch()- XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))- app.buttons["Add as-needed medication"].tap()+ XCTAssertTrue(app.tabBars.buttons["Medications"].waitForExistence(timeout: 10))+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Add medication"].tap()+ for _ in 0..<8 where !app.buttons["Add photo"].isHittable { app.swipeUp() } XCTAssertTrue(app.staticTexts["Add photo"].waitForExistence(timeout: 5)) app.staticTexts["Add photo"].tap() let cancelButtons = app.buttons.matching(identifier: "Cancel") XCTAssertTrue(cancelButtons.firstMatch.waitForExistence(timeout: 5)) cancelButtons.element(boundBy: cancelButtons.count - 1).tap()- XCTAssertTrue(app.textFields["Name"].waitForExistence(timeout: 5))+ // After picker dismissal, reveal Name if the form has scrolled or virtualized it.+ XCTAssertTrue(app.buttons["Add photo"].waitForExistence(timeout: 5))+ for _ in 0..<8 where !app.buttons["Add photo"].isHittable { app.swipeUp() } XCTAssertTrue(app.buttons["Add photo"].exists) XCTAssertFalse(app.buttons["Remove photo"].exists) let name = app.textFields["Name"]+ for _ in 0..<8 where !name.isHittable { app.swipeDown() }+ XCTAssertTrue(name.exists && name.isHittable) name.tap() name.typeText("Synthetic photo-free item") if app.keyboards.firstMatch.exists { app.swipeUp() } app.buttons["Save"].tap()- XCTAssertTrue(app.buttons["Mark Synthetic photo-free item taken"].waitForExistence(timeout: 5))+ XCTAssertTrue(app.buttons["Synthetic photo-free item"].waitForExistence(timeout: 5)) XCTAssertFalse(app.alerts.firstMatch.exists) }
diff --git a/Meddy/MeddyUITests/MeddyPhotoUITests.swift b/Meddy/MeddyUITests/MeddyPhotoUITests.swiftnew file mode 100644index 0000000..67996e9--- /dev/null+++ b/Meddy/MeddyUITests/MeddyPhotoUITests.swift@@ -0,0 +1,120 @@+import XCTest++@MainActor+final class MeddyPhotoUITests: XCTestCase {+ func testDarkRecognitionPhotosAndDraftRemoval() { inspectPhotos(appearance: "dark") }+ func testLightRecognitionPhotosAndDraftRemoval() { inspectPhotos(appearance: "light") }++ private func inspectPhotos(appearance: String) {+ continueAfterFailure = false+ let app = XCUIApplication()+ app.launchEnvironment["MEDDY_TESTING"] = "1"+ app.launchEnvironment["MEDDY_TEST_REDESIGN_REFERENCE"] = "1"+ app.launchEnvironment["MEDDY_TEST_RECOGNITION_PHOTOS"] = "1"+ app.launchEnvironment["MEDDY_TEST_APPEARANCE"] = appearance+ app.launch()+ XCTAssertTrue(app.buttons["takeDueMedications"].waitForExistence(timeout: 10))+ let dueVitamin = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Vitamin D3")).firstMatch+ XCTAssertEqual(dueVitamin.value as? String, "Recognition photo attached")+ capture("today-photos-" + appearance, app: app)+ let tile = app.buttons["Log dose for Paracetamol"]+ reveal(tile, app: app)+ XCTAssertEqual(tile.value as? String, "Recognition photo attached")+ capture("as-needed-photos-" + appearance, app: app)+ openMedicationLibrary(app: app)+ let row = app.buttons["Paracetamol"]+ XCTAssertTrue(row.waitForExistence(timeout: 5))+ XCTAssertEqual(row.value as? String, "Recognition photo attached")+ capture("library-photos-" + appearance, app: app)+ openProfilePicker(app: app)+ app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label == %@", "careProfile_", "Alex")).firstMatch.tap()+ openMedicationLibrary(app: app)+ XCTAssertTrue(row.waitForExistence(timeout: 3))+ XCTAssertNotEqual(row.value as? String, "Recognition photo attached")+ XCTAssertFalse(app.buttons["Vitamin D3"].exists)+ openProfilePicker(app: app)+ app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label == %@", "careProfile_", "Me")).firstMatch.tap()+ openMedicationLibrary(app: app)+ XCTAssertEqual(row.value as? String, "Recognition photo attached")+ reveal(row, app: app)+ row.tap()+ let photo = app.descendants(matching: .any)["medicationRecognitionPhoto"].firstMatch+ XCTAssertTrue(photo.waitForExistence(timeout: 5))+ XCTAssertEqual(photo.frame.width, 220, accuracy: 1)+ XCTAssertTrue(photo.isHittable)+ capture("detail-photo-" + appearance, app: app)+ app.buttons["Change recognition photo"].tap()+ reveal(app.buttons["Replace photo"], app: app)+ XCTAssertTrue(app.buttons["Replace photo"].waitForExistence(timeout: 5))+ XCTAssertTrue(app.buttons["Remove photo"].exists)+ capture("editor-photo-" + appearance, app: app)+ app.buttons["Replace photo"].tap()+ let cancelButtons = app.buttons.matching(identifier: "Cancel")+ XCTAssertTrue(cancelButtons.firstMatch.waitForExistence(timeout: 5))+ cancelButtons.element(boundBy: cancelButtons.count - 1).tap()+ XCTAssertTrue(app.buttons["Replace photo"].waitForExistence(timeout: 3))+ reveal(app.buttons["Remove photo"], app: app)+ app.buttons["Remove photo"].tap()+ XCTAssertTrue(app.buttons["Add photo"].waitForExistence(timeout: 3))+ app.buttons["Cancel"].tap()+ XCTAssertTrue(photo.waitForExistence(timeout: 3))+ reveal(app.buttons["Log dose"], app: app)+ app.buttons["Log dose"].tap()+ XCTAssertTrue(photo.waitForExistence(timeout: 3))+ XCTAssertEqual(photo.frame.width, 160, accuracy: 1)+ capture("dose-photo-" + appearance, app: app)+ app.buttons["Cancel"].tap()+ app.buttons["Change recognition photo"].tap()+ reveal(app.buttons["Remove photo"], app: app)+ app.buttons["Remove photo"].tap()+ app.buttons["Save"].tap()+ XCTAssertTrue(app.buttons["Add recognition photo"].waitForExistence(timeout: 3))+ XCTAssertFalse(photo.exists)+ openMedicationLibrary(app: app)+ XCTAssertTrue(row.waitForExistence(timeout: 3))+ XCTAssertNotEqual(row.value as? String, "Recognition photo attached")+ XCTAssertEqual(app.buttons["Vitamin D3"].value as? String, "Recognition photo attached")+ XCTAssertFalse(app.alerts.firstMatch.exists)+ }++ private func openMedicationLibrary(app: XCUIApplication) {+ let tab = app.tabBars.buttons["Medications"]+ let search = app.textFields["medicationSearch"]+ tab.tap()+ // Profile-scoped navigation can finish rebuilding after the first tab tap.+ if !search.waitForExistence(timeout: 3) && !tab.isSelected { tab.tap() }+ XCTAssertTrue(search.waitForExistence(timeout: 5))+ }++ private func openProfilePicker(app: XCUIApplication) {+ app.tabBars.buttons["Today"].tap()+ let picker = app.buttons["careProfilePicker"]+ for _ in 0..<8 where !picker.isHittable { app.scrollViews.firstMatch.swipeDown() }+ XCTAssertTrue(picker.isHittable)+ picker.tap()+ }++ private func reveal(_ element: XCUIElement, app: XCUIApplication) {+ let form = app.descendants(matching: .any)["medicationEditorForm"].firstMatch+ let container = form.exists ? form : app.scrollViews.firstMatch+ for attempt in 0..<16 {+ if element.exists && element.isHittable && element.frame.midY > 160+ && element.frame.midY < app.frame.height - 70 { break }+ let upper = container.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.2))+ let lower = container.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))+ if element.exists ? element.frame.midY < 160 : attempt >= 8 {+ upper.press(forDuration: 0.05, thenDragTo: lower)+ } else {+ lower.press(forDuration: 0.05, thenDragTo: upper)+ }+ }+ XCTAssertTrue(element.exists && element.isHittable)+ }++ private func capture(_ name: String, app: XCUIApplication) {+ let attachment = XCTAttachment(screenshot: app.screenshot())+ attachment.name = name+ attachment.lifetime = .keepAlways+ add(attachment)+ }+}
diff --git a/Meddy/MeddyUITests/MeddyPrescriptionUITests.swift b/Meddy/MeddyUITests/MeddyPrescriptionUITests.swiftnew file mode 100644index 0000000..ac2c290--- /dev/null+++ b/Meddy/MeddyUITests/MeddyPrescriptionUITests.swift@@ -0,0 +1,111 @@+import XCTest++@MainActor final class MeddyPrescriptionUITests: XCTestCase {+ func testPrescriptionEditorCancelSaveAndRepeatUndo() {+ continueAfterFailure = false+ let app = XCUIApplication()+ app.launchEnvironment["MEDDY_TESTING"] = "1"+ app.launch()+ let picker = app.buttons["careProfilePicker"]+ XCTAssertTrue(picker.waitForExistence(timeout: 10))+ picker.tap()+ app.buttons["Manage profiles…"].tap()+ app.buttons["addDependant"].tap()+ let profileName = app.textFields["profileDisplayName"]+ XCTAssertTrue(profileName.waitForExistence(timeout: 3))+ profileName.tap()+ profileName.typeText("Synthetic prescription owner")+ app.buttons["Save"].tap()+ app.navigationBars["Care profiles"].buttons["Done"].tap()+ app.navigationBars["Profiles"].buttons["Done"].tap()+ XCTAssertTrue(app.tabBars.buttons["Medications"].waitForExistence(timeout: 3))+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Add medication"].tap()+ func reveal(_ element: XCUIElement) {+ for attempt in 0..<16 {+ if element.exists {+ let vertical = element.frame.midY+ if element.isHittable && vertical > 160 && vertical < app.frame.height * 0.55 { return }+ scroll(vertical < 160, app: app)+ } else {+ scroll(attempt >= 8, app: app)+ }+ }+ XCTAssertTrue(element.exists && element.isHittable)+ }+ func fill(_ id: String, _ text: String) {+ let field = app.textFields[id]+ reveal(field)+ field.tap()+ field.typeText(text)+ if app.keyboards.firstMatch.exists { scroll(false, app: app) }+ }+ fill("Name", "Synthetic prescription")+ let dateToggle = app.switches["prescriptionHasDate"]+ reveal(dateToggle)+ dateToggle.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()+ XCTAssertTrue(app.datePickers["prescriptionDate"].exists)+ fill("prescriptionPrescriber", "Synthetic clinic")+ fill("prescriptionDays", "30")+ fill("prescriptionRepeats", "2")+ app.buttons["Save"].tap()+ app.buttons["Synthetic prescription"].tap()+ let lower = app.buttons["lowerRepeats"]+ reveal(lower)+ let clinic = app.descendants(matching: .any).matching(NSPredicate(+ format: "label CONTAINS %@ OR value CONTAINS %@", "Synthetic clinic", "Synthetic clinic")+ ).firstMatch+ reveal(clinic)+ XCTAssertTrue(clinic.exists)+ reveal(lower)+ lower.tap()+ let undo = app.buttons["undoRepeatChange"]+ XCTAssertTrue(undo.waitForExistence(timeout: 5))+ undo.tap()+ XCTAssertFalse(undo.exists)+ lower.tap()+ lower.tap()+ XCTAssertFalse(lower.isEnabled)+ app.buttons["Edit"].tap()+ let repeats = app.textFields["prescriptionRepeats"]+ reveal(repeats)+ XCTAssertEqual(repeats.value as? String, "0")+ repeats.tap()+ repeats.typeText("9")+ app.buttons["Cancel"].tap()+ XCTAssertFalse(lower.isEnabled)+ app.buttons["Edit"].tap()+ reveal(repeats)+ XCTAssertEqual(repeats.value as? String, "0")+ app.buttons["Cancel"].tap()+ app.tabBars.buttons["Today"].tap()+ picker.tap()+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label == %@", "careProfile_", "Me")+ ).firstMatch.tap()+ app.tabBars.buttons["Medications"].tap()+ XCTAssertFalse(app.buttons["Synthetic prescription"].exists)+ app.tabBars.buttons["Today"].tap()+ picker.tap()+ app.buttons.matching(NSPredicate(+ format: "label BEGINSWITH %@", "Synthetic prescription owner")+ ).firstMatch.tap()+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Synthetic prescription"].tap()+ reveal(lower)+ XCTAssertFalse(lower.isEnabled)+ XCTAssertFalse(app.alerts.firstMatch.exists)+ }++ private func scroll(_ down: Bool, app: XCUIApplication) {+ let form = app.descendants(matching: .any)["medicationEditorForm"].firstMatch+ if form.exists {+ let upper = form.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.15))+ let lower = form.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.45))+ if down { upper.press(forDuration: 0.05, thenDragTo: lower) } else { lower.press(forDuration: 0.05, thenDragTo: upper) }+ } else {+ let view = app.collectionViews.count > 0 ? app.collectionViews.firstMatch : app.scrollViews.firstMatch+ if down { view.swipeDown() } else { view.swipeUp() }+ }+ }+}
diff --git a/Meddy/MeddyUITests/MeddyProfileUITests.swift b/Meddy/MeddyUITests/MeddyProfileUITests.swiftindex 3e55a84..681db3f 100644--- a/Meddy/MeddyUITests/MeddyProfileUITests.swift+++ b/Meddy/MeddyUITests/MeddyProfileUITests.swift@@ -8,6 +8,7 @@ final class MeddyProfileUITests: XCTestCase { let picker = app.buttons["careProfilePicker"] XCTAssertTrue(picker.waitForExistence(timeout: 8)) func manage() {+ app.tabBars.buttons["Today"].tap() picker.tap() app.buttons["Manage profiles…"].tap() }@@ -22,20 +23,27 @@ final class MeddyProfileUITests: XCTestCase { manage() add("Synthetic Alpha") app.navigationBars["Care profiles"].buttons["Done"].tap()- app.buttons["Add as-needed medication"].tap()+ app.navigationBars["Profiles"].buttons["Done"].tap()+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Add medication"].tap() let name = app.textFields["Name"] XCTAssertTrue(name.waitForExistence(timeout: 3)) name.tap() name.typeText("Synthetic same medicine") app.buttons["Save"].tap()- XCTAssertTrue(app.staticTexts["Synthetic same medicine"].waitForExistence(timeout: 4))+ XCTAssertTrue(+ app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine"))+ .firstMatch.waitForExistence(timeout: 4)) manage() add("Synthetic Beta") app.navigationBars["Care profiles"].buttons["Done"].tap()- XCTAssertFalse(app.staticTexts["Synthetic same medicine"].exists)+ app.navigationBars["Profiles"].buttons["Done"].tap()+ XCTAssertFalse(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine")).firstMatch.exists) picker.tap()- app.buttons["Synthetic Alpha"].tap()- XCTAssertTrue(app.staticTexts["Synthetic same medicine"].waitForExistence(timeout: 3))+ app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Synthetic Alpha")).firstMatch.tap()+ XCTAssertTrue(+ app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine"))+ .firstMatch.waitForExistence(timeout: 3)) manage() let alpha = app.cells.containing(.staticText, identifier: "Synthetic Alpha").firstMatch alpha.buttons["Rename"].tap()@@ -52,11 +60,14 @@ final class MeddyProfileUITests: XCTestCase { } app.buttons["Save"].tap() app.navigationBars["Care profiles"].buttons["Done"].tap()+ app.navigationBars["Profiles"].buttons["Done"].tap() XCTAssertTrue(picker.label.contains("Synthetic Renamed"))- XCTAssertTrue(app.staticTexts["Synthetic same medicine"].exists)+ XCTAssertTrue(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine")).firstMatch.exists) picker.tap()- app.buttons["Me"].tap()- XCTAssertFalse(app.staticTexts["Synthetic same medicine"].exists)+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label == %@", "careProfile_", "Me")+ ).firstMatch.tap()+ XCTAssertFalse(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine")).firstMatch.exists) app.terminate() app.launch() XCTAssertTrue(app.buttons["careProfilePicker"].waitForExistence(timeout: 8))
diff --git a/Meddy/MeddyUITests/MeddyRedesignUITests.swift b/Meddy/MeddyUITests/MeddyRedesignUITests.swiftnew file mode 100644index 0000000..697c35f--- /dev/null+++ b/Meddy/MeddyUITests/MeddyRedesignUITests.swift@@ -0,0 +1,108 @@+import XCTest++@MainActor+final class MeddyRedesignUITests: XCTestCase {+ func testDarkReferenceScreensAndPrimaryRecording() { inspectReference(appearance: "dark") }+ func testLightReferenceScreensAndPrimaryRecording() { inspectReference(appearance: "light") }++ private func inspectReference(appearance: String) {+ continueAfterFailure = false+ let app = XCUIApplication()+ app.launchEnvironment["MEDDY_TESTING"] = "1"+ app.launchEnvironment["MEDDY_TEST_REDESIGN_REFERENCE"] = "1"+ app.launchEnvironment["MEDDY_TEST_APPEARANCE"] = appearance+ app.launch()+ XCTAssertTrue(app.buttons["takeDueMedications"].waitForExistence(timeout: 10))+ capture("01-today-" + appearance, app: app)+ app.buttons["takeDueMedications"].tap()+ let undo = app.buttons["Undo Taken"]+ XCTAssertTrue(undo.waitForExistence(timeout: 3))+ undo.tap()+ XCTAssertTrue(app.buttons["takeDueMedications"].waitForExistence(timeout: 3))+ app.buttons["careProfilePicker"].tap()+ XCTAssertTrue(app.staticTexts["TRACKING FOR"].waitForExistence(timeout: 3))+ capture("09-profiles-" + appearance, app: app)+ app.navigationBars["Profiles"].buttons["Done"].tap()+ app.tabBars.buttons["Medications"].tap()+ XCTAssertTrue(app.textFields["medicationSearch"].waitForExistence(timeout: 3))+ capture("02-medications-" + appearance, app: app)+ let search = app.textFields["medicationSearch"]+ search.tap()+ search.typeText("Paracetamol\n")+ XCTAssertFalse(app.buttons["Metformin"].exists)+ app.buttons["Paracetamol"].tap()+ XCTAssertTrue(app.buttons["Log dose"].waitForExistence(timeout: 3))+ capture("04-medication-detail-" + appearance, app: app)+ app.buttons["Edit"].tap()+ XCTAssertTrue(app.textFields["Name"].waitForExistence(timeout: 3))+ capture("05-medication-editor-" + appearance, app: app)+ reveal(app.buttons["scheduleType_fixedTimes"], app: app, down: false)+ app.buttons["scheduleType_fixedTimes"].tap()+ let fixed = app.textFields["Times (HH:mm, separated by commas)"]+ reveal(fixed, app: app, down: false)+ fixed.tap()+ fixed.typeText("08:00, 18:00")+ app.buttons["scheduleType_asNeeded"].tap()+ app.buttons["scheduleType_fixedTimes"].tap()+ XCTAssertEqual(fixed.value as? String, "08:00, 18:00")+ app.buttons["Cancel"].tap()+ app.buttons["Log dose"].tap()+ XCTAssertTrue(app.buttons["Increase recorded quantity"].waitForExistence(timeout: 3))+ capture("06-log-dose-" + appearance, app: app)+ app.buttons["Increase recorded quantity"].tap()+ let save = app.buttons["Save"]+ reveal(save, app: app, down: false)+ save.tap()+ XCTAssertTrue(app.buttons["Undo Taken"].waitForExistence(timeout: 3))+ app.buttons["Undo Taken"].tap()+ app.tabBars.buttons["Routines"].tap()+ XCTAssertTrue(app.staticTexts["Eye drops"].waitForExistence(timeout: 3))+ capture("03-routines-" + appearance, app: app)+ app.buttons["Start"].firstMatch.tap()+ let circle = app.buttons["phoneTimerCircle"]+ XCTAssertTrue(circle.waitForExistence(timeout: 3))+ capture("07-timer-" + appearance, app: app)+ circle.tap()+ XCTAssertEqual(circle.label, "Pause round 1 of 3")+ circle.tap()+ XCTAssertEqual(circle.label, "Resume round 1 of 3")+ app.buttons["Close"].tap()+ let start = app.buttons["Start session"]+ reveal(start, app: app, down: false)+ start.tap()+ if app.buttons["Start selected session"].waitForExistence(timeout: 2) {+ app.buttons["Start selected session"].tap()+ }+ XCTAssertTrue(app.buttons["Done"].waitForExistence(timeout: 3))+ app.buttons["Done"].tap()+ XCTAssertTrue(app.buttons["Taken / Applied"].waitForExistence(timeout: 3))+ capture("08-ordered-session-" + appearance, app: app)+ app.buttons["Close"].tap()+ XCTAssertFalse(app.alerts.firstMatch.exists)+ }+ private func capture(_ name: String, app: XCUIApplication) {+ let attachment = XCTAttachment(screenshot: app.screenshot())+ attachment.name = name+ attachment.lifetime = .keepAlways+ add(attachment)+ }+ private func reveal(_ element: XCUIElement, app: XCUIApplication, down: Bool) {+ for _ in 0..<8 {+ if element.exists && element.isHittable { return }+ if app.collectionViews.count > 0 {+ if down {+ app.collectionViews.firstMatch.swipeDown()+ } else {+ app.collectionViews.firstMatch.swipeUp()+ }+ } else {+ if down {+ app.scrollViews.firstMatch.swipeDown()+ } else {+ app.scrollViews.firstMatch.swipeUp()+ }+ }+ }+ XCTAssertTrue(element.exists && element.isHittable)+ }+}
diff --git a/Meddy/MeddyUITests/MeddyRoutineUITests.swift b/Meddy/MeddyUITests/MeddyRoutineUITests.swiftindex a8febdd..8e437e3 100644--- a/Meddy/MeddyUITests/MeddyRoutineUITests.swift+++ b/Meddy/MeddyUITests/MeddyRoutineUITests.swift@@ -52,22 +52,28 @@ final class MeddyRoutineUITests: XCTestCase { app.buttons["Synthetic group"].tap() app.buttons["Start Session 1"].tap() XCTAssertTrue(- app.staticTexts["0 of 3 steps completed"].waitForExistence(timeout: 5), app.debugDescription)+ app.otherElements.matching(NSPredicate(format: "label == %@", "0 of 3 steps completed"))+ .firstMatch.waitForExistence(timeout: 5), app.debugDescription) app.buttons["Done"].tap() app.buttons["Start timer"].tap() XCTAssertTrue(app.buttons["phoneTimerCircle"].waitForExistence(timeout: 5)) XCTAssertEqual(app.buttons["phoneTimerCircle"].label, "Start round 1 of 1") app.buttons["phoneTimerCircle"].tap()- XCTAssertTrue(app.staticTexts["1 rounds completed"].waitForExistence(timeout: 8))+ let completed = NSPredicate(format: "label == %@", "All 1 rounds completed")+ expectation(for: completed, evaluatedWith: app.buttons["phoneTimerCircle"])+ waitForExpectations(timeout: 8) app.navigationBars.buttons.element(boundBy: 0).tap() reveal(app.buttons["Taken / Applied"], in: app) app.buttons["Taken / Applied"].tap()- XCTAssertTrue(app.staticTexts["3 of 3 steps completed"].waitForExistence(timeout: 5))+ XCTAssertTrue(+ app.otherElements.matching(NSPredicate(format: "label == %@", "3 of 3 steps completed"))+ .firstMatch.waitForExistence(timeout: 5)) app.buttons["Close"].tap() XCTAssertTrue(app.buttons["Start Session 2"].exists) app.buttons["Start Session 2"].tap() XCTAssertTrue(- app.staticTexts["0 of 3 steps completed"].waitForExistence(timeout: 5), app.debugDescription)+ app.otherElements.matching(NSPredicate(format: "label == %@", "0 of 3 steps completed"))+ .firstMatch.waitForExistence(timeout: 5), app.debugDescription) app.buttons["Skip step"].firstMatch.tap() XCTAssertTrue(app.buttons["Continue with skipped step"].exists) XCTAssertFalse(app.buttons["Taken / Applied"].exists)@@ -195,13 +201,19 @@ final class MeddyRoutineUITests: XCTestCase { field.typeText(text) } private func reveal(_ element: XCUIElement, in app: XCUIApplication) {- if app.keyboards.firstMatch.exists {- app.collectionViews.element(boundBy: app.collectionViews.count - 1).swipeUp()- }+ let collection = app.collectionViews.element(boundBy: max(0, app.collectionViews.count - 1))+ let scroll = app.collectionViews.count > 0 ? collection : app.scrollViews.firstMatch+ if app.keyboards.firstMatch.exists { scroll.swipeDown() }+ let bar = app.navigationBars.firstMatch+ let top = app.buttons["Save"].exists ? app.buttons["Save"].frame.maxY : (bar.exists ? bar.frame.maxY : 0) for _ in 0..<10 {- if element.exists && element.isHittable { return }- app.collectionViews.element(boundBy: app.collectionViews.count - 1).swipeUp()+ if element.exists && element.isHittable && element.frame.minY > top { return }+ if element.exists && element.frame.minY <= top {+ scroll.swipeDown()+ } else {+ scroll.swipeUp()+ } }- XCTAssertTrue(element.exists && element.isHittable)+ XCTAssertTrue(element.exists && element.isHittable && element.frame.minY > top, app.debugDescription) } }
diff --git a/Meddy/MeddyUITests/MeddyWakeUITests.swift b/Meddy/MeddyUITests/MeddyWakeUITests.swiftindex 1f4ce5d..8b0854e 100644--- a/Meddy/MeddyUITests/MeddyWakeUITests.swift+++ b/Meddy/MeddyUITests/MeddyWakeUITests.swift@@ -5,17 +5,17 @@ final class MeddyWakeUITests: XCTestCase { let app = XCUIApplication() app.launchEnvironment["MEDDY_TESTING"] = "1" app.launch()- XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 8))- app.buttons["Add as-needed medication"].tap()+ XCTAssertTrue(app.tabBars.buttons["Medications"].waitForExistence(timeout: 8))+ app.tabBars.buttons["Medications"].tap()+ app.buttons["Add medication"].tap() let name = app.textFields["Name"] XCTAssertTrue(name.waitForExistence(timeout: 3)) name.tap() name.typeText("Synthetic wake medicine") if app.keyboards.firstMatch.exists { app.swipeUp() }- let schedule = app.buttons["medicationSchedulePicker"]+ let schedule = app.buttons["scheduleType_afterWaking"] for _ in 0..<4 where !schedule.isHittable { app.swipeUp() } schedule.tap()- app.buttons["After waking"].tap() let offset = app.textFields["wakeOffsetMinutes"] for _ in 0..<4 where !offset.isHittable { app.swipeUp() } XCTAssertTrue(offset.waitForExistence(timeout: 3))@@ -23,8 +23,8 @@ final class MeddyWakeUITests: XCTestCase { offset.typeText(XCUIKeyboardKey.delete.rawValue + "35") app.buttons["Save"].tap() app.buttons["Medications"].tap()- XCTAssertTrue(app.staticTexts["Synthetic wake medicine"].waitForExistence(timeout: 4))- app.staticTexts["Synthetic wake medicine"].tap()+ XCTAssertTrue(app.buttons["Synthetic wake medicine"].waitForExistence(timeout: 4))+ app.buttons["Synthetic wake medicine"].tap() app.buttons["Edit"].tap() for _ in 0..<4 where !app.textFields["wakeOffsetMinutes"].isHittable { app.swipeUp() } XCTAssertEqual(app.textFields["wakeOffsetMinutes"].value as? String, "35")
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 078eee8..559026b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,7 +2,12 @@ ## Unreleased +### Changed+- Recreate the Meddy redesign in native SwiftUI with dark/light lavender tokens, purpose cards, focused Today actions, searchable medication lists, routine progress, grouped editors and avatar-based profiles. Preserve existing care history, frozen sessions, explicit timer continuation and dose-limit semantics without a schema migration.+- Restore medication recognition photos throughout the redesigned iPhone care screens, bring the detail image and Add/Replace/Remove editor controls forward, and retain existing photo storage and Save/Cancel behavior.+ ### Fixed+- Restore the scheduled medication detail’s Remind me later action through the existing reminder service, without recording a dose. - T2425: Open the saved child timer immediately after Start timer in an ordered routine, preserving its paused/resume state on return. - Apply strict Swift lint cleanup and focused helpers while preserving care/state semantics; replace the deprecated Watch foreground-state API with WKApplication. - T2419: Remove redundant Done editing keyboard buttons from care editors, retaining scrolling and explicit Save/Cancel.@@ -10,6 +15,7 @@ - T2413: Keep notification snoozes at their chosen 15-minute deadline, cancel queued originals, suppress elapsed replay and await background scheduling completion. ### Added+- Optional medication prescription date, doctor/clinic, user-entered supply-duration days and repeats left; profile-scoped editor/detail/export with explicit decrement and guarded Undo. - T2426: Short completion chime and longer per-round feedback: a two-pulse iPhone haptic pattern and two Watch notification pulses, subject to device sound/haptic settings. - T2423: Repository agent guide covering simulator tooling, recalled knowledge, synthetic stores, captured care/profile ownership and truthful initialization provenance. - T2421: Help-first simulator Makefile with isolated caches/results, fast targeted checks, strict lint and unchanged full serial publication gates.
diff --git a/Meddy/MeddyTests/PrescriptionFixtures/README.md b/Meddy/MeddyTests/PrescriptionFixtures/README.mdnew file mode 100644index 0000000..38ec14d--- /dev/null+++ b/Meddy/MeddyTests/PrescriptionFixtures/README.md@@ -0,0 +1,3 @@+Synthetic pre-prescription SwiftData fixture++Consolidated read-only SQLite backup of the synthetic `profile-fixtures/4a9daaa/fixture.store` generated during earlier schema verification. Contains one synthetic medication, purpose, deleted administration, treatment/completion and frozen routine/run; no personal records. Source SHA-256: 25a7b62850a69836c9a83e08506a38849349693d1ad96ec891c3ad640c403445. This predates prescription fields and also predates profile/wake additions, so acceptance proves upgrade from that historical schema; exact installed-1201a8d store upgrade and live CloudKit remain separate verification limits.
diff --git a/docs/meddy-design.md b/docs/meddy-design.mdindex d9cb9c0..f6091b5 100644--- a/docs/meddy-design.md+++ b/docs/meddy-design.md@@ -1687,3 +1687,21 @@ The App Intent declares background execution and `alwaysAllowed` authentication, Setup after an installation is requested: in Meddy choose the correct profile, set After waking and the offset on the medication or daily ordered-session slot, and enable reminders. In Shortcuts add **Meddy → Record Waking Up**, leave Profile as Me or explicitly select the intended dependant, and invoke it from the user's chosen automation. The action never records Taken automatically. No shortcut, notification permission, physical installation or live data action is performed during source verification. Update active phone/Watch copies together for the new shared schedule value. Verification: `WakeDomainFinal.xcresult` passed all 182 phone domain tests across 26 suites before the final owned-anchor/restore refinements. `WakeUnitReviewed.xcresult` then passed 34 final affected tests across 4 suites, covering wake domain/service/intent behavior, both actual old-schema fixtures, profile routing and phone companion handling. `WakeWatchFinal.xcresult` passed 13 tests across 2 suites, including preservation of nil versus captured wake IDs and rejection of foreign-anchor snapshots. `WakeUIFinal.xcresult` passed the medication/routine timing editor smoke, including persistence of the entered 35-minute offset. App Intent metadata was extracted into the built phone app. Independent read-only review found no remaining concrete blocker. `git diff --check` passed. Synthetic fixture lifetime and accessibility-tap issues were corrected before final passing runs; stalled asset/failure-diagnostic runs were stopped only by verified owned process IDs and fully drained. Those incomplete runs are not counted as acceptance. Existing simulator publication/frame/accessibility warnings remain; locked-device automation, real notification delivery, live CloudKit and physical Watch acceptance are not claimed.+++## Native visual redesign implementation (October 2026)++The supplied Meddy redesign handoff defines the current visual direction: native SwiftUI navigation, sheets and tabs; dark/light lavender app colors; user-purpose colors; a due-now Today hero; flat searchable medication rows; purpose routine cards and rings; grouped editors and profile selection through the Today avatar. Shared native components apply the same style to treatment/routine details, history, existing-log selection and appointment sharing. The HTML prototype remains reference material.++Existing purpose relationships already support the design; no model migration is required. The visual work retains captured ownership, canonical corrected history and Undo tombstones, frozen routine plans, independent scheduled occurrences, explicit skip confirmation and timer continuation. Timer round transitions do not auto-start the next round. The current execution service has no Skip-round operation, so that prototype control is omitted. Library routine cards open canonical execution rather than recording from a second surface. Dose checks describe entered limits and recorded quantities, including actual legacy windows; they make no medical-safety claim. Custom/unknown dose recording remains available in the dose sheet.++Focused simulator verification covers all nine designed screens in both appearances and primary recording/navigation interactions. See the implementation plan for gate status. This redesign changes no account, signing, entitlement or CloudKit configuration and requires no real-store reset.++Owner feedback on missing photos restores the existing §23 recognition surfaces within this visual direction. Medication library rows and Today due/later/PRN/taken cards show the current aspect-preserving thumbnail alongside the name. Medication detail presents its larger image near the heading, with an Add/Change recognition photo shortcut to the existing editor. The editor's Add/Replace/Remove draft controls follow the medication identity fields; detailed dose logging and ordered routine steps retain their recognition images. A medication without a photo keeps its name-based layout, without reserving an empty thumbnail. Existing nullable storage, bounded processing/cache, profile filtering, Save/Cancel behavior and iPhone-only scope remain unchanged.+++## 32. Approved prescription metadata (2026-10-08)++The owner approved optional medication prescription date (“prescribed at”), free-form doctor/clinic (“prescribed by”), user-entered supply-duration days and repeats remaining. The [approved plan](meddy-prescription-details-plan.md) defines validation, UI, correction and export. Civil dates retain their entered day across time zones. Supply duration is metadata, not an inferred course, remaining stock, countdown or dose rule. Blank means not recorded; zero repeats is an explicit value. A manual −1 repeat action on medication detail stops at zero and offers a revision-guarded latest Undo; direct editing/clearing remains available.++All medication modes support these fields, captured to the canonical medication/profile. A profile switch cannot redirect Save/decrement/Undo; owner archive/restore invalidates stale actions. Untouched prescription fields preserve newer values, while conflicting changed fields require reconciliation. Include recorded prescription fields in the existing selected-profile Markdown summary, reusing text escaping. No prescription history ledger, automatic refill scheduling, stock tracking, clinical warning, Watch prescription action or change to real care events is added.
diff --git a/docs/meddy-implementation-plan.md b/docs/meddy-implementation-plan.mdindex c03cc1b..60c852b 100644--- a/docs/meddy-implementation-plan.md+++ b/docs/meddy-implementation-plan.md@@ -292,3 +292,43 @@ Start timer now saves/returns the existing canonical timed child and immediately Completion services still emit once after durable completed-round progression, independent of view redraws. Their shared native adapter plays a bundled 0.85-second two-note PCM chime. iPhone uses two continuous Core Haptics pulses over 1.3 seconds, with the former success cue as an engine-error fallback; Watch uses two system notification pulses 0.7 seconds apart. Audio uses the ambient category and does not bypass silent mode/volume. Authorised background iPhone timer notifications use the same chime; background vibration remains under OS control. No new background mode, permission, signing or entitlement is introduced. Physical Watch delivery is not inferred from simulator results. Verification in the isolated feature branch from `bcba6d9`: phone domain tests passed **189 tests in 26 suites**, Watch domain/controller tests passed **14 tests in two suites**, and the new adapter passed strict SwiftLint after one formatting correction. Both app targets compiled, with the baseline `WKExtension` deprecation and App Intents metadata warnings retained. The targeted immediate-navigation/pause/back/reopen UI case logged one pass in **16.164 seconds**, but the overall command did not exit before its separate **300-second deadline** and was terminated. This is incomplete UI gate evidence, consistent with the independently observed shared XCTest runner completion/teardown blocker; no equivalent retry or full UI suite was run. Assigned simulators were shut down and exact owned process groups were confirmed absent. Three source reviewers found no material issues. The reviewed source is preserved in a local feature-branch commit with this UI-finalization limitation recorded. Push and draft PR publication remain held pending a completed applicable gate. Deployment awaits the user's explicit reply; no installation has occurred.+++## Meddy visual redesign — implementation and verification++Source: `design_handoff_meddy_redesign/README.md`, `Meddy Redesign.dc.html`, and its generated `support.js`. The HTML is reference material, not shipped app code. Reviewed all nine screen references in both 3a dark and 3b light: Today, medication library, routine library, medication detail, medication editor, dose sheet, timer, ordered session, and profiles. Rendered the actual reference pixels in six three-screen panels before implementation. Native SF Pro, navigation bars, TabView, form controls, sheets and swipe corrections remain. App icon stays unchanged. Asset colors convert the specified OKLCH purpose roles to sRGB, with light/dark variants and fallback for arbitrary user-entered purpose names.++The draft puts due medications into a hero with an atomic Take/Take both/Take all action, separates later/PRN/taken presentation, adds search and archive/share actions, uses purpose cards and progress rings for routines, and opens profile selection from Today’s avatar. Editors retain draft and validation behavior while changing schedule selection to wrapping chips. Unknown and fractional recorded quantities remain supported; no medicine-specific quantity or strength conversion is inferred. Purpose already exists on medications, treatments and routines, so no schema migration is needed.++Behavior deliberately retained from the approved care design: captured profile/lifecycle ownership; logical days beginning at 02:00; frozen routine plans and canonical event correction; Undo tombstones; explicit skip confirmation and unresolved-log review; explicit continuation between timer rounds; background deadline/haptic behavior and device handoff. The prototype’s automatic next round and reset-style routine Undo would change those behaviors and are not introduced by this visual work. The existing timer service has no skip-round operation, so this draft does not invent a completion or expose a nonfunctional Skip control. Routine library cards open the canonical execution view instead of recording a step from a second execution surface. Full independent scheduled occurrence selection remains in routine detail. Dose status remains “Fits your entered limits,” rather than a medical-safety claim. Saved non-24-hour caps retain their actual configured window. Sync status is shown in Profiles and on Today only when attention is needed.++Coverage of screens without mocks: shared grouped surfaces and colors apply to treatment/routine editors, profile management, photo/follow-up/limits fields and appointment sharing. Routine and treatment detail lead with a purpose card, preserve history and independent session controls; canonical history and review remain available from execution screens. Empty medication/Today states use a single explanatory hero.++Photo restoration after owner feedback: comparison with `70f79a8` found that the redesign removed medication-row and detailed-dose recognition images, moved the detail image into Settings, and moved the editor's retained photo controls to the bottom. `recognitionPhotoData`, the photo service/importer and draft transaction were retained; no personal store was inspected. The correction reuses `MedicationPhotoView` for library/Today thumbnails, a prominent detail image, detailed logging and the ordered routine's all-steps list. Add/Replace/Remove are reachable near the editor's identity fields; detail opens that same editor through Add/Change recognition photo. Routine selection and the current-step image were already retained. There is no new photo storage, permission, export or Watch transport.++Source review through four perspectives found no photo/data/profile blocker; a narrow PRN-tile layout concern was addressed by placing the thumbnail above the name header. Due and attention cards retain combined VoiceOver status/dose/instruction labels, with photo presence added separately. Strict SwiftLint passes all 111 Swift files with zero violations, and whitespace validation passes. Focused verification at `cc8bed7` passes **nine photo domain tests and both dark/light photo UI scenarios**, command exit 0 (`focused-verification`, 219.498 seconds). They cover attached/absent visibility, same-name profile separation, Replace picker cancellation, Remove/Cancel, saved removal and preservation of another medication's photo. The nine existing photo domain assertions cover bounded import/metadata, replacement, rollback, relaunch and stale drafts. The first `cf40672` attempt passed the nine domain tests but failed both UI journeys on navigation assumptions; native accessibility evidence showed a profile-scoped tab rebuilding after the first tap, and a redundant Back after re-tapping Medications had already returned to the library. The correction waits for the actual library search field and retains every photo/profile assertion.++All **12 photo-bearing screenshots**, six in each appearance, were inspected against the original photo-free handoff panels: Today, PRN cards, library, detail, editor and dose logging. Images retain their aspect ratio, names/purpose labels remain readable, the PRN thumbnail does not crowd the name header, and detail/editor controls are prominent. The addition of recognition images and moving the editor section earlier are intentional owner-requested differences from the mockups; native colors/cards and recording controls remain. Publication verification passed **201 phone domain tests in 28 suites, 14 Watch tests in two suites, and all 16 native UI scenarios**. Phone/Watch domains ran at clean `3110683`; fresh full UI ran at clean `abf67e3`, command exit 0 (`ui-final-verification`, 855.894 seconds). App/shared/Watch source is byte-identical across these checkpoints; the only intervening change corrects a UI-test viewport assumption. Native summaries and inventories validate all 231 declarations with zero failures/skips. An earlier full attempt completed phone/Watch domains but failed the dosage helper’s upper-half requirement; the native frame showed the field visible and hittable near the form end after moving photo controls earlier. The interrupted attempt and lost transport status remain recorded as non-passing. The corrected helper retains navigation clearance, hittability and every saved-care assertion; its focused scenario also passed with exit 0. Strict lint and whitespace passed in the final UI command. Draft PR #3 is updated through the existing branch; no merge or phone installation is included. Assigned simulators are shut down and owned build groups drained; the heavy lane is released. Tracker intent stays local while Transit is paused.++Verification on the isolated feature branch from `70f79a8`: strict SwiftLint and whitespace checks pass; phone domain tests pass **191 tests in 27 suites**; the Watch simulator gate passes **14 tests in two suites**; the final full phone UI gate passes **all 13 tests with exit 0** (`final-full-ui-32`, 626.191 seconds). Its native result inventory exactly matches all 13 declared UI scenarios. Both focused appearances also passed independently, and the final full gate retains **18 native reference screenshots**, nine in each appearance. Batch tests verify persisted Undo tombstones through a fresh context, profile separation, quantity snapshots and rollback. Largest-text timer, profile add/rename/switch/relaunch, whole independent-session execution, waking-time persistence, photo cancellation, dose limits and follow-up/Undo flows are covered.++Phone domain results validate unchanged domain/service source from the completed redesign draft; Watch ran on checkpoint `815a869`, and final full UI ran on `cf21e68`. Later checkpoint changes are phone accessibility identifiers, UI tests and verification documentation; no shared/domain/model source changed between these gates. Final documentation reconciliation does not change tested production source. Four source-review perspectives and final scoped reviews are clean. No unresolved source findings remain.++Actual pixel comparison covered all 18 retained native captures against the six handoff panels. Colors, purpose roles, rounded cards and main hierarchy match the reference. Native navigation, floating tabs and sheets use system spacing. Editors deliberately retain all existing optional dose, requirements, notes and timing fields, making their forms longer than the mock. Dose recording retains custom/unknown quantities and actual-time controls without inferred medicine-strength conversion. Routine cards open canonical execution; timer continuation and saved-step audit remain explicit. Profiles show actual synthetic counts and truthful isolated-store status rather than invented sync freshness or new persisted avatar colors. Screenshot content uses six synthetic medications and two routines, so its counts and current due occurrences differ from the prototype.++Pixel review found footer actions partly covered by the floating tab bar. Today and both libraries now use the handoff’s 120-point bottom clearance; the final full-gate reference captures include that corrected source. Native screen content uses isolated synthetic fixtures. Original handoff files remain untracked and byte-for-byte unchanged in the original checkout and its worktree copy.++Earlier failed evidence is retained: the first full UI attempt executed all 13 tests with four failures and exceeded its 600-second result-collection deadline. Scoped fixes corrected virtualized/offscreen form assertions, dose-default keyboard scrolling, profile identifier/Me-selector collisions, the removed timer-completion heading and bounded directional editor scrolling. A later full attempt executed all 13 with one test-helper failure querying the routine library’s intentionally hidden navigation bar; its execution transport disconnected before the harness receipt finalized. Native failure output and confirmed absent owned processes are retained separately. The guarded timer scenario passed with exit 0, followed by the completed all-13 full gate. Failed/mixed runs are not used as passing gate evidence. Runtime-only diagnostic collection was disabled and the final gate used a detached bounded driver to preserve deadline enforcement and receipts across transport disconnects; repository tooling/settings are unchanged.++Non-failing SwiftUI background-publication warnings remain in simulator logs. Physical Watch delivery and live CloudKit acceptance retain their existing scope limits. No live data, signing/account/entitlement settings, physical Watch install, phone installation, merge, or production Transit tracking changes occurred. The simulator batch is drained and its heavy slot released.+++## Prescription details — completed local implementation (2026-10-08)++The owner approved the [prescription details plan](meddy-prescription-details-plan.md), confirming prescribed-at as date and prescribed-by as doctor/clinic text. Optional civil date, prescriber, supply-duration days and repeats left are stored on Medication, with a small revision token for stale Undo protection. Grouped iPhone editor/detail and profile-scoped consultation export use those entered values. Decrement stops at zero; Undo guards canonical owner, lifecycle and revision, including medication archive/reactivate. Unchanged draft fields preserve newer values and conflicts are visible. This adds no dose, scheduling, stock/refill or treatment-course inference and no new entity, relationship or entitlement.++Simulator compilation, **26 focused domain tests across four suites** (nine prescription cases), and **two affected UI cases with command exit 0** pass. Coverage includes optional/clear/zero and invalid values, date validation, untouched/conflicting drafts, failed transactions/retry, repeated/stale actions, medication/profile archive fencing, historical synthetic-store upgrade/reopen, selected-profile escaped export, prescription editor/decrement/Undo/profile switching and existing name-only/Before sleeping/Taken/Undo. Final native summaries have zero failures or skips. Strict lint passes 110 files with zero violations; whitespace passes.++Domain checkpoint: `1b59fee`; final UI checkpoint: `6f4fba4`, differing only in a UI test locator. Later documentation does not change tested production source. Scoped local review found missing medication archive/reactivate revision invalidation; the narrow fix and dedicated regression pass. Earlier UI failures involved virtualized controls, keyboard collection/focus/field positioning and native menu-label hit testing. Explicit form targeting and bounded positioning/visible coordinate targeting corrected the tests without removing their saved-value assertions. Failed receipts remain preserved separately.++The fixture predates profile/wake additions; exact installed-store and live CloudKit acceptance are not claimed. Existing simulator publication/accessibility and baseline photo actor-isolation warnings remain. No unrelated full UI run, Watch runtime test, live data operation, phone install, signing/account change, publication or Transit write occurred. Build groups are drained; heavy lane released. These statements describe the focused-verification checkpoint; the subsequent phone installation and current publication approval are recorded in the prescription plan. Pending ticket intent remains local until Transit cleanup.
diff --git a/docs/meddy-prescription-details-plan.md b/docs/meddy-prescription-details-plan.mdnew file mode 100644index 0000000..4523e81--- /dev/null+++ b/docs/meddy-prescription-details-plan.md@@ -0,0 +1,80 @@+# Meddy prescription details — approved plan and implementation record++Status: approved for implementation, 2026-10-08. The owner confirmed “prescribed at” means date, and prescribed by covers doctor/clinic. No Transit ticket has been created. Implementation and local verification are complete; subsequent phone installation and publication approvals are recorded below.++## Proposed behaviour++Each medication can hold its current prescription details. The fields are optional, work for Me and dependants, and apply equally to scheduled, as-needed and routine-managed medication. Existing medication creation stays name-only.++| Requested field | Proposed meaning and input |+| --- | --- |+| Prescribed at | **Prescription date**, displayed as **Prescribed on**. A date without a time or location; optional, explicitly added or cleared. |+| Prescribed by | Free text for the prescriber, such as a name or practice. Blank means not recorded; no contact lookup or account integration. |+| Lasts for X days | **Supply lasts (days)**: a positive whole number entered by the user for how long one supplied quantity is intended to last. Optional; not a treatment-course length, computed remaining supply or countdown. |+| Repeats left | Remaining repeat dispensings after the current supply: an optional nonnegative whole number. Blank means unknown; **0** means none recorded as remaining. |++**Approved interpretation:** “prescribed at” is a date; doctor/clinic is entered under prescribed by. “Lasts for X days” uses the proposed supply-duration meaning.++Example using synthetic values: Prescribed on 8 October 2026; Prescribed by “Example practice”; Supply lasts 30 days; Repeats left 3. Tapping **−1 repeat** changes 3 to 2. It does not record taking medication, dispensing stock, a new prescription date or any actual care event.++These are user-entered facts. Supply duration does not change reminders, dose limits, routines or medication status. No refill scheduling, stock tracking, exhaustion alerts, inferred doses or medical advice are added. This first version stores the current details, with manual correction; it does not introduce a prescription-history ledger.++## iPhone presentation and correction++- Add a **Prescription** group to the redesigned Add/Edit medication form, after the recording defaults and before schedule controls. Use the existing grouped surfaces, native date control and number/text inputs. Do not prefill today, a duration or a repeat count merely by opening the editor. Each field can be cleared.+- Show recorded fields in a **Prescription** section on medication detail, between “How to take” and “Today”. Omit missing rows; omit an entirely empty section. Keep Today and medication library layouts unchanged.+- Show **−1 repeat** beside a known positive count, with accessibility label “Lower repeats left by one”. Disable it at zero and while its save is in progress; for an unknown count, offer editing rather than inventing a starting number. No confirmation sheet is needed for this reversible action.+- After a successful decrement, show the updated count and **Undo repeat change**, separate from “Undo Taken”. A second deliberate decrement lowers by one again; Undo applies only to the most recent successful decrement in that detail view. Undo lasts until leaving the view or a subsequent prescription change invalidates it. Edit always permits an explicit correction or clearing the count, including after relaunch.+- Failure leaves the persisted count unchanged, reports the existing save error and permits retry. Do not show a successful decrement or enable its Undo before persistence succeeds.++## Persistence and ownership++Extend the existing `Medication` model with four nullable fields: a validated Gregorian civil-date string (`YYYY-MM-DD`), prescriber text, supply duration in days and repeats left. A civil date prevents travel/time-zone changes from moving the displayed prescription date. Use localized display while keeping the stored date and exported ISO date stable. Trim text; reject malformed dates, fractional/negative counts, nonpositive duration and integer overflow. Do not impose an invented clinical maximum.++Add one nullable prescription-change UUID alongside those values. This small revision token distinguishes a later edit from the decrement being undone, even if the numeric count happens to match again. Existing rows start with all fields absent; their care/history/schedules remain intact. Use the current SwiftData private store and CloudKit container without new entities, relationships, team settings or entitlements. Additive compatibility must be demonstrated with an isolated old-schema disk fixture; no automatic live-store migration success is claimed by this plan.++Create a focused prescription draft/service rather than widening dose-recording actions:++- Capture medication UUID, owner and lifecycle when opening a draft or creating a quick action. Resolve the canonical medication and validate ownership/lifecycle using `ProfileAccess` before Save, decrement or Undo. Switching the visible profile cannot redirect an action. Reject an archived owner, stale lifecycle or ambiguous target; archived medications retain details but do not offer the quick action.+- Integrate changed prescription fields into the medication editor's existing single `EditorTransaction`, including other medication changes. Cancel changes nothing. Untouched prescription fields preserve newer saved values; a changed field conflicting with a newer value asks the user to reopen/reconcile rather than silently overwrite it.+- Decrement the validated current count by exactly one in one save, guarded against a stale revision and against zero/unknown values. Rotate the revision on a successful prescription mutation. Busy-state protection prevents one tap being submitted twice; repeated intentional taps remain available after each save.+- The transient Undo receipt captures target, owner/lifecycle, previous count and post-save revision. Restore that previous count only if the current revision still matches the decrement. Rotate the revision after Undo; never overwrite a later edit, clear, archive/restore or decrement. Repeated Undo is inert.++This uses the app's current synchronization model, not a cross-device refill ledger or server-atomic counter. Concurrent disconnected edits on separate phones are not promised to merge as two decrements. Watch payloads, notification actions, dose snapshots and frozen routine plans do not need these fields and stay unchanged. Prescription editing and quick decrement are iPhone features.++## Consultation export++Extend the existing profile-scoped Markdown consultation summary with labelled **Prescribed on**, **Prescribed by**, **Supply lasts (days)** and **Repeats left** rows. Include only recorded values, including an explicit zero repeat count. Export the civil date as ISO `YYYY-MM-DD`; reuse existing user-text escaping. Preserve profile filtering and the user's explicit system-share action. No automatic sending, prescription history, private notes or photo export is added.++## Implementation sequence after approval++1. Add nullable model fields, validation, draft preservation and the small revision-guarded decrement/Undo service.+2. Wire the grouped editor and medication-detail section/actions into the existing redesign; preserve its care flows and captured profile ownership.+3. Extend consultation export and update the existing design/implementation documentation to record the approved semantics.+4. Run focused synthetic tests and relevant simulator compilation/lint. Address failures before reporting completion. Publication and any later phone installation remain separately authorised actions; publication and phone installation were held at that planning checkpoint.++Focused acceptance covers optional/clear/zero values; date stability across time zones; invalid numeric/date input; name-only creation; unchanged and conflicting drafts; atomic save failure/retry from a fresh context; decrement 3→2, 1→0, zero/unknown rejection, successive taps and Undo; stale/repeated Undo and intervening edits; same-name medications in Me plus two dependants; profile switch and archive/lifecycle rejection; disk relaunch and old-schema upgrade preserving care/history; and export escaping, omissions, zero and owner isolation. One affected UI journey exercises editor Save/Cancel, decrement/Undo and profile separation in the redesigned form/detail. Reuse relevant profile/editor/export regressions; no unrelated full UI rerun is planned for the implementation loop. Required repository publication checks still apply if publication is later authorised.++## Repository basis at the planning checkpoint++Plan branch: `plan/meddy-prescription-details`, based on current local main `70f79a8`. UI integration is designed against inspected, installed redesign checkpoint `1201a8d`; that feature worktree is untouched. Reconcile the implementation branch with the redesign when implementation is authorised; do not copy or replace its production source as part of this plan.++Inspected: `Meddy/Meddy/Models/Models.swift` (`Medication`), `ContentView.swift` (`MedicationEditor`), `Features/MedicationDetailView.swift`, `Features/ConsultationMarkdown.swift`, `Features/MedicationScheduleFields.swift`, `Services/MedicationService.swift`, `EditorTransaction.swift`, `ProfileAccess.swift`, `App/AppEnvironment.swift`, and current design, preflight, implementation and dependant-profile documents. At the planning checkpoint none defined structured prescription fields. Recalled notes on captured action ownership, preserving untouched editor values and SwiftData rollback inform the transaction/Undo tests; any rollback workaround must be justified by reproduction, not installed broadly from a note alone.++This document retains the local pending-ticket intent until Transit cleanup completes. The planning phase made no source, installation, account or tracking changes.++## Completed local implementation and focused verification checkpoint++Implemented on `feature/meddy-prescription-details` from redesign `1201a8d`: five nullable medication attributes (four entered fields plus mutation revision), grouped iPhone editor/detail, profile-scoped export, and explicit decrement/Undo. Medication archive/reactivate rotates the revision; profile archive/restore uses the existing lifecycle fence. Both reject older repeat actions without changing recorded care.++Simulator compilation and **26 domain tests in four suites** pass, including **nine prescription tests** plus profile routing, editor transactions and Markdown export. The historical synthetic disk fixture upgrades with absent prescription values while retaining medication ID, photo/fixed-time bytes, deleted administration and frozen-definition bytes. Prescription details survive reopening. **Two affected UI cases pass with exit 0**: prescription date/provider/duration/repeats Save, decrement/Undo, zero floor, Cancel and dependant switching; and existing name-only creation/Before sleeping/Taken/Undo. Strict lint passes **110 Swift files**, zero violations; whitespace passes. Scoped local review found and fixed the medication archive/reactivate invalidation edge; no unresolved source finding remains.++Domain acceptance ran at `1b59fee`; final UI acceptance ran at `6f4fba4`. Between them only the older UI test's native menu-label locator changed; production source is identical. Final documentation does not alter tested production source. Receipts/native summaries and earlier failed attempts remain under workspace `meddy-prescription-verification/`. UI failures involved virtualized controls, keyboard focus/position and native read-only-label hit testing; the final two-case command completed successfully.++The fixture predates profile/wake fields: this establishes historical synthetic local-store upgrade, not an inspected personal-store or live CloudKit result. Existing simulator publication/accessibility and baseline photo actor-isolation warnings remain. No unrelated full UI gate or Watch runtime test was run. Owned build groups are drained; the heavy lane is released. No phone install, account/signing change, publication or Transit write occurred. Pending ticket intent remains local until Transit cleanup finishes.++## Subsequent installation and publication authorization++The owner subsequently requested phone installation. The Dark Side accepted an in-place version 1.0/build 7 update from clean source `27e03cf`, using the existing bundle/team/CloudKit container and a package without embedded Watch content. Post-install app listing and launch verification were blocked by CoreDevice connectivity error 4016; exact personal-store and live CloudKit acceptance remain unverified. No uninstall/reset, physical Watch install or personal-record inspection occurred.++The owner then approved pushing and creating the PR. The repository publication gates and pre-push review now apply. Review identified a redesign regression that had removed foreground medication snooze; the medication detail restores the existing reminder callback for active standalone scheduled medications with reminders enabled. It still defers notification delivery only and never records a dose. Transit intent remains local pending cleanup; publication authorization does not authorize merging or additional installation.
Phone and Watch domain gates passed at clean 3110683; the complete UI gate passed at clean abf67e3. Production/shared/Watch source is identical across these checkpoints. Later changes, if any, are documentation only. Native summaries and inventories back 201 phone domain, 14 Watch and 16 UI declarations. No coverage instrumentation was requested.
Phone accepted build 7 from 27e03cf. Post-install listing/launch checks were blocked by CoreDevice4016. The later snooze restoration has not been installed; this publication task does not perform another installation.
The original pre-push attempt completed phone/Watch domains, then UI exposed an upper-half viewport assumption after the photo editor moved earlier. Its terminal transport also disconnected, losing the overall status. The owned UI process was interrupted and drained; that attempt is not counted as passing. The corrected dosage scenario and a fresh complete 16-case UI command passed with exit 0, along with whitespace and strict lint.
Generated JPEGs in the isolated synthetic store verified photo visibility and draft removal; system picker cancellation was tested. No user library asset was selected, no personal store inspected, and no live CloudKit/photo hardware acceptance is claimed.