Add interactive iOS widget with subscription-based views
- Add direct API completion from widget via quick-complete endpoint - Share auth token and API URL with widget via App Group UserDefaults - Add dirty flag mechanism to refresh tasks when app returns from background - Widget checkbox colors indicate priority (red=urgent, orange=high, yellow=medium, green=low) - Show simple "X tasks waiting" view for free tier users when limitations enabled - Show interactive task completion widget for premium users or when limitations disabled - Sync subscription status with widget extension for view selection 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
import Foundation
|
||||
import ComposeApp
|
||||
import WidgetKit
|
||||
|
||||
/// Processes pending actions queued by the widget extension
|
||||
/// Call `processPendingActions()` when the app becomes active
|
||||
@MainActor
|
||||
final class WidgetActionProcessor {
|
||||
static let shared = WidgetActionProcessor()
|
||||
|
||||
private init() {}
|
||||
|
||||
/// Check if there are pending widget actions to process
|
||||
var hasPendingActions: Bool {
|
||||
WidgetDataManager.shared.hasPendingActions
|
||||
}
|
||||
|
||||
/// Process all pending widget actions
|
||||
/// Should be called when app becomes active
|
||||
func processPendingActions() {
|
||||
guard DataManager.shared.isAuthenticated() else {
|
||||
print("WidgetActionProcessor: Not authenticated, skipping action processing")
|
||||
return
|
||||
}
|
||||
|
||||
let actions = WidgetDataManager.shared.loadPendingActions()
|
||||
guard !actions.isEmpty else {
|
||||
print("WidgetActionProcessor: No pending actions")
|
||||
return
|
||||
}
|
||||
|
||||
print("WidgetActionProcessor: Processing \(actions.count) pending action(s)")
|
||||
|
||||
for action in actions {
|
||||
Task {
|
||||
await processAction(action)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Process a single widget action
|
||||
private func processAction(_ action: WidgetDataManager.WidgetAction) async {
|
||||
switch action {
|
||||
case .completeTask(let taskId, let taskTitle):
|
||||
await completeTask(taskId: taskId, taskTitle: taskTitle, action: action)
|
||||
}
|
||||
}
|
||||
|
||||
/// Complete a task via the API
|
||||
private func completeTask(taskId: Int, taskTitle: String, action: WidgetDataManager.WidgetAction) async {
|
||||
print("WidgetActionProcessor: Completing task \(taskId) - \(taskTitle)")
|
||||
|
||||
do {
|
||||
// Create a task completion with default values (quick complete from widget)
|
||||
let request = TaskCompletionCreateRequest(
|
||||
taskId: Int32(taskId),
|
||||
completedAt: nil, // Defaults to now on server
|
||||
notes: "Completed from widget",
|
||||
actualCost: nil,
|
||||
rating: nil,
|
||||
imageUrls: nil
|
||||
)
|
||||
|
||||
let result = try await APILayer.shared.createTaskCompletion(request: request)
|
||||
|
||||
if result is ApiResultSuccess<TaskCompletionResponse> {
|
||||
print("WidgetActionProcessor: Task \(taskId) completed successfully")
|
||||
// Remove the processed action
|
||||
WidgetDataManager.shared.removeAction(action)
|
||||
// Clear pending state for this task
|
||||
WidgetDataManager.shared.clearPendingState(forTaskId: taskId)
|
||||
// Refresh tasks to update UI
|
||||
await refreshTasks()
|
||||
} else if let error = result as? ApiResultError {
|
||||
print("WidgetActionProcessor: Failed to complete task \(taskId): \(error.message)")
|
||||
// Remove action to avoid infinite retries
|
||||
WidgetDataManager.shared.removeAction(action)
|
||||
WidgetDataManager.shared.clearPendingState(forTaskId: taskId)
|
||||
}
|
||||
} catch {
|
||||
print("WidgetActionProcessor: Error completing task \(taskId): \(error)")
|
||||
// Remove action to avoid retries on error
|
||||
WidgetDataManager.shared.removeAction(action)
|
||||
WidgetDataManager.shared.clearPendingState(forTaskId: taskId)
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh tasks from the server to update UI and widget
|
||||
private func refreshTasks() async {
|
||||
do {
|
||||
let result = try await APILayer.shared.getTasks(forceRefresh: true)
|
||||
if let success = result as? ApiResultSuccess<TaskColumnsResponse>,
|
||||
let data = success.data {
|
||||
// Update widget with fresh data
|
||||
WidgetDataManager.shared.saveTasks(from: data)
|
||||
}
|
||||
} catch {
|
||||
print("WidgetActionProcessor: Error refreshing tasks: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,214 @@ final class WidgetDataManager {
|
||||
|
||||
private let appGroupIdentifier = "group.com.tt.casera.CaseraDev"
|
||||
private let tasksFileName = "widget_tasks.json"
|
||||
private let actionsFileName = "widget_pending_actions.json"
|
||||
private let pendingTasksFileName = "widget_pending_tasks.json"
|
||||
private let tokenKey = "widget_auth_token"
|
||||
private let dirtyFlagKey = "widget_tasks_dirty"
|
||||
private let apiBaseURLKey = "widget_api_base_url"
|
||||
private let limitationsEnabledKey = "widget_limitations_enabled"
|
||||
private let isPremiumKey = "widget_is_premium"
|
||||
|
||||
private var sharedDefaults: UserDefaults? {
|
||||
UserDefaults(suiteName: appGroupIdentifier)
|
||||
}
|
||||
|
||||
private init() {}
|
||||
|
||||
// MARK: - Auth Token Sharing
|
||||
|
||||
/// Save auth token to shared App Group for widget access
|
||||
/// Call this after successful login or when token is refreshed
|
||||
func saveAuthToken(_ token: String) {
|
||||
sharedDefaults?.set(token, forKey: tokenKey)
|
||||
sharedDefaults?.synchronize()
|
||||
print("WidgetDataManager: Saved auth token to shared container")
|
||||
}
|
||||
|
||||
/// Get auth token from shared App Group
|
||||
/// Used by widget to authenticate API requests
|
||||
func getAuthToken() -> String? {
|
||||
return sharedDefaults?.string(forKey: tokenKey)
|
||||
}
|
||||
|
||||
/// Clear auth token from shared App Group
|
||||
/// Call this on logout
|
||||
func clearAuthToken() {
|
||||
sharedDefaults?.removeObject(forKey: tokenKey)
|
||||
sharedDefaults?.synchronize()
|
||||
print("WidgetDataManager: Cleared auth token from shared container")
|
||||
}
|
||||
|
||||
/// Save API base URL to shared container for widget
|
||||
func saveAPIBaseURL(_ url: String) {
|
||||
sharedDefaults?.set(url, forKey: apiBaseURLKey)
|
||||
sharedDefaults?.synchronize()
|
||||
}
|
||||
|
||||
/// Get API base URL from shared container
|
||||
func getAPIBaseURL() -> String? {
|
||||
return sharedDefaults?.string(forKey: apiBaseURLKey)
|
||||
}
|
||||
|
||||
// MARK: - Subscription Status Sharing
|
||||
|
||||
/// Save subscription status for widget to determine which view to show
|
||||
/// Call this when subscription status changes
|
||||
func saveSubscriptionStatus(limitationsEnabled: Bool, isPremium: Bool) {
|
||||
sharedDefaults?.set(limitationsEnabled, forKey: limitationsEnabledKey)
|
||||
sharedDefaults?.set(isPremium, forKey: isPremiumKey)
|
||||
sharedDefaults?.synchronize()
|
||||
print("WidgetDataManager: Saved subscription status - limitations=\(limitationsEnabled), premium=\(isPremium)")
|
||||
// Reload widget to reflect new subscription status
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
}
|
||||
|
||||
/// Check if limitations are enabled (from backend)
|
||||
func areLimitationsEnabled() -> Bool {
|
||||
return sharedDefaults?.bool(forKey: limitationsEnabledKey) ?? false
|
||||
}
|
||||
|
||||
/// Check if user has premium subscription
|
||||
func isPremium() -> Bool {
|
||||
return sharedDefaults?.bool(forKey: isPremiumKey) ?? false
|
||||
}
|
||||
|
||||
/// Check if widget should show interactive features
|
||||
/// Returns true if: limitations disabled OR user is premium
|
||||
func shouldShowInteractiveWidget() -> Bool {
|
||||
let limitationsEnabled = areLimitationsEnabled()
|
||||
let premium = isPremium()
|
||||
// Interactive if limitations are off, or if user is premium
|
||||
return !limitationsEnabled || premium
|
||||
}
|
||||
|
||||
// MARK: - Dirty Flag for Task Refresh
|
||||
|
||||
/// Mark tasks as dirty (needs refresh from server)
|
||||
/// Called by widget after completing a task
|
||||
func markTasksDirty() {
|
||||
sharedDefaults?.set(true, forKey: dirtyFlagKey)
|
||||
sharedDefaults?.synchronize()
|
||||
print("WidgetDataManager: Marked tasks as dirty")
|
||||
}
|
||||
|
||||
/// Check if tasks need refresh
|
||||
func areTasksDirty() -> Bool {
|
||||
return sharedDefaults?.bool(forKey: dirtyFlagKey) ?? false
|
||||
}
|
||||
|
||||
/// Clear dirty flag after refreshing tasks
|
||||
func clearDirtyFlag() {
|
||||
sharedDefaults?.set(false, forKey: dirtyFlagKey)
|
||||
sharedDefaults?.synchronize()
|
||||
print("WidgetDataManager: Cleared dirty flag")
|
||||
}
|
||||
|
||||
// MARK: - Widget Action Types (must match AppIntent.swift in widget extension)
|
||||
|
||||
enum WidgetAction: Codable, Equatable {
|
||||
case completeTask(taskId: Int, taskTitle: String)
|
||||
|
||||
var taskId: Int {
|
||||
switch self {
|
||||
case .completeTask(let id, _):
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
var taskTitle: String {
|
||||
switch self {
|
||||
case .completeTask(_, let title):
|
||||
return title
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pending Action Processing
|
||||
|
||||
/// Load pending actions queued by the widget
|
||||
func loadPendingActions() -> [WidgetAction] {
|
||||
guard let fileURL = sharedContainerURL?.appendingPathComponent(actionsFileName),
|
||||
FileManager.default.fileExists(atPath: fileURL.path) else {
|
||||
return []
|
||||
}
|
||||
|
||||
do {
|
||||
let data = try Data(contentsOf: fileURL)
|
||||
return try JSONDecoder().decode([WidgetAction].self, from: data)
|
||||
} catch {
|
||||
print("WidgetDataManager: Error loading pending actions - \(error)")
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear all pending actions after processing
|
||||
func clearPendingActions() {
|
||||
guard let fileURL = sharedContainerURL?.appendingPathComponent(actionsFileName) else { return }
|
||||
|
||||
do {
|
||||
try FileManager.default.removeItem(at: fileURL)
|
||||
print("WidgetDataManager: Cleared pending actions")
|
||||
} catch {
|
||||
// File might not exist
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a specific action after processing
|
||||
func removeAction(_ action: WidgetAction) {
|
||||
var actions = loadPendingActions()
|
||||
actions.removeAll { $0 == action }
|
||||
|
||||
if actions.isEmpty {
|
||||
clearPendingActions()
|
||||
} else {
|
||||
guard let fileURL = sharedContainerURL?.appendingPathComponent(actionsFileName) else { return }
|
||||
do {
|
||||
let data = try JSONEncoder().encode(actions)
|
||||
try data.write(to: fileURL, options: .atomic)
|
||||
} catch {
|
||||
print("WidgetDataManager: Error saving actions - \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear pending state for a task after it's been synced
|
||||
func clearPendingState(forTaskId taskId: Int) {
|
||||
guard let fileURL = sharedContainerURL?.appendingPathComponent(pendingTasksFileName),
|
||||
FileManager.default.fileExists(atPath: fileURL.path) else {
|
||||
return
|
||||
}
|
||||
|
||||
struct PendingTaskState: Codable {
|
||||
let taskId: Int
|
||||
let pendingAction: String
|
||||
let timestamp: Date
|
||||
}
|
||||
|
||||
do {
|
||||
let data = try Data(contentsOf: fileURL)
|
||||
var states = try JSONDecoder().decode([PendingTaskState].self, from: data)
|
||||
states.removeAll { $0.taskId == taskId }
|
||||
|
||||
if states.isEmpty {
|
||||
try FileManager.default.removeItem(at: fileURL)
|
||||
} else {
|
||||
let updatedData = try JSONEncoder().encode(states)
|
||||
try updatedData.write(to: fileURL, options: .atomic)
|
||||
}
|
||||
|
||||
// Reload widget to reflect the change
|
||||
WidgetCenter.shared.reloadTimelines(ofKind: "Casera")
|
||||
} catch {
|
||||
print("WidgetDataManager: Error clearing pending state - \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if there are any pending actions from the widget
|
||||
var hasPendingActions: Bool {
|
||||
!loadPendingActions().isEmpty
|
||||
}
|
||||
|
||||
/// Task model for widget display - simplified version of TaskDetail
|
||||
struct WidgetTask: Codable {
|
||||
let id: Int
|
||||
|
||||
Reference in New Issue
Block a user