From c015824b36d7078bcc73c8c403747cd9abbefb25 Mon Sep 17 00:00:00 2001 From: Cosmo Date: Wed, 25 Mar 2026 11:49:52 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=BF=D0=BE=D0=BB=D0=BD=D0=BE=D1=86?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D0=BE=D0=B5=20Pulse=20=D0=BF=D1=80=D0=B8?= =?UTF-8?q?=D0=BB=D0=BE=D0=B6=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=81=20TabBar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 сервиса --- PulseHealth/App.swift | 38 ++-- PulseHealth/Models/AuthModels.swift | 32 +++- PulseHealth/Models/FinanceModels.swift | 51 +++++ PulseHealth/Models/HabitModels.swift | 46 +++++ PulseHealth/Models/TaskModels.swift | 51 +++++ PulseHealth/Services/APIService.swift | 161 ++++++++-------- PulseHealth/Services/HealthAPIService.swift | 60 ++++++ PulseHealth/Services/HealthKitService.swift | 2 +- .../Views/Dashboard/DashboardView.swift | 181 ++++++++++++++++++ .../Views/Finance/AddTransactionView.swift | 82 ++++++++ PulseHealth/Views/Finance/FinanceView.swift | 125 ++++++++++++ PulseHealth/Views/Habits/HabitRowView.swift | 45 +++++ PulseHealth/Views/Habits/HabitsView.swift | 73 +++++++ .../HealthView.swift} | 40 +--- .../Views/{ => Health}/MetricCardView.swift | 0 .../{ => Health}/ReadinessCardView.swift | 0 .../Views/{ => Health}/ToastView.swift | 0 .../Views/{ => Health}/WeeklyChartView.swift | 0 PulseHealth/Views/LoginView.swift | 84 ++------ PulseHealth/Views/MainTabView.swift | 26 +++ PulseHealth/Views/Tasks/AddTaskView.swift | 55 ++++++ PulseHealth/Views/Tasks/TaskRowView.swift | 45 +++++ PulseHealth/Views/Tasks/TasksView.swift | 95 +++++++++ 23 files changed, 1090 insertions(+), 202 deletions(-) create mode 100644 PulseHealth/Models/FinanceModels.swift create mode 100644 PulseHealth/Models/HabitModels.swift create mode 100644 PulseHealth/Models/TaskModels.swift create mode 100644 PulseHealth/Services/HealthAPIService.swift create mode 100644 PulseHealth/Views/Dashboard/DashboardView.swift create mode 100644 PulseHealth/Views/Finance/AddTransactionView.swift create mode 100644 PulseHealth/Views/Finance/FinanceView.swift create mode 100644 PulseHealth/Views/Habits/HabitRowView.swift create mode 100644 PulseHealth/Views/Habits/HabitsView.swift rename PulseHealth/Views/{DashboardView.swift => Health/HealthView.swift} (84%) rename PulseHealth/Views/{ => Health}/MetricCardView.swift (100%) rename PulseHealth/Views/{ => Health}/ReadinessCardView.swift (100%) rename PulseHealth/Views/{ => Health}/ToastView.swift (100%) rename PulseHealth/Views/{ => Health}/WeeklyChartView.swift (100%) create mode 100644 PulseHealth/Views/MainTabView.swift create mode 100644 PulseHealth/Views/Tasks/AddTaskView.swift create mode 100644 PulseHealth/Views/Tasks/TaskRowView.swift create mode 100644 PulseHealth/Views/Tasks/TasksView.swift diff --git a/PulseHealth/App.swift b/PulseHealth/App.swift index 3bdc6e3..4e81843 100644 --- a/PulseHealth/App.swift +++ b/PulseHealth/App.swift @@ -17,14 +17,17 @@ extension Color { } @main -struct PulseHealthApp: App { +struct PulseApp: App { @StateObject private var authManager = AuthManager() + var body: some Scene { WindowGroup { if authManager.isLoggedIn { - DashboardView().environmentObject(authManager) + MainTabView() + .environmentObject(authManager) } else { - LoginView().environmentObject(authManager) + LoginView() + .environmentObject(authManager) } } } @@ -34,25 +37,32 @@ class AuthManager: ObservableObject { @Published var isLoggedIn: Bool = false @Published var token: String = "" @Published var userName: String = "" - @Published var apiKey: String = "" + @Published var userId: Int = 0 + @Published var healthApiKey: String = "health-cosmo-2026" + init() { - token = UserDefaults.standard.string(forKey: "authToken") ?? "" + token = UserDefaults.standard.string(forKey: "pulseToken") ?? "" userName = UserDefaults.standard.string(forKey: "userName") ?? "" - apiKey = UserDefaults.standard.string(forKey: "apiKey") ?? "" + userId = UserDefaults.standard.integer(forKey: "userId") + healthApiKey = UserDefaults.standard.string(forKey: "healthApiKey") ?? "health-cosmo-2026" isLoggedIn = !token.isEmpty } - func login(token: String, name: String, apiKey: String) { - self.token = token; self.userName = name; self.apiKey = apiKey - UserDefaults.standard.set(token, forKey: "authToken") - UserDefaults.standard.set(name, forKey: "userName") - UserDefaults.standard.set(apiKey, forKey: "apiKey") + + func login(token: String, user: UserInfo) { + self.token = token + self.userName = user.name ?? user.email + self.userId = user.id + UserDefaults.standard.set(token, forKey: "pulseToken") + UserDefaults.standard.set(user.name ?? user.email, forKey: "userName") + UserDefaults.standard.set(user.id, forKey: "userId") isLoggedIn = true } + func logout() { - token = ""; userName = ""; apiKey = "" - UserDefaults.standard.removeObject(forKey: "authToken") + token = ""; userName = ""; userId = 0 + UserDefaults.standard.removeObject(forKey: "pulseToken") UserDefaults.standard.removeObject(forKey: "userName") - UserDefaults.standard.removeObject(forKey: "apiKey") + UserDefaults.standard.removeObject(forKey: "userId") isLoggedIn = false } } diff --git a/PulseHealth/Models/AuthModels.swift b/PulseHealth/Models/AuthModels.swift index 2b3d12c..68fa56b 100644 --- a/PulseHealth/Models/AuthModels.swift +++ b/PulseHealth/Models/AuthModels.swift @@ -1,5 +1,29 @@ import Foundation -struct LoginRequest: Codable { let email: String; let password: String } -struct LoginResponse: Codable { let token: String; let user: UserInfo } -struct UserInfo: Codable { let id: Int; let email: String; let name: String } -struct ProfileResponse: Codable { let user: UserInfo; let apiKey: String? } + +struct LoginRequest: Codable { + let email: String + let password: String +} + +struct RegisterRequest: Codable { + let email: String + let password: String + let name: String +} + +struct AuthResponse: Codable { + let token: String + let user: UserInfo +} + +struct UserInfo: Codable { + let id: Int + let email: String + let name: String? + let createdAt: String? + + enum CodingKeys: String, CodingKey { + case id, email, name + case createdAt = "created_at" + } +} diff --git a/PulseHealth/Models/FinanceModels.swift b/PulseHealth/Models/FinanceModels.swift new file mode 100644 index 0000000..ea2ca8f --- /dev/null +++ b/PulseHealth/Models/FinanceModels.swift @@ -0,0 +1,51 @@ +import Foundation + +struct FinanceTransaction: Codable, Identifiable { + let id: Int + var amount: Double + var categoryId: Int? + var description: String? + var type: String // "income" or "expense" + var date: String? + var createdAt: String? + + enum CodingKeys: String, CodingKey { + case id, amount, description, type, date + case categoryId = "category_id" + case createdAt = "created_at" + } +} + +struct FinanceCategory: Codable, Identifiable { + let id: Int + var name: String + var icon: String? + var color: String? + var type: String +} + +struct FinanceSummary: Codable { + var totalIncome: Double? + var totalExpenses: Double? + var balance: Double? + var month: String? + + enum CodingKeys: String, CodingKey { + case totalIncome = "total_income" + case totalExpenses = "total_expenses" + case balance, month + } +} + +struct CreateTransactionRequest: Codable { + var amount: Double + var categoryId: Int? + var description: String? + var type: String + var date: String? + + enum CodingKeys: String, CodingKey { + case amount, description, type, date + case categoryId = "category_id" + } +} diff --git a/PulseHealth/Models/HabitModels.swift b/PulseHealth/Models/HabitModels.swift new file mode 100644 index 0000000..b474632 --- /dev/null +++ b/PulseHealth/Models/HabitModels.swift @@ -0,0 +1,46 @@ +import Foundation + +enum HabitFrequency: String, Codable { + case daily, weekly, monthly + var displayName: String { + switch self { + case .daily: return "Ежедневно" + case .weekly: return "Еженедельно" + case .monthly: return "Ежемесячно" + } + } +} + +struct Habit: Codable, Identifiable { + let id: Int + var name: String + var description: String? + var icon: String? + var color: String? + var frequency: HabitFrequency + var reminderTime: String? + var targetDays: Int? + var currentStreak: Int? + var longestStreak: Int? + var completedToday: Bool? + var totalCompleted: Int? + + enum CodingKeys: String, CodingKey { + case id, name, description, icon, color, frequency + case reminderTime = "reminder_time" + case targetDays = "target_days" + case currentStreak = "current_streak" + case longestStreak = "longest_streak" + case completedToday = "completed_today" + case totalCompleted = "total_completed" + } +} + +struct HabitLogRequest: Codable { + var completedAt: String? + var note: String? + enum CodingKeys: String, CodingKey { + case completedAt = "completed_at" + case note + } +} diff --git a/PulseHealth/Models/TaskModels.swift b/PulseHealth/Models/TaskModels.swift new file mode 100644 index 0000000..af4a341 --- /dev/null +++ b/PulseHealth/Models/TaskModels.swift @@ -0,0 +1,51 @@ +import Foundation + +enum TaskPriority: String, Codable, CaseIterable { + case low, medium, high, urgent + var displayName: String { + switch self { + case .low: return "Низкий" + case .medium: return "Средний" + case .high: return "Высокий" + case .urgent: return "Срочный" + } + } + var color: String { + switch self { + case .low: return "8888aa" + case .medium: return "ffa502" + case .high: return "ff4757" + case .urgent: return "ff0000" + } + } +} + +struct PulseTask: Codable, Identifiable { + let id: Int + var title: String + var description: String? + var done: Bool + var priority: TaskPriority? + var dueDate: String? + var reminderTime: String? + var createdAt: String? + + enum CodingKeys: String, CodingKey { + case id, title, description, done, priority + case dueDate = "due_date" + case reminderTime = "reminder_time" + case createdAt = "created_at" + } +} + +struct CreateTaskRequest: Codable { + var title: String + var description: String? + var priority: TaskPriority? + var dueDate: String? + + enum CodingKeys: String, CodingKey { + case title, description, priority + case dueDate = "due_date" + } +} diff --git a/PulseHealth/Services/APIService.swift b/PulseHealth/Services/APIService.swift index 5872c99..0fbe648 100644 --- a/PulseHealth/Services/APIService.swift +++ b/PulseHealth/Services/APIService.swift @@ -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(_ 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 {} diff --git a/PulseHealth/Services/HealthAPIService.swift b/PulseHealth/Services/HealthAPIService.swift new file mode 100644 index 0000000..7b0bf3d --- /dev/null +++ b/PulseHealth/Services/HealthAPIService.swift @@ -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 данных") + } + } +} diff --git a/PulseHealth/Services/HealthKitService.swift b/PulseHealth/Services/HealthKitService.swift index 1368dbf..a1b7347 100644 --- a/PulseHealth/Services/HealthKitService.swift +++ b/PulseHealth/Services/HealthKitService.swift @@ -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 } diff --git a/PulseHealth/Views/Dashboard/DashboardView.swift b/PulseHealth/Views/Dashboard/DashboardView.swift new file mode 100644 index 0000000..3460665 --- /dev/null +++ b/PulseHealth/Views/Dashboard/DashboardView.swift @@ -0,0 +1,181 @@ +import SwiftUI + +struct DashboardView: View { + @EnvironmentObject var authManager: AuthManager + @State private var tasks: [PulseTask] = [] + @State private var habits: [Habit] = [] + @State private var readiness: ReadinessResponse? + @State private var summary: FinanceSummary? + @State private var isLoading = true + + var greeting: String { + let h = Calendar.current.component(.hour, from: Date()) + switch h { + case 5..<12: return "Доброе утро" + case 12..<17: return "Добрый день" + case 17..<22: return "Добрый вечер" + default: return "Доброй ночи" + } + } + + var pendingTasks: [PulseTask] { tasks.filter { !$0.done } } + var completedHabitsToday: Int { habits.filter { $0.completedToday == true }.count } + + var body: some View { + ZStack { + Color(hex: "0a0a1a").ignoresSafeArea() + ScrollView { + VStack(spacing: 20) { + // Header + HStack { + VStack(alignment: .leading, spacing: 4) { + Text(greeting + ", " + authManager.userName + "!") + .font(.title2.bold()).foregroundColor(.white) + Text(Date(), style: .date) + .font(.subheadline).foregroundColor(Color(hex: "8888aa")) + } + Spacer() + + // Logout + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + authManager.logout() + } label: { + ZStack { + Circle() + .fill(Color(hex: "1a1a3e")) + .frame(width: 42, height: 42) + Image(systemName: "rectangle.portrait.and.arrow.right") + .font(.system(size: 14, weight: .medium)) + .foregroundColor(Color(hex: "8888aa")) + } + } + } + .padding(.horizontal) + .padding(.top) + + if isLoading { + ProgressView().tint(Color(hex: "00d4aa")).padding(.top, 40) + } else { + // Readiness Score mini card + if let r = readiness { + ReadinessMiniCard(readiness: r) + } + + // Stats row + HStack(spacing: 12) { + StatCard(icon: "checkmark.circle.fill", value: "\(pendingTasks.count)", label: "Задач", color: "00d4aa") + StatCard(icon: "flame.fill", value: "\(completedHabitsToday)/\(habits.count)", label: "Привычек", color: "ffa502") + if let s = summary, let balance = s.balance { + StatCard(icon: "rublesign.circle.fill", value: "\(Int(balance))₽", label: "Баланс", color: "7c3aed") + } + } + .padding(.horizontal) + + // Today's tasks + if !pendingTasks.isEmpty { + VStack(alignment: .leading, spacing: 12) { + Text("Задачи на сегодня").font(.headline).foregroundColor(.white).padding(.horizontal) + ForEach(pendingTasks.prefix(3)) { task in + TaskRowView(task: task) { + await completeTask(task) + } + } + } + } + + // Habits progress + if !habits.isEmpty { + VStack(alignment: .leading, spacing: 12) { + Text("Привычки сегодня").font(.headline).foregroundColor(.white).padding(.horizontal) + ForEach(habits.prefix(4)) { habit in + HabitRowView(habit: habit) { + await logHabit(habit) + } + } + } + } + } + Spacer(minLength: 20) + } + } + .refreshable { await loadData() } + } + .task { await loadData() } + } + + func loadData() async { + isLoading = true + async let t = APIService.shared.getTodayTasks(token: authManager.token) + async let h = APIService.shared.getHabits(token: authManager.token) + async let r = HealthAPIService.shared.getReadiness(apiKey: authManager.healthApiKey) + async let s = APIService.shared.getFinanceSummary(token: authManager.token) + tasks = (try? await t) ?? [] + habits = (try? await h) ?? [] + readiness = try? await r + summary = try? await s + isLoading = false + } + + func completeTask(_ task: PulseTask) async { + try? await APIService.shared.completeTask(token: authManager.token, id: task.id) + await loadData() + } + + func logHabit(_ habit: Habit) async { + try? await APIService.shared.logHabit(token: authManager.token, id: habit.id) + await loadData() + } +} + +// MARK: - StatCard + +struct StatCard: View { + let icon: String + let value: String + let label: String + let color: String + + var body: some View { + VStack(spacing: 6) { + Image(systemName: icon).foregroundColor(Color(hex: color)).font(.title3) + Text(value).font(.headline.bold()).foregroundColor(.white) + Text(label).font(.caption).foregroundColor(Color(hex: "8888aa")) + } + .frame(maxWidth: .infinity) + .padding(12) + .background(RoundedRectangle(cornerRadius: 16).fill(Color.white.opacity(0.05))) + } +} + +// MARK: - ReadinessMiniCard + +struct ReadinessMiniCard: View { + let readiness: ReadinessResponse + + var statusColor: Color { + readiness.score >= 80 ? Color(hex: "00d4aa") : + readiness.score >= 60 ? Color(hex: "ffa502") : + Color(hex: "ff4757") + } + + var body: some View { + HStack(spacing: 16) { + ZStack { + Circle().stroke(Color.white.opacity(0.1), lineWidth: 6).frame(width: 60, height: 60) + Circle().trim(from: 0, to: CGFloat(readiness.score) / 100) + .stroke(statusColor, style: StrokeStyle(lineWidth: 6, lineCap: .round)) + .frame(width: 60, height: 60).rotationEffect(.degrees(-90)) + Text("\(readiness.score)").font(.headline.bold()).foregroundColor(statusColor) + } + VStack(alignment: .leading, spacing: 4) { + Text("Готовность").font(.subheadline).foregroundColor(Color(hex: "8888aa")) + Text(readiness.recommendation).font(.callout).foregroundColor(.white).lineLimit(2) + } + Spacer() + } + .padding(16) + .background(RoundedRectangle(cornerRadius: 16).fill(Color.white.opacity(0.05))) + .padding(.horizontal) + } +} diff --git a/PulseHealth/Views/Finance/AddTransactionView.swift b/PulseHealth/Views/Finance/AddTransactionView.swift new file mode 100644 index 0000000..c6cd78e --- /dev/null +++ b/PulseHealth/Views/Finance/AddTransactionView.swift @@ -0,0 +1,82 @@ +import SwiftUI + +struct AddTransactionView: View { + @Binding var isPresented: Bool + @EnvironmentObject var authManager: AuthManager + let categories: [FinanceCategory] + let onAdded: () async -> Void + + @State private var amount = "" + @State private var description = "" + @State private var type = "expense" + @State private var selectedCategoryId: Int? = nil + @State private var isLoading = false + + var filteredCategories: [FinanceCategory] { categories.filter { $0.type == type } } + + var body: some View { + NavigationView { + ZStack { + Color(hex: "0a0a1a").ignoresSafeArea() + VStack(spacing: 16) { + Picker("", selection: $type) { + Text("Расход").tag("expense") + Text("Доход").tag("income") + } + .pickerStyle(.segmented) + + TextField("Сумма", text: $amount) + .keyboardType(.decimalPad) + .padding().background(Color.white.opacity(0.08)).cornerRadius(12).foregroundColor(.white) + + TextField("Описание", text: $description) + .padding().background(Color.white.opacity(0.08)).cornerRadius(12).foregroundColor(.white) + + if !filteredCategories.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(filteredCategories) { cat in + Button(action: { selectedCategoryId = cat.id }) { + HStack(spacing: 4) { + Text(cat.icon ?? "").font(.caption) + Text(cat.name).font(.caption) + } + .padding(.horizontal, 12).padding(.vertical, 6) + .background(RoundedRectangle(cornerRadius: 20) + .fill(selectedCategoryId == cat.id ? Color(hex: "00d4aa").opacity(0.3) : Color.white.opacity(0.08))) + .foregroundColor(selectedCategoryId == cat.id ? Color(hex: "00d4aa") : .white) + } + } + }.padding(.horizontal) + } + } + Spacer() + }.padding() + } + .navigationTitle("Новая операция") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Отмена") { isPresented = false } } + ToolbarItem(placement: .confirmationAction) { + Button("Добавить") { + guard let a = Double(amount.replacingOccurrences(of: ",", with: ".")) else { return } + isLoading = true + Task { + let req = CreateTransactionRequest( + amount: a, + categoryId: selectedCategoryId, + description: description.isEmpty ? nil : description, + type: type + ) + try? await APIService.shared.createTransaction(token: authManager.token, request: req) + await onAdded() + await MainActor.run { isPresented = false } + } + } + .disabled(amount.isEmpty || isLoading) + } + } + .preferredColorScheme(.dark) + } + } +} diff --git a/PulseHealth/Views/Finance/FinanceView.swift b/PulseHealth/Views/Finance/FinanceView.swift new file mode 100644 index 0000000..900c15f --- /dev/null +++ b/PulseHealth/Views/Finance/FinanceView.swift @@ -0,0 +1,125 @@ +import SwiftUI + +struct FinanceView: View { + @EnvironmentObject var authManager: AuthManager + @State private var summary: FinanceSummary? + @State private var transactions: [FinanceTransaction] = [] + @State private var categories: [FinanceCategory] = [] + @State private var isLoading = true + @State private var showAddTransaction = false + + var body: some View { + ZStack { + Color(hex: "0a0a1a").ignoresSafeArea() + VStack(spacing: 0) { + HStack { + Text("Финансы").font(.title.bold()).foregroundColor(.white) + Spacer() + Button(action: { showAddTransaction = true }) { + Image(systemName: "plus.circle.fill").font(.title2).foregroundColor(Color(hex: "00d4aa")) + } + }.padding() + + if isLoading { + ProgressView().tint(Color(hex: "00d4aa")).padding(.top, 40) + Spacer() + } else { + ScrollView { + VStack(spacing: 16) { + // Summary card + if let s = summary { + FinanceSummaryCard(summary: s) + } + + // Recent transactions + if !transactions.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Text("Последние операции") + .font(.headline).foregroundColor(.white).padding(.horizontal) + ForEach(transactions.prefix(20)) { tx in + TransactionRowView(transaction: tx, categories: categories) + } + } + } + } + } + } + } + } + .sheet(isPresented: $showAddTransaction) { + AddTransactionView(isPresented: $showAddTransaction, categories: categories) { await loadData() } + } + .task { await loadData() } + .refreshable { await loadData() } + } + + func loadData() async { + isLoading = true + async let s = APIService.shared.getFinanceSummary(token: authManager.token) + async let t = APIService.shared.getTransactions(token: authManager.token) + async let c = APIService.shared.getFinanceCategories(token: authManager.token) + summary = try? await s + transactions = (try? await t) ?? [] + categories = (try? await c) ?? [] + isLoading = false + } +} + +// MARK: - FinanceSummaryCard + +struct FinanceSummaryCard: View { + let summary: FinanceSummary + + var body: some View { + VStack(spacing: 16) { + HStack(spacing: 20) { + VStack(spacing: 4) { + Text("Доходы").font(.caption).foregroundColor(Color(hex: "8888aa")) + Text("+\(Int(summary.totalIncome ?? 0))₽").font(.headline).foregroundColor(Color(hex: "00d4aa")) + } + Spacer() + VStack(spacing: 4) { + Text("Баланс").font(.subheadline).foregroundColor(Color(hex: "8888aa")) + Text("\(Int(summary.balance ?? 0))₽").font(.title2.bold()).foregroundColor(.white) + } + Spacer() + VStack(spacing: 4) { + Text("Расходы").font(.caption).foregroundColor(Color(hex: "8888aa")) + Text("-\(Int(summary.totalExpenses ?? 0))₽").font(.headline).foregroundColor(Color(hex: "ff4757")) + } + } + } + .padding(20) + .background(RoundedRectangle(cornerRadius: 20).fill(Color.white.opacity(0.05))) + .padding(.horizontal) + } +} + +// MARK: - TransactionRowView + +struct TransactionRowView: View { + let transaction: FinanceTransaction + let categories: [FinanceCategory] + + var category: FinanceCategory? { categories.first { $0.id == transaction.categoryId } } + var isIncome: Bool { transaction.type == "income" } + + var body: some View { + HStack { + Text(category?.icon ?? (isIncome ? "💰" : "💸")).font(.title2) + VStack(alignment: .leading, spacing: 2) { + Text(transaction.description ?? category?.name ?? "Операция") + .font(.callout).foregroundColor(.white) + Text(transaction.date ?? "").font(.caption).foregroundColor(Color(hex: "8888aa")) + } + Spacer() + Text("\(isIncome ? "+" : "-")\(Int(transaction.amount))₽") + .font(.callout.bold()) + .foregroundColor(isIncome ? Color(hex: "00d4aa") : Color(hex: "ff4757")) + } + .padding(12) + .background(RoundedRectangle(cornerRadius: 12).fill(Color.white.opacity(0.04))) + .padding(.horizontal) + .padding(.vertical, 2) + } +} diff --git a/PulseHealth/Views/Habits/HabitRowView.swift b/PulseHealth/Views/Habits/HabitRowView.swift new file mode 100644 index 0000000..a8a7bb3 --- /dev/null +++ b/PulseHealth/Views/Habits/HabitRowView.swift @@ -0,0 +1,45 @@ +import SwiftUI + +struct HabitRowView: View { + let habit: Habit + let onLog: () async -> Void + + var accentColor: Color { Color(hex: habit.color ?? "00d4aa") } + var isDone: Bool { habit.completedToday == true } + + var body: some View { + HStack(spacing: 14) { + // Icon + ZStack { + Circle().fill(accentColor.opacity(isDone ? 0.3 : 0.1)).frame(width: 44, height: 44) + Text(habit.icon ?? "🔥").font(.title3) + } + + VStack(alignment: .leading, spacing: 4) { + Text(habit.name).font(.callout.weight(.medium)).foregroundColor(.white) + HStack(spacing: 8) { + Text(habit.frequency.displayName).font(.caption).foregroundColor(Color(hex: "8888aa")) + if let streak = habit.currentStreak, streak > 0 { + Text("🔥 \(streak)").font(.caption).foregroundColor(Color(hex: "ffa502")) + } + } + } + + Spacer() + + Button(action: { guard !isDone else { return }; Task { await onLog() } }) { + Image(systemName: isDone ? "checkmark.circle.fill" : "circle") + .font(.title2) + .foregroundColor(isDone ? accentColor : Color(hex: "8888aa")) + } + } + .padding(14) + .background( + RoundedRectangle(cornerRadius: 16) + .fill(isDone ? accentColor.opacity(0.08) : Color.white.opacity(0.04)) + .overlay(RoundedRectangle(cornerRadius: 16).stroke(isDone ? accentColor.opacity(0.3) : Color.clear, lineWidth: 1)) + ) + .padding(.horizontal) + .padding(.vertical, 3) + } +} diff --git a/PulseHealth/Views/Habits/HabitsView.swift b/PulseHealth/Views/Habits/HabitsView.swift new file mode 100644 index 0000000..d28f6a9 --- /dev/null +++ b/PulseHealth/Views/Habits/HabitsView.swift @@ -0,0 +1,73 @@ +import SwiftUI + +struct HabitsView: View { + @EnvironmentObject var authManager: AuthManager + @State private var habits: [Habit] = [] + @State private var isLoading = true + + var completedCount: Int { habits.filter { $0.completedToday == true }.count } + + var body: some View { + ZStack { + Color(hex: "0a0a1a").ignoresSafeArea() + VStack(spacing: 0) { + HStack { + VStack(alignment: .leading) { + Text("Привычки").font(.title.bold()).foregroundColor(.white) + Text("\(completedCount)/\(habits.count) выполнено").font(.subheadline).foregroundColor(Color(hex: "8888aa")) + } + Spacer() + }.padding() + + // Progress bar + if !habits.isEmpty { + GeometryReader { geo in + ZStack(alignment: .leading) { + RoundedRectangle(cornerRadius: 4).fill(Color.white.opacity(0.1)) + RoundedRectangle(cornerRadius: 4).fill(Color(hex: "00d4aa")) + .frame(width: geo.size.width * CGFloat(completedCount) / CGFloat(max(habits.count, 1))) + } + } + .frame(height: 6) + .padding(.horizontal) + .padding(.bottom, 16) + } + + if isLoading { + ProgressView().tint(Color(hex: "00d4aa")).padding(.top, 40) + Spacer() + } else if habits.isEmpty { + VStack(spacing: 12) { + Text("🔥").font(.system(size: 50)) + Text("Нет привычек").foregroundColor(Color(hex: "8888aa")) + }.padding(.top, 60) + Spacer() + } else { + List { + ForEach(habits) { habit in + HabitRowView(habit: habit) { await logHabit(habit) } + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + } + } + } + .task { await loadHabits() } + .refreshable { await loadHabits() } + } + + func loadHabits() async { + isLoading = true + habits = (try? await APIService.shared.getHabits(token: authManager.token)) ?? [] + isLoading = false + } + + func logHabit(_ habit: Habit) async { + try? await APIService.shared.logHabit(token: authManager.token, id: habit.id) + await loadHabits() + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + } +} diff --git a/PulseHealth/Views/DashboardView.swift b/PulseHealth/Views/Health/HealthView.swift similarity index 84% rename from PulseHealth/Views/DashboardView.swift rename to PulseHealth/Views/Health/HealthView.swift index 0fac783..7d767f8 100644 --- a/PulseHealth/Views/DashboardView.swift +++ b/PulseHealth/Views/Health/HealthView.swift @@ -1,6 +1,6 @@ import SwiftUI -struct DashboardView: View { +struct HealthView: View { @EnvironmentObject var authManager: AuthManager @StateObject private var healthKit = HealthKitService() @@ -33,7 +33,6 @@ struct DashboardView: View { var body: some View { ZStack { - // Background Color(hex: "0a0a1a") .ignoresSafeArea() @@ -80,7 +79,7 @@ struct DashboardView: View { VStack(alignment: .leading, spacing: 4) { HStack { VStack(alignment: .leading, spacing: 4) { - Text("\(greeting), \(authManager.userName) 👋") + Text("Здоровье 🫀") .font(.title2.bold()) .foregroundColor(.white) @@ -112,22 +111,6 @@ struct DashboardView: View { } } .disabled(healthKit.isSyncing) - - // Logout - Button { - UIImpactFeedbackGenerator(style: .light).impactOccurred() - authManager.logout() - } label: { - ZStack { - Circle() - .fill(Color(hex: "1a1a3e")) - .frame(width: 42, height: 42) - - Image(systemName: "rectangle.portrait.and.arrow.right") - .font(.system(size: 14, weight: .medium)) - .foregroundColor(Color(hex: "8888aa")) - } - } } } .padding(.horizontal) @@ -152,13 +135,11 @@ struct DashboardView: View { private var metricsGrid: some View { LazyVGrid(columns: [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)], spacing: 12) { - // Sleep if let sleep = latest?.sleep { SleepCard(sleep: sleep) .frame(maxHeight: .infinity) } - // Heart Rate if let rhr = latest?.restingHeartRate { MetricCardView( icon: "heart.fill", @@ -171,7 +152,6 @@ struct DashboardView: View { .frame(maxHeight: .infinity) } - // HRV if let hrv = latest?.hrv { MetricCardView( icon: "waveform.path.ecg", @@ -184,7 +164,6 @@ struct DashboardView: View { .frame(maxHeight: .infinity) } - // Steps if let steps = latest?.steps { StepsCard(steps: steps.total ?? 0) .frame(maxHeight: .infinity) @@ -198,9 +177,11 @@ struct DashboardView: View { func loadData() async { isLoading = true - async let r = APIService.shared.getReadiness(token: authManager.token) - async let l = APIService.shared.getLatest(token: authManager.token) - async let h = APIService.shared.getHeatmap(token: authManager.token, days: 7) + let apiKey = authManager.healthApiKey + + async let r = HealthAPIService.shared.getReadiness(apiKey: apiKey) + async let l = HealthAPIService.shared.getLatest(apiKey: apiKey) + async let h = HealthAPIService.shared.getHeatmap(apiKey: apiKey, days: 7) readiness = try? await r latest = try? await l @@ -217,18 +198,17 @@ struct DashboardView: View { return } - guard !authManager.apiKey.isEmpty else { - showToastMessage("API ключ не найден. Войдите заново.", success: false) + guard !authManager.healthApiKey.isEmpty else { + showToastMessage("Health API ключ не найден", success: false) return } UIImpactFeedbackGenerator(style: .medium).impactOccurred() do { - try await healthKit.syncToServer(apiKey: authManager.apiKey) + try await healthKit.syncToServer(apiKey: authManager.healthApiKey) UINotificationFeedbackGenerator().notificationOccurred(.success) showToastMessage("Данные синхронизированы ✓", success: true) - // Reload dashboard after sync await loadData() } catch { UINotificationFeedbackGenerator().notificationOccurred(.error) diff --git a/PulseHealth/Views/MetricCardView.swift b/PulseHealth/Views/Health/MetricCardView.swift similarity index 100% rename from PulseHealth/Views/MetricCardView.swift rename to PulseHealth/Views/Health/MetricCardView.swift diff --git a/PulseHealth/Views/ReadinessCardView.swift b/PulseHealth/Views/Health/ReadinessCardView.swift similarity index 100% rename from PulseHealth/Views/ReadinessCardView.swift rename to PulseHealth/Views/Health/ReadinessCardView.swift diff --git a/PulseHealth/Views/ToastView.swift b/PulseHealth/Views/Health/ToastView.swift similarity index 100% rename from PulseHealth/Views/ToastView.swift rename to PulseHealth/Views/Health/ToastView.swift diff --git a/PulseHealth/Views/WeeklyChartView.swift b/PulseHealth/Views/Health/WeeklyChartView.swift similarity index 100% rename from PulseHealth/Views/WeeklyChartView.swift rename to PulseHealth/Views/Health/WeeklyChartView.swift diff --git a/PulseHealth/Views/LoginView.swift b/PulseHealth/Views/LoginView.swift index 8262dee..ace8631 100644 --- a/PulseHealth/Views/LoginView.swift +++ b/PulseHealth/Views/LoginView.swift @@ -9,9 +9,6 @@ struct LoginView: View { @State private var errorMessage = "" @State private var showPassword = false @State private var isRegistering = false - @State private var forgotEmail = "" - @State private var showForgotSheet = false - @State private var forgotSent = false var body: some View { ZStack { @@ -20,9 +17,9 @@ struct LoginView: View { VStack(spacing: 32) { VStack(spacing: 8) { - Text("🫀").font(.system(size: 60)) - Text("Pulse Health").font(.largeTitle.bold()).foregroundColor(.white) - Text(isRegistering ? "Создать аккаунт" : "Персональный дашборд здоровья") + Text("⚡").font(.system(size: 60)) + Text("Pulse").font(.largeTitle.bold()).foregroundColor(.white) + Text(isRegistering ? "Создать аккаунт" : "Управление жизнью") .font(.subheadline).foregroundColor(.white.opacity(0.6)) }.padding(.top, 60) @@ -86,15 +83,6 @@ struct LoginView: View { .cornerRadius(12) .disabled(isLoading || email.isEmpty || password.isEmpty) - // Forgot password (only on login) - if !isRegistering { - Button(action: { showForgotSheet = true }) { - Text("Забыли пароль?") - .font(.footnote) - .foregroundColor(Color(hex: "00d4aa")) - } - } - // Toggle login/register HStack { Text(isRegistering ? "Уже есть аккаунт?" : "Нет аккаунта?") @@ -114,9 +102,6 @@ struct LoginView: View { Spacer() } - .sheet(isPresented: $showForgotSheet) { - ForgotPasswordView(isPresented: $showForgotSheet) - } } } @@ -124,10 +109,12 @@ struct LoginView: View { isLoading = true; errorMessage = "" Task { do { - let response = try await APIService.shared.login(email: email.trimmingCharacters(in: .whitespaces), password: password) - let profile = try? await APIService.shared.getProfile(token: response.token) + let response = try await APIService.shared.login( + email: email.trimmingCharacters(in: .whitespaces), + password: password + ) await MainActor.run { - authManager.login(token: response.token, name: response.user.name, apiKey: profile?.apiKey ?? "") + authManager.login(token: response.token, user: response.user) } } catch let error as APIError { await MainActor.run { errorMessage = error.errorDescription ?? "Ошибка"; isLoading = false } @@ -141,10 +128,13 @@ struct LoginView: View { isLoading = true; errorMessage = "" Task { do { - let response = try await APIService.shared.register(email: email.trimmingCharacters(in: .whitespaces), password: password, name: name) - let profile = try? await APIService.shared.getProfile(token: response.token) + let response = try await APIService.shared.register( + email: email.trimmingCharacters(in: .whitespaces), + password: password, + name: name + ) await MainActor.run { - authManager.login(token: response.token, name: response.user.name, apiKey: profile?.apiKey ?? "") + authManager.login(token: response.token, user: response.user) } } catch let error as APIError { await MainActor.run { errorMessage = error.errorDescription ?? "Ошибка"; isLoading = false } @@ -154,49 +144,3 @@ struct LoginView: View { } } } - -struct ForgotPasswordView: View { - @Binding var isPresented: Bool - @State private var email = "" - @State private var isSent = false - @State private var isLoading = false - - var body: some View { - ZStack { - Color(hex: "0a0a1a").ignoresSafeArea() - VStack(spacing: 24) { - Text("Сброс пароля").font(.title2.bold()).foregroundColor(.white) - if isSent { - VStack(spacing: 12) { - Text("✅").font(.system(size: 50)) - Text("Письмо отправлено!\nПроверьте \(email)") - .foregroundColor(.white).multilineTextAlignment(.center) - } - Button("Закрыть") { isPresented = false } - .padding().foregroundColor(Color(hex: "00d4aa")) - } else { - Text("Введите email и мы отправим ссылку для сброса пароля") - .foregroundColor(.white.opacity(0.6)).multilineTextAlignment(.center) - TextField("Email", text: $email) - .keyboardType(.emailAddress).autocapitalization(.none) - .padding().background(Color.white.opacity(0.1)).cornerRadius(12).foregroundColor(.white) - Button(action: send) { - if isLoading { ProgressView().tint(.black) } - else { Text("Отправить").font(.headline).foregroundColor(.black) } - } - .frame(maxWidth: .infinity).padding() - .background(Color(hex: "00d4aa")).cornerRadius(12).disabled(email.isEmpty || isLoading) - Button("Отмена") { isPresented = false }.foregroundColor(.white.opacity(0.5)) - } - }.padding(32) - } - } - - func send() { - isLoading = true - Task { - try? await APIService.shared.forgotPassword(email: email) - await MainActor.run { isSent = true; isLoading = false } - } - } -} diff --git a/PulseHealth/Views/MainTabView.swift b/PulseHealth/Views/MainTabView.swift new file mode 100644 index 0000000..1adc03e --- /dev/null +++ b/PulseHealth/Views/MainTabView.swift @@ -0,0 +1,26 @@ +import SwiftUI + +struct MainTabView: View { + @EnvironmentObject var authManager: AuthManager + + var body: some View { + TabView { + DashboardView() + .tabItem { Label("Главная", systemImage: "house.fill") } + + TasksView() + .tabItem { Label("Задачи", systemImage: "checkmark.circle.fill") } + + HabitsView() + .tabItem { Label("Привычки", systemImage: "flame.fill") } + + HealthView() + .tabItem { Label("Здоровье", systemImage: "heart.fill") } + + FinanceView() + .tabItem { Label("Финансы", systemImage: "rublesign.circle.fill") } + } + .accentColor(Color(hex: "00d4aa")) + .preferredColorScheme(.dark) + } +} diff --git a/PulseHealth/Views/Tasks/AddTaskView.swift b/PulseHealth/Views/Tasks/AddTaskView.swift new file mode 100644 index 0000000..7792080 --- /dev/null +++ b/PulseHealth/Views/Tasks/AddTaskView.swift @@ -0,0 +1,55 @@ +import SwiftUI + +struct AddTaskView: View { + @Binding var isPresented: Bool + @EnvironmentObject var authManager: AuthManager + let onAdded: () async -> Void + + @State private var title = "" + @State private var description = "" + @State private var priority: TaskPriority = .medium + @State private var isLoading = false + + var body: some View { + NavigationView { + ZStack { + Color(hex: "0a0a1a").ignoresSafeArea() + VStack(spacing: 20) { + TextField("Название задачи", text: $title) + .padding().background(Color.white.opacity(0.08)).cornerRadius(12).foregroundColor(.white) + TextField("Описание (необязательно)", text: $description) + .padding().background(Color.white.opacity(0.08)).cornerRadius(12).foregroundColor(.white) + Picker("Приоритет", selection: $priority) { + ForEach(TaskPriority.allCases, id: \.self) { p in Text(p.displayName).tag(p) } + } + .pickerStyle(.segmented) + Spacer() + }.padding() + } + .navigationTitle("Новая задача") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Отмена") { isPresented = false } + } + ToolbarItem(placement: .confirmationAction) { + Button("Добавить") { + isLoading = true + Task { + let req = CreateTaskRequest( + title: title, + description: description.isEmpty ? nil : description, + priority: priority + ) + try? await APIService.shared.createTask(token: authManager.token, request: req) + await onAdded() + await MainActor.run { isPresented = false } + } + } + .disabled(title.isEmpty || isLoading) + } + } + .preferredColorScheme(.dark) + } + } +} diff --git a/PulseHealth/Views/Tasks/TaskRowView.swift b/PulseHealth/Views/Tasks/TaskRowView.swift new file mode 100644 index 0000000..22b9c27 --- /dev/null +++ b/PulseHealth/Views/Tasks/TaskRowView.swift @@ -0,0 +1,45 @@ +import SwiftUI + +struct TaskRowView: View { + let task: PulseTask + let onComplete: () async -> Void + + var priorityColor: Color { + switch task.priority { + case .urgent: return Color(hex: "ff0000") + case .high: return Color(hex: "ff4757") + case .medium: return Color(hex: "ffa502") + default: return Color(hex: "8888aa") + } + } + + var body: some View { + HStack(spacing: 12) { + Button(action: { Task { await onComplete() } }) { + Image(systemName: task.done ? "checkmark.circle.fill" : "circle") + .font(.title3) + .foregroundColor(task.done ? Color(hex: "00d4aa") : Color(hex: "8888aa")) + } + VStack(alignment: .leading, spacing: 4) { + Text(task.title) + .foregroundColor(task.done ? Color(hex: "8888aa") : .white) + .strikethrough(task.done) + .font(.callout) + if let desc = task.description, !desc.isEmpty { + Text(desc).font(.caption).foregroundColor(Color(hex: "8888aa")).lineLimit(1) + } + if let due = task.dueDate { + Text(due).font(.caption2).foregroundColor(Color(hex: "ffa502")) + } + } + Spacer() + if let priority = task.priority, priority != .low { + Circle().fill(priorityColor).frame(width: 8, height: 8) + } + } + .padding(12) + .background(RoundedRectangle(cornerRadius: 12).fill(Color.white.opacity(0.05))) + .padding(.horizontal) + .padding(.vertical, 2) + } +} diff --git a/PulseHealth/Views/Tasks/TasksView.swift b/PulseHealth/Views/Tasks/TasksView.swift new file mode 100644 index 0000000..cd8a774 --- /dev/null +++ b/PulseHealth/Views/Tasks/TasksView.swift @@ -0,0 +1,95 @@ +import SwiftUI + +struct TasksView: View { + @EnvironmentObject var authManager: AuthManager + @State private var tasks: [PulseTask] = [] + @State private var isLoading = true + @State private var showAddTask = false + @State private var filter: TaskFilter = .pending + + enum TaskFilter: String, CaseIterable { + case pending = "Активные" + case completed = "Выполненные" + case all = "Все" + } + + var filteredTasks: [PulseTask] { + switch filter { + case .pending: return tasks.filter { !$0.done } + case .completed: return tasks.filter { $0.done } + case .all: return tasks + } + } + + var body: some View { + ZStack { + Color(hex: "0a0a1a").ignoresSafeArea() + VStack(spacing: 0) { + // Header + HStack { + Text("Задачи").font(.title.bold()).foregroundColor(.white) + Spacer() + Button(action: { showAddTask = true }) { + Image(systemName: "plus.circle.fill").font(.title2).foregroundColor(Color(hex: "00d4aa")) + } + }.padding() + + // Filter + Picker("", selection: $filter) { + ForEach(TaskFilter.allCases, id: \.self) { f in Text(f.rawValue).tag(f) } + } + .pickerStyle(.segmented) + .padding(.horizontal) + .padding(.bottom, 8) + + if isLoading { + ProgressView().tint(Color(hex: "00d4aa")).padding(.top, 40) + Spacer() + } else if filteredTasks.isEmpty { + VStack(spacing: 12) { + Text("✅").font(.system(size: 50)) + Text(filter == .pending ? "Нет активных задач" : "Нет задач") + .foregroundColor(Color(hex: "8888aa")) + }.padding(.top, 60) + Spacer() + } else { + List { + ForEach(filteredTasks) { task in + TaskRowView(task: task) { await completeTask(task) } + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } + .onDelete { indices in + let tasksToDelete = indices.map { filteredTasks[$0] } + Task { + for task in tasksToDelete { + try? await APIService.shared.deleteTask(token: authManager.token, id: task.id) + } + await loadTasks() + } + } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + } + } + } + .sheet(isPresented: $showAddTask) { + AddTaskView(isPresented: $showAddTask) { await loadTasks() } + } + .task { await loadTasks() } + .refreshable { await loadTasks() } + } + + func loadTasks() async { + isLoading = true + tasks = (try? await APIService.shared.getTasks(token: authManager.token)) ?? [] + isLoading = false + } + + func completeTask(_ task: PulseTask) async { + try? await APIService.shared.completeTask(token: authManager.token, id: task.id) + await loadTasks() + UIImpactFeedbackGenerator(style: .light).impactOccurred() + } +}