05/02 Phase C 2
This commit is contained in:
+134
-147
@@ -1,12 +1,9 @@
|
||||
// API/APIClient.swift
|
||||
// -------------------
|
||||
// Central HTTP client for all JQC API calls.
|
||||
// Phase C adds: fetchInspectionHistory()
|
||||
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
enum APIError: Error, LocalizedError {
|
||||
enum APIError: Error, LocalizedError, Sendable {
|
||||
case invalidURL
|
||||
case notAuthenticated
|
||||
case serverError(String)
|
||||
@@ -24,160 +21,125 @@ enum APIError: Error, LocalizedError {
|
||||
}
|
||||
}
|
||||
|
||||
// File-scope envelope — cannot be nested in a generic function (Swift restriction).
|
||||
// T is constrained to Sendable so `data: T?` does not inherit @MainActor isolation.
|
||||
private struct _Envelope<T: Decodable & Sendable>: Decodable, Sendable {
|
||||
let ok: Bool
|
||||
let data: T?
|
||||
let error: String?
|
||||
|
||||
nonisolated init(from decoder: any Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
ok = try c.decode(Bool.self, forKey: .ok)
|
||||
data = try? c.decode(T.self, forKey: .data)
|
||||
error = try? c.decode(String.self, forKey: .error)
|
||||
}
|
||||
private enum CodingKeys: String, CodingKey { case ok, data, error }
|
||||
}
|
||||
|
||||
// Refresh-only envelope — uses a non-Sendable-constrained local struct
|
||||
// decoded manually to avoid pulling RefreshResponseData into the Sendable chain.
|
||||
private struct _RefreshEnvelope: Decodable {
|
||||
struct Tokens: Decodable {
|
||||
let accessToken: String
|
||||
let refreshToken: String
|
||||
}
|
||||
let ok: Bool
|
||||
let data: Tokens?
|
||||
}
|
||||
|
||||
actor APIClient {
|
||||
static let shared = APIClient()
|
||||
|
||||
private let baseURL: String
|
||||
private let session: URLSession
|
||||
private let decoder: JSONDecoder
|
||||
|
||||
private init() {
|
||||
self.baseURL = Constants.baseURL
|
||||
let config = URLSessionConfiguration.default
|
||||
let config = URLSessionConfiguration.default
|
||||
config.timeoutIntervalForRequest = 30
|
||||
self.session = URLSession(configuration: config)
|
||||
self.decoder = JSONDecoder()
|
||||
self.decoder.keyDecodingStrategy = .convertFromSnakeCase
|
||||
}
|
||||
|
||||
// ── Generic JSON Request ──────────────────────────────────────────────
|
||||
|
||||
func request<T: Decodable>(
|
||||
func request<T: Decodable & Sendable>(
|
||||
_ endpoint: String,
|
||||
method: String = "GET",
|
||||
body: [String: Any]? = nil,
|
||||
retrying: Bool = false
|
||||
) async throws -> T {
|
||||
let url = try buildURL(endpoint)
|
||||
var req = buildRequest(url: url, method: method, body: body)
|
||||
injectToken(&req)
|
||||
|
||||
guard let url = URL(string: baseURL + endpoint) else {
|
||||
throw APIError.invalidURL
|
||||
}
|
||||
let (data, response) = try await performRequest(req)
|
||||
|
||||
var req = URLRequest(url: url)
|
||||
req.httpMethod = method
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
|
||||
if let token = KeychainHelper.get(Constants.Keychain.accessToken) {
|
||||
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||
}
|
||||
|
||||
if let body {
|
||||
req.httpBody = try? JSONSerialization.data(withJSONObject: body)
|
||||
}
|
||||
|
||||
let (data, response) = try await session.data(for: req)
|
||||
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw APIError.networkError("Invalid response")
|
||||
}
|
||||
|
||||
if http.statusCode == 401 && !retrying {
|
||||
if shouldRefresh(response, retrying: retrying) {
|
||||
let refreshed = await refreshAccessToken()
|
||||
if refreshed {
|
||||
return try await request(endpoint, method: method, body: body, retrying: true)
|
||||
} else {
|
||||
throw APIError.notAuthenticated
|
||||
}
|
||||
throw APIError.notAuthenticated
|
||||
}
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.keyDecodingStrategy = .convertFromSnakeCase
|
||||
|
||||
if let envelope = try? decoder.decode(APIResponse<T>.self, from: data) {
|
||||
if envelope.ok, let result = envelope.data {
|
||||
return result
|
||||
} else {
|
||||
throw APIError.serverError(envelope.error ?? "Unknown server error")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
return try decoder.decode(T.self, from: data)
|
||||
} catch {
|
||||
throw APIError.decodingError(error.localizedDescription)
|
||||
}
|
||||
return try decode(data)
|
||||
}
|
||||
|
||||
func post<T: Decodable>(_ endpoint: String, body: [String: Any]) async throws -> T {
|
||||
func post<T: Decodable & Sendable>(_ endpoint: String, body: [String: Any]) async throws -> T {
|
||||
return try await request(endpoint, method: "POST", body: body)
|
||||
}
|
||||
|
||||
// ── Inspection History (Phase C) ──────────────────────────────────────
|
||||
// ── Inspection History ────────────────────────────────────────────────
|
||||
|
||||
/// Fetch the inspector's synced inspection history from the server.
|
||||
/// Returns up to `limit` records starting at `offset`.
|
||||
func fetchInspectionHistory(
|
||||
limit: Int = 50,
|
||||
offset: Int = 0,
|
||||
facilityId: Int? = nil
|
||||
) async throws -> InspectionHistoryResponseData {
|
||||
var endpoint = "/api/v1/inspections?limit=\(limit)&offset=\(offset)&status=completed"
|
||||
if let fid = facilityId {
|
||||
endpoint += "&facility_id=\(fid)"
|
||||
}
|
||||
return try await request(endpoint)
|
||||
var ep = "/api/v1/inspections?limit=\(limit)&offset=\(offset)&status=completed"
|
||||
if let fid = facilityId { ep += "&facility_id=\(fid)" }
|
||||
return try await request(ep)
|
||||
}
|
||||
|
||||
// ── Photo Upload (multipart/form-data) ────────────────────────────────
|
||||
// ── Photo Upload ──────────────────────────────────────────────────────
|
||||
|
||||
func uploadPhoto(localPath: String, entityType: String) async throws -> String {
|
||||
guard let url = URL(string: baseURL + "/api/v1/photos/upload") else {
|
||||
throw APIError.invalidURL
|
||||
}
|
||||
let url = try buildURL("/api/v1/photos/upload")
|
||||
|
||||
guard let imageData = FileManager.default.contents(atPath: localPath) else {
|
||||
throw APIError.networkError("Could not read photo file: \(localPath)")
|
||||
throw APIError.networkError("Could not read photo: \(localPath)")
|
||||
}
|
||||
|
||||
let boundary = "Boundary-\(UUID().uuidString)"
|
||||
var body = Data()
|
||||
|
||||
body.append("--\(boundary)\r\n".data(using: .utf8)!)
|
||||
body.append("Content-Disposition: form-data; name=\"entity_type\"\r\n\r\n".data(using: .utf8)!)
|
||||
body.append("\(entityType)\r\n".data(using: .utf8)!)
|
||||
|
||||
let filename = URL(fileURLWithPath: localPath).lastPathComponent
|
||||
let ext = (filename as NSString).pathExtension.lowercased()
|
||||
let mimeType = ext == "png" ? "image/png" : "image/jpeg"
|
||||
let mime = ext == "png" ? "image/png" : "image/jpeg"
|
||||
|
||||
body.append("--\(boundary)\r\n".data(using: .utf8)!)
|
||||
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n".data(using: .utf8)!)
|
||||
body.append("Content-Type: \(mimeType)\r\n\r\n".data(using: .utf8)!)
|
||||
var body = Data()
|
||||
body.append("--\(boundary)\r\nContent-Disposition: form-data; name=\"entity_type\"\r\n\r\n\(entityType)\r\n".data(using: .utf8)!)
|
||||
body.append("--\(boundary)\r\nContent-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\nContent-Type: \(mime)\r\n\r\n".data(using: .utf8)!)
|
||||
body.append(imageData)
|
||||
body.append("\r\n".data(using: .utf8)!)
|
||||
body.append("--\(boundary)--\r\n".data(using: .utf8)!)
|
||||
body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
|
||||
|
||||
var req = URLRequest(url: url)
|
||||
req.httpMethod = "POST"
|
||||
req.setValue("multipart/form-data; boundary=\(boundary)",
|
||||
forHTTPHeaderField: "Content-Type")
|
||||
if let token = KeychainHelper.get(Constants.Keychain.accessToken) {
|
||||
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||
}
|
||||
req.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
|
||||
injectToken(&req)
|
||||
req.httpBody = body
|
||||
|
||||
let (data, response) = try await session.data(for: req)
|
||||
let (data, response) = try await performRequest(req)
|
||||
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw APIError.networkError("Invalid response")
|
||||
}
|
||||
|
||||
if http.statusCode == 401 {
|
||||
if shouldRefresh(response, retrying: false) {
|
||||
let refreshed = await refreshAccessToken()
|
||||
if refreshed {
|
||||
return try await uploadPhoto(localPath: localPath, entityType: entityType)
|
||||
} else {
|
||||
throw APIError.notAuthenticated
|
||||
}
|
||||
}
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.keyDecodingStrategy = .convertFromSnakeCase
|
||||
|
||||
struct PhotoUploadData: Decodable { let serverPath: String }
|
||||
if let envelope = try? decoder.decode(APIResponse<PhotoUploadData>.self, from: data),
|
||||
envelope.ok,
|
||||
let result = envelope.data {
|
||||
return result.serverPath
|
||||
if refreshed { return try await uploadPhoto(localPath: localPath, entityType: entityType) }
|
||||
throw APIError.notAuthenticated
|
||||
}
|
||||
|
||||
struct PhotoResult: Decodable, Sendable { let serverPath: String }
|
||||
if let env = try? decoder.decode(_Envelope<PhotoResult>.self, from: data),
|
||||
env.ok, let r = env.data { return r.serverPath }
|
||||
throw APIError.serverError("Photo upload failed")
|
||||
}
|
||||
|
||||
@@ -190,25 +152,18 @@ actor APIClient {
|
||||
"status": "completed",
|
||||
"form_data": inspection.formData,
|
||||
"mobile_local_id": inspection.localId,
|
||||
"overall_score": inspection.overallScore as Any,
|
||||
]
|
||||
if let score = inspection.overallScore { body["overall_score"] = score }
|
||||
if let areaId = inspection.areaServerId { body["area_id"] = areaId }
|
||||
if !inspection.inspectorNotes.isEmpty { body["notes"] = inspection.inspectorNotes }
|
||||
|
||||
if let areaId = inspection.areaServerId { body["area_id"] = areaId }
|
||||
if !inspection.inspectorNotes.isEmpty { body["notes"] = inspection.inspectorNotes }
|
||||
let fmt = ISO8601DateFormatter()
|
||||
body["inspection_date"] = fmt.string(from: inspection.inspectionDate)
|
||||
if let c = inspection.completedAt { body["completed_at"] = fmt.string(from: c) }
|
||||
|
||||
let formatter = ISO8601DateFormatter()
|
||||
body["inspection_date"] = formatter.string(from: inspection.inspectionDate)
|
||||
if let completedAt = inspection.completedAt {
|
||||
body["completed_at"] = formatter.string(from: completedAt)
|
||||
}
|
||||
|
||||
struct InspectionResponseData: Decodable {
|
||||
let inspectionId: Int
|
||||
let duplicate: Bool
|
||||
}
|
||||
|
||||
let result: InspectionResponseData = try await post("/api/v1/inspections", body: body)
|
||||
return result.inspectionId
|
||||
struct R: Decodable, Sendable { let inspectionId: Int; let duplicate: Bool }
|
||||
let r: R = try await post("/api/v1/inspections", body: body)
|
||||
return r.inspectionId
|
||||
}
|
||||
|
||||
// ── Submit Issue ──────────────────────────────────────────────────────
|
||||
@@ -220,53 +175,85 @@ actor APIClient {
|
||||
"description": issue.issueDescription,
|
||||
"mobile_local_id": issue.localId,
|
||||
]
|
||||
if let id = issue.inspection?.serverId { body["inspection_id"] = id }
|
||||
if let path = issue.photoServerPath { body["photo_path"] = path }
|
||||
|
||||
if let inspServerId = issue.inspection?.serverId {
|
||||
body["inspection_id"] = inspServerId
|
||||
}
|
||||
if let serverPhotoPath = issue.photoServerPath {
|
||||
body["photo_path"] = serverPhotoPath
|
||||
}
|
||||
|
||||
struct IssueResponseData: Decodable {
|
||||
let issueId: Int
|
||||
let duplicate: Bool
|
||||
}
|
||||
|
||||
let result: IssueResponseData = try await post("/api/v1/issues", body: body)
|
||||
return result.issueId
|
||||
struct R: Decodable, Sendable { let issueId: Int; let duplicate: Bool }
|
||||
let r: R = try await post("/api/v1/issues", body: body)
|
||||
return r.issueId
|
||||
}
|
||||
|
||||
// ── Token Refresh ─────────────────────────────────────────────────────
|
||||
|
||||
private func refreshAccessToken() async -> Bool {
|
||||
guard let refreshToken = KeychainHelper.get(Constants.Keychain.refreshToken),
|
||||
let url = URL(string: baseURL + "/api/v1/auth/refresh") else {
|
||||
return false
|
||||
}
|
||||
guard let token = KeychainHelper.get(Constants.Keychain.refreshToken),
|
||||
let url = URL(string: Constants.baseURL + "/api/v1/auth/refresh")
|
||||
else { return false }
|
||||
|
||||
var req = URLRequest(url: url)
|
||||
req.httpMethod = "POST"
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
req.httpBody = try? JSONSerialization.data(
|
||||
withJSONObject: ["refresh_token": refreshToken]
|
||||
)
|
||||
req.httpBody = try? JSONSerialization.data(withJSONObject: ["refresh_token": token])
|
||||
|
||||
guard let (data, response) = try? await session.data(for: req),
|
||||
let http = response as? HTTPURLResponse,
|
||||
http.statusCode == 200
|
||||
let http = response as? HTTPURLResponse, http.statusCode == 200
|
||||
else { return false }
|
||||
|
||||
let decoder = JSONDecoder()
|
||||
decoder.keyDecodingStrategy = .convertFromSnakeCase
|
||||
|
||||
guard let envelope = try? decoder.decode(APIResponse<RefreshResponseData>.self, from: data),
|
||||
envelope.ok,
|
||||
let refreshData = envelope.data
|
||||
guard let env = try? decoder.decode(_RefreshEnvelope.self, from: data),
|
||||
env.ok,
|
||||
let tokens = env.data
|
||||
else { return false }
|
||||
|
||||
KeychainHelper.set(refreshData.accessToken, forKey: Constants.Keychain.accessToken)
|
||||
KeychainHelper.set(refreshData.refreshToken, forKey: Constants.Keychain.refreshToken)
|
||||
KeychainHelper.set(tokens.accessToken, forKey: Constants.Keychain.accessToken)
|
||||
KeychainHelper.set(tokens.refreshToken, forKey: Constants.Keychain.refreshToken)
|
||||
return true
|
||||
}
|
||||
|
||||
// ── Private Helpers ───────────────────────────────────────────────────
|
||||
|
||||
private func buildURL(_ endpoint: String) throws -> URL {
|
||||
guard let url = URL(string: Constants.baseURL + endpoint) else {
|
||||
throw APIError.invalidURL
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
private func buildRequest(url: URL, method: String, body: [String: Any]?) -> URLRequest {
|
||||
var req = URLRequest(url: url)
|
||||
req.httpMethod = method
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
if let body { req.httpBody = try? JSONSerialization.data(withJSONObject: body) }
|
||||
return req
|
||||
}
|
||||
|
||||
private func injectToken(_ req: inout URLRequest) {
|
||||
if let token = KeychainHelper.get(Constants.Keychain.accessToken) {
|
||||
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||
}
|
||||
}
|
||||
|
||||
private func performRequest(_ req: URLRequest) async throws -> (Data, URLResponse) {
|
||||
do {
|
||||
return try await session.data(for: req)
|
||||
} catch {
|
||||
throw APIError.networkError(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
private func shouldRefresh(_ response: URLResponse, retrying: Bool) -> Bool {
|
||||
guard !retrying, let http = response as? HTTPURLResponse else { return false }
|
||||
return http.statusCode == 401
|
||||
}
|
||||
|
||||
private func decode<T: Decodable & Sendable>(_ data: Data) throws -> T {
|
||||
if let env = try? decoder.decode(_Envelope<T>.self, from: data) {
|
||||
if env.ok, let result = env.data { return result }
|
||||
throw APIError.serverError(env.error ?? "Unknown server error")
|
||||
}
|
||||
do {
|
||||
return try decoder.decode(T.self, from: data)
|
||||
} catch {
|
||||
throw APIError.decodingError(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user