Files
FrenoCorp/Lendair/Services/FamilyPlanService.swift
Michael Freno 57a460761a FRE-4665: Implement Phase 3 AI training plans and premium features
- Models: TrainingPlan, Race, FamilyPlan, BeginnerMode, CommunityEvent
- Services: 5 service layers with protocol-based architecture
- ViewModels: 5 view models with @MainActor ObservableObject pattern
- Views: 10 SwiftUI views for all Phase 3 features
- Updated README with full Phase 3 documentation

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-05-03 15:21:01 -04:00

126 lines
4.4 KiB
Swift

import Foundation
// MARK: - Service Protocol
protocol FamilyPlanServiceProtocol: Sendable {
func getFamilyPlan() async throws -> FamilyPlan
func inviteMember(request: InviteMemberRequest) async throws
func removeMember(id: String) async throws
func getLeaderboard(metric: LeaderboardMetric) async throws -> [FamilyLeaderboardEntry]
}
// MARK: - Default Service
class FamilyPlanService: FamilyPlanServiceProtocol {
private let baseURL: URL
private let session: URLSession
private let authToken: String?
init(
baseURL: URL = URL(string: "http://localhost:3000")!,
session: URLSession = .shared,
authToken: String? = nil
) {
self.baseURL = baseURL
self.session = session
self.authToken = authToken
}
func getFamilyPlan() async throws -> FamilyPlan {
let url = baseURL.appendingPathComponent("/api/family-plan")
let request = try buildRequest(url: url)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
let decoded = try JSONDecoder().decode(FamilyPlanDetailResponse.self, from: data)
return decoded.plan
}
func inviteMember(request: InviteMemberRequest) async throws {
let url = baseURL.appendingPathComponent("/api/family-plan/invite")
var request = try buildRequest(url: url, method: .post)
request.httpBody = try JSONEncoder().encode(request)
let (_, response) = try await session.data(for: request)
try validateResponse(response)
}
func removeMember(id: String) async throws {
let url = baseURL.appendingPathComponent("/api/family-plan/members/\(id)")
let request = try buildRequest(url: url, method: .delete)
let (_, response) = try await session.data(for: request)
try validateResponse(response)
}
func getLeaderboard(metric: LeaderboardMetric) async throws -> [FamilyLeaderboardEntry] {
var components = URLComponents(url: baseURL.appendingPathComponent("/api/family-plan/leaderboard"), resolvingAgainstBaseURL: true)!
components.queryItems = [URLQueryItem(name: "metric", value: metric.rawValue)]
let request = try buildRequest(url: components.url!)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
let decoded = try JSONDecoder().decode(FamilyLeaderboardResponse.self, from: data)
return decoded.entries
}
// MARK: - Helpers
private func buildRequest(url: URL, method: HTTPMethod = .get, body: Data? = nil) throws -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let token = authToken {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
if let body = body {
request.httpBody = body
}
return request
}
private func validateResponse(_ response: URLResponse) throws {
guard let httpResponse = response as? HTTPURLResponse else {
throw FamilyPlanError.invalidResponse
}
guard (200...299).contains(httpResponse.statusCode) else {
switch httpResponse.statusCode {
case 401: throw FamilyPlanError.unauthorized
case 403: throw FamilyPlanError.forbidden
case 404: throw FamilyPlanError.notFound
case 429: throw FamilyPlanError.rateLimited
case 500...599: throw FamilyPlanError.serverError(httpResponse.statusCode)
default: throw FamilyPlanError.httpError(httpResponse.statusCode)
}
}
}
}
// MARK: - Error Types
enum FamilyPlanError: LocalizedError {
case invalidResponse
case unauthorized
case forbidden
case notFound
case rateLimited
case serverError(Int)
case httpError(Int)
var errorDescription: String {
switch self {
case .invalidResponse: return "Invalid server response"
case .unauthorized: return "Unauthorized — please log in again"
case .forbidden: return "Forbidden — check permissions"
case .notFound: return "Family plan not found"
case .rateLimited: return "Too many requests — try again shortly"
case .serverError(let code): return "Server error (\(code))"
case .httpError(let code): return "HTTP error (\(code))"
}
}
}