Jobley / app / Sources / JobleyUI / Models.swift
| 1 | import SwiftUI |
| 2 | import JobleyKit |
| 3 | |
| 4 | /// The public board: search, filters and "load more", exactly as jobley.ai/jobs/ shows it. |
| 5 | @MainActor |
| 6 | public final class BoardModel: ObservableObject { |
| 7 | @Published public var query = "" |
| 8 | @Published public var workplace = "" |
| 9 | @Published public var type = "" |
| 10 | @Published public var category = "" |
| 11 | @Published public private(set) var jobs: [Job] = [] |
| 12 | @Published public private(set) var nextCursor: String? |
| 13 | @Published public private(set) var loading = false |
| 14 | @Published public private(set) var error: String? |
| 15 | @Published public private(set) var labels = Labels() |
| 16 | |
| 17 | public private(set) var api: APIClient |
| 18 | |
| 19 | public init(api: APIClient) { self.api = api } |
| 20 | |
| 21 | public var hasFilters: Bool { !query.isEmpty || !workplace.isEmpty || !type.isEmpty || !category.isEmpty } |
| 22 | |
| 23 | public func loadMeta() async { |
| 24 | if let meta = try? await api.meta() { labels = Labels(meta) } |
| 25 | } |
| 26 | |
| 27 | public func reload() async { |
| 28 | loading = true; error = nil |
| 29 | defer { loading = false } |
| 30 | do { |
| 31 | let page = try await api.jobs(query: query, workplace: workplace, type: type, category: category) |
| 32 | jobs = page.jobs; nextCursor = page.nextCursor |
| 33 | } catch { |
| 34 | self.error = error.localizedDescription |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | public func loadMore() async { |
| 39 | guard let cursor = nextCursor, !loading else { return } |
| 40 | loading = true |
| 41 | defer { loading = false } |
| 42 | do { |
| 43 | let page = try await api.jobs(query: query, workplace: workplace, type: type, category: category, cursor: cursor) |
| 44 | jobs += page.jobs; nextCursor = page.nextCursor |
| 45 | } catch { |
| 46 | self.error = error.localizedDescription |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | public func clearFilters() { query = ""; workplace = ""; type = ""; category = "" } |
| 51 | } |
| 52 | |
| 53 | /// Jobs saved on this device (iPhone). Kept as the job itself so the list works offline. |
| 54 | @MainActor |
| 55 | public final class SavedJobs: ObservableObject { |
| 56 | static let key = "jobley.savedJobs" |
| 57 | @Published public private(set) var jobs: [Job] |
| 58 | let defaults: UserDefaults |
| 59 | |
| 60 | public init(defaults: UserDefaults = .standard) { |
| 61 | self.defaults = defaults |
| 62 | jobs = (defaults.data(forKey: Self.key)).flatMap { try? JSONDecoder().decode([Job].self, from: $0) } ?? [] |
| 63 | } |
| 64 | |
| 65 | public func contains(_ job: Job) -> Bool { jobs.contains { $0.id == job.id } } |
| 66 | |
| 67 | public func toggle(_ job: Job) { |
| 68 | if contains(job) { jobs.removeAll { $0.id == job.id } } |
| 69 | else { jobs.insert(job, at: 0) } |
| 70 | defaults.set(try? JSONEncoder().encode(jobs), forKey: Self.key) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// The review queue and everything a curator or moderator does, for both apps. |
| 75 | /// People decide here. Lists are oldest first and are never sorted by anything but time. |
| 76 | @MainActor |
| 77 | public final class CuratorModel: ObservableObject { |
| 78 | public enum Queue: String, CaseIterable, Identifiable, Sendable { |
| 79 | case pending, approved, published, rejected, unpublished |
| 80 | public var id: Self { self } |
| 81 | public var title: String { |
| 82 | switch self { |
| 83 | case .pending: "Review queue" |
| 84 | case .approved: "Approved" |
| 85 | case .published: "Published" |
| 86 | case .rejected: "Sent back" |
| 87 | case .unpublished: "Unpublished" |
| 88 | } |
| 89 | } |
| 90 | public var systemImage: String { |
| 91 | switch self { |
| 92 | case .pending: "tray.full" |
| 93 | case .approved: "checkmark.circle" |
| 94 | case .published: "megaphone" |
| 95 | case .rejected: "arrow.uturn.backward.circle" |
| 96 | case .unpublished: "eye.slash" |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | @Published public private(set) var me: Me? |
| 102 | @Published public private(set) var stats: Stats? |
| 103 | @Published public private(set) var lists: [Queue: [Job]] = [:] |
| 104 | @Published public private(set) var item: JobReviewItem? |
| 105 | @Published public var error: String? |
| 106 | @Published public private(set) var busy = false |
| 107 | @Published public private(set) var signingIn = false |
| 108 | /// The signed-in person's passkeys (Settings shows them; a second one is the way to recover). |
| 109 | @Published public private(set) var passkeys: [Passkey] = [] |
| 110 | |
| 111 | public private(set) var api: APIClient |
| 112 | let saveToken: (String?) throws -> Void |
| 113 | private let authorizer = PasskeyAuthorizer() |
| 114 | |
| 115 | public init(api: APIClient, saveToken: @escaping (String?) throws -> Void = { token in |
| 116 | if let token { try TokenStore.save(token) } else { TokenStore.remove() } |
| 117 | }) { |
| 118 | self.api = api |
| 119 | self.saveToken = saveToken |
| 120 | } |
| 121 | |
| 122 | public var isSignedIn: Bool { me != nil } |
| 123 | public var canSeeCandidates: Bool { me?.isCurator == true || me?.canSeeCandidates == true } |
| 124 | public func jobs(_ queue: Queue) -> [Job] { lists[queue] ?? [] } |
| 125 | |
| 126 | /// Checks the saved sign-in. Called at launch. |
| 127 | public func start() async { |
| 128 | guard api.hasToken else { return } |
| 129 | do { me = try await api.me(); await refreshAll() } |
| 130 | catch let error as APIError where error.code == "unauthorized" { |
| 131 | try? saveToken(nil); api = api.withToken(nil); me = nil |
| 132 | self.error = "You've been signed out. Sign in with your passkey." |
| 133 | } |
| 134 | catch { self.error = error.localizedDescription } |
| 135 | } |
| 136 | |
| 137 | /// Signs in with a passkey the person already has. |
| 138 | @discardableResult |
| 139 | public func signInWithPasskey() async -> Bool { |
| 140 | await passkeyStep { |
| 141 | let challenge = try await self.api.passkeySignInOptions() |
| 142 | let assertion = try await self.authorizer.signIn(challenge) |
| 143 | return try await self.api.signIn(challengeID: challenge.challengeID, assertion: assertion) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | /// Adds a first passkey with a one-time setup link (from the curator, or the setup endpoint), |
| 148 | /// then signs in with it. |
| 149 | @discardableResult |
| 150 | public func addFirstPasskey(setupLink: String) async -> Bool { |
| 151 | guard let code = PasskeyResponse.setupCode(from: setupLink) else { error = PasskeyError.badLink.localizedDescription; return false } |
| 152 | return await passkeyStep { |
| 153 | let challenge = try await self.api.passkeyOptions(setupCode: code) |
| 154 | let registration = try await self.authorizer.register(challenge) |
| 155 | return try await self.api.addPasskey(challengeID: challenge.challengeID, registration: registration, name: PasskeyAuthorizer.deviceName) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /// Adds another passkey while signed in. A second passkey is how a person recovers. |
| 160 | public func addAnotherPasskey() async { |
| 161 | signingIn = true |
| 162 | defer { signingIn = false } |
| 163 | do { |
| 164 | let challenge = try await api.anotherPasskeyOptions() |
| 165 | let registration = try await authorizer.register(challenge) |
| 166 | try await api.addAnotherPasskey(challengeID: challenge.challengeID, registration: registration, name: PasskeyAuthorizer.deviceName) |
| 167 | error = nil |
| 168 | await loadPasskeys() |
| 169 | } catch PasskeyError.cancelled { |
| 170 | } catch { report(error) } |
| 171 | } |
| 172 | |
| 173 | public func loadPasskeys() async { |
| 174 | do { passkeys = try await api.passkeys() } catch { report(error) } |
| 175 | } |
| 176 | |
| 177 | /// The server keeps the last passkey; Settings only offers Remove when there are two or more. |
| 178 | public func removePasskey(_ passkey: Passkey) async { |
| 179 | do { try await api.removePasskey(passkey.id); await loadPasskeys() } catch { report(error) } |
| 180 | } |
| 181 | |
| 182 | public func signOut() { |
| 183 | let ending = api |
| 184 | Task { try? await ending.signOut() } |
| 185 | try? saveToken(nil) |
| 186 | api = api.withToken(nil); me = nil; stats = nil; lists = [:]; item = nil; passkeys = [] |
| 187 | } |
| 188 | |
| 189 | private func passkeyStep(_ work: @escaping () async throws -> PasskeySession) async -> Bool { |
| 190 | signingIn = true |
| 191 | defer { signingIn = false } |
| 192 | do { |
| 193 | let session = try await work() |
| 194 | let signedIn = api.withToken(session.token) |
| 195 | let who = try await signedIn.me() |
| 196 | try saveToken(session.token) |
| 197 | api = signedIn; me = who; error = nil |
| 198 | await refreshAll() |
| 199 | await loadPasskeys() |
| 200 | return true |
| 201 | } catch PasskeyError.cancelled { |
| 202 | return false |
| 203 | } catch { |
| 204 | report(error) |
| 205 | return false |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | public func refreshAll() async { |
| 210 | await refreshStats() |
| 211 | for queue in Queue.allCases { await load(queue) } |
| 212 | } |
| 213 | |
| 214 | public func refreshStats() async { |
| 215 | do { stats = try await api.stats() } catch { report(error) } |
| 216 | } |
| 217 | |
| 218 | public func load(_ queue: Queue) async { |
| 219 | do { lists[queue] = try await api.adminJobs(status: queue.rawValue) } catch { report(error) } |
| 220 | } |
| 221 | |
| 222 | public func open(_ id: String?) async { |
| 223 | guard let id else { item = nil; return } |
| 224 | if item?.job.id != id { item = nil } |
| 225 | do { item = try await api.reviewItem(id) } catch { report(error) } |
| 226 | } |
| 227 | |
| 228 | // MARK: Decisions (people only) |
| 229 | |
| 230 | /// The normal one-step Publish: approve and publish. |
| 231 | public func publishNow(_ job: Job) async -> Bool { |
| 232 | await decide(job) { try await self.api.approve(job: job.id, publish: true) } |
| 233 | } |
| 234 | public func approveOnly(_ job: Job) async -> Bool { |
| 235 | await decide(job) { try await self.api.approve(job: job.id, publish: false) } |
| 236 | } |
| 237 | public func publish(_ job: Job) async -> Bool { |
| 238 | await decide(job) { try await self.api.publish(job: job.id) } |
| 239 | } |
| 240 | public func sendBack(_ job: Job, reason: String) async -> Bool { |
| 241 | await decide(job) { try await self.api.reject(job: job.id, reason: reason) } |
| 242 | } |
| 243 | public func unpublish(_ job: Job, reason: String) async -> Bool { |
| 244 | await decide(job) { try await self.api.unpublish(job: job.id, reason: reason) } |
| 245 | } |
| 246 | |
| 247 | public func save(_ job: Job, edit: JobEdit) async -> Bool { |
| 248 | let changes = edit.changes(from: job) |
| 249 | guard !changes.isEmpty else { return true } |
| 250 | return await decide(job) { try await self.api.edit(job: job.id, changes: changes) } |
| 251 | } |
| 252 | |
| 253 | public func addNote(_ job: Job, note: String) async -> Bool { |
| 254 | let text = note.trimmingCharacters(in: .whitespacesAndNewlines) |
| 255 | guard !text.isEmpty else { return false } |
| 256 | busy = true |
| 257 | defer { busy = false } |
| 258 | do { |
| 259 | try await api.addNote(job: job.id, note: text) |
| 260 | await open(job.id) |
| 261 | return true |
| 262 | } catch { report(error); return false } |
| 263 | } |
| 264 | |
| 265 | private func decide(_ job: Job, _ work: @escaping () async throws -> Job) async -> Bool { |
| 266 | busy = true |
| 267 | defer { busy = false } |
| 268 | do { |
| 269 | _ = try await work() |
| 270 | await refreshAll() |
| 271 | await open(job.id) |
| 272 | return true |
| 273 | } catch { report(error); return false } |
| 274 | } |
| 275 | |
| 276 | func report(_ error: Error) { |
| 277 | self.error = error.localizedDescription |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | /// Candidates and introductions (the curator, or moderators the curator switched on). |
| 282 | @MainActor |
| 283 | public final class CandidatesModel: ObservableObject { |
| 284 | public enum Scope: Hashable, Sendable { case everyone, anyJob, job(String) } |
| 285 | |
| 286 | @Published public var scope: Scope = .everyone |
| 287 | @Published public var status = "" |
| 288 | @Published public private(set) var candidates: [Candidate] = [] |
| 289 | @Published public private(set) var detail: CandidateDetail? |
| 290 | @Published public var error: String? |
| 291 | |
| 292 | let api: () -> APIClient |
| 293 | public init(api: @escaping () -> APIClient) { self.api = api } |
| 294 | |
| 295 | public func reload() async { |
| 296 | let jobID: String? = switch scope { case .everyone: nil; case .anyJob: "none"; case .job(let id): id } |
| 297 | do { candidates = try await api().candidates(jobID: jobID, status: status.isEmpty ? nil : status) } |
| 298 | catch { self.error = error.localizedDescription } |
| 299 | } |
| 300 | |
| 301 | public func open(_ id: String?) async { |
| 302 | guard let id else { detail = nil; return } |
| 303 | do { detail = try await api().candidate(id) } catch { self.error = error.localizedDescription } |
| 304 | } |
| 305 | |
| 306 | public func setStatus(_ candidate: Candidate, _ status: String) async { |
| 307 | do { _ = try await api().setStatus(candidate: candidate.id, status: status); await reload(); await open(candidate.id) } |
| 308 | catch { self.error = error.localizedDescription } |
| 309 | } |
| 310 | |
| 311 | /// Records an introduction a person made (the email itself goes from their own mail app). |
| 312 | public func introduce(_ candidate: Candidate, jobID: String, note: String) async -> Bool { |
| 313 | do { |
| 314 | _ = try await api().introduce(candidate: candidate.id, jobID: jobID, note: note) |
| 315 | await reload(); await open(candidate.id) |
| 316 | return true |
| 317 | } catch { self.error = error.localizedDescription; return false } |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | /// Moderator applications and moderators (curator only). |
| 322 | @MainActor |
| 323 | public final class ModeratorsModel: ObservableObject { |
| 324 | @Published public private(set) var applications: [ModeratorApplication] = [] |
| 325 | @Published public private(set) var moderators: [Moderator] = [] |
| 326 | /// Shown once, right after approving (or making a new link), with a Copy button. |
| 327 | @Published public var newSetupLink: ModeratorSetupLink? |
| 328 | @Published public var error: String? |
| 329 | |
| 330 | let api: () -> APIClient |
| 331 | public init(api: @escaping () -> APIClient) { self.api = api } |
| 332 | |
| 333 | public func reload() async { |
| 334 | do { |
| 335 | applications = try await api().moderatorApplications() |
| 336 | moderators = try await api().moderators() |
| 337 | } catch { self.error = error.localizedDescription } |
| 338 | } |
| 339 | |
| 340 | public func approve(_ application: ModeratorApplication, canSeeCandidates: Bool) async { |
| 341 | do { |
| 342 | let made = try await api().approve(application: application.id, canSeeCandidates: canSeeCandidates) |
| 343 | newSetupLink = ModeratorSetupLink(id: made.moderator.id, name: made.moderator.name, link: made.setup) |
| 344 | await reload() |
| 345 | } catch { self.error = error.localizedDescription } |
| 346 | } |
| 347 | |
| 348 | /// A new one-time setup link, for a moderator adding their first passkey or one who lost theirs. |
| 349 | public func makeSetupLink(_ moderator: Moderator) async { |
| 350 | do { newSetupLink = ModeratorSetupLink(id: moderator.id, name: moderator.name, link: try await api().setupLink(moderator: moderator.id)) } |
| 351 | catch { self.error = error.localizedDescription } |
| 352 | } |
| 353 | |
| 354 | public func decline(_ application: ModeratorApplication) async { |
| 355 | do { try await api().decline(application: application.id); await reload() } catch { self.error = error.localizedDescription } |
| 356 | } |
| 357 | |
| 358 | public func setAccess(_ moderator: Moderator, _ value: Bool) async { |
| 359 | do { try await api().setAccess(moderator: moderator.id, canSeeCandidates: value); await reload() } |
| 360 | catch { self.error = error.localizedDescription } |
| 361 | } |
| 362 | |
| 363 | public func revoke(_ moderator: Moderator) async { |
| 364 | do { try await api().revoke(moderator: moderator.id); await reload() } catch { self.error = error.localizedDescription } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /// A moderator's one-time passkey setup link, shown once to the curator to hand on. |
| 369 | public struct ModeratorSetupLink: Identifiable, Sendable { |
| 370 | public var id: String |
| 371 | public var name: String |
| 372 | public var link: SetupLink |
| 373 | } |