diff --git a/OpenHealthSync/API/WorkoutAPIClient.swift b/OpenHealthSync/API/WorkoutAPIClient.swift index 1480460..177b971 100644 --- a/OpenHealthSync/API/WorkoutAPIClient.swift +++ b/OpenHealthSync/API/WorkoutAPIClient.swift @@ -467,6 +467,23 @@ actor WorkoutAPIClient { try await perform("PUT", "api/me/data-consent", body: Self.encoder.encode(payload)) } + // MARK: - Display Units + + /// The units stored on the athlete's account, or nil when nobody has + /// chosen yet. The dashboard and the coach read the same value. + /// + /// Throws on a server that predates the endpoint (its catch-all answers + /// the GET with the dashboard's HTML, which doesn't decode); callers treat + /// that as "keep the local choice". + func fetchUnits() async throws -> DisplayUnits? { + let (data, _) = try await perform("GET", "api/me/units") + return try Self.decoder.decode(UnitsPayload.self, from: data).units.flatMap(DisplayUnits.init(rawValue:)) + } + + func sendUnits(_ units: DisplayUnits) async throws { + try await perform("PUT", "api/me/units", body: Self.encoder.encode(UnitsPayload(units: units.rawValue))) + } + // MARK: - Health Metrics func sendHealthMetrics(_ payload: HealthMetricsBulkPayload) async throws { diff --git a/OpenHealthSync/App/OpenHealthSyncApp.swift b/OpenHealthSync/App/OpenHealthSyncApp.swift index 8be11db..44f3286 100644 --- a/OpenHealthSync/App/OpenHealthSyncApp.swift +++ b/OpenHealthSync/App/OpenHealthSyncApp.swift @@ -28,6 +28,9 @@ struct LoopbackApp: App { private var domains: DataDomains { DataDomains(rawValue: domainsRaw).union(.required) } + /// Empty until the athlete picks or the account's choice is adopted. + @AppStorage(DisplayUnits.storageKey) private var unitsRaw: String = "" + @Environment(\.scenePhase) private var scenePhase private let apiClient: WorkoutAPIClient @@ -129,6 +132,8 @@ struct LoopbackApp: App { // permission prompts never fire on the way to the login screen. guard session.isAuthenticated else { return } + await UnitsSync.reconcile(with: apiClient) + await scheduleManager.requestAuthorization() await scheduleManager.loadScheduledWorkouts() await scheduleManager.autoSync() @@ -146,6 +151,10 @@ struct LoopbackApp: App { } .onChange(of: scenePhase) { _, phase in if phase == .active { + Task { + guard session.isAuthenticated else { return } + await UnitsSync.reconcile(with: apiClient) + } Task { await scheduleManager.loadScheduledWorkouts() await scheduleManager.autoSync() @@ -168,6 +177,13 @@ struct LoopbackApp: App { .onChange(of: domainsRaw) { _, _ in Task { await startHealthPipeline() } } + // Units changed, in Settings or by adopting the account's choice. + // The second case sends the server its own value back, which it + // ignores; telling the two apart isn't worth the state. + .onChange(of: unitsRaw) { _, raw in + guard session.isAuthenticated, let units = DisplayUnits(rawValue: raw) else { return } + Task { await UnitsSync.push(units, with: apiClient) } + } } } diff --git a/OpenHealthSync/Models/DisplayUnits.swift b/OpenHealthSync/Models/DisplayUnits.swift index 42fc3cc..54e669d 100644 --- a/OpenHealthSync/Models/DisplayUnits.swift +++ b/OpenHealthSync/Models/DisplayUnits.swift @@ -4,11 +4,13 @@ // // Display-unit preference (metric / imperial). Display only: HealthKit, the // API and everything stored stay metric, and nothing is converted on the -// wire. Mirrors the dashboard's `format.ts`, but the choice is local to this -// device — the server doesn't store one. +// wire. Mirrors the dashboard's `format.ts`. The choice belongs to the +// account (`/api/me/units`, see `UnitsSync`), so the dashboard and the coach +// follow it too; `@AppStorage` holds this device's copy. // import Foundation +import os enum DisplayUnits: String, CaseIterable, Identifiable, Sendable { case metric @@ -131,3 +133,51 @@ enum DisplayUnits: String, CaseIterable, Identifiable, Sendable { return "\(number(min(lower, upper))) – \(number(max(lower, upper))) \(speedUnit)" } } + +/// Body of `GET` and `PUT /api/me/units`. `units` is null on the server until +/// someone chooses; an unknown string from a newer server reads as unset. +nonisolated struct UnitsPayload: Codable, Sendable { + let units: String? +} + +/// Keeps this device's units in step with the account's. +/// +/// The server wins once it holds a choice, so a change made in the dashboard +/// or on another phone arrives here on the next launch or foreground. Until +/// then this device offers its own, with one exception: a metric *default* +/// is never offered. The server already reads "unset" as metric, so sending +/// it would add nothing, and it would overwrite a miles choice still waiting +/// in the athlete's browser from before the preference moved server-side. +/// +/// Every failure is silent. A server that predates the endpoint, or no +/// network, leaves the local choice exactly as it was. +enum UnitsSync { + /// Whether the athlete has picked, as opposed to following the device. + private static var localChoice: DisplayUnits? { + UserDefaults.standard.string(forKey: DisplayUnits.storageKey).flatMap(DisplayUnits.init(rawValue:)) + } + + /// Launch and foreground: adopt the account's choice, or offer ours. + static func reconcile(with client: WorkoutAPIClient) async { + do { + if let remote = try await client.fetchUnits() { + if remote != localChoice { + UserDefaults.standard.set(remote.rawValue, forKey: DisplayUnits.storageKey) + } + } else if let offer = localChoice ?? (DisplayUnits.deviceDefault == .imperial ? .imperial : nil) { + try await client.sendUnits(offer) + } + } catch { + AppLog.sync.info("Units sync skipped: \(String(describing: error), privacy: .public)") + } + } + + /// The athlete changed the picker in Settings. + static func push(_ units: DisplayUnits, with client: WorkoutAPIClient) async { + do { + try await client.sendUnits(units) + } catch { + AppLog.sync.info("Units push failed: \(String(describing: error), privacy: .public)") + } + } +} diff --git a/OpenHealthSync/Views/Settings/TrainingSettingsView.swift b/OpenHealthSync/Views/Settings/TrainingSettingsView.swift index f394f41..cafbfd3 100644 --- a/OpenHealthSync/Views/Settings/TrainingSettingsView.swift +++ b/OpenHealthSync/Views/Settings/TrainingSettingsView.swift @@ -43,7 +43,7 @@ struct TrainingSettingsView: View { } header: { Text("Units") } footer: { - Text("Changes how distances and paces are shown in the app. Workouts on your watch and data on your server are unaffected.") + Text("How distances and paces are shown here and on your dashboard, and the units your coach uses. Workouts on your watch and data on your server are unaffected.") } } .listRowBackground(LB.surface)