fix: comprehensive codebase hardening — crashes, silent failures, performance, and security

Fixes ~95 issues from deep audit across 12 categories in 82 files:

- Crash prevention: double-resume in PhotoMetadataExtractor, force unwraps in
  DateRangePicker, array bounds checks in polls/achievements, ProGate hit-test
  bypass, Dictionary(uniqueKeysWithValues:) → uniquingKeysWith in 4 files
- Silent failure elimination: all 34 try? sites replaced with do/try/catch +
  logging (SavedTrip, TripDetailView, CanonicalSyncService, BootstrapService,
  CanonicalModels, CKModels, SportsTimeApp, and more)
- Performance: cached DateFormatters (7 files), O(1) team lookups via
  AppDataProvider, achievement definition dictionary, AnimatedBackground
  consolidated from 19 Tasks to 1, task cancellation in SharePreviewView
- Concurrency: UIKit drawing → MainActor.run, background fetch timeout guard,
  @MainActor on ThemeManager/AppearanceManager, SyncLogger read/write race fix
- Planning engine: game end time in travel feasibility, state-aware city
  normalization, exact city matching, DrivingConstraints parameter propagation
- IAP: unknown subscription states → expired, unverified transaction logging,
  entitlements updated before paywall dismiss, restore visible to all users
- Security: API key to Info.plist lookup, filename sanitization in PDF export,
  honest User-Agent, removed stale "Feels" analytics super properties
- Navigation: consolidated competing navigationDestination, boolean → value-based
- Testing: 8 sleep() → waitForExistence, duplicates extracted, Swift 6 compat
- Service bugs: infinite retry cap, duplicate achievement prevention, TOCTOU vote
  fix, PollVote.odg → voterId rename, deterministic placeholder IDs, parallel
  MKDirections, Sendable-safe POI struct

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Trey t
2026-02-27 17:03:09 -06:00
parent e046cb6b34
commit c94e373e33
82 changed files with 1163 additions and 599 deletions

View File

@@ -183,15 +183,15 @@ final class ProgressViewModel {
stadiumVisitStatus = statusMap
// Pre-compute sport progress fractions for SportSelectorGrid
var sportCounts: [Sport: Int] = [:]
var uniqueStadiumIdsBySport: [Sport: Set<String>] = [:]
for visit in visits {
if let sport = visit.sportEnum {
sportCounts[sport, default: 0] += 1
uniqueStadiumIdsBySport[sport, default: []].insert(visit.stadiumId)
}
}
sportProgressFractions = Dictionary(uniqueKeysWithValues: Sport.supported.map { sport in
let total = LeagueStructure.stadiumCount(for: sport)
let visited = min(sportCounts[sport] ?? 0, total)
let visited = min(uniqueStadiumIdsBySport[sport]?.count ?? 0, total)
return (sport, total > 0 ? Double(visited) / Double(total) : 0)
})

View File

@@ -304,11 +304,15 @@ struct GameMatchConfirmationView: View {
// MARK: - Helpers
private static let longDateShortTimeFormatter: DateFormatter = {
let f = DateFormatter()
f.dateStyle = .long
f.timeStyle = .short
return f
}()
private func formatDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .short
return formatter.string(from: date)
Self.longDateShortTimeFormatter.string(from: date)
}
private func confidenceColor(_ confidence: MatchConfidence) -> Color {

View File

@@ -478,10 +478,14 @@ struct PhotoImportCandidateCard: View {
.clipShape(Capsule())
}
private static let mediumDateFormatter: DateFormatter = {
let f = DateFormatter()
f.dateStyle = .medium
return f
}()
private func formatDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter.string(from: date)
Self.mediumDateFormatter.string(from: date)
}
}

View File

@@ -63,7 +63,7 @@ struct ProgressTabView: View {
}
}
.onChange(of: visits, initial: true) { _, newVisits in
visitsById = Dictionary(uniqueKeysWithValues: newVisits.map { ($0.id, $0) })
visitsById = Dictionary(newVisits.map { ($0.id, $0) }, uniquingKeysWith: { _, last in last })
}
.task {
viewModel.configure(with: modelContext.container)

View File

@@ -411,15 +411,15 @@ struct StadiumVisitSheet: View {
source: .manual
)
// Save to SwiftData
modelContext.insert(visit)
// Save to SwiftData insert and save together so we can clean up on failure
do {
modelContext.insert(visit)
try modelContext.save()
AnalyticsManager.shared.track(.stadiumVisitAdded(stadiumId: stadium.id, sport: selectedSport.rawValue))
onSave?(visit)
dismiss()
} catch {
modelContext.delete(visit)
errorMessage = "Failed to save visit: \(error.localizedDescription)"
isSaving = false
}

View File

@@ -18,6 +18,7 @@ struct VisitDetailView: View {
@State private var isEditing = false
@State private var showDeleteConfirmation = false
@State private var errorMessage: String?
// Edit state
@State private var editVisitDate: Date
@@ -134,6 +135,18 @@ struct VisitDetailView: View {
} message: {
Text("Are you sure you want to delete this visit? This action cannot be undone.")
}
.alert("Error", isPresented: Binding(
get: { errorMessage != nil },
set: { if !$0 { errorMessage = nil } }
)) {
Button("OK", role: .cancel) {
errorMessage = nil
}
} message: {
if let errorMessage {
Text(errorMessage)
}
}
}
// MARK: - Header
@@ -435,17 +448,25 @@ struct VisitDetailView: View {
visit.sportEnum?.themeColor ?? Theme.warmOrange
}
private static let longDateFormatter: DateFormatter = {
let f = DateFormatter()
f.dateStyle = .long
return f
}()
private static let mediumDateShortTimeFormatter: DateFormatter = {
let f = DateFormatter()
f.dateStyle = .medium
f.timeStyle = .short
return f
}()
private var formattedDate: String {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter.string(from: visit.visitDate)
Self.longDateFormatter.string(from: visit.visitDate)
}
private var formattedCreatedDate: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter.string(from: visit.createdAt)
Self.mediumDateShortTimeFormatter.string(from: visit.createdAt)
}
// MARK: - Actions
@@ -472,7 +493,12 @@ struct VisitDetailView: View {
visit.dataSource = .userCorrected
}
try? modelContext.save()
do {
try modelContext.save()
} catch {
errorMessage = "Failed to save: \(error.localizedDescription)"
return
}
withAnimation {
isEditing = false
@@ -506,7 +532,12 @@ struct VisitDetailView: View {
private func deleteVisit() {
modelContext.delete(visit)
try? modelContext.save()
do {
try modelContext.save()
} catch {
errorMessage = "Failed to delete: \(error.localizedDescription)"
return
}
dismiss()
}
}