DomainDig/IntegrationsView.swift

530 lines · 21454 bytes

  1import SwiftUI
  2
  3struct IntegrationsSettingsView: View {
  4    @State private var integrationService = IntegrationService.shared
  5    @State private var editingTarget: IntegrationTarget?
  6    @State private var showingCreateSheet = false
  7
  8    var body: some View {
  9        List {
 10            Section("Overview") {
 11                LabeledContent("Integrations", value: "\(integrationService.targets.count)")
 12                LabeledContent("Queued Deliveries", value: "\(integrationService.queue.count)")
 13                LabeledContent("Recent Log Entries", value: "\(integrationService.deliveryRecords.count)")
 14
 15                if let statusMessage = integrationService.statusMessage {
 16                    Text(statusMessage)
 17                        .font(.caption)
 18                        .foregroundStyle(Color(.appTextSecondary))
 19                }
 20
 21                Button("Process Queue Now") {
 22                    integrationService.processQueueNow()
 23                }
 24            }
 25
 26            Section("Targets") {
 27                if integrationService.targets.isEmpty {
 28                    Text("No integrations configured.")
 29                        .foregroundStyle(Color(.appTextSecondary))
 30                } else {
 31                    ForEach(integrationService.targets) { target in
 32                        NavigationLink {
 33                            IntegrationDetailView(
 34                                integrationID: target.id,
 35                                onEdit: {
 36                                    editingTarget = target
 37                                }
 38                            )
 39                        } label: {
 40                            VStack(alignment: .leading, spacing: 4) {
 41                                HStack {
 42                                    Text(target.name)
 43                                    Spacer()
 44                                    Text(target.type.title)
 45                                        .foregroundStyle(Color(.appTextSecondary))
 46                                }
 47
 48                                Text(summary(for: target))
 49                                    .font(.caption)
 50                                    .foregroundStyle(Color(.appTextSecondary))
 51
 52                                if !target.isEnabled {
 53                                    Text("Disabled")
 54                                        .font(.caption2)
 55                                        .foregroundStyle(Color(.statusWarning))
 56                                }
 57                            }
 58                        }
 59                    }
 60                }
 61
 62                Button("Add Integration") {
 63                    showingCreateSheet = true
 64                }
 65            }
 66        }
 67        .navigationTitle("Integrations")
 68        .sheet(isPresented: $showingCreateSheet) {
 69            NavigationStack {
 70                IntegrationEditorView(existingTarget: nil)
 71            }
 72        }
 73        .sheet(item: $editingTarget) { target in
 74            NavigationStack {
 75                IntegrationEditorView(existingTarget: target)
 76            }
 77        }
 78        .onAppear {
 79            integrationService.refresh()
 80        }
 81    }
 82
 83    private func summary(for target: IntegrationTarget) -> String {
 84        switch target.configuration {
 85        case .webhook(let configuration):
 86            return configuration.endpointDisplayHost.isEmpty ? "Webhook" : configuration.endpointDisplayHost
 87        case .slack(let configuration):
 88            return configuration.destinationLabel
 89        case .email(let configuration):
 90            return configuration.recipientAddresses.joined(separator: ", ")
 91        }
 92    }
 93}
 94
 95private struct IntegrationDetailView: View {
 96    @Environment(\.dismiss) private var dismiss
 97    @State private var integrationService = IntegrationService.shared
 98
 99    let integrationID: UUID
100    let onEdit: () -> Void
101
102    private var target: IntegrationTarget? {
103        integrationService.targets.first(where: { $0.id == integrationID })
104    }
105
106    var body: some View {
107        List {
108            if let target {
109                Section("Configuration") {
110                    LabeledContent("Type", value: target.type.title)
111                    LabeledContent("Status", value: target.isEnabled ? "Enabled" : "Disabled")
112                    LabeledContent("Destination", value: destination(for: target))
113                    LabeledContent("Minimum Severity", value: target.filters.minimumSeverity.title)
114                    if !target.filters.domains.isEmpty {
115                        LabeledContent("Domains", value: target.filters.domains.joined(separator: ", "))
116                    }
117                }
118
119                Section("Actions") {
120                    Button("Edit Integration") {
121                        onEdit()
122                    }
123
124                    Button("Send Test Event") {
125                        integrationService.sendTest(for: target.id)
126                    }
127
128                    Button(target.isEnabled ? "Disable" : "Enable") {
129                        integrationService.setEnabled(!target.isEnabled, for: target.id)
130                    }
131
132                    Button("Delete Integration", role: .destructive) {
133                        integrationService.delete(targetID: target.id)
134                        dismiss()
135                    }
136                }
137
138                Section("Delivery Log") {
139                    if integrationService.deliveryRecords(for: target.id).isEmpty {
140                        Text("No deliveries yet.")
141                            .foregroundStyle(Color(.appTextSecondary))
142                    } else {
143                        ForEach(integrationService.deliveryRecords(for: target.id), id: \.id) { record in
144                            VStack(alignment: .leading, spacing: 4) {
145                                HStack {
146                                    Text(record.status.title)
147                                    Spacer()
148                                    Text(record.timestamp.formatted(date: .abbreviated, time: .shortened))
149                                        .font(.caption)
150                                        .foregroundStyle(Color(.appTextSecondary))
151                                }
152
153                                Text(record.summary)
154                                    .font(.subheadline)
155
156                                Text(record.destination)
157                                    .font(.caption)
158                                    .foregroundStyle(Color(.appTextSecondary))
159
160                                if let failureReason = record.failureReason {
161                                    let failureColor: Color = record.status == .skipped ? .secondary : Color(.statusCritical)
162                                    Text(failureReason)
163                                        .font(.caption)
164                                        .foregroundStyle(failureColor)
165                                }
166                            }
167                        }
168                    }
169                }
170            } else {
171                Text("Integration not found.")
172                    .foregroundStyle(Color(.appTextSecondary))
173            }
174        }
175        .navigationTitle(target?.name ?? "Integration")
176    }
177
178    private func destination(for target: IntegrationTarget) -> String {
179        switch target.configuration {
180        case .webhook(let configuration):
181            return configuration.endpointDisplayHost
182        case .slack(let configuration):
183            return configuration.destinationLabel
184        case .email(let configuration):
185            return configuration.recipientAddresses.joined(separator: ", ")
186        }
187    }
188}
189
190private struct IntegrationEditorView: View {
191    @Environment(\.dismiss) private var dismiss
192    @State private var integrationService = IntegrationService.shared
193
194    let existingTarget: IntegrationTarget?
195
196    @State private var type: IntegrationType = .webhook
197    @State private var name: String = ""
198    @State private var isEnabled = true
199    @State private var minimumSeverity: EventSeverity = .warning
200    @State private var selectedEventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.allCases.filter { $0 != .test })
201    @State private var domainsText = ""
202
203    @State private var webhookURL = ""
204    @State private var slackWebhookURL = ""
205    @State private var emailHost = ""
206    @State private var emailPort = "465"
207    @State private var emailUsername = ""
208    @State private var emailPassword = ""
209    @State private var senderAddress = ""
210    @State private var recipientAddresses = ""
211    @State private var smtpSecurity: SMTPSecurityMode = .directTLS
212
213    @State private var validationMessage: String?
214
215    var body: some View {
216        Form {
217            Section("Integration") {
218                Picker("Type", selection: $type) {
219                    ForEach(IntegrationType.allCases) { integrationType in
220                        Text(integrationType.title).tag(integrationType)
221                    }
222                }
223                .disabled(existingTarget != nil)
224
225                TextField("Name", text: $name)
226                Toggle("Enabled", isOn: $isEnabled)
227            }
228
229            Section("Routing Rules") {
230                Picker("Minimum Severity", selection: $minimumSeverity) {
231                    ForEach(EventSeverity.allCases) { severity in
232                        Text(severity.title).tag(severity)
233                    }
234                }
235
236                TextField("Domains (comma-separated)", text: $domainsText)
237                    .textInputAutocapitalization(.never)
238                    .autocorrectionDisabled()
239
240                ForEach(MonitoringEventType.allCases.filter { $0 != .test }, id: \.self) { eventType in
241                    Toggle(
242                        eventType.title,
243                        isOn: Binding(
244                            get: { selectedEventTypes.contains(eventType) },
245                            set: { isSelected in
246                                if isSelected {
247                                    selectedEventTypes.insert(eventType)
248                                } else {
249                                    selectedEventTypes.remove(eventType)
250                                }
251                            }
252                        )
253                    )
254                }
255            }
256
257            switch type {
258            case .webhook:
259                Section("Webhook") {
260                    TextField("https://example.com/webhook", text: $webhookURL)
261                        .textInputAutocapitalization(.never)
262                        .autocorrectionDisabled()
263                        .keyboardType(.URL)
264
265                    if existingTarget != nil {
266                        Text("Saved webhook URL remains in Keychain unless you replace it.")
267                            .font(.caption)
268                            .foregroundStyle(Color(.appTextSecondary))
269                    }
270                }
271            case .slack:
272                Section("Slack") {
273                    TextField("https://hooks.slack.com/services/...", text: $slackWebhookURL)
274                        .textInputAutocapitalization(.never)
275                        .autocorrectionDisabled()
276                        .keyboardType(.URL)
277
278                    if existingTarget != nil {
279                        Text("Saved Slack webhook remains in Keychain unless you replace it.")
280                            .font(.caption)
281                            .foregroundStyle(Color(.appTextSecondary))
282                    }
283                }
284            case .email:
285                Section("SMTP") {
286                    TextField("SMTP Host", text: $emailHost)
287                        .textInputAutocapitalization(.never)
288                        .autocorrectionDisabled()
289
290                    TextField("Port", text: $emailPort)
291                        .keyboardType(.numberPad)
292
293                    Text("Port 465 with Direct TLS is supported. Port 587 (STARTTLS) is not.")
294                        .font(.caption)
295                        .foregroundStyle(Color(.appTextSecondary))
296
297                    TextField("Username", text: $emailUsername)
298                        .textInputAutocapitalization(.never)
299                        .autocorrectionDisabled()
300
301                    SecureField(existingTarget == nil ? "Password" : "Replace Password", text: $emailPassword)
302
303                    TextField("Sender Address", text: $senderAddress)
304                        .textInputAutocapitalization(.never)
305                        .autocorrectionDisabled()
306                        .keyboardType(.emailAddress)
307
308                    TextField("Recipients (comma-separated)", text: $recipientAddresses)
309                        .textInputAutocapitalization(.never)
310                        .autocorrectionDisabled()
311                        .keyboardType(.emailAddress)
312
313                    Picker("Security", selection: $smtpSecurity) {
314                        ForEach(SMTPSecurityMode.allCases) { mode in
315                            Text(mode.title).tag(mode)
316                        }
317                    }
318
319                    if existingTarget != nil {
320                        Text("Saved SMTP password remains in Keychain unless you replace it.")
321                            .font(.caption)
322                            .foregroundStyle(Color(.appTextSecondary))
323                    }
324                }
325            }
326
327            if let validationMessage {
328                Section {
329                    Text(validationMessage)
330                        .font(.caption)
331                        .foregroundStyle(Color(.statusCritical))
332                }
333            }
334        }
335        .navigationTitle(existingTarget == nil ? "Add Integration" : "Edit Integration")
336        .toolbar {
337            ToolbarItem(placement: .cancellationAction) {
338                Button("Cancel") {
339                    dismiss()
340                }
341            }
342
343            ToolbarItem(placement: .confirmationAction) {
344                Button("Save") {
345                    save()
346                }
347            }
348        }
349        .onAppear {
350            populateFromExisting()
351        }
352    }
353
354    private func populateFromExisting() {
355        guard let existingTarget else { return }
356        type = existingTarget.type
357        name = existingTarget.name
358        isEnabled = existingTarget.isEnabled
359        minimumSeverity = existingTarget.filters.minimumSeverity
360        selectedEventTypes = existingTarget.filters.eventTypes
361        domainsText = existingTarget.filters.domains.joined(separator: ", ")
362
363        switch existingTarget.configuration {
364        case .webhook:
365            break
366        case .slack:
367            break
368        case .email(let configuration):
369            emailHost = configuration.smtpHost
370            emailPort = String(configuration.port)
371            emailUsername = configuration.username
372            senderAddress = configuration.senderAddress
373            recipientAddresses = configuration.recipientAddresses.joined(separator: ", ")
374            smtpSecurity = configuration.securityMode
375        }
376    }
377
378    private func save() {
379        validationMessage = nil
380
381        let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
382        guard !trimmedName.isEmpty else {
383            validationMessage = "Name is required."
384            return
385        }
386
387        let filters = IntegrationFilterSet(
388            minimumSeverity: minimumSeverity,
389            eventTypes: selectedEventTypes,
390            domains: domainsText
391                .split(separator: ",")
392                .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
393                .filter { !$0.isEmpty }
394        )
395
396        let targetID = existingTarget?.id ?? UUID()
397
398        do {
399            switch type {
400            case .webhook:
401                let existingReference: String? = {
402                    guard case .webhook(let configuration) = existingTarget?.configuration else { return nil }
403                    return configuration.credentialReference
404                }()
405                if webhookURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existingReference == nil {
406                    validationMessage = "Webhook URL is required."
407                    return
408                }
409
410                let target = IntegrationTarget(
411                    id: targetID,
412                    type: .webhook,
413                    name: trimmedName,
414                    isEnabled: isEnabled,
415                    configuration: .webhook(
416                        WebhookIntegrationConfiguration(
417                            endpointDisplayHost: existingWebhookDisplayHost(),
418                            timeoutSeconds: 15,
419                            additionalHeaders: [:],
420                            credentialReference: existingReference
421                        )
422                    ),
423                    filters: filters
424                )
425                try integrationService.upsert(
426                    target: target,
427                    webhookURL: webhookURL.nilIfBlank
428                )
429            case .slack:
430                let existingReference: String? = {
431                    guard case .slack(let configuration) = existingTarget?.configuration else { return nil }
432                    return configuration.credentialReference
433                }()
434                if slackWebhookURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existingReference == nil {
435                    validationMessage = "Slack webhook URL is required."
436                    return
437                }
438
439                let target = IntegrationTarget(
440                    id: targetID,
441                    type: .slack,
442                    name: trimmedName,
443                    isEnabled: isEnabled,
444                    configuration: .slack(
445                        SlackIntegrationConfiguration(
446                            destinationLabel: existingSlackDestination(),
447                            credentialReference: existingReference
448                        )
449                    ),
450                    filters: filters
451                )
452                try integrationService.upsert(
453                    target: target,
454                    slackWebhookURL: slackWebhookURL.nilIfBlank
455                )
456            case .email:
457                guard let port = Int(emailPort) else {
458                    validationMessage = "SMTP port must be a number."
459                    return
460                }
461
462                let recipients = recipientAddresses
463                    .split(separator: ",")
464                    .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
465                    .filter { !$0.isEmpty }
466
467                let existingReference: String? = {
468                    guard case .email(let configuration) = existingTarget?.configuration else { return nil }
469                    return configuration.credentialReference
470                }()
471                if emailPassword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existingReference == nil {
472                    validationMessage = "SMTP password is required."
473                    return
474                }
475                if smtpSecurity != .directTLS, !emailUsername.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
476                    validationMessage = "A username needs Direct TLS, usually on port 465. Without it the password would be sent in cleartext."
477                    return
478                }
479
480                let target = IntegrationTarget(
481                    id: targetID,
482                    type: .email,
483                    name: trimmedName,
484                    isEnabled: isEnabled,
485                    configuration: .email(
486                        EmailIntegrationConfiguration(
487                            smtpHost: emailHost.trimmingCharacters(in: .whitespacesAndNewlines),
488                            port: port,
489                            username: emailUsername.trimmingCharacters(in: .whitespacesAndNewlines),
490                            senderAddress: senderAddress.trimmingCharacters(in: .whitespacesAndNewlines),
491                            recipientAddresses: recipients,
492                            securityMode: smtpSecurity,
493                            credentialReference: existingReference
494                        )
495                    ),
496                    filters: filters
497                )
498                try integrationService.upsert(
499                    target: target,
500                    emailPassword: emailPassword.nilIfBlank
501                )
502            }
503
504            dismiss()
505        } catch {
506            validationMessage = error.localizedDescription
507        }
508    }
509
510    private func existingWebhookDisplayHost() -> String {
511        guard case .webhook(let configuration) = existingTarget?.configuration else {
512            return ""
513        }
514        return configuration.endpointDisplayHost
515    }
516
517    private func existingSlackDestination() -> String {
518        guard case .slack(let configuration) = existingTarget?.configuration else {
519            return "Slack"
520        }
521        return configuration.destinationLabel
522    }
523}
524
525private extension String {
526    var nilIfBlank: String? {
527        let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
528        return trimmed.isEmpty ? nil : trimmed
529    }
530}