Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Monitor9// File : App/Sources/Features/ReportsView.swift10// Description : Report builder: kind, period, preview, export to PDF /11// Markdown / CSV / JSON, and comparison of two saved12// reports.13// Module : Features14// Repository : https://git.spboucher.ai/orix-monitor15// Created : 2026-11-2116// Last Modified : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import AppKit92import ORIXMonitorCore93import SwiftUI94import UniformTypeIdentifiers9596enum ReportFormat: String, CaseIterable, Identifiable {97 case pdf, markdown, csv, json98 var id: String { rawValue }99 var title: String {100 switch self {101 case .pdf: "PDF"102 case .markdown: "Markdown"103 case .csv: "CSV"104 case .json: "JSON"105 }106 }107108 var fileExtension: String { self == .markdown ? "md" : rawValue }109 var type: UTType {110 switch self {111 case .pdf: .pdf112 case .markdown: UTType(filenameExtension: "md") ?? .plainText113 case .csv: .commaSeparatedText114 case .json: .json115 }116 }117}118119enum ReportText {120 static func title(_ kind: ReportKind) -> String { L(ReportGenerator.title(kind)) }121122 static func summary(_ kind: ReportKind) -> String {123 switch kind {124 case .system: L("Every subsystem at a glance, with volumes, interfaces, battery and top processes.")125 case .cpu: L("CPU usage, user and system time, load average and the busiest processes.")126 case .memory: L("Memory accounting, pressure, swap and paging, and the largest processes.")127 case .storage: L("Volume capacity, available-space trend and disk throughput.")128 case .network: L("Throughput history and interface totals.")129 case .processes: L("The 25 busiest processes right now, with the process count over time.")130 case .incident: L("Everything recorded around a moment: metrics, alerts, findings and system events.")131 }132 }133}134135struct ReportsView: View {136 @Environment(MonitorModel.self) private var model137 @Environment(AppSettings.self) private var settings138 @State private var kind: ReportKind = .system139 @State private var range: HistoryRange = .hour140 @State private var incidentDate = Date()141 @State private var report: Report?142 @State private var isBuilding = false143 @State private var comparison: ReportTable?144 @State private var comparisonNames: (String, String)?145 @State private var message: String?146 @State private var refresh = 0147148 var body: some View {149 Page {150 PageHeader(title: "Reports", subtitle: L("Built from stored measurements, with their sources and their gaps"), family: .system, symbol: "doc.text")151 CardRow {152 Card("Report") {153 Picker("Type", selection: $kind) { ForEach(ReportKind.allCases) { Text(ReportText.title($0)).tag($0) } }154 .accessibilityIdentifier("reports.kind")155 Text(ReportText.summary(kind)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)156 if kind == .incident {157 DatePicker("Moment of the incident", selection: $incidentDate, in: ...Date())158 Text("The report covers 30 minutes before and after that moment.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)159 } else {160 Picker("Period", selection: $range) { ForEach(HistoryRange.allCases) { Text($0.title).tag($0) } }161 }162 Toggle("Include this Mac's host name", isOn: Bindable(settings).includeHostInReports)163 Text("Off by default. Reports never contain the serial number, IP addresses or user names.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)164 }165 Card("Export") {166 HStack {167 Button { refresh += 1 } label: { Label("Refresh", systemImage: "arrow.clockwise") }.help("Rebuild the report with the latest stored samples")168 .accessibilityIdentifier("reports.refresh")169 Divider().frame(height: 16)170 ForEach(ReportFormat.allCases) { format in171 Button(format.title) { export(format) }.disabled(report == nil).accessibilityIdentifier("reports.export.\(format.rawValue)")172 }173 }174 Text("PDF includes charts. CSV holds every stored bucket in long format. JSON holds the complete report and can be compared later.")175 .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)176 Divider()177 Button("Compare Two Saved Reports…") { compare() }.accessibilityIdentifier("reports.compare")178 Text("Choose two JSON reports exported earlier to see averages and peaks side by side.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)179 if let message { Label(message, systemImage: "info.circle").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.warning) }180 }181 }182 if let comparison, let names = comparisonNames {183 Card("Comparison") {184 Text("A: \(names.0) · B: \(names.1)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)185 ReportTableView(table: comparison)186 }187 }188 if let report {189 Card("Preview") {190 HStack(alignment: .firstTextBaseline) {191 Text(report.title).font(.system(size: 16, weight: .bold))192 Spacer()193 Text("\(model.format.date(report.from)) → \(model.format.date(report.to))").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)194 }195 let f = model.format196 ReportTableView(table: ReportTable(title: "", headers: [L("Metric"), L("Minimum"), L("Average"), L("Maximum"), L("Samples"), L("Resolution"), L("Gaps")], rows: report.series.map { s in197 let cells = [s.minimum, s.average, s.maximum].map { x in x.map { AlertText.formatted($0, metric: s.metric, formatter: f) } ?? "—" }198 return [s.name] + cells + [String(s.sampleCount), f.duration(s.step), String(s.gaps.count)]199 }))200 ForEach(Array(report.tables.enumerated()), id: \.offset) { _, table in201 Text(table.title).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary).padding(.top, 6)202 ReportTableView(table: table)203 }204 if !report.findings.isEmpty {205 Text("Findings").font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary).padding(.top, 6)206 ForEach(report.findings) { finding in207 Label(FindingText.title(finding), systemImage: finding.severity.symbol).font(.system(size: 12)).foregroundStyle(finding.severity.color)208 }209 }210 Text("Limitations").font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary).padding(.top, 6)211 ForEach(report.limitations, id: \.self) { Text("• \($0)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true) }212 }213 } else if isBuilding {214 ProgressView().frame(maxWidth: .infinity, minHeight: 160)215 }216 }217 .task(id: "\(kind.rawValue)|\(range.rawValue)|\(Int(incidentDate.timeIntervalSince1970 / 60))|\(settings.includeHostInReports)|\(refresh)") { await build() }218 }219220 private func build() async {221 guard let store = model.store else { return }222 isBuilding = true223 let now = Date()224 let (from, to): (Date, Date) = kind == .incident225 ? (incidentDate.addingTimeInterval(-1800), min(now, incidentDate.addingTimeInterval(1800)))226 : (now.addingTimeInterval(-range.seconds), now)227 var series: [Series] = []228 for metric in kind.metrics { series.append(await store.series(metric, from: from, to: to, maxPoints: 360, now: now)) }229 let events = kind == .incident || kind == .system ? await store.events(kinds: [.alert, .system, .bookmark, .process], from: from, to: to, limit: 100) : []230 let inWindow = model.findings.filter { $0.end >= from && $0.start <= to }231 let inputs = ReportInputs(232 kind: kind, from: from, to: to, samplingInterval: settings.telemetry.interval, system: model.system, includeHostName: settings.includeHostInReports,233 series: series, volumes: model.snapshot?.volumes ?? [], interfaces: model.snapshot?.network?.interfaces ?? [],234 processes: model.processes?.processes ?? [], power: model.snapshot?.power, findings: inWindow, events: events,235 appVersion: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "—")236 report = ReportGenerator.build(inputs, formatter: model.format) { L($0) }237 isBuilding = false238 }239240 private func export(_ format: ReportFormat) {241 guard let report else { return }242 let data: Data243 switch format {244 case .pdf: data = PDFReportRenderer(report: report, formatter: model.format).render()245 case .markdown: data = Data(ReportGenerator.markdown(report, formatter: model.format) { L($0) }.utf8)246 case .csv: data = Data(ReportGenerator.csv(report).utf8)247 case .json: data = (try? ReportGenerator.json(report)) ?? Data()248 }249 let stamp = report.generated.formatted(.iso8601.year().month().day().dateSeparator(.dash))250 let panel = NSSavePanel()251 panel.nameFieldStringValue = "ORIX-Monitor-\(report.kind.rawValue)-\(stamp).\(format.fileExtension)"252 panel.allowedContentTypes = [format.type]253 guard panel.runModal() == .OK, let url = panel.url else { return }254 do {255 try data.write(to: url)256 message = nil257 } catch {258 message = error.localizedDescription259 }260 }261262 private func compare() {263 let panel = NSOpenPanel()264 panel.allowedContentTypes = [.json]265 panel.allowsMultipleSelection = true266 panel.message = L("Choose two JSON reports exported by ORIX Monitor.")267 guard panel.runModal() == .OK else { return }268 guard panel.urls.count == 2 else {269 message = L("Select exactly two reports.")270 return271 }272 let decoder = JSONDecoder()273 decoder.dateDecodingStrategy = .iso8601274 let reports = panel.urls.compactMap { try? decoder.decode(Report.self, from: Data(contentsOf: $0)) }.sorted { $0.from < $1.from }275 guard reports.count == 2 else {276 message = L("One of the files is not an ORIX Monitor report.")277 return278 }279 comparison = ReportGenerator.compare(reports[0], reports[1], formatter: model.format) { L($0) }280 comparisonNames = (model.format.date(reports[0].from), model.format.date(reports[1].from))281 message = comparison?.rows.isEmpty == true ? L("The two reports share no metric.") : nil282 }283}284285struct ReportTableView: View {286 var table: ReportTable287288 var body: some View {289 Grid(alignment: .leading, horizontalSpacing: ORIX.Space.md, verticalSpacing: 5) {290 GridRow { ForEach(Array(table.headers.enumerated()), id: \.offset) { Text($0.element).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary) } }291 ForEach(Array(table.rows.prefix(40).enumerated()), id: \.offset) { _, row in292 GridRow { ForEach(Array(row.enumerated()), id: \.offset) { Text($0.element).font(ORIX.Typeface.value).lineLimit(2).textSelection(.enabled) } }293 }294 }295 }296}297