DomainDig/AuditViews.swift

572 lines · 27844 bytes

  1import SwiftUI
  2
  3struct AuditListView: View {
  4    @Environment(\.appDensity) private var appDensity
  5    @Bindable var viewModel: DomainViewModel
  6    @State private var auditStartInFlight = false
  7
  8    private var groupedSessions: [(domain: String, sessions: [AuditSession])] {
  9        Dictionary(grouping: viewModel.auditSessions) { $0.domain.lowercased() }
 10            .values
 11            .map { sessions in
 12                let sorted = sessions.sorted { $0.createdAt > $1.createdAt }
 13                return (domain: sorted.first?.domain ?? "unknown", sessions: sorted)
 14            }
 15            .sorted { $0.domain < $1.domain }
 16    }
 17
 18    var body: some View {
 19        List {
 20            if groupedSessions.isEmpty {
 21                Section {
 22                    EmptyStateCardView(
 23                        title: "No Audits Yet",
 24                        message: "Audit Mode captures evidence, findings, checklist progress, and point-in-time review output for each domain assessment.",
 25                        suggestion: "Open Inspect for a domain and start an audit to create your first review session.",
 26                        systemImage: "checklist.unchecked",
 27                        showsCardBackground: false
 28                    )
 29                }
 30                .listRowBackground(Color(.appSurface))
 31            } else {
 32                Section("Audit Domains") {
 33                    ForEach(groupedSessions, id: \.domain) { group in
 34                        NavigationLink {
 35                            AuditDomainTimelineView(viewModel: viewModel, domain: group.domain)
 36                        } label: {
 37                            VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing + 2) {
 38                                HStack {
 39                                    Text(group.domain)
 40                                        .font(appDensity.font(.callout, design: .default, weight: .semibold))
 41                                    Spacer()
 42                                    Text("\(group.sessions.count) audit\(group.sessions.count == 1 ? "" : "s")")
 43                                        .font(appDensity.font(.caption2))
 44                                        .foregroundStyle(Color(.appTextSecondary))
 45                                }
 46
 47                                if let latest = group.sessions.first {
 48                                    Text(latest.findings.isEmpty ? "No findings recorded yet" : latest.findings.map(\.title).prefix(2).joined(separator: " • "))
 49                                        .font(appDensity.font(.caption))
 50                                        .foregroundStyle(Color(.appTextSecondary))
 51                                        .lineLimit(2)
 52
 53                                    HStack(spacing: 8) {
 54                                        auditStatusBadge(latest.status)
 55                                        if let severity = latest.highestSeverity {
 56                                            findingSeverityBadge(severity)
 57                                        }
 58                                        Text("Checklist \(latest.completedChecklistCount)/\(latest.checklist.count)")
 59                                            .font(appDensity.font(.caption2))
 60                                            .foregroundStyle(Color(.appTextSecondary))
 61                                    }
 62                                }
 63                            }
 64                            .padding(.vertical, 4)
 65                        }
 66                    }
 67                }
 68                .listRowBackground(Color(.appSurface))
 69            }
 70        }
 71        .scrollContentBackground(.hidden)
 72        .background(Color(.appBackground))
 73        .navigationTitle("Audit Mode")
 74        .toolbar {
 75            if !viewModel.searchedDomain.isEmpty {
 76                ToolbarItem(placement: .topBarTrailing) {
 77                    Button(auditStartInFlight ? "Auditing…" : "Start Audit") {
 78                        Task {
 79                            auditStartInFlight = true
 80                            _ = await viewModel.startAudit(for: viewModel.searchedDomain)
 81                            auditStartInFlight = false
 82                        }
 83                    }
 84                    .disabled(auditStartInFlight)
 85                }
 86            }
 87        }
 88    }
 89}
 90
 91struct AuditDomainTimelineView: View {
 92    @Environment(\.appDensity) private var appDensity
 93    @Bindable var viewModel: DomainViewModel
 94    let domain: String
 95    @State private var auditStartInFlight = false
 96
 97    private var sessions: [AuditSession] {
 98        viewModel.audits(for: domain)
 99    }
100
101    var body: some View {
102        List {
103            Section("Sessions") {
104                ForEach(sessions) { session in
105                    NavigationLink {
106                        AuditSessionDetailView(viewModel: viewModel, sessionID: session.id)
107                    } label: {
108                        VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing + 2) {
109                            HStack {
110                                Text(session.createdAt.formatted(date: .abbreviated, time: .shortened))
111                                    .font(appDensity.font(.callout))
112                                Spacer()
113                                auditStatusBadge(session.status)
114                            }
115
116                            Text("Reviewer: \(session.reviewer)")
117                                .font(appDensity.font(.caption))
118                                .foregroundStyle(Color(.appTextSecondary))
119
120                            HStack(spacing: 8) {
121                                Text("\(session.findings.count) findings")
122                                Text("Checklist \(session.completedChecklistCount)/\(session.checklist.count)")
123                                if let severity = session.highestSeverity {
124                                    Text("Top \(severity.title)")
125                                }
126                            }
127                            .font(appDensity.font(.caption2))
128                            .foregroundStyle(Color(.appTextSecondary))
129                        }
130                        .padding(.vertical, 4)
131                    }
132                }
133            }
134            .listRowBackground(Color(.appSurface))
135
136            Section("Trend") {
137                ForEach(viewModel.auditTimeline(for: domain)) { point in
138                    VStack(alignment: .leading, spacing: 4) {
139                        HStack {
140                            Text(point.createdAt.formatted(date: .abbreviated, time: .shortened))
141                                .font(appDensity.font(.caption, weight: .semibold))
142                            Spacer()
143                            Text("\(point.findingCount) findings")
144                                .font(appDensity.font(.caption2))
145                                .foregroundStyle(Color(.appTextSecondary))
146                        }
147                        Text("Open high severity: \(point.openHighSeverityCount) • Repeated issues: \(point.repeatedIssueCount)")
148                            .font(appDensity.font(.caption2))
149                            .foregroundStyle(Color(.appTextSecondary))
150                    }
151                    .padding(.vertical, 2)
152                }
153            }
154            .listRowBackground(Color(.appSurface))
155        }
156        .scrollContentBackground(.hidden)
157        .background(Color(.appBackground))
158        .navigationTitle(domain)
159        .toolbar {
160            ToolbarItem(placement: .topBarTrailing) {
161                Button(auditStartInFlight ? "Auditing…" : "New Audit") {
162                    Task {
163                        auditStartInFlight = true
164                        _ = await viewModel.startAudit(for: domain)
165                        auditStartInFlight = false
166                    }
167                }
168                .disabled(auditStartInFlight)
169            }
170        }
171    }
172}
173
174struct AuditSessionDetailView: View {
175    @Environment(\.appDensity) private var appDensity
176    @Bindable var viewModel: DomainViewModel
177    let sessionID: UUID
178
179    @State private var notesDraft = ""
180    @State private var showingFindingEditor = false
181    @State private var editingFinding: AuditFinding?
182
183    private var session: AuditSession? {
184        viewModel.auditSession(withID: sessionID)
185    }
186
187    var body: some View {
188        Group {
189            if let session {
190                List {
191                    Section {
192                        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
193                            HStack {
194                                VStack(alignment: .leading, spacing: 4) {
195                                    Text(session.domain)
196                                        .font(appDensity.font(.headline, design: .default, weight: .semibold))
197                                    Text("Reviewer: \(session.reviewer)")
198                                        .font(appDensity.font(.caption))
199                                        .foregroundStyle(Color(.appTextSecondary))
200                                }
201                                Spacer()
202                                auditStatusBadge(session.status)
203                            }
204
205                            Picker("Status", selection: Binding(
206                                get: { session.status },
207                                set: { viewModel.updateAuditStatus($0, sessionID: session.id) }
208                            )) {
209                                ForEach(AuditStatus.allCases) { status in
210                                    Text(status.title).tag(status)
211                                }
212                            }
213                            .pickerStyle(.segmented)
214
215                            Text("Captured \(session.evidence.capturedAt.formatted(date: .abbreviated, time: .shortened))")
216                                .font(appDensity.font(.caption2))
217                                .foregroundStyle(Color(.appTextSecondary))
218                        }
219                    }
220                    .listRowBackground(Color(.appSurface))
221
222                    Section("Audit Summary") {
223                        LabeledContent("Findings", value: "\(session.findings.count)")
224                        LabeledContent("Checklist", value: "\(session.completedChecklistCount)/\(session.checklist.count)")
225                        LabeledContent("Risk Score", value: "\(session.evidence.report.riskAssessment.score)")
226                        if let severity = session.highestSeverity {
227                            LabeledContent("Highest Severity", value: severity.title)
228                        }
229                    }
230                    .listRowBackground(Color(.appSurface))
231
232                    Section("Reviewer Notes") {
233                        TextEditor(text: $notesDraft)
234                            .frame(minHeight: 120)
235                            .scrollContentBackground(.hidden)
236                            .background(Color.clear)
237
238                        Button("Save Notes") {
239                            viewModel.updateAuditNotes(notesDraft, sessionID: session.id)
240                        }
241                    }
242                    .listRowBackground(Color(.appSurface))
243
244                    Section("Checklist") {
245                        ForEach(session.checklist) { item in
246                            Button {
247                                viewModel.toggleAuditChecklistItem(sessionID: session.id, itemID: item.id)
248                            } label: {
249                                HStack(alignment: .top, spacing: 10) {
250                                    Image(systemName: item.isComplete ? "checkmark.circle.fill" : "circle")
251                                        .foregroundStyle(item.isComplete ? Color(.statusPositive) : .secondary)
252                                    VStack(alignment: .leading, spacing: 4) {
253                                        Text(item.title)
254                                            .font(appDensity.font(.callout))
255                                            .foregroundStyle(.primary)
256                                        Text(item.detail)
257                                            .font(appDensity.font(.caption))
258                                            .foregroundStyle(Color(.appTextSecondary))
259                                    }
260                                    Spacer()
261                                }
262                            }
263                            .buttonStyle(.plain)
264                            .accessibilityAddTraits(item.isComplete ? .isSelected : [])
265                            .accessibilityHint(item.isComplete ? "Marks incomplete" : "Marks complete")
266                        }
267                    }
268                    .listRowBackground(Color(.appSurface))
269
270                    Section("Findings") {
271                        if session.findings.isEmpty {
272                            Text("No findings recorded.")
273                                .font(appDensity.font(.caption))
274                                .foregroundStyle(Color(.appTextSecondary))
275                        } else {
276                            ForEach(session.findings) { finding in
277                                Button {
278                                    editingFinding = finding
279                                } label: {
280                                    VStack(alignment: .leading, spacing: 6) {
281                                        HStack {
282                                            Text(finding.title)
283                                                .font(appDensity.font(.callout, design: .default, weight: .semibold))
284                                                .foregroundStyle(.primary)
285                                            Spacer()
286                                            findingSeverityBadge(finding.severity)
287                                        }
288                                        Text(finding.summary)
289                                            .font(appDensity.font(.caption))
290                                            .foregroundStyle(Color(.appTextSecondary))
291                                            .lineLimit(2)
292                                        Text("\(finding.status.title) • \(finding.evidenceReferences.count) evidence refs")
293                                            .font(appDensity.font(.caption2))
294                                            .foregroundStyle(Color(.appTextSecondary))
295                                    }
296                                    .padding(.vertical, 2)
297                                }
298                                .buttonStyle(.plain)
299                            }
300                            .onDelete { offsets in
301                                viewModel.removeAuditFindings(at: offsets, sessionID: session.id)
302                            }
303                        }
304                    }
305                    .listRowBackground(Color(.appSurface))
306
307                    Section("Evidence Snapshot") {
308                        LabeledContent("Availability", value: availabilityTitle(session.evidence.report.availability))
309                        LabeledContent("Primary IP", value: session.evidence.report.dns.primaryIP ?? "Unavailable")
310                        LabeledContent("TLS", value: session.evidence.report.web.tlsStatus)
311                        LabeledContent("Final URL", value: session.evidence.report.web.finalURL ?? "Unavailable")
312                        LabeledContent("Reachability", value: session.evidence.report.network.reachabilitySummary)
313                        LabeledContent("Registrar", value: session.evidence.report.ownership?.registrar ?? "Unavailable")
314                    }
315                    .listRowBackground(Color(.appSurface))
316
317                    if !session.evidence.historicalContext.isEmpty {
318                        Section("Historical Context") {
319                            ForEach(session.evidence.historicalContext) { entry in
320                                VStack(alignment: .leading, spacing: 4) {
321                                    Text(entry.timestamp.formatted(date: .abbreviated, time: .shortened))
322                                        .font(appDensity.font(.caption, weight: .semibold))
323                                    Text(entry.changeSummaryMessage ?? "No change summary")
324                                        .font(appDensity.font(.caption2))
325                                        .foregroundStyle(Color(.appTextSecondary))
326                                }
327                            }
328                        }
329                        .listRowBackground(Color(.appSurface))
330                    }
331
332                    Section("Audit Timeline") {
333                        ForEach(viewModel.auditTimeline(for: session.domain)) { point in
334                            VStack(alignment: .leading, spacing: 4) {
335                                HStack {
336                                    Text(point.createdAt.formatted(date: .abbreviated, time: .shortened))
337                                        .font(appDensity.font(.caption, weight: .semibold))
338                                    Spacer()
339                                    Text(point.status.title)
340                                        .font(appDensity.font(.caption2))
341                                        .foregroundStyle(Color(.appTextSecondary))
342                                }
343                                Text("Findings \(point.findingCount) • Open high \(point.openHighSeverityCount) • Repeated \(point.repeatedIssueCount)")
344                                    .font(appDensity.font(.caption2))
345                                    .foregroundStyle(Color(.appTextSecondary))
346                            }
347                        }
348                    }
349                    .listRowBackground(Color(.appSurface))
350                }
351                .scrollContentBackground(.hidden)
352                .background(Color(.appBackground))
353                .navigationTitle("Audit Session")
354                .toolbar {
355                    ToolbarItemGroup(placement: .topBarTrailing) {
356                        Button("Add Finding") {
357                            editingFinding = nil
358                            showingFindingEditor = true
359                        }
360                        Menu("Export") {
361                            ForEach(AuditExportFormat.allCases) { format in
362                                Button("Export \(format.fileExtension.uppercased())") {
363                                    guard let data = viewModel.exportAuditData(sessionID: session.id, format: format) else { return }
364                                    ExportPresenter.share(
365                                        filename: "\(session.domain)-audit-\(session.createdAt.ISO8601Format()).\(format.fileExtension)",
366                                        data: data
367                                    )
368                                }
369                            }
370                        }
371                    }
372                }
373                .onAppear {
374                    notesDraft = session.notes
375                }
376                .onChange(of: session.notes) { _, newValue in
377                    notesDraft = newValue
378                }
379                .sheet(isPresented: $showingFindingEditor) {
380                    AuditFindingEditorView(
381                        existingFinding: nil,
382                        session: session
383                    ) { draft in
384                        viewModel.addAuditFinding(
385                            sessionID: session.id,
386                            title: draft.title,
387                            severity: draft.severity,
388                            summary: draft.summary,
389                            evidenceReferences: draft.evidenceReferences,
390                            notes: draft.notes,
391                            checklistAreas: draft.checklistAreas
392                        )
393                    }
394                }
395                .sheet(item: $editingFinding) { finding in
396                    AuditFindingEditorView(existingFinding: finding, session: session) { updated in
397                        viewModel.updateAuditFinding(updated, sessionID: session.id)
398                    }
399                }
400            } else {
401                ContentUnavailableView("Audit Session Missing", systemImage: "exclamationmark.triangle")
402                    .background(Color(.appBackground))
403            }
404        }
405    }
406}
407
408private struct AuditFindingEditorView: View {
409    @Environment(\.dismiss) private var dismiss
410
411    let existingFinding: AuditFinding?
412    let session: AuditSession
413    let onSave: (AuditFinding) -> Void
414
415    @State private var title: String
416    @State private var severity: AuditFindingSeverity
417    @State private var summary: String
418    @State private var evidenceReferencesText: String
419    @State private var notes: String
420    @State private var status: AuditFindingStatus
421    @State private var selectedAreas: Set<AuditChecklistArea>
422
423    init(existingFinding: AuditFinding?, session: AuditSession, onSave: @escaping (AuditFinding) -> Void) {
424        self.existingFinding = existingFinding
425        self.session = session
426        self.onSave = onSave
427        _title = State(initialValue: existingFinding?.title ?? "")
428        _severity = State(initialValue: existingFinding?.severity ?? .medium)
429        _summary = State(initialValue: existingFinding?.summary ?? "")
430        _evidenceReferencesText = State(initialValue: existingFinding?.evidenceReferences.joined(separator: "\n") ?? "")
431        _notes = State(initialValue: existingFinding?.notes ?? "")
432        _status = State(initialValue: existingFinding?.status ?? .open)
433        _selectedAreas = State(initialValue: Set(existingFinding?.checklistAreas ?? []))
434    }
435
436    var body: some View {
437        NavigationStack {
438            Form {
439                Section("Finding") {
440                    TextField("Title", text: $title)
441                    Picker("Severity", selection: $severity) {
442                        ForEach(AuditFindingSeverity.allCases) { severity in
443                            Text(severity.title).tag(severity)
444                        }
445                    }
446                    Picker("Status", selection: $status) {
447                        ForEach(AuditFindingStatus.allCases) { status in
448                            Text(status.title).tag(status)
449                        }
450                    }
451                    TextField("Summary", text: $summary, axis: .vertical)
452                        .lineLimit(3...6)
453                }
454
455                Section("Evidence References") {
456                    TextField("One reference per line", text: $evidenceReferencesText, axis: .vertical)
457                        .lineLimit(4...8)
458                    if !session.evidence.screenshots.isEmpty {
459                        ForEach(session.evidence.screenshots) { asset in
460                            Text("\(asset.title): \(asset.reference)")
461                                .font(.caption)
462                                .foregroundStyle(Color(.appTextSecondary))
463                        }
464                    }
465                }
466
467                Section("Checklist Areas") {
468                    ForEach(AuditChecklistArea.allCases) { area in
469                        Button {
470                            if selectedAreas.contains(area) {
471                                selectedAreas.remove(area)
472                            } else {
473                                selectedAreas.insert(area)
474                            }
475                        } label: {
476                            HStack {
477                                Text(area.title)
478                                Spacer()
479                                Image(systemName: selectedAreas.contains(area) ? "checkmark.circle.fill" : "circle")
480                                    .foregroundStyle(selectedAreas.contains(area) ? Color(.statusPositive) : .secondary)
481                            }
482                        }
483                        .buttonStyle(.plain)
484                        .accessibilityAddTraits(selectedAreas.contains(area) ? .isSelected : [])
485                    }
486                }
487
488                Section("Notes") {
489                    TextField("Optional notes", text: $notes, axis: .vertical)
490                        .lineLimit(4...8)
491                }
492            }
493            .navigationTitle(existingFinding == nil ? "New Finding" : "Edit Finding")
494            .toolbar {
495                ToolbarItem(placement: .cancellationAction) {
496                    Button("Cancel") {
497                        dismiss()
498                    }
499                }
500                ToolbarItem(placement: .confirmationAction) {
501                    Button("Save") {
502                        onSave(
503                            AuditFinding(
504                                id: existingFinding?.id ?? UUID(),
505                                title: title.trimmingCharacters(in: .whitespacesAndNewlines),
506                                severity: severity,
507                                summary: summary.trimmingCharacters(in: .whitespacesAndNewlines),
508                                evidenceReferences: evidenceReferencesText
509                                    .split(separator: "\n")
510                                    .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) }
511                                    .filter { !$0.isEmpty },
512                                notes: notes.trimmingCharacters(in: .whitespacesAndNewlines),
513                                status: status,
514                                checklistAreas: Array(selectedAreas).sorted { $0.title < $1.title },
515                                createdAt: existingFinding?.createdAt ?? Date(),
516                                updatedAt: Date()
517                            )
518                        )
519                        dismiss()
520                    }
521                    .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || summary.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
522                }
523            }
524        }
525    }
526}
527
528private func auditStatusBadge(_ status: AuditStatus) -> some View {
529    let model: AppStatusBadgeModel
530    switch status {
531    case .draft:
532        model = .init(title: "Draft", systemImage: "square.and.pencil", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarningSurface))
533    case .inReview:
534        model = .init(title: "In Review", systemImage: "doc.text.magnifyingglass", foregroundColor: Color(.statusInfo), backgroundColor: Color(.statusInfoSurface))
535    case .complete:
536        model = .init(title: "Complete", systemImage: "checkmark.seal.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositiveSurface))
537    }
538    return AppStatusBadgeView(model: model)
539}
540
541private func findingSeverityBadge(_ severity: AuditFindingSeverity) -> some View {
542    let tone: AppStatusTone
543    switch severity {
544    case .informational:
545        tone = .neutral
546    case .low:
547        tone = .positive
548    case .medium:
549        tone = .warning
550    case .high:
551        tone = .critical
552    }
553    return AppStatusBadgeView(
554        model: .init(
555            title: severity.title,
556            systemImage: "exclamationmark.circle.fill",
557            foregroundColor: tone.foreground,
558            backgroundColor: tone.surface
559        )
560    )
561}
562
563private func availabilityTitle(_ status: DomainAvailabilityStatus) -> String {
564    switch status {
565    case .available:
566        return "Available"
567    case .registered:
568        return "Registered"
569    case .unknown:
570        return "Unknown"
571    }
572}