import Foundation /// Which app is calling. The API records it in the audit log, and refuses people-only actions /// (approve, reject, publish, unpublish, anything about candidates) from `mcp`. public enum ClientKind: String, Sendable { case mac, iphone, mcp } /// Every error the API sends: `{ok:false, error, message, fields?, status?}`. public struct APIError: Error, LocalizedError, Equatable, Sendable { public var code: String public var message: String public var fields: [String: String] public var status: String? public var httpStatus: Int public init(code: String, message: String, fields: [String: String] = [:], status: String? = nil, httpStatus: Int = 0) { self.code = code; self.message = message; self.fields = fields; self.status = status; self.httpStatus = httpStatus } public var errorDescription: String? { if fields.isEmpty { return message } return message + " " + fields.sorted { $0.key < $1.key }.map(\.value).joined(separator: " ") } public static let signedOut = APIError(code: "unauthorized", message: "Sign in with your passkey in Settings first.", httpStatus: 401) } /// A job post from the "Post a job" form (`POST /api/jobs`). public struct JobDraft: Equatable, Sendable { public var title = "", company = "", companyURL = "", location = "" public var workplace = "", employmentType = "", category = "" public var payMin = "", payMax = "", payPeriod = "hour", payCurrency = "USD" public var description = "", applyURL = "", contactName = "", contactEmail = "" public init() {} func body(turnstileToken: String?) -> [String: Any] { var body: [String: Any] = [ "title": title, "company": company, "location": location, "workplace": workplace, "employment_type": employmentType, "category": category, "pay_period": payPeriod, "pay_currency": payCurrency.uppercased(), "description": description, "contact_name": contactName, "contact_email": contactEmail, "pay_min": Int(payMin.filter(\.isNumber)) ?? payMin, "pay_max": Int(payMax.filter(\.isNumber)) ?? payMax ] if !companyURL.isEmpty { body["company_url"] = companyURL } if !applyURL.isEmpty { body["apply_url"] = applyURL } if let turnstileToken { body["turnstile_token"] = turnstileToken } return body } } /// "Put me forward" (`POST /api/candidates`), for one job or for a kind of job. public struct CandidateDraft: Equatable, Sendable { public var jobID: String? public var name = "", email = "", headline = "", location = "", lookingFor = "", about = "" public var links = "", resumeURL = "" public var consent = false public init(jobID: String? = nil) { self.jobID = jobID } func body(turnstileToken: String?) -> [String: Any] { var body: [String: Any] = ["name": name, "email": email, "headline": headline, "consent": consent] if let jobID { body["job_id"] = jobID } if !location.isEmpty { body["location"] = location } if !lookingFor.isEmpty { body["looking_for"] = lookingFor } if !about.isEmpty { body["about"] = about } if !resumeURL.isEmpty { body["resume_url"] = resumeURL } let list = links.split(whereSeparator: { $0.isNewline || $0 == " " || $0 == "," }).map(String.init).filter { !$0.isEmpty } if !list.isEmpty { body["links"] = list } if let turnstileToken { body["turnstile_token"] = turnstileToken } return body } } /// The fields an edit may change (`PATCH /api/admin/jobs/:id`). Contact and status never change here. public struct JobEdit: Equatable, Sendable { public var title: String, company: String, companyURL: String, location: String public var workplace: String, employmentType: String, category: String public var payMin: Int, payMax: Int, payPeriod: String, payCurrency: String public var description: String, applyURL: String public init(_ job: Job) { title = job.title; company = job.company; companyURL = job.companyURL ?? ""; location = job.location workplace = job.workplace; employmentType = job.employmentType; category = job.category payMin = job.pay.min; payMax = job.pay.max; payPeriod = job.pay.period; payCurrency = job.pay.currency description = job.description; applyURL = job.applyURL ?? "" } /// Only the fields that differ from the job, so the audit log shows what really changed. public func changes(from job: Job) -> [String: Any] { let before = JobEdit(job) var out: [String: Any] = [:] if title != before.title { out["title"] = title } if company != before.company { out["company"] = company } if companyURL != before.companyURL { out["company_url"] = companyURL } if location != before.location { out["location"] = location } if workplace != before.workplace { out["workplace"] = workplace } if employmentType != before.employmentType { out["employment_type"] = employmentType } if category != before.category { out["category"] = category } if payMin != before.payMin || payMax != before.payMax { out["pay_min"] = payMin; out["pay_max"] = payMax } if payPeriod != before.payPeriod { out["pay_period"] = payPeriod } if payCurrency != before.payCurrency { out["pay_currency"] = payCurrency } if description != before.description { out["description"] = description } if applyURL != before.applyURL { out["apply_url"] = applyURL } return out } } /// The Jobley API (PRD section 7). Public calls need no token; admin calls send /// `Authorization: Bearer ` and `X-Client`. public struct APIClient: Sendable { public let base: URL public let client: ClientKind public let token: String? let session: URLSession /// Production until jobley.ai is connected. `JOBLEY_API_BASE` (tests, local work) and the /// "Server" setting override it. public static let productionBase = URL(string: "https://jobley.ai")! public static let serverDefaultsKey = "jobley.server" public static var configuredBase: URL { if let env = ProcessInfo.processInfo.environment["JOBLEY_API_BASE"], let url = URL(string: env) { return url } if let saved = UserDefaults.standard.string(forKey: serverDefaultsKey), let url = URL(string: saved), url.scheme != nil { return url } return productionBase } public init(base: URL = APIClient.configuredBase, client: ClientKind, token: String? = nil, session: URLSession = .shared) { self.base = base; self.client = client; self.token = token?.trimmingCharacters(in: .whitespacesAndNewlines); self.session = session } public var hasToken: Bool { !(token ?? "").isEmpty } public var turnstilePage: URL { base.appending(path: "app/turnstile/") } public func withToken(_ token: String?) -> APIClient { APIClient(base: base, client: client, token: token, session: session) } // MARK: Public public func meta() async throws -> Meta { try await get("api/meta") } public func jobs(query: String = "", workplace: String = "", type: String = "", category: String = "", limit: Int = 30, cursor: String? = nil) async throws -> JobPage { var items = [URLQueryItem(name: "limit", value: String(limit))] if !query.isEmpty { items.append(.init(name: "q", value: String(query.prefix(80)))) } if !workplace.isEmpty { items.append(.init(name: "workplace", value: workplace)) } if !type.isEmpty { items.append(.init(name: "type", value: type)) } if !category.isEmpty { items.append(.init(name: "category", value: category)) } if let cursor { items.append(.init(name: "cursor", value: cursor)) } return try await get("api/jobs", query: items) } public func job(_ id: String) async throws -> Job { let reply: JobReply = try await get("api/jobs/\(id)") return reply.job } public func post(_ draft: JobDraft, turnstileToken: String?) async throws -> PostedJob { try await send("POST", "api/jobs", body: draft.body(turnstileToken: turnstileToken), admin: false) } public func close(job id: String, manageToken: String) async throws { let _: Received = try await send("POST", "api/jobs/\(id)/close", body: ["manage_token": manageToken], admin: false) } public func putForward(_ draft: CandidateDraft, turnstileToken: String?) async throws -> Received { try await send("POST", "api/candidates", body: draft.body(turnstileToken: turnstileToken), admin: false) } // MARK: Admin: jobs public func me() async throws -> Me { try await get("api/admin/me", admin: true) } public func stats() async throws -> Stats { try await get("api/admin/stats", admin: true) } public func adminJobs(status: String, limit: Int = 100) async throws -> [Job] { let reply: JobsReply = try await get("api/admin/jobs", query: [.init(name: "status", value: status), .init(name: "limit", value: String(limit))], admin: true) return reply.jobs } public func reviewItem(_ id: String) async throws -> JobReviewItem { try await get("api/admin/jobs/\(id)", admin: true) } public func edit(job id: String, changes: [String: Any]) async throws -> Job { let reply: JobReply = try await send("PATCH", "api/admin/jobs/\(id)", body: changes) return reply.job } @discardableResult public func addNote(job id: String, note: String) async throws -> String { let reply: IDReply = try await send("POST", "api/admin/jobs/\(id)/notes", body: ["note": note]) return reply.id } /// The normal one-step "Publish" is `approve(publish: true)`. public func approve(job id: String, publish: Bool, reason: String? = nil) async throws -> Job { var body: [String: Any] = ["publish": publish] if let reason, !reason.isEmpty { body["reason"] = reason } let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/approve", body: body) return reply.job } /// "Send back": the reason is required and goes to the poster. public func reject(job id: String, reason: String) async throws -> Job { let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/reject", body: ["reason": reason]) return reply.job } public func publish(job id: String) async throws -> Job { let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/publish", body: [:]) return reply.job } public func unpublish(job id: String, reason: String? = nil) async throws -> Job { var body: [String: Any] = [:] if let reason, !reason.isEmpty { body["reason"] = reason } let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/unpublish", body: body) return reply.job } // MARK: Admin: candidates (people only, never agents) /// `jobID` nil lists everyone; "none" lists people who asked about a kind of job. Oldest first. public func candidates(jobID: String? = nil, status: String? = nil, limit: Int = 200) async throws -> [Candidate] { var items = [URLQueryItem(name: "limit", value: String(limit))] if let jobID { items.append(.init(name: "job_id", value: jobID)) } if let status, !status.isEmpty { items.append(.init(name: "status", value: status)) } let reply: CandidatesReply = try await get("api/admin/candidates", query: items, admin: true) return reply.candidates } public func candidate(_ id: String) async throws -> CandidateDetail { try await get("api/admin/candidates/\(id)", admin: true) } public func introduce(candidate id: String, jobID: String?, note: String?) async throws -> IntroductionResult { var body: [String: Any] = [:] if let jobID { body["job_id"] = jobID } if let note, !note.isEmpty { body["note"] = note } return try await send("POST", "api/admin/candidates/\(id)/introduce", body: body) } public func setStatus(candidate id: String, status: String, note: String? = nil) async throws -> Candidate { var body: [String: Any] = ["status": status] if let note, !note.isEmpty { body["note"] = note } let reply: CandidateReply = try await send("POST", "api/admin/candidates/\(id)/status", body: body) return reply.candidate } // MARK: Admin: moderators (curator only) public func moderatorApplications(status: String = "new") async throws -> [ModeratorApplication] { let reply: ApplicationsReply = try await get("api/admin/moderator-applications", query: [.init(name: "status", value: status)], admin: true) return reply.applications } public func approve(application id: String, canSeeCandidates: Bool) async throws -> NewModerator { try await send("POST", "api/admin/moderator-applications/\(id)/approve", body: ["can_see_candidates": canSeeCandidates]) } public func decline(application id: String, note: String? = nil) async throws { var body: [String: Any] = [:] if let note, !note.isEmpty { body["note"] = note } let _: IDReply = try await send("POST", "api/admin/moderator-applications/\(id)/decline", body: body) } public func moderators() async throws -> [Moderator] { let reply: ModeratorsReply = try await get("api/admin/moderators", admin: true) return reply.moderators } public func setAccess(moderator id: String, canSeeCandidates: Bool) async throws { let _: IDReply = try await send("POST", "api/admin/moderators/\(id)/access", body: ["can_see_candidates": canSeeCandidates]) } public func revoke(moderator id: String) async throws { let _: IDReply = try await send("POST", "api/admin/moderators/\(id)/revoke", body: [:]) } /// Deletes what is past the retention period. The Mac app calls it when the curator opens it. public func purge() async throws -> PurgeResult { try await send("POST", "api/admin/purge", body: [:]) } // MARK: Transport func get(_ path: String, query: [URLQueryItem] = [], admin: Bool = false) async throws -> T { try await perform(request("GET", path, query: query, admin: admin)) } func send(_ method: String, _ path: String, body: [String: Any], admin: Bool = true) async throws -> T { var request = try request(method, path, admin: admin) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try JSONSerialization.data(withJSONObject: body) return try await perform(request) } func request(_ method: String, _ path: String, query: [URLQueryItem] = [], admin: Bool) throws -> URLRequest { var components = URLComponents(url: base.appending(path: path), resolvingAgainstBaseURL: false)! if !query.isEmpty { components.queryItems = query } // Always fresh: the board answers with cache-control max-age=60, and a curator must see a // post disappear the moment it is unpublished. var request = URLRequest(url: components.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30) request.httpMethod = method request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue(client.rawValue, forHTTPHeaderField: "X-Client") if admin { guard let token, !token.isEmpty else { throw APIError.signedOut } request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } return request } func perform(_ request: URLRequest) async throws -> T { let data: Data, response: URLResponse do { (data, response) = try await session.data(for: request) } catch { throw APIError(code: "offline", message: "We couldn't reach Jobley. Check your connection and try again.") } let status = (response as? HTTPURLResponse)?.statusCode ?? 0 guard (200..<300).contains(status) else { throw Self.error(from: data, status: status) } do { return try JSONDecoder().decode(T.self, from: data) } catch { throw APIError(code: "bad_reply", message: "Jobley sent a reply we couldn't read.", httpStatus: status) } } static func error(from data: Data, status: Int) -> APIError { guard let reply = try? JSONDecoder().decode(ErrorReply.self, from: data) else { return APIError(code: "http_\(status)", message: "Jobley answered with an error (\(status)). Please try again.", httpStatus: status) } return APIError(code: reply.error, message: reply.message, fields: reply.fields ?? [:], status: reply.status, httpStatus: status) } } struct ErrorReply: Decodable { var error: String var message: String var fields: [String: String]? var status: String? } struct JobReply: Decodable { var job: Job } struct JobsReply: Decodable { var jobs: [Job] } struct IDReply: Decodable { var id: String } struct CandidatesReply: Decodable { var candidates: [Candidate] } struct CandidateReply: Decodable { var candidate: Candidate } struct ApplicationsReply: Decodable { var applications: [ModeratorApplication] } struct ModeratorsReply: Decodable { var moderators: [Moderator] }