SPB Git

Repository Public License

ReportsView.swift 11.4 KB 231 lines swift

1// ORIX Secure2// File: App/Sources/Features/Reports/ReportsView.swift3// Description: Saved reports and history: list, read, export as PDF / Markdown / JSON / plain text (optionally redacted), delete.4//              Reports stay on the device until the user exports one.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDesign9import ORIXReporting10import ORIXSecureModel11import SwiftUI1213extension ReportDocument.Kind {14    var systemImage: String {15        switch self {16        case .securityAssessment: "checkmark.shield"17        case .privacyAudit: "hand.raised"18        case .storage: "internaldrive"19        case .cleanup: "photo.stack"20        case .network: "network"21        case .urlAnalysis: "link"22        case .fileInspection: "doc.text.magnifyingglass"23        case .device: "iphone"24        case .investigation: "magnifyingglass"25        case .workflow: "point.3.connected.trianglepath.dotted"26        }27    }28}2930struct ReportRow: View {31    let report: ReportSummary32    var body: some View {33        HStack(spacing: ORIX.Space.sm) {34            ORIXGlyph(report.kind.systemImage)35            VStack(alignment: .leading, spacing: 2) {36                Text(verbatim: report.title).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary).multilineTextAlignment(.leading).lineLimit(2)37                Text(verbatim: report.createdAt.formatted(date: .abbreviated, time: .shortened)).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)38            }39            Spacer(minLength: 0)40            if report.attentionCount > 0 {41                ORIXChip(Text(verbatim: "\(report.attentionCount)"), systemName: "exclamationmark.triangle.fill", tint: ORIX.Palette.warning)42                    .accessibilityLabel(Text("\(report.attentionCount) need attention"))43            }44            Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)45        }46        .padding(.vertical, 6)47        .contentShape(Rectangle())48        .accessibilityElement(children: .combine)49        .accessibilityAddTraits(.isButton)50    }51}5253struct ReportsView: View {54    @Environment(AppModel.self) private var model55    @Environment(Router.self) private var router56    @Environment(\.horizontalSizeClass) private var sizeClass57    @State private var confirmDeleteAll = false58    @State private var filter: ReportDocument.Kind?5960    var body: some View {61        let all = model.store.reports()62        let reports = filter.map { kind in all.filter { $0.kind == kind } } ?? all63        Group {64            if all.isEmpty {65                ORIXEmptyState(systemName: "doc.richtext", title: "No reports yet",66                               message: "Save an assessment, a cleanup or an investigation and it appears here. Reports stay on this device until you export one.") {67                    Button { router.open(.securityAudit) } label: { Text("Open Security Audit") }.buttonStyle(.orixPrimary).frame(maxWidth: 280)68                        .accessibilityIdentifier("reports.openAudit")69                }70                .background(ORIX.Palette.canvas.ignoresSafeArea())71                .accessibilityIdentifier("reports.empty")72            } else {73                List {74                    Section {75                        ForEach(reports) { report in76                            Button { router.push(.report(report.id)) } label: { ReportRow(report: report) }77                                .buttonStyle(.plain)78                                .swipeActions { Button("Delete", role: .destructive) { model.store.deleteReport(report.id) } }79                                .accessibilityIdentifier("report.row")80                        }81                    } footer: {82                        Text("\(reports.count) report(s), stored on this device under iOS Data Protection.")83                    }84                }85                .scrollContentBackground(.hidden)86                .background(ORIX.Palette.canvas.ignoresSafeArea())87            }88        }89        .navigationTitle("Reports")90        .toolbar {91            ToolbarItemGroup(placement: .topBarTrailing) {92                if !all.isEmpty {93                    Menu {94                        Picker("Kind", selection: $filter) {95                            Text("All reports").tag(ReportDocument.Kind?.none)96                            ForEach(Array(Set(all.map(\.kind))).sorted { $0.rawValue < $1.rawValue }, id: \.self) { kind in97                                Text(verbatim: kind.title).tag(ReportDocument.Kind?.some(kind))98                            }99                        }100                        Divider()101                        Button("Delete All Reports", systemImage: "trash", role: .destructive) { confirmDeleteAll = true }102                    } label: { Label("More", systemImage: "ellipsis.circle") }103                        .accessibilityIdentifier("reports.menu")104                }105                if sizeClass != .regular {106                    Button { router.push(.destination(.settings)) } label: { Label("Settings", systemImage: "gearshape") }107                        .accessibilityIdentifier("reports.settings")108                }109            }110        }111        .confirmationDialog("Delete all reports?", isPresented: $confirmDeleteAll, titleVisibility: .visible) {112            Button("Delete \(all.count) Report(s)", role: .destructive) { model.store.deleteAllReports() }113        } message: { Text("This cannot be undone. Exported copies are not affected.") }114        .accessibilityIdentifier("reports")115    }116}117118struct ReportDetailView: View {119    let reportID: UUID120    @Environment(AppModel.self) private var model121    @Environment(AppSettings.self) private var settings122    @Environment(\.dismiss) private var dismiss123    @State private var share: ShareItem?124    @State private var exportError: String?125    @State private var confirmDelete = false126127    var body: some View {128        Group {129            if let report = model.store.report(reportID) {130                ReportContentView(report: report)131                    .toolbar {132                        ToolbarItemGroup(placement: .topBarTrailing) {133                            Menu {134                                Section(settings.redactExports ? "Exported with identifiers masked" : "Exported as shown") {135                                    ForEach(ReportFormat.allCases) { format in136                                        Button { export(report, as: format) } label: { Label { Text(verbatim: format.title) } icon: { Image(systemName: format.systemImage) } }137                                            .accessibilityIdentifier("export." + format.rawValue)138                                    }139                                }140                            } label: { Label("Export", systemImage: "square.and.arrow.up") }141                                .accessibilityIdentifier("report.export")142                            Button(role: .destructive) { confirmDelete = true } label: { Label("Delete", systemImage: "trash") }143                                .accessibilityIdentifier("report.delete")144                        }145                    }146            } else {147                ORIXEmptyState(systemName: "doc.questionmark", title: "Report not found", message: "It may have been deleted.")148            }149        }150        .navigationBarTitleDisplayMode(.inline)151        .sheet(item: $share) { ActivityView(item: $0) }152        .alert("Export failed", isPresented: Binding(get: { exportError != nil }, set: { if !$0 { exportError = nil } })) {153            Button("OK", role: .cancel) {}154        } message: { Text(verbatim: exportError ?? "") }155        .confirmationDialog("Delete this report?", isPresented: $confirmDelete, titleVisibility: .visible) {156            Button("Delete Report", role: .destructive) { model.store.deleteReport(reportID); dismiss() }157        }158    }159160    private func export(_ report: ReportDocument, as format: ReportFormat) {161        do {162            let document = settings.redactExports ? report.redacted(.all) : report163            try FileManager.default.createDirectory(at: AppFolders.exports, withIntermediateDirectories: true)164            let url = try ReportGenerator().export(document, as: format, to: AppFolders.exports)165            share = ShareItem(urls: [url])166        } catch {167            exportError = error.localizedDescription168        }169    }170}171172extension ReportFormat {173    var systemImage: String {174        switch self {175        case .pdf: "doc.richtext"176        case .markdown: "text.badge.checkmark"177        case .json: "curlybraces"178        case .plainText: "doc.plaintext"179        }180    }181}182183/// A report rendered natively, with the same content the exports carry.184struct ReportContentView: View {185    let report: ReportDocument186187    var body: some View {188        ScreenScroll {189            VStack(alignment: .leading, spacing: ORIX.Space.xs) {190                ORIXChip(Text(verbatim: report.kind.title), systemName: report.kind.systemImage, tint: ORIXAccent.secure.primary)191                Text(verbatim: report.title).font(.orixTitle).foregroundStyle(ORIX.Palette.textPrimary)192                Text(verbatim: "\(report.createdAt.formatted(date: .long, time: .shortened)) · \(report.generator)")193                    .font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)194                Text(verbatim: report.summary).font(.orixBody).foregroundStyle(ORIX.Palette.textSecondary)195            }196            ForEach(report.sections) { section in197                if !(section.paragraphs.isEmpty && section.facts.isEmpty && section.findings.isEmpty && section.bullets.isEmpty) {198                    Text(verbatim: section.title).font(.orixTitle).foregroundStyle(ORIX.Palette.textPrimary).accessibilityAddTraits(.isHeader)199                    ForEach(section.paragraphs, id: \.self) { Text(verbatim: $0).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary) }200                    if !section.facts.isEmpty {201                        VStack(spacing: 0) {202                            ForEach(Array(section.facts.enumerated()), id: \.offset) { index, fact in203                                ReadingRow(label: fact.label, value: .measured(fact.value))204                                if index < section.facts.count - 1 { Divider() }205                            }206                        }207                        .orixCard(padding: ORIX.Space.sm)208                    }209                    if !section.findings.isEmpty { FindingList(findings: section.findings) }210                    if !section.bullets.isEmpty {211                        VStack(alignment: .leading, spacing: ORIX.Space.sm) {212                            ForEach(section.bullets, id: \.self) { bullet in213                                Label { Text(verbatim: bullet) } icon: { Image(systemName: "circle.fill").font(.system(size: 5)) }214                                    .font(.orixCallout).foregroundStyle(ORIX.Palette.textPrimary)215                            }216                        }217                        .frame(maxWidth: .infinity, alignment: .leading)218                        .orixCard()219                    }220                }221            }222            if !report.unavailable.isEmpty {223                LimitsCard(title: "Checks that could not be made", items: report.unavailable)224            }225            Text(verbatim: ReportGenerator.closingStatement).font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)226        }227        .navigationTitle(Text(verbatim: report.kind.title))228        .accessibilityIdentifier("report.detail")229    }230}231
Files main
Menu

Theme