feat: полноценное Pulse приложение с TabBar
- Auth: переключено на Pulse API (api.digital-home.site) вместо health - TabBar: Главная, Задачи, Привычки, Здоровье, Финансы - Models: TaskModels, HabitModels, FinanceModels, обновлённые AuthModels - Services: APIService (Pulse API), HealthAPIService (health отдельно) - Dashboard: обзор дня с задачами, привычками, readiness, балансом - Tasks: список, фильтр, создание, выполнение, удаление - Habits: список с прогресс-баром, отметка выполнения, стрики - Health: бывший DashboardView, HealthKit sync через health API key - Finance: баланс, список транзакций, добавление расхода/дохода - Health данные через x-api-key вместо JWT токена health сервиса
This commit is contained in:
@@ -9,115 +9,110 @@ enum APIError: Error, LocalizedError {
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .unauthorized: return "Неверный email или пароль"
|
||||
case .networkError(let msg): return "Ошибка сети: \(msg)"
|
||||
case .decodingError(let msg): return "Ошибка данных: \(msg)"
|
||||
case .serverError(let code, let msg): return "Ошибка сервера \(code): \(msg)"
|
||||
case .networkError(let m): return "Ошибка сети: \(m)"
|
||||
case .decodingError(let m): return "Ошибка данных: \(m)"
|
||||
case .serverError(let c, let m): return "Ошибка \(c): \(m)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class APIService {
|
||||
static let shared = APIService()
|
||||
let baseURL = "https://health.digital-home.site"
|
||||
let baseURL = "https://api.digital-home.site"
|
||||
|
||||
private func makeRequest(url: URL, method: String = "GET", token: String? = nil, body: Data? = nil) -> URLRequest {
|
||||
var req = URLRequest(url: url)
|
||||
private func makeRequest(_ path: String, method: String = "GET", token: String? = nil, body: Data? = nil) -> URLRequest {
|
||||
var req = URLRequest(url: URL(string: "\(baseURL)\(path)")!)
|
||||
req.httpMethod = method
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
req.timeoutInterval = 15
|
||||
if let token = token {
|
||||
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||
}
|
||||
if let t = token { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }
|
||||
req.httpBody = body
|
||||
return req
|
||||
}
|
||||
|
||||
func login(email: String, password: String) async throws -> LoginResponse {
|
||||
let url = URL(string: "\(baseURL)/api/auth/login")!
|
||||
private func fetch<T: Decodable>(_ path: String, method: String = "GET", token: String? = nil, body: Data? = nil) async throws -> T {
|
||||
let req = makeRequest(path, method: method, token: token, body: body)
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let http = response as? HTTPURLResponse else { throw APIError.networkError("Нет ответа") }
|
||||
if http.statusCode == 401 { throw APIError.unauthorized }
|
||||
if http.statusCode >= 400 {
|
||||
let msg = String(data: data, encoding: .utf8) ?? "Unknown"
|
||||
throw APIError.serverError(http.statusCode, msg)
|
||||
}
|
||||
do { return try JSONDecoder().decode(T.self, from: data) }
|
||||
catch { throw APIError.decodingError(error.localizedDescription) }
|
||||
}
|
||||
|
||||
// MARK: - Auth
|
||||
|
||||
func login(email: String, password: String) async throws -> AuthResponse {
|
||||
let body = try JSONEncoder().encode(LoginRequest(email: email, password: password))
|
||||
let req = makeRequest(url: url, method: "POST", body: body)
|
||||
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let httpResponse = response as? HTTPURLResponse else {
|
||||
throw APIError.networkError("Нет ответа от сервера")
|
||||
}
|
||||
|
||||
if httpResponse.statusCode == 401 {
|
||||
throw APIError.unauthorized
|
||||
}
|
||||
|
||||
if httpResponse.statusCode != 200 {
|
||||
let msg = String(data: data, encoding: .utf8) ?? "Unknown"
|
||||
throw APIError.serverError(httpResponse.statusCode, msg)
|
||||
}
|
||||
|
||||
do {
|
||||
return try JSONDecoder().decode(LoginResponse.self, from: data)
|
||||
} catch {
|
||||
throw APIError.decodingError(error.localizedDescription)
|
||||
}
|
||||
return try await fetch("/auth/login", method: "POST", body: body)
|
||||
}
|
||||
|
||||
func register(email: String, password: String, name: String) async throws -> LoginResponse {
|
||||
let url = URL(string: "\(baseURL)/api/auth/register")!
|
||||
let body = try JSONEncoder().encode(["email": email, "password": password, "name": name])
|
||||
let req = makeRequest(url: url, method: "POST", body: body)
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let httpResponse = response as? HTTPURLResponse else { throw APIError.networkError("Нет ответа") }
|
||||
if httpResponse.statusCode == 409 { throw APIError.serverError(409, "Email уже занят") }
|
||||
if httpResponse.statusCode != 200 && httpResponse.statusCode != 201 {
|
||||
let msg = String(data: data, encoding: .utf8) ?? "Unknown"
|
||||
throw APIError.serverError(httpResponse.statusCode, msg)
|
||||
}
|
||||
return try JSONDecoder().decode(LoginResponse.self, from: data)
|
||||
func register(email: String, password: String, name: String) async throws -> AuthResponse {
|
||||
let body = try JSONEncoder().encode(RegisterRequest(email: email, password: password, name: name))
|
||||
return try await fetch("/auth/register", method: "POST", body: body)
|
||||
}
|
||||
|
||||
func forgotPassword(email: String) async throws {
|
||||
let url = URL(string: "\(baseURL)/api/auth/forgot-password")!
|
||||
let body = try JSONEncoder().encode(["email": email])
|
||||
let req = makeRequest(url: url, method: "POST", body: body)
|
||||
_ = try await URLSession.shared.data(for: req)
|
||||
func me(token: String) async throws -> UserInfo {
|
||||
return try await fetch("/auth/me", token: token)
|
||||
}
|
||||
|
||||
func getProfile(token: String) async throws -> ProfileResponse {
|
||||
let url = URL(string: "\(baseURL)/api/profile")!
|
||||
let req = makeRequest(url: url, token: token)
|
||||
let (data, _) = try await URLSession.shared.data(for: req)
|
||||
return try JSONDecoder().decode(ProfileResponse.self, from: data)
|
||||
// MARK: - Tasks
|
||||
|
||||
func getTasks(token: String) async throws -> [PulseTask] {
|
||||
return try await fetch("/tasks", token: token)
|
||||
}
|
||||
|
||||
func getReadiness(token: String) async throws -> ReadinessResponse {
|
||||
let url = URL(string: "\(baseURL)/api/health/readiness")!
|
||||
let req = makeRequest(url: url, token: token)
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
|
||||
throw APIError.networkError("Readiness недоступен")
|
||||
}
|
||||
return try JSONDecoder().decode(ReadinessResponse.self, from: data)
|
||||
func getTodayTasks(token: String) async throws -> [PulseTask] {
|
||||
return try await fetch("/tasks/today", token: token)
|
||||
}
|
||||
|
||||
func getLatest(token: String) async throws -> LatestHealthResponse {
|
||||
let url = URL(string: "\(baseURL)/api/health/latest")!
|
||||
let req = makeRequest(url: url, token: token)
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
|
||||
throw APIError.networkError("Latest недоступен")
|
||||
}
|
||||
return try JSONDecoder().decode(LatestHealthResponse.self, from: data)
|
||||
@discardableResult
|
||||
func createTask(token: String, request: CreateTaskRequest) async throws -> PulseTask {
|
||||
let body = try JSONEncoder().encode(request)
|
||||
return try await fetch("/tasks", method: "POST", token: token, body: body)
|
||||
}
|
||||
|
||||
func getHeatmap(token: String, days: Int = 7) async throws -> [HeatmapEntry] {
|
||||
let url = URL(string: "\(baseURL)/api/health/heatmap?days=\(days)")!
|
||||
let req = makeRequest(url: url, token: token)
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
|
||||
throw APIError.networkError("Heatmap недоступен")
|
||||
}
|
||||
// Try array first, then wrapped response
|
||||
if let entries = try? JSONDecoder().decode([HeatmapEntry].self, from: data) {
|
||||
return entries
|
||||
}
|
||||
let wrapped = try JSONDecoder().decode(HeatmapResponse.self, from: data)
|
||||
return wrapped.data
|
||||
func completeTask(token: String, id: Int) async throws {
|
||||
let _: EmptyResponse = try await fetch("/tasks/\(id)/complete", method: "POST", token: token)
|
||||
}
|
||||
|
||||
func deleteTask(token: String, id: Int) async throws {
|
||||
let _: EmptyResponse = try await fetch("/tasks/\(id)", method: "DELETE", token: token)
|
||||
}
|
||||
|
||||
// MARK: - Habits
|
||||
|
||||
func getHabits(token: String) async throws -> [Habit] {
|
||||
return try await fetch("/habits", token: token)
|
||||
}
|
||||
|
||||
func logHabit(token: String, id: Int) async throws {
|
||||
let body = try JSONEncoder().encode(HabitLogRequest())
|
||||
let _: EmptyResponse = try await fetch("/habits/\(id)/log", method: "POST", token: token, body: body)
|
||||
}
|
||||
|
||||
// MARK: - Finance
|
||||
|
||||
func getFinanceSummary(token: String) async throws -> FinanceSummary {
|
||||
return try await fetch("/finance/summary", token: token)
|
||||
}
|
||||
|
||||
func getTransactions(token: String) async throws -> [FinanceTransaction] {
|
||||
return try await fetch("/finance/transactions", token: token)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func createTransaction(token: String, request: CreateTransactionRequest) async throws -> FinanceTransaction {
|
||||
let body = try JSONEncoder().encode(request)
|
||||
return try await fetch("/finance/transactions", method: "POST", token: token, body: body)
|
||||
}
|
||||
|
||||
func getFinanceCategories(token: String) async throws -> [FinanceCategory] {
|
||||
return try await fetch("/finance/categories", token: token)
|
||||
}
|
||||
}
|
||||
|
||||
struct EmptyResponse: Codable {}
|
||||
|
||||
60
PulseHealth/Services/HealthAPIService.swift
Normal file
60
PulseHealth/Services/HealthAPIService.swift
Normal file
@@ -0,0 +1,60 @@
|
||||
import Foundation
|
||||
|
||||
class HealthAPIService {
|
||||
static let shared = HealthAPIService()
|
||||
let baseURL = "https://health.digital-home.site"
|
||||
|
||||
private func makeRequest(_ path: String, token: String? = nil, apiKey: String? = nil) -> URLRequest {
|
||||
var req = URLRequest(url: URL(string: "\(baseURL)\(path)")!)
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
req.timeoutInterval = 15
|
||||
if let t = token { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }
|
||||
if let k = apiKey { req.setValue(k, forHTTPHeaderField: "x-api-key") }
|
||||
return req
|
||||
}
|
||||
|
||||
func getLatest(apiKey: String) async throws -> LatestHealthResponse {
|
||||
let req = makeRequest("/api/health/latest", apiKey: apiKey)
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
|
||||
throw APIError.networkError("Latest недоступен")
|
||||
}
|
||||
return try JSONDecoder().decode(LatestHealthResponse.self, from: data)
|
||||
}
|
||||
|
||||
func getReadiness(apiKey: String) async throws -> ReadinessResponse {
|
||||
let req = makeRequest("/api/health/readiness", apiKey: apiKey)
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
|
||||
throw APIError.networkError("Readiness недоступен")
|
||||
}
|
||||
return try JSONDecoder().decode(ReadinessResponse.self, from: data)
|
||||
}
|
||||
|
||||
func getHeatmap(apiKey: String, days: Int = 7) async throws -> [HeatmapEntry] {
|
||||
let req = makeRequest("/api/health/heatmap?days=\(days)", apiKey: apiKey)
|
||||
let (data, response) = try await URLSession.shared.data(for: req)
|
||||
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
|
||||
throw APIError.networkError("Heatmap недоступен")
|
||||
}
|
||||
if let entries = try? JSONDecoder().decode([HeatmapEntry].self, from: data) {
|
||||
return entries
|
||||
}
|
||||
let wrapped = try JSONDecoder().decode(HeatmapResponse.self, from: data)
|
||||
return wrapped.data
|
||||
}
|
||||
|
||||
func sendHealthData(apiKey: String, payload: Data) async throws {
|
||||
let url = URL(string: "\(baseURL)/api/health?key=\(apiKey)")!
|
||||
var req = URLRequest(url: url)
|
||||
req.httpMethod = "POST"
|
||||
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
req.httpBody = payload
|
||||
req.timeoutInterval = 30
|
||||
let (_, response) = try await URLSession.shared.data(for: req)
|
||||
guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode) else {
|
||||
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
|
||||
throw APIError.serverError(code, "Ошибка отправки health данных")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ class HealthKitService: ObservableObject {
|
||||
|
||||
let jsonData = try JSONSerialization.data(withJSONObject: payload)
|
||||
|
||||
let urlStr = "\(APIService.shared.baseURL)/api/health?key=\(apiKey)"
|
||||
let urlStr = "\(HealthAPIService.shared.baseURL)/api/health?key=\(apiKey)"
|
||||
guard let url = URL(string: urlStr) else {
|
||||
throw HealthKitError.invalidURL
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user