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:
Trey t
2025-12-08 12:02:16 -06:00
parent c5b08befea
commit efdb760438
10 changed files with 1008 additions and 124 deletions

View File

@@ -7,12 +7,295 @@
import WidgetKit
import AppIntents
import Foundation
// MARK: - Widget Configuration Intent
struct ConfigurationAppIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource { "Configuration" }
static var description: IntentDescription { "This is an example widget." }
// An example configurable parameter.
@Parameter(title: "Favorite Emoji", default: "😃")
var favoriteEmoji: String
static var title: LocalizedStringResource { "Casera Configuration" }
static var description: IntentDescription { "Configure your Casera widget" }
}
// MARK: - Complete Task Intent
/// Marks a task as completed from the widget by calling the API directly
struct CompleteTaskIntent: AppIntent {
static var title: LocalizedStringResource { "Complete Task" }
static var description: IntentDescription { "Mark a task as completed" }
@Parameter(title: "Task ID")
var taskId: Int
@Parameter(title: "Task Title")
var taskTitle: String
init() {
self.taskId = 0
self.taskTitle = ""
}
init(taskId: Int, taskTitle: String) {
self.taskId = taskId
self.taskTitle = taskTitle
}
func perform() async throws -> some IntentResult {
print("CompleteTaskIntent: Starting completion for task \(taskId)")
// Mark task as pending completion immediately (optimistic UI)
WidgetActionManager.shared.markTaskPendingCompletion(taskId: taskId)
// Get auth token and API URL from shared container
guard let token = WidgetActionManager.shared.getAuthToken() else {
print("CompleteTaskIntent: No auth token available")
WidgetCenter.shared.reloadTimelines(ofKind: "Casera")
return .result()
}
guard let baseURL = WidgetActionManager.shared.getAPIBaseURL() else {
print("CompleteTaskIntent: No API base URL available")
WidgetCenter.shared.reloadTimelines(ofKind: "Casera")
return .result()
}
// Make API call to complete the task
let success = await WidgetAPIClient.quickCompleteTask(
taskId: taskId,
token: token,
baseURL: baseURL
)
if success {
print("CompleteTaskIntent: Task \(taskId) completed successfully")
// Mark tasks as dirty so main app refreshes on next launch
WidgetActionManager.shared.markTasksDirty()
} else {
print("CompleteTaskIntent: Failed to complete task \(taskId)")
// Task will remain hidden until it times out or app refreshes
}
// Reload widget
WidgetCenter.shared.reloadTimelines(ofKind: "Casera")
return .result()
}
}
// MARK: - Widget API Client
/// Lightweight API client for widget network calls
enum WidgetAPIClient {
/// Complete a task via the quick-complete endpoint
/// Returns true on success, false on failure
static func quickCompleteTask(taskId: Int, token: String, baseURL: String) async -> Bool {
let urlString = "\(baseURL)/tasks/\(taskId)/quick-complete/"
guard let url = URL(string: urlString) else {
print("WidgetAPIClient: Invalid URL: \(urlString)")
return false
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Token \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 10 // Short timeout for widget
do {
let (_, response) = try await URLSession.shared.data(for: request)
if let httpResponse = response as? HTTPURLResponse {
let isSuccess = httpResponse.statusCode == 200
print("WidgetAPIClient: quick-complete response: \(httpResponse.statusCode)")
return isSuccess
}
return false
} catch {
print("WidgetAPIClient: Error completing task: \(error.localizedDescription)")
return false
}
}
}
// MARK: - Open Task Intent
/// Opens a specific task in the main app
struct OpenTaskIntent: AppIntent {
static var title: LocalizedStringResource { "Open Task" }
static var description: IntentDescription { "Open task details in the app" }
@Parameter(title: "Task ID")
var taskId: Int
init() {
self.taskId = 0
}
init(taskId: Int) {
self.taskId = taskId
}
static var openAppWhenRun: Bool { true }
func perform() async throws -> some IntentResult {
// The app will handle deep linking via URL scheme
return .result()
}
}
// MARK: - Widget Action Manager
/// Manages shared data between the main app and widget extension via App Group
final class WidgetActionManager {
static let shared = WidgetActionManager()
private let appGroupIdentifier = "group.com.tt.casera.CaseraDev"
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: - Shared Container Access
private var sharedContainerURL: URL? {
FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)
}
private var pendingTasksFileURL: URL? {
sharedContainerURL?.appendingPathComponent(pendingTasksFileName)
}
// MARK: - Auth Token Access
/// Get auth token from shared App Group (set by main app)
func getAuthToken() -> String? {
return sharedDefaults?.string(forKey: tokenKey)
}
/// Get API base URL from shared App Group (set by main app)
func getAPIBaseURL() -> String? {
return sharedDefaults?.string(forKey: apiBaseURLKey)
}
// MARK: - Dirty Flag
/// Mark tasks as dirty (needs refresh from server)
func markTasksDirty() {
sharedDefaults?.set(true, forKey: dirtyFlagKey)
sharedDefaults?.synchronize()
print("WidgetActionManager: Marked tasks as dirty")
}
// MARK: - Subscription Status
/// 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: - Pending Task State Management
/// Tracks which tasks have pending completion (not yet synced with server)
struct PendingTaskState: Codable {
let taskId: Int
let timestamp: Date
}
/// Mark a task as pending completion (optimistic UI update - hides from widget)
func markTaskPendingCompletion(taskId: Int) {
var pendingTasks = loadPendingTaskStates()
// Remove any existing state for this task
pendingTasks.removeAll { $0.taskId == taskId }
// Add new pending state
pendingTasks.append(PendingTaskState(
taskId: taskId,
timestamp: Date()
))
savePendingTaskStates(pendingTasks)
}
/// Load pending task states
func loadPendingTaskStates() -> [PendingTaskState] {
guard let fileURL = pendingTasksFileURL,
FileManager.default.fileExists(atPath: fileURL.path) else {
return []
}
do {
let data = try Data(contentsOf: fileURL)
let states = try JSONDecoder().decode([PendingTaskState].self, from: data)
// Filter out stale states (older than 5 minutes)
let freshStates = states.filter { state in
Date().timeIntervalSince(state.timestamp) < 300 // 5 minutes
}
if freshStates.count != states.count {
savePendingTaskStates(freshStates)
}
return freshStates
} catch {
return []
}
}
/// Save pending task states
private func savePendingTaskStates(_ states: [PendingTaskState]) {
guard let fileURL = pendingTasksFileURL else { return }
do {
let data = try JSONEncoder().encode(states)
try data.write(to: fileURL, options: .atomic)
} catch {
print("WidgetActionManager: Error saving pending task states - \(error)")
}
}
/// Clear pending state for a task (called after synced with server)
func clearPendingState(forTaskId taskId: Int) {
var pendingTasks = loadPendingTaskStates()
pendingTasks.removeAll { $0.taskId == taskId }
savePendingTaskStates(pendingTasks)
// Also reload widget
WidgetCenter.shared.reloadTimelines(ofKind: "Casera")
}
/// Clear all pending states
func clearAllPendingStates() {
guard let fileURL = pendingTasksFileURL else { return }
do {
try FileManager.default.removeItem(at: fileURL)
} catch {
// File might not exist
}
}
/// Check if a task is pending completion
func isTaskPendingCompletion(taskId: Int) -> Bool {
let states = loadPendingTaskStates()
return states.contains { $0.taskId == taskId }
}
}

View File

@@ -7,6 +7,7 @@
import WidgetKit
import SwiftUI
import AppIntents
// MARK: - Date Formatting Helper
/// Parses date strings in either yyyy-MM-dd or ISO8601 (RFC3339) format
@@ -58,7 +59,7 @@ private func formatWidgetDate(_ dateString: String) -> String {
/// CacheManager reads tasks from the App Group shared container
/// Data is written by the main app via WidgetDataManager
class CacheManager {
struct CustomTask: Codable {
struct CustomTask: Codable, Identifiable {
let id: Int
let title: String
let description: String?
@@ -75,6 +76,16 @@ class CacheManager {
case residenceName = "residence_name"
case isOverdue = "is_overdue"
}
/// Whether this task is pending completion (tapped on widget, waiting for sync)
var isPendingCompletion: Bool {
WidgetActionManager.shared.isTaskPendingCompletion(taskId: id)
}
/// Whether this task should be shown (not pending completion)
var shouldShow: Bool {
!isPendingCompletion
}
}
private static let appGroupIdentifier = "group.com.tt.casera.CaseraDev"
@@ -116,9 +127,11 @@ class CacheManager {
let allTasks = getData()
// Filter for pending/in-progress tasks, sorted by due date
// Also exclude tasks that are pending completion via widget
let upcoming = allTasks.filter { task in
let status = task.status?.lowercased() ?? ""
return status == "pending" || status == "in_progress" || status == "in progress"
let isActive = status == "pending" || status == "in_progress" || status == "in progress"
return isActive && task.shouldShow
}
// Sort by due date (earliest first), with overdue at top
@@ -142,31 +155,36 @@ struct Provider: AppIntentTimelineProvider {
SimpleEntry(
date: Date(),
configuration: ConfigurationAppIntent(),
upcomingTasks: []
upcomingTasks: [],
isInteractive: true
)
}
func snapshot(for configuration: ConfigurationAppIntent, in context: Context) async -> SimpleEntry {
let tasks = CacheManager.getUpcomingTasks()
let isInteractive = WidgetActionManager.shared.shouldShowInteractiveWidget()
return SimpleEntry(
date: Date(),
configuration: configuration,
upcomingTasks: tasks
upcomingTasks: tasks,
isInteractive: isInteractive
)
}
func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<SimpleEntry> {
let tasks = CacheManager.getUpcomingTasks()
// Update every hour
let isInteractive = WidgetActionManager.shared.shouldShowInteractiveWidget()
// Update every 30 minutes (more frequent for interactive widgets)
let currentDate = Date()
let nextUpdate = Calendar.current.date(byAdding: .hour, value: 1, to: currentDate)!
let nextUpdate = Calendar.current.date(byAdding: .minute, value: 30, to: currentDate)!
let entry = SimpleEntry(
date: currentDate,
configuration: configuration,
upcomingTasks: tasks
upcomingTasks: tasks,
isInteractive: isInteractive
)
return Timeline(entries: [entry], policy: .after(nextUpdate))
}
}
@@ -175,11 +193,12 @@ struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationAppIntent
let upcomingTasks: [CacheManager.CustomTask]
let isInteractive: Bool
var taskCount: Int {
upcomingTasks.count
}
var nextTask: CacheManager.CustomTask? {
upcomingTasks.first
}
@@ -190,23 +209,58 @@ struct CaseraEntryView : View {
@Environment(\.widgetFamily) var family
var body: some View {
switch family {
case .systemSmall:
SmallWidgetView(entry: entry)
case .systemMedium:
MediumWidgetView(entry: entry)
case .systemLarge:
LargeWidgetView(entry: entry)
default:
SmallWidgetView(entry: entry)
if entry.isInteractive {
// Premium/no-limitations: Show interactive widget with task completion
switch family {
case .systemSmall:
SmallWidgetView(entry: entry)
case .systemMedium:
MediumWidgetView(entry: entry)
case .systemLarge:
LargeWidgetView(entry: entry)
default:
SmallWidgetView(entry: entry)
}
} else {
// Free tier with limitations: Show simple task count view
FreeWidgetView(entry: entry)
}
}
}
// MARK: - Free Tier Widget View (Non-Interactive)
struct FreeWidgetView: View {
let entry: SimpleEntry
var body: some View {
VStack(spacing: 12) {
Spacer()
// Task count display
Text("\(entry.taskCount)")
.font(.system(size: 56, weight: .bold))
.foregroundStyle(.blue)
Text(entry.taskCount == 1 ? "task waiting on you" : "tasks waiting on you")
.font(.system(size: 14, weight: .medium))
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
Spacer()
// Subtle upgrade hint
Text("Upgrade for interactive widgets")
.font(.system(size: 10))
.foregroundStyle(.tertiary)
}
.padding(16)
}
}
// MARK: - Small Widget View
struct SmallWidgetView: View {
let entry: SimpleEntry
var body: some View {
VStack(alignment: .leading, spacing: 0) {
// Task Count
@@ -214,35 +268,47 @@ struct SmallWidgetView: View {
Text("\(entry.taskCount)")
.font(.system(size: 36, weight: .bold))
.foregroundStyle(.blue)
if entry.taskCount > 0 {
Text(entry.taskCount == 1 ? "upcoming task" : "upcoming tasks")
.font(.system(size: 12, weight: .medium))
.foregroundStyle(.secondary)
}
}
// Next Task
// Next Task with Complete Button
if let nextTask = entry.nextTask {
VStack(alignment: .leading, spacing: 4) {
VStack(alignment: .leading, spacing: 6) {
Text("NEXT UP")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(.secondary)
.tracking(0.5)
Text(nextTask.title)
.font(.system(size: 12, weight: .semibold))
.lineLimit(2)
.lineLimit(1)
.foregroundStyle(.primary)
if let dueDate = nextTask.dueDate {
HStack(spacing: 4) {
Image(systemName: "calendar")
.font(.system(size: 9))
Text(formatWidgetDate(dueDate))
.font(.system(size: 10, weight: .medium))
HStack(spacing: 8) {
if let dueDate = nextTask.dueDate {
HStack(spacing: 4) {
Image(systemName: "calendar")
.font(.system(size: 9))
Text(formatWidgetDate(dueDate))
.font(.system(size: 10, weight: .medium))
}
.foregroundStyle(nextTask.isOverdue ? .red : .orange)
}
.foregroundStyle(.orange)
Spacer()
// Complete button
Button(intent: CompleteTaskIntent(taskId: nextTask.id, taskTitle: nextTask.title)) {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 20))
.foregroundStyle(.green)
}
.buttonStyle(.plain)
}
}
.padding(.top, 8)
@@ -258,9 +324,9 @@ struct SmallWidgetView: View {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 16))
.foregroundStyle(.green)
// Text("All caught up!")
// .font(.system(size: 11, weight: .medium))
// .foregroundStyle(.secondary)
Text("All caught up!")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 8)
@@ -277,53 +343,51 @@ struct SmallWidgetView: View {
// MARK: - Medium Widget View
struct MediumWidgetView: View {
let entry: SimpleEntry
var body: some View {
HStack(spacing: 16) {
// Left side - Task count
VStack(alignment: .leading, spacing: 4) {
Spacer()
Text("\(entry.taskCount)")
.font(.system(size: 42, weight: .bold))
.foregroundStyle(.blue)
VStack(alignment: .leading) {
Text("upcoming:")
Text("upcoming")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(.secondary)
.lineLimit(2)
Text(entry.taskCount == 1 ? "task" : "tasks")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(.secondary)
.lineLimit(2)
}
Spacer()
}
.frame(maxWidth: 75)
Divider()
// Right side - Next tasks
VStack(alignment: .leading, spacing: 8) {
if let nextTask = entry.nextTask {
// Right side - Next tasks with interactive buttons
VStack(alignment: .leading, spacing: 6) {
if entry.nextTask != nil {
Text("NEXT UP")
.font(.system(size: 9, weight: .semibold))
.foregroundStyle(.secondary)
.tracking(0.5)
}
if entry.nextTask != nil {
ForEach(Array(entry.upcomingTasks.prefix(3).enumerated()), id: \.element.id) { index, task in
TaskRowView(task: task, index: index)
InteractiveTaskRowView(task: task)
}
Spacer()
} else {
Spacer()
VStack(spacing: 8) {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 24))
@@ -333,7 +397,7 @@ struct MediumWidgetView: View {
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
Spacer()
}
}
@@ -343,23 +407,26 @@ struct MediumWidgetView: View {
}
}
// MARK: - Task Row
struct TaskRowView: View {
// MARK: - Interactive Task Row (for Medium widget)
struct InteractiveTaskRowView: View {
let task: CacheManager.CustomTask
let index: Int
var body: some View {
HStack(spacing: 8) {
Circle()
.fill(priorityColor)
.frame(width: 6, height: 6)
// Checkbox to complete task (color indicates priority)
Button(intent: CompleteTaskIntent(taskId: task.id, taskTitle: task.title)) {
Image(systemName: "circle")
.font(.system(size: 18))
.foregroundStyle(priorityColor)
}
.buttonStyle(.plain)
VStack(alignment: .leading, spacing: 2) {
Text(task.title)
.font(.system(size: 11, weight: .semibold))
// .lineLimit(1)
.lineLimit(1)
.foregroundStyle(.primary)
if let dueDate = task.dueDate {
HStack(spacing: 3) {
Image(systemName: "calendar")
@@ -367,32 +434,21 @@ struct TaskRowView: View {
Text(formatWidgetDate(dueDate))
.font(.system(size: 9, weight: .medium))
}
.foregroundStyle(.secondary)
.foregroundStyle(task.isOverdue ? .red : .secondary)
}
}
Spacer()
if let priority = task.priority {
Text(priority.prefix(1).uppercased())
.font(.system(size: 9, weight: .bold))
.foregroundStyle(.white)
.frame(width: 16, height: 16)
.background(
Circle()
.fill(priorityColor)
)
}
}
.padding(.vertical, 4)
.padding(.vertical, 3)
}
private var priorityColor: Color {
switch task.priority?.lowercased() {
case "urgent": return .red
case "high": return .orange
case "medium": return .blue
default: return .gray
case "medium": return .yellow
default: return .green
}
}
}
@@ -410,7 +466,7 @@ struct LargeWidgetView: View {
// Header
HStack(spacing: 6) {
Spacer()
Text("\(entry.taskCount)")
.font(.system(size: 22, weight: .bold))
.foregroundStyle(.blue)
@@ -435,9 +491,9 @@ struct LargeWidgetView: View {
Spacer()
} else {
// Show tasks
// Show tasks with interactive buttons
ForEach(Array(entry.upcomingTasks.prefix(maxTasksToShow).enumerated()), id: \.element.id) { index, task in
LargeTaskRowView(task: task, isOverdue: task.isOverdue)
LargeInteractiveTaskRowView(task: task)
}
if entry.upcomingTasks.count > 6 {
@@ -453,17 +509,19 @@ struct LargeWidgetView: View {
}
}
// MARK: - Large Task Row
struct LargeTaskRowView: View {
// MARK: - Large Interactive Task Row
struct LargeInteractiveTaskRowView: View {
let task: CacheManager.CustomTask
let isOverdue: Bool
var body: some View {
HStack(spacing: 8) {
// Priority indicator
RoundedRectangle(cornerRadius: 2)
.fill(priorityColor)
.frame(width: 3, height: 32)
// Checkbox to complete task (color indicates priority)
Button(intent: CompleteTaskIntent(taskId: task.id, taskTitle: task.title)) {
Image(systemName: "circle")
.font(.system(size: 20))
.foregroundStyle(priorityColor)
}
.buttonStyle(.plain)
VStack(alignment: .leading, spacing: 2) {
Text(task.title)
@@ -472,7 +530,7 @@ struct LargeTaskRowView: View {
.foregroundStyle(.primary)
HStack(spacing: 10) {
if let residenceName = task.residenceName {
if let residenceName = task.residenceName, !residenceName.isEmpty {
HStack(spacing: 2) {
Image("icon")
.resizable()
@@ -489,23 +547,14 @@ struct LargeTaskRowView: View {
Image(systemName: "calendar")
.font(.system(size: 7))
Text(formatWidgetDate(dueDate))
.font(.system(size: 9, weight: isOverdue ? .semibold : .regular))
.font(.system(size: 9, weight: task.isOverdue ? .semibold : .regular))
}
.foregroundStyle(isOverdue ? .red : .secondary)
.foregroundStyle(task.isOverdue ? .red : .secondary)
}
}
}
Spacer()
// Priority badge
if let priority = task.priority {
Text(priority.prefix(1).uppercased())
.font(.system(size: 8, weight: .bold))
.foregroundStyle(.white)
.frame(width: 16, height: 16)
.background(Circle().fill(priorityColor))
}
}
.padding(.vertical, 4)
.padding(.horizontal, 6)
@@ -519,8 +568,8 @@ struct LargeTaskRowView: View {
switch task.priority?.lowercased() {
case "urgent": return .red
case "high": return .orange
case "medium": return .blue
default: return .gray
case "medium": return .yellow
default: return .green
}
}
}
@@ -533,6 +582,9 @@ struct Casera: Widget {
CaseraEntryView(entry: entry)
.containerBackground(.fill.tertiary, for: .widget)
}
.configurationDisplayName("Casera Tasks")
.description("View and complete your upcoming tasks.")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
@@ -566,13 +618,57 @@ struct Casera: Widget {
residenceName: "Home",
isOverdue: false
)
]
],
isInteractive: true
)
// Free tier preview
SimpleEntry(
date: .now,
configuration: ConfigurationAppIntent(),
upcomingTasks: [
CacheManager.CustomTask(
id: 1,
title: "Fix leaky faucet",
description: nil,
priority: "high",
status: "pending",
dueDate: "2024-12-15",
category: "plumbing",
residenceName: "Home",
isOverdue: false
),
CacheManager.CustomTask(
id: 2,
title: "Paint living room",
description: nil,
priority: "medium",
status: "pending",
dueDate: "2024-12-20",
category: "painting",
residenceName: "Home",
isOverdue: false
),
CacheManager.CustomTask(
id: 3,
title: "Clean gutters",
description: nil,
priority: "low",
status: "pending",
dueDate: "2024-12-25",
category: "maintenance",
residenceName: "Home",
isOverdue: false
)
],
isInteractive: false
)
SimpleEntry(
date: .now,
configuration: ConfigurationAppIntent(),
upcomingTasks: []
upcomingTasks: [],
isInteractive: true
)
}
@@ -599,7 +695,7 @@ struct Casera: Widget {
title: "Paint living room",
description: nil,
priority: "medium",
status: "pending",
status: "in_progress",
dueDate: "2024-12-20",
category: "painting",
residenceName: "Cabin",
@@ -616,13 +712,79 @@ struct Casera: Widget {
residenceName: "Home",
isOverdue: false
)
]
],
isInteractive: true
)
// Free tier preview
SimpleEntry(
date: .now,
configuration: ConfigurationAppIntent(),
upcomingTasks: [
CacheManager.CustomTask(
id: 1,
title: "Fix leaky faucet",
description: nil,
priority: "high",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 2,
title: "Paint living room",
description: nil,
priority: "medium",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 3,
title: "Clean gutters",
description: nil,
priority: "low",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 4,
title: "Replace HVAC filter",
description: nil,
priority: "medium",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 5,
title: "Check smoke detectors",
description: nil,
priority: "high",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
)
],
isInteractive: false
)
SimpleEntry(
date: .now,
configuration: ConfigurationAppIntent(),
upcomingTasks: []
upcomingTasks: [],
isInteractive: true
)
}
@@ -649,7 +811,7 @@ struct Casera: Widget {
title: "Paint living room walls",
description: nil,
priority: "medium",
status: "pending",
status: "in_progress",
dueDate: "2024-12-20",
category: "painting",
residenceName: "Cabin",
@@ -721,12 +883,100 @@ struct Casera: Widget {
residenceName: "Beach House",
isOverdue: false
)
]
],
isInteractive: true
)
// Free tier preview
SimpleEntry(
date: .now,
configuration: ConfigurationAppIntent(),
upcomingTasks: [
CacheManager.CustomTask(
id: 1,
title: "Task 1",
description: nil,
priority: "high",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 2,
title: "Task 2",
description: nil,
priority: "medium",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 3,
title: "Task 3",
description: nil,
priority: "low",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 4,
title: "Task 4",
description: nil,
priority: "medium",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 5,
title: "Task 5",
description: nil,
priority: "high",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 6,
title: "Task 6",
description: nil,
priority: "low",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
),
CacheManager.CustomTask(
id: 7,
title: "Task 7",
description: nil,
priority: "medium",
status: "pending",
dueDate: nil,
category: nil,
residenceName: nil,
isOverdue: false
)
],
isInteractive: false
)
SimpleEntry(
date: .now,
configuration: ConfigurationAppIntent(),
upcomingTasks: []
upcomingTasks: [],
isInteractive: true
)
}

View File

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

View File

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

View File

@@ -73,6 +73,10 @@ class LoginViewModel: ObservableObject {
print("Login successful!")
print("User: \(response.user.username ?? "unknown"), Verified: \(self.isVerified)")
// Share token and API URL with widget extension
WidgetDataManager.shared.saveAuthToken(response.token)
WidgetDataManager.shared.saveAPIBaseURL(ApiClient.shared.getBaseUrl())
// Track successful login
PostHogAnalytics.shared.capture(AnalyticsEvents.userSignedIn, properties: ["method": "email"])
PostHogAnalytics.shared.identify(

View File

@@ -55,6 +55,10 @@ class RegisterViewModel: ObservableObject {
// - Storing token in TokenManager
// - Initializing lookups
// Share token and API URL with widget extension
WidgetDataManager.shared.saveAuthToken(response.token)
WidgetDataManager.shared.saveAPIBaseURL(ApiClient.shared.getBaseUrl())
// Track successful registration
PostHogAnalytics.shared.capture(AnalyticsEvents.userRegistered, properties: ["method": "email"])
PostHogAnalytics.shared.identify(

View File

@@ -90,8 +90,9 @@ class AuthenticationManager: ObservableObject {
_ = try? await APILayer.shared.logout()
}
// Clear widget task data
// Clear widget data (tasks and auth token)
WidgetDataManager.shared.clearCache()
WidgetDataManager.shared.clearAuthToken()
// Update authentication state
isAuthenticated = false

View File

@@ -117,6 +117,8 @@ class SubscriptionCacheWrapper: ObservableObject {
private func observeSubscriptionStatusSync() {
if let subscription = ComposeApp.SubscriptionCache.shared.currentSubscription.value as? SubscriptionStatus {
self.currentSubscription = subscription
// Sync subscription status with widget
syncWidgetSubscriptionStatus(subscription: subscription)
}
}
@@ -127,13 +129,25 @@ class SubscriptionCacheWrapper: ObservableObject {
self.upgradeTriggers = triggers
}
}
func updateSubscription(_ subscription: SubscriptionStatus) {
ComposeApp.SubscriptionCache.shared.updateSubscriptionStatus(subscription: subscription)
DispatchQueue.main.async {
self.currentSubscription = subscription
// Sync subscription status with widget
self.syncWidgetSubscriptionStatus(subscription: subscription)
}
}
/// Sync subscription status with widget extension
private func syncWidgetSubscriptionStatus(subscription: SubscriptionStatus) {
let limitationsEnabled = subscription.limitationsEnabled
let isPremium = currentTier == "pro"
WidgetDataManager.shared.saveSubscriptionStatus(
limitationsEnabled: limitationsEnabled,
isPremium: isPremium
)
}
func clear() {
ComposeApp.SubscriptionCache.shared.clear()

View File

@@ -2,6 +2,7 @@ import SwiftUI
import ComposeApp
struct AllTasksView: View {
@Environment(\.scenePhase) private var scenePhase
@StateObject private var taskViewModel = TaskViewModel()
@StateObject private var residenceViewModel = ResidenceViewModel()
@StateObject private var subscriptionCache = SubscriptionCacheWrapper.shared
@@ -98,7 +99,14 @@ struct AllTasksView: View {
}
.onAppear {
PostHogAnalytics.shared.screen(AnalyticsEvents.taskScreenShown)
loadAllTasks()
// Check if widget completed a task - force refresh if dirty
if WidgetDataManager.shared.areTasksDirty() {
WidgetDataManager.shared.clearDirtyFlag()
loadAllTasks(forceRefresh: true)
} else {
loadAllTasks()
}
residenceViewModel.loadMyResidences()
}
// Handle push notification deep links
@@ -126,6 +134,15 @@ struct AllTasksView: View {
}
}
}
// Check dirty flag when app returns from background (widget may have completed a task)
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
if WidgetDataManager.shared.areTasksDirty() {
WidgetDataManager.shared.clearDirtyFlag()
loadAllTasks(forceRefresh: true)
}
}
}
}
@ViewBuilder

View File

@@ -62,6 +62,11 @@ struct iOSApp: App {
Task {
_ = try? await APILayer.shared.initializeLookups()
}
// Process any pending widget actions (task completions, mark in-progress)
Task { @MainActor in
WidgetActionProcessor.shared.processPendingActions()
}
} else if newPhase == .background {
// Refresh widget when app goes to background
WidgetCenter.shared.reloadAllTimelines()