feat: major app overhaul — API fixes, glassmorphism UI, health dashboard, notifications

API Integration:
- Fix logHabit: send "date" instead of "completed_at"
- Fix FinanceCategory: "icon" → "emoji" to match API
- Fix task priorities: remove level 4, keep 1-3 matching API
- Fix habit frequencies: map monthly/interval → "custom" for API
- Add token refresh (401 → auto retry with new token)
- Add proper error handling (remove try? in save functions, show errors in UI)
- Add date field to savings transactions
- Add MonthlyPaymentDetail and OverduePayment models
- Fix habit completedToday: compute on client from logs (API doesn't return it)
- Filter habits by day of week on client (daily/weekly/monthly/interval)

Design System (glassmorphism):
- New DesignSystem.swift: Theme colors, GlassCard modifier, GlowIcon, GlowStatCard
- Custom tab bar with per-tab glow colors (VStack layout, not ZStack overlay)
- Deep dark background #06060f across all views
- Glass cards with gradient fill + stroke throughout app
- App icon: glassmorphism style with teal glow

Health Dashboard:
- Compact ReadinessBanner with recommendation text
- 8 metric tiles: sleep, HR, HRV, steps, SpO2, respiratory rate, energy, distance
- Each tile with status indicator (good/ok/bad) and hint text
- Heart rate card (min/avg/max)
- Weekly trends card (averages)
- Recovery score (weighted: 40% sleep, 35% HRV, 25% RHR)
- Tips card with actionable recommendations
- Sleep detail view with hypnogram (step chart of phases)
- Sleep segments timeline from HealthKit (deep/rem/core/awake with exact times)
- Line chart replacing bar chart for weekly data
- Collect respiratory_rate and sleep phases with timestamps from HealthKit
- Background sync every ~30min via BGProcessingTask

Notifications:
- NotificationService for local push notifications
- Morning/evening reminders with native DatePicker (wheel)
- Payment reminders: 5 days, 1 day, and day-of for recurring savings
- Notification settings in Settings tab

UI Fixes:
- Fix color picker overflow: HStack → LazyVGrid 5 columns
- Fix sheet headers: shorter text, proper padding
- Fix task/habit toggle: separate tap zones (checkbox vs edit)
- Fix deprecated onChange syntax for iOS 17+
- Savings overview: real monthly payments and detailed overdues from API
- Settings: timezone as Menu picker, removed Telegram/server notifications sections
- All sheets use .presentationDetents([.large])

Config:
- project.yml: real DEVELOPMENT_TEAM, HealthKit + BackgroundModes capabilities
- Info.plist: BGTaskScheduler + UIBackgroundModes
- Assets.xcassets with AppIcon
- CLAUDE.md project documentation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-05 23:15:36 +03:00
parent 1146965bcb
commit 28fca1de89
38 changed files with 3608 additions and 1031 deletions

View File

@@ -23,6 +23,7 @@ enum APIError: Error, LocalizedError {
class APIService {
static let shared = APIService()
let baseURL = "https://api.digital-home.site"
weak var authManager: AuthManager?
private func makeRequest(_ path: String, method: String = "GET", token: String? = nil, body: Data? = nil) -> URLRequest {
var req = URLRequest(url: URL(string: "\(baseURL)\(path)")!)
@@ -38,6 +39,27 @@ class APIService {
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, let auth = authManager, !auth.refreshToken.isEmpty, !path.contains("/auth/refresh") {
// Try to refresh the token
do {
let refreshResp = try await refreshToken(refreshToken: auth.refreshToken)
let newToken = refreshResp.authToken
guard !newToken.isEmpty else { throw APIError.unauthorized }
await MainActor.run { auth.updateTokens(accessToken: newToken, refreshToken: refreshResp.refreshToken) }
// Retry original request with new token
let retryReq = makeRequest(path, method: method, token: newToken, body: body)
let (retryData, retryResp) = try await URLSession.shared.data(for: retryReq)
guard let retryHttp = retryResp as? HTTPURLResponse else { throw APIError.networkError("Нет ответа") }
if retryHttp.statusCode == 401 { throw APIError.unauthorized }
if retryHttp.statusCode >= 400 {
let msg = String(data: retryData, encoding: .utf8) ?? "Unknown"
throw APIError.serverError(retryHttp.statusCode, msg)
}
return try JSONDecoder().decode(T.self, from: retryData)
} catch {
throw APIError.unauthorized
}
}
if http.statusCode == 401 { throw APIError.unauthorized }
if http.statusCode >= 400 {
let msg = String(data: data, encoding: .utf8) ?? "Unknown"
@@ -46,7 +68,6 @@ class APIService {
let decoder = JSONDecoder()
do { return try decoder.decode(T.self, from: data) }
catch {
// Debug: print first 200 chars of response
let snippet = String(data: data, encoding: .utf8)?.prefix(200) ?? ""
throw APIError.decodingError("\(error.localizedDescription) | Response: \(snippet)")
}
@@ -68,6 +89,11 @@ class APIService {
return try await fetch("/auth/me", token: token)
}
func refreshToken(refreshToken: String) async throws -> RefreshResponse {
let body = try JSONEncoder().encode(RefreshRequest(refreshToken: refreshToken))
return try await fetch("/auth/refresh", method: "POST", body: body)
}
// MARK: - Profile
func getProfile(token: String) async throws -> UserProfile {
@@ -136,7 +162,7 @@ class APIService {
func logHabit(token: String, id: Int, date: String? = nil) async throws {
var params: [String: Any] = [:]
if let d = date { params["completed_at"] = d }
if let d = date { params["date"] = d }
let body = try JSONSerialization.data(withJSONObject: params)
let _: EmptyResponse = try await fetch("/habits/\(id)/log", method: "POST", token: token, body: body)
}
@@ -229,6 +255,78 @@ class APIService {
func deleteSavingsTransaction(token: String, id: Int) async throws {
let _: EmptyResponse = try await fetch("/savings/transactions/\(id)", method: "DELETE", token: token)
}
@discardableResult
func updateSavingsTransaction(token: String, id: Int, request: CreateSavingsTransactionRequest) async throws -> SavingsTransaction {
let body = try JSONEncoder().encode(request)
return try await fetch("/savings/transactions/\(id)", method: "PUT", token: token, body: body)
}
// MARK: - Savings Recurring Plans
func getRecurringPlans(token: String, categoryId: Int) async throws -> [SavingsRecurringPlan] {
return try await fetch("/savings/categories/\(categoryId)/recurring-plans", token: token)
}
@discardableResult
func createRecurringPlan(token: String, categoryId: Int, request: CreateRecurringPlanRequest) async throws -> SavingsRecurringPlan {
let body = try JSONEncoder().encode(request)
return try await fetch("/savings/categories/\(categoryId)/recurring-plans", method: "POST", token: token, body: body)
}
@discardableResult
func updateRecurringPlan(token: String, planId: Int, request: UpdateRecurringPlanRequest) async throws -> SavingsRecurringPlan {
let body = try JSONEncoder().encode(request)
return try await fetch("/savings/recurring-plans/\(planId)", method: "PUT", token: token, body: body)
}
func deleteRecurringPlan(token: String, planId: Int) async throws {
let _: EmptyResponse = try await fetch("/savings/recurring-plans/\(planId)", method: "DELETE", token: token)
}
// MARK: - Habit Freezes
func getHabitFreezes(token: String, habitId: Int) async throws -> [HabitFreeze] {
return try await fetch("/habits/\(habitId)/freezes", token: token)
}
@discardableResult
func createHabitFreeze(token: String, habitId: Int, startDate: String, endDate: String, reason: String? = nil) async throws -> HabitFreeze {
var params: [String: Any] = ["start_date": startDate, "end_date": endDate]
if let r = reason { params["reason"] = r }
let body = try JSONSerialization.data(withJSONObject: params)
return try await fetch("/habits/\(habitId)/freezes", method: "POST", token: token, body: body)
}
func deleteHabitFreeze(token: String, habitId: Int, freezeId: Int) async throws {
let _: EmptyResponse = try await fetch("/habits/\(habitId)/freezes/\(freezeId)", method: "DELETE", token: token)
}
// MARK: - Finance Categories CRUD
@discardableResult
func createFinanceCategory(token: String, request: CreateFinanceCategoryRequest) async throws -> FinanceCategory {
let body = try JSONEncoder().encode(request)
return try await fetch("/finance/categories", method: "POST", token: token, body: body)
}
@discardableResult
func updateFinanceCategory(token: String, id: Int, request: CreateFinanceCategoryRequest) async throws -> FinanceCategory {
let body = try JSONEncoder().encode(request)
return try await fetch("/finance/categories/\(id)", method: "PUT", token: token, body: body)
}
func deleteFinanceCategory(token: String, id: Int) async throws {
let _: EmptyResponse = try await fetch("/finance/categories/\(id)", method: "DELETE", token: token)
}
// MARK: - Finance Transaction Update
@discardableResult
func updateTransaction(token: String, id: Int, request: CreateTransactionRequest) async throws -> FinanceTransaction {
let body = try JSONEncoder().encode(request)
return try await fetch("/finance/transactions/\(id)", method: "PUT", token: token, body: body)
}
}
struct EmptyResponse: Codable {}