DomainDig/PortfolioDashboard.swift

2ad5d8160338d289a65d6a4d1c214a02bf916f1f
domain-dig/DomainDig/PortfolioDashboard.swift history · blame · raw

151 lines · 5629 bytes

9 symbols in this file
  1import Foundation
  2
  3// The portfolio dashboard's value types and the filtering that derives a
  4// visible subset from them. Split out of DomainViewModel.swift (A13), where
  5// they sat above the class; the filtering arrived there with A4 and belongs
  6// with the data rather than with the view model.
  7
  8struct PortfolioDomainStatus: Identifiable {
  9    let trackedDomain: TrackedDomain
 10    let latestEntry: HistoryEntry?
 11    let report: DomainReport
 12    let apexDomain: String
 13    let health: DomainHealth
 14    let lastChangeDate: Date?
 15    let lastMonitoringFailure: Date?
 16    let instabilityScore: Int
 17    let certificateExpiryState: CertificateWarningLevel
 18    let certificateDaysRemaining: Int?
 19    let isUnreachable: Bool
 20    let recentDNSChange: Bool
 21    let recentCriticalChange: Bool
 22    let recentFailureCount: Int
 23
 24    var id: UUID { trackedDomain.id }
 25}
 26
 27struct PortfolioActivityItem: Identifiable {
 28    let id: String
 29    let trackedDomainID: UUID
 30    let domain: String
 31    let message: String
 32    let timestamp: Date
 33    let health: DomainHealth
 34    let systemImage: String
 35}
 36
 37struct PortfolioAttentionItem: Identifiable {
 38    let id: String
 39    let trackedDomainID: UUID
 40    let domain: String
 41    let reason: String
 42    let timestamp: Date
 43    let health: DomainHealth
 44}
 45
 46struct PortfolioGroup: Identifiable {
 47    let apexDomain: String
 48    let domains: [PortfolioDomainStatus]
 49
 50    var id: String { apexDomain }
 51}
 52
 53struct PortfolioDashboardData {
 54    let snapshot: PortfolioSnapshot
 55    let domainStates: [PortfolioDomainStatus]
 56    let recentActivity: [PortfolioActivityItem]
 57    let attentionRequired: [PortfolioAttentionItem]
 58    let expiringSoon: [PortfolioDomainStatus]
 59    let groups: [PortfolioGroup]
 60
 61    /// The same dashboard narrowed to the domains matching the filter and the
 62    /// search text, with every list kept consistent with that set.
 63    ///
 64    /// This used to be five computed properties on the view model, each of
 65    /// which re-read `portfolioDashboardData` and re-derived the visible set.
 66    /// A4: the view reads each of them twice, so the dashboard was rebuilt
 67    /// more than twenty times per render. Filtering is a function of the data
 68    /// now, so a view can do it once.
 69    func filtered(by filter: PortfolioFilterOption, searchText: String) -> PortfolioDashboardData {
 70        let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
 71        let visibleStates = domainStates.filter {
 72            $0.matches(filter) && $0.matches(searchQuery: query)
 73        }
 74        let visibleIDs = Set(visibleStates.map(\.trackedDomain.id))
 75
 76        return PortfolioDashboardData(
 77            snapshot: snapshot,
 78            domainStates: visibleStates,
 79            recentActivity: recentActivity.filter { visibleIDs.contains($0.trackedDomainID) },
 80            attentionRequired: attentionRequired.filter { visibleIDs.contains($0.trackedDomainID) },
 81            expiringSoon: expiringSoon.filter { visibleIDs.contains($0.trackedDomain.id) },
 82            groups: PortfolioDashboardData.groups(from: visibleStates)
 83        )
 84    }
 85
 86    /// Worst health first, then alphabetical, within a group and between them.
 87    static func groups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] {
 88        Dictionary(grouping: domainStates, by: \.apexDomain)
 89            .map { apexDomain, domains in
 90                PortfolioGroup(
 91                    apexDomain: apexDomain,
 92                    domains: domains.sorted { lhs, rhs in
 93                        if lhs.health != rhs.health {
 94                            return lhs.health.severityRank > rhs.health.severityRank
 95                        }
 96                        return lhs.trackedDomain.domain
 97                            .localizedCaseInsensitiveCompare(rhs.trackedDomain.domain) == .orderedAscending
 98                    }
 99                )
100            }
101            .sorted { lhs, rhs in
102                if let lhsMostSevere = lhs.domains.map(\.health.severityRank).max(),
103                   let rhsMostSevere = rhs.domains.map(\.health.severityRank).max(),
104                   lhsMostSevere != rhsMostSevere {
105                    return lhsMostSevere > rhsMostSevere
106                }
107                return lhs.apexDomain.localizedCaseInsensitiveCompare(rhs.apexDomain) == .orderedAscending
108            }
109    }
110}
111
112extension DomainHealth {
113    /// Sort order for "worst first" listings. Was a private `healthRank` on the
114    /// view model, which is the wrong owner for a property of the health value.
115    var severityRank: Int {
116        switch self {
117        case .healthy: return 0
118        case .warning: return 1
119        case .critical: return 2
120        }
121    }
122}
123
124extension PortfolioDomainStatus {
125    func matches(_ filter: PortfolioFilterOption) -> Bool {
126        switch filter {
127        case .all:
128            return true
129        case .healthy:
130            return health == .healthy
131        case .warning:
132            return health == .warning
133        case .critical:
134            return health == .critical
135        case .changed:
136            guard let lastChangeDate else { return false }
137            return Date().timeIntervalSince(lastChangeDate) <= 24 * 60 * 60
138        case .expiring:
139            return certificateExpiryState != .none
140        case .unreachable:
141            return isUnreachable
142        }
143    }
144
145    func matches(searchQuery query: String) -> Bool {
146        guard !query.isEmpty else { return true }
147        let normalized = query.lowercased()
148        return trackedDomain.domain.lowercased().contains(normalized)
149            || apexDomain.lowercased().contains(normalized)
150    }
151}