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

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

View File

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

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