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:
Cosmo
2026-03-25 11:49:52 +00:00
parent cf0e535639
commit c015824b36
23 changed files with 1090 additions and 202 deletions

View File

@@ -17,14 +17,17 @@ extension Color {
} }
@main @main
struct PulseHealthApp: App { struct PulseApp: App {
@StateObject private var authManager = AuthManager() @StateObject private var authManager = AuthManager()
var body: some Scene { var body: some Scene {
WindowGroup { WindowGroup {
if authManager.isLoggedIn { if authManager.isLoggedIn {
DashboardView().environmentObject(authManager) MainTabView()
.environmentObject(authManager)
} else { } else {
LoginView().environmentObject(authManager) LoginView()
.environmentObject(authManager)
} }
} }
} }
@@ -34,25 +37,32 @@ class AuthManager: ObservableObject {
@Published var isLoggedIn: Bool = false @Published var isLoggedIn: Bool = false
@Published var token: String = "" @Published var token: String = ""
@Published var userName: String = "" @Published var userName: String = ""
@Published var apiKey: String = "" @Published var userId: Int = 0
@Published var healthApiKey: String = "health-cosmo-2026"
init() { init() {
token = UserDefaults.standard.string(forKey: "authToken") ?? "" token = UserDefaults.standard.string(forKey: "pulseToken") ?? ""
userName = UserDefaults.standard.string(forKey: "userName") ?? "" 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 isLoggedIn = !token.isEmpty
} }
func login(token: String, name: String, apiKey: String) {
self.token = token; self.userName = name; self.apiKey = apiKey func login(token: String, user: UserInfo) {
UserDefaults.standard.set(token, forKey: "authToken") self.token = token
UserDefaults.standard.set(name, forKey: "userName") self.userName = user.name ?? user.email
UserDefaults.standard.set(apiKey, forKey: "apiKey") 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 isLoggedIn = true
} }
func logout() { func logout() {
token = ""; userName = ""; apiKey = "" token = ""; userName = ""; userId = 0
UserDefaults.standard.removeObject(forKey: "authToken") UserDefaults.standard.removeObject(forKey: "pulseToken")
UserDefaults.standard.removeObject(forKey: "userName") UserDefaults.standard.removeObject(forKey: "userName")
UserDefaults.standard.removeObject(forKey: "apiKey") UserDefaults.standard.removeObject(forKey: "userId")
isLoggedIn = false isLoggedIn = false
} }
} }

View File

@@ -1,5 +1,29 @@
import Foundation import Foundation
struct LoginRequest: Codable { let email: String; let password: String }
struct LoginResponse: Codable { let token: String; let user: UserInfo } struct LoginRequest: Codable {
struct UserInfo: Codable { let id: Int; let email: String; let name: String } let email: String
struct ProfileResponse: Codable { let user: UserInfo; let apiKey: 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"
}
}

View File

@@ -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"
}
}

View File

@@ -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
}
}

View File

@@ -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"
}
}

View File

@@ -9,115 +9,110 @@ enum APIError: Error, LocalizedError {
var errorDescription: String? { var errorDescription: String? {
switch self { switch self {
case .unauthorized: return "Неверный email или пароль" case .unauthorized: return "Неверный email или пароль"
case .networkError(let msg): return "Ошибка сети: \(msg)" case .networkError(let m): return "Ошибка сети: \(m)"
case .decodingError(let msg): return "Ошибка данных: \(msg)" case .decodingError(let m): return "Ошибка данных: \(m)"
case .serverError(let code, let msg): return "Ошибка сервера \(code): \(msg)" case .serverError(let c, let m): return "Ошибка \(c): \(m)"
} }
} }
} }
class APIService { class APIService {
static let shared = 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 { private func makeRequest(_ path: String, method: String = "GET", token: String? = nil, body: Data? = nil) -> URLRequest {
var req = URLRequest(url: url) var req = URLRequest(url: URL(string: "\(baseURL)\(path)")!)
req.httpMethod = method req.httpMethod = method
req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.timeoutInterval = 15 req.timeoutInterval = 15
if let token = token { if let t = token { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
req.httpBody = body req.httpBody = body
return req return req
} }
func login(email: String, password: String) async throws -> LoginResponse { private func fetch<T: Decodable>(_ path: String, method: String = "GET", token: String? = nil, body: Data? = nil) async throws -> T {
let url = URL(string: "\(baseURL)/api/auth/login")! 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 body = try JSONEncoder().encode(LoginRequest(email: email, password: password))
let req = makeRequest(url: url, method: "POST", body: body) return try await fetch("/auth/login", 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)
}
} }
func register(email: String, password: String, name: String) async throws -> LoginResponse { func register(email: String, password: String, name: String) async throws -> AuthResponse {
let url = URL(string: "\(baseURL)/api/auth/register")! let body = try JSONEncoder().encode(RegisterRequest(email: email, password: password, name: name))
let body = try JSONEncoder().encode(["email": email, "password": password, "name": name]) return try await fetch("/auth/register", method: "POST", body: body)
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 forgotPassword(email: String) async throws { func me(token: String) async throws -> UserInfo {
let url = URL(string: "\(baseURL)/api/auth/forgot-password")! return try await fetch("/auth/me", token: token)
let body = try JSONEncoder().encode(["email": email])
let req = makeRequest(url: url, method: "POST", body: body)
_ = try await URLSession.shared.data(for: req)
} }
func getProfile(token: String) async throws -> ProfileResponse { // MARK: - Tasks
let url = URL(string: "\(baseURL)/api/profile")!
let req = makeRequest(url: url, token: token) func getTasks(token: String) async throws -> [PulseTask] {
let (data, _) = try await URLSession.shared.data(for: req) return try await fetch("/tasks", token: token)
return try JSONDecoder().decode(ProfileResponse.self, from: data)
} }
func getReadiness(token: String) async throws -> ReadinessResponse { func getTodayTasks(token: String) async throws -> [PulseTask] {
let url = URL(string: "\(baseURL)/api/health/readiness")! return try await fetch("/tasks/today", token: token)
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 getLatest(token: String) async throws -> LatestHealthResponse { @discardableResult
let url = URL(string: "\(baseURL)/api/health/latest")! func createTask(token: String, request: CreateTaskRequest) async throws -> PulseTask {
let req = makeRequest(url: url, token: token) let body = try JSONEncoder().encode(request)
let (data, response) = try await URLSession.shared.data(for: req) return try await fetch("/tasks", method: "POST", token: token, body: body)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw APIError.networkError("Latest недоступен")
}
return try JSONDecoder().decode(LatestHealthResponse.self, from: data)
} }
func getHeatmap(token: String, days: Int = 7) async throws -> [HeatmapEntry] { func completeTask(token: String, id: Int) async throws {
let url = URL(string: "\(baseURL)/api/health/heatmap?days=\(days)")! let _: EmptyResponse = try await fetch("/tasks/\(id)/complete", method: "POST", token: token)
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 { func deleteTask(token: String, id: Int) async throws {
throw APIError.networkError("Heatmap недоступен") let _: EmptyResponse = try await fetch("/tasks/\(id)", method: "DELETE", token: token)
} }
// Try array first, then wrapped response
if let entries = try? JSONDecoder().decode([HeatmapEntry].self, from: data) { // MARK: - Habits
return entries
} func getHabits(token: String) async throws -> [Habit] {
let wrapped = try JSONDecoder().decode(HeatmapResponse.self, from: data) return try await fetch("/habits", token: token)
return wrapped.data }
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 {}

View 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 данных")
}
}
}

View File

@@ -140,7 +140,7 @@ class HealthKitService: ObservableObject {
let jsonData = try JSONSerialization.data(withJSONObject: payload) 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 { guard let url = URL(string: urlStr) else {
throw HealthKitError.invalidURL throw HealthKitError.invalidURL
} }

View File

@@ -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)
}
}

View File

@@ -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)
}
}
}

View File

@@ -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)
}
}

View File

@@ -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)
}
}

View File

@@ -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()
}
}

View File

@@ -1,6 +1,6 @@
import SwiftUI import SwiftUI
struct DashboardView: View { struct HealthView: View {
@EnvironmentObject var authManager: AuthManager @EnvironmentObject var authManager: AuthManager
@StateObject private var healthKit = HealthKitService() @StateObject private var healthKit = HealthKitService()
@@ -33,7 +33,6 @@ struct DashboardView: View {
var body: some View { var body: some View {
ZStack { ZStack {
// Background
Color(hex: "0a0a1a") Color(hex: "0a0a1a")
.ignoresSafeArea() .ignoresSafeArea()
@@ -80,7 +79,7 @@ struct DashboardView: View {
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
HStack { HStack {
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
Text("\(greeting), \(authManager.userName) 👋") Text("Здоровье 🫀")
.font(.title2.bold()) .font(.title2.bold())
.foregroundColor(.white) .foregroundColor(.white)
@@ -112,22 +111,6 @@ struct DashboardView: View {
} }
} }
.disabled(healthKit.isSyncing) .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) .padding(.horizontal)
@@ -152,13 +135,11 @@ struct DashboardView: View {
private var metricsGrid: some View { private var metricsGrid: some View {
LazyVGrid(columns: [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)], spacing: 12) { LazyVGrid(columns: [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)], spacing: 12) {
// Sleep
if let sleep = latest?.sleep { if let sleep = latest?.sleep {
SleepCard(sleep: sleep) SleepCard(sleep: sleep)
.frame(maxHeight: .infinity) .frame(maxHeight: .infinity)
} }
// Heart Rate
if let rhr = latest?.restingHeartRate { if let rhr = latest?.restingHeartRate {
MetricCardView( MetricCardView(
icon: "heart.fill", icon: "heart.fill",
@@ -171,7 +152,6 @@ struct DashboardView: View {
.frame(maxHeight: .infinity) .frame(maxHeight: .infinity)
} }
// HRV
if let hrv = latest?.hrv { if let hrv = latest?.hrv {
MetricCardView( MetricCardView(
icon: "waveform.path.ecg", icon: "waveform.path.ecg",
@@ -184,7 +164,6 @@ struct DashboardView: View {
.frame(maxHeight: .infinity) .frame(maxHeight: .infinity)
} }
// Steps
if let steps = latest?.steps { if let steps = latest?.steps {
StepsCard(steps: steps.total ?? 0) StepsCard(steps: steps.total ?? 0)
.frame(maxHeight: .infinity) .frame(maxHeight: .infinity)
@@ -198,9 +177,11 @@ struct DashboardView: View {
func loadData() async { func loadData() async {
isLoading = true isLoading = true
async let r = APIService.shared.getReadiness(token: authManager.token) let apiKey = authManager.healthApiKey
async let l = APIService.shared.getLatest(token: authManager.token)
async let h = APIService.shared.getHeatmap(token: authManager.token, days: 7) 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 readiness = try? await r
latest = try? await l latest = try? await l
@@ -217,18 +198,17 @@ struct DashboardView: View {
return return
} }
guard !authManager.apiKey.isEmpty else { guard !authManager.healthApiKey.isEmpty else {
showToastMessage("API ключ не найден. Войдите заново.", success: false) showToastMessage("Health API ключ не найден", success: false)
return return
} }
UIImpactFeedbackGenerator(style: .medium).impactOccurred() UIImpactFeedbackGenerator(style: .medium).impactOccurred()
do { do {
try await healthKit.syncToServer(apiKey: authManager.apiKey) try await healthKit.syncToServer(apiKey: authManager.healthApiKey)
UINotificationFeedbackGenerator().notificationOccurred(.success) UINotificationFeedbackGenerator().notificationOccurred(.success)
showToastMessage("Данные синхронизированы ✓", success: true) showToastMessage("Данные синхронизированы ✓", success: true)
// Reload dashboard after sync
await loadData() await loadData()
} catch { } catch {
UINotificationFeedbackGenerator().notificationOccurred(.error) UINotificationFeedbackGenerator().notificationOccurred(.error)

View File

@@ -9,9 +9,6 @@ struct LoginView: View {
@State private var errorMessage = "" @State private var errorMessage = ""
@State private var showPassword = false @State private var showPassword = false
@State private var isRegistering = false @State private var isRegistering = false
@State private var forgotEmail = ""
@State private var showForgotSheet = false
@State private var forgotSent = false
var body: some View { var body: some View {
ZStack { ZStack {
@@ -20,9 +17,9 @@ struct LoginView: View {
VStack(spacing: 32) { VStack(spacing: 32) {
VStack(spacing: 8) { VStack(spacing: 8) {
Text("🫀").font(.system(size: 60)) Text("").font(.system(size: 60))
Text("Pulse Health").font(.largeTitle.bold()).foregroundColor(.white) Text("Pulse").font(.largeTitle.bold()).foregroundColor(.white)
Text(isRegistering ? "Создать аккаунт" : "Персональный дашборд здоровья") Text(isRegistering ? "Создать аккаунт" : "Управление жизнью")
.font(.subheadline).foregroundColor(.white.opacity(0.6)) .font(.subheadline).foregroundColor(.white.opacity(0.6))
}.padding(.top, 60) }.padding(.top, 60)
@@ -86,15 +83,6 @@ struct LoginView: View {
.cornerRadius(12) .cornerRadius(12)
.disabled(isLoading || email.isEmpty || password.isEmpty) .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 // Toggle login/register
HStack { HStack {
Text(isRegistering ? "Уже есть аккаунт?" : "Нет аккаунта?") Text(isRegistering ? "Уже есть аккаунт?" : "Нет аккаунта?")
@@ -114,9 +102,6 @@ struct LoginView: View {
Spacer() Spacer()
} }
.sheet(isPresented: $showForgotSheet) {
ForgotPasswordView(isPresented: $showForgotSheet)
}
} }
} }
@@ -124,10 +109,12 @@ struct LoginView: View {
isLoading = true; errorMessage = "" isLoading = true; errorMessage = ""
Task { Task {
do { do {
let response = try await APIService.shared.login(email: email.trimmingCharacters(in: .whitespaces), password: password) let response = try await APIService.shared.login(
let profile = try? await APIService.shared.getProfile(token: response.token) email: email.trimmingCharacters(in: .whitespaces),
password: password
)
await MainActor.run { 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 { } catch let error as APIError {
await MainActor.run { errorMessage = error.errorDescription ?? "Ошибка"; isLoading = false } await MainActor.run { errorMessage = error.errorDescription ?? "Ошибка"; isLoading = false }
@@ -141,10 +128,13 @@ struct LoginView: View {
isLoading = true; errorMessage = "" isLoading = true; errorMessage = ""
Task { Task {
do { do {
let response = try await APIService.shared.register(email: email.trimmingCharacters(in: .whitespaces), password: password, name: name) let response = try await APIService.shared.register(
let profile = try? await APIService.shared.getProfile(token: response.token) email: email.trimmingCharacters(in: .whitespaces),
password: password,
name: name
)
await MainActor.run { 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 { } catch let error as APIError {
await MainActor.run { errorMessage = error.errorDescription ?? "Ошибка"; isLoading = false } 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 }
}
}
}

View File

@@ -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)
}
}

View File

@@ -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)
}
}
}

View File

@@ -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)
}
}

View File

@@ -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()
}
}