fix: codebase audit fixes — safety, accessibility, and production hygiene

Address 16 issues from external audit:
- Move StoreKit transaction listener ownership to StoreManager singleton with proper deinit
- Remove noisy VoiceOver announcements, add missing accessibility on StatPill and BootstrapLoadingView
- Replace String @retroactive Identifiable with IdentifiableShareCode wrapper
- Add crash guard in AchievementEngine getContributingVisitIds + cache stadium lookups
- Pre-compute GamesHistoryViewModel filtered properties to avoid redundant SwiftUI recomputation
- Remove force-unwraps in ProgressMapView with safe guard-let fallback
- Add diff-based update gating in ItineraryTableViewWrapper to prevent unnecessary reloads
- Replace deprecated UIScreen.main with UIWindowScene lookup
- Add deinit task cancellation in ScheduleViewModel and SuggestedTripsGenerator
- Wrap ~234 unguarded print() calls across 27 files in #if DEBUG

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Trey t
2026-02-22 00:07:53 -06:00
parent 826eadbc0f
commit 91c5eac22d
32 changed files with 434 additions and 67 deletions

View File

@@ -7,40 +7,17 @@ final class GamesHistoryViewModel {
private let modelContext: ModelContext
var allVisits: [StadiumVisit] = []
var selectedSports: Set<Sport> = []
var selectedSports: Set<Sport> = [] {
didSet { recomputeFilteredData() }
}
var isLoading = false
var error: String?
// Computed: visits grouped by year
var visitsByYear: [Int: [StadiumVisit]] {
let calendar = Calendar.current
let filtered = filteredVisits
return Dictionary(grouping: filtered) { visit in
calendar.component(.year, from: visit.visitDate)
}
}
// Computed: sorted year keys (descending)
var sortedYears: [Int] {
visitsByYear.keys.sorted(by: >)
}
// Computed: filtered by selected sports
var filteredVisits: [StadiumVisit] {
guard !selectedSports.isEmpty else { return allVisits }
return allVisits.filter { visit in
guard let stadium = AppDataProvider.shared.stadium(for: visit.stadiumId) else {
return false
}
return selectedSports.contains(stadium.sport)
}
}
// Total count
var totalGamesCount: Int {
filteredVisits.count
}
// Pre-computed stored properties (updated via recomputeFilteredData)
private(set) var filteredVisits: [StadiumVisit] = []
private(set) var visitsByYear: [Int: [StadiumVisit]] = [:]
private(set) var sortedYears: [Int] = []
private(set) var totalGamesCount: Int = 0
init(modelContext: ModelContext) {
self.modelContext = modelContext
@@ -60,6 +37,8 @@ final class GamesHistoryViewModel {
self.error = "Failed to load games: \(error.localizedDescription)"
allVisits = []
}
recomputeFilteredData()
}
func toggleSport(_ sport: Sport) {
@@ -73,4 +52,24 @@ final class GamesHistoryViewModel {
func clearFilters() {
selectedSports.removeAll()
}
private func recomputeFilteredData() {
if selectedSports.isEmpty {
filteredVisits = allVisits
} else {
filteredVisits = allVisits.filter { visit in
guard let stadium = AppDataProvider.shared.stadium(for: visit.stadiumId) else {
return false
}
return selectedSports.contains(stadium.sport)
}
}
let calendar = Calendar.current
visitsByYear = Dictionary(grouping: filteredVisits) { visit in
calendar.component(.year, from: visit.visitDate)
}
sortedYears = visitsByYear.keys.sorted(by: >)
totalGamesCount = filteredVisits.count
}
}

View File

@@ -47,8 +47,10 @@ final class PhotoImportViewModel {
func processSelectedPhotos(_ items: [PhotosPickerItem]) async {
guard !items.isEmpty else { return }
#if DEBUG
print("📷 [PhotoImport] ════════════════════════════════════════════════")
print("📷 [PhotoImport] Starting photo import with \(items.count) items")
#endif
isProcessing = true
totalCount = items.count
@@ -61,16 +63,21 @@ final class PhotoImportViewModel {
var assets: [PHAsset] = []
for (index, item) in items.enumerated() {
#if DEBUG
print("📷 [PhotoImport] ────────────────────────────────────────────────")
print("📷 [PhotoImport] Processing item \(index + 1)/\(items.count)")
print("📷 [PhotoImport] Item identifier: \(item.itemIdentifier ?? "nil")")
print("📷 [PhotoImport] Item supportedContentTypes: \(item.supportedContentTypes)")
#endif
if let assetId = item.itemIdentifier {
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [assetId], options: nil)
#if DEBUG
print("📷 [PhotoImport] PHAsset fetch result count: \(fetchResult.count)")
#endif
if let asset = fetchResult.firstObject {
#if DEBUG
print("📷 [PhotoImport] ✅ Found PHAsset")
print("📷 [PhotoImport] - localIdentifier: \(asset.localIdentifier)")
print("📷 [PhotoImport] - mediaType: \(asset.mediaType.rawValue)")
@@ -79,22 +86,30 @@ final class PhotoImportViewModel {
print("📷 [PhotoImport] - sourceType: \(asset.sourceType.rawValue)")
print("📷 [PhotoImport] - pixelWidth: \(asset.pixelWidth)")
print("📷 [PhotoImport] - pixelHeight: \(asset.pixelHeight)")
#endif
assets.append(asset)
} else {
#if DEBUG
print("📷 [PhotoImport] ⚠️ No PHAsset found for identifier")
#endif
}
} else {
#if DEBUG
print("📷 [PhotoImport] ⚠️ No itemIdentifier on PhotosPickerItem")
#endif
}
processedCount += 1
}
#if DEBUG
print("📷 [PhotoImport] ────────────────────────────────────────────────")
print("📷 [PhotoImport] Loaded \(assets.count) PHAssets, extracting metadata...")
#endif
// Extract metadata from all assets
let metadataList = await metadataExtractor.extractMetadata(from: assets)
#if DEBUG
print("📷 [PhotoImport] ────────────────────────────────────────────────")
print("📷 [PhotoImport] Extracted \(metadataList.count) metadata records")
@@ -103,25 +118,32 @@ final class PhotoImportViewModel {
let withDate = metadataList.filter { $0.hasValidDate }.count
print("📷 [PhotoImport] Photos with location: \(withLocation)/\(metadataList.count)")
print("📷 [PhotoImport] Photos with date: \(withDate)/\(metadataList.count)")
#endif
// Process each photo through game matcher
processedCount = 0
for (index, metadata) in metadataList.enumerated() {
#if DEBUG
print("📷 [PhotoImport] Matching photo \(index + 1): date=\(metadata.captureDate?.description ?? "nil"), location=\(metadata.hasValidLocation)")
#endif
let candidate = await gameMatcher.processPhotoForImport(metadata: metadata)
processedPhotos.append(candidate)
// Auto-confirm high-confidence matches
if candidate.canAutoProcess {
confirmedImports.insert(candidate.id)
#if DEBUG
print("📷 [PhotoImport] ✅ Auto-confirmed match")
#endif
}
processedCount += 1
}
#if DEBUG
print("📷 [PhotoImport] ════════════════════════════════════════════════")
print("📷 [PhotoImport] Import complete: \(processedPhotos.count) photos, \(confirmedImports.count) auto-confirmed")
#endif
isProcessing = false
}

View File

@@ -182,10 +182,15 @@ extension ProgressMapView {
let latitudes = stadiums.map { $0.latitude }
let longitudes = stadiums.map { $0.longitude }
let minLat = latitudes.min()!
let maxLat = latitudes.max()!
let minLon = longitudes.min()!
let maxLon = longitudes.max()!
guard let minLat = latitudes.min(),
let maxLat = latitudes.max(),
let minLon = longitudes.min(),
let maxLon = longitudes.max() else {
return MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 39.8283, longitude: -98.5795),
span: MKCoordinateSpan(latitudeDelta: 50, longitudeDelta: 50)
)
}
let center = CLLocationCoordinate2D(
latitude: (minLat + maxLat) / 2,

View File

@@ -28,7 +28,7 @@ final class ScheduleViewModel {
private(set) var errorMessage: String?
private let dataProvider = AppDataProvider.shared
private var loadTask: Task<Void, Never>?
nonisolated(unsafe) private var loadTask: Task<Void, Never>?
// MARK: - Pre-computed Groupings (avoid computed property overhead)
@@ -43,6 +43,10 @@ final class ScheduleViewModel {
/// Debug info for troubleshooting missing games
private(set) var diagnostics: ScheduleDiagnostics = ScheduleDiagnostics()
deinit {
loadTask?.cancel()
}
var hasFilters: Bool {
selectedSports.count < Sport.supported.count || !searchText.isEmpty
}

View File

@@ -468,6 +468,8 @@ private struct PlaceRow: View {
#Preview {
PlaceSearchSheet { place in
#if DEBUG
print("Selected: \(place.name ?? "unknown")")
#endif
}
}

View File

@@ -734,7 +734,9 @@ private struct PressableStyle: ButtonStyle {
day: 1,
existingItem: nil
) { item in
#if DEBUG
print("Saved: \(item)")
#endif
}
.preferredColorScheme(.light)
}
@@ -745,7 +747,9 @@ private struct PressableStyle: ButtonStyle {
day: 3,
existingItem: nil
) { item in
#if DEBUG
print("Saved: \(item)")
#endif
}
.preferredColorScheme(.dark)
}
@@ -770,6 +774,8 @@ private struct PressableStyle: ButtonStyle {
day: existing.day,
existingItem: existing
) { item in
#if DEBUG
print("Updated: \(item)")
#endif
}
}

View File

@@ -83,7 +83,9 @@ enum ItineraryReorderingLogic {
// nil is valid during initial display before travel is persisted.
let lookedUp = findTravelSortOrder(segment)
sortOrder = lookedUp ?? defaultTravelSortOrder
#if DEBUG
print("📋 [flattenDays] Travel \(segment.fromLocation.name)->\(segment.toLocation.name) on day \(day.dayNumber): lookedUp=\(String(describing: lookedUp)), using sortOrder=\(sortOrder)")
#endif
case .games, .dayHeader:
// These item types are not movable and handled separately.
@@ -319,6 +321,7 @@ enum ItineraryReorderingLogic {
}
// DEBUG: Log the row positions
#if DEBUG
print("🔢 [calculateSortOrder] row=\(row), day=\(day), gamesRow=\(String(describing: gamesRow))")
print("🔢 [calculateSortOrder] items around row:")
for i in max(0, row - 2)...min(items.count - 1, row + 2) {
@@ -326,6 +329,7 @@ enum ItineraryReorderingLogic {
let gMarker = (gamesRow == i) ? " [GAMES]" : ""
print("🔢 \(marker) [\(i)] \(items[i])\(gMarker)")
}
#endif
// Strict region classification:
// - row < gamesRow => before-games (negative sortOrder)
@@ -333,10 +337,14 @@ enum ItineraryReorderingLogic {
let isBeforeGames: Bool
if let gr = gamesRow {
isBeforeGames = row < gr
#if DEBUG
print("🔢 [calculateSortOrder] row(\(row)) < gamesRow(\(gr)) = \(isBeforeGames) → isBeforeGames=\(isBeforeGames)")
#endif
} else {
isBeforeGames = false // No games means everything is "after games"
#if DEBUG
print("🔢 [calculateSortOrder] No games on day \(day) → isBeforeGames=false")
#endif
}
/// Get sortOrder from a movable item (custom item or travel)
@@ -442,7 +450,9 @@ enum ItineraryReorderingLogic {
}
}
#if DEBUG
print("🔢 [calculateSortOrder] RESULT: \(result) (isBeforeGames=\(isBeforeGames))")
#endif
return result
}

View File

@@ -869,6 +869,7 @@ final class ItineraryTableViewController: UITableViewController {
let sortOrder = calculateSortOrder(at: destinationIndexPath.row)
// DEBUG: Log the final state after insertion
#if DEBUG
print("🎯 [Drop] source=\(sourceIndexPath.row) → dest=\(destinationIndexPath.row)")
print("🎯 [Drop] flatItems around dest:")
for i in max(0, destinationIndexPath.row - 2)...min(flatItems.count - 1, destinationIndexPath.row + 2) {
@@ -876,6 +877,7 @@ final class ItineraryTableViewController: UITableViewController {
print("🎯 [Drop] \(marker) [\(i)] \(flatItems[i])")
}
print("🎯 [Drop] Calculated day=\(destinationDay), sortOrder=\(sortOrder)")
#endif
onCustomItemMoved?(customItem.id, destinationDay, sortOrder)

View File

@@ -53,6 +53,10 @@ struct ItineraryTableViewWrapper<HeaderContent: View>: UIViewControllerRepresent
class Coordinator {
var headerHostingController: UIHostingController<HeaderContent>?
var lastStopCount: Int = 0
var lastGameIDsHash: Int = 0
var lastItemCount: Int = 0
var lastOverrideCount: Int = 0
}
func makeUIViewController(context: Context) -> ItineraryTableViewController {
@@ -73,7 +77,9 @@ struct ItineraryTableViewWrapper<HeaderContent: View>: UIViewControllerRepresent
// Pre-size the header view
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
let targetWidth = UIScreen.main.bounds.width
let targetWidth = UIApplication.shared.connectedScenes
.compactMap { ($0 as? UIWindowScene)?.screen.bounds.width }
.first ?? 390
let targetSize = CGSize(width: targetWidth, height: UIView.layoutFittingCompressedSize.height)
let size = hostingController.view.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
hostingController.view.frame = CGRect(origin: .zero, size: CGSize(width: targetWidth, height: max(size.height, 450)))
@@ -109,6 +115,25 @@ struct ItineraryTableViewWrapper<HeaderContent: View>: UIViewControllerRepresent
// This avoids recreating the view hierarchy and prevents infinite loops
context.coordinator.headerHostingController?.rootView = headerContent
// Diff inputs before rebuilding to avoid unnecessary reloads
let currentStopCount = trip.stops.count
let currentGameIDsHash = games.map(\.game.id).hashValue
let currentItemCount = itineraryItems.count
let currentOverrideCount = travelOverrides.count
let coord = context.coordinator
guard currentStopCount != coord.lastStopCount ||
currentGameIDsHash != coord.lastGameIDsHash ||
currentItemCount != coord.lastItemCount ||
currentOverrideCount != coord.lastOverrideCount else {
return
}
coord.lastStopCount = currentStopCount
coord.lastGameIDsHash = currentGameIDsHash
coord.lastItemCount = currentItemCount
coord.lastOverrideCount = currentOverrideCount
let (days, validRanges, allItemsForConstraints, travelSegmentIndices) = buildItineraryData()
controller.reloadData(
days: days,

View File

@@ -197,12 +197,14 @@ struct TripDetailView: View {
private func handleItineraryItemsChange(_ newItems: [ItineraryItem]) {
draggedItem = nil
dropTargetId = nil
#if DEBUG
print("🗺️ [MapUpdate] itineraryItems changed, count: \(newItems.count)")
for item in newItems {
if item.isCustom, let info = item.customInfo, info.isMappable {
print("🗺️ [MapUpdate] Mappable: \(info.title) on day \(item.day), sortOrder: \(item.sortOrder)")
}
}
#endif
mapUpdateTask?.cancel()
mapUpdateTask = Task {
updateMapRegion()
@@ -851,7 +853,9 @@ struct TripDetailView: View {
updated.modifiedAt = Date()
let title = item.customInfo?.title ?? "item"
#if DEBUG
print("📍 [Move] Moving \(title) to day \(day), sortOrder: \(sortOrder)")
#endif
// Update local state
if let idx = itineraryItems.firstIndex(where: { $0.id == item.id }) {
@@ -863,7 +867,9 @@ struct TripDetailView: View {
// Sync to CloudKit (debounced)
await ItineraryItemService.shared.updateItem(updated)
#if DEBUG
print("✅ [Move] Synced \(title) with day: \(day), sortOrder: \(sortOrder)")
#endif
}
/// Recompute cached itinerary sections from current state.
@@ -1389,7 +1395,9 @@ struct TripDetailView: View {
// MARK: - Itinerary Items (Local-first persistence with CloudKit sync)
private func loadItineraryItems() async {
#if DEBUG
print("🔍 [ItineraryItems] Loading items for trip: \(trip.id)")
#endif
// 1. Load from local SwiftData first (instant, works offline)
let tripId = trip.id
@@ -1398,7 +1406,9 @@ struct TripDetailView: View {
)
let localItems = (try? modelContext.fetch(descriptor))?.compactMap(\.toItem) ?? []
if !localItems.isEmpty {
#if DEBUG
print("✅ [ItineraryItems] Loaded \(localItems.count) items from local cache")
#endif
itineraryItems = localItems
extractTravelOverrides(from: localItems)
}
@@ -1406,7 +1416,9 @@ struct TripDetailView: View {
// 2. Try CloudKit for latest data (background sync)
do {
let cloudItems = try await ItineraryItemService.shared.fetchItems(forTripId: trip.id)
#if DEBUG
print("✅ [ItineraryItems] Loaded \(cloudItems.count) items from CloudKit")
#endif
// Merge: use CloudKit as source of truth when available
if !cloudItems.isEmpty || localItems.isEmpty {
@@ -1415,7 +1427,9 @@ struct TripDetailView: View {
syncLocalCache(with: cloudItems)
}
} catch {
#if DEBUG
print("⚠️ [ItineraryItems] CloudKit fetch failed (using local cache): \(error)")
#endif
}
}
@@ -1429,7 +1443,9 @@ struct TripDetailView: View {
segIdx < trip.travelSegments.count {
let segment = trip.travelSegments[segIdx]
if !travelInfo.matches(segment: segment) {
#if DEBUG
print("⚠️ [TravelOverrides] Mismatched travel cities for segment \(segIdx); using canonical segment cities")
#endif
}
let travelId = stableTravelAnchorId(segment, at: segIdx)
overrides[travelId] = TravelOverride(day: item.day, sortOrder: item.sortOrder)
@@ -1441,7 +1457,9 @@ struct TripDetailView: View {
}
guard matches.count == 1, let match = matches.first else {
#if DEBUG
print("⚠️ [TravelOverrides] Ignoring ambiguous legacy travel override \(travelInfo.fromCity)->\(travelInfo.toCity)")
#endif
continue
}
@@ -1452,7 +1470,9 @@ struct TripDetailView: View {
}
travelOverrides = overrides
#if DEBUG
print("✅ [TravelOverrides] Extracted \(overrides.count) travel overrides (day + sortOrder)")
#endif
}
private func syncLocalCache(with items: [ItineraryItem]) {
@@ -1473,7 +1493,9 @@ struct TripDetailView: View {
private func saveItineraryItem(_ item: ItineraryItem) async {
let isUpdate = itineraryItems.contains(where: { $0.id == item.id })
let title = item.customInfo?.title ?? "item"
#if DEBUG
print("💾 [ItineraryItems] Saving item: '\(title)' (isUpdate: \(isUpdate))")
#endif
// Update in-memory state immediately
if isUpdate {
@@ -1491,14 +1513,20 @@ struct TripDetailView: View {
do {
if isUpdate {
await ItineraryItemService.shared.updateItem(item)
#if DEBUG
print("✅ [ItineraryItems] Updated in CloudKit: \(title)")
#endif
} else {
_ = try await ItineraryItemService.shared.createItem(item)
#if DEBUG
print("✅ [ItineraryItems] Created in CloudKit: \(title)")
#endif
markLocalItemSynced(item.id)
}
} catch {
#if DEBUG
print("⚠️ [ItineraryItems] CloudKit save failed (saved locally): \(error)")
#endif
}
}
@@ -1535,7 +1563,9 @@ struct TripDetailView: View {
private func deleteItineraryItem(_ item: ItineraryItem) async {
let title = item.customInfo?.title ?? "item"
#if DEBUG
print("🗑️ [ItineraryItems] Deleting item: '\(title)'")
#endif
// Remove from in-memory state
itineraryItems.removeAll { $0.id == item.id }
@@ -1553,9 +1583,13 @@ struct TripDetailView: View {
// Delete from CloudKit
do {
try await ItineraryItemService.shared.deleteItem(item.id)
#if DEBUG
print("✅ [ItineraryItems] Deleted from CloudKit")
#endif
} catch {
#if DEBUG
print("⚠️ [ItineraryItems] CloudKit delete failed (removed locally): \(error)")
#endif
}
}
@@ -1632,12 +1666,16 @@ struct TripDetailView: View {
}
private func saveTravelDayOverride(travelAnchorId: String, displayDay: Int, sortOrder: Double) async {
#if DEBUG
print("💾 [TravelOverrides] Saving override: \(travelAnchorId) -> day \(displayDay), sortOrder \(sortOrder)")
#endif
guard let segmentIndex = Self.parseSegmentIndex(from: travelAnchorId),
segmentIndex >= 0,
segmentIndex < trip.travelSegments.count else {
#if DEBUG
print("❌ [TravelOverrides] Invalid travel segment index in ID: \(travelAnchorId)")
#endif
return
}
@@ -1676,14 +1714,18 @@ struct TripDetailView: View {
_ = try await ItineraryItemService.shared.createItem(item)
markLocalItemSynced(item.id)
} catch {
#if DEBUG
print("❌ [TravelOverrides] CloudKit save failed: \(error)")
#endif
return
}
}
#if DEBUG
if canonicalTravelId != travelAnchorId {
print(" [TravelOverrides] Canonicalized travel ID to \(canonicalTravelId)")
}
print("✅ [TravelOverrides] Saved to CloudKit")
#endif
}
}

View File

@@ -203,7 +203,9 @@ struct TripWizardView: View {
// Team-First mode: fetch ALL games for the season
// ScenarioEPlanner will generate sliding windows across the full season
games = try await AppDataProvider.shared.allGames(for: preferences.sports)
#if DEBUG
print("🔍 TripWizard: Team-First mode - fetched \(games.count) games for \(preferences.sports)")
#endif
} else if viewModel.planningMode == .gameFirst && !viewModel.selectedGameIds.isEmpty {
// Fetch all games for the selected sports within the UI date range
// GamePickerStep already set viewModel.startDate/endDate to a 7-day span