Branchwell

Docley / app / Apps / iOS / DocleyApp.swift

1import SwiftUI
2import StoreKit
3
4// Docley for iPhone and iPad. Search and doctor pages are native, built on the site's JSON API.
5// Signing in, rating, claiming and replying open the website in an in-app browser, so there is one
6// set of rules and one account system. Mac users use the website.
7
8@main
9struct DocleyApp: App {
10 var body: some Scene {
11 WindowGroup {
12 TabView {
13 NavigationStack { SearchView() }
14 .tabItem { Label("Search", systemImage: "magnifyingglass") }
15 NavigationStack { SettingsView() }
16 .tabItem { Label("Settings", systemImage: "gearshape") }
17 }
18 .tint(Theme.accent)
19 .preferredColorScheme(.dark)
20 .onAppear { RatingPrompt.countLaunch() }
21 }
22 }
23}
24
25enum Theme {
26 static let accent = Color(red: 0.96, green: 0.50, blue: 0.15) // #F58025
27 static let panel = Color(white: 0.07)
28}
29
30enum Site {
31 static let base = URL(string: "https://doctors.projectatom.ai")!
32 static func url(_ path: String) -> URL { URL(string: path, relativeTo: base)!.absoluteURL }
33}
34
35// MARK: - API
36
37struct DoctorSummary: Codable, Identifiable, Hashable {
38 let npi: String
39 let name: String
40 let credential: String?
41 let specialty: String?
42 let city: String?
43 let state: String?
44 var id: String { npi }
45 var title: String { credential.map { "\(name), \($0)" } ?? name }
46}
47
48struct PublicRecord: Codable, Identifiable, Hashable {
49 let id: String
50 let source: String
51 let kind: String
52 let case_status: String?
53 let action_date: String?
54 let summary: String
55 let url: String
56 let ended: String?
57 let reply: String?
58}
59
60struct Score: Codable, Hashable { let count: Int; let score: Double? }
61
62struct Comment: Codable, Identifiable, Hashable {
63 let id: String
64 let kind: String
65 let alias: String?
66 let comment: String
67 let updated: String?
68 let avg: Double
69 let reply: String?
70}
71
72struct Doctor: Codable, Hashable {
73 let npi: String
74 let name: String
75 let credential: String?
76 let specialty: String?
77 let address: String?
78 let city: String?
79 let state: String?
80 let zip: String?
81 let phone: String?
82 let records: [PublicRecord]
83 let scores: [String: Score]
84 let comments: [Comment]
85}
86
87struct SearchResponse: Codable { let page: Int; let more: Bool; let results: [DoctorSummary] }
88
89enum API {
90 static func search(q: String, state: String, page: Int) async throws -> SearchResponse {
91 var c = URLComponents(url: Site.url("/api/search"), resolvingAgainstBaseURL: false)!
92 c.queryItems = [.init(name: "q", value: q), .init(name: "state", value: state), .init(name: "page", value: String(page))]
93 let (data, _) = try await URLSession.shared.data(from: c.url!)
94 return try JSONDecoder().decode(SearchResponse.self, from: data)
95 }
96 static func doctor(_ npi: String) async throws -> Doctor {
97 let (data, _) = try await URLSession.shared.data(from: Site.url("/api/doctor/\(npi)"))
98 return try JSONDecoder().decode(Doctor.self, from: data)
99 }
100}
101
102// MARK: - Search
103
104struct SearchView: View {
105 @State private var query = ""
106 @State private var state = ""
107 @State private var results: [DoctorSummary] = []
108 @State private var page = 1
109 @State private var more = false
110 @State private var loading = false
111 @State private var error: String?
112
113 var body: some View {
114 List {
115 Section {
116 Picker("State", selection: $state) {
117 Text("All states").tag("")
118 ForEach(States.all, id: \.0) { Text($0.1).tag($0.0) }
119 }
120 .onChange(of: state) { Task { await run(reset: true) } }
121 }
122 if let error { Text(error).foregroundStyle(.secondary) }
123 ForEach(results) { d in
124 NavigationLink(value: d) {
125 VStack(alignment: .leading, spacing: 2) {
126 Text(d.title).font(.headline)
127 Text("\(d.specialty ?? "Physician") · \(d.city ?? ""), \(d.state ?? "")")
128 .font(.subheadline).foregroundStyle(.secondary)
129 }
130 .padding(.vertical, 2)
131 }
132 }
133 if more {
134 Button(loading ? "Loading…" : "Show more") { Task { await run(reset: false) } }.disabled(loading)
135 }
136 if results.isEmpty && error == nil && !loading {
137 Text("Search every licensed doctor in America by name, specialty or city.")
138 .foregroundStyle(.secondary)
139 }
140 }
141 .navigationTitle("Docley")
142 .navigationDestination(for: DoctorSummary.self) { DoctorView(npi: $0.npi, title: $0.title) }
143 .searchable(text: $query, prompt: "Name, specialty or city")
144 .onSubmit(of: .search) { Task { await run(reset: true) } }
145 }
146
147 func run(reset: Bool) async {
148 guard !query.isEmpty || !state.isEmpty else { results = []; more = false; return }
149 loading = true; defer { loading = false }
150 let next = reset ? 1 : page + 1
151 do {
152 let r = try await API.search(q: query, state: state, page: next)
153 results = reset ? r.results : results + r.results
154 page = next; more = r.more; error = r.results.isEmpty && reset ? "No doctors found. Try fewer words or another state." : nil
155 } catch {
156 self.error = "We couldn't reach Docley. Check your connection and try again."
157 }
158 }
159}
160
161// MARK: - Doctor
162
163struct DoctorView: View {
164 let npi: String
165 let title: String
166 @State private var doctor: Doctor?
167 @State private var web: URL?
168 @State private var failed = false
169
170 var body: some View {
171 List {
172 if let d = doctor {
173 Section {
174 VStack(alignment: .leading, spacing: 4) {
175 Text(title).font(.title2.bold())
176 Text("\(d.specialty ?? "Physician") · \(d.city ?? ""), \(d.state ?? "")").foregroundStyle(.secondary)
177 }
178 }
179 Section("Public record") {
180 if d.records.isEmpty {
181 Text("No federal exclusions found in the HHS Office of Inspector General list. State board and malpractice court records are being added state by state.")
182 .font(.subheadline).foregroundStyle(.secondary)
183 }
184 ForEach(d.records) { r in RecordRow(record: r) }
185 }
186 Section("Ratings") {
187 ScoreRow(label: "Patients", score: d.scores["patient"])
188 ScoreRow(label: "Colleagues", score: d.scores["colleague"])
189 Button { web = Site.url("/doctor/\(d.npi)/rate") } label: {
190 Text("Rate this doctor").frame(maxWidth: .infinity).fontWeight(.semibold)
191 }
192 .buttonStyle(.borderedProminent).buttonBorderShape(.capsule)
193 .listRowBackground(Color.clear)
194 }
195 if !d.comments.isEmpty {
196 Section("What people say") {
197 ForEach(d.comments) { c in
198 VStack(alignment: .leading, spacing: 6) {
199 Text("\(c.alias ?? "Verified person") · \(c.kind == "colleague" ? "Colleague" : "Patient") · \(String(format: "%.1f", c.avg)) of 5")
200 .font(.caption).foregroundStyle(.secondary)
201 Text(c.comment)
202 if let reply = c.reply {
203 Text("The doctor's reply: \(reply)").font(.subheadline)
204 .padding(.leading, 10).overlay(alignment: .leading) { Rectangle().fill(Theme.accent).frame(width: 2) }
205 }
206 }
207 }
208 }
209 }
210 Section("Practice") {
211 if let a = d.address { LabeledContent("Address", value: "\(a), \(d.city ?? ""), \(d.state ?? "") \(d.zip ?? "")") }
212 if let p = d.phone, let tel = URL(string: "tel:" + p.filter(\.isNumber)) { Link(p, destination: tel) }
213 LabeledContent("NPI", value: d.npi)
214 }
215 Section {
216 Button("Are you this doctor? Claim your page") { web = Site.url("/doctor/\(d.npi)/claim") }
217 Link("Open on the web", destination: Site.url("/doctor/\(d.npi)"))
218 }
219 } else if failed {
220 Text("We couldn't load this doctor. Pull to try again.").foregroundStyle(.secondary)
221 } else {
222 ProgressView().frame(maxWidth: .infinity)
223 }
224 }
225 .navigationTitle(doctor == nil ? "" : "Doctor")
226 .navigationBarTitleDisplayMode(.inline)
227 .task { await load() }
228 .refreshable { await load() }
229 .sheet(item: $web, onDismiss: { Task { await load() } }) { url in WebSheet(url: url) }
230 }
231
232 func load() async {
233 do { doctor = try await API.doctor(npi); failed = false } catch { failed = true }
234 }
235}
236
237struct RecordRow: View {
238 let record: PublicRecord
239 static let kinds = ["exclusion": "Federal exclusion", "license_action": "License action", "malpractice_case": "Malpractice case"]
240 static let statuses = ["filed": "Filed, not yet decided", "settled": "Settled", "dismissed": "Dismissed", "judgment_for_patient": "Judgment for the patient", "judgment_for_doctor": "Judgment for the doctor"]
241 var body: some View {
242 VStack(alignment: .leading, spacing: 6) {
243 Text([Self.kinds[record.kind] ?? record.kind, record.case_status.flatMap { Self.statuses[$0] }, record.action_date].compactMap { $0 }.joined(separator: " · "))
244 .font(.headline).foregroundStyle(Theme.accent)
245 Text(record.summary)
246 if let u = URL(string: record.url) { Link("Source: \(record.source)", destination: u).font(.subheadline) }
247 if let reply = record.reply { Text("The doctor's reply: \(reply)").font(.subheadline).foregroundStyle(.secondary) }
248 }
249 .padding(.vertical, 4)
250 }
251}
252
253struct ScoreRow: View {
254 let label: String
255 let score: Score?
256 var body: some View {
257 LabeledContent(label) {
258 if let s = score?.score { Text(String(format: "%.1f of 5 · %d ratings", s, score?.count ?? 0)).bold() }
259 else if let n = score?.count, n > 0 { Text("\(n) of 5 ratings needed") }
260 else { Text("No ratings yet") }
261 }
262 }
263}
264
265extension URL: @retroactive Identifiable { public var id: String { absoluteString } }
266
267// MARK: - Settings (house standard: rating row, free support, no tips, no nag screens)
268
269struct SettingsView: View {
270 @Environment(\.requestReview) private var requestReview
271 var body: some View {
272 Form {
273 Section {
274 Button("Rate Docley") { requestReview() }
275 Link("Send feedback", destination: URL(string: "https://projectatom.ai/apps?app=docley#feedback")!)
276 Link("Ask ATOM", destination: URL(string: "https://projectatom.ai")!)
277 ShareLink("Share Docley", item: Site.base)
278 } header: { Text("Support Docley") } footer: { Text("Docley is free for everyone. Support is free too.") }
279 Section("About") {
280 LabeledContent("Version", value: "\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "") (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? ""))")
281 Link("Rating rules", destination: Site.url("/rules"))
282 Link("Privacy", destination: URL(string: "https://projectatom.ai/privacy")!)
283 Link("Source code (public domain, Unlicense)", destination: URL(string: "https://github.com/projectatomai/docley")!)
284 }
285 Section {
286 Link(destination: URL(string: "https://projectatom.ai")!) {
287 Text("A Project ATOM project").font(.subheadline.weight(.semibold))
288 .padding(.horizontal, 18).padding(.vertical, 10)
289 .overlay(Capsule().stroke(Theme.accent))
290 }
291 .frame(maxWidth: .infinity)
292 }
293 .listRowBackground(Color.clear)
294 }
295 .navigationTitle("Settings")
296 }
297}
298
299/// The only automatic prompt: Apple's rating request, after a few launches.
300enum RatingPrompt {
301 static func countLaunch() {
302 let n = UserDefaults.standard.integer(forKey: "launches") + 1
303 UserDefaults.standard.set(n, forKey: "launches")
304 guard n == 5, let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
305 AppStore.requestReview(in: scene)
306 }
307}